Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d3457130a | ||
|
|
5d24fef4bf | ||
|
|
2c32a4ef3c | ||
|
|
2a102bc75b | ||
|
|
c299f31032 |
No files matched your search
@@ -77,30 +77,3 @@ jobs:
|
||||
run: |
|
||||
uv run --frozen graphify --help
|
||||
uv run --frozen graphify install
|
||||
|
||||
security-scan:
|
||||
# The dev deps include bandit and pip-audit. Run them in CI so a new
|
||||
# HIGH-severity finding or vulnerable dependency is caught on the PR that
|
||||
# introduces it, rather than at the next manual audit.
|
||||
# Non-blocking for now (continue-on-error) to avoid breaking CI on
|
||||
# pre-existing findings; remove continue-on-error after the initial
|
||||
# cleanup pass.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v8.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync --frozen
|
||||
|
||||
- name: bandit (static security analysis)
|
||||
continue-on-error: true
|
||||
run: uv run --frozen bandit -r graphify -ll
|
||||
|
||||
- name: pip-audit (dependency vulnerabilities)
|
||||
continue-on-error: true
|
||||
run: uv run --frozen pip-audit --strict
|
||||
@@ -1,64 +0,0 @@
|
||||
name: Release graph asset
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-graph:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # needed to upload release assets
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v8.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install graphify
|
||||
run: uv sync --frozen
|
||||
|
||||
- name: Build graph of graphify source (AST-only, no API cost)
|
||||
# graphify/skills/ contains 126+ .md files that trigger the LLM pass.
|
||||
# Temporarily ignore all .md files so extraction stays pure AST (no API key needed).
|
||||
run: |
|
||||
echo "*.md" >> .graphifyignore
|
||||
echo "*.txt" >> .graphifyignore
|
||||
uv run --frozen graphify extract graphify/ --out .
|
||||
git checkout .graphifyignore 2>/dev/null || rm -f .graphifyignore
|
||||
|
||||
- name: Cluster, label communities and generate GRAPH_REPORT.md
|
||||
# cluster-only writes GRAPH_REPORT.md and names communities (no LLM needed
|
||||
# for basic numeric labels; --no-label skips LLM labeling entirely).
|
||||
run: uv run --frozen graphify cluster-only . --no-label
|
||||
|
||||
- name: Generate HTML viewer
|
||||
run: uv run --frozen graphify export html --graph graphify-out/graph.json
|
||||
|
||||
- name: Bundle release asset
|
||||
run: |
|
||||
mkdir -p dist-graph
|
||||
cp graphify-out/graph.json dist-graph/
|
||||
cp graphify-out/graph.html dist-graph/
|
||||
[ -f graphify-out/GRAPH_REPORT.md ] && cp graphify-out/GRAPH_REPORT.md dist-graph/ || true
|
||||
tar -czf graphify-self-graph.tar.gz -C dist-graph .
|
||||
echo "Asset contents:"
|
||||
tar -tzf graphify-self-graph.tar.gz
|
||||
|
||||
- name: Upload to GitHub release
|
||||
if: github.event_name == 'release'
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: graphify-self-graph.tar.gz
|
||||
|
||||
- name: Upload as workflow artifact (for workflow_dispatch runs)
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: graphify-self-graph
|
||||
path: graphify-self-graph.tar.gz
|
||||
retention-days: 7
|
||||
@@ -37,6 +37,3 @@ scripts/llm.py
|
||||
scripts/benchmark_kimi*.json
|
||||
scripts/benchmark_kimi*.py
|
||||
paper/
|
||||
|
||||
# macOS Finder metadata
|
||||
.DS_Store
|
||||
-187
@@ -1,187 +0,0 @@
|
||||
# graphify Benchmarks
|
||||
|
||||
How graphify performs as conversational long-term memory and as a
|
||||
code-intelligence layer, measured on an open harness with competing systems run
|
||||
under identical conditions (same model, same budgets, same grader).
|
||||
|
||||
Last updated: 2026-07-05.
|
||||
|
||||
## Summary
|
||||
|
||||
graphify's deterministic graph plus hybrid retrieval has the best retrieval
|
||||
recall on LOCOMO of any system tested, the best LOCOMO QA accuracy per dollar,
|
||||
ties for the best LongMemEval score, and builds its index with zero LLM credits.
|
||||
Every system was run on the same harness with one shared model (Kimi K2.6),
|
||||
identical budgets, and a judge blind-validated against a second independent judge
|
||||
(90.6% agreement, Cohen's kappa 0.81).
|
||||
|
||||
Highlights:
|
||||
- LOCOMO retrieval recall@10 of 0.497, about 10x mem0 (0.048) and above BM25 (0.362).
|
||||
- LOCOMO QA accuracy of 45.3%: +18 points over mem0, +14 over BM25, and within
|
||||
4.4 points of supermemory at about a tenth of supermemory's ingest cost.
|
||||
- LongMemEval-S of 76%, tied for best with dense RAG.
|
||||
- Zero LLM credits to build the graph, and about 11x cheaper memory ingest than
|
||||
supermemory ($1.40 vs $15.67).
|
||||
|
||||
## Results at a glance
|
||||
|
||||
| Suite | Dataset (n) | Metric | graphify | Field |
|
||||
|---|---|---|---|---|
|
||||
| Memory | LOCOMO (300) | QA accuracy | 45.3% | supermemory 49.7% (11x ingest cost), bm25 31.3%, mem0 27.3% |
|
||||
| Memory | LOCOMO (300) | recall@10 | 0.497 | bm25 0.362, mem0 0.048 |
|
||||
| Memory | LongMemEval-S (50) | QA accuracy | 76% | dense RAG 76%, hybrid 74%, mem0 70% |
|
||||
| Cost | LOCOMO ingest | USD | ~$1.40 | supermemory $15.67, mem0 $3.48 |
|
||||
| Cost | graph build | LLM credits | $0 | n/a |
|
||||
|
||||
## Harness
|
||||
|
||||
graphify's own harness. Competing systems (mem0, supermemory) are run as
|
||||
adapters inside it, so every system sees the same model, token budget, and
|
||||
grader.
|
||||
|
||||
```
|
||||
ingest -> index -> search -> answer -> grade
|
||||
(build) (store) (retrieve) (Kimi K2.6) (key-fact coverage)
|
||||
```
|
||||
|
||||
- Memory suite (`memory/`): graphify's graph retrieval vs dedicated memory
|
||||
systems (mem0, supermemory) and classic baselines (BM25, dense RAG,
|
||||
hybrid RRF). mem0 and supermemory run self-hosted as adapters, wired through
|
||||
a proxy so their LLM calls also use Kimi K2.6.
|
||||
- Code suite (`crosstool/`): a fixed coding agent (Claude Opus 4.8, at most 14
|
||||
turns, a grep/read/list floor plus one code-intelligence tool) answers graded
|
||||
questions on ERPNext, a roughly 1M-LOC production repo
|
||||
([frappe/erpnext](https://github.com/frappe/erpnext)), with a temporal
|
||||
sub-suite of 689 weekly AST checkpoints from 2011 to 2026.
|
||||
|
||||
## Datasets
|
||||
|
||||
- LOCOMO (`locomo10.json`, n=300): multi-session conversational QA.
|
||||
- LongMemEval-S (n=50, English subset): long-horizon conversational memory.
|
||||
- ERPNext: a large real-world Python codebase for code intelligence.
|
||||
|
||||
LOCOMO and LongMemEval are the same academic datasets other memory systems
|
||||
report on, so results are cross-referenceable. Datasets are not redistributed;
|
||||
the harness documents the expected local layout.
|
||||
|
||||
## Judge and grading
|
||||
|
||||
Answers are graded by Kimi K2.6 against a gold set of atomic key facts a correct
|
||||
answer must contain:
|
||||
|
||||
```
|
||||
coverage = (covered + 0.5 * partial) / total
|
||||
```
|
||||
|
||||
Every verdict cites a verbatim quote from the answer, so grades are auditable
|
||||
rather than one opaque score.
|
||||
|
||||
Judge validation: the judge was blind-validated against a second, independent
|
||||
judge on a sampled set at 90.6% agreement, Cohen's kappa 0.81 (substantial
|
||||
agreement). Most published memory benchmarks disclose no judge validation at
|
||||
all; we publish ours so the grading itself can be audited.
|
||||
|
||||
## Fairness rules
|
||||
|
||||
- One model for every LLM role: Kimi K2.6 via Moonshot.
|
||||
- One shared local embedder where the system allows it: BGE-m3 (1024-d,
|
||||
multilingual).
|
||||
- Identical token budgets. Every run writes a spend ledger and respects
|
||||
`--max-spend`.
|
||||
- Graphs build AST-only with no LLM (an unset API key produces zero credits);
|
||||
embeddings use a local deterministic model.
|
||||
|
||||
## Results: conversational memory
|
||||
|
||||
### LOCOMO (n=300)
|
||||
|
||||
Sorted by recall@10.
|
||||
|
||||
| System | QA accuracy | recall@10 | Ingest cost |
|
||||
|---|---|---|---|
|
||||
| **graphify** (graph-expand) | **45.3%** | **0.497** | ~$1.40 |
|
||||
| hybrid RRF | 43.3% | 0.493 | $0 (shared index) |
|
||||
| graphify (SurrealDB engine) | 43.3% | 0.485 | $0 (shared index) |
|
||||
| dense RAG | 41.3% | 0.439 | $0 (shared index) |
|
||||
| BM25 | 31.3% | 0.362 | $0 (shared index) |
|
||||
| supermemory | 49.7% | 0.149* | $15.67 |
|
||||
| mem0 | 27.3% | 0.048 | $3.48 |
|
||||
|
||||
Bold marks graphify's primary configuration, not the column maximum. Baselines
|
||||
retrieve from the same harness-built index, so they incur no separate ingest
|
||||
cost.
|
||||
|
||||
`*` Retrieval-recall is embedder-confounded: supermemory's self-host locks in
|
||||
its own 768-d English-only embedder rather than the shared BGE-m3. The
|
||||
QA-accuracy axis (a shared Kimi reader and judge over each system's hits) is the
|
||||
clean comparison.
|
||||
|
||||
Reading: supermemory scores a few points higher on raw QA, but at about 11x the
|
||||
ingest cost ($15.67 vs $1.40) and with about 3x worse retrieval recall. graphify
|
||||
has the best retrieval recall on LOCOMO of any system tested, the best QA of the
|
||||
systems on the shared embedder, and does it for about a tenth of supermemory's
|
||||
cost. It retrieves the right memory about 10x more often than mem0 and answers
|
||||
+18 points more accurately. A seed-only ablation (no graph expansion) still
|
||||
scores 42.7% at $1.40 ingest, so most of the accuracy holds at the cheapest
|
||||
setting.
|
||||
|
||||
### LongMemEval-S (n=50)
|
||||
|
||||
| System | QA accuracy | recall@10 |
|
||||
|---|---|---|
|
||||
| **graphify** (graph-expand) | **76%** | **0.844** |
|
||||
| dense RAG | 76% | 0.848 |
|
||||
| graphify (SurrealDB engine) | 74% | 0.833 |
|
||||
| hybrid RRF | 74% | 0.822 |
|
||||
| BM25 | 70% | 0.710 |
|
||||
| mem0 | 70% | 0.344 |
|
||||
|
||||
graphify ties dense RAG for the best QA accuracy (76%); dense RAG edges it on
|
||||
recall (0.848 vs 0.844). Both retrieve far more than mem0 (recall 0.344).
|
||||
|
||||
## Results: code intelligence
|
||||
|
||||
On ERPNext (a roughly 1M-LOC production repo), giving a fixed coding agent one
|
||||
graphify tool lifts key-fact coverage across the graded question set (n=6) from
|
||||
70.8% (a grep and read baseline) to 82.0%, at about 140K tokens per query.
|
||||
graphify pays for itself in accuracy against searching raw files, and avoids the
|
||||
context-stuffing anti-pattern of packing the whole repo into every turn (which
|
||||
costs roughly 20x the tokens for lower coverage).
|
||||
|
||||
## Results: temporal (15 years of ERPNext)
|
||||
|
||||
689 weekly AST checkpoints, 2011 to 2026, built deterministically with no LLM.
|
||||
|
||||
| Checkpoint | Nodes | Edges | Files |
|
||||
|---|---|---|---|
|
||||
| 2011-06-08 | 3,069 | 2,900 | 1,032 |
|
||||
| 2026-06-24 | 22,620 | 48,710 | 3,758 |
|
||||
|
||||
The graph grows about 7x in nodes and 17x in edges across the span. As the
|
||||
codebase grows, plain lexical retrieval finds less of the answer while graph and
|
||||
semantic retrieval scale with it, and the AST extraction itself stays stable.
|
||||
|
||||
## Cost and token economics
|
||||
|
||||
- Graph construction costs zero LLM credits. graphify extracts with tree-sitter
|
||||
(deterministic, about 40 languages) and a local embedder, so building the
|
||||
index uses no API tokens. Most memory and semantic-retrieval systems pay a
|
||||
per-document LLM ingest cost.
|
||||
- Memory ingest is about 11x cheaper: graphify's LOCOMO ingest runs around
|
||||
$1.40 against supermemory's $15.67.
|
||||
- Every number here is backed by a per-run spend ledger in the harness output.
|
||||
|
||||
## Reproducing
|
||||
|
||||
Set `MOONSHOT_API_KEY`. Datasets are fetched to the local layout documented in
|
||||
the harness. Each run respects `--max-spend` and writes a spend ledger.
|
||||
|
||||
```bash
|
||||
# Memory (LOCOMO). This invokes the SurrealDB-engine row (43.3%); the
|
||||
# graph-expand headline (45.3%) is a separate adapter in the same harness.
|
||||
python memory/runner.py --phase 3 --split locomo --n 300 \
|
||||
--adapters graphify_v1_surreal --cn natural --workers 6 --max-spend 15
|
||||
|
||||
# Code cross-tool (ERPNext)
|
||||
python crosstool/run.py --repo erpnext --max-spend <budget>
|
||||
```
|
||||
-429
@@ -2,434 +2,6 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 0.9.14 (2026-07-12)
|
||||
|
||||
- Fix: Visual Studio *solution folder* nodes no longer embed the absolute scan path (including the local username) in their `id` and `source_file` (#1789, thanks @fremat79). A solution folder is a virtual grouping, not a file — VS writes its name as both the display name and the "path" — but `extract_sln` resolved it to an absolute filesystem path anyway and keyed the node id off that. The CLI's id-relativization pass only remaps ids of real files in the scan set, so a virtual folder never matched and its absolute id survived into a committed `graph.json` (e.g. `id=/Users/<name>/proj/Plugins` instead of `id=plugins`). Solution folders are now detected (name == path) and keyed off the folder name only; real project files still resolve as before. (The earlier fix covered `.csproj`/`.sln` file nodes but missed the virtual folders — this completes it.)
|
||||
|
||||
- Fix: the CLI no longer crashes with exit code 255 when a downstream reader closes the pipe early (#1807 / #1811, thanks @varuntej07). Truncating output with `head`, PowerShell's `Select-Object -First N`, or `sed q` disconnected the reader mid-write, graphify hit an unhandled `BrokenPipeError` (or `OSError(EINVAL)` on Windows) and exited 255 — so CI wrappers and agent harnesses that both trim output and check the exit code read a successful query as a command failure. An early-closing reader is now treated as success: stdout is flushed inside the guard (piped stdout is block-buffered, so a small output would otherwise only flush at interpreter shutdown, where the error escapes as a noisy "Exception ignored" and a nonzero exit), then redirected to devnull so the shutdown flush can't raise again, and the process exits 0.
|
||||
|
||||
- Fix: `extract()` no longer writes its AST cache into the analyzed source tree (#1774 / #1802, thanks @SimiSips). With no explicit `cache_root`, the cache defaulted to the inferred common parent of the input files — the source tree — so analyzing a read-only or foreign corpus silently created `graphify-out/cache/` inside it. The cache is an output, so it now defaults to the current working directory. Crucially, the cache *location* is decoupled from the key/id *anchor*: the inferred common parent still anchors the content-hash keys, node ids, symbol resolution, and the XAML/C# project-scan boundary, so keys stay relative and portable (shared/CI cache reuse keeps working) and out-of-CWD corpora aren't mis-scanned. An explicit `cache_root` (as the CLI and watcher pass) is unchanged.
|
||||
|
||||
- Fix: `graphify query` no longer floods results with homonymous generic symbols (#1766 / #1832, thanks @devcool20). When dozens of nodes share one generic label — framework route handlers all labelled `GET`/`POST`, a repeated `handler` — they used to consume every BFS seed slot, so the traversal explored many near-identical neighborhoods and drowned out the query's actual target. Seed selection now deduplicates by normalized label (`GET`/`Get`/`get` collapse together), keeping at most one representative per label while still guaranteeing a seed for each distinct query term. The per-label cap is scoping-only — the shared node scorer (also used by `shortest_path`/`explain` endpoint resolution) is left untouched, so those are unaffected.
|
||||
|
||||
- Fix: semantic cache writes are now scoped to the files actually dispatched in each extraction batch (#1757 / #1835, thanks @TPAteeq). A model can attribute a node's `source_file` to another corpus file; `save_semantic_cache` would then replace (or, mid-run, pollute) that other file's complete cache entry with a stray fragment — silently, with no shrink guard. Writes now honor an `allowed_source_files` allowlist: the final CLI write is scoped to the uncached file set, and the per-chunk incremental checkpoint (`extract_corpus_parallel`, the default path for `extract`/`update`) is scoped to that chunk's own files, so an out-of-scope attribution is skipped with a warning instead of clobbering a legitimate entry.
|
||||
|
||||
- Fix: `graphify export graphml` no longer crashes on dict- or list-valued attributes (#1831 / #1830, thanks @hofmockel). `nx.write_graphml` only accepts scalar values, so a per-node `metadata` dict or the graph-level `hyperedges` list raised `GraphML does not support type <class 'dict'/'list'>` and failed the entire export — on a real ~2,300-node graph, every attempt. `to_graphml` now coerces `None -> ""` and JSON-serializes non-scalars across graph/node/edge scopes (GraphML-native int/float/bool/str pass through unchanged), and writes atomically via a temp file so a failed export no longer leaves a 0-byte `.graphml` that downstream tooling mistakes for a completed one.
|
||||
|
||||
- Fix: `.nox/` (nox virtualenvs) is now skipped during detection alongside `.tox/` (#1804, thanks @igorregoir-lgtm). nox is tox's successor and creates a `.nox/` tree of the same shape, but only `.tox` was in the skip set — so a repo with a nox env got its site-packages fully indexed (one real repo came out 91% venv noise: 6,720 of 7,365 nodes from `.nox/`) and semantic extraction burned tokens reading venv docs.
|
||||
|
||||
- Fix: detection now honors `.git/info/exclude`, not just `.gitignore`/`.graphifyignore` (#1810, thanks @cdahl86-cyber). `info/exclude` is where git records local-only excludes and where `git worktree add` writes nested worktree paths, so a repo can exclude a directory without any `.gitignore` entry. graphify walked straight into those worktree copies and the graph exploded (one repo with 5 worktrees went from ~9,400 nodes / 10 MB to ~210,000 nodes / 311 MB, ~77% duplicate worktree nodes, near the 512 MB cap — regenerated on every commit by the auto-rebuild hooks). The exclude file is loaded at lowest precedence (below every per-directory `.gitignore`/`.graphifyignore`), matching git, so a nearer `!` re-include still wins; the linked-worktree/submodule case (where `.git` is a file) is resolved to the shared common git dir.
|
||||
|
||||
- Fix: the git hooks no longer misbehave inside linked worktrees, and `GRAPHIFY_SKIP_HOOK` now suppresses both hooks (#1809, thanks @cdahl86-cyber; worktree guard co-developed with @Claude-Madera's #1806). Two gaps: (1) `post-checkout` never checked `GRAPHIFY_SKIP_HOOK`, so the var stopped commit-triggered rebuilds but not branch-switch ones; it now honors it like `post-commit`. (2) With `core.hooksPath` shared across worktrees, a commit in any linked worktree fired `post-commit`, which wrote a rogue delta-only `graph.json` into that worktree and raced deploy/CI `git clean` against the detached rebuild (`failed to remove graphify-out/: Directory not empty`). Both hooks now short-circuit in a linked worktree (git-dir != git-common-dir), comparing absolute paths so the primary checkout — where `--git-common-dir` is the relative `.git` — is never false-positived and wrongly skipped.
|
||||
|
||||
## 0.9.13 (2026-07-12)
|
||||
|
||||
- Fix: the query log is now opt-in (off by default) (#1797, thanks @adam-pond-agent). `querylog` wrote every `query`/`path`/`explain` question and corpus path (and full responses if `GRAPHIFY_QUERY_LOG_RESPONSES`) to a default-on, unbounded, fail-silent plaintext file at `~/.cache/graphify-queries.log` — outside any repo's .gitignore/retention, and undocumented, which contradicts graphify's on-device / no-telemetry posture. Logging is now OFF unless you opt in with `GRAPHIFY_QUERY_LOG_ENABLE=1` (default path) or `GRAPHIFY_QUERY_LOG=<path>`; `GRAPHIFY_QUERY_LOG_DISABLE=1` still forces it off. All the query-log env vars are now documented in the README.
|
||||
|
||||
- Fix: a markdown file that went through semantic extraction is no longer duplicated into two disconnected nodes on later `graphify update` (#1799, thanks @jerp86). The semantic pass mints `<slug>_doc` while the markdown quick-scan mints the bare `<slug>`, so the file's edges split across two twins (a docs->code path query would dead-end on the bare half; centrality and communities split too). `build_from_json` now merges the bare quick-scan node into the semantic `_doc` node when both share the same `source_file` and are `file_type: document`, consolidating their edges/hyperedges onto one node. Gated so an unrelated code symbol `foo` and `foo_doc` never merge.
|
||||
|
||||
- Fix: incremental `graphify update` no longer silently evicts nodes for a file that left the scan corpus but still exists on disk (#1795, thanks @CJNA). `_reconcile_existing_graph` read "source absent from the collected corpus" as "deleted", but that's also what an ignore-rule/filter change looks like (e.g. an upgrade that starts honoring `.gitignore`) — in one 27k-node graph the first rebuild after such an upgrade mass-evicted 655 nodes whose files were present the whole time. Eviction now fails closed: a corpus-absent source is only evicted when `Path(identity).exists()` is False (true deletion), otherwise its nodes/edges/hyperedges are preserved and a loud line reports how many were kept and why. True deletions and renames evict as before; a full `extract --force` still purges deliberate exclusions.
|
||||
|
||||
- Fix: `build_merge` no longer silently deletes a re-extracted file's fresh nodes when that file is also passed in `prune_sources` (#1796, thanks @erichkusuki). A file present in `new_chunks` is being replaced, not deleted, so it's now excluded from the prune set — "replace" wins over a contradictory "delete" of the same source. Previously, following the old edit-workflow (pass the changed file in `prune_sources`) deleted the just-built concept whenever an edit kept a node's label. Genuine deletions (a file in `prune_sources` but not `new_chunks`) still prune.
|
||||
|
||||
- Fix: `graphify path` resolves each endpoint to the first candidate whose label contains every query token, instead of blindly taking the top-scored node (#1785, thanks @CJNA). `_score_nodes`' full-query bonus only fires when the query equals/prefixes a label, so a query that is a token *subset* of the intended label (`"Reject-everything judge"` vs `"Degenerate Reject-Everything Judge"`) got no bonus and a node prefix-matching one rare token could outscore it — anchoring the path on an unrelated, often disconnected node and yielding a false "No path found". When the top candidate already full-matches (the common case) the pick is unchanged. Applied to both the `path` CLI and the MCP shortest-path tool; the close-runner-up ambiguity warning now fires only when the score head is what was actually picked.
|
||||
|
||||
- Fix: the report's "Suggested Questions" weakly-connected-node count now matches its "Knowledge Gaps" count (#1768, thanks @balloon72). `suggest_questions()` omitted the `file_type != "rationale"` filter that `report.py`'s Knowledge Gaps section applies, so the same `GRAPH_REPORT.md` showed two different numbers for the same concept (e.g. 757 vs 245), making a healthy graph look like it had a major documentation gap. Both computations now use the same filter.
|
||||
|
||||
- Fix: Bash scripts that run each other by execution now get a cross-file edge (#1756, thanks @balloon72). `extract_bash` only linked `source x.sh` / `. x.sh`; the two most common forms — `bash x.sh` and `./x.sh` — produced no edge, so execution topology was missing. They now emit a `calls` edge (context `script_invocation`) to the invoked script's entry node when the target resolves to a real file on disk (script runners `bash`/`sh`/`zsh`/`ksh`/`dash` and bare `./x.sh`), skipping missing or shadowed targets.
|
||||
|
||||
- Fix: Ruby `.rake` files are now extracted and participate in Ruby cross-file resolution like `.rb` (#1784, thanks @krishnateja7). `.rake` is plain Ruby but the extension was gated out of seven places (classification, extractor dispatch, the language-name/family maps, the `ruby_member_calls` resolver's suffix set, both `.rb`-suffix filters in `ruby_resolution.py`, and the build repo-tag map), so every rake task was skipped and its calls were invisible. All seven now include `.rake`; `Widget.tally` from a `.rake` task resolves to its `.rb` definition.
|
||||
|
||||
- Fix: cross-module references to a function now resolve to its definition instead of dangling on a name-only stub (#1781, thanks @EmilNyg). `_rewire_unique_stub_nodes` gated merge targets through `_is_type_like_definition`, which rejects any label ending in `)` — so function/method defs could never absorb their reference stubs, and "who references this function" returned nothing on the definition node while a sourceless stub held all the edges. Top-level function defs are now eligible rewire targets when the label match is globally unique, gated by a language-family match with the referrers (a Python `get_db` reference can't bind to a unique Go `get_db()`) and excluding stubs used as a supertype (`inherits`/`implements`/`extends` — you don't inherit from a function). Types are unchanged.
|
||||
|
||||
## 0.9.12 (2026-07-10)
|
||||
|
||||
- Fix: live PostgreSQL introspection (`--postgres`) now emits foreign-key `references` edges under a read-only role (#1746, thanks @rithyKabir). The FK query read `information_schema.referential_constraints`, which is privilege-filtered — a role with only SELECT sees zero FK rows while tables/views/routines still appear, so every `references` edge silently vanished. It now reads the world-readable `pg_catalog.pg_constraint` (keyed by oid, which also fixes same-named constraints on sibling tables cross-matching in the old name-based joins), preserving composite-FK column order via `UNNEST ... WITH ORDINALITY`.
|
||||
|
||||
- Fix: `json_config` no longer emits `imports`/`extends` edges to node IDs it never creates (#1764, thanks @oleksii-tumanov). `package.json` dependencies and `tsconfig.json` `extends`/`$ref` targets produced edges whose endpoint node was absent, so `build_from_json` silently dropped them (the "no matching node id" case is filtered out of real errors) — losing dependency/extends structure on two of the most common files in any JS/TS repo. The extractor now creates the referenced target as a `concept` node before adding the edge.
|
||||
|
||||
- Fix: `graphify update` no longer deletes semantic hyperedges on every run (#1755, thanks @oleksii-tumanov). The AST-only rebuild treated every rebuilt corpus file as grounds to evict hyperedges anchored to it, but the AST pass never re-emits hyperedges, so doc-sourced hyperedges (exactly what semantic extraction produces) were permanently lost on the first `update` after a full build — even a no-op run. Hyperedge eviction is now scoped to genuinely deleted (or symlink-outside) sources, mirroring node/edge handling; replacement-by-id and dangling-member cleanup are unchanged.
|
||||
|
||||
- Fix: Java member calls resolve against the receiver's declared type instead of a bare method-name match (#1696/#1697, thanks @oleksii-tumanov). `gw.charge()` where `gw: PaymentGateway` now binds to `PaymentGateway.charge`, not a same-named `AuditLog.charge` in another file. Explicit-type receivers and `this` are exact; current-class fields, method parameters, and explicitly-typed locals resolve via a method-scoped type table; a missing, ambiguous, inherited, or chained receiver is skipped rather than guessed (same god-node guard as the C#/Swift/Ruby resolvers). Fully-qualified and nested-type receivers are deferred (they need package/nesting-aware type identity).
|
||||
|
||||
- Fix: output/cache artifacts no longer land in the scanned corpus or CWD when `--out`/`--graph` point elsewhere (#1747, thanks @bbqboogiedwonsen). `extract <corpus> --out <dir>` correctly wrote the graph to `<dir>` but `detect()`'s word-count/stat-index cache still created a stray `graphify-out/cache/` inside the corpus (it uses the scan root); it now honors the `--out` dir via a threaded `cache_root`. And `cluster-only --graph <elsewhere>/graphify-out/graph.json` wrote `GRAPH_REPORT.md`/labels/analysis/re-clustered graph to the CWD instead of beside the input; it now writes beside `--graph` when that graph lives in a `graphify-out/` dir, while still restoring into the CWD for an archived `backup/graph.json` (#934).
|
||||
|
||||
- Fix: `imports`/`references` edges no longer bind across a language boundary (#1749, thanks @philberndt). The spec already forbids cross-language `calls`, but an unresolved Python `import time` could still resolve by bare stem onto a `src/time.ts` file node — welding a polyglot repo's halves together at a phantom edge (in the reporter's repo, 3 such edges were the *only* thing bridging 2409 Python nodes to 1403 TS nodes, inflating `time.ts` betweenness ~90x and making it the #1 "god node"). The build-time cross-language guard now covers `imports`/`imports_from`/`references` in addition to `calls`, dropping an edge only when both endpoints are known code languages of different interop families (so a config/manifest → code reference is untouched).
|
||||
|
||||
- Fix: files whose extractor bailed out for a missing optional dependency no longer vanish without a trace (#1745, thanks @rithyKabir). `.sql` files (and other extra-gated languages) have a dispatch entry, so the #1689 no-extractor warning can't fire, and `extract_sql` returns an error result when `tree-sitter-sql` is absent, so the #1666 zero-node warning skips it too — the graph built "successfully" while an entire SQL corpus contributed nothing. `extract()` now surfaces these grouped by extension, naming the extra that restores the language (e.g. `pip install "graphifyy[sql]"`).
|
||||
|
||||
- Fix: `build_from_json` is deterministic across process runs again (#1753, thanks @erasmust-dotcom). The ghost-node merge iterated `set(G.nodes())`, so which node survived a `(basename, label)` collision depended on CPython's per-process string-hash seed — rebuilding the same extraction JSON in a fresh process could silently pick a different canonical id (breaking the cluster→relabel workflow with a `KeyError` on an id that vanished). The Pass 1/Pass 2 loops now iterate in sorted order. Additionally, two non-AST (semantic) nodes sharing a key but from *different* files are now treated as distinct concepts and both survive (mirroring the AST/AST ambiguity guard #1257) instead of one arbitrarily merging away; a genuine same-file duplicate still collapses.
|
||||
|
||||
- Fix: a Java field/parameter/return-type reference to a class whose simple name is shared by two modules no longer dangles on a sourceless phantom node (#1744, thanks @aviciot). Both same-named classes already survive as distinct path-scoped nodes, but the cross-module `references` edge was left pointing at a bare no-source stub because `_resolve_java_type_references` re-pointed `implements`/`inherits`/`imports` but not `references` — so a query about the referenced class could miss it. The Java resolver now disambiguates `references` by the importing file's `import` statement (falling back to same-package), mirroring the C# resolver, and drops the orphaned phantom.
|
||||
|
||||
## 0.9.11 (2026-07-08)
|
||||
|
||||
- Fix: file enumeration no longer silently drops a directory subtree. `detect()`'s `os.walk` had no `onerror` handler, so an `os.scandir` failure (a permission error, or a directory created/deleted mid-walk by concurrent writes) was swallowed and that whole subtree vanished from the scan with no log, yielding a silently partial `graph.json`. The walk now records every skipped directory (surfaced in the result's `walk_errors`) and warns to stderr, while still enumerating the rest. Relatedly, `to_json`'s anti-shrink guard (#479) now fails safe: a non-empty but unreadable existing `graph.json` refuses the overwrite (pass `force=True` to override) instead of silently clobbering a good graph; an empty file still proceeds.
|
||||
- Fix: Pascal/Delphi extractors no longer emit duplicate `method`/`contains`/`inherits` edges. A class method declared in the interface section and defined in the implementation section each emitted an edge to the same node, so ~half of a Pascal graph's method edges were doubled (skewing degree/centrality and tripping the new cross-file resolver's god-node guard). Both extractors now dedup edges on (source, target, relation), mirroring the existing node dedup.
|
||||
- Fix: Pascal/Delphi call resolution is scoped to the caller's class + inherits chain, and calls to methods inherited across file boundaries now resolve (#1739, thanks @richtext). Both extractors previously resolved every call via a single file-wide `{name: node_id}` dict, so two unrelated classes with a same-named method (property accessors, generated COM/TLB wrappers) collapsed onto whichever was inserted last, producing wrong cross-class `calls` edges. Resolution now walks own-class then ancestor chain then file-level free functions, emitting no edge when ambiguous (same god-node guard as the Ruby resolver). A new corpus-wide resolver (`graphify/pascal_resolution.py`) resolves calls from a descendant to a base-class method declared in a different file (the common generated-base/manual-descendant split). Also stops emitting a duplicate cross-file base-class stub carrying the wrong `source_file`.
|
||||
- Fix: query ranking no longer lets a lone generic term that exact-matches a short leaf label hijack seed selection in multi-term queries (#1602/#1724, thanks @fkhawajagh). `_score_nodes` scales the per-term exact/prefix tiers by squared term coverage; single-term and full-coverage queries are unchanged.
|
||||
- Fix: Kotlin enum entries are extracted as nodes with `case_of` edges to their enum (#1700, thanks @ivanzhilovich). Closes the Kotlin half of #1700 (the Java half shipped in 0.9.10 via #1719); `enum class ChatType { NORMAL, GROUP, SYSTEM }` now yields NORMAL/GROUP/SYSTEM nodes and "where is ChatType.X used" works for Kotlin.
|
||||
- Fix: SKILL.md's POSIX interpreter probe no longer silently falls back to a graphify-less system python (#1735, thanks @mohammedMsgm). Step 1 ran `uv tool run graphifyy python -c ...`, but the `graphifyy` package's executable is `graphify`, so uv treated `python` as a missing `graphifyy` command; `2>/dev/null` hid uv's own `--from` hint, leaving `PYTHON` on an interpreter without graphify. The probe now runs `uv tool run --from graphifyy python -c ...`. The PowerShell path was already correct.
|
||||
|
||||
- Refactor: decomposed the two largest modules into focused, single-responsibility modules — verbatim moves only, every original import path preserved via re-exports, no behavior change (#1737, thanks @TPAteeq). `extract.py` 17,054 → 4,740 LOC (the tree-sitter engine, cross-file resolution, shared models, and 23 language extractors moved under `graphify/extractors/`), `__main__.py` 5,368 → 673 (install/uninstall + CLI dispatch split into `graphify/install.py` and `graphify/cli.py`), `export.py` 1,671 → 962 (HTML + graph-DB exporters under `graphify/exporters/`). Full suite unchanged.
|
||||
- Fix: `merge-graphs` gives each input a distinct repo tag so same-stem nodes from different source graphs don't collapse (#1729). Two graphs under a same-named repo dir (`src/graphify-out` and `frontend/src/graphify-out`, both → `src`) shared the `src::` prefix, so a backend `src/app.js` and a frontend `App.jsx` (both bare `app`) merged into one node with edges from both — false cross-runtime `path` results. Colliding tags are now widened (`frontend_src`) with an index-suffix backstop, and the command prints a note when it disambiguates.
|
||||
- Fix: `uninstall` removes the graphify hook/section from Claude's local-only files too (#1731, thanks @TPAteeq). It now cleans `.claude/settings.local.json` and both `CLAUDE.local.md` locations in addition to the standard files, via both `graphify uninstall` and `graphify claude uninstall`.
|
||||
- Feat: `graphify extract --code-only` indexes code (local AST, no API key) and skips the doc/paper/image semantic pass, so a mixed repo no longer hard-fails when no LLM backend is configured (#1734). Reports what it skipped; the no-key error now points users at the flag.
|
||||
|
||||
## 0.9.10 (2026-07-08)
|
||||
|
||||
- Fix: TS/JS member calls on a builtin-typed receiver no longer collapse onto a same-named user symbol (#1726). `_resolve_typescript_member_calls` matched a receiver's type to a definition by casefolded label, so `x: Date; x.getTime()` bound the caller to a user `class DATE`/`const DATE` in another file — inventing hundreds of phantom `references` edges and a false god node. Builtin-global receiver types (`Date`, `Promise`, `Map`, ...) are now skipped, mirroring the cross-file call guard; genuine user types are unaffected.
|
||||
- Fix: never bind a cross-file `calls` edge to a definition in a different language family (#1718, thanks @edinaldoof). Name-only matching resolved a TSX callback passed by name to a same-named Kotlin method (and a Python call to a Kotlin fun) — phantom edges the spec forbids. Candidates are now filtered by interop family (JVM, native C-family, JS/TS module graph, ...); unknown families stay permissive.
|
||||
- Fix: an ambiguous legacy-stem alias in `build_merge` no longer silently merges two unrelated files (#1713, thanks @mallyskies). The `#1504` old-stem alias (`ping.h`/`ping.php` → bare `ping`) resolved by hash-order, riding a dangling edge onto an arbitrary same-named file. Aliases are now committed only when exactly one file claims them; a salted `.h`/`.cpp` file node is recognized as its own claimant so a genuine collision stays ambiguous (and dropped) instead of picking a wrong winner.
|
||||
- Fix: inline base-class stubs are tagged with `origin_file` (#1707, thanks @mallyskies). Five inheritance handlers built cross-file base-class stubs without `origin_file`, so same-named bases across files collapsed onto one shared stub that could then merge with an unrelated real class (218 wrong `inherits` edges observed). They now route through `ensure_named_node`, which sets the tag.
|
||||
- Fix: Java enum constants are extracted as nodes with `case_of` edges to their enum (#1719, thanks @ivanzhl). Closes the Java half of #1700; `affected ErrorCode` / "where is ErrorCode.X used" now works for Java.
|
||||
- Fix: `graphify` rebuilds recover from a deleted hook working directory instead of crashing (#1703, thanks @FranciscoJSBarragan). A detached git hook can inherit a CWD that no longer exists; the rebuild now recovers via `GRAPHIFY_REPO_ROOT` or fails cleanly instead of raising `FileNotFoundError`.
|
||||
- Feat: the semantic cache is checkpointed per chunk so an interrupted extraction resumes instead of restarting (#1715, thanks @A-Levin). Each completed chunk is unioned into the cache immediately (opt out with `GRAPHIFY_NO_INCREMENTAL_CACHE`); the final write still overwrites authoritatively.
|
||||
- Docs: `SECURITY.md` no longer claims stdio-only now that an opt-in `--transport http` (binds `127.0.0.1` by default) exists (#1714, thanks @Thizeidler); added tests for `GRAPHIFY_MAX_GRAPH_BYTES` parsing and corrected its unit docstring to binary MiB/GiB (#1722, thanks @Cekaru).
|
||||
|
||||
## 0.9.9 (2026-07-07)
|
||||
|
||||
- Fix: `graphify explain` resolves an exactly-typed punctuated label symmetrically against `norm_label` (#1704). The search term tokenized on `\w+` ("blockStream.ts" -> "blockstream ts", space where the '.' was) while a node's stored `norm_label` keeps punctuation ("blockstream.ts"). The verbatim case was already rescued by the tokenized-label tier, but that broke if a node's `label` and `norm_label` diverged; a punctuation-preserving `norm_query` is now matched against `norm_label` across the exact/prefix/substring tiers (and fed to the trigram prefilter), so it is robust by construction.
|
||||
- Fix: code files with no AST extractor are surfaced instead of silently dropped (#1689, thanks for the precise root-cause). `.r`/`.R` (also `.ejs`, `.ets`) are in `CODE_EXTENSIONS` so they are counted as code, but there is no extractor for them, so they produced zero nodes with no warning. `extract` now prints a grouped warning ("N file(s) are classified as code but graphify has no AST extractor ...: .r (17)"). Adding a real `tree-sitter-r` extractor remains a follow-up.
|
||||
- Fix: the AST-extraction progress line keeps a consistent denominator to the end (#1693). Intermediate lines counted against `len(uncached_work)` but the final line switched to `total_files` (which includes cached hits and no-extractor files), so on a large corpus the count appeared to jump upward right after 99%. Both the parallel and sequential final lines now use the `uncached_work` denominator.
|
||||
- Fix: `GRAPH_REPORT.md` no longer emits dangling `[[_COMMUNITY_*]]` Obsidian wikilinks by default (#1712). The `_COMMUNITY_*.md` notes those links target are only created by the opt-in `--obsidian` export, and the report is written at build time before any export, so on a default run every link dangled (spawning phantom nodes in a vault's graph view, literal brackets elsewhere). The Community Hubs section now renders as plain text by default; the wikilink form is behind an `obsidian=True` opt-in.
|
||||
- Fix: `.m` files are no longer force-parsed by the Objective-C grammar when they are MATLAB (#1702, thanks @catalystdream for the diagnosis). `.m` is shared by Objective-C and MATLAB, but the dispatch routed every `.m` to `extract_objc`, which turned real MATLAB into garbage nodes/edges. `.m` is now content-sniffed like `.h`: a genuine Objective-C `.m` (with `@implementation`/`@interface`/`@import`/`#import`) still routes to `extract_objc`; a MATLAB `.m` gets no extractor and is surfaced by the #1689 warning rather than mis-parsed. `.mm` is unchanged (unambiguously Objective-C++). A real `tree-sitter-matlab` extractor remains a follow-up.
|
||||
- Fix: the `/graphify` usage comment in the skill files no longer claims a bare `/graphify` produces an Obsidian vault by default (#1681, thanks for the audit). It now reads "full pipeline on current directory (HTML viz; add `--obsidian` for a vault)", matching Step 6. Fixed at the skillgen source so every generated `skill-*.md` variant carries the corrected comment.
|
||||
- Feat: files graphify sees but cannot classify are surfaced instead of vanishing (#1692). Extensionless, non-shebang project files (Dockerfile, Gemfile, Makefile, Rakefile, LICENSE, ...) and unsupported extensions previously left no trace at all. `detect` now collects them into an `unclassified` list, and `graphify extract` reports "N file(s) not classified (no supported extension or shebang), skipped: ...". Actually extracting Dockerfile/Makefile-style content remains a follow-up.
|
||||
|
||||
## 0.9.8 (2026-07-06)
|
||||
|
||||
- Fix: the Claude Code / Codebuddy `PreToolUse` and Gemini CLI `BeforeTool` graph-nudge hooks now work on Windows (#522). The hooks were inline POSIX bash (`case/esac`, `[ -f ]`, single-quoted `echo`), which Windows cmd.exe/PowerShell cannot parse — so on Windows the hook failed silently, no "run `graphify query` before grepping/reading raw files" context was injected, and users had to invoke `/graphify` by hand. The detection logic (grep-command match, source-file extension match, skip-if-under-output-dir, graph-exists check) moved into a shell-agnostic `graphify hook-guard <search|read>` subcommand invoked via the absolute exe path (the same pattern the codex hook already uses), so the hook parses and runs identically on Windows, macOS, and Linux. Behavior on macOS/Linux is unchanged (byte-identical nudge payload); the graph path now also honors `GRAPHIFY_OUT`. The Gemini `BeforeTool` hook got the same treatment (`graphify hook-guard gemini`), which also removes its dependency on a bare `python` being on PATH. Codex stays a no-op there because Codex Desktop rejects `additionalContext`.
|
||||
- Fix: `--update`-style section writes to `CLAUDE.md`/`AGENTS.md` no longer corrupt or drop content (#1688, thanks @bdfinst). `_replace_or_append_section` located its managed block by substring (`marker in content`) and `next(... if marker in line)`, so a heading that appeared as a substring of another line (or duplicate headings) matched the wrong offset and the rewrite could truncate the file. It now matches the section heading exactly (`line.strip() == marker`), appends when absent, and prefers the last exact match when several exist, so unrelated content is preserved.
|
||||
- Fix: token estimation no longer crashes on files containing tiktoken special-token text like `<|endoftext|>` (#1685, thanks @Kyzcreig). `_TOKENIZER.encode(content)` raises `ValueError` by default when the text contains a special token, which aborted packing on docs/corpora that merely mention these strings. Both `encode` sites now pass `disallowed_special=()` so such text is tokenized as ordinary bytes.
|
||||
- Fix: the Ollama backend no longer multiplies a hang by the retry count (#1686, thanks @Kyzcreig). A stalled local model would wedge for `timeout * (max_retries + 1)`, which with the default 6 retries turned one long stall into a very long one. Ollama now defaults to zero client-side retries (a local model that stalls will not un-stall on retry); set `GRAPHIFY_MAX_RETRIES` to opt back in. Other backends are unchanged. Note: the underlying stall is non-deterministic and driven by the model server, so this bounds the wait rather than eliminating the hang.
|
||||
- Fix: a truncated or slightly malformed community-labeling reply no longer discards the whole batch (#1690, thanks @vdgbcrypto). `_parse_label_response` now salvages the complete `"id": "name"` pairs from a reply that failed a strict `json.loads` (e.g. a reply truncated mid-object), raising only when no pairs can be recovered. The per-batch token budget was also raised (`256 + 48*n`, was `64 + 24*n`) to give models that prepend a short preamble enough headroom to finish the JSON. The exact provider truncation in the report could not be reproduced without a live key; the parser and budget fixes address the mechanism.
|
||||
- Fix: cluster-only mode now reports the real token cost of community labeling instead of a hardcoded zero (#1694, thanks @sub4biz). The labeling LLM calls were never accounted for, so `GRAPH_REPORT.md`'s "Token cost" line always read `0 input · 0 output` in cluster-only runs. `_call_llm` now accumulates per-response usage into an optional accumulator that is threaded through the labeling path and surfaced in the report. Backends that do not return usage (the Claude Code CLI) still contribute nothing, which is honest rather than estimated.
|
||||
- Docs/Feat: `deepseek-v4-flash` (and `v4-pro`) have thinking ENABLED by default; graphify no longer implies otherwise and adds an opt-in `GRAPHIFY_DISABLE_THINKING=1` toggle (#1621, thanks @sub4biz for the empirical testing). Disabling thinking removes a rare reasoning-leak failure mode (which the adaptive extraction/labeling retry already recovers from) but, measured on real corpora, trades it for more frequent benign truncation and measurably lower extraction quality and file coverage — so it stays a documented user choice rather than a forced default. The stale "non-thinking" comment on the built-in deepseek config is corrected. The moonshot (kimi) branch is unchanged (it must disable thinking or content comes back empty).
|
||||
- Fix: source files are no longer silently dropped during discovery by two over-broad filters (#1666, thanks @krishnateja7 for the precise root-cause). (a) A bare `snapshots/` directory was pruned as a Jest/Vitest artifact, which killed legitimate code namespaces like a Rails `app/services/snapshots/`; it is now pruned only when it actually contains `.snap` files or sits directly under a JS test root (`__snapshots__` stays unconditionally pruned). (b) `_is_sensitive` dropped files on a bare name-keyword hit (`device_token.rb`, `passwords_controller.rb`) even when `classify_file` had already resolved them to source code; a genuine programming-language source file is now exempt from the weak keyword heuristic, while real secret stores in data/config formats (`credentials.json`, `secrets.yaml`, `.env`, `.pem`, ...) are still caught. This is the discovery-layer fix; the 0.9.7 no-cache-on-empty change could not surface these because the files never reached extraction.
|
||||
|
||||
## 0.9.7 (2026-07-06)
|
||||
|
||||
- Fix: Java standard-library types are no longer emitted as `references` noise (#1603, thanks @NydiaChung). A `_JAVA_BUILTIN_TYPES` skip list now suppresses ubiquitous `java.lang`/`java.util`/`java.io`/`java.time`/`java.math`/`java.nio.file` type names (`String`, `List`, `Map`, `Optional`, `Integer`, `Exception`, ...) at the type-ref walker; they never resolve to a project node, so edges to them were pure noise (mirrors `_GO_PREDECLARED_TYPES`/`_PYTHON_ANNOTATION_NOISE`). Nested user-type generic arguments still resolve: `List<Item>` drops the `List` edge but keeps `Item`.
|
||||
- Feat: added a `pascal` optional extra for AST-quality Pascal/Delphi extraction (#1616, thanks @vinicius-l-machado). `extract_pascal` already used tree-sitter-pascal when present (with a regex fallback), but the grammar was never declared in the package metadata, so the AST path never ran out of the box. `uv tool install "graphifyy[pascal]"` now opts into it (also included in `[all]`); tree-sitter-pascal ships prebuilt wheels for every platform, so no C toolchain is needed. On a mid-size Delphi codebase the AST path yields notably more accurate `calls`/`inherits` edges than the regex fallback.
|
||||
- Feat: JS/TS rationale comments and ADR/RFC citations are now extracted (#1599, thanks @niltonmourafilho-arch). Python already turned `# NOTE:`/`# WHY:`/`# HACK:` comments and docstrings into `rationale` nodes, but JS/TS comments were discarded. `extract_js` now runs the same post-pass: `// NOTE:`-style and block-comment rationale become `rationale` nodes with `rationale_for` edges, and `ADR-NNNN` / `RFC NNNN` citations become `doc_ref` nodes with `cites` edges from the file, closing the code-to-design-doc gap in mixed corpora at zero LLM cost (pure line scan). Files with no such comments are unaffected.
|
||||
- Fix: extensionless executables with a shebang (CLI entry points like `devctl`, `manage`) are now extracted (#1683, thanks @Stashub). `detect` already classified a `#!/usr/bin/env bash`/`python`/`node`/... file as code, but `_get_extractor` dispatched on the suffix alone and returned nothing, so the file was silently dropped from the graph and its doc-referenced symbols stayed dangling stubs. Extensionless files now resolve their extractor from the shebang interpreter (`_SHEBANG_DISPATCH`), mirroring detection. Only interpreters with a real extractor are mapped (python, bash-family, node, ruby, lua, php, julia); others (perl, fish, Rscript) stay skipped rather than mis-parsed by a wrong grammar.
|
||||
- Feat: Ruby `include`/`extend`/`prepend <Module>` now emits a `mixes_in` edge to the module (#1668, thanks @krishnateja7). Concerns/mixins are the composition mechanism in Rails, but they produced no edges, so the blast radius of editing a shared concern was invisible to `affected`. A constant-argument mixin inside a class or module body now resolves to the module node (reusing the #1634 candidate logic and the #1640 module nodes, under the single-owner guard) and emits `Class --mixes_in--> Module`, which `affected` already traverses. `extend self` and non-constant arguments are skipped; an ambiguous or undefined module produces no edge.
|
||||
- Feat: `affected <Class>` now reaches callers that bind to the class's method nodes (#1669, thanks @krishnateja7). Since #1634 binds `Service.call` precisely to the `def self.call` method node, a class-level `affected` query missed those callers because `method`/`contains` are (correctly) not general-traversal relations. The reverse walk now seeds from the root's own member nodes (one `method`/`contains` hop outward) so method-bound callers are reachable from the class, with no change to the general traversal (no forward noise) and the member nodes themselves are not reported as hits.
|
||||
- Fix: capitalized/mixed-case file extensions are no longer silently skipped (#1671, thanks @raman118). `collect_files` and `_get_extractor` matched suffixes case-sensitively, so `App.PY`, `script.JS`, `Lib.Ts`, etc. fell through and were never extracted. Suffix matching now falls back to the lowercased form for both file discovery and extractor dispatch (including `.blade.php`); an unsupported extension like `.xyz` is still skipped.
|
||||
- Fix: the virtual PostgreSQL `source_file` URI no longer gets backslash-mangled on Windows (#1672, thanks @raman118). `introspect_postgres` built the synthetic `postgresql://host/db` path with `Path`, which rewrites `/` to `\` on Windows; it now uses `PurePosixPath` so the URI stays forward-slashed on every platform.
|
||||
- Fix: a deferred `import(...)` no longer manufactures a phantom file cycle (#1241, thanks @Synvoya). Dynamic imports are real dependencies but not static ones, so two files that reference each other via one static import plus one dynamic import were reported as a circular dependency. The dynamic-import edge stays in the graph (marked `deferred`) but is excluded from `find_import_cycles`.
|
||||
- Fix: an extractable source file that produces zero nodes is no longer cached, and is surfaced with a warning (#1666, thanks @krishnateja7). Every supported file yields at least a file node, so a zero-node result is anomalous (a transient batch/parallel hiccup). Caching it made the empty byte-stable across runs and silently blinded `affected`/`explain` to and through the file. The cache write is now skipped for a zero-node result so a rerun self-heals, and `extract` warns when an accepted source file lands in the graph with no nodes. This addresses the persistence and the silent blindness; if the underlying zero-node extraction still reproduces on a specific corpus, the warning now makes it visible to report.
|
||||
- Fix: the Windows skill variant now declares `name: graphify` instead of `name: graphify-windows` (#1635, thanks @ray8875). `graphify install --platform windows` writes the variant to `~/.claude/skills/graphify/SKILL.md`, but Claude Code requires the skill folder name to equal the frontmatter `name`, so the `-windows` suffix broke discovery/validation. The variant suffix is a packaging detail, not part of the skill's identity.
|
||||
- Fix: the OpenCode plugin joins its reminder to the user's command with `;` instead of `&&` (#1646, thanks @gonaik). Windows PowerShell 5.1 rejects `&&` as a statement separator (`not a valid statement separator`), so the first bash command of every OpenCode session on Windows failed. `;` works in PowerShell 5.1, Bash, and POSIX shells. (Both the OpenCode and Kilo plugin templates are fixed.)
|
||||
- Fix: the `GRAPH_REPORT.md` "Import Cycles" section is now emitted only when the graph contains code (#1657, thanks @Ns2384-star). On a documents-only corpus there are no imports, so the section was pure noise ("None detected") on every run; it is now conditioned on code nodes or import edges being present. (The same report also confirms the mojibake and stdout-encoding items in that issue are already addressed on the current branch: manifest.json and `GRAPH_REPORT.md` are written UTF-8, and the CLI reconfigures stdout/stderr to UTF-8 with `errors="replace"`.)
|
||||
- Fix: a modified `.docx`/`.xlsx` now re-enters `--update` (#1649, thanks @Ns2384-star). `detect_incremental` tracks the converted markdown sidecar, and `convert_office_file` early-returned whenever the sidecar already existed — so an Office source edited after its first conversion never updated its sidecar and was reported "unchanged" forever, freezing the graph on a living docs corpus. The sidecar is now re-converted when the source is newer than it (which bumps the sidecar's mtime/content so the incremental hash check picks it up); an unchanged source still skips the rewrite so it never churns (#1226).
|
||||
- Fix: files whose absolute path exceeds Windows' 260-char limit are now hashed (#1655, thanks @Ns2384-star). `_md5_file`/`save_manifest`/`count_words` used plain `open()`/`stat()`, which the Windows file APIs reject for long paths unless prefixed with the extended-length marker `\\?\` — so deeply-nested files (accented, deep folders) never hashed, their manifest entry never stabilized, and `detect_incremental` re-flagged them as changed on every run. Change-detection I/O now prefixes long absolute paths on win32 (mirroring the normalization `cache.py` already applied to cache keys). No-op on other platforms.
|
||||
- Perf: word counts are cached against each file's stat signature (#1656, thanks @Ns2384-star). `detect()` counted words in every PDF/docx/text file to size the corpus, re-opening and re-parsing every binary on each run — minutes on a large docs corpus even when only a few files changed. Counts are now memoized in the existing content-hash stat index (keyed by size + mtime), so an unchanged file is parsed once and read from the index thereafter; incremental detection drops from O(corpus) parsing to O(changed).
|
||||
- Fix: a JS/TS call with no local definition and no import no longer binds to a same-named export in an unrelated package (#1659, thanks @leonaburime-ucla). When a callee had exactly one same-named definition repo-wide, the cross-file resolver emitted a `calls` edge at INFERRED/0.8 even with no import path between the two files. On a monorepo this fabricated dependencies: a 14-package repo showed `platform` and `sidecar` depending on `registry-protocol` purely because it exported generically-named symbols (`*Schema`, etc.) that unresolved calls collapsed onto. JS/TS modules have no implicit cross-module scope, so a cross-file call is real only if the caller imported it — direct JS/TS cross-file `calls` attribution is now gated on import evidence and left unresolved otherwise. Other languages keep the single-candidate resolution (C/C++ headers, Ruby autoload, same-package implicit scope legitimately call across files without an explicit import), and the `indirect_call` path (already INFERRED and callable-gated) is unchanged. As part of the fix, caller→file mapping for import-evidence now uses the raw call's `source_file` string, so a path-resolution/symlink mismatch can no longer spuriously fail evidence and mislabel a real cross-file call.
|
||||
|
||||
## 0.9.6 (2026-07-04)
|
||||
|
||||
- Fix: Ruby plain modules and `Struct.new` / `Class.new` / `Data.define` constant assignments now get container nodes (#1640, thanks @krishnateja7). The extractor only created nodes for `class Foo`, so `module Foo` (utility/`module_function` modules), `Foo = Struct.new(...) do ... end`, `Foo = Class.new(StandardError)`, and `Result = Data.define(...)` produced no node at all — their methods hung off the file via `contains` with dot-less labels, and no edge could ever target them. `module` is now a container type (methods attach via `method` like a class, nested modules included), and a constant assignment whose RHS is one of those factories synthesizes a class node named after the constant, attaches block-defined methods to it, and emits an `inherits` edge for `Class.new(Super)`. Plain constant assignments (`MAX = 100`, `X = Foo.new`) are untouched.
|
||||
- Fix: Ruby constant-receiver singleton calls now resolve cross-file (#1634, thanks @krishnateja7). `Service.call`, `Model.where`, `SomeJob.perform_async` — the dominant Rails idiom — emitted no `calls` edge, so with Zeitwerk autoloading (no `require`s) a Rails app had essentially no cross-file edges and `affected`/`path` came up empty. `resolve_ruby_member_calls` now handles a capitalized (constant) receiver with any callee: it binds to the class's singleton/instance method when one is owned (`def self.call`, which the extractor indexes), else to the class node itself so inherited/dynamic class methods (ActiveRecord `where`/`find_by`) still give correct blast-radius. Namespaced receivers (`Billing::Processor.call`) resolve by the bare class name. The single-owning-class god-node guard is kept throughout — an ambiguous receiver resolves to nothing rather than a wrong edge.
|
||||
- Fix: Apex `interface X extends A, B` now emits an `extends` edge per parent (#1645, thanks @Synvoya). The interface regex captured the parent list in group 2, but the handler only read the interface name (group 1), so multiple-inheritance parents were dropped and only the `contains` edge survived. The interface branch now iterates the parent list and resolves each the same way the class branch already does.
|
||||
- Fix: Kotlin interface delegation (`class Foo : Bar by baz`) now emits the `implements` edge (#1644, thanks @Synvoya). The `by` form wraps the delegated interface in an `explicit_delegation` node, so neither the `constructor_invocation` nor the bare `user_type` branch fired and the edge was silently dropped. The delegation-specifier loop now unwraps `explicit_delegation` to its `user_type` (generic-argument recovery still runs), so idiomatic Kotlin delegation shows up in the graph.
|
||||
- Fix: a malformed semantic chunk no longer crashes `extract` and discards every successful chunk (#1631, thanks @ssazy). When an LLM returned a well-formed object whose `edges` (or `nodes`/`hyperedges`) array carried a stray non-dict entry — a nested list where an edge object belongs — the AST+semantic merge and the semantic-cache write both called `.get()` per entry and raised `AttributeError: 'list' object has no attribute 'get'`. On a 34-chunk run where 33 succeeded, that meant no `graph.json` was written and the cache write failed too, so a re-run re-extracted everything. `_parse_llm_json` now sanitizes each fragment at the single parse chokepoint (keeping only dict entries and coercing a non-list value to `[]`), so the cache writer, the adaptive-retry merge, and the CLI merge are all protected in one place.
|
||||
- Fix: an unresolved bare npm import no longer aliases onto an unrelated same-named local file (#1638, thanks @EveX1). `import colors from "tailwindcss/colors"` in a `.tsx` file emitted an `imports_from` edge to the bare id `colors`, and build.py's pre-migration alias index (which registers every local file's bare stem) then remapped it onto an unrelated `backend/utils/colors.py` — a confident (`EXTRACTED`) cross-language phantom edge, and one per `.tsx` file sharing the import. In a real monorepo eight unrelated `.tsx` files all landed on a single Python module. Common package subpaths (`colors`, `utils`, `types`, `config`, `client`) collide this way constantly. The external-import fallback now namespaces its target with the `ref` prefix (the same J-4 convention used for tsconfig `extends`/`$ref` externals), so it can never collapse to a local file/symbol id; the ref-namespaced target has no node, so build drops it as an external reference — the correct outcome for a third-party import.
|
||||
- Fix: `graph.json` node/edge ordering is now stable run-to-run for document/semantic corpora (#1632, thanks @umeshpsatwe). With a parallel LLM backend, `extract_corpus_parallel` merged chunk results in completion order, so which network call happened to return first reordered the nodes and edges even when the model returned identical content — churning `graph.json` between otherwise-identical runs. Chunks are now merged in deterministic submission order after the pool drains (matching the serial path); the progress callback still fires in completion order so long local runs aren't silent. Note: the semantic content the LLM extracts is itself nondeterministic run-to-run — this fix removes the pipeline's own ordering churn, not the model's variance.
|
||||
|
||||
- Fix: `graphify export obsidian` no longer crashes in `to_canvas` on a dangling community member (#1236 follow-up, thanks @swells808). The original #1236 fix guarded `to_obsidian` but not `to_canvas`, so a community member id with no backing node in the graph still raised `KeyError` while writing `graph.canvas` — after the notes had exported, leaving a partial mirror. `to_canvas` now applies the same dangling-member filter (`m in G and m in node_filenames`) in both the box-sizing and card-layout loops.
|
||||
|
||||
- Feat: TS/JS member calls on a local `new` binding or a type-annotated parameter now resolve (#1630, thanks @DanielC000). `const s = new Svc(); s.doThing()` and a call on a typed param — including inside a returned closure (`(svc: Svc) => () => svc.doThing()`) — now emit `calls` edges to the receiver type's method, so `affected` no longer silently under-reports. Extends the #1316 `this.field` resolver: the per-file type table now also learns local `new` bindings and bare-typed parameters, and `walk_calls` descends into inline/returned closures (attributing their calls to the enclosing function) instead of stopping at the arrow boundary. Resolution keeps the single-definition guard; an untyped or non-bare-typed (array/union/generic) receiver produces no edge.
|
||||
|
||||
- Fix: the `query` reference doc's inline vocab/fallback snippets now read and write files with `encoding="utf-8"` (#1619 A2, thanks @edtrackai). On Windows (default cp1252) the bare `read_text()`/`write_text()` calls crashed on exactly the cross-language corpora the doc demonstrates (e.g. Cyrillic labels like `обработчик`). Fixed across all generated skill variants.
|
||||
|
||||
- Fix: `graphify update`/`watch` no longer leaves stale sources after a deletion or a destination-only rename (#1623 / #1622, thanks @oleksii-tumanov). When the last supported file was deleted, or a rename reported only its destination in `changed_paths`, the removed source's nodes lingered in `graph.json`. The rebuild now reconciles extractor-backed sources against the files still present (code and document sources, subdirectory roots, legacy markers, symlinks, hyperedges) while preserving semantic and out-of-scope records.
|
||||
- Fix: `graphify query` guarantees per-term BFS seed diversity (#1596 / #1445, thanks @nokternol). A multi-term natural-language query could collapse to one seed when a single term hit an exact label match on an otherwise-unrelated node (`_EXACT_MATCH_BONUS` outscores substring matches ~1000×), and the 20%-gap seed cutoff then discarded every other term's seeds — so BFS explored only the incidental match's neighborhood. `_pick_seeds` now also seeds the best match for each distinct query term (ties broken by graph degree), so one term's incidental collision can't starve out the others. Partially addresses the seed-hijack in #1602.
|
||||
- Fix: `extract` no longer crashes during final graph assembly when a node's `source_file` equals the scan root (#1618, thanks @sub4biz). Such a node (e.g. a project-level semantic concept the LLM attributed to the whole repo) relativized to `Path('.')`, and `_file_stem`'s `path.with_suffix("")` raised `ValueError: '.' has an empty name` — crashing *after* all LLM extraction cost was spent and writing no `graph.json` at all. `_file_stem` now returns `""` for a name-less path, and `_semantic_id_remap` skips the root-equal node (it has no per-file identity to remap, so its id is left untouched). Not a 0.9.5 regression — the latent code was hit only when dedup happened to produce a root-`source_file` node.
|
||||
- Feat: C# receiver-typed member-call resolution (#1609, thanks @JensD-git). `recv.Method()` where `recv` is a typed field, property, parameter, or local now resolves to the receiver *type's* method. C# previously had no member-call resolver, so the bare method name matched any same-named method in the corpus — `_server.Save()` silently mis-bound to an unrelated `Cache.Save()` (a wrong edge, not just a missing one), leaving delegation-heavy call graphs blind across typed boundaries. The receiver is now typed from a per-file field/property/param/local table (incl. `var v = new T()`) and resolved with the single-definition god-node guard; `this.M()` binds to the enclosing class and `Type.M()` to the named type. An untypable receiver (e.g. `dynamic`) or a method absent on the type produces no edge — precision over recall, matching the Swift/C++/Python resolvers.
|
||||
- Fix: `graphify cluster-only` now writes `.graphify_analysis.json` alongside `graph.json` (#1617 / #1610, thanks @sanmaxdev). Without it, a re-cluster left a stale/absent sidecar and a later `export html` silently reported "Single community". The sidecar now carries communities/cohesion/gods/surprises/questions, matching the full extract path.
|
||||
- Fix: `.mts` / `.cts` (TypeScript module extensions) are now treated as TypeScript (#1607, thanks @ashmitg). They were missing from the code-extension set and the JS/TS language maps, so `.mts`/`.cts` sources were detected as non-code and silently skipped.
|
||||
- Fix: four TS/JS extractor gaps (#1615, thanks @papinto). Generator functions (`function*`) now register as callables; `namespace`/`module`/`declare module` containers become queryable nodes; and the TS import-equals form (`import x = require("./m")`) now emits an import edge (its module string nests in an `import_require_clause` the direct-child scan missed).
|
||||
- Fix: symlinked extraction inputs are contained to the scan root (#1613, thanks @Tok6Flow0). Symlink-directory following is now explicit opt-in, and resolved corpus paths must stay under the scan root before detection, AST collection, and LLM/image reads — an in-corpus symlink pointing outside the selected root is skipped rather than silently indexed. In-root symlinked sub-trees still work.
|
||||
- Fix: the `claude-cli` backend no longer stalls on an infinite chunk bisection under newer Claude Code CLIs. The extraction schema was delivered via `--system-prompt` with only the raw file dump in the user turn, on the assumption that a replacement system prompt is the model's sole authority. Claude Code >= ~2.1 (verified on 2.1.197) does not honour that: it still layers in the local coding-agent context (CLAUDE.md/AGENTS.md in cwd, skills, MCP) and, given a user turn that is just a file with no request, replies conversationally ("I see the file, but there's no actual request attached — what would you like me to do with it?"). That prose parses to zero nodes/edges, so `_response_is_hollow` flagged it as truncation and the adaptive-retry path bisected the chunk indefinitely (`94 → 47 → 23 → …`), never converging and never writing `graph.json`. The full extraction schema plus an explicit imperative now ride in the user turn and `--system-prompt` is dropped, so the CLI emits the JSON object directly; the `<untrusted_source>` prompt-injection guardrails are carried verbatim and unchanged. Other `_call_claude_cli` behaviour (model override, `--add-dir` image handling, timeout, token accounting) is untouched.
|
||||
|
||||
## 0.9.5 (2026-07-02)
|
||||
|
||||
- Feat: the MCP server can serve many projects from one process via an optional `project_path` on every tool (#1594, thanks @joanfgarcia). Omit it and nothing changes — the server answers against the graph it was started with. Pass an absolute `project_path` and that call is routed to `<project_path>/<GRAPHIFY_OUT>/graph.json` instead, with its own mtime+size hot-reload, so one stdio/HTTP server backs a whole workspace of repos. Graphs load lazily and cache per resolved path; a missing/corrupt project graph is a tool error, not a process exit, and the server starts even when its default graph is absent. Backward-compatible and additive.
|
||||
- Fix: Swift singleton cached into a local var now resolves later calls (#1604, thanks @jerryliurui). `let x = NetworkManager.shared` followed by `x.fetchData()` on a subsequent line produced zero call edges — local `let`/`var` bindings inside method bodies weren't typed (only class-level properties and params were), and a static-member init (`Type.shared`, a navigation expression) wasn't recognized even where locals were typed. Method-body locals are now typed from both constructor (`Type()`) and static-member (`Type.shared`) initializers, so `x.method()` resolves to the receiver type via the existing single-definition guard. This singleton-into-local idiom is one of the most common Swift call patterns.
|
||||
- Fix: the skill's Python-interpreter detection now accepts Homebrew `python@3.x` paths (#1586, thanks @SUDARSHANCHAUDHARI). The shebang allowlist rejected any path with a character outside `[a-zA-Z0-9/_.-]`, but Homebrew installs versioned Python under `python@3.13`, so a valid interpreter containing `@` was skipped and detection fell through to a bare `python3` that lacked graphify (every step then failed with `ModuleNotFoundError`). `@` is now allowed across all skill variants (matching the #473 hooks.py fix); injection characters are still rejected.
|
||||
- Fix: `graphify merge-graphs` no longer crashes on inputs that disagree on graph type (#1606, thanks @AdrianRusan). Per-repo `graph.json` files don't always share the same `directed` / `multigraph` flags, and `compose` requires one uniform type, so a mixed set raised an unhandled `NetworkXError`. All inputs are now normalized to a plain undirected graph (which the cross-repo merged view already is) before composing.
|
||||
- Fix: type-reference / inheritance edge gaps closed across seven languages (all thanks @Synvoya):
|
||||
- Scala: `var` field declarations now emit type `references` like `val` (#1587).
|
||||
- PowerShell: class base types after `:` now emit `inherits` (first) / `implements` (rest), matching the C# convention (#1588).
|
||||
- Objective-C: protocol-to-protocol adoption (`@protocol Derived <Base>`) now emits an `implements` edge (#1589).
|
||||
- PHP: promoted constructor properties (`__construct(private Repo $r)`) now emit type `references` (method + class field) (#1590).
|
||||
- C#: auto-properties (`public Widget Main { get; set; }`) now emit type `references` like fields, including generic args (#1591).
|
||||
- C++: base-class template arguments (`class Car : Base<Dep>`) now emit `generic_arg` references, matching the Java behavior (#1592).
|
||||
- Swift: enum associated-value types (`case started(Session)`) now emit `references` (#1593).
|
||||
- Fix: cross-file name resolution now respects case in case-sensitive languages (#1581, thanks @sheik-hiiobd). Resolution matched identifiers case-insensitively for every language, so in Python/Rust/Go/Java/etc. `from pathlib import Path` resolved to an unrelated shell-script `export PATH=...` node — a single variable becoming the corpus's #1 god-node (266 false incoming edges on one real repo), inflating god-node rankings, `affected` blast-radius, and community assignment. Both the cross-file call resolver and the type-reference stub-rewire now match by exact case; only genuinely case-insensitive languages (PHP functions/classes, SQL, Nim) still fold. For case-sensitive languages this only ever removes false edges.
|
||||
- Fix: Julia qualified / relative / scoped-selected imports now emit edges (#1580, thanks @Synvoya). Only bare `using Foo` was handled; `using Base.Threads` (scoped), `using ..Parent` (relative import_path), and the scoped package of `import Base.Threads: nthreads` were dropped.
|
||||
- Fix: Rust tuple-struct field types now emit `references` edges (#1582, thanks @Synvoya). `struct Wrapper(Logger, Vec<Config>);` referenced nothing — positional fields nest under `ordered_field_declaration_list` with no `field_declaration` wrapper, the same shape as tuple enum variants (#1579); that path wasn't traversed for structs.
|
||||
- Fix: SystemVerilog class properties with leading qualifiers now emit field `references` (#1583, thanks @Synvoya). The field regex only matched unqualified `<type> <name>;`, so `rand Config x;` / `protected Base b;` (qualifier + type + name) failed to match and their type references were dropped.
|
||||
- Fix: Elixir multi-alias brace form now emits imports edges (#1577, thanks @Synvoya). `alias Foo.{Bar, Baz}` produced no imports (the handler only matched a bare single alias); it now expands to one edge per member module. Single `alias`/`import`/`require`/`use` unchanged.
|
||||
- Fix: Fortran function invocations now emit `calls` edges (#1578, thanks @Synvoya). Only `call sub(...)` (subroutine) calls were captured; `y = f(x)` function calls (a `call_expression`) were dropped. Resolved against procedures defined in the file so array indexing (`arr(i)`, same `name(...)` syntax) can't fabricate a spurious call.
|
||||
- Fix: Rust enum variant payload types now emit `references` edges (#1579, thanks @Synvoya). `Click(Logger)` / `Resize { size: Dim }` referenced nothing — `enum_item` had no type-reference handler (struct/trait did). Both tuple and struct variant field types now resolve.
|
||||
- Fix: `graphify cluster-only` no longer reuses stale community labels after the graph changed. When a repo was re-scoped/re-clustered, the saved `.graphify_labels.json` was applied wholesale to the new community set — so a community id that now covered a different community wore the old (LLM) name, silently. cluster-only now writes a per-community membership signature beside the labels and, on reuse, keeps a saved label only for communities whose membership is unchanged; any community that changed (or, for pre-signature label files, when the community count no longer matches) is renamed by its deterministic hub, with a warning to run `graphify label` for fresh LLM names.
|
||||
- Fix: cross-file `indirect_call` edges were dropped by `graphify extract` on the CLI (a 0.9.4 regression). The callable-target guard for cross-file indirect dispatch was keyed on node ids collected before the id-relativization/disambiguation passes; when the scan root relativizes ids (the CLI's default, `cache_root == project root`), those ids went stale and every cross-file indirect edge was silently dropped — only same-file ones survived. Callable-ness is now read from a node marker that rides through the remaps, so `submit(imported_fn)`, imported dispatch tables, assignment/getattr aliases across files resolve on the CLI as they already did via the `extract()` API.
|
||||
|
||||
## 0.9.4 (2026-07-01)
|
||||
|
||||
- Fix: Ruby class inheritance now emits an `inherits` edge (#1535, thanks @Synvoya). `class Dog < Animal` produced `contains`/method/call edges but no `inherits` edge — the inheritance handler had branches for Java/Kotlin/C#/Scala/C++/PHP/Swift/Python but none for Ruby, so the `superclass` field was never read. Handles both bare (`< Animal`) and qualified (`< M::Base`) superclasses.
|
||||
- Fix: Groovy `extends`/`implements` now emit `inherits`/`implements` edges (#1534, thanks @Synvoya). tree-sitter-groovy exposes inheritance through the same grammar shape as tree-sitter-java, but the handler was gated to Java only, so every Groovy inheritance relationship was dropped.
|
||||
- Fix: corrupt `graph.json` now raises a clear, actionable error instead of a raw traceback (#1537 / #1536, thanks @guyoron1). The three graph-loading paths — `build_merge` (`--update`), `load_graph` (`graphify prs`), and diagnostics (`graphify diagnose`) — wrap `json.loads` and raise a `RuntimeError` with recovery guidance on a truncated/invalid file (incomplete write, power loss, manual edit).
|
||||
- Fix: cross-chunk node-ID collisions now warn instead of silently dropping a node (#1508 / #1504, thanks @nuthalapativarun). When two nodes share an ID but come from different source files (two same-named files in different directories), dedup keeps the first and now prints a warning naming both files and how to avoid the loss (`graphify extract` per subfolder + `merge-graphs`).
|
||||
- Fix: git hooks on Windows/MSYS default to sequential rebuilds (#1554, thanks @matiasduartee). Hook-triggered rebuilds now export `GRAPHIFY_MAX_WORKERS=1` on Windows/MSYS (explicit user value still wins), avoiding fragile inherited pipe handles; and the Windows-path hooks guard is a no-op on native Windows, where such paths are legitimate.
|
||||
- Docs: correct the `deduplicate_by_label` docstring — it is dormant, not auto-called by `build()` (#1514, thanks @TPAteeq). The active dedup path is `deduplicate_entities`; the note that `deduplicate_by_label` runs automatically was never true, and it must not be enabled for code nodes (it merges by label with no file_type guard, conflating same-named symbols across files).
|
||||
- Feat: deterministic hub community labels, readable without an LLM (#1576, thanks @sheik-hiiobd). When no LLM backend is configured, community labels used to fall back to `Community 70`, making the report and its Suggested Questions unreadable. Each community is now named after its highest-degree member (the structural hub, ties broken by node id for run-to-run stability) — so a plain `graphify` run reads `auth` / `log_action` at zero token cost. A configured LLM naming pass still overrides these with richer names; `--no-label` still yields bare `Community N`.
|
||||
- Feat: extend `indirect_call` to `getattr(obj, "name")` reflective dispatch (#1575, #1566 slice 3, thanks @sheik-hiiobd). A callable looked up by a string literal — `fn = getattr(obj, "handler")` — now emits an `indirect_call` edge (context `getattr`, INFERRED) so `affected` reaches it. Only a plain string literal resolves; a variable, f-string, or concatenation is dynamic and emits nothing. Unlike the identifier paths, a getattr string names an attribute, not a binding, so it is never shadowed by a param/local — `def via(handler): getattr(x, "handler")` still resolves to the module `handler`. Function and module scope; cross-file handled by the shared resolver. Python only for now.
|
||||
- Fix: `graphify --update` no longer drops hyperedges from unchanged files (#1574, thanks @socar-tender). `build_merge` read only nodes and edges from the existing `graph.json`, never hyperedges — so every incremental update collapsed the graph's hyperedge set (the semantic domain-flow groupings) down to just the re-extracted files'. Existing hyperedges are now carried forward: re-extracted files' prior hyperedges are replaced by their new version (by `source_file`), deleted files' are pruned, and the rest are preserved with id-dedup — mirroring how `watch` already handled it.
|
||||
- Fix: `graphify --update` no longer leaves ghost nodes for deleted files when `build_merge` is called without `root` (#1571, thanks @goodjira). Absolute `prune_sources` paths (from `detect_incremental`) never relativized to match the stored relative `source_file` keys, so deleted files' nodes survived the prune. `build_merge` now infers a fallback root when none is passed — the committed `graphify-out/.graphify_root` marker, else the output dir's parent — so pruning (and re-extract replacement) work regardless of the caller. The shipped `--update` runbooks already pass `root`; this hardens the library for any caller that doesn't.
|
||||
- Feat: extend `indirect_call` to assignment and return references (#1569, #1566 slice 2, thanks @sheik-hiiobd). A function bound to a name (`cb = handler`), returned from a factory (`def make(): return handler`), or aliased at module level (`CALLBACK = handler`) now emits an `indirect_call` edge, so `affected` reaches it. Captures the value side only (a bare name or a bare unpack `a, b = f, g`); a collection literal on the RHS stays with the dispatch-table scan. Reuses the shared guard, so the inverted-shadow trap is handled by construction — a param/local named on the RHS still hits the shadow guard and emits nothing (no return of #1565's false edges). Function and module scope; Python only for now.
|
||||
- Fix: the skill-version mismatch warning is now direction-aware (#1568, thanks @TPAteeq). It used to advise `Run 'graphify install' to update` on ANY version difference, but `install` writes the package's own bundled skill and re-stamps the version — so when the skill on disk was NEWER than the package (a stale `uv tool` CLI, or a contributor's dev checkout), following that advice silently DOWNGRADED the skill to make the warning go away. Now when the skill is newer, the warning recommends upgrading the package (`uv tool upgrade graphifyy` / `pip install -U graphifyy`) instead; the older-skill case still recommends `install`. Versions compare numerically (so `0.10` > `0.9`).
|
||||
- Feat: extend `indirect_call` capture to JS/TS (#1566). The same model now applies to JavaScript and TypeScript: a callback passed by name (`arr.map(fn)`, `setTimeout(fn)`, Express-style `app.get("/", handler)`, event wiring `emitter.on("e", handler)`) and functions listed in object/array dispatch tables (`const ROUTES = { create: handler }`, `const HOOKS = [onStart, onStop]`). Arrow-const functions (`const cb = () => {}`) count as callable targets; object shorthand (`{ handler }`) is a reference; inline arrows/function expressions are direct definitions and are not captured; object KEYS and non-callable values are excluded. Same guards as Python: callable-target-only, not shadowed by a param/local/module reassignment, single-definition god-node guard cross-file. Cross-file resolution is import-aware — a `import { onEvent }` edge to the symbol no longer suppresses the `indirect_call` to it. Module-level call-argument registration (idiomatic in JS) is captured in addition to the function-scoped capture Python has.
|
||||
- Feat: extend `indirect_call` to dispatch tables (#1566). A function listed as a VALUE in a dict/list/set/tuple literal — a route/handler registry like `ROUTES = {"create": create_user, "delete": delete_user}` or `HOOKS = [on_start, on_stop]` — now emits an `indirect_call` edge so `affected` reaches those handlers too. Works at module level (attributed to the file) and inside a function (attributed to the function), same-file and cross-file. Same guards as the call-argument case: callable-target-only, not shadowed by a param/local/module-level reassignment, dict KEYS excluded (only values are references).
|
||||
- Feat: capture indirect dispatch as `indirect_call` edges so `graphify affected` (blast radius) catches callers that pass a function by name as a call argument — `executor.submit(fn)`, `Thread(target=fn)`, `map(fn, xs)`, callbacks (#1565, thanks @sheik-hiiobd). Kept as a distinct INFERRED relation separate from `calls` (strict call-graph queries stay precise) and added to the affected relation set. Hardened against false edges: the argument name must resolve to a callable definition and must NOT be shadowed by a parameter or local binding in the enclosing function — so the idiomatic `def via(pool, handler): pool.submit(handler)` (handler is the param) and a data variable sharing a function's name produce no edge. Now also resolves cross-file: a callback imported from another module (`from .handlers import on_event; pool.submit(on_event)`) routes through the same cross-file resolver as direct calls — single-definition god-node guard, callable-target-only, staying INFERRED — closing the gap where #1565 saw only same-file callbacks (the common real-world shape is cross-module). Python only for now.
|
||||
|
||||
## 0.9.3 (2026-06-30)
|
||||
|
||||
- Feat: cross-file member-call resolution for C++ and Objective-C (#1547, #1556). A class declared in a header and defined in its `.cpp`/`.m` no longer fragments into two nodes (a decl/def merge pass collapses the sibling header/impl pair, gated to same-directory same-name so unrelated classes never merge), and a member call now resolves across files by the receiver's inferred type: C++ `Foo f; f.bar()` / `Foo::bar()` / `this->bar()` and ObjC `Foo *f = [[Foo alloc] init]; [f doThing]` / `[self render]` link to the owning class's method. Resolution is by receiver type, never bare name, with the single-definition god-node guard — an uninferable or ambiguous receiver produces no edge (high precision over recall, grounded in how compiler-free indexers like ctags/Doxygen mis-resolve by name). Also routes C++ headers to the C++ extractor and ObjC `#import` bridging headers to the ObjC extractor. Reported by @c0dezer019 and @JabberYQ. (Residual cross-file `#include` edge resolution under symlinked roots and ObjC dynamic-dispatch receivers remain follow-ups.)
|
||||
- Feat: namespace-aware C# cross-file type resolution (#1562, thanks @TheFedaikin). The namespace is folded into the C# node id (so same-named types in different namespaces stay distinct), `using` directives are honored with lexical per-block scope, and qualified references (`Namespace.Type`, `using` aliases) resolve — disambiguating a bare reference to the one in-scope namespace that provides it, and refusing (no edge) when ambiguous. Advances the #1318 shadow-node umbrella for C#.
|
||||
- Fix: test mocks no longer erase the real cross-file call graph (#1553, thanks @Schweinehund). When a bare callee name had 2+ definitions without unique import evidence, the god-node guard dropped the edge entirely — so a single same-named test mock wiped the real call graph (a 76-stub Pester suite erased everything). The guard now applies tie-breakers — non-test preference (a shared, segment-aware path classifier) then path proximity — and resolves only when exactly one candidate survives, else still bails. A real def plus a test mock resolves to the real def; two genuine non-test defs still bail (no fan-out).
|
||||
- Fix: hyperedge member lists keyed `members` or `node_ids` are now accepted, not silently dropped (#1561, thanks @askalot-io). Normalized to the canonical `nodes` at ingest (in build_from_json and semantic_cleanup), deduped, with a warning — mirroring the existing from/to edge-endpoint aliasing.
|
||||
- Feat: work-memory overlay — `graphify reflect` now projects the verdicts it distills (preferred / tentative / contested, recency-weighted) into a `.graphify_learning.json` sidecar next to graph.json, and `graphify explain` / `query` / `GRAPH_REPORT.md` / the HTML viewer surface them where you look (a `Lesson:` hint, a colored node ring). Builds on the idea in #1441/#1542 (thanks @TPAteeq), implemented as a sidecar rather than stamping graph.json: structural truth stays separate (no `learning_*` in graph.json or GraphML exports, no rebuild churn). Each verdict carries the source questions that produced it (provenance) and a content fingerprint of the cited code, so a verdict on a file that has changed since is flagged "code changed — re-verify" instead of shown as still-authoritative. Dead-ends stay query-scoped (a report section, never a node attribute). Letting verdicts influence query traversal is deliberately deferred (it needs propensity correction + exploration to avoid a self-reinforcing feedback loop).
|
||||
- Feat: type-aware `this.field.method()` resolution for TypeScript/JS (#1316, thanks @guyoron1). A member call through a constructor-injected dependency (`constructor(private db: Database)` then `this.db.query()`) now produces a `calls` edge to the field type's method, resolved by the field's declared type and gated by the single-definition god-node guard (an ambiguous or untyped field produces no edge — no global name-match fan-out). EXTRACTED confidence; constructor parameter-property injection scope.
|
||||
- Feat: resolve TypeScript wildcard path aliases (#1544, thanks @oleksii-tumanov). A `compilerOptions.paths` pattern like `@app/*` or `@*/interfaces` now captures the matched segment and substitutes it into each target in order, honoring tsc's longest-prefix / exact-wins specificity, baseUrl, and the first-existing-target fallback. Extends the #1531 resolver.
|
||||
- Feat: resolve JS namespace re-export bindings (#1552, thanks @oleksii-tumanov). `export * as ns from './mod'` now creates a real symbol node for `ns`, registers it as a named export (so a downstream `import { ns }` resolves to it), and emits a file-level `re_exports` edge — treated as a single opaque binding, so `ns.member` accesses don't fan out into false per-symbol edges. Includes cycle and deep-chain guards.
|
||||
- Feat: Objective-C dot-syntax property accesses and `@selector()` call edges (#1475, #1543, thanks @guyoron1). `self.product.name` now emits an `accesses` edge and `@selector(method)` a `calls` edge, each resolved only to an unambiguous in-scope definition by exact method-id match (a sibling of the same class for dot-syntax; exactly one method by exact selector name for `@selector`) — so `self.name` can't mis-resolve to a `-surname` sibling and same-named methods across classes don't fan out. Completes the #1475 ObjC follow-ups.
|
||||
|
||||
## 0.9.2 (2026-06-29)
|
||||
|
||||
- Feat: type-aware Ruby member-call resolution (#1499, thanks @vamsipavanmahesh). `p.run` is now resolved by the inferred type of the receiver (`p = Processor.new` ⇒ `Processor#run`) instead of by globally-unique method name, so the edge survives name collisions (an unrelated `Worker#run` no longer makes it ambiguous) and never points at the wrong method. Introduces a small resolver-registry framework that the existing Swift (#1356) and Python (#1446) cross-file passes register into. Receiver types are inferred only from unambiguous local `var = ClassName.new` bindings; a call whose receiver type can't be proven resolves to nothing rather than to a guess — a deliberate precision-over-recall change for Ruby member calls.
|
||||
- Feat: resolve workspace imports through the package's `exports` map (#1308, thanks @guyoron1). A subpath import like `import { x } from "@scope/pkg/browser"` now resolves through the package.json `exports` map (string values, condition objects, nested conditions, and `./*` wildcard patterns) instead of falling back to a bare path string, falling back to the existing bare-path/index resolution when there's no exports map or no match. `default` is consulted last (Node's catch-all), and an export target that escapes the package directory is rejected.
|
||||
- Fix: import edges silently dropped on codebases using tsconfig path aliases or workspace packages (#1529), a regression from the 0.9.0 full-repo-relative node-ID change. Relative imports resolve to repo-relative paths and matched fine, but alias (`@/lib/utils`) and workspace imports resolve to absolute paths, so the import-target ID baked in the on-disk prefix and no longer matched the repo-relative definition node — the edge was dropped at build (common on Next.js/SvelteKit). The id-remap post-pass now also registers the absolute-resolved form, so alias/workspace import targets land on the real node again.
|
||||
- Fix: tsconfig `compilerOptions.paths` fallback targets are now honored (#1531, thanks @oleksii-tumanov). A `paths` value is an ordered list (`"@app/*": ["src/app/*", "lib/app/*"]`) that `tsc` tries in turn; graphify kept only the first entry, so an import whose file lived at a later target was dropped or misresolved. Each target is now tried in order and the first that resolves to a real file wins (no false edge when none exist).
|
||||
- Fix: the semantic (LLM) extraction cache is now pruned (#1527, thanks @mwolter805). The AST cache was version-swept but the content-hash-keyed semantic cache had no cleanup, so every content change or file deletion left an orphan entry and `graphify-out/cache/semantic/` grew unbounded. Orphan entries are now removed at the end of `extract`, computed against the full live document set (not the incremental changed subset, which would have evicted still-valid entries) and only touching `cache/semantic/`; the cache stays unversioned so releases never re-bill LLM extraction.
|
||||
- Fix: three Objective-C extractor bugs (#1475, thanks @JabberYQ for the detailed report and test repo). (1) `.h` headers using `NS_ASSUME_NONNULL_BEGIN` before `@interface` produced no class node — tree-sitter-objc can't expand the argument-less macro and fails to emit a `class_interface` node at all, so the macro is now blanked (offset-preserving) before parsing. (2) Quoted `#import "X.h"` edges dangled once a `.h`/`.m` pair existed (the bare-stem target was salted away during id-disambiguation); imports now resolve to the real header file node, fixing the equivalent latent C `#include` bug too. (3) `[[Foo alloc] init]` now emits a `references` edge to the allocated class, resolved only to an unambiguous class (no false edges). Dot-syntax property accesses and `@selector(...)` target-action edges remain follow-ups.
|
||||
- Fix: Swift type-qualified static calls now resolve as EXTRACTED rather than INFERRED (#1533, thanks @JabberYQ). `SessionType.staticMethod()` / `Singleton.shared.method()` name the receiver type explicitly in source, so the resolved edge is an exact reference, matching the Python qualified-class-method pass; instance calls typed via local inference (`obj.method()`) stay INFERRED.
|
||||
- Fix: enforce the API timeout in the secondary LLM dispatch path (#1442, thanks @DhruvTilva). `_call_llm` (used by the dedup LLM tiebreaker) built its Anthropic/OpenAI clients without `timeout`, so requests there ignored `GRAPHIFY_API_TIMEOUT` and could hang — it now passes the timeout like the primary extraction paths.
|
||||
- Fix: `to_graphml` no longer raises `ValueError` on a node/edge with a `None` attribute value — null fields are coerced to `""` before writing (#1502, thanks @antonioscarinci).
|
||||
- Feat: `graphify save-result` accepts `--answer-file` as an alternative to `--answer`, so a long or multi-line answer can be read from a file instead of an inline shell argument (#1502, thanks @antonioscarinci).
|
||||
- Fix: generated install/skill guidance is now host-generic (#1530, thanks @ari-mitophane). The wording no longer tells agents to invoke a literal `skill` tool with `skill: "graphify"` (host-specific and invalid in many environments); it now points to the installed graphify skill or instructions.
|
||||
- Security: bump `msgpack` to 1.2.1 (GHSA-6v7p-g79w-8964) and `pydantic-settings` to 2.14.2 (GHSA-4xgf-cpjx-pc3j), and drop the unused `safety` dev dependency, which only pulled in `nltk` (an unpatched HIGH advisory). All transitive; the two HIGH-severity ones were dev-tooling only and never in the published wheel. `pip-audit` (already run in CI) continues to provide dependency-CVE scanning.
|
||||
|
||||
## 0.9.1 (2026-06-28)
|
||||
|
||||
- Fix: rate-limited (HTTP 429) extraction chunks are now retried instead of dropped (#1523, thanks @bercedev). The provider SDKs back off and honor `Retry-After`, but the SDK default of 2 retries was too low for strict per-org concurrency/RPM caps (e.g. Moonshot/kimi), so a parallel `extract` 429'd, each chunk logged `chunk N failed`, and was silently lost (incomplete graph + console spam). The OpenAI-compatible, Azure, and Anthropic clients are now built with a higher `max_retries` (default 6, override via `GRAPHIFY_MAX_RETRIES`). For very tight accounts, `--max-concurrency 1` further reduces the concurrency that triggers org-level limits.
|
||||
|
||||
- Fix: `graphify update` now prunes the edges a re-extracted file no longer produces (#1521, thanks @UltronOfSpace). Old edges were preserved by endpoint-node membership alone, so a deleted import's edge survived forever as long as both endpoints still existed — driving phantom circular-dependency findings (and `--force` didn't help). Edges owned by a re-extracted file (`source_file`) are dropped before merging the fresh extraction; cross-file edges that merely point at the file are untouched.
|
||||
- Fix: residual node-ID collisions after the 0.9.0 full-path change (#1522, thanks @sub4biz). `normalize_id` collapses every separator to `_`, so distinct paths that differ only by a separator-vs-punctuation swap (`foo/bar_baz.py` vs `foo_bar/baz.py`) still merged. Colliders are now salted with a short stable path hash so they stay distinct; non-colliding IDs are byte-identical to 0.9.0 (no re-migration).
|
||||
- Fix: Java record component types now emit `references` edges (#1519, thanks @oleksii-tumanov) — a record's data dependencies (`record Order(Payload p, List<Item> items, …)`) were invisible; primitives and the record's own type parameters are skipped.
|
||||
- Fix: same-label cross-file imported-type stubs now stay distinct in the six dedicated extractors too — Julia, Fortran, Go, Rust, PowerShell, ObjC (#1515, thanks @TPAteeq). The #1462 disambiguation previously only covered the generic extractor, so e.g. two Go files importing the same `ext.Widget` collapsed into one conflated node; they're now kept distinct (while `source_file` stays empty so the #1402 rewire onto a real definition is unchanged).
|
||||
- Fix: Java type parameters no longer emit spurious `references` edges (#1518, thanks @oleksii-tumanov). The generic-parent support (#1511) created a stray edge/stub for the bare `T` in `class Box<T> extends Container<T>`; the extractor now collects in-scope type-parameter names (class/interface/record/method/constructor, incl. bounded/multiple) and skips them, while keeping every real type and the `inherits`/`implements` edge to the base.
|
||||
- Fix: the internal `origin_file` disambiguation field (#1462) is no longer serialized into graph.json, where it had shipped (in 0.9.0) as an absolute, machine-specific path — it is dropped once the colliding-id pass consumes it, keeping output portable (#1516, thanks @TPAteeq; cf. #555, #932). `_origin` stays (the incremental watcher needs it, #1116).
|
||||
|
||||
## 0.9.0 (2026-06-28)
|
||||
|
||||
- **Breaking — node IDs now include the full repo-relative path** (#1504, #1509). The node-ID stem was the immediate parent dir + filename, so same-named files in different directories collided into one last-writer-wins node and silently dropped graph content (`docs/v1/api/README.md` and `docs/v2/api/README.md` both → `api_readme`). The stem is now the full repo-relative path (`docs_v1_api_readme` vs `docs_v2_api_readme`); top-level files are unchanged (`setup.py` → `setup`). The AST extractor, the LLM system prompt, the extraction-spec, and the two hand-copied stem helpers are all aligned to this one rule (fixing the #1509 AST↔LLM divergence that produced ghost duplicates), and `build_from_json` deterministically re-keys any cached/older semantic fragment onto the new IDs from its `source_file` so the unversioned semantic cache survives without ghosts or a re-bill. **Existing graphs migrate to the new ID format automatically on the next `build`/`update`** (no re-bill). Note: same-named files in different directories that previously collided into one node are only *recovered as distinct nodes* by a fresh extraction — run `graphify extract --force` to rebuild and gain them (migrating an already-collided graph/cache can't resurrect the nodes that were already dropped). If you push to a persisted **Neo4j** store, re-import after upgrading (re-exported IDs change); saved Gephi/yEd (GraphML) layouts go stale; MCP/cypher consumers should query by label rather than persisting node IDs across rebuilds.
|
||||
- Feat: `--timing` flag on `graphify extract` and `graphify cluster-only` prints per-stage wall-clock timings to stderr (#1490). Shows how long each pipeline stage takes — `extract`: detect → AST → semantic → build → cluster → analyze → export; `cluster-only`: load → cluster → analyze → label → report → export — plus a final total, so slow stages are visible on large corpora. Off by default (monotonic `perf_counter`, stderr-only); machine-read stdout / `graph.json` are unchanged.
|
||||
|
||||
## 0.8.51 (2026-06-28)
|
||||
|
||||
- Fix: the Obsidian export (`--obsidian` / `to_obsidian`) no longer overwrites a user's own notes or `.obsidian/` config when pointed at an existing vault (#1506). It wrote one note per node straight into the target dir and unconditionally replaced `.obsidian/graph.json`, so `--obsidian-dir ~/my-vault` could clobber a same-named note (`Database.md`) and the user's graph-view settings — silently, no backup. graphify now records the files it owns in a `.graphify_obsidian_manifest.json` and refuses to overwrite any pre-existing file it didn't create (skipping it with one aggregated warning); a re-run still updates graphify's own notes. The default `graphify-out/obsidian` output is unchanged.
|
||||
- Fix: Java enum and annotation (`@interface`) declarations are now emitted as type nodes (#1512, thanks @oleksii-tumanov), so a field typed as an enum or a class annotated with a project annotation resolves to a real node instead of a dangling reference.
|
||||
- Fix: Java generic parent relationships are no longer dropped (#1510, thanks @oleksii-tumanov) — `class Foo extends Bar<T>` / `implements List<T>` now emit the `inherits`/`implements` edge to the base type, with the type arguments as `generic_arg` references.
|
||||
- Fix: the `claude-cli` backend no longer crashes with `UnicodeDecodeError` on Windows systems where `claude.cmd` emits GBK/cp936 bytes (#1505, thanks @nuthalapativarun) — both subprocess calls decode with `errors="replace"`.
|
||||
- Fix: `graphify explain` and `graphify affected` now resolve a query given as a source-file path even when the graph has multiple nodes from that file (#1503, thanks @behavio1). A path like `app/api/route.ts` tokenized to terms that matched no node, so explain returned "No node matching"; source-file paths are now indexed and matched exactly, and when several nodes share the file the lookup prefers the file-level node (the `L1` node whose name matches the file). Trailing-separator handling is aligned between the two commands.
|
||||
- Docs: clearer install/PATH guidance for `uv tool install graphifyy` on macOS (#1471, thanks @Patsch36). Two expected uv behaviors read as bugs: (1) after `uv tool install`, the `graphify` command lands in uv's tool bin dir (`~/.local/bin`), which a fresh macOS/zsh shell often doesn't have on `PATH` — the README now points to `uv tool update-shell` instead of implying uv always wires `PATH`; (2) `uvx graphify …` / `uv tool run graphify …` resolve the first word as a *package* and fail, because the package is `graphifyy` and `graphify` is only its console script — the docs now show `uvx --from graphifyy graphify install`. README install note + Troubleshooting only; no code change.
|
||||
- Fix: imported type stubs with the same label no longer falsely merge across files when there is no project definition to rewire onto (#1462, thanks @jiangyq9). Two files that both `from pathlib import Path` and use `Path` as a type previously collapsed into one node; the referencing file is now kept as an internal disambiguator (`origin_file`) used only when splitting colliding ids, while `source_file` stays empty so a real project definition can still be rewired onto (the #1402 path is unaffected).
|
||||
- Feat: resolve C# cross-file type references and extract `enum`/`struct`/`record` declarations (#1466, thanks @TheFedaikin). A new `_resolve_csharp_type_references` (the C# counterpart to the Java resolver) re-points dangling `inherits`/`implements`/`references` edges from no-source "shadow" stubs to their real definitions, disambiguating same-named types in different namespaces via the referencing file's `using` directives and enclosing namespace; ambiguous matches are refused rather than guessed. `enum`/`struct`/`record` types are now extracted as definitions so those references resolve too. Advances #1318 for C#.
|
||||
- Fix: the Go AST extractor no longer creates phantom duplicate nodes for cross-file type references — the Go copy of `ensure_named_node` still used the older sourced-stub fallback; it now emits a sourceless stub like the other extractors, extending the #1402 fix to Go (#1500, thanks @TPAteeq).
|
||||
- Fix: cross-file references to a same-named type now stay distinct across the six dedicated AST extractors (Go, Rust, Julia, Fortran, PowerShell, ObjC) instead of conflating into one shared node — #1462's `origin_file` stub-disambiguation had only been applied to the generic extractor; it now covers all seven.
|
||||
|
||||
## 0.8.50 (2026-06-27)
|
||||
|
||||
- Feat: `graphify label --missing-only` relabels only communities that are unnamed or still hold a `Community N` placeholder, preserving existing non-placeholder labels from `.graphify_labels.json` (#1481, thanks @jiangyq9; supersedes #1421 by @matiasduartee, who proposed the same flag). Lets a large graph be relabeled incrementally without re-naming (and paying for) communities that already have good names.
|
||||
- Feat: index Metal (`.metal`) shader files — Metal Shading Language is C++14, so `.metal` is classified as code and routed through the existing C++ extractor, mirroring the CUDA `.cu`/`.cuh` reuse (#1480, thanks @jiangyq9; supersedes #1450 by @GoodOlClint). Also adds `.cu`/`.cuh`/`.metal` to the cross-language edge-filter family map (they were missing), so phantom cross-language `calls` edges between these and C++ are correctly suppressed.
|
||||
- Fix: pass `stream: False` explicitly on OpenAI-compatible chat-completion calls (#1223, thanks @jiangyq9). Some gateways default to SSE streaming when `stream` is omitted, but graphify always reads the result as a single response, so the call failed against those gateways. Applied to both the extraction dispatch path and the `--dedup-llm` tiebreaker path.
|
||||
- Fix: emit `references` edges for Java field types (#1485) and for type-level annotations on Java classes/interfaces/records (#1487, both thanks @oleksii-tumanov). Field types (including the `generic_arg` element of `List<Handler>`) and class annotations (`@Service`, `@Entity`) were missing from the graph even though parameter/return types and method annotations were already captured; primitives are still skipped.
|
||||
- Fix: the Objective-C extractor was silently dropping most code-level relationships (#1475, thanks @JabberYQ for the detailed report). Five fixes: (1) ObjC `.h` headers were parsed by the C extractor (1 node, 0 edges, losing every `@interface`/`@protocol`/`@property`/method) — a `.h` is now routed to the ObjC extractor when it contains an ObjC-only directive (`@interface`/`@protocol`/`@implementation`/`@import`), which never hijacks a real C/C++ header; (2) `[receiver selector]` calls produced no `calls` edges at all because the method-body pass looked for `selector`/`keyword_argument_list` nodes, but the grammar tags selector parts with the field name `method` (type `identifier`) — the selector is now read from the `method` fields, skipping the receiver, which also makes compound sends like `[self a:x b:y]` resolve; (3) generic property types (`NSArray<Product *> *`) were invisible because the type was wrapped in a `generic_specifier` — the element and container types are now both referenced; (4) class methods (`+foo`) were mislabeled `-foo`; (5) `@import Foundation;` now produces an `imports` edge. Property/dot-syntax `accesses` and `@selector(...)` target-action edges remain follow-ups.
|
||||
- Feat: link WPF/XAML views to their ViewModels and extract richer binding references (#1473, thanks @MikeKatsoulakis). Builds on the initial XAML support (#1460). Resolves a view to its ViewModel from an explicit `<Window.DataContext><vm:MainViewModel/>`, a design-time `d:DataContext="{d:DesignInstance Type=…}"`, the `View`→`ViewModel` naming convention, or Prism `ViewModelLocator.AutoWireViewModel="True"` — always against an actually-extracted C# class, so a name with no matching class (or an ambiguous one) emits no edge (explicit DataContext is EXTRACTED, conventions are INFERRED). Also extracts binding paths (`{Binding User.Name}`, `Path=Order.Total`), commands (`Command="{Binding SaveCommand}"`), converters, and CommunityToolkit `[ObservableProperty]`/`[RelayCommand]` generated members. The event-handler resolution stays gated on the .NET handler signature (no spurious event edges), and ViewModel discovery is bounded to the extraction root.
|
||||
- Fix: `.vue` Single File Components now extract their `<script>` with the right grammar (#1468, thanks @papinto). `.vue` was dispatched to `extract_js`, which selects a tree-sitter grammar by suffix; `.vue` is neither `.ts` nor `.tsx`, so the whole SFC — `<template>` markup, `<script>`, and `<style>` — was parsed as JavaScript, producing a top-level ERROR node and recovering no imports, symbols, or type references. A dedicated `extract_vue` now masks everything outside `<script>` (replacing it with spaces so line numbers stay accurate) and parses just the script with the grammar named by `lang` (`ts` default, `tsx`/`js`/`jsx` honored). The open-tag scan tolerates `>` inside quoted attributes, so Vue 3.3+ generic components (`generic="T extends Record<string, unknown>"`) parse correctly.
|
||||
- Fix: `graphify reflect --if-stale` now also checks the `.graphify_analysis.json` and `.graphify_labels.json` sidecars (and any custom `--analysis`/`--labels` paths) when deciding whether `LESSONS.md` is up to date (#1470, thanks @oleksii-tumanov). It previously only stat'd the memory docs and `graph.json`, so lessons could stay stale after community analysis or labels changed without the graph changing. A missing sidecar is treated as not-an-input, so no-cluster builds are unaffected.
|
||||
- Fix: the `Read|Glob` PreToolUse hook (the "run graphify first" nudge installed for Claude Code and CodeBuddy) now matches the file's real trailing extension instead of substring-scanning the path (#1463, thanks @marketechniks). The old check asked `any(ext in path)`, which had two opposite failures: `.json` files (`package.json`, `tsconfig.json`) spuriously fired because `.js` is a substring of `.json`, and `.astro`/`.vue`/`.svelte` never fired because they weren't in the set — so on Astro/Vue/Svelte projects, where those are the primary source type, reads and globs never surfaced the graph. The hook now compares the segment after the last `/` then after the last `.` against the extension set (with `.astro`/`.vue`/`.svelte` added), so `package.json` stays silent, `data.geojson` stays silent, `**/*.astro` fires, and an extension sitting on a directory component (`my.ts/file`) correctly doesn't. The `graphify-out/` suppression and fail-open behavior are unchanged.
|
||||
- Fix: make it unambiguous in the skill that graphify needs no API key, so terminal-style hosts stop looping on a missing one (#1461). Hermes (and the other AGENTS.md hosts: Codex, Aider, OpenClaw, Droid, Trae, …) run the `graphify` CLI directly and don't dispatch subagents, but the Step 3 extraction guidance framed the no-key path only as "fall through to subagent dispatch" — so on `/graphify .` those agents would spin for minutes insisting they needed an API key before eventually proceeding. Step 3 now opens with an explicit, hoisted "graphify needs no API key — never ask the user for one, never block on one" statement (code is AST-only; a code-only corpus skips semantic extraction entirely), and the fallback now spells out a non-subagent path for terminal hosts instead of assuming subagent dispatch. Applied across every generated skill body, including the aider/devin monoliths, with a regression test that pins the wording in place.
|
||||
- Feat: extract WPF/XAML structure from `.xaml` files (#1460, thanks @MikeKatsoulakis). No new parser dependency (stdlib XML, with the same DOCTYPE/ENTITY and size guards as the `.csproj` extractor). Captures the root element, named controls (`x:Name`/`Name`) and their control types, `{Binding ...}` references, and `x:Class`, and bridges the view to its `.xaml.cs` code-behind by resolving event-handler attributes to the matching methods on the partial class. Event resolution is gated on the .NET handler signature `(object sender, …EventArgs e)` and skips free-form attributes (`Content`, `Text`, `Tag`, …), so a property value that merely matches a method name (e.g. `Content="Save"` next to a business method `Save()`) can't fabricate a spurious event edge.
|
||||
- Fix: `to_canvas` (Obsidian Canvas export) now lays out each community's node cards in the same `ceil(sqrt(n))`-column grid the group box is sized for. The box width assumed a roughly-square `sqrt(n)`-column layout, but the placement loop hardcoded 3 columns, so any community larger than ~9 members rendered as a cramped 3-wide strip in an over-wide, mostly-empty box. The column count is now computed once per community and reused for the box width, box height, and card placement, so the cards fill the box. Cosmetic, no data change (#1452, thanks @TPAteeq).
|
||||
- Fix: `to_obsidian` / `to_canvas` / `to_wiki` no longer silently overwrite notes whose labels differ only by case (e.g. a class `References` and a prose heading `references`). The filename dedup was keyed on the exact-case name, so two such labels counted as non-colliding and the second write clobbered the first on case-insensitive filesystems (macOS/APFS, Windows/NTFS) — no suffix, no warning. Dedup now folds case (keyed on the lowercased name) while still emitting the original-case filename, so any pair that would collide on disk gets a numeric suffix. The obsidian/canvas dedup is shared in one helper so they can't drift, `wiki`'s slug dedup gets the matching fix, the `_COMMUNITY_*.md` overview notes (which had no dedup) are covered, and a generated `base_1` is itself re-checked so it can't overwrite a node literally labelled `base_1` (#1453, thanks @TPAteeq).
|
||||
- Feat: the `kimi`, `gemini`, and `deepseek` semantic-extraction backends now honor `KIMI_BASE_URL`, `GEMINI_BASE_URL`, and `DEEPSEEK_BASE_URL` to point at any OpenAI-compatible endpoint (a proxy, gateway, or self-hosted relay), matching the existing `OLLAMA_BASE_URL` / `OPENAI_BASE_URL` overrides. Each falls back to its hardcoded official default when the variable is unset, so behavior is unchanged for everyone who doesn't set it (#1458, thanks @jc2shile).
|
||||
- Fix: `to_wiki` (Wikipedia-style wiki export) now emits portable relative markdown links instead of Obsidian `[[wikilinks]]`, so navigation works in every renderer — VS Code preview, GitHub, GitLab, a plain browser — not just Obsidian. Two defects: (1) `[[Title]]` resolves by note title only inside Obsidian; everywhere else `[[Domain Data Models]]` points at a literal `Domain Data Models.md`, but the article file is `Domain_Data_Models.md` (the slug substitutes spaces and reserved characters), so nearly every community/god-node navigation link opened an empty page. (2) God-node articles linked every neighbor (`[[AwsHelper.py]]`, `[[.read_object_key()]]`), but only communities and god nodes get article files, so those node-level links were dead even inside Obsidian. Links are now standard `[display](slug.md)` with the target URL-encoded, so spaces, `&`, parentheses, and `#` survive intact in CommonMark renderers and Obsidian alike; any link whose target has no article is downgraded to plain text instead of left dangling. Each article's slug is computed up front (a `label -> slug` resolver built before any body is rendered) so a link to a community or god-node article points at the real on-disk filename, including the case-fold collision suffix (`parser_2.md`). Cosmetic, no graph/data change (#1444, thanks @restagner).
|
||||
|
||||
## 0.8.49 (2026-06-24)
|
||||
|
||||
- Fix: the `get_community` MCP tool now shows the community name in its header (`Community 12 — Auth & Sessions (8 nodes)`), matching `get_node` and the query-traversal output, which already read the `community_name` attribute `to_json` writes onto every node. `get_community` was the only graph tool still returning a bare numeric id. The name is read from the community's member nodes (they share it), sanitised like every other LLM-derived field, and skipped when it is just the `Community N` placeholder so the header never doubles to `Community 12 — Community 12` (#1448, thanks @rmart1308).
|
||||
- Security: floor `starlette` at `>=1.3.1` to pick up the fixes for CVE-2026-48818 and CVE-2026-54283 (both resolved by 1.3.1). starlette underpins the HTTP MCP transport (`graphify-mcp` over HTTP / `serve_http`); the stdio transport and CLI are unaffected. It was an undeclared transitive dependency (via `mcp`) that `graphify/serve.py` imports directly, so it is now declared in the `mcp` (and `all`) extras and floored, which protects end users installing `graphifyy[mcp]`, not just the locked dev/CI environment. Lockfile bumped 1.0.0 -> 1.3.1; serve/MCP/HTTP tests pass on the new version (#1391, #1396, thanks @orbisai0security).
|
||||
- Refactor: begin splitting the monolithic `extract.py` into per-language modules under `graphify/extractors/` (#1212). The `blade`, `elixir`, `razor`, and `zig` extractors plus the shared primitives (`_make_id`, `_file_stem`, `_read_text`, `_LANGUAGE_BUILTIN_GLOBALS`) move into their own files, with `graphify/extractors/base.py` holding the shared pieces and a strict one-way import direction (`extract.py` -> `extractors/`, never the reverse). `extract.py` re-exports the moved names, so every `from graphify.extract import ...` caller and the dispatch table are unchanged. Behavior-neutral lift-and-shift (verified byte-identical), groundwork for moving the remaining languages out. See `graphify/extractors/MIGRATION.md`.
|
||||
- Feat: community labeling can now run in parallel (#1390). `graphify cluster-only` and `graphify label` accept `--max-concurrency N` (default 4) to fan labeling batches out across a thread pool, and `--batch-size N` (default 100) to tune communities per LLM call. A large graph that previously needed hundreds of sequential calls now runs them in rounds. Mirrors the existing `extract` parallelism, including the safety guards: `ollama` and `claude-cli` are forced serial (set `GRAPHIFY_OLLAMA_PARALLEL=1` / `GRAPHIFY_CLAUDE_CLI_PARALLEL=1` to override). Output is unchanged and deterministic regardless of concurrency, since results are keyed by community id and merged on the main thread.
|
||||
- Fix: `graphify reflect` no longer duplicates lines in the "known dead ends" and "corrections" sections when the same Q&A is saved more than once. Those lists were appended per memory doc with no key (node scoring already dedups by node, but these two did not); they now collapse by question, keeping the most recent entry — so a re-corrected question shows its latest correction. Output stays deterministic (ordered by date then question).
|
||||
- Fix: the work-memory loop no longer depends on the git hook. The skill now tells the agent to run `graphify reflect --if-stale` itself at the start of graph work (cheap, deterministic, a no-op when no outcomes have been saved), then read `LESSONS.md`. Previously a skill-only install (without `graphify hook install`) would keep recording outcomes via `save-result` but never regenerate `LESSONS.md`, so the lessons never surfaced. The post-commit hook is now an optimization for between-session freshness rather than a requirement. The new `--if-stale` flag skips the run when `LESSONS.md` is already newer than every input (the memory docs and the graph), so when the hook just refreshed it the agent's session-start run costs almost nothing.
|
||||
|
||||
## 0.8.47 (2026-06-24)
|
||||
|
||||
- Feat: the work-memory loop is now zero-config for agents (#1441). The skill's query reference instructs the agent to read `graphify-out/reflections/LESSONS.md` at the start of graph work (start from preferred sources, skip known dead ends) and to record an `--outcome useful|dead_end|corrected` on `save-result`; the git post-commit/post-checkout hooks now auto-run `reflect` after each rebuild — best-effort and only when saved outcomes exist — so `LESSONS.md` stays current without a manual `graphify reflect`.
|
||||
- Feat: a first deterministic slice of self-improving "work memory" (#1441). `graphify save-result` gains optional `--outcome useful|dead_end|corrected` and `--correction TEXT` flags that record how a saved Q&A turned out — written to the memory doc's frontmatter and an `## Outcome` body section so the signal both stays machine-readable and round-trips into the graph on the next semantic re-extraction. A new `graphify reflect` command then scans `graphify-out/memory/` and writes a deterministic `graphify-out/reflections/LESSONS.md` an agent can load at the start of the next session — grouped by community when a `graph.json` is present, flat otherwise. Source nodes are scored, not counted: each citation is a signed, time-decayed value (`useful` positive, `dead_end`/`corrected` negative, configurable half-life via `--half-life-days`, default 30), so a fresh dead end outweighs a months-old useful. A node is only promoted to "preferred" once corroborated by ≥`--min-corroboration` distinct results (default 2) — one save can't mint a trusted lesson; the rest render as "tentative", and nodes with both positive and negative signals render once as "contested" with a recency-wins verdict. Source nodes are matched to the graph by label or id, and citations whose node no longer exists are dropped so stale lessons don't linger. Deterministic, no LLM; bare `graphify save-result` and all existing behavior are unchanged.
|
||||
- Fix: `graphify update` now prunes a function/symbol removed from a still-present file without needing `--force`. The build already dropped the stale node (#1116), but the shrink-guard then refused to write the smaller graph ("new graph has N nodes but existing has M … Refusing to overwrite"), so the deletion silently never persisted unless you passed `--force` — leaving stale nodes (and the work-memory node-existence gate) lagging until a forced rebuild. The guard is now file-aware: a net shrink is allowed when every lost node belongs to a file re-extracted this run (or deleted), and still refused when a node disappears from a file that was *not* touched (the failed/partial-extraction case it exists to catch).
|
||||
- Fix: `validate_extraction` and `build_from_json` no longer crash on a non-hashable node `id` or edge `source`/`target` (e.g. a list emitted by a malformed LLM extraction) — previously a single bad node raised `TypeError: unhashable type` and aborted the entire build of an otherwise-complete corpus. The validator now reports the bad id/endpoint as an error string (its documented contract), and the build skips the malformed entry with a stderr warning while keeping every well-formed node/edge; non-dict nodes are still left to raise so shape diagnostics are unchanged (#1447, thanks @dschwartzi).
|
||||
- Fix: Python qualified class-method calls (`ClassName.method(...)`) now produce an EXTRACTED `calls` edge to the class-qualified method node (#1446). Previously these cross-class static/qualified calls were dropped: the shared cross-file pass skips all member calls (the #543/#1219 god-node guard against bare `obj.method()` collisions), and when the called method shared its name with an in-file node — e.g. a viewset action `approve()` delegating to a service `Service.approve()` — the bare-name lookup matched the caller's own node and silently dropped it. The Python extractor now captures a simple-identifier receiver, defers capitalized-receiver member calls to a new receiver-based resolver (`_resolve_python_member_calls`, mirroring the Swift pass), and emits the edge only when the receiver resolves to exactly one class that owns the method (single-definition god-node guard); instance/module calls (`self.x()`, `obj.x()`, lowercase receivers) are unaffected.
|
||||
- Feat: new first-class `agents` platform installs the skill to the generic cross-framework Agent-Skills locations. `graphify install --platform agents` (alias `--platform skills`) writes the spec's user-global `~/.agents/skills/graphify/SKILL.md` — the directory `npx skills` and spec-compliant frameworks read — and `--project` writes `./.agents/skills/graphify/SKILL.md`; `graphify uninstall` removes them. Previously that user-global location was only reachable as an accidental side effect of the gemini-on-Windows branch. The skill bundle re-homes amp's agents-md body (registered in `tools/skillgen/platforms.toml`, rendered through the skillgen drift/coverage guards); the body is identical to amp's, and only the on-demand hooks reference differs — it points at `graphify agents install`, which (as the amp-twin subcommand) wires the skill plus an AGENTS.md always-on section. Bare `graphify install` is unchanged — still single-platform (claude/windows) (#1432, closes #1405).
|
||||
|
||||
## 0.8.46 (2026-06-23)
|
||||
|
||||
- Perf: graph queries on large graphs are faster via a trigram candidate prefilter in the MCP/CLI query path. A trigram→node index (built once per graph and rebuilt on hot-reload) narrows the candidate set before the IDF-weighted scorer runs, cutting the previous O(N) scan. The prefilter is a strict superset of the exhaustive scorer (it indexes `norm_label`, `label_tokens`, `nid`, and `source_file`), so results and ranking are unchanged; short/CJK queries and low-selectivity terms fall back to the full scan (#1431; thanks @papinto).
|
||||
- Feat: the skill runbook adds a Step 4.5 graph-health gate that runs `diagnose_extraction` and surfaces dangling/self-loop/collapsed-edge warnings before labeling, and anchors the semantic cache on the scan root (`root='INPUT_PATH'`) so cache hits survive a non-cwd scan. Read-only — never aborts the build (#1437; thanks @bahcgscateringsa-design).
|
||||
- Fix: `graphify install --platform hermes` now installs to the right directory on Windows. Hermes scans `%LOCALAPPDATA%\hermes\skills`, but the installer always used the POSIX `~/.hermes/skills` (so on Windows the skill was never discovered). `_platform_skill_destination` gained a hermes branch that targets `%LOCALAPPDATA%\hermes\skills` on Windows and keeps `~/.hermes/skills` elsewhere (#1403).
|
||||
- Fix: cross-file type-annotation references no longer create phantom duplicate nodes. A class defined once but referenced via type annotations in N other files (`def f(x: Thing) -> Thing`) produced 1+N nodes — the extra ones with the referencing file's path baked into the id (`pkg_a_py_thing`). `ensure_named_node` minted a *sourced* stub for these cross-file refs, which `_disambiguate_colliding_node_ids` then collided into per-file ids and `_rewire_unique_stub_nodes` refused to collapse. The fallback now emits a *sourceless* stub (like the inheritance-base path), so the references resolve to the single canonical definition. Fixed uniformly across all six language extractors that share the helper (#1402).
|
||||
- Feat: CUDA (`.cu`/`.cuh`) source files are now extracted. CUDA is a C++ superset, so these files route through the existing C++ (`tree-sitter-cpp`) extractor — no new grammar dependency. `__global__`/`__device__` kernels, host functions, structs and `#include`s are captured, host call edges are inferred, and `<<<grid, block>>>` kernel-launch syntax parses without error. Detection and file-watching follow automatically since both derive their extension sets from the dispatch table / `CODE_EXTENSIONS` (#1411).
|
||||
- Fix: `to_obsidian` / `to_canvas` no longer emit punctuation-only filenames (e.g. `@.md` from a `@/*` tsconfig `paths` key). Such a file is valid on disk but empty once a downstream tool re-slugs on word characters (it crashes `qmd update`), so an all-punctuation label now falls back to `unnamed` (#1409; thanks @Mylock51).
|
||||
- Fix: the opencode plugin's search reminder no longer contains backticks. The hook prepends the reminder inside a double-quoted `echo`, where bash performed command substitution on the backticks — silently running `graphify query "<question>"` on every search. The reminder is now plain text (#1413; thanks @WSHAPER).
|
||||
- Fix: `graphify extract --cargo` exits with a clear error instead of a traceback when `Cargo.toml` is missing or unreadable (the introspection now also catches `OSError`) (#1428; thanks @DhruvTilva).
|
||||
- Chore: resolve an `F821` (undefined `nx`) flagged in `prs.py` by importing `networkx` under `TYPE_CHECKING` for the quoted type annotation (#1429; thanks @DhruvTilva).
|
||||
|
||||
## 0.8.45 (2026-06-22)
|
||||
|
||||
- Fix: native-backend semantic extraction now produces hyperedges. The `graphify extract --backend <gemini|claude|claude-cli|openai|kimi|…>` prompt (`llm._EXTRACTION_SYSTEM`) only ever showed `"hyperedges":[]` in its output schema and never explained what a hyperedge is, so every native backend silently emitted zero — while the agent/skill path (whose `extraction-spec.md` fully documents hyperedges) produced them. The two prompts had drifted. The native prompt now carries the same "3 or more nodes participate together" instruction and a populated schema example, so both extraction paths yield the same hyperedge behaviour for a given corpus. Verified end-to-end: a doc that previously produced 0 hyperedges now produces one (correctly relativized, per #1418). Guard tests assert the two prompts can't drift apart again.
|
||||
- Fix: `GRAPHIFY_OUT` is now honoured end-to-end. The override (a custom output-dir name or absolute path, for worktrees/shared setups — #686) was only respected by some readers; `graphify extract` and several commands hardcoded `graphify-out/`, so a `GRAPHIFY_OUT=custom-out graphify extract` still wrote to `graphify-out/`, and downstream `query`/`serve`/`update` looked in the wrong place. The output-dir name is now resolved through `graphify.paths` everywhere it matters: the `extract` write dir, `cluster-only`/`label`, `query`/`affected`/`benchmark` defaults, `save-result --memory-dir`, `uninstall --purge`, `cache-check`, the `manifest.json`/`transcripts`/`memory`/`converted` paths in `detect`/`transcribe`, the `build_merge`/`serve`/`benchmark`/`prs` graph-path defaults, and the `detect` scan-exclude (so a renamed output dir is never re-ingested as source). Default behaviour is unchanged — without the env var everything still uses `graphify-out/` (#1423).
|
||||
- Fix: the `GRAPH_REPORT.md` header now shows the actual scan root instead of a literal `.`. The split-skill runbook passed `'.'` as the `root` argument to `report.generate` in Steps 4 and 5, so a `/graphify /some/path` run produced a report titled `# Graph Report - .`. It now passes `'INPUT_PATH'` (matching the monoliths, which were already correct). Display-only — no path written to `graph.json`/`manifest.json` was affected (#1419).
|
||||
- Fix: the skill runbooks now write a portable `manifest.json`. Step 9 (full build) and the `--update` reference called `save_manifest(...)` without `root=`, so manifest keys were stored as absolute paths; cloning or moving the repo then broke `graphify --update` — every cached file missed and the whole corpus re-extracted. All four runbook call sites (the lean-core `skill.md`, the Aider/Devin monoliths, and the shared `--update` reference) now pass `root='INPUT_PATH'`, relativizing keys to the scan root to match the native `graphify update` path. The monolith change is registered as a new sanctioned change-class in the round-trip guard (#1417).
|
||||
- Fix: hyperedge `source_file` is now relativized to the scan root like nodes and edges. `build_from_json(root=...)` relativized `source_file` on `nodes[]` and `links[]`, but stored `graph.hyperedges[]` verbatim, so a semantic subagent's absolute path (e.g. `/Users/.../CLAUDE.md`) leaked into `graph.json`. The fix lives in `build_from_json` (not `to_json`, which has no `root` to relativize against) and mirrors the existing node/edge handling (#1418).
|
||||
- Fix: the `GRAPHIFY_OUT` override is now honoured everywhere instead of a hardcoded `"graphify-out"` literal. The name is consolidated into a single `graphify.paths` module (was duplicated across `__main__`, `cache`, and `watch`); `security.validate_graph_path`'s `base=None` discovery + fallback, `callflow_html`'s project-root resolution, and the post-commit/post-checkout hook bodies (which now read the env var at hook-run time) all use it. Previously a renamed output dir validated against the wrong base or made the hook miss `.graphify_root` (#1423).
|
||||
- Fix: the Aider and Devin monolith skills now carry the #1392 runbook fixes that the split skill got in 0.8.44. These single-file skills are hand-maintained and frozen against a pinned pristine-v8 blob by a round-trip guard, so they had been excluded. The guard is now a multiset diff that classifies every added/removed line against documented sanctioned change-classes (rather than a positional zip that forbade any line-count change), which lets the multi-line fixes land while still failing on any unsanctioned drift. Both monoliths now propagate `directed=IS_DIRECTED` into every `build_from_json` call (a `--directed` run no longer collapses reciprocal edges), scope semantic extraction to document/paper/image (code is covered by the AST pass), delete `.graphify_cached.json` on a cache miss, and run Step 4's zero-node guard before any write with the report/analysis gated on `to_json` actually persisting the graph (#1392).
|
||||
|
||||
## 0.8.44 (2026-06-19)
|
||||
|
||||
- Fix: generated Claude/agent skill, crash & data-loss bugs in the runbooks (#1392). (1) Semantic chunk files were written under the **scanned dir** (`.graphify_root`) but the merge globs **cwd** `graphify-out/`, so a non-cwd scan produced "no nodes"; chunk paths are now derived from cwd. (2) Code-only corpora skipped Part B but Part C reads `.graphify_semantic.json` unconditionally, raising `FileNotFoundError`; the fast path now writes an empty semantic file first. (3) `--cluster-only` told the agent to re-run Steps 5-9, which read intermediate files a prior cleanup deleted (`FileNotFoundError`); it now relies on the self-contained `graphify cluster-only` CLI. (4) Step 4's zero-node guard ran *after* `GRAPH_REPORT.md`/`graph.json`/analysis were written, and `GRAPH_REPORT.md` was written before `to_json`'s #479 shrink-guard; the guard now runs before any write and the report/analysis are written only when `to_json` actually persisted the graph.
|
||||
- Fix: generated Claude/agent skill, remaining correctness bugs in the runbooks (#1392). `--directed` is now propagated as `directed=IS_DIRECTED` into `build_from_json` (Step 4 + Step 5 rebuild) and `build_merge` (the `--update` merge + diff), so a `--directed` (and `--directed --update`) run no longer silently rebuilds undirected and collapses reciprocal A<->B edges. Semantic extraction flattens only `document`/`paper`/`image` (code is already covered structurally by the AST pass) so subagents stop re-reading every source file. `.graphify_cached.json` is deleted on a cache miss so Part C never merges a stale cache from a prior run. `--update` now transcribes changed video files and moves the transcripts into documents before the semantic pipeline. Transcription writes via `write_text` (no shell redirect), honours `GRAPHIFY_WHISPER_MODEL`/`GRAPHIFY_WHISPER_PROMPT`, and prints status to stderr. `add-watch` and `exports` use the resolved interpreter explicitly, and the MCP Desktop config documents the absolute interpreter path. Extraction-spec example id is namespaced; query term split keeps tokens of 3+ chars.
|
||||
- Fix: the semantic extract entry points no longer crash on `FileSlice` units. The 0.8.43 `#1386` fix coerced every item with `[Path(f) for f in files]`, which raised `TypeError` on the `FileSlice` objects produced by the oversized-text slicing path (#1369), so a corpus containing a document large enough to be sliced crashed on extract. Items are now coerced only when they are not already a `Path` or `FileSlice` (#1397, #1399).
|
||||
|
||||
## 0.8.43 (2026-06-19)
|
||||
|
||||
- Feat: package manifests are now parsed deterministically into a dependency graph. `apm.yml`, `pyproject.toml`, `go.mod`, and `pom.xml` each yield ONE canonical package node per package (keyed by name) plus `depends_on` edges, routed to the AST path so the LLM never sees them. Previously `apm.yml` was an LLM-handled document, so the same package got a different file-anchored id from its own manifest than from each dependent's dependency reference and split into duplicate nodes; a package referenced from N manifests is now a single hub node (#1377).
|
||||
- Feat: markdown links now become graph edges. `extract_markdown` only emitted heading nodes + `contains` edges and never parsed link syntax, so a doc full of `[text](./other.md)` links (e.g. `index.md`, `table-of-contents.md`) had no edges to what it links and never became a hub. Inline links, reference-style links, and `[[wikilinks]]` are resolved relative to the source file (external URLs / in-page anchors / images skipped) and emitted as `references` edges, with targets resolved via the same node-id recipe so they merge onto the real doc node (#1376).
|
||||
- Security: bumped vulnerable dependencies to patched versions — `pypdf` 6.11.0→6.13.3 (CVE-2026-48155/48156), `yt-dlp` 2026.3.17→2026.6.9, `pyjwt` 2.12.1→2.13.0, `cryptography` 48.0.0→49.0.0, `python-multipart` 0.0.28→0.0.32 — with lower-bound floors for the direct deps (`pypdf`, `yt-dlp`) so installs get the patched versions (#1375; thanks @hypnwtykvmpr).
|
||||
- Fix: the semantic extract entry points (`extract_corpus_parallel`, `extract_files_direct`) crashed with `AttributeError` when passed `str` paths instead of `pathlib.Path`. Both now coerce `files = [Path(f) for f in files]` at entry (#1386).
|
||||
- Fix: community labeling now recovers from a malformed-JSON batch by splitting it at the midpoint and retrying each half (mirroring the extract path), instead of logging-and-skipping it — which silently lost ~100 community names per failed batch on large graphs (#1280, #1278; thanks @CJdev232).
|
||||
- Fix: `graphify hook install` no longer creates a literal backslash-named junk directory and reports false success when `core.hooksPath` (or `git rev-parse --git-path hooks`) is a Windows-style path under WSL. Drive-letter / embedded-backslash hooks paths are now rejected with a clear error (#1385).
|
||||
- Refactor: node-ID normalization is unified into a single `graphify.ids` module. `extract._make_id`, `build._normalize_id`, `mcp_ingest._make_id`, and `symbol_resolution._bash_make_id` were four hand-synced copies of the same NFKC/casefold recipe — the root of the recurring ghost-node bug class (#811/#550/#1033/#1104). All four now delegate to one implementation guarded by contract + hypothesis property tests (#1378; thanks @danielnguyenfinhub).
|
||||
|
||||
## 0.8.42 (2026-06-18)
|
||||
|
||||
- Fix: large text documents are no longer silently truncated during semantic extraction. `_read_files` capped every file at 20,000 characters, so a Markdown/text/rST document longer than that had everything past the cap dropped — the model never saw it, and the packer/adaptive-retry path couldn't recover ("packing can't shrink one big file"). Oversized splittable-text files are now sliced at heading/paragraph boundaries into units that each fit the cap and together cover the whole file; every slice reports its parent file as `source_file`, so the graph is not fragmented per-slice. A single slice that still overflows the model's output is bisected and retried. Code files and PDFs are never sliced (they keep whole-symbol / page handling). (#1369)
|
||||
- Fix: `/graphify --update` no longer deletes a changed file's freshly re-extracted nodes. The `0.8.41` `root=` fix (#1361) made `build_merge`'s prune actually match relative `source_file` values — which then matched the just-re-extracted nodes of *changed* files (still listed in `prune_sources`) and removed them, so an `--update` on a changed file could wipe its nodes. The update runbook now prunes only genuinely **deleted** files; changed files are reconciled by `build_merge`'s replace-on-re-extract (#1344). The full build also now passes `root=` to `build_from_json`, and the extraction-spec `source_file` is pinned to the verbatim path, so the full build and incremental updates never drift on node-key base. (#1366; thanks @RelywOo)
|
||||
- Fix: Java `record` declarations are now modeled as first-class type nodes (they share `class_declaration`'s name/body/interfaces fields), and `new Foo(...)` constructor calls now produce a `calls` edge to the constructed type. Previously a record appeared only as its file node (degree 0) with no incoming edges, and body-level `new` usages were dropped because `object_creation_expression` wasn't a recognized call type and its callee lives in the `type` field rather than `name`. (#1373)
|
||||
- Security fix: `.graphifyignore` and `.gitignore` are now **merged** per directory instead of `.graphifyignore` silently replacing that directory's `.gitignore`. Previously, adding a `.graphifyignore` (e.g. to exclude media) disabled the dir's `.gitignore` entirely, so a file excluded only by `.gitignore` — including neutrally-named secrets like `prod-dump.sql` or `customer-data.json` that the sensitive-file heuristic doesn't catch — got indexed into the graph, whose artifacts embed file contents and are routinely committed. `.gitignore` is read first and `.graphifyignore` last, so `.graphifyignore` patterns (including `!` negations) still win on conflict; adding one can only ever exclude more, never re-include a `.gitignore`-excluded file. (#1363)
|
||||
|
||||
## 0.8.41 (2026-06-17)
|
||||
|
||||
- Fix: OpenAI-compatible backends (`ollama`, `openai`, `deepseek`, `kimi`) now honour their configured `16384` output-token cap instead of silently falling back to `8192`. The dispatch read a `max_completion_tokens` config key that only `gemini` defines; the others set `max_tokens`, so their advertised cap was dead and deep-mode JSON truncated mid-string (recovered by the adaptive bisect, but noisy and slower). The dispatch now reads either key, and the `openai` config gained an explicit cap. `GRAPHIFY_MAX_OUTPUT_TOKENS` still overrides. (#1365)
|
||||
- Fix: fuzzy dedup no longer over-merges distinct nodes in three cases. (1) Numbered/versioned siblings whose embedded digit runs differ as zero-padding-insensitive multisets (`ADR 0011` vs `ADR 0013`, `3.1 Product Goals` vs `1.1 Product Goals`, `40%+ …` vs `<20% …`) never merge. (2) `rationale`/`document` nodes are file-anchored like code (#1205's reasoning): near-identical docstring/heading boilerplate in parallel files no longer collapses across files, while same-file duplicates still merge. (3) Cross-file labels that share a long prefix but diverge in a distinguishing token (`testing-library jest-native` vs `react-native`) are scored on plain Jaro instead of Jaro-Winkler, so the leading-prefix bonus can no longer fabricate a merge; genuine cross-file duplicates still clear the bar on Jaro alone, and same-file near-duplicates keep Jaro-Winkler. Guards are mirrored into the `--dedup-llm` ambiguous-pair collection. (#1284 thanks @van4oza, #1243)
|
||||
- Fix: Swift cross-file class relationships expressed through member calls and constructors now resolve to the receiver's real definition. A per-file type table (built from property/parameter declarations and constructor inference) types the receiver of `recv.method()` / `Type.staticMethod()` / `Singleton.shared.method()` / `self.prop.method()`, and property/field initializers (`let vm = VM()`) are now walked for constructor calls. Edges are emitted only when the receiver's type resolves to exactly one definition (preserving the #543/#1219 god-node guards) and are tagged `INFERRED`; the blanket member-call skip in the shared call pass is untouched (#1356).
|
||||
- Fix: `/graphify <path> --update` now prunes stale nodes correctly. The update runbook called `build_merge(prune_sources=...)` without `root=`, so the absolute prune paths were never relativized to match the graph's relative `source_file` values — nothing was pruned and changed/deleted files left ghost nodes that compounded on every incremental run. The shared skill fragment now passes `root` (the native `graphify update` CLI was already correct) (#1361).
|
||||
- Fix: `export obsidian` no longer writes an empty 32-byte `graph.canvas` on a populated graph. `to_canvas` built cards solely by iterating communities, so a graph with no community data (`--no-cluster` builds, or a missing analysis sidecar) produced the empty `{"nodes": [], "edges": []}` shell while the markdown notes rendered fine. It now falls back to one synthetic community covering every node (#1324).
|
||||
- Fix: edges missing a `source_file` field (occasionally emitted by the semantic/LLM extractor, which `build` only normalized when the field was already present) are now backfilled from the edge's endpoint nodes in `build_from_json` and the `--no-cluster` raw-write path, so they no longer reach `graph.json` without a file reference or trip validation (#1279).
|
||||
- Fix: every platform's query skill now ships **both** the vocab/IDF query-expansion step and the inline NetworkX fallback. Previously the two capabilities were split across `cli.md` / `cli-inline.md` so no platform got both — Claude had the superior expansion but no CLI-down fallback, while all other platforms had the fallback but the weaker raw-question matcher. The two fragments are merged into one unified `query` reference (and stub) shipped to all hosts; the `query_variant` enum and its coverage-audit exemption are removed (#1325; thanks @LeanderBlume).
|
||||
- Fix: cross-file Java `implements`/`inherits`/`imports` edges no longer orphan onto bare "shadow" nodes when two packages define a same-named type. The referencing file's `import` statement now disambiguates by exact package (FQN) and re-points the edge to the real definition, dropping the orphan stub. Previously `_rewire_unique_stub_nodes` could only repair the globally-unique case, so same-named interfaces (common in large Java codebases — `Handler`, `Service`, interface+impl pairs) left the real definition isolated in its own community (#1318).
|
||||
- Fix: Swift imports of the same module from multiple files now collapse to a single shared `type=module` node instead of N path-qualified duplicates. The import target is tagged `type=module` and exempted from id-disambiguation, so reverse traversal ("what imports CoreKit?") works; the `--no-cluster` writer also now dedupes nodes by id (and edges) to match the clustered `build_from_json` path. Builds on the v0.8.40 Swift-import fix (#1327, #1330; thanks @duncan-daydream).
|
||||
|
||||
## 0.8.40 (2026-06-16)
|
||||
|
||||
- Feat: custom OpenAI- and Anthropic-compatible endpoints via `OPENAI_BASE_URL`/`OPENAI_MODEL` and `ANTHROPIC_BASE_URL`/`ANTHROPIC_MODEL`. Point either backend at a self-hosted or proxy server (vLLM, llama.cpp, LM Studio, LiteLLM, gateways); defaults still resolve to `api.openai.com` / `api.anthropic.com`, and `GRAPHIFY_OPENAI_MODEL` keeps precedence over `OPENAI_MODEL`. Wired through both the extraction path (`_call_claude`) and community labeling (#1273).
|
||||
- Feat: PowerShell `.psm1` modules are now indexed. `.psm1` was absent from `CODE_EXTENSIONS` and the extractor dispatch table, so modules — and their dependents — were silently missing from the graph; they parse cleanly with the existing PowerShell grammar (#1315). (`.psd1` manifests and `Import-Module` / dot-source import edges remain a follow-up.)
|
||||
- Fix: Swift `import` edges are no longer silently dropped. `_import_swift` emitted an edge to a bare module id with no backing node, so `build.py` pruned 100% of Swift imports. The target module node is now synthesized (new opt-in `LanguageConfig.synthesize_import_module_nodes`) so the edge survives the build (#1327).
|
||||
- Fix: `--no-cluster` and incremental `graphify update` no longer accumulate duplicate edges. These paths bypass the NetworkX `DiGraph` that collapses parallel edges, so repeated `update` grew the edge count every run and counts diverged across build modes. Edges are now deduped by `(source, target, relation)` before writing — deterministic and idempotent; the no-cluster rebuild log now reports the written (deduped) edge count instead of the raw pre-merge count (#1317).
|
||||
- Perf: `save_manifest` file hashing parallelized with a `ThreadPoolExecutor` (#1295).
|
||||
- Perf: `_walk_js_tree` converted from a recursive generator to an iterative walk, reducing overhead on large JS/TS trees (#1294).
|
||||
|
||||
- Feat: JS/TS AST now extracts function symbols defined via `this.X = () => {}` / `this.X = function(){}` (constructor-assigned methods), `exports.X = fn` / `module.exports.X = fn`, `Foo.prototype.X = fn`, class arrow/function fields (`class C { onClick = (e) => {} }`), and `const f = function(){}` function expressions. Previously only top-level `function` declarations, top-level `const x = () =>` arrows, classes, and method shorthand were captured, so the majority of callable symbols in constructor-style and CommonJS codebases (DAOs, route handlers, services) never became nodes and could not be call-edge endpoints. Arbitrary `obj.x = fn` is deliberately not captured, preserving the #1077 phantom-god-node guard (#1322).
|
||||
- Fix: `graphify query`, `graphify explain`, and MCP `query_graph`/`get_node` now show the human-readable community name (e.g. "FlashAttention Paper") instead of a blank or numeric ID after running `cluster-only`. `to_json` now accepts `community_labels` and embeds `community_name` on each node; read paths fall back to the numeric `community` field for backward compatibility with old graphs (#1305).
|
||||
- Fix: `graphify-mcp` and `python -m graphify.serve` now accept `--graph <path>` as an alias for the positional argument, consistent with every other graphify subcommand. Previously `--graph` raised "unrecognized arguments" (#1304).
|
||||
|
||||
- CI: bandit (MEDIUM+ severity) and pip-audit security scans added as a non-blocking `security-scan` job. Both run with `continue-on-error: true` so they never break CI — advisory signal only, with the intent to remove the gate once pre-existing findings are triaged.
|
||||
- Docs: RFC for file-level node summaries added (`docs/node-summaries-rfc.md`). Proposes inline `graph.json` attribute vs sidecar storage options with pros/cons, phased implementation plan, and open questions for maintainer decision.
|
||||
|
||||
- Fix: AST extraction no longer crashes on Windows machines with >61 logical cores. `ProcessPoolExecutor` on Windows is hard-capped at 61 workers via `WaitForMultipleObjects`; the clamp now applies to all three input paths (auto-compute, `GRAPHIFY_MAX_WORKERS`, `--max-workers`) (#1298).
|
||||
- Fix: ghost-merge skips ambiguous `(basename, label)` collisions where two AST nodes share the same key. When same-named symbols appear in same-named files across different directories (e.g. two `render()` in two `index.ts`), the previous last-writer-wins produced an arbitrary canonical node and mis-pointed all edges. Ambiguous keys are now tracked and skipped (#1257).
|
||||
- Fix: startup no longer crashes on unreadable `.graphify_version` files. On restricted-permission installs or network mounts, `.exists()` / `.read_text()` raised `PermissionError` and crashed every `graphify query/explain/path` call. All three FS probes now wrapped in `try/except OSError: return` (#1299).
|
||||
- Fix: `prs.py` claude-cli backend resolves `claude.cmd` on Windows. The `_call_llm` and `_call_claude_cli` extraction paths were already fixed; `prs.py` had the same bare `["claude", ...]` subprocess call that fails on Windows npm installs with WinError 2 (#1288).
|
||||
|
||||
## 0.8.39 (2026-06-12)
|
||||
|
||||
- Perf: O(n²)→O(n) LSH neighbor lookup in `deduplicate_entities`. The inner scan `next(n for n in candidates if n["id"]==neighbor_id)` was O(n) per neighbor; replaced with a `candidates_by_id` dict built once per pass. Also adds a `norm_cache` to avoid re-normalising labels on every comparison.
|
||||
- Fix: `graphify merge-chunks` summary now prints the node count instead of the raw list object. `global_graph.py` printed `merged['nodes']` (the list) instead of `len(merged['nodes'])`.
|
||||
- Fix: manifest data-loss on corrupt `~/.graphify/manifest.json`. A parse error previously triggered `except Exception: pass`, silently returning an empty manifest and overwriting the file — wiping all tracked repos. The corrupt file is now renamed to a timestamped `.corrupt.<ts>` backup with a stderr warning before starting fresh.
|
||||
- Fix: tree-sitter grammar packages now have pinned upper-bound version ranges in `pyproject.toml`. Grammar packages routinely break node-type and field APIs across minor bumps; ceilings prevent silent breakage on future upgrades.
|
||||
- Feat: FalkorDB export backend. `graphify export falkordb --push redis://localhost:6379` pushes the graph to a FalkorDB instance. Optional dep (`uv tool install "graphifyy[falkordb]"`); lazy import; idempotent (MERGE semantics); Cypher injection guarded.
|
||||
|
||||
- Fix: `affected` and `graphify query` now handle graph files that use `"edges"` as the top-level key instead of `"links"`. Graphs produced by native `graphify extract` on some corpus layouts used `"edges"`; loading them in `affected.py` raised `KeyError: 'links'`. Normalised using the same established pattern already in `__main__.py` and `serve.py`.
|
||||
- Fix: a single `!` negation rule in `.graphifyignore` no longer disables all directory pruning. Previously any negation pattern caused `collect_files` to descend every ignored directory to look for re-included files. Since gitignore semantics cannot rescue files beneath an excluded parent, this descent was always wasted — the per-file filter still excluded them. Pruning now proceeds unconditionally; only the final per-file `_is_ignored` check is consulted for negation.
|
||||
- Feat: `--model` flag added to `graphify label-communities` and `graphify cluster-only`. Routes through `generate_community_labels` → `label_communities` → `_call_llm`; defaults to `None` (keeps existing backend default). Also fixes a latent arg-parsing bug where `--backend gemini` (space-separated) was mis-parsed as the positional path argument.
|
||||
- Docs: Persian (فارسی) README translation added (`docs/translations/README.fa-IR.md`).
|
||||
|
||||
## 0.8.38 (2026-06-11)
|
||||
|
||||
- Fix: LLM-generated `calls` edges now have correct direction. The extraction prompt previously never stated that `source` = caller and `target` = callee; the LLM systematically emitted callee→caller edges. An explicit direction rule was added to the prompt. Separately, ghost-node merge was extended to collapse LLM duplicate nodes (bare-stem IDs) onto AST canonical nodes (parent-qualified IDs) even when the LLM node carries a `source_location` — the old check only caught `source_location=None` ghosts. Post-fix annotation: `calls` precision 100% (n=6), overall INFERRED precision 94% (n=16).
|
||||
- Fix: default imports/exports now produce symbol-level edges. JS/TS symbol resolution only handled named imports, so a `export default class Foo` imported as `import Foo from './foo'` got just a file→file `imports_from` edge — the class node received no incoming symbol edge. On codebases that default-export most classes (NestJS services/helpers/models, etc.) this left those symbols looking like isolated leaf nodes and made `graphify affected "<Class>"` / `explain` report no callers. Default imports are now recorded with `imported_name="default"`, `export default <class|function|identifier>` registers a `"default"` export, and the existing resolver wires the `imports` edge (and resolves calls through the local binding, even when renamed). Anonymous defaults (`export default class {}`) remain file-level only.
|
||||
- Fix: tsconfig `paths` aliases now resolved relative to `baseUrl`. Previously all `@/*` → `src/*` aliases were resolved from the config file's directory regardless of `baseUrl`, breaking path alias import resolution for NestJS, monorepo, and similar layouts that set `baseUrl: "./src"`.
|
||||
- Fix: ghost-merge skips ambiguous `(basename, label)` keys where multiple AST nodes share the same pair. Previously the last-writer-wins pass silently mis-merged one of two same-named symbols in different files (e.g. two `render` functions across separate modules), re-pointing edges to the wrong canonical node.
|
||||
- Fix: `resolve_seed` now matches bare query terms against callable-decorated node labels. A query for `"render"` failed to seed nodes whose label was stored as `".render()"` because the string comparison was exact. Bare names are now tried against stripped labels as a fallback after exact and prefix matches.
|
||||
- Fix: AST cache is now namespaced by graphify version. Stale AST cache entries from a previous release no longer silently produce wrong extraction output after an upgrade — each version writes to its own subdirectory under `graphify-out/cache/ast/<version>/`. Semantic cache is deliberately unversioned (LLM calls are expensive to re-run).
|
||||
- Fix: global-graph edges are now rewired to deduplicated external nodes. When two repos shared an external dependency node (e.g. both reference `requests`), one copy was pruned but edges still pointed to the removed node ID, creating dangling references. Edges are now remapped through the dedup remap table before insertion.
|
||||
- Fix: dedup pass 2 now picks the winner only from the verified `(node, neighbor)` pair. The previous code unioned both normalised-label groups before calling `_pick_winner`, allowing an unrelated same-named node from a different file to be dragged into the merge and supplant the correct winner.
|
||||
- Fix: extraction cache is anchored at the `--out` directory root instead of leaking a `graphify-out/` into the scanned project. Using `graphify extract ./src --out /tmp/out` previously wrote cache files into `./src/graphify-out/cache/` alongside source files. Cache now writes exclusively under the `--out` path.
|
||||
- Fix: `collect_files` rewritten as a single pruned `os.walk` instead of one `rglob` per extension. On large repos this eliminated ~85 redundant filesystem traversals; noise directories (`node_modules`, `.git`, `__pycache__`, etc.) are now pruned before descent, preventing those subtrees from being scanned at all.
|
||||
- Fix: frontmatter delimiter detection now requires a whole `---` line (regex `^---[ \t]*\r?$`). Thematic break lines (`----`) and YAML documents that open with `--- title: foo` were incorrectly parsed as frontmatter delimiters, causing cache hash instability on Markdown files with those constructs.
|
||||
- Fix: `claude-cli` backend now spawns `claude.cmd` on Windows headless installs. `npm`-installed Claude Code ships a `.cmd` shim on Windows; `CreateProcess` cannot run it without the explicit extension. `shutil.which("claude.cmd")` is now tried first on win32, mirroring the fix already applied to the extraction path. `CREATE_NO_WINDOW` flag added to both subprocess spawn sites to prevent console windows flashing during headless runs.
|
||||
- Fix: `claude-cli` backend handles JSON-array envelope from Claude Code CLI ≥ 2.1. Older CLI versions returned a single JSON object; 2.1+ wraps the response in a streaming array of events. The envelope parser now accepts both shapes, preferring the last `{"type":"result"}` event from an array.
|
||||
- Feat: Cargo workspace dependency extraction. `graphify extract ./my-workspace --cargo` introspects `Cargo.toml` files across a Rust workspace and emits `crate:<name>` nodes with `crate_depends_on` edges for workspace-internal dependencies. Registry dependencies are excluded. Handles virtual workspaces, root-package workspaces, glob members, and `{workspace = true}` inherited deps.
|
||||
- Fix: SystemVerilog class-level extraction improved. Classes, interfaces, enums, parameters, and their inheritance/implementation relationships are now extracted correctly from `.sv`/`.svh` files. Dart `with MyMixin` clauses now emit `mixes_in` edges (was incorrectly `implements`), consistent with PHP and Scala.
|
||||
- Docs: README grammar count updated from 28 to 36, reflecting all currently supported tree-sitter language grammars.
|
||||
|
||||
## 0.8.37 (2026-06-10)
|
||||
|
||||
- Security: SSRF guard rewritten to eliminate thread-safety race. The global `socket.getaddrinfo` monkey-patch is replaced with per-connection `_SSRFGuardedHTTPConnection`/`_SSRFGuardedHTTPSConnection` subclasses that resolve DNS once, validate the IP, and connect to that exact address — closing both the concurrent-thread race window and the underlying TOCTOU gap. No global state is mutated, so sibling threads (MCP server, PR triage pool) are unaffected.
|
||||
- Security: Prompt injection mitigation for LLM semantic extraction. Untrusted source file content is now wrapped in `<untrusted_source path="..." sha256="...">` XML delimiters; jailbreak sentinel tokens (`<|im_start|>`, `[INST]`, `<<SYS>>`, forged closing tags) are neutralised with a zero-width space; the extraction system prompt includes an explicit SECURITY block stating that content inside the wrapper is inert data.
|
||||
- Fix: `export obsidian` and `export canvas` no longer crash with `KeyError` when a community contains a node ID absent from the graph (stale community index, merge artifacts). Dangling members are silently skipped.
|
||||
- Fix: `--update` on macOS no longer re-extracts all Office files on every run. `convert_office_file()` now NFC-normalises the source path before hashing the sidecar filename, so NFD paths returned by `os.walk` (HFS+/APFS) produce the same sidecar as NFC-constructed paths. An early-return when the sidecar exists prevents mtime bumps causing spurious re-detection.
|
||||
- Fix: Data `.json` files no longer explode into hundreds of orphan key-nodes. The JSON extractor now only processes config/manifest JSON (detected by filename — `package.json`, `tsconfig.json`, `.eslintrc.json`, `deno.json`, etc. — or by top-level keys such as `dependencies`, `extends`, `$ref`, `compilerOptions`). Data JSON (top-level arrays, generic key/value files) is skipped by the AST pass and left for the LLM semantic pass.
|
||||
- Fix: OpenAI-compatible backends no longer send `temperature=0` to reasoning models. `_resolve_temperature()` auto-detects o1/o3/o4 and gpt-5 series and omits temperature from the request. Override with `GRAPHIFY_LLM_TEMPERATURE=<value>` (or `none` to omit explicitly for any model).
|
||||
- Fix: EDR / corporate Windows hang eliminated. `datasketch` (which transitively imports `scipy` → `numpy.testing` → `platform.machine()` subprocess at import time) is replaced by a self-contained pure-numpy MinHash/MinHashLSH implementation with byte-identical hash math. Removes `datasketch` and `scipy` from the dependency tree.
|
||||
- Perf: `detect()` ignore-pattern checks memoized per scan. Each ancestor directory is now evaluated once across all sibling files, eliminating ~42M redundant `fnmatch` calls on large repos (~34% whole-run speedup on 2k-file corpora).
|
||||
- Fix: `dedup.py` label-based merge passes now skip code nodes entirely. Distinct same-named symbols in different files (e.g. two `Config` classes) were being merged by the exact-label and MinHash/LSH passes. Code nodes are now deduplicated by ID only, which is correct.
|
||||
- Feat: `GRAPHIFY_MAX_GRAPH_BYTES` env var to override the 512 MiB `graph.json` size cap. Accepts plain bytes, `<N>MB`, or `<N>GB`. The cap error message now cites this env var. `graphify export html` auto-falls back to the community-aggregation view when over cap instead of hard-failing.
|
||||
- Feat: `CLAUDE.md` template now uses mandatory language for the graphify-first rule — "MANDATORY: Before using Read/Grep/Glob/Bash to explore the codebase, you MUST run graphify first" — and explicitly requires forwarding the rule to subagent prompts. PreToolUse hook message hardened to match.
|
||||
- CI: Release workflow added. Every GitHub release now ships `graphify-self-graph.tar.gz` as a downloadable asset — `graph.json` + `graph.html` + `GRAPH_REPORT.md` from running Graphify on its own source. Open `graph.html` locally with no install required to see what Graphify produces.
|
||||
|
||||
## 0.8.36 (2026-06-08)
|
||||
|
||||
- Feat: `extra_body` field in `providers.json` forwarded to OpenAI-compat calls at extraction and labeling. Lets vLLM/Qwen3/Llama endpoints pass model-specific request shapes (e.g. `{"chat_template_kwargs": {"enable_thinking": false}}`). Explicit `extra_body` also bypasses Ollama `num_ctx` auto-derive. Thanks to @EirikWolf (#1197).
|
||||
- Feat: `label_communities` multi-batch for 16k-context models. Chunks of 100 communities per call (configurable `batch_size=`); `max_communities` defaults to `None` (label all); partial batch failures no longer drop the whole pass. Thanks to @EirikWolf (#1197).
|
||||
- Feat: `.slnx` Visual Studio solution file support. Extracts `contains` (project references) and `imports` (build dependencies) edges from the modern XML solution format (VS 2022 17.13+). Thanks to @bakgaard (#1189).
|
||||
- Feat: `graphify-mcp` console script. MCP stdio server now directly invocable as `graphify-mcp` from `uv tool install` / `pipx`. Thanks to @jr2804 (#1190).
|
||||
- Fix: `label_communities` token budget raised and `GRAPHIFY_MAX_OUTPUT_TOKENS` now honoured. Hardcoded `min(40+16n, 4096)` undershooted (~16 tok/community); raised to `min(64+24n, 8192)` and wrapped in `_resolve_max_tokens()` (#1200).
|
||||
- Fix: `find_import_cycles` no longer hangs on large graphs. `nx.simple_cycles()` now receives `length_bound=max_cycle_length`, pruning during enumeration rather than post-filtering — drops from never-returns to ~0.1s on dense graphs (#1196).
|
||||
- Fix: fuzzy dedup no longer merges prefix-extension symbol pairs. `getActiveSession`/`getActiveSessions`, `parseConfig`/`parseConfigFile` etc. scored ~98-99 JW and were auto-merged. A prefix-extension guard now prevents merge when one normalised label is a strict prefix of the other, in both Pass 2 and the LLM tiebreaker (#1201).
|
||||
- Fix: `_norm`, `_norm_label`, `_strip_diacritics` guard against `None` node labels, preventing `TypeError` crash on corpora with explicit `null` label fields (#1194). Thanks to @freiit (#1195).
|
||||
- Fix: skill frontmatter `trigger:` field removed from all 14 skill variants — not part of Agent Skills spec, flagged by `agentskills validate` CI (#1180).
|
||||
|
||||
## 0.8.35 (2026-06-07)
|
||||
|
||||
- Feat: CodeBuddy platform support. `graphify codebuddy install` installs the graphify skill to `~/.codebuddy/skills/graphify/SKILL.md`, writes a `CODEBUDDY.md` always-on section, and registers Bash + Read|Glob PreToolUse hooks in `.codebuddy/settings.json` that nudge the agent toward `graphify query` instead of grepping raw files when a graph exists. `graphify install --platform codebuddy` and `graphify codebuddy uninstall` also supported. Thanks to @studyzy (#1136).
|
||||
- Fix: `graphify --update` no longer destructively collapses distinct same-named symbols across files. The skill's `--update` merge now passes re-extracted (changed) files to `prune_sources` alongside deleted files, so old nodes for changed files are pruned before fresh AST is inserted — no fuzzy reconciliation needed. Separately, `dedup.py` Pass 1 now skips nodes with an empty `source_file` so label-only merging across no-source-file nodes is prevented. The anti-shrink guard message now names fuzzy dedup as a possible cause rather than only blaming missing chunk files (#1178).
|
||||
|
||||
## 0.8.34 (2026-06-07)
|
||||
|
||||
- Feat: Streamable HTTP transport for the MCP server. `python -m graphify.serve graph.json --transport http --port 8080 --api-key $SECRET` serves the graph over the MCP Streamable HTTP transport (spec 2025-03-26) so a single shared process can serve the whole team. Flags: `--host`, `--port`, `--api-key` (env `GRAPHIFY_API_KEY`), `--path`, `--json-response`, `--stateless`, `--session-timeout`. Docker image included. stdio remains the default (#1143).
|
||||
@@ -450,7 +22,6 @@ Full release notes with details on each version: [GitHub Releases](https://githu
|
||||
|
||||
## 0.8.33 (2026-06-06)
|
||||
|
||||
- Feat: FalkorDB export backend — sibling to Neo4j, selected via `graphify export falkordb [--push falkordb://localhost:6379]`. FalkorDB is OpenCypher-compatible, so the MERGE/SET upsert queries match the Neo4j path; auth is optional and the target graph defaults to `graphify`. Install with `uv tool install "graphifyy[falkordb]"` (#1175).
|
||||
- Feat: install banner — `graphify install` now prints an amber knowledge-graph brain in the terminal (TTY-only, silent in CI/pipes, never raises).
|
||||
- Fix: Python `from pkg import submod` package-form imports now resolve to a file-level `imports_from` edge to the submodule file when it exists on disk. Previously these imports produced zero edges, leaving test files as disconnected islands in the graph (up to 66% of test nodes in some corpora). The fix lives in the symbol-resolution post-pass which has filesystem access (#1146).
|
||||
- Fix: builtin type-annotation nodes (`str`, `int`, `bool`, `float`, `bytes`, `MagicMock`, `Mock`, `AsyncMock`, etc.) no longer appear as graph nodes or accumulate edges. They were being created via the annotation walker whenever used as parameter or return types, inflating degree counts ~25% and displacing real abstractions from god-node rankings. A new `_PYTHON_ANNOTATION_NOISE` filter suppresses them at extraction time; `god_nodes` also filters them as a defense for pre-existing graphs (#1147).
|
||||
|
||||
@@ -1,54 +1,37 @@
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/logo.png" width="300" height="140" alt="Graphify"/></a>
|
||||
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/25296?utm_source=repository-badge&utm_medium=badge&utm_campaign=badge-repository-25296" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/25296" alt="Graphify-Labs%2Fgraphify | Trendshift" width="250" height="55"/></a>
|
||||
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="docs/translations/README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="docs/translations/README.fil-PH.md">Filipino</a>
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
<details><summary><b>Read this in other languages</b></summary>
|
||||
|
||||
🇺🇸 <a href="README.md">English</a> | 🇨🇳 <a href="docs/translations/README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="docs/translations/README.ja-JP.md">日本語</a> | 🇰🇷 <a href="docs/translations/README.ko-KR.md">한국어</a> | 🇩🇪 <a href="docs/translations/README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="docs/translations/README.fr-FR.md">Français</a> | 🇪🇸 <a href="docs/translations/README.es-ES.md">Español</a> | 🇮🇳 <a href="docs/translations/README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="docs/translations/README.pt-BR.md">Português</a> | 🇷🇺 <a href="docs/translations/README.ru-RU.md">Русский</a> | 🇸🇦 <a href="docs/translations/README.ar-SA.md">العربية</a> | 🇮🇷 <a href="docs/translations/README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="docs/translations/README.it-IT.md">Italiano</a> | 🇵🇱 <a href="docs/translations/README.pl-PL.md">Polski</a> | 🇳🇱 <a href="docs/translations/README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="docs/translations/README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="docs/translations/README.uk-UA.md">Українська</a> | 🇻🇳 <a href="docs/translations/README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="docs/translations/README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="docs/translations/README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="docs/translations/README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="docs/translations/README.ro-RO.md">Română</a> | 🇨🇿 <a href="docs/translations/README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="docs/translations/README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="docs/translations/README.da-DK.md">Dansk</a> | 🇳🇴 <a href="docs/translations/README.no-NO.md">Norsk</a> | 🇭🇺 <a href="docs/translations/README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="docs/translations/README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="docs/translations/README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="docs/translations/README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="docs/translations/README.fil-PH.md">Filipino</a> | 🇮🇱 <a href="docs/translations/README.he-IL.md">עברית</a>
|
||||
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
<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=v8" 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://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" alt="Downloads"/></a>
|
||||
<a href="https://discord.gg/598Ad9zQZ"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://www.linkedin.com/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/>
|
||||
<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>
|
||||
</p>
|
||||
|
||||
Type `/graphify` in your AI coding assistant and it maps your entire project (code, docs, PDFs, images, videos) into a **knowledge graph** you can **query instead of grepping** through files.
|
||||
|
||||
- **Code maps for free, fully local.** Code is parsed with tree-sitter AST: deterministic, no LLM, nothing leaves your machine. (Docs, PDFs, images and video use your assistant's model, or a configured API key, for a semantic pass.)
|
||||
- **Every edge is explained.** Each connection is tagged `EXTRACTED` (explicit in the source) or `INFERRED` (resolved by graphify), so you can tell what was read directly from what was inferred.
|
||||
- **Not a vector index.** No embeddings, no vector store: a real graph you traverse. Ask a question, trace the path between two things, or explain one concept.
|
||||
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graph-hero.png" alt="graphify's interactive graph.html showing the FastAPI codebase as a force-directed knowledge graph with a legend of detected communities" width="900">
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>The FastAPI codebase mapped by graphify. Every node is a concept, colors are detected communities, and the whole thing is clickable in graph.html.</em>
|
||||
<a href="https://star-history.com/#safishamsi/graphify&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**Get started** (30 seconds):
|
||||
Type `/graphify` in your AI coding assistant and it maps your entire project — code, docs, PDFs, images, videos — into a knowledge graph you can query instead of grepping through files.
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy # install the CLI (or: pipx install graphifyy)
|
||||
graphify install # register the skill with your AI assistant
|
||||
```
|
||||
|
||||
Then, in your AI assistant:
|
||||
Works in Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, Devin CLI, and Google Antigravity.
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
That's it. You get **three files**:
|
||||
That's it. You get three files:
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
@@ -57,68 +40,12 @@ graphify-out/
|
||||
└── graph.json the full graph — query it anytime without re-reading your files
|
||||
```
|
||||
|
||||
**Works in** Claude Code, Cursor, Codex, Gemini CLI, GitHub Copilot, and 15+ more — [pick your platform](#install).
|
||||
For a readable architecture page with Mermaid call-flow diagrams, run:
|
||||
|
||||
---
|
||||
|
||||
## See it in action
|
||||
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/demo-path.svg" alt="graphify path query: a terminal asks for the shortest path between FastAPI and ModelField, and the answer lights up hop by hop across the knowledge graph" width="900">
|
||||
</p>
|
||||
|
||||
Once the graph is built you query it instead of reading files. Real output, graphify run on the FastAPI codebase shown above:
|
||||
|
||||
```text
|
||||
$ graphify explain "APIRouter"
|
||||
Node: APIRouter
|
||||
Source: routing.py L2210
|
||||
Community: 2
|
||||
Degree: 47
|
||||
|
||||
Connections (47):
|
||||
--> RequestValidationError [uses] [INFERRED]
|
||||
--> Dependant [uses] [INFERRED]
|
||||
--> .get() [method] [EXTRACTED]
|
||||
<-- __init__.py [imports] [EXTRACTED]
|
||||
...
|
||||
|
||||
$ graphify path "FastAPI" "ModelField"
|
||||
Shortest path (3 hops):
|
||||
FastAPI --uses--> DefaultPlaceholder <--references-- get_request_handler() --references--> ModelField
|
||||
```bash
|
||||
graphify export callflow-html
|
||||
```
|
||||
|
||||
Every edge carries a **confidence tag** (`EXTRACTED` = explicit in the source, `INFERRED` = derived by resolution), so you can tell what was read directly from what was inferred. `graphify query "<question>"` returns a scoped subgraph for a plain-language question, and `graphify path A B` traces how any two things connect.
|
||||
|
||||
---
|
||||
|
||||
## What it does
|
||||
|
||||
What you get out of the box:
|
||||
|
||||
| Capability | What you get |
|
||||
|---|---|
|
||||
| **God nodes** | The most-connected concepts, so you see what everything flows through |
|
||||
| **Communities** | The graph split into subsystems (Leiden), with LLM-free labels |
|
||||
| **Cross-file links** | `calls` / `imports` / `inherits` / `mixes_in` resolved across ~40 languages via tree-sitter AST |
|
||||
| **Query, path, explain** | Ask a question, trace the path between two things, or explain one concept, all against `graph.json` |
|
||||
| **Rationale + doc refs** | `# NOTE:` / `# WHY:` comments and ADR/RFC citations become first-class nodes linked to the code |
|
||||
| **Beyond code** | Docs, PDFs, images, and video/audio all map into the same graph |
|
||||
| **Local-first** | Code is parsed locally with tree-sitter (no LLM, nothing leaves your machine); only the semantic pass over docs/media calls a backend, and only if you configure one |
|
||||
|
||||
---
|
||||
|
||||
## Benchmarks
|
||||
|
||||
| Benchmark | Metric | graphify | Field |
|
||||
|---|---|---|---|
|
||||
| LOCOMO (n=300) | recall@10 | **0.497** | mem0 0.048, supermemory 0.149 |
|
||||
| LOCOMO (n=300) | QA accuracy | 45.3% | supermemory 49.7%, mem0 27.3% |
|
||||
| LongMemEval-S (n=50) | QA accuracy | **76%** | tied with dense RAG |
|
||||
| Graph build | LLM credits | **0** | per-token for most systems |
|
||||
|
||||
Every system ran on the same harness with the same model and budgets, scored by a judge blind-validated against a second judge (90.6% agreement, Cohen's kappa 0.81). Full per-system tables, the code-intelligence result, and reproduction commands: **[BENCHMARKS.md](./BENCHMARKS.md)**.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
@@ -155,7 +82,7 @@ curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
**Step 1 — install the package:**
|
||||
|
||||
```bash
|
||||
# Recommended (isolated env; if 'graphify' isn't found after, run: uv tool update-shell):
|
||||
# Recommended (uv puts graphify on PATH automatically):
|
||||
uv tool install graphifyy
|
||||
|
||||
# Alternatives:
|
||||
@@ -188,16 +115,13 @@ for example `graphify claude install --project` or `graphify codex install --pro
|
||||
|
||||
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell.
|
||||
|
||||
> **`graphify: command not found`?** `uv tool install` / `pipx install` put the `graphify` command in their tool bin dir (`~/.local/bin`). If your shell can't find it right after install — common on a fresh macOS + zsh setup — that dir isn't on your `PATH` yet: run `uv tool update-shell` (or `pipx ensurepath`), then open a new terminal. With plain `pip`, add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify`.
|
||||
|
||||
> **Running with `uvx` / `uv tool run` instead of installing?** Name the package, not the command: `uvx --from graphifyy graphify install`. Plain `uvx graphify …` fails (`No solution found … no versions of graphify`) because `uv tool run` reads the first word as a *package*, and the package is `graphifyy` — the `graphify` command lives inside it.
|
||||
> **`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`.
|
||||
|
||||
> **Avoid `pip install` on Mac/Windows** if possible. The skill resolves Python at runtime from `graphify-out/.graphify_python`; if that points to a different environment than where `pip` installed the package, you'll get `ModuleNotFoundError: No module named 'graphify'`. `uv tool install` and `pipx install` isolate the package in their own env and avoid this entirely.
|
||||
|
||||
> **Git hooks and uv tool / pipx:** `graphify hook install` embeds the current interpreter path directly into the hook scripts at install time, so the post-commit hook fires correctly even in GUI git clients and CI runners where `~/.local/bin` is not on PATH. If you reinstall or upgrade graphify, re-run `graphify hook install` to refresh the embedded path.
|
||||
|
||||
<details>
|
||||
<summary><b>Pick your platform</b> (20+ assistants, click to expand)</summary>
|
||||
### Pick your platform
|
||||
|
||||
| Platform | Install command |
|
||||
|----------|----------------|
|
||||
@@ -218,23 +142,19 @@ for example `graphify claude install --project` or `graphify codex install --pro
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Agent Skills (cross-framework) | `graphify install --platform agents` (alias `--platform skills`) |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify install --platform pi` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as Claude Code. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support `PreToolUse` hooks, so AGENTS.md is the always-on mechanism.
|
||||
|
||||
`--platform agents` (alias `--platform skills`) targets the generic cross-framework [Agent-Skills](https://github.com/anthropics/skills) locations: the spec's user-global `~/.agents/skills/` (read by `npx skills` and spec-compliant frameworks) for a global install, and `./.agents/skills/` for a project (`--project`) install. The bare `graphify install` stays single-platform (Claude Code) by design — use the named `agents` platform when you want the skill discoverable by any framework that reads `.agents/skills`.
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as Claude Code. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism.
|
||||
|
||||
> Codex uses `$graphify` instead of `/graphify`.
|
||||
|
||||
</details>
|
||||
### Optional extras
|
||||
|
||||
<details>
|
||||
<summary><b>Optional extras</b> (install only what you need)</summary>
|
||||
Install only what you need:
|
||||
|
||||
| Extra | What it adds | Install |
|
||||
|---|---|---|
|
||||
@@ -244,7 +164,6 @@ Codex users also need `multi_agent = true` under `[features]` in `~/.codex/confi
|
||||
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` |
|
||||
| `mcp` | MCP stdio server | `uv tool install "graphifyy[mcp]"` |
|
||||
| `neo4j` | Neo4j push support | `uv tool install "graphifyy[neo4j]"` |
|
||||
| `falkordb` | FalkorDB push support | `uv tool install "graphifyy[falkordb]"` |
|
||||
| `svg` | SVG graph export | `uv tool install "graphifyy[svg]"` |
|
||||
| `leiden` | Leiden community detection (Python < 3.13 only) | `uv tool install "graphifyy[leiden]"` |
|
||||
| `ollama` | Ollama local inference | `uv tool install "graphifyy[ollama]"` |
|
||||
@@ -257,12 +176,9 @@ Codex users also need `multi_agent = true` under `[features]` in `~/.codex/confi
|
||||
| `postgres` | Live PostgreSQL introspection (`--postgres DSN`) | `uv tool install "graphifyy[postgres]"` |
|
||||
| `dm` | BYOND DreamMaker `.dm`/`.dme` AST extraction (may need a C compiler + `python3-dev` if no wheel matches your platform) | `uv tool install "graphifyy[dm]"` |
|
||||
| `terraform` | Terraform / HCL `.tf`/`.tfvars`/`.hcl` AST extraction | `uv tool install "graphifyy[terraform]"` |
|
||||
| `pascal` | Pascal / Delphi `.pas`/`.dpr`/`.dpk`/`.inc` AST extraction (more accurate `calls`/`inherits` edges; falls back to a regex extractor when absent) | `uv tool install "graphifyy[pascal]"` |
|
||||
| `chinese` | Chinese query segmentation (jieba) | `uv tool install "graphifyy[chinese]"` |
|
||||
| `all` | Everything above | `uv tool install "graphifyy[all]"` |
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Make your assistant always use the graph
|
||||
@@ -288,31 +204,25 @@ Run this once in your project after building a graph:
|
||||
| Hermes | `graphify hermes install` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Agent Skills (cross-framework) | `graphify agents install` (alias `graphify skills install`) |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify pi install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions, preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files.
|
||||
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions — preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files. On platforms that support payload-bearing hooks (Claude Code, Gemini CLI), a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path. On the others (Codex, OpenCode, Cursor, etc.), the persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance. `GRAPH_REPORT.md` is still available for broad architecture review.
|
||||
|
||||
- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path.
|
||||
- **Instruction-file platforms** (Codex, OpenCode, Cursor, etc.): persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance.
|
||||
**CodeBuddy** does the same two things as Claude Code: writes a `CODEBUDDY.md` section telling CodeBuddy to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`.codebuddy/settings.json`) that fires before every Glob and Grep call.
|
||||
|
||||
`GRAPH_REPORT.md` is still available for broad architecture review.
|
||||
|
||||
**CodeBuddy** does the same two things as Claude Code: writes a `CODEBUDDY.md` section telling CodeBuddy to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs `PreToolUse` hooks (`.codebuddy/settings.json`) that fire before Bash search commands and file reads, nudging toward `graphify query` instead.
|
||||
|
||||
**Codex** writes to `AGENTS.md` and also installs a `PreToolUse` hook in `.codex/hooks.json` that fires before every Bash tool call, same always-on mechanism as Claude Code.
|
||||
|
||||
**Kilo Code** installs the Graphify skill to `~/.config/kilo/skills/graphify/SKILL.md` and a native `/graphify` command to `~/.config/kilo/command/graphify.md`. `graphify kilo install` also writes `AGENTS.md` plus a native `tool.execute.before` plugin (`.kilo/plugins/graphify.js` + `.kilo/kilo.json` or `.kilo/kilo.jsonc` registration) so Kilo gets the same always-on graph reminder behavior through native `.kilo` config.
|
||||
|
||||
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true`, so Cursor includes it in every conversation automatically, no hook needed.
|
||||
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
|
||||
|
||||
To remove graphify from all platforms at once: `graphify uninstall` (add `--purge` to also delete `graphify-out/`). Or use the per-platform command (e.g. `graphify claude uninstall`).
|
||||
|
||||
---
|
||||
|
||||
**Kilo Code** installs the Graphify skill to `~/.config/kilo/skills/graphify/SKILL.md` and a native `/graphify` command to `~/.config/kilo/command/graphify.md`. `graphify kilo install` also writes `AGENTS.md` plus a native **`tool.execute.before` plugin** (`.kilo/plugins/graphify.js` + `.kilo/kilo.json` or `.kilo/kilo.jsonc` registration) so Kilo gets the same always-on graph reminder behavior through native `.kilo` config.
|
||||
|
||||
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
|
||||
|
||||
## What's in the report
|
||||
|
||||
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
|
||||
@@ -327,12 +237,11 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
|
||||
|
||||
| Type | Extensions |
|
||||
|------|-----------|
|
||||
| Code (36 tree-sitter grammars) | `.py .ts .mts .cts .js .jsx .tsx .mjs .go .rs .java .c .cpp .cc .cxx .h .hpp .cu .cuh .metal .rb .cs .kt .kts .scala .php .swift .lua .luau .toc .zig .ps1 .psm1 .psd1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .slnx .csproj .fsproj .vbproj .xaml .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`; `.mts`/`.cts` reuse the TypeScript grammar, `.cc`/`.cxx` and CUDA `.cu`/`.cuh` and Metal `.metal` reuse the C++ grammar) |
|
||||
| Code (28 tree-sitter grammars) | `.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 .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .csproj .fsproj .vbproj .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`) |
|
||||
| Salesforce Apex | `.cls .trigger` (regex-based; classes, interfaces, enums, methods, triggers, SOQL/DML edges) |
|
||||
| Terraform / HCL | `.tf .tfvars .hcl` (requires `uv tool install graphifyy[terraform]`) |
|
||||
| MCP configs | `.mcp.json` `mcp.json` `mcp_servers.json` `claude_desktop_config.json` — extracts server nodes, package refs, env var requirements |
|
||||
| Package manifests | `apm.yml` `pyproject.toml` `go.mod` `pom.xml` — one canonical package node per package (by name) plus `depends_on` edges, so a package referenced from many manifests is a single hub |
|
||||
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` (markdown `[text](./other.md)` links and `[[wikilinks]]` become `references` edges between docs) |
|
||||
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
|
||||
| Office | `.docx .xlsx` (requires `uv tool install graphifyy[office]`) |
|
||||
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `uv tool install graphifyy[google]`) |
|
||||
| PDFs | `.pdf` |
|
||||
@@ -340,7 +249,7 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
|
||||
| Video / Audio | `.mp4 .mov .mp3 .wav` and more (requires `uv tool install graphifyy[video]`) |
|
||||
| YouTube / URLs | any video URL (requires `uv tool install graphifyy[video]`) |
|
||||
|
||||
Code is extracted **locally with no API calls** (AST via tree-sitter). Everything else goes through your AI assistant's model API.
|
||||
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
|
||||
|
||||
Google Drive for desktop `.gdoc`, `.gsheet`, and `.gslides` files are shortcut
|
||||
pointers, not document content. To include native Google Docs, Sheets, and Slides
|
||||
@@ -394,7 +303,7 @@ See the [full command reference](#full-command-reference) below.
|
||||
|
||||
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation.
|
||||
|
||||
**`.gitignore` is respected automatically.** graphify reads the `.gitignore` in each directory. If a `.graphifyignore` is also present, the two are **merged** — `.graphifyignore` patterns are evaluated last, so they win on conflicts (including `!` negations). Adding a `.graphifyignore` only ever excludes more; it never re-includes a file your `.gitignore` already excluded. Subdirectory scoping works the same way as git — an ignore file only affects its own subtree.
|
||||
**`.gitignore` is respected automatically.** If no `.graphifyignore` is present in a directory, graphify falls back to the `.gitignore` in that directory. If both exist, `.graphifyignore` takes priority. Subdirectory scoping works the same way as git — an ignore file only affects its own subtree.
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
@@ -439,7 +348,6 @@ graphify query "what connects DigestAuth to Response?" --graph graphify-out/grap
|
||||
|
||||
# expose the graph as an MCP server (for repeated tool-call access)
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
python -m graphify.serve --graph graphify-out/graph.json # --graph flag also accepted
|
||||
|
||||
# register with Kimi Code:
|
||||
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
|
||||
@@ -488,12 +396,8 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
|
||||
| Variable | Used for | When required |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | Claude (Anthropic) backend | `--backend claude` |
|
||||
| `ANTHROPIC_BASE_URL` | Anthropic-compatible endpoint URL (LiteLLM proxy, gateways, ...) | `--backend claude` (default: `https://api.anthropic.com`) |
|
||||
| `ANTHROPIC_MODEL` | Model name for the Claude backend — for custom endpoints, use the model name/alias your server exposes | `--backend claude` (default: `claude-sonnet-4-6`) |
|
||||
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Google Gemini backend | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` (local servers accept any non-empty value) |
|
||||
| `OPENAI_BASE_URL` | OpenAI-compatible server URL (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (default: `https://api.openai.com/v1`) |
|
||||
| `OPENAI_MODEL` | Model name for the OpenAI backend — for self-hosted servers, use the model name/alias your server exposes (check its `/v1/models` endpoint), e.g. `LFM2.5-8B-A1B-UD-Q4_K_XL` for llama.cpp | `--backend openai` (default: `gpt-4.1-mini`) |
|
||||
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` |
|
||||
| `DEEPSEEK_API_KEY` | DeepSeek backend | `--backend deepseek` |
|
||||
| `MOONSHOT_API_KEY` | Kimi Code backend | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | Ollama local inference URL | `--backend ollama` (default: `http://localhost:11434`) |
|
||||
@@ -508,17 +412,13 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
|
||||
| `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` | Per-call timeout in seconds for HTTP, claude-cli, and Anthropic SDK backends (default: 600) | optional — also `--api-timeout` flag |
|
||||
| `GRAPHIFY_MAX_RETRIES` | How many times to retry a rate-limited (429) request before giving up (default: 6; honors `Retry-After`) | optional — raise for strict per-org limits (e.g. kimi); `0` disables |
|
||||
| `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` |
|
||||
| `GRAPHIFY_TRIAGE_BACKEND` | Backend for `graphify prs --triage` | optional — auto-detected from available keys |
|
||||
| `GRAPHIFY_TRIAGE_MODEL` | Model override for triage | optional — e.g. `claude-opus-4-7` |
|
||||
| `GRAPHIFY_QUERY_LOG_ENABLE` | Set to `1` to turn on the local query log at `~/.cache/graphify-queries.log` (records each query/path/explain question + corpus path). Off by default — nothing is written unless you opt in (#1797) | optional |
|
||||
| `GRAPHIFY_QUERY_LOG` | Enable the query log and write it to this path instead of the default | optional — off unless this or `_ENABLE` is set |
|
||||
| `GRAPHIFY_QUERY_LOG_DISABLE` | Set to `1` to force the query log off (wins over the enable vars) | optional |
|
||||
| `GRAPHIFY_QUERY_LOG_RESPONSES` | When the log is enabled, also record full subgraph responses (off by default) | optional |
|
||||
| `GRAPHIFY_MAX_GRAPH_BYTES` | Override the 512 MiB graph.json size cap — e.g. `700MB`, `2GB`, or plain bytes | optional — useful for very large corpora |
|
||||
| `GRAPHIFY_LLM_TEMPERATURE` | Override LLM temperature for semantic extraction — e.g. `0.7`, or `none` to omit | optional — auto-omitted for o1/o3/o4/gpt-5 reasoning models |
|
||||
| `GRAPHIFY_QUERY_LOG` | Override query log path (default: `~/.cache/graphify-queries.log`) | optional — set to empty or `/dev/null` to silence |
|
||||
| `GRAPHIFY_QUERY_LOG_DISABLE` | Set to `1` to disable query logging entirely | optional |
|
||||
| `GRAPHIFY_QUERY_LOG_RESPONSES` | Set to `1` to also log full subgraph responses (off by default) | optional |
|
||||
|
||||
---
|
||||
|
||||
@@ -528,24 +428,21 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
|
||||
- **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), `DEEPSEEK_API_KEY` (DeepSeek), 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.
|
||||
- **Data residency** — `graphify extract` auto-detects which provider to use based on which API key is set (priority: Gemini → Kimi → Claude → OpenAI → DeepSeek → Azure → Bedrock → Ollama). For code with data-residency requirements, use `--backend ollama` (fully local) or pass an explicit `--backend` flag. Kimi (`MOONSHOT_API_KEY`) routes to Moonshot AI servers in China.
|
||||
- **No telemetry**, no usage tracking, no analytics.
|
||||
- No telemetry, no usage tracking, no analytics.
|
||||
- **Query logging** — every `graphify query`, `graphify path`, `graphify explain`, and MCP `query_graph` call is logged to `~/.cache/graphify-queries.log` in JSON Lines format (timestamp, question, corpus, nodes returned, duration). Full subgraph responses are **not** stored by default. Set `GRAPHIFY_QUERY_LOG_DISABLE=1` to opt out, or `GRAPHIFY_QUERY_LOG=/dev/null` to silence without disabling the code path.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**`graphify: command not found` after installing**
|
||||
The CLI is installed but its bin directory isn't on your shell's `PATH`. Pick the fix for how you installed:
|
||||
- **uv** (`uv tool install graphifyy`): the command lands in uv's tool bin dir (`~/.local/bin`), which a fresh macOS/zsh setup often doesn't have on `PATH`. Run `uv tool update-shell`, then open a new terminal. (Find the dir with `uv tool dir --bin`.)
|
||||
- **pipx** (`pipx install graphifyy`): run `pipx ensurepath`, then open a new terminal.
|
||||
- **pip** (`pip install graphifyy`): pip installs scripts to a user bin dir that may not be on `PATH` — add `~/Library/Python/3.x/bin` (macOS) or `~/.local/bin` (Linux) to your `PATH` in `~/.zshrc`/`~/.bashrc`, or just run `python -m graphify`.
|
||||
|
||||
**`uvx graphify …` or `uv tool run graphify …` fails to resolve `graphify`**
|
||||
The PyPI package is `graphifyy`; `graphify` is only the command it provides. `uv tool run` treats the first word as a *package name*, so it looks for a package called `graphify` and reports `No solution found … no versions of graphify`. Name the package explicitly: `uvx --from graphifyy graphify install` (same as `uv tool run --from graphifyy graphify install`). Or `uv tool install graphifyy` once and then call `graphify` directly.
|
||||
**`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 bin directory the command was installed to. Prefer `uv tool install` / `pipx install` over plain `pip`, then run `uv tool update-shell` / `pipx ensurepath` and open a new terminal (see the install notes above).
|
||||
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.
|
||||
@@ -565,14 +462,6 @@ The KV-cache window is auto-sized but may be too large for your GPU. Reduce it:
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
|
||||
```
|
||||
|
||||
**`LLM returned invalid JSON` / `Unterminated string` warnings**
|
||||
The model's JSON response hit its output-token limit and was cut off mid-string. graphify auto-recovers (it splits the chunk and re-extracts the halves, and an oversized single document is first sliced at heading/paragraph boundaries so the whole file is still covered), so these warnings are noisy but not data loss. To reduce the churn, raise the output cap or shrink each chunk's output:
|
||||
```bash
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=16384 graphify extract . --mode deep # lift the cap
|
||||
graphify extract . --mode deep --token-budget 4000 # smaller input chunks -> smaller output
|
||||
```
|
||||
With a cloud gateway like OpenRouter, prefer `--backend openai` (set `OPENAI_BASE_URL`) over the Ollama shim — it's a cleaner OpenAI-compatible path. If the model has its own max-output ceiling, lowering `--token-budget` is the reliable lever.
|
||||
|
||||
**Graph HTML is too large to open in a browser (>5000 nodes)**
|
||||
Skip HTML generation and use the JSON directly:
|
||||
```bash
|
||||
@@ -596,14 +485,6 @@ uv tool upgrade graphifyy
|
||||
graphify install # overwrites the skill file
|
||||
```
|
||||
|
||||
**Claude Code prompt cache invalidated after every `graphify extract`**
|
||||
Graphify writes output files (`graph.json`, `graphify-out/`) into the workspace. If those paths aren't ignored, every write invalidates Claude Code's prompt cache, forcing a full re-upload at cache-write rates on the next turn. Add them to `.claudeignore`:
|
||||
```text
|
||||
# .claudeignore
|
||||
graph.json
|
||||
graphify-out/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Full command reference
|
||||
@@ -617,14 +498,11 @@ graphify-out/
|
||||
/graphify ./raw --cluster-only # rerun clustering on existing graph
|
||||
/graphify ./raw --no-viz # skip HTML visualization
|
||||
/graphify ./raw --obsidian # generate Obsidian vault
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vault # write into an existing vault (never overwrites your own notes or .obsidian config)
|
||||
/graphify ./raw --wiki # build agent-crawlable markdown wiki
|
||||
/graphify ./raw --svg # export graph.svg
|
||||
/graphify ./raw --graphml # export for Gephi / yEd
|
||||
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687
|
||||
/graphify ./raw --falkordb # generate cypher.txt for FalkorDB
|
||||
/graphify ./raw --falkordb-push falkordb://localhost:6379
|
||||
/graphify ./raw --watch # auto-sync as files change
|
||||
/graphify ./raw --mcp # start MCP stdio server
|
||||
|
||||
@@ -637,14 +515,6 @@ graphify-out/
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify save-result --question "Q" --answer "A" --nodes Foo Bar --outcome useful # record how a Q&A turned out (work memory; outcome ∈ useful|dead_end|corrected)
|
||||
graphify reflect # aggregate graphify-out/memory/ outcomes into reflections/LESSONS.md
|
||||
graphify reflect --if-stale # no-op when LESSONS.md is already newer than every input (cheap to run each session)
|
||||
graphify reflect --out docs/LESSONS.md # write the lessons doc somewhere else
|
||||
graphify reflect --graph graphify-out/graph.json # group lessons by community + write the work-memory overlay (.graphify_learning.json)
|
||||
# the overlay tags nodes preferred/tentative/contested (recency-weighted, with provenance);
|
||||
# graphify explain / query then show a "Lesson:" hint, flagged "code changed — re-verify" when the source moved on
|
||||
|
||||
graphify uninstall # remove from all platforms in one shot
|
||||
graphify uninstall --purge # also delete graphify-out/
|
||||
graphify uninstall --project --platform codex # remove project-scoped install files only
|
||||
@@ -682,8 +552,6 @@ graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
|
||||
graphify hermes uninstall
|
||||
graphify amp install # skill file (Amp)
|
||||
graphify amp uninstall
|
||||
graphify agents install # ~/.agents/skills/ + AGENTS.md (cross-framework; alias: graphify skills)
|
||||
graphify agents uninstall
|
||||
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
|
||||
graphify kiro uninstall
|
||||
graphify pi install # skill file (Pi coding agent)
|
||||
@@ -697,8 +565,6 @@ graphify extract ./docs # headless LLM extraction for CI
|
||||
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock, or claude-cli
|
||||
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
|
||||
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL) - no API key needed for loopback
|
||||
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # any OpenAI-compatible server (llama.cpp, vLLM, LM Studio)
|
||||
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # any Anthropic-compatible endpoint (LiteLLM proxy, gateways)
|
||||
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
|
||||
@@ -706,14 +572,12 @@ graphify extract ./docs --backend claude-cli # route through Claude Code CLI -
|
||||
graphify extract ./docs --backend azure # Azure OpenAI (set AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT)
|
||||
graphify extract ./docs --max-workers 16 # AST parallelism (also GRAPHIFY_MAX_WORKERS)
|
||||
graphify extract --postgres "postgresql://user:pass@host/db" # introspect live PostgreSQL schema directly
|
||||
graphify extract ./my-workspace --cargo # introspect Rust Cargo workspace dependencies directly
|
||||
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 --mode deep # richer semantic extraction via extended system prompt
|
||||
graphify extract ./docs --no-cluster # raw extraction only, skip clustering
|
||||
graphify extract ./docs --timing # print per-stage wall-clock timings to stderr (also works on cluster-only)
|
||||
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
|
||||
@@ -724,7 +588,7 @@ graphify export callflow-html --max-sections 8 # cap generated architecture
|
||||
graphify export callflow-html --output docs/arch.html
|
||||
graphify export callflow-html ./some-repo/graphify-out
|
||||
|
||||
graphify global add graphify-out/graph.json --as myrepo # register a project graph into ~/.graphify/global-graph.json
|
||||
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
|
||||
graphify global path # print path to the global graph file
|
||||
@@ -748,14 +612,12 @@ graphify update ./src --no-cluster # skip reclustering, write raw AST graph onl
|
||||
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
|
||||
graphify cluster-only ./my-project --max-concurrency 16 --batch-size 200 # parallel community labeling (large graphs)
|
||||
graphify cluster-only ./my-project --resolution 1.5 # more, smaller communities
|
||||
graphify cluster-only ./my-project --exclude-hubs 99 # exclude p99 degree nodes from partitioning
|
||||
graphify cluster-only ./my-project --no-label # keep "Community N" placeholders
|
||||
graphify cluster-only ./my-project --backend=gemini # backend for community naming
|
||||
graphify cluster-only ./my-project --backend=gemini --model gemini-2.5-pro # specific model
|
||||
graphify label ./my-project # (re)name communities with the configured backend
|
||||
graphify label ./my-project --backend=openai --model gpt-4o # force a specific backend and model
|
||||
graphify label ./my-project --backend=openai # force a specific backend
|
||||
```
|
||||
|
||||
> **Community names:** inside an agent (Claude Code, Gemini CLI) the agent names communities itself. When you run the bare CLI, `cluster-only` auto-names them with the configured backend (built-in or custom OpenAI-compatible provider) — pass `--no-label` to keep `Community N`, or run `graphify label` to (re)generate names on demand.
|
||||
@@ -767,17 +629,16 @@ graphify label ./my-project --backend=openai --model gpt-4o # force a specific
|
||||
- [How it works](docs/how-it-works.md) — the extraction pipeline, community detection, confidence scoring, benchmarks
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) — module breakdown, how to add a language
|
||||
- [Optional integrations](docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
|
||||
- [The Memory Layer](https://safishamsi.gumroad.com/l/qetvlo) — the book on the ideas behind graphify, the architecture end to end
|
||||
|
||||
---
|
||||
|
||||
## Built on graphify: Penpax
|
||||
## Built on graphify — Penpax
|
||||
|
||||
[**Penpax**](https://graphify.com) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working life: meetings, browser history, emails, files, and code, updating continuously in the background.
|
||||
[**Penpax**](https://graphifylabs.ai) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working life: meetings, browser history, emails, files, and code, updating continuously in the background.
|
||||
|
||||
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
|
||||
|
||||
**Free trial launching soon.** [Join the waitlist →](https://www.graphify.com)
|
||||
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
|
||||
|
||||
---
|
||||
|
||||
@@ -831,22 +692,3 @@ uv run pytest tests/ -q -k "python" # filter by name
|
||||
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
<a href="https://star-history.com/#safishamsi/graphify&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## Community and links
|
||||
|
||||
<p align="center">
|
||||
<a href="https://discord.gg/598Ad9zQZ"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></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://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>
|
||||
</p>
|
||||
+1
-2
@@ -34,7 +34,6 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
|
||||
| Path traversal in MCP server | `security.validate_graph_path()` resolves paths and requires them to be inside `graphify-out/`. Also requires the `graphify-out/` directory to exist. |
|
||||
| XSS in graph HTML output | `security.sanitize_label()` strips control characters, caps at 256 chars, and HTML-escapes all node labels and edge titles before pyvis embeds them. |
|
||||
| Prompt injection via node labels | `sanitize_label()` also applied to MCP text output - node labels from user-controlled source files cannot break the text format returned to agents. |
|
||||
| Prompt injection via source file content | During the semantic pass, source files are attacker-controlled text mixed into the LLM context. `_read_files()` in `llm.py` wraps every file in a hash-stamped `<untrusted_source path=... sha256=...>` delimiter block, the extraction system prompt instructs the model to treat that block as inert data and never as instructions, and `_neutralise_injection_sentinels()` defangs known chat-template/jailbreak tokens (`<\|im_start\|>`, `[INST]`, `<<SYS>>`, forged `</untrusted_source>`, etc.) before insertion. This is the table-stakes defense (issue #1210): it does not make injection impossible, but changes it from "works on first try" to "requires evasion." |
|
||||
| YAML frontmatter injection | `_yaml_str()` escapes backslashes, double quotes, and newlines before embedding user-controlled strings (webpage titles, query questions) in YAML frontmatter. |
|
||||
| Encoding crashes on source files | All tree-sitter byte slices decoded with `errors="replace"` - non-UTF-8 source files degrade gracefully instead of crashing extraction. |
|
||||
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
|
||||
@@ -42,7 +41,7 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
|
||||
|
||||
### What graphify does NOT do
|
||||
|
||||
- Does not run a network listener by default (stdio transport); `--transport http` is opt-in, documented in the README, and binds to `127.0.0.1` unless `--host 0.0.0.0` is passed
|
||||
- Does not run a network listener (MCP server communicates over stdio only)
|
||||
- Does not execute code from source files (tree-sitter parses ASTs - no eval/exec)
|
||||
- Does not use `shell=True` in any subprocess call
|
||||
- Does not store credentials or API keys
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 360" width="900" height="360" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" role="img" aria-label="graphify path query lighting up a knowledge graph"><defs><linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0c1712"/><stop offset="1" stop-color="#0f1e18"/></linearGradient><radialGradient id="glow" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#62c4a2" stop-opacity="0.35"/><stop offset="1" stop-color="#62c4a2" stop-opacity="0"/></radialGradient></defs><rect x="1" y="1" width="898" height="358" rx="14" fill="url(#bg)" stroke="#20342b" stroke-width="1.5"/><line x1="336" y1="18" x2="336" y2="342" stroke="#1c2c25" stroke-width="1"/><circle cx="28" cy="30" r="4.5" fill="#ff5f56"/><circle cx="46" cy="30" r="4.5" fill="#ffbd2e"/><circle cx="64" cy="30" r="4.5" fill="#27c93f"/><text x="320" y="34" text-anchor="end" font-size="10" fill="#6f8a7f">graphify</text><text x="20" y="74" font-size="11" fill="#4db18f" font-weight="600">$</text><text x="33.2" y="74" font-size="11" fill="#c6d6ce" opacity="0">g<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.035;0.047;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="39.9" y="74" font-size="11" fill="#c6d6ce" opacity="0">r<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0408;0.0528;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="46.5" y="74" font-size="11" fill="#c6d6ce" opacity="0">a<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0466;0.0586;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="53.1" y="74" font-size="11" fill="#c6d6ce" opacity="0">p<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0524;0.0644;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="59.7" y="74" font-size="11" fill="#c6d6ce" opacity="0">h<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0582;0.0702;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="66.3" y="74" font-size="11" fill="#c6d6ce" opacity="0">i<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.064;0.076;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="73.0" y="74" font-size="11" fill="#c6d6ce" opacity="0">f<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0698;0.0818;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="79.6" y="74" font-size="11" fill="#c6d6ce" opacity="0">y<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0756;0.0876;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="92.8" y="74" font-size="11" fill="#c6d6ce" opacity="0">p<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0872;0.0992;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="99.4" y="74" font-size="11" fill="#c6d6ce" opacity="0">a<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.093;0.105;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="106.1" y="74" font-size="11" fill="#c6d6ce" opacity="0">t<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.0988;0.1108;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="112.7" y="74" font-size="11" fill="#c6d6ce" opacity="0">h<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1046;0.1166;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="125.9" y="74" font-size="11" fill="#c6d6ce" opacity="0">"<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1162;0.1282;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="132.5" y="74" font-size="11" fill="#c6d6ce" opacity="0">F<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.122;0.134;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="139.2" y="74" font-size="11" fill="#c6d6ce" opacity="0">a<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1278;0.1398;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="145.8" y="74" font-size="11" fill="#c6d6ce" opacity="0">s<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1336;0.1456;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="152.4" y="74" font-size="11" fill="#c6d6ce" opacity="0">t<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1394;0.1514;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="159.0" y="74" font-size="11" fill="#c6d6ce" opacity="0">A<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1452;0.1572;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="165.6" y="74" font-size="11" fill="#c6d6ce" opacity="0">P<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.151;0.163;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="172.3" y="74" font-size="11" fill="#c6d6ce" opacity="0">I<animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.1568;0.1688;0.96;1" dur="10.0s" repeatCount="indefinite"/></text><text x="178.9" y="Line truncated
|
||||
|
Before Width: | Height: | Size: 20 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 634 KiB |
@@ -88,9 +88,6 @@ The output `graph.json` uses NetworkX's node-link format. Each node has:
|
||||
- `file_type` — `code`, `document`, `paper`, `image`, `rationale`
|
||||
- `source_file` — where it came from
|
||||
|
||||
See [RFC: file-level node summaries](node-summaries-rfc.md) for two proposed
|
||||
ways to add compact optional summaries for AI navigation.
|
||||
|
||||
Each edge has:
|
||||
- `source`, `target` — node IDs
|
||||
- `relation` — verb phrase (e.g. `calls`, `imports`, `implements`, `semantically_similar_to`)
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 143 KiB |
@@ -1,186 +0,0 @@
|
||||
# RFC: file-level node summaries
|
||||
|
||||
This RFC proposes an optional way for graphify to expose compact file-level
|
||||
summaries for AI coding agents.
|
||||
|
||||
## Problem
|
||||
|
||||
`graph.json` gives agents graph structure, source files, node labels, and
|
||||
relationships. That helps avoid reading an entire repository, but agents still
|
||||
often need to inspect raw files just to answer a basic navigation question:
|
||||
|
||||
> What is this file or node responsible for?
|
||||
|
||||
A short summary near the graph node could reduce repeated file reads during
|
||||
`graphify query`, `graphify explain`, MCP node lookup, and graph navigation.
|
||||
|
||||
## Goals
|
||||
|
||||
- Help agents choose relevant files with less context.
|
||||
- Preserve graphify's offline, deterministic behavior by default.
|
||||
- Keep the first implementation small and reviewable.
|
||||
- Avoid adding long prose to `GRAPH_REPORT.md`.
|
||||
- Leave room for a future opt-in LLM-generated summary backend.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Summarizing every function, method, or local symbol in the first version.
|
||||
- Calling an LLM or remote API by default.
|
||||
- Replacing `graphify explain`; summaries should make `explain` more useful.
|
||||
- Turning `GRAPH_REPORT.md` into a full per-file index.
|
||||
|
||||
## Shared constraints for either option
|
||||
|
||||
- Start with file-level nodes only.
|
||||
- Keep each summary bounded, for example one sentence or roughly 200-300
|
||||
characters.
|
||||
- Generate deterministic summaries first from existing local signal:
|
||||
module docstrings, top comments, exported symbols, imports, relation counts,
|
||||
and community/context data.
|
||||
- Do not emit summaries by default until the storage model is agreed on.
|
||||
- Display a summary in `graphify explain <node>` when one exists.
|
||||
- Include summaries in `graphify serve` / MCP node lookup when one exists.
|
||||
|
||||
## Proposed summary contents
|
||||
|
||||
Each file-level summary should give an agent enough signal to decide whether to
|
||||
inspect the file, without replacing the file or bloating graph output.
|
||||
|
||||
Recommended fields:
|
||||
|
||||
| Field | Why it helps agents |
|
||||
| --- | --- |
|
||||
| `summary` | One bounded sentence describing the file's responsibility. This is the main token-saving field. |
|
||||
| `source_file` | Lets the agent jump to the right file without resolving a node ID manually. |
|
||||
| `label` | Keeps the summary readable in CLI, MCP, and UI contexts. |
|
||||
| `generated_by` | Distinguishes deterministic summaries from future LLM-generated summaries. |
|
||||
| `summary_version` | Allows the format to evolve without guessing how an older summary was produced. |
|
||||
|
||||
Recommended signal inside the `summary` sentence:
|
||||
|
||||
| Signal | Why it belongs in the sentence |
|
||||
| --- | --- |
|
||||
| Module docstring or top comment | Usually the highest-quality human-authored purpose statement. |
|
||||
| Exported classes/functions/symbols | Tells the agent what API surface the file provides. |
|
||||
| Important imports or dependencies | Reveals whether the file belongs to auth, database, UI, CLI, test, etc. |
|
||||
| Dominant graph relations | Shows whether the file mainly calls, imports, defines, contains, or references other nodes. |
|
||||
| Community or nearby hub label | Gives architectural context without reading the whole community report. |
|
||||
| Source location coverage when available | Helps distinguish a file-level summary from a symbol-level explanation. |
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"label": "extract.py",
|
||||
"source_file": "graphify/extract.py",
|
||||
"summary": "Extracts source files into graph nodes and relationships; defines language parsers and import/call extraction helpers.",
|
||||
"generated_by": "deterministic",
|
||||
"summary_version": 1
|
||||
}
|
||||
```
|
||||
|
||||
The summary should not include long call chains, full dependency lists, raw code,
|
||||
or every symbol in the file. Those details already belong in the graph and can
|
||||
be fetched through `graphify explain`, `graphify query`, or direct file reads
|
||||
when needed.
|
||||
|
||||
## Option A: `summary` attribute in `graph.json`
|
||||
|
||||
Add an optional `summary` field to file-level nodes:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "graphify_extract",
|
||||
"label": "extract.py",
|
||||
"file_type": "code",
|
||||
"source_file": "graphify/extract.py",
|
||||
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
|
||||
}
|
||||
```
|
||||
|
||||
Possible user flow:
|
||||
|
||||
```bash
|
||||
graphify . --summarize-nodes
|
||||
graphify explain "extract.py"
|
||||
```
|
||||
|
||||
Pros:
|
||||
|
||||
- Single artifact for graph consumers.
|
||||
- Matches NetworkX node attributes and existing node metadata.
|
||||
- Easy for `explain`, `serve`, visualizers, and MCP tools to consume.
|
||||
- No sidecar freshness or node-ID join logic.
|
||||
|
||||
Cons:
|
||||
|
||||
- Adds text to the core graph artifact.
|
||||
- Expands the graph schema surface.
|
||||
- Consumers that dump all of `graph.json` into an LLM context would pay for all
|
||||
summaries at once.
|
||||
|
||||
## Option B: sidecar `node-summaries.json`
|
||||
|
||||
Write summaries to a separate artifact keyed by node ID:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"generator": "deterministic",
|
||||
"nodes": {
|
||||
"graphify_extract": {
|
||||
"label": "extract.py",
|
||||
"source_file": "graphify/extract.py",
|
||||
"summary": "Extracts source files into graph nodes and relationships using language-specific parsers."
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Possible user flow:
|
||||
|
||||
```bash
|
||||
graphify summarize
|
||||
graphify explain "extract.py"
|
||||
```
|
||||
|
||||
Pros:
|
||||
|
||||
- Keeps `graph.json` lean and topology-focused.
|
||||
- Makes summaries clearly optional.
|
||||
- Can be regenerated independently.
|
||||
- Provides a natural place for future generator metadata.
|
||||
|
||||
Cons:
|
||||
|
||||
- Adds a second artifact that consumers must discover and load.
|
||||
- Introduces freshness and synchronization questions.
|
||||
- Every consumer that wants summaries must join by node ID.
|
||||
|
||||
## Suggested first implementation once storage is chosen
|
||||
|
||||
1. Add deterministic file-level summary generation.
|
||||
2. Store summaries using the selected option.
|
||||
3. Surface summaries in `graphify explain`.
|
||||
4. Surface summaries in `graphify serve` / MCP node lookup.
|
||||
5. Add tests for default behavior, generated summaries, missing summaries, and
|
||||
bounded summary length.
|
||||
|
||||
## Follow-up ideas
|
||||
|
||||
- Add opt-in LLM-generated summaries with explicit provider/backend selection.
|
||||
- Extend summaries to class or module-level nodes if file-level summaries prove
|
||||
useful.
|
||||
- Allow `graphify query` to include summaries for returned nodes under a budget.
|
||||
- Add cache/freshness metadata if summaries are generated separately from the
|
||||
main graph.
|
||||
|
||||
## Questions for maintainers and users
|
||||
|
||||
1. Should graphify prefer one artifact (`graph.json`) or keep generated text in a
|
||||
sidecar?
|
||||
2. Should deterministic file-level summaries be generated during graph creation,
|
||||
or only through an explicit command such as `graphify summarize`?
|
||||
3. Is `summary` the right term, or would `synopsis` better communicate a short,
|
||||
bounded description?
|
||||
4. What summary length budget would be acceptable for large repositories?
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
**Eine KI-Coding-Assistent-Skill.** Tippe `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro oder Google Antigravity — es liest deine Dateien, baut einen Wissensgraphen und gibt dir Struktur zurück, die du vorher nicht sehen konntest. Verstehe eine Codebasis schneller. Finde das „Warum" hinter Architekturentscheidungen.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
**Una habilidad para asistentes de código IA.** Escribe `/graphify` en Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro o Google Antigravity — lee tus archivos, construye un grafo de conocimiento y te devuelve estructura que no sabías que existía. Entiende una base de código más rápido. Encuentra el «por qué» detrás de las decisiones arquitectónicas.
|
||||
|
||||
@@ -1,572 +0,0 @@
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇷 <a href="README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></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=v8" 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://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" 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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-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>
|
||||
</p>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**یک مهارت برای دستیار کدنویسی هوش مصنوعی.** `/graphify` را در Claude Code، Codex، OpenCode، Kilo Code، Cursor، Gemini CLI، GitHub Copilot CLI، VS Code Copilot Chat، Aider، Amp، OpenClaw، Factory Droid، Trae، Hermes، Kimi Code، Kiro، Pi، Devin CLI یا Google Antigravity تایپ کنید — تمام پروژهتان را میخواند، یک گراف دانش میسازد، و ساختاری که نمیدانستید وجود دارد را به شما بازمیگرداند. کدبیس را سریعتر درک کنید. «چرا»ی پشت تصمیمات معماری را کشف کنید.
|
||||
|
||||
کاملاً چندوجهی. کد، PDF، مارکداون، اسکرینشات، نمودار، عکس وایتبورد، تصاویر به زبانهای دیگر، یا فایلهای ویدئو و صوتی بریزید — graphify مفاهیم و روابط را از همه آنها استخراج کرده و در یک گراف به هم متصل میکند. ویدئوها بهصورت محلی با Whisper رونویسی میشوند. ۳۶ زبان برنامهنویسی از طریق tree-sitter AST پشتیبانی میشوند.
|
||||
|
||||
> Andrej Karpathy یک پوشه `/raw` نگه میدارد که در آن مقالات، توییتها، اسکرینشاتها و یادداشتها میریزد. graphify پاسخ آن مشکل است — **۷۱.۵ برابر** کمتر توکن در هر پرسوجو در مقایسه با خواندن فایلهای خام، در طول جلسات پایدار، و صادق در مورد آنچه پیدا شده در برابر آنچه استنباط شده است.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
همین. سه فایل دریافت میکنید:
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html در هر مرورگری باز کنید — روی گرهها کلیک کنید، فیلتر کنید، جستجو کنید
|
||||
├── GRAPH_REPORT.md نکات کلیدی: مفاهیم محوری، اتصالات شگفتانگیز، سؤالات پیشنهادی
|
||||
└── graph.json گراف کامل — هر زمان بدون نیاز به بازخوانی فایلها پرسوجو کنید
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
برای یک صفحه معماری خوانا با نمودارهای جریان فراخوانی Mermaid، اجرا کنید:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify export callflow-html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## پیشنیازها
|
||||
|
||||
</div>
|
||||
|
||||
| پیشنیاز | حداقل | بررسی | نصب |
|
||||
|---|---|---|---|
|
||||
| Python | ۳.۱۰+ | `python --version` | [python.org](https://www.python.org/downloads/) |
|
||||
| uv *(پیشنهادی)* | هر نسخه | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
|
||||
| pipx *(جایگزین)* | هر نسخه | `pipx --version` | `pip install pipx` |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**نصب سریع macOS (Homebrew):**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
brew install python@3.12 uv
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**نصب سریع Windows:**
|
||||
|
||||
</div>
|
||||
|
||||
```powershell
|
||||
winget install astral-sh.uv
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**Ubuntu/Debian:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
sudo apt install python3.12 python3-pip pipx
|
||||
# یا نصب uv:
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## نصب
|
||||
|
||||
> **بسته رسمی:** بسته PyPI به نام `graphifyy` است (با دو y). سایر بستههای `graphify*` در PyPI وابسته به این پروژه نیستند. دستور CLI همچنان `graphify` است.
|
||||
|
||||
**مرحله ۱ — نصب بسته:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# پیشنهادی (uv بهطور خودکار graphify را در PATH قرار میدهد):
|
||||
uv tool install graphifyy
|
||||
|
||||
# جایگزینها:
|
||||
pipx install graphifyy
|
||||
pip install graphifyy # ممکن است نیاز به تنظیم PATH داشته باشد — یادداشت زیر را ببینید
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**مرحله ۲ — ثبت مهارت در دستیار هوش مصنوعی:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify install
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
همین. دستیار هوش مصنوعیتان را باز کنید و `/graphify .` تایپ کنید.
|
||||
|
||||
برای نصب مهارت دستیار در مخزن جاری بهجای پروفایل کاربری، `--project` اضافه کنید:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify install --project
|
||||
graphify install --project --platform codex
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> **یادداشت PowerShell:** از `graphify .` استفاده کنید نه `/graphify .` — اسلش ابتدایی در PowerShell جداکننده مسیر است.
|
||||
|
||||
> **`graphify: command not found`؟** از `uv tool install graphifyy` یا `pipx install graphifyy` استفاده کنید — هر دو CLI را بهطور خودکار در PATH قرار میدهند.
|
||||
|
||||
### انتخاب پلتفرم
|
||||
|
||||
</div>
|
||||
|
||||
| پلتفرم | دستور نصب |
|
||||
|----------|----------------|
|
||||
| Claude Code (Linux/Mac) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (تشخیص خودکار) یا `graphify install --platform windows` |
|
||||
| CodeBuddy | `graphify install --platform codebuddy` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| Kilo Code | `graphify install --platform kilo` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify install --platform pi` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### افزونههای اختیاری
|
||||
|
||||
فقط آنچه نیاز دارید نصب کنید:
|
||||
|
||||
</div>
|
||||
|
||||
| افزونه | چه چیزی اضافه میکند | نصب |
|
||||
|---|---|---|
|
||||
| `pdf` | استخراج PDF | `uv tool install "graphifyy[pdf]"` |
|
||||
| `office` | پشتیبانی از `.docx` و `.xlsx` | `uv tool install "graphifyy[office]"` |
|
||||
| `google` | رندرینگ Google Sheets | `uv tool install "graphifyy[google]"` |
|
||||
| `video` | رونویسی ویدئو/صوت | `uv tool install "graphifyy[video]"` |
|
||||
| `mcp` | سرور MCP stdio | `uv tool install "graphifyy[mcp]"` |
|
||||
| `neo4j` | پشتیبانی از Neo4j | `uv tool install "graphifyy[neo4j]"` |
|
||||
| `ollama` | استنتاج محلی Ollama | `uv tool install "graphifyy[ollama]"` |
|
||||
| `openai` | OpenAI / APIهای سازگار با OpenAI | `uv tool install "graphifyy[openai]"` |
|
||||
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
|
||||
| `anthropic` | Anthropic Claude API | `uv tool install "graphifyy[anthropic]"` |
|
||||
| `bedrock` | AWS Bedrock (از IAM استفاده میکند) | `uv tool install "graphifyy[bedrock]"` |
|
||||
| `sql` | استخراج طرح SQL | `uv tool install "graphifyy[sql]"` |
|
||||
| `all` | همه موارد بالا | `uv tool install "graphifyy[all]"` |
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## دستیار را همیشه از گراف استفاده کنید
|
||||
|
||||
پس از ساخت گراف، یک بار در پروژهتان اجرا کنید:
|
||||
|
||||
</div>
|
||||
|
||||
| پلتفرم | دستور |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| CodeBuddy | `graphify codebuddy install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Kilo Code | `graphify kilo install` |
|
||||
| GitHub Copilot CLI | `graphify copilot install` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify aider install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
این یک فایل پیکربندی کوچک مینویسد که به دستیارتان میگوید برای سؤالات مربوط به کدبیس، گراف دانش را مشورت بگیرد. برای حذف graphify از همه پلتفرمها به یکباره: `graphify uninstall` (با `--purge` برای حذف `graphify-out/` نیز).
|
||||
|
||||
---
|
||||
|
||||
## محتوای گزارش
|
||||
|
||||
- **گرههای اصلی** — پرارتباطترین مفاهیم پروژه. همه چیز از اینها عبور میکند.
|
||||
- **اتصالات شگفتانگیز** — پیوندهایی بین چیزهایی که در فایلها یا ماژولهای مختلف زندگی میکنند. بر اساس میزان غیرمنتظره بودن رتبهبندی شده.
|
||||
- **«چرا»** — نظرات درونخطی (`# NOTE:`، `# WHY:`، `# HACK:`)، داکاسترینگها و منطق طراحی از اسناد بهعنوان گرههای جداگانه مرتبط با کدی که توضیح میدهند استخراج میشوند.
|
||||
- **سؤالات پیشنهادی** — ۴ تا ۵ سؤال که گراف بهطور منحصربهفرد میتواند پاسخ دهد.
|
||||
- **برچسبهای اطمینان** — هر رابطه استنباطشده با `EXTRACTED`، `INFERRED` یا `AMBIGUOUS` علامتگذاری میشود. همیشه میدانید چه چیزی پیدا شده در برابر چه چیزی حدس زده شده.
|
||||
|
||||
---
|
||||
|
||||
## فایلهای پشتیبانیشده
|
||||
|
||||
</div>
|
||||
|
||||
| نوع | پسوندها |
|
||||
|------|-----------|
|
||||
| کد (۳۶ دستور زبان tree-sitter) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .vue .svelte .dart` و بیشتر |
|
||||
| اسناد | `.md .mdx .html .txt .rst .yaml .yml` |
|
||||
| Office | `.docx .xlsx` (نیاز به `graphifyy[office]`) |
|
||||
| PDF | `.pdf` |
|
||||
| تصاویر | `.png .jpg .webp .gif` |
|
||||
| ویدئو / صوت | `.mp4 .mov .mp3 .wav` و بیشتر (نیاز به `graphifyy[video]`) |
|
||||
| YouTube / URLها | هر URL ویدئویی (نیاز به `graphifyy[video]`) |
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
کد بهصورت محلی با tree-sitter بدون هیچ فراخوانی API استخراج میشود. بقیه از طریق API مدل دستیار هوش مصنوعی شما پردازش میشوند.
|
||||
|
||||
---
|
||||
|
||||
## دستورات رایج
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
/graphify . # ساخت گراف برای پوشه جاری
|
||||
/graphify ./docs --update # فقط فایلهای تغییریافته را مجدداً استخراج کن
|
||||
/graphify . --cluster-only # خوشهبندی مجدد بدون استخراج مجدد
|
||||
/graphify . --no-viz # فقط گزارش + JSON، بدون HTML
|
||||
/graphify . --wiki # ساخت ویکی مارکداون از گراف
|
||||
graphify export callflow-html # HTML معماری/جریان فراخوانی Mermaid
|
||||
|
||||
/graphify query "چه چیزی auth را به پایگاه داده متصل میکند؟"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
/graphify explain "RateLimiter"
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # یک مقاله را واکشی و اضافه کن
|
||||
/graphify add <youtube-url> # رونویسی و اضافه کردن ویدئو
|
||||
|
||||
graphify hook install # بازسازی خودکار پس از هر commit
|
||||
graphify merge-graphs a.json b.json # ترکیب دو گراف
|
||||
|
||||
graphify prs # داشبورد PR: وضعیت CI، بررسی، تأثیر گراف
|
||||
graphify prs 42 # بررسی عمیق PR شماره ۴۲
|
||||
graphify prs --triage # رتبهبندی صف بررسی با هوش مصنوعی
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
[مرجع کامل دستورات](#full-command-reference) را ببینید.
|
||||
|
||||
---
|
||||
|
||||
## نادیده گرفتن فایلها
|
||||
|
||||
یک `.graphifyignore` در ریشه پروژه بسازید — همان سینتکس `.gitignore`، از جمله نفی با `!`.
|
||||
|
||||
**`.gitignore` بهطور خودکار رعایت میشود.** اگر `.graphifyignore` در یک دایرکتوری وجود نداشته باشد، graphify به `.gitignore` آن دایرکتوری بازمیگردد.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
|
||||
# فقط src/ را ایندکس کن، بقیه را نادیده بگیر
|
||||
*
|
||||
!src/
|
||||
!src/**
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## تنظیمات تیمی
|
||||
|
||||
`graphify-out/` برای commit شدن در git طراحی شده تا همه در تیم با یک نقشه شروع کنند.
|
||||
|
||||
**افزودنهای پیشنهادی به `.gitignore`:**
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
graphify-out/cost.json # فقط محلی
|
||||
# graphify-out/cache/ # اختیاری: برای سرعت commit کنید، برای کوچک نگه داشتن repo حذف کنید
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**جریان کار:**
|
||||
۱. یک نفر `/graphify .` اجرا میکند و `graphify-out/` را commit میکند.
|
||||
۲. همه pull میکنند — دستیارشان فوراً گراف را میخواند.
|
||||
۳. `graphify hook install` را اجرا کنید تا پس از هر commit بهطور خودکار بازسازی شود.
|
||||
۴. وقتی اسناد یا مقالات تغییر کردند، `/graphify --update` اجرا کنید.
|
||||
|
||||
---
|
||||
|
||||
## استفاده مستقیم از گراف
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# پرسوجو از گراف در ترمینال
|
||||
graphify query "جریان احراز هویت را نشان بده"
|
||||
graphify query "چه چیزی DigestAuth را به Response متصل میکند؟" --graph graphify-out/graph.json
|
||||
|
||||
# نمایش گراف بهعنوان سرور MCP
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
|
||||
# یا سرویسدهی از طریق HTTP برای دسترسی تیمی:
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
سرور MCP دسترسی ساختاریافته میدهد: `query_graph`، `get_node`، `get_neighbors`، `shortest_path`، `list_prs`، `get_pr_impact`، `triage_prs`.
|
||||
|
||||
---
|
||||
|
||||
## متغیرهای محیطی
|
||||
|
||||
اینها فقط برای **استخراج بدون نمایشگر / CI** (`graphify extract`) لازم هستند. هنگام اجرا از طریق مهارت `/graphify` داخل IDE، API مدل توسط جلسه IDE شما تأمین میشود.
|
||||
|
||||
</div>
|
||||
|
||||
| متغیر | استفاده | شرط لزوم |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | بکاند Claude (Anthropic) | `--backend claude` |
|
||||
| `GEMINI_API_KEY` یا `GOOGLE_API_KEY` | بکاند Google Gemini | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI یا APIهای سازگار | `--backend openai` |
|
||||
| `DEEPSEEK_API_KEY` | بکاند DeepSeek | `--backend deepseek` |
|
||||
| `MOONSHOT_API_KEY` | بکاند Kimi Code | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | URL استنتاج محلی Ollama | `--backend ollama` |
|
||||
| `AZURE_OPENAI_API_KEY` | بکاند Azure OpenAI | `--backend azure` |
|
||||
| `GRAPHIFY_MAX_WORKERS` | تعداد thread های موازی AST | اختیاری |
|
||||
| `GRAPHIFY_FORCE` | بازسازی اجباری گراف | اختیاری |
|
||||
| `GRAPHIFY_QUERY_LOG_DISABLE` | برای غیرفعال کردن ثبت پرسوجو `1` تنظیم کنید | اختیاری |
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## حریم خصوصی
|
||||
|
||||
- **فایلهای کد** — بهصورت محلی از طریق tree-sitter پردازش میشوند. هیچ چیزی دستگاه شما را ترک نمیکند.
|
||||
- **ویدئو / صوت** — بهصورت محلی با faster-whisper رونویسی میشوند. هیچ چیزی دستگاه شما را ترک نمیکند.
|
||||
- **اسناد، PDFها، تصاویر** — برای استخراج معنایی به API مدل دستیار هوش مصنوعی شما ارسال میشوند.
|
||||
- بدون تلهمتری، بدون ردیابی استفاده، بدون آنالیتیکس.
|
||||
|
||||
---
|
||||
|
||||
## عیبیابی
|
||||
|
||||
**`graphify: command not found` پس از `pip install graphifyy`**
|
||||
pip اسکریپتها را در دایرکتوری bin کاربر نصب میکند که ممکن است در PATH نباشد:
|
||||
- macOS: `~/Library/Python/3.x/bin` را به PATH در `~/.zshrc` اضافه کنید
|
||||
- Linux: `~/.local/bin` را به PATH در `~/.bashrc` اضافه کنید
|
||||
- یا از `uv tool install graphifyy` / `pipx install graphifyy` استفاده کنید.
|
||||
|
||||
**`/graphify .` در PowerShell "path not recognized" نشان میدهد**
|
||||
PowerShell `/` ابتدایی را بهعنوان جداکننده مسیر در نظر میگیرد. از `graphify .` (بدون اسلش) در Windows استفاده کنید.
|
||||
|
||||
**گراف پس از `--update` یا بازسازی گره کمتری دارد**
|
||||
اگر یک refactor فایلها را حذف کرده، گرههای قدیمی باقی میمانند. `--force` (یا `GRAPHIFY_FORCE=1`) را پاس دهید:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify extract . --force
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**استخراج برای اسناد یا PDFها گره/یال خالی برمیگرداند**
|
||||
اسناد، PDFها و تصاویر به یک فراخوانی LLM نیاز دارند. بررسی کنید API key تنظیم شده و بکاند صحیح است:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## مرجع کامل دستورات
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify # اجرا روی دایرکتوری جاری
|
||||
/graphify ./raw # اجرا روی پوشه مشخص
|
||||
/graphify ./raw --mode deep # استخراج رابطههای عمیقتر
|
||||
/graphify ./raw --update # فقط فایلهای تغییریافته را مجدداً استخراج کن
|
||||
/graphify ./raw --directed # حفظ جهت یالها
|
||||
/graphify ./raw --cluster-only # خوشهبندی مجدد روی گراف موجود
|
||||
/graphify ./raw --no-viz # بدون HTML بصریسازی
|
||||
/graphify ./raw --obsidian # تولید Obsidian vault
|
||||
/graphify ./raw --wiki # ساخت ویکی مارکداون قابل خزیدن برای agent
|
||||
/graphify ./raw --svg # خروجی graph.svg
|
||||
/graphify ./raw --graphml # خروجی برای Gephi / yEd
|
||||
/graphify ./raw --neo4j # تولید cypher.txt برای Neo4j
|
||||
/graphify ./raw --watch # همگامسازی خودکار با تغییر فایلها
|
||||
/graphify ./raw --mcp # شروع سرور MCP stdio
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762
|
||||
/graphify add <video-url>
|
||||
|
||||
/graphify query "چه چیزی attention را به optimizer متصل میکند؟"
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify uninstall # حذف از همه پلتفرمها
|
||||
graphify uninstall --purge # همچنین graphify-out/ را حذف کن
|
||||
|
||||
graphify hook install # hook های post-commit + post-checkout
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
|
||||
graphify codex install # AGENTS.md + PreToolUse hook (Codex)
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
|
||||
graphify amp install # فایل مهارت (Amp)
|
||||
graphify kiro install # .kiro/skills/ + .kiro/steering/ (Kiro)
|
||||
graphify devin install # فایل مهارت + .windsurf/rules/ (Devin CLI)
|
||||
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
|
||||
|
||||
graphify extract ./docs # استخراج بدون نمایشگر برای CI
|
||||
graphify extract ./docs --backend gemini # بکاند صریح
|
||||
graphify extract ./docs --backend ollama # Ollama محلی - بدون نیاز به API key
|
||||
graphify extract ./docs --backend bedrock # AWS Bedrock از طریق IAM
|
||||
graphify extract --postgres "postgresql://user:pass@host/db" # طرح PostgreSQL زنده
|
||||
|
||||
graphify prs # داشبورد PR
|
||||
graphify prs 42 # بررسی عمیق PR شماره ۴۲
|
||||
graphify prs --triage # رتبهبندی هوش مصنوعی
|
||||
graphify prs --conflicts # PR هایی که جوامع گراف را به اشتراک میگذارند
|
||||
|
||||
graphify export callflow-html # HTML معماری/جریان فراخوانی
|
||||
graphify merge-graphs a.json b.json --out merged.json
|
||||
graphify --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## بیشتر بدانید
|
||||
|
||||
- [نحوه عملکرد](../../docs/how-it-works.md) — پایپلاین استخراج، تشخیص جامعه، امتیازدهی اطمینان، معیارها
|
||||
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — تقسیمبندی ماژولها، نحوه اضافه کردن زبان جدید
|
||||
- [یکپارچهسازیهای اختیاری](../../docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
|
||||
|
||||
---
|
||||
|
||||
## ساختهشده روی graphify — Penpax
|
||||
|
||||
[**Penpax**](https://graphify.com) لایه همیشهروشن ساختهشده روی graphify است — همان رویکرد گراف را بر کل زندگی کاری شما اعمال میکند: جلسات، تاریخچه مرورگر، ایمیلها، فایلها و کد، بهصورت مداوم در پسزمینه بهروزرسانی میشود.
|
||||
|
||||
ساختهشده برای کسانی که کارشان در صدها مکالمه و سند پراکنده است. بدون ابر، کاملاً روی دستگاه.
|
||||
|
||||
**آزمایش رایگان بهزودی راهاندازی میشود.** [به لیست انتظار بپیوندید ←](https://graphify.com)
|
||||
|
||||
---
|
||||
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary>مشارکت در پروژه</summary>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### راهاندازی محیط توسعه
|
||||
|
||||
این پروژه از [uv](https://docs.astral.sh/uv/) برای جریان کار توسعه استفاده میکند. یک بار آن را نصب کنید، سپس:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
git clone https://github.com/safishamsi/graphify.git
|
||||
cd graphify
|
||||
git checkout v8 # شاخه توسعه فعال
|
||||
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### اجرای تستها
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
uv run pytest tests/ -q # اجرای کل مجموعه
|
||||
uv run pytest tests/test_extract.py -q # یک ماژول
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### جریان کار Git
|
||||
|
||||
- توسعه فعال روی شاخه `v8` انجام میشود.
|
||||
- سبک commit: `fix: <توضیح>` / `feat: <توضیح>` / `docs: <توضیح>`
|
||||
- قبل از باز کردن PR، `uv run pytest tests/ -q` اجرا کنید و از موفقیت آن مطمئن شوید.
|
||||
|
||||
### چه چیزی مشارکت کنیم
|
||||
|
||||
**نمونههای کاری** مفیدترین نوع مشارکت هستند. `/graphify` را روی یک corpus واقعی اجرا کنید، خروجی را در `worked/{slug}/` ذخیره کنید، یک `review.md` صادقانه بنویسید که چه چیزهایی درست و نادرست بوده، و یک PR باز کنید.
|
||||
|
||||
**باگهای استخراج** — یک issue با فایل ورودی، آیتم کش (`graphify-out/cache/`) و آنچه اشتباه یا حذف شده باز کنید.
|
||||
|
||||
برای مسئولیتهای ماژول و نحوه اضافه کردن زبان جدید [ARCHITECTURE.md](../../ARCHITECTURE.md) را ببینید.
|
||||
|
||||
</div>
|
||||
|
||||
</details>
|
||||
@@ -72,6 +72,6 @@ Ang mga code file ay prinoseso nang lokal sa pamamagitan ng tree-sitter AST. Ang
|
||||
|
||||
## Binuo sa ibabaw ng graphify — Penpax
|
||||
|
||||
Ang [**Penpax**](https://graphify.com) ay ang enterprise layer sa ibabaw ng graphify. **Malapit nang magkaroon ng libreng trial.** [Sumali sa waitlist →](https://graphify.com)
|
||||
Ang [**Penpax**](https://graphifylabs.ai) ay ang enterprise layer sa ibabaw ng graphify. **Malapit nang magkaroon ng libreng trial.** [Sumali sa waitlist →](https://graphifylabs.ai)
|
||||
|
||||
[](https://star-history.com/#safishamsi/graphify&Date)
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
**Une compétence pour assistant de code IA.** Tapez `/graphify` dans Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — il lit vos fichiers, construit un graphe de connaissances et vous révèle une structure que vous ne voyiez pas auparavant. Comprenez une base de code plus rapidement. Trouvez le « pourquoi » derrière les décisions architecturales.
|
||||
|
||||
@@ -1,849 +0,0 @@
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
🇺🇸 <a href="../../README.md">English</a> | 🇨🇳 <a href="README.zh-CN.md">简体中文</a> | 🇯🇵 <a href="README.ja-JP.md">日本語</a> | 🇰🇷 <a href="README.ko-KR.md">한국어</a> | 🇩🇪 <a href="README.de-DE.md">Deutsch</a> | 🇫🇷 <a href="README.fr-FR.md">Français</a> | 🇪🇸 <a href="README.es-ES.md">Español</a> | 🇮🇳 <a href="README.hi-IN.md">हिन्दी</a> | 🇧🇷 <a href="README.pt-BR.md">Português</a> | 🇷🇺 <a href="README.ru-RU.md">Русский</a> | 🇸🇦 <a href="README.ar-SA.md">العربية</a> | 🇮🇷 <a href="README.fa-IR.md">فارسی</a> | 🇮🇹 <a href="README.it-IT.md">Italiano</a> | 🇵🇱 <a href="README.pl-PL.md">Polski</a> | 🇳🇱 <a href="README.nl-NL.md">Nederlands</a> | 🇹🇷 <a href="README.tr-TR.md">Türkçe</a> | 🇺🇦 <a href="README.uk-UA.md">Українська</a> | 🇻🇳 <a href="README.vi-VN.md">Tiếng Việt</a> | 🇮🇩 <a href="README.id-ID.md">Bahasa Indonesia</a> | 🇸🇪 <a href="README.sv-SE.md">Svenska</a> | 🇬🇷 <a href="README.el-GR.md">Ελληνικά</a> | 🇷🇴 <a href="README.ro-RO.md">Română</a> | 🇨🇿 <a href="README.cs-CZ.md">Čeština</a> | 🇫🇮 <a href="README.fi-FI.md">Suomi</a> | 🇩🇰 <a href="README.da-DK.md">Dansk</a> | 🇳🇴 <a href="README.no-NO.md">Norsk</a> | 🇭🇺 <a href="README.hu-HU.md">Magyar</a> | 🇹🇭 <a href="README.th-TH.md">ภาษาไทย</a> | 🇺🇿 <a href="README.uz-UZ.md">Oʻzbekcha</a> | 🇹🇼 <a href="README.zh-TW.md">繁體中文</a> | 🇵🇭 <a href="README.fil-PH.md">Filipino</a> | 🇮🇱 <a href="README.he-IL.md">עברית</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.ycombinator.com/companies/graphify"><img src="https://img.shields.io/badge/Y%20Combinator-S26-F0652F?style=flat&logo=ycombinator&logoColor=white" alt="YC S26"/></a>
|
||||
<a href="https://discord.gg/598Ad9zQZ"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
|
||||
<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=v8" 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://img.shields.io/pepy/dt/graphifyy?color=blue&label=downloads" 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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-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>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://star-history.com/#safishamsi/graphify&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
הקלידו `/graphify` בעוזר ה-AI לכתיבת קוד שלכם, והוא ימפה את הפרויקט כולו — קוד, מסמכים, קובצי PDF, תמונות, סרטונים — לגרף ידע שאפשר לשאול עליו שאלות, במקום לחפש בקבצים עם grep.
|
||||
|
||||
עובד ב-Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, Devin CLI ו-Google Antigravity.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify .
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
זה הכול. מקבלים שלושה קבצים:
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
graphify-out/
|
||||
├── graph.html נפתח בכל דפדפן — לחיצה על צמתים, סינון, חיפוש
|
||||
├── GRAPH_REPORT.md עיקרי הדברים: מושגי מפתח, קשרים מפתיעים, שאלות מוצעות
|
||||
└── graph.json הגרף המלא — אפשר לשאול עליו בכל רגע בלי לקרוא שוב את הקבצים
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
לדף ארכיטקטורה קריא עם דיאגרמות זרימת-קריאות ב-Mermaid, הריצו:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify export callflow-html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## דרישות מקדימות
|
||||
|
||||
| דרישה | מינימום | בדיקה | התקנה |
|
||||
|---|---|---|---|
|
||||
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
|
||||
| uv *(מומלץ)* | כל גרסה | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
|
||||
| pipx *(חלופה)* | כל גרסה | `pipx --version` | `pip install pipx` |
|
||||
|
||||
**התקנה מהירה ב-macOS (עם Homebrew):**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
brew install python@3.12 uv
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**התקנה מהירה ב-Windows:**
|
||||
|
||||
</div>
|
||||
|
||||
```powershell
|
||||
winget install astral-sh.uv
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**Ubuntu/Debian:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
sudo apt install python3.12 python3-pip pipx
|
||||
# או התקנת uv:
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
## התקנה
|
||||
|
||||
> **החבילה הרשמית:** חבילת ה-PyPI היא `graphifyy` (עם y כפולה). חבילות `graphify*` אחרות ב-PyPI אינן קשורות לפרויקט. פקודת ה-CLI היא עדיין `graphify`.
|
||||
|
||||
**שלב 1 — התקנת החבילה:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# מומלץ (סביבה מבודדת; אם הפקודה 'graphify' לא נמצאת אחר כך, הריצו: uv tool update-shell):
|
||||
uv tool install graphifyy
|
||||
|
||||
# חלופות:
|
||||
pipx install graphifyy
|
||||
pip install graphifyy # עשוי לדרוש הגדרת PATH — ראו הערה בהמשך
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**שלב 2 — רישום המיומנות (skill) אצל עוזר ה-AI שלכם:**
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify install
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
זהו. פתחו את עוזר ה-AI והקלידו `/graphify .`
|
||||
|
||||
כדי להתקין את המיומנות בתוך המאגר הנוכחי במקום בפרופיל המשתמש, הוסיפו `--project`:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify install --project
|
||||
graphify install --project --platform codex
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
התקנה ברמת הפרויקט כותבת לתוך התיקייה הנוכחית, למשל `.claude/skills/graphify/SKILL.md` או `.agents/skills/graphify/SKILL.md` (בתוספת תיקיית `references/` שהמיומנות טוענת לפי הצורך), ומדפיסה רמז `git add` לקבצים שאפשר לבצע להם commit. פקודות פר-פלטפורמה שתומכות בהתקנה ברמת הפרויקט מקבלות את אותו דגל, למשל `graphify claude install --project` או `graphify codex install --project`.
|
||||
|
||||
> **הערת PowerShell:** השתמשו ב-`graphify .` ולא ב-`/graphify .` — הלוכסן המוביל הוא מפריד נתיבים ב-PowerShell.
|
||||
|
||||
> **`graphify: command not found`?** `uv tool install` / `pipx install` מציבים את פקודת `graphify` בתיקיית הכלים שלהם (`~/.local/bin`). אם המעטפת (shell) לא מוצאת אותה מיד אחרי ההתקנה — נפוץ בהתקנת macOS + zsh טרייה — התיקייה הזו עדיין לא ב-`PATH`: הריצו `uv tool update-shell` (או `pipx ensurepath`) ופתחו טרמינל חדש. עם `pip` רגיל, הוסיפו את `~/.local/bin` (בלינוקס) או `~/Library/Python/3.x/bin` (במק) ל-PATH, או הריצו `python -m graphify`.
|
||||
|
||||
> **מריצים עם `uvx` / `uv tool run` בלי להתקין?** ציינו את שם החבילה, לא את שם הפקודה: `uvx --from graphifyy graphify install`. `uvx graphify …` רגיל נכשל (`No solution found … no versions of graphify`) כי `uv tool run` קורא את המילה הראשונה כשם *חבילה*, והחבילה היא `graphifyy` — פקודת `graphify` נמצאת בתוכה.
|
||||
|
||||
> **הימנעו מ-`pip install` במק/Windows** אם אפשר. המיומנות מאתרת את Python בזמן ריצה מתוך `graphify-out/.graphify_python`; אם הוא מצביע על סביבה שונה מזו שבה `pip` התקין את החבילה, תקבלו `ModuleNotFoundError: No module named 'graphify'`. `uv tool install` ו-`pipx install` מבודדים את החבילה בסביבה משלהם ונמנעים מהבעיה לחלוטין.
|
||||
|
||||
> **הוקים של Git עם uv tool / pipx:** `graphify hook install` מטמיע את נתיב המפרש הנוכחי ישירות בסקריפטי ההוק בזמן ההתקנה, כך שהוק ה-post-commit יופעל כראוי גם בלקוחות Git גרפיים וב-CI שבהם `~/.local/bin` אינו ב-PATH. אם התקנתם מחדש או שדרגתם את graphify, הריצו שוב `graphify hook install` כדי לרענן את הנתיב המוטמע.
|
||||
|
||||
### בחרו את הפלטפורמה שלכם
|
||||
|
||||
| פלטפורמה | פקודת התקנה |
|
||||
|----------|----------------|
|
||||
| Claude Code (לינוקס/מק) | `graphify install` |
|
||||
| Claude Code (Windows) | `graphify install` (זיהוי אוטומטי) או `graphify install --platform windows` |
|
||||
| CodeBuddy | `graphify install --platform codebuddy` |
|
||||
| Codex | `graphify install --platform codex` |
|
||||
| OpenCode | `graphify install --platform opencode` |
|
||||
| Kilo Code | `graphify install --platform kilo` |
|
||||
| GitHub Copilot CLI | `graphify install --platform copilot` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify install --platform aider` |
|
||||
| OpenClaw | `graphify install --platform claw` |
|
||||
| Factory Droid | `graphify install --platform droid` |
|
||||
| Trae | `graphify install --platform trae` |
|
||||
| Trae CN | `graphify install --platform trae-cn` |
|
||||
| Gemini CLI | `graphify install --platform gemini` |
|
||||
| Hermes | `graphify install --platform hermes` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Agent Skills (חוצה-פלטפורמות) | `graphify install --platform agents` (כינוי: `--platform skills`) |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify install --platform pi` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
משתמשי Codex צריכים גם `multi_agent = true` תחת `[features]` בקובץ `~/.codex/config.toml` לצורך חילוץ מקבילי. CodeBuddy משתמש באותו מנגנון Agent tool והוק PreToolUse כמו Claude Code. Factory Droid משתמש בכלי `Task` לשיגור תת-סוכנים במקביל. OpenClaw ו-Aider משתמשים בחילוץ טורי (תמיכה בסוכנים מקביליים עדיין מוקדמת בפלטפורמות אלו). Trae משתמש ב-Agent tool לשיגור תת-סוכנים במקביל ו**אינו** תומך בהוקים מסוג PreToolUse — AGENTS.md הוא המנגנון הקבוע שם.
|
||||
|
||||
`--platform agents` (כינוי: `--platform skills`) מכוון למיקומים הגנריים חוצי-הפלטפורמות של [Agent-Skills](https://github.com/anthropics/skills): `~/.agents/skills/` הגלובלי של המשתמש (נקרא על ידי `npx skills` ומסגרות תואמות-מפרט) בהתקנה גלובלית, ו-`./.agents/skills/` בהתקנת פרויקט (`--project`). `graphify install` החשוף נשאר חד-פלטפורמי (Claude Code) בכוונה — השתמשו בפלטפורמת `agents` כשתרצו שהמיומנות תהיה זמינה לכל מסגרת שקוראת `.agents/skills`.
|
||||
|
||||
> Codex משתמש ב-`$graphify` במקום `/graphify`.
|
||||
|
||||
### תוספים אופציונליים
|
||||
|
||||
התקינו רק מה שצריך:
|
||||
|
||||
| תוסף | מה הוא מוסיף | התקנה |
|
||||
|---|---|---|
|
||||
| `pdf` | חילוץ PDF | `uv tool install "graphifyy[pdf]"` |
|
||||
| `office` | תמיכה ב-`.docx` ו-`.xlsx` | `uv tool install "graphifyy[office]"` |
|
||||
| `google` | רינדור Google Sheets | `uv tool install "graphifyy[google]"` |
|
||||
| `video` | תמלול וידאו/אודיו (faster-whisper + yt-dlp) | `uv tool install "graphifyy[video]"` |
|
||||
| `mcp` | שרת MCP stdio | `uv tool install "graphifyy[mcp]"` |
|
||||
| `neo4j` | דחיפה ל-Neo4j | `uv tool install "graphifyy[neo4j]"` |
|
||||
| `falkordb` | דחיפה ל-FalkorDB | `uv tool install "graphifyy[falkordb]"` |
|
||||
| `svg` | ייצוא גרף ל-SVG | `uv tool install "graphifyy[svg]"` |
|
||||
| `leiden` | זיהוי קהילות Leiden (Python < 3.13 בלבד) | `uv tool install "graphifyy[leiden]"` |
|
||||
| `ollama` | הרצה מקומית עם Ollama | `uv tool install "graphifyy[ollama]"` |
|
||||
| `openai` | OpenAI / ממשקי API תואמי-OpenAI | `uv tool install "graphifyy[openai]"` |
|
||||
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
|
||||
| `anthropic` | Anthropic Claude API (`--backend claude`, משתמש ב-`ANTHROPIC_API_KEY`) | `uv tool install "graphifyy[anthropic]"` |
|
||||
| `bedrock` | AWS Bedrock (משתמש ב-IAM, ללא מפתח API) | `uv tool install "graphifyy[bedrock]"` |
|
||||
| `azure` | Azure OpenAI Service (`--backend azure`, משתמש ב-`AZURE_OPENAI_API_KEY` + `AZURE_OPENAI_ENDPOINT`) | `uv tool install "graphifyy[openai]"` |
|
||||
| `sql` | חילוץ סכמות SQL | `uv tool install "graphifyy[sql]"` |
|
||||
| `postgres` | אינטרוספקציה של PostgreSQL חי (`--postgres DSN`) | `uv tool install "graphifyy[postgres]"` |
|
||||
| `dm` | חילוץ AST של BYOND DreamMaker `.dm`/`.dme` (עשוי לדרוש קומפיילר C + `python3-dev` אם אין wheel מתאים לפלטפורמה) | `uv tool install "graphifyy[dm]"` |
|
||||
| `terraform` | חילוץ AST של Terraform / HCL `.tf`/`.tfvars`/`.hcl` | `uv tool install "graphifyy[terraform]"` |
|
||||
| `chinese` | פילוח שאילתות בסינית (jieba) | `uv tool install "graphifyy[chinese]"` |
|
||||
| `all` | כל מה שלמעלה | `uv tool install "graphifyy[all]"` |
|
||||
|
||||
---
|
||||
|
||||
## גרמו לעוזר שלכם להשתמש בגרף תמיד
|
||||
|
||||
הריצו פעם אחת בפרויקט אחרי בניית גרף:
|
||||
|
||||
| פלטפורמה | פקודה |
|
||||
|----------|---------|
|
||||
| Claude Code | `graphify claude install` |
|
||||
| CodeBuddy | `graphify codebuddy install` |
|
||||
| Codex | `graphify codex install` |
|
||||
| OpenCode | `graphify opencode install` |
|
||||
| Kilo Code | `graphify kilo install` |
|
||||
| GitHub Copilot CLI | `graphify copilot install` |
|
||||
| VS Code Copilot Chat | `graphify vscode install` |
|
||||
| Aider | `graphify aider install` |
|
||||
| OpenClaw | `graphify claw install` |
|
||||
| Factory Droid | `graphify droid install` |
|
||||
| Trae | `graphify trae install` |
|
||||
| Trae CN | `graphify trae-cn install` |
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Gemini CLI | `graphify gemini install` |
|
||||
| Hermes | `graphify hermes install` |
|
||||
| Kimi Code | `graphify install --platform kimi` |
|
||||
| Amp | `graphify amp install` |
|
||||
| Agent Skills (חוצה-פלטפורמות) | `graphify agents install` (כינוי: `graphify skills install`) |
|
||||
| Kiro IDE/CLI | `graphify kiro install` |
|
||||
| Pi coding agent | `graphify pi install` |
|
||||
| Devin CLI | `graphify devin install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
הפקודה כותבת קובץ תצורה קטן שמנחה את העוזר שלכם להתייעץ עם גרף הידע בשאלות על בסיס הקוד — ולהעדיף שאילתות ממוקדות כמו `graphify query "<שאלה>"` על פני קריאת הדוח המלא או grep על קבצים גולמיים. בפלטפורמות שתומכות בהוקים נושאי-מטען (Claude Code, Gemini CLI), הוק מופעל אוטומטית לפני קריאות כלי בסגנון חיפוש (וב-Claude Code גם לפני קריאת קובצי מקור אחד-אחד דרך הכלים Read/Glob) ומכוון את העוזר לנתיב הגרף. באחרות (Codex, OpenCode, Cursor וכו'), קובצי ההנחיות הקבועים (`AGENTS.md`, `.cursor/rules/` וכו') מספקים את אותה הנחיית "קודם הגרף". `GRAPH_REPORT.md` עדיין זמין לסקירת ארכיטקטורה רחבה.
|
||||
|
||||
**CodeBuddy** עושה את אותם שני דברים כמו Claude Code: כותב קטע `CODEBUDDY.md` שמנחה את CodeBuddy לקרוא את `graphify-out/GRAPH_REPORT.md` לפני מענה על שאלות ארכיטקטורה, ומתקין **הוקים מסוג PreToolUse** (`.codebuddy/settings.json`) שמופעלים לפני פקודות חיפוש ב-Bash וקריאת קבצים, ומכוונים ל-`graphify query` במקום.
|
||||
|
||||
**Codex** כותב ל-`AGENTS.md` וגם מתקין **הוק PreToolUse** ב-`.codex/hooks.json` שמופעל לפני כל קריאת כלי Bash — אותו מנגנון קבוע כמו ב-Claude Code.
|
||||
|
||||
להסרת graphify מכל הפלטפורמות בבת אחת: `graphify uninstall` (הוסיפו `--purge` כדי למחוק גם את `graphify-out/`). או השתמשו בפקודה הפר-פלטפורמית (למשל `graphify claude uninstall`).
|
||||
|
||||
---
|
||||
|
||||
**Kilo Code** מתקין את מיומנות Graphify ל-`~/.config/kilo/skills/graphify/SKILL.md` ופקודת `/graphify` נטיבית ל-`~/.config/kilo/command/graphify.md`. `graphify kilo install` כותב גם `AGENTS.md` וגם **תוסף `tool.execute.before` נטיבי** (`.kilo/plugins/graphify.js` + רישום ב-`.kilo/kilo.json` או `.kilo/kilo.jsonc`) כך ש-Kilo מקבל את אותה התנהגות תזכורת-גרף קבועה דרך תצורת `.kilo` נטיבית.
|
||||
|
||||
**Cursor** כותב `.cursor/rules/graphify.mdc` עם `alwaysApply: true` — Cursor מכליל אותו בכל שיחה אוטומטית, ללא צורך בהוק.
|
||||
|
||||
## מה יש בדוח
|
||||
|
||||
- **צומתי מפתח (God nodes)** — המושגים המקושרים ביותר בפרויקט. הכול עובר דרכם.
|
||||
- **קשרים מפתיעים** — קישורים בין דברים שחיים בקבצים או מודולים שונים. מדורגים לפי מידת ההפתעה.
|
||||
- **ה"למה"** — הערות בקוד (`# NOTE:`, `# WHY:`, `# HACK:`), docstrings ורציונל עיצובי מהמסמכים מחולצים כצמתים נפרדים המקושרים לקוד שהם מסבירים.
|
||||
- **שאלות מוצעות** — 4–5 שאלות שהגרף נמצא בעמדה ייחודית לענות עליהן.
|
||||
- **תגי ביטחון** — כל קשר מוסק מסומן `EXTRACTED`, `INFERRED` או `AMBIGUOUS`. תמיד יודעים מה נמצא ומה נוחש.
|
||||
|
||||
---
|
||||
|
||||
## אילו קבצים הוא מטפל
|
||||
|
||||
| סוג | סיומות |
|
||||
|------|-----------|
|
||||
| קוד (36 דקדוקי tree-sitter) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .cu .cuh .metal .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .psm1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .slnx .csproj .fsproj .vbproj .xaml .razor .cshtml` (`.dm`/`.dme` דורש `uv tool install graphifyy[dm]`; CUDA `.cu`/`.cuh` ו-Metal `.metal` משתמשים בדקדוק C++) |
|
||||
| Salesforce Apex | `.cls .trigger` (מבוסס regex; מחלקות, ממשקים, enums, מתודות, טריגרים, קשתות SOQL/DML) |
|
||||
| Terraform / HCL | `.tf .tfvars .hcl` (דורש `uv tool install graphifyy[terraform]`) |
|
||||
| תצורות MCP | `.mcp.json` `mcp.json` `mcp_servers.json` `claude_desktop_config.json` — מחלץ צומתי שרתים, הפניות לחבילות, דרישות משתני סביבה |
|
||||
| מניפסטים של חבילות | `apm.yml` `pyproject.toml` `go.mod` `pom.xml` — צומת חבילה קנוני אחד לכל חבילה (לפי שם) בתוספת קשתות `depends_on`, כך שחבילה שמופנית מכמה מניפסטים היא מוקד (hub) יחיד |
|
||||
| מסמכים | `.md .mdx .qmd .html .txt .rst .yaml .yml` (קישורי markdown `[text](./other.md)` ו-`[[wikilinks]]` הופכים לקשתות `references` בין מסמכים) |
|
||||
| Office | `.docx .xlsx` (דורש `uv tool install graphifyy[office]`) |
|
||||
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; דורש אימות `gws` ו-`--google-workspace`; Sheets דורש `uv tool install graphifyy[google]`) |
|
||||
| PDF | `.pdf` |
|
||||
| תמונות | `.png .jpg .webp .gif` |
|
||||
| וידאו / אודיו | `.mp4 .mov .mp3 .wav` ועוד (דורש `uv tool install graphifyy[video]`) |
|
||||
| YouTube / כתובות URL | כל כתובת וידאו (דורש `uv tool install graphifyy[video]`) |
|
||||
|
||||
קוד מחולץ מקומית ללא קריאות API (AST באמצעות tree-sitter). כל השאר עובר דרך ה-API של מודל עוזר ה-AI שלכם.
|
||||
|
||||
קובצי `.gdoc`, `.gsheet` ו-`.gslides` של Google Drive לשולחן העבודה הם קיצורי דרך, לא תוכן מסמכים. כדי לכלול מסמכי Google Docs, Sheets ו-Slides נטיביים בחילוץ headless, התקינו ואמתו את [`gws` CLI](https://github.com/googleworkspace/cli), ואז הריצו:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
uv tool install "graphifyy[google]" # נדרש לרינדור טבלאות Google Sheets
|
||||
gws auth login -s drive
|
||||
graphify extract ./docs --google-workspace
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
אפשר גם להגדיר `GRAPHIFY_GOOGLE_WORKSPACE=1`. graphify מייצא קיצורי דרך אל `graphify-out/converted/` כקובצי Markdown נלווים, ואז מחלץ אותם.
|
||||
|
||||
---
|
||||
|
||||
## פקודות נפוצות
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
/graphify . # בניית גרף לתיקייה הנוכחית
|
||||
/graphify ./docs --update # חילוץ מחדש של קבצים שהשתנו בלבד
|
||||
/graphify . --cluster-only # הרצת אשכול מחדש בלי לחלץ מחדש
|
||||
/graphify . --cluster-only --resolution 1.5 # קהילות מפורטות יותר
|
||||
/graphify . --cluster-only --exclude-hubs 99 # הסתרת מוקדי-עזר מדירוג צומתי המפתח
|
||||
/graphify . --no-viz # דילוג על ה-HTML, רק הדוח וה-JSON
|
||||
/graphify . --wiki # בניית ויקי markdown מהגרף
|
||||
graphify export callflow-html # HTML ארכיטקטורה/זרימת-קריאות ב-Mermaid (מתחדש אוטומטית בכל commit אם ההוק מותקן)
|
||||
|
||||
/graphify query "מה מחבר את האימות למסד הנתונים?"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
/graphify explain "RateLimiter"
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762 # הבאת מאמר והוספתו
|
||||
/graphify add <youtube-url> # תמלול והוספת סרטון
|
||||
|
||||
graphify hook install # בנייה מחדש אוטומטית בכל commit
|
||||
graphify merge-graphs a.json b.json # מיזוג שני גרפים
|
||||
|
||||
graphify prs # לוח PR: מצב CI, סטטוס ביקורת, מיפוי worktree
|
||||
graphify prs 42 # צלילה עמוקה ל-PR #42 עם השפעת גרף
|
||||
graphify prs --triage # AI מדרג את תור הביקורות שלכם (משתמש ב-backend המוגדר)
|
||||
graphify prs --conflicts # PRs שחולקים קהילות גרף — סיכון בסדר המיזוג
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
ראו את [רשימת הפקודות המלאה](#רשימת-הפקודות-המלאה) בהמשך.
|
||||
|
||||
---
|
||||
|
||||
## התעלמות מקבצים
|
||||
|
||||
צרו קובץ `.graphifyignore` בשורש הפרויקט — אותו תחביר כמו `.gitignore`, כולל שלילה עם `!`.
|
||||
|
||||
**`.gitignore` נאכף אוטומטית.** graphify קורא את ה-`.gitignore` בכל תיקייה. אם קיים גם `.graphifyignore`, השניים **ממוזגים** — תבניות `.graphifyignore` מוערכות אחרונות, כך שהן גוברות במקרה של התנגשות (כולל שלילות `!`). הוספת `.graphifyignore` רק מחריגה עוד; היא לעולם לא תחזיר קובץ שה-`.gitignore` כבר החריג. תחולת תת-תיקיות עובדת כמו ב-git — קובץ ignore משפיע רק על תת-העץ שלו.
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
# .graphifyignore
|
||||
node_modules/
|
||||
dist/
|
||||
*.generated.py
|
||||
|
||||
# לאנדקס רק את src/, להתעלם מכל השאר
|
||||
*
|
||||
!src/
|
||||
!src/**
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
---
|
||||
|
||||
## עבודת צוות
|
||||
|
||||
`graphify-out/` מיועד להיכנס ל-git כדי שכל חברי הצוות יתחילו עם מפה מוכנה.
|
||||
|
||||
**תוספות מומלצות ל-`.gitignore`:**
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
graphify-out/cost.json # מקומי בלבד
|
||||
# graphify-out/cache/ # אופציונלי: commit למהירות, דילוג לשמירה על ריפו קטן
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> `manifest.json` הוא כעת נייד — המפתחות נשמרים כנתיבים יחסיים ומעוגנים מחדש בטעינה, כך שבטוח לבצע לו commit והדבר חוסך בנייה מלאה מחדש ב-checkout הראשון.
|
||||
|
||||
**תהליך העבודה:**
|
||||
1. אחד מחברי הצוות מריץ `/graphify .` ומבצע commit ל-`graphify-out/`.
|
||||
2. כולם מושכים — העוזר שלהם קורא את הגרף מיד.
|
||||
3. הריצו `graphify hook install` לבנייה אוטומטית מחדש אחרי כל commit (AST בלבד, ללא עלות API). זה גם מגדיר merge driver של git כך ש-`graph.json` לעולם לא יישאר עם סימוני קונפליקט — שני מפתחים שמבצעים commit במקביל מקבלים מיזוג-איחוד אוטומטי של הגרפים.
|
||||
4. כשמסמכים או מאמרים משתנים, הריצו `/graphify --update` לרענון הצמתים הללו.
|
||||
|
||||
---
|
||||
|
||||
## שימוש ישיר בגרף
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
# שאילתת גרף מהטרמינל
|
||||
graphify query "הצג את זרימת האימות"
|
||||
graphify query "מה מחבר בין DigestAuth ל-Response?" --graph graphify-out/graph.json
|
||||
|
||||
# חשיפת הגרף כשרת MCP (לגישת כלים חוזרת)
|
||||
python -m graphify.serve graphify-out/graph.json
|
||||
python -m graphify.serve --graph graphify-out/graph.json # גם הדגל --graph מתקבל
|
||||
|
||||
# רישום ב-Kimi Code:
|
||||
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
|
||||
|
||||
# או הגשה על HTTP כך שכל הצוות מצביע על URL אחד (בלי graphify מקומי):
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --port 8080
|
||||
python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
שרת ה-MCP נותן לעוזר שלכם גישה מובנית: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
|
||||
|
||||
### שרת HTTP משותף
|
||||
|
||||
`--transport stdio` (ברירת המחדל) מריץ שרת מקומי אחד לכל מפתח. `--transport http` מגיש את אותם כלים על גבי MCP Streamable HTTP, כך שתהליך משותף אחד יכול לשרת את הגרף לכל הצוות — הלקוחות מכוונים את תצורת ה-MCP של ה-IDE אל `http://<host>:8080/mcp` במקום להריץ graphify מקומית.
|
||||
|
||||
| דגל | ברירת מחדל | תפקיד |
|
||||
|---|---|---|
|
||||
| `--transport {stdio,http}` | `stdio` | סוג התעבורה |
|
||||
| `--host` | `127.0.0.1` | כתובת ההאזנה ל-HTTP (השתמשו ב-`0.0.0.0` לחשיפה מעבר ל-localhost) |
|
||||
| `--port` | `8080` | פורט ההאזנה |
|
||||
| `--api-key` | משתנה סביבה `GRAPHIFY_API_KEY` | דרישת `Authorization: Bearer <key>` (או `X-API-Key`) |
|
||||
| `--path` | `/mcp` | נתיב העיגון ב-HTTP |
|
||||
| `--json-response` | כבוי | החזרת JSON רגיל במקום זרמי SSE |
|
||||
| `--stateless` | כבוי | ללא מצב פר-סשן (לפריסות מאוזנות-עומס / CI) |
|
||||
| `--session-timeout` | `3600` | ניקוי סשנים לא פעילים אחרי N שניות (`0` מבטל) |
|
||||
|
||||
ברירת המחדל `127.0.0.1` היא loopback בלבד. הגדירו `--host 0.0.0.0` **וגם** `--api-key` יחד כשחושפים על מארח משותף. אפשר להריץ בקונטיינר:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
docker build -t graphify .
|
||||
docker run -p 8080:8080 -v "$(pwd)/graphify-out:/data" graphify \
|
||||
/data/graph.json --transport http --host 0.0.0.0 --api-key "$SECRET"
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> **הערת WSL / לינוקס:** אובונטו מגיעה עם `python3`, לא `python`. השתמשו ב-venv כדי להימנע מהתנגשויות:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
---
|
||||
|
||||
## משתני סביבה
|
||||
|
||||
אלו נדרשים רק ל**חילוץ headless / CI** (`graphify extract`). בהרצה דרך מיומנות `/graphify` בתוך ה-IDE, ה-API של המודל מסופק על ידי סשן ה-IDE — לא נדרשים מפתחות נוספים.
|
||||
|
||||
| משתנה | משמש עבור | מתי נדרש |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | backend של Claude (Anthropic) | `--backend claude` |
|
||||
| `ANTHROPIC_BASE_URL` | כתובת endpoint תואם-Anthropic (פרוקסי LiteLLM, שערים, ...) | `--backend claude` (ברירת מחדל: `https://api.anthropic.com`) |
|
||||
| `ANTHROPIC_MODEL` | שם המודל ל-backend של Claude — ל-endpoints מותאמים, השתמשו בשם/כינוי שהשרת שלכם חושף | `--backend claude` (ברירת מחדל: `claude-sonnet-4-6`) |
|
||||
| `GEMINI_API_KEY` או `GOOGLE_API_KEY` | backend של Google Gemini | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI או ממשקים תואמי-OpenAI | `--backend openai` (שרתים מקומיים מקבלים כל ערך לא ריק) |
|
||||
| `OPENAI_BASE_URL` | כתובת שרת תואם-OpenAI (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (ברירת מחדל: `https://api.openai.com/v1`) |
|
||||
| `OPENAI_MODEL` | שם המודל ל-backend של OpenAI — לשרתים בהרצה עצמית, השתמשו בשם/כינוי שהשרת חושף (בדקו את endpoint ה-`/v1/models` שלו) | `--backend openai` (ברירת מחדל: `gpt-4.1-mini`) |
|
||||
| `DEEPSEEK_API_KEY` | backend של DeepSeek | `--backend deepseek` |
|
||||
| `MOONSHOT_API_KEY` | backend של Kimi Code | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | כתובת הרצה מקומית של Ollama | `--backend ollama` (ברירת מחדל: `http://localhost:11434`) |
|
||||
| `OLLAMA_MODEL` | שם מודל Ollama | `--backend ollama` (ברירת מחדל: זיהוי אוטומטי) |
|
||||
| `GRAPHIFY_OLLAMA_NUM_CTX` | דריסת גודל חלון ה-KV-cache של Ollama | אופציונלי — מותאם אוטומטית כברירת מחדל |
|
||||
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | דקות להשארת מודל Ollama טעון | אופציונלי — `0` לפריקה אחרי כל chunk |
|
||||
| `AZURE_OPENAI_API_KEY` | backend של Azure OpenAI Service | `--backend azure` |
|
||||
| `AZURE_OPENAI_ENDPOINT` | כתובת ה-endpoint של משאב Azure | `--backend azure` (נדרש יחד עם מפתח ה-API) |
|
||||
| `AZURE_OPENAI_API_VERSION` | דריסת גרסת ה-API של Azure | אופציונלי — ברירת מחדל `2024-12-01-preview` |
|
||||
| `AZURE_OPENAI_DEPLOYMENT` או `GRAPHIFY_AZURE_MODEL` | שם הפריסה ב-Azure | אופציונלי — ברירת מחדל `gpt-4o` |
|
||||
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — שרשרת אישורים סטנדרטית | `--backend bedrock` (ללא מפתח API, משתמש ב-IAM) |
|
||||
| `GRAPHIFY_MAX_WORKERS` | מספר threads למקביליות AST | אופציונלי — גם דגל `--max-workers` |
|
||||
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | העלאת תקרת הפלט לקורפוסים צפופים | אופציונלי — למשל `32768` לקבצים גדולים |
|
||||
| `GRAPHIFY_API_TIMEOUT` | timeout לקריאה בשניות עבור HTTP, claude-cli ו-Anthropic SDK (ברירת מחדל: 600) | אופציונלי — גם דגל `--api-timeout` |
|
||||
| `GRAPHIFY_MAX_RETRIES` | מספר ניסיונות חוזרים לבקשה שנחסמה בקצב (429) לפני ויתור (ברירת מחדל: 6; מכבד `Retry-After`) | אופציונלי — העלו למגבלות ארגוניות נוקשות; `0` מבטל |
|
||||
| `GRAPHIFY_FORCE` | כפיית בנייה מחדש של הגרף גם עם פחות צמתים | אופציונלי — גם דגל `--force` |
|
||||
| `GRAPHIFY_GOOGLE_WORKSPACE` | הפעלה אוטומטית של ייצוא Google Workspace | אופציונלי — הגדירו `1` |
|
||||
| `GRAPHIFY_TRIAGE_BACKEND` | backend עבור `graphify prs --triage` | אופציונלי — מזוהה אוטומטית מהמפתחות הזמינים |
|
||||
| `GRAPHIFY_TRIAGE_MODEL` | דריסת מודל לטריאז' | אופציונלי — למשל `claude-opus-4-7` |
|
||||
| `GRAPHIFY_QUERY_LOG` | דריסת נתיב יומן השאילתות (ברירת מחדל: `~/.cache/graphify-queries.log`) | אופציונלי — ערך ריק או `/dev/null` להשתקה |
|
||||
| `GRAPHIFY_QUERY_LOG_DISABLE` | הגדירו `1` לביטול מוחלט של יומן השאילתות | אופציונלי |
|
||||
| `GRAPHIFY_QUERY_LOG_RESPONSES` | הגדירו `1` לרישום גם של תשובות תת-גרף מלאות (כבוי כברירת מחדל) | אופציונלי |
|
||||
| `GRAPHIFY_MAX_GRAPH_BYTES` | דריסת תקרת הגודל של graph.json (512 MiB) — למשל `700MB`, `2GB` או בייטים | אופציונלי — שימושי לקורפוסים גדולים מאוד |
|
||||
| `GRAPHIFY_LLM_TEMPERATURE` | דריסת טמפרטורת ה-LLM לחילוץ סמנטי — למשל `0.7`, או `none` להשמטה | אופציונלי — מושמט אוטומטית למודלי היסק o1/o3/o4/gpt-5 |
|
||||
|
||||
---
|
||||
|
||||
## פרטיות
|
||||
|
||||
- **קובצי קוד** — מעובדים מקומית עם tree-sitter. שום דבר לא עוזב את המחשב. קורפוס של קוד בלבד אינו דורש מפתח API — `graphify extract` רץ לגמרי offline.
|
||||
- **וידאו / אודיו** — מתומלל מקומית עם faster-whisper. שום דבר לא עוזב את המחשב.
|
||||
- **מסמכים, PDF, תמונות** — נשלחים לעוזר ה-AI שלכם לחילוץ סמנטי (דרך מיומנות `/graphify`, עם המודל שסשן ה-IDE שלכם מריץ). `graphify extract` בחילוץ headless דורש `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), `DEEPSEEK_API_KEY` (DeepSeek), מופע Ollama רץ (`OLLAMA_BASE_URL`), אישורי AWS דרך שרשרת הספקים הסטנדרטית (Bedrock — ללא מפתח API, משתמש ב-IAM), או קובץ ההרצה `claude` (Claude Code — ללא מפתח API, משתמש במנוי Claude שלכם). הדגל `--dedup-llm` משתמש באותו מפתח.
|
||||
- **מיקום נתונים (Data residency)** — `graphify extract` מזהה אוטומטית באיזה ספק להשתמש לפי המפתח שמוגדר (עדיפות: Gemini → Kimi → Claude → OpenAI → DeepSeek → Azure → Bedrock → Ollama). לקוד עם דרישות מיקום נתונים, השתמשו ב-`--backend ollama` (מקומי לחלוטין) או העבירו דגל `--backend` מפורש. Kimi (`MOONSHOT_API_KEY`) מנתב לשרתי Moonshot AI בסין.
|
||||
- ללא טלמטריה, ללא מעקב שימוש, ללא אנליטיקה.
|
||||
- **יומן שאילתות** — כל קריאת `graphify query`, `graphify path`, `graphify explain` ו-`query_graph` של MCP נרשמת ל-`~/.cache/graphify-queries.log` בפורמט JSON Lines (חותמת זמן, שאלה, קורפוס, צמתים שהוחזרו, משך). תשובות תת-גרף מלאות **אינן** נשמרות כברירת מחדל. הגדירו `GRAPHIFY_QUERY_LOG_DISABLE=1` לביטול, או `GRAPHIFY_QUERY_LOG=/dev/null` להשתקה בלי לבטל את המנגנון.
|
||||
|
||||
---
|
||||
|
||||
## פתרון בעיות
|
||||
|
||||
**`graphify: command not found` אחרי ההתקנה**
|
||||
ה-CLI מותקן אבל תיקיית ה-bin שלו אינה ב-`PATH` של המעטפת. בחרו את התיקון לפי אופן ההתקנה:
|
||||
- **uv** (`uv tool install graphifyy`): הפקודה מגיעה לתיקיית הכלים של uv (`~/.local/bin`), שהתקנת macOS/zsh טרייה לרוב לא כוללת ב-`PATH`. הריצו `uv tool update-shell` ופתחו טרמינל חדש. (מצאו את התיקייה עם `uv tool dir --bin`.)
|
||||
- **pipx** (`pipx install graphifyy`): הריצו `pipx ensurepath` ופתחו טרמינל חדש.
|
||||
- **pip** (`pip install graphifyy`): pip מתקין סקריפטים לתיקיית bin של המשתמש שאולי אינה ב-`PATH` — הוסיפו את `~/Library/Python/3.x/bin` (macOS) או `~/.local/bin` (לינוקס) ל-`PATH` ב-`~/.zshrc`/`~/.bashrc`, או פשוט הריצו `python -m graphify`.
|
||||
|
||||
**`uvx graphify …` או `uv tool run graphify …` לא מצליחים לפתור את `graphify`**
|
||||
חבילת ה-PyPI היא `graphifyy`; `graphify` הוא רק הפקודה שהיא מספקת. `uv tool run` מתייחס למילה הראשונה כשם *חבילה*, מחפש חבילה בשם `graphify` ומדווח `No solution found … no versions of graphify`. ציינו את החבילה במפורש: `uvx --from graphifyy graphify install` (זהה ל-`uv tool run --from graphifyy graphify install`). או התקינו פעם אחת עם `uv tool install graphifyy` וקראו ל-`graphify` ישירות.
|
||||
|
||||
**`python -m graphify` עובד אבל פקודת `graphify` לא**
|
||||
ה-`PATH` של המעטפת לא כולל את תיקיית ה-bin שאליה הותקנה הפקודה. העדיפו `uv tool install` / `pipx install` על פני `pip` רגיל, ואז הריצו `uv tool update-shell` / `pipx ensurepath` ופתחו טרמינל חדש (ראו הערות ההתקנה לעיל).
|
||||
|
||||
**`/graphify .` גורם ל-"path not recognized" ב-PowerShell**
|
||||
PowerShell מתייחס ל-`/` מוביל כמפריד נתיבים. השתמשו ב-`graphify .` (בלי לוכסן) ב-Windows.
|
||||
|
||||
**לגרף יש פחות צמתים אחרי `--update` או בנייה מחדש**
|
||||
אם refactor מחק קבצים, הצמתים הישנים נשארים. העבירו `--force` (או הגדירו `GRAPHIFY_FORCE=1`) לדריסה גם כשהבנייה החדשה קטנה יותר.
|
||||
|
||||
**לגרף יש צמתים כפולים לאותה ישות (ghost duplicates)**
|
||||
כפילויות רפאים (אותו סימבול מופיע פעמיים — פעם מחילוץ AST עם מיקום מקור, ופעם מחילוץ סמנטי בלעדיו) ממוזגות כעת אוטומטית בזמן הבנייה. אם אתם רואים זאת בגרף שנבנה לפני v0.8.33, הריצו חילוץ מלא מחדש לניקוי:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify extract . --force
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**Ollama נגמר לו ה-VRAM / חריגה מחלון ההקשר**
|
||||
חלון ה-KV-cache מותאם אוטומטית אך עשוי להיות גדול מדי ל-GPU שלכם. הקטינו אותו:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**אזהרות `LLM returned invalid JSON` / `Unterminated string`**
|
||||
תשובת ה-JSON של המודל פגעה במגבלת אסימוני הפלט ונחתכה באמצע מחרוזת. graphify מתאושש אוטומטית (הוא מפצל את ה-chunk ומחלץ מחדש את החצאים, ומסמך יחיד גדול מדי נחתך תחילה בגבולות כותרות/פסקאות כך שהקובץ כולו עדיין מכוסה), כך שהאזהרות רועשות אך אין אובדן נתונים. להפחתת התופעה, העלו את תקרת הפלט או הקטינו את פלט ה-chunk:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=16384 graphify extract . --mode deep # הרמת התקרה
|
||||
graphify extract . --mode deep --token-budget 4000 # קלטים קטנים יותר -> פלט קטן יותר
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
עם שער ענן כמו OpenRouter, העדיפו `--backend openai` (הגדירו `OPENAI_BASE_URL`) על פני שכבת ה-Ollama — זה נתיב תואם-OpenAI נקי יותר. אם למודל יש תקרת פלט משלו, הורדת `--token-budget` היא המנוף האמין.
|
||||
|
||||
**HTML של הגרף גדול מדי לפתיחה בדפדפן (מעל 5000 צמתים)**
|
||||
דלגו על יצירת ה-HTML והשתמשו ב-JSON ישירות:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
graphify cluster-only ./my-project --no-viz
|
||||
graphify query "..."
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**ל-`graph.json` יש סימוני קונפליקט אחרי ששני מפתחים ביצעו commit במקביל**
|
||||
הריצו `graphify hook install` — הוא מגדיר merge driver של git שממזג-מאחד את `graph.json` אוטומטית כך שקונפליקטים לא קורים בכלל.
|
||||
|
||||
**החילוץ מחזיר צמתים/קשתות ריקים למסמכים או PDF**
|
||||
מסמכים, PDF ותמונות דורשים קריאת LLM — קורפוסים של קוד בלבד אינם דורשים מפתח. ודאו שמפתח ה-API מוגדר וה-backend נכון:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
**אזהרת חוסר התאמה בגרסת המיומנות ב-IDE**
|
||||
גרסת graphify המותקנת שונה מקובץ המיומנות. עדכנו:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
uv tool upgrade graphifyy
|
||||
graphify install # דורס את קובץ המיומנות
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
---
|
||||
|
||||
## רשימת הפקודות המלאה
|
||||
|
||||
</div>
|
||||
|
||||
```
|
||||
/graphify # הרצה על התיקייה הנוכחית
|
||||
/graphify ./raw # הרצה על תיקייה מסוימת
|
||||
/graphify ./raw --mode deep # חילוץ קשרים אגרסיבי יותר
|
||||
/graphify ./raw --update # חילוץ מחדש של קבצים שהשתנו בלבד
|
||||
/graphify ./raw --directed # שמירת כיוון הקשתות
|
||||
/graphify ./raw --cluster-only # הרצת אשכול מחדש על גרף קיים
|
||||
/graphify ./raw --no-viz # דילוג על ויזואליזציית HTML
|
||||
/graphify ./raw --obsidian # יצירת כספת Obsidian
|
||||
/graphify ./raw --obsidian --obsidian-dir ~/vault # כתיבה לכספת קיימת (לעולם לא דורס פתקים או תצורת .obsidian שלכם)
|
||||
/graphify ./raw --wiki # בניית ויקי markdown שסוכנים יכולים לסרוק
|
||||
/graphify ./raw --svg # ייצוא graph.svg
|
||||
/graphify ./raw --graphml # ייצוא ל-Gephi / yEd
|
||||
/graphify ./raw --neo4j # יצירת cypher.txt ל-Neo4j
|
||||
/graphify ./raw --neo4j-push bolt://localhost:7687
|
||||
/graphify ./raw --falkordb # יצירת cypher.txt ל-FalkorDB
|
||||
/graphify ./raw --falkordb-push falkordb://localhost:6379
|
||||
/graphify ./raw --watch # סנכרון אוטומטי כשקבצים משתנים
|
||||
/graphify ./raw --mcp # הפעלת שרת MCP stdio
|
||||
|
||||
/graphify add https://arxiv.org/abs/1706.03762
|
||||
/graphify add <video-url>
|
||||
/graphify add https://... --author "Name" --contributor "Name"
|
||||
|
||||
/graphify query "מה מחבר את ה-attention לאופטימייזר?"
|
||||
/graphify query "..." --dfs --budget 1500
|
||||
/graphify path "DigestAuth" "Response"
|
||||
/graphify explain "SwinTransformer"
|
||||
|
||||
graphify save-result --question "Q" --answer "A" --nodes Foo Bar --outcome useful # תיעוד תוצאת שאלה-תשובה (זיכרון עבודה; outcome ∈ useful|dead_end|corrected)
|
||||
graphify reflect # איחוד תוצאות graphify-out/memory/ אל reflections/LESSONS.md
|
||||
graphify reflect --if-stale # לא עושה דבר אם LESSONS.md כבר חדש מכל הקלטים (זול להרצה בכל סשן)
|
||||
graphify reflect --out docs/LESSONS.md # כתיבת מסמך הלקחים למקום אחר
|
||||
graphify reflect --graph graphify-out/graph.json # קיבוץ לקחים לפי קהילה + כתיבת שכבת זיכרון העבודה (.graphify_learning.json)
|
||||
# השכבה מתייגת צמתים preferred/tentative/contested (משוקלל-עדכניות, עם מקור);
|
||||
# graphify explain / query מציגים אז רמז "Lesson:", מסומן "code changed — re-verify" כשהמקור התקדם
|
||||
|
||||
graphify uninstall # הסרה מכל הפלטפורמות במכה אחת
|
||||
graphify uninstall --purge # מחיקה גם של graphify-out/
|
||||
graphify uninstall --project --platform codex # הסרת קובצי התקנה ברמת פרויקט בלבד
|
||||
|
||||
graphify hook install # הוקים של post-commit + post-checkout
|
||||
graphify hook uninstall
|
||||
graphify hook status
|
||||
|
||||
# הנחיות עוזר קבועות - פר פלטפורמה
|
||||
graphify claude install # CLAUDE.md + הוק PreToolUse (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codebuddy install # CODEBUDDY.md + הוק PreToolUse (CodeBuddy)
|
||||
graphify codebuddy uninstall
|
||||
graphify codex install # AGENTS.md + הוק PreToolUse ב-.codex/hooks.json (Codex)
|
||||
graphify opencode install # AGENTS.md + תוסף tool.execute.before (OpenCode)
|
||||
graphify kilo install # מיומנות Kilo נטיבית + פקודת /graphify + AGENTS.md + תוסף .kilo
|
||||
graphify kilo uninstall
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify cursor uninstall
|
||||
graphify gemini install # GEMINI.md + הוק BeforeTool (Gemini CLI)
|
||||
graphify gemini uninstall
|
||||
graphify copilot install # קובץ מיומנות (GitHub Copilot CLI)
|
||||
graphify copilot uninstall
|
||||
graphify aider install # AGENTS.md (Aider)
|
||||
graphify aider uninstall
|
||||
graphify claw install # AGENTS.md (OpenClaw)
|
||||
graphify claw uninstall
|
||||
graphify droid install # AGENTS.md (Factory Droid)
|
||||
graphify droid uninstall
|
||||
graphify trae install # AGENTS.md (Trae)
|
||||
graphify trae uninstall
|
||||
graphify trae-cn install # AGENTS.md (Trae CN)
|
||||
graphify trae-cn uninstall
|
||||
graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
|
||||
graphify hermes uninstall
|
||||
graphify amp install # קובץ מיומנות (Amp)
|
||||
graphify amp uninstall
|
||||
graphify agents install # ~/.agents/skills/ + AGENTS.md (חוצה-פלטפורמות; כינוי: graphify skills)
|
||||
graphify agents uninstall
|
||||
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
|
||||
graphify kiro uninstall
|
||||
graphify pi install # קובץ מיומנות (Pi coding agent)
|
||||
graphify pi uninstall
|
||||
graphify devin install # קובץ מיומנות + .windsurf/rules/graphify.md (Devin CLI)
|
||||
graphify devin uninstall
|
||||
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
|
||||
graphify antigravity uninstall
|
||||
|
||||
graphify extract ./docs # חילוץ LLM headless ל-CI (ללא IDE)
|
||||
graphify extract ./docs --backend gemini # backend מפורש: gemini, kimi, claude, openai, deepseek, ollama, bedrock או claude-cli
|
||||
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
|
||||
graphify extract ./docs --backend ollama # Ollama מקומי (הגדירו OLLAMA_BASE_URL / OLLAMA_MODEL) - ללא מפתח API ל-loopback
|
||||
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # כל שרת תואם-OpenAI (llama.cpp, vLLM, LM Studio)
|
||||
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # כל endpoint תואם-Anthropic (פרוקסי LiteLLM, שערים)
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # דריסת חלון ה-KV-cache (מותאם אוטומטית כברירת מחדל)
|
||||
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # פריקת המודל אחרי כל chunk (חוסך VRAM ב-GPU קטן)
|
||||
graphify extract ./docs --backend bedrock # AWS Bedrock דרך IAM - ללא מפתח API, שרשרת אישורי AWS
|
||||
graphify extract ./docs --backend claude-cli # ניתוב דרך Claude Code CLI - ללא מפתח API, דרך מנוי Claude שלכם
|
||||
graphify extract ./docs --backend azure # Azure OpenAI (הגדירו AZURE_OPENAI_API_KEY + AZURE_OPENAI_ENDPOINT)
|
||||
graphify extract ./docs --max-workers 16 # מקביליות AST (גם GRAPHIFY_MAX_WORKERS)
|
||||
graphify extract --postgres "postgresql://user:pass@host/db" # אינטרוספקציה ישירה של סכמת PostgreSQL חיה
|
||||
graphify extract ./my-workspace --cargo # אינטרוספקציה ישירה של תלויות Cargo workspace ברוסט
|
||||
graphify extract ./docs --token-budget 30000 # chunks סמנטיים קטנים יותר למודלים מקומיים/קטנים
|
||||
graphify extract ./docs --max-concurrency 2 # פחות קריאות LLM מקביליות (שימושי להרצה מקומית)
|
||||
graphify extract ./docs --api-timeout 900 # timeout ארוך יותר למודלים מקומיים איטיים (ברירת מחדל 600 שניות)
|
||||
graphify extract ./docs --google-workspace # ייצוא .gdoc/.gsheet/.gslides דרך gws לפני החילוץ
|
||||
graphify extract ./docs --mode deep # חילוץ סמנטי עשיר יותר עם system prompt מורחב
|
||||
graphify extract ./docs --no-cluster # חילוץ גולמי בלבד, דילוג על אשכול
|
||||
graphify extract ./docs --timing # הדפסת זמני ריצה פר-שלב ל-stderr (עובד גם ב-cluster-only)
|
||||
graphify extract ./docs --force # דריסת graph.json גם אם לגרף החדש פחות צמתים (אחרי refactors או לניקוי כפילויות רפאים)
|
||||
graphify extract ./docs --dedup-llm # LLM כמכריע לזוגות ישויות עמומים (משתמש באותו מפתח API)
|
||||
graphify extract ./docs --global --as myrepo # חילוץ ורישום בגרף הגלובלי חוצה-הפרויקטים
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # הרמת תקרת הפלט לקורפוסים צפופים
|
||||
|
||||
graphify export callflow-html # graphify-out/<project>-callflow.html
|
||||
graphify export callflow-html --max-sections 8 # הגבלת מספר קטעי הארכיטקטורה שנוצרים
|
||||
graphify export callflow-html --output docs/arch.html
|
||||
graphify export callflow-html ./some-repo/graphify-out
|
||||
|
||||
graphify global add graphify-out/graph.json --as myrepo # רישום גרף פרויקט אל ~/.graphify/global-graph.json
|
||||
graphify global remove myrepo # הסרת פרויקט מהגרף הגלובלי
|
||||
graphify global list # הצגת כל המאגרים הרשומים + ספירות צמתים/קשתות
|
||||
graphify global path # הדפסת הנתיב לקובץ הגרף הגלובלי
|
||||
|
||||
graphify prs # לוח PR: CI, ביקורת, worktree, השפעת גרף
|
||||
graphify prs 42 # צלילה עמוקה ל-PR #42
|
||||
graphify prs --triage # דירוג טריאז' AI (מזהה backend אוטומטית מהסביבה)
|
||||
graphify prs --worktrees # מיפוי worktree ← branch ← PR
|
||||
graphify prs --conflicts # PRs שחולקים קהילות גרף (סיכון בסדר המיזוג)
|
||||
graphify prs --base main # סינון ל-PRs שמכוונים ל-branch בסיס מסוים
|
||||
graphify prs --repo owner/repo # הרצה מול מאגר GitHub אחר
|
||||
GRAPHIFY_TRIAGE_BACKEND=kimi graphify prs --triage # backend מסוים לטריאז'
|
||||
|
||||
graphify clone https://github.com/karpathy/nanoGPT
|
||||
graphify merge-graphs a.json b.json --out merged.json
|
||||
graphify --version # הדפסת הגרסה המותקנת
|
||||
graphify watch ./src
|
||||
graphify check-update ./src
|
||||
graphify update ./src
|
||||
graphify update ./src --no-cluster # דילוג על אשכול מחדש, כתיבת גרף AST גולמי בלבד
|
||||
graphify update ./src --force # דריסה גם אם לגרף החדש פחות צמתים
|
||||
graphify cluster-only ./my-project
|
||||
graphify cluster-only ./my-project --graph path/to/graph.json # מיקום גרף מותאם
|
||||
graphify cluster-only ./my-project --max-concurrency 16 --batch-size 200 # תיוג קהילות מקבילי (גרפים גדולים)
|
||||
graphify cluster-only ./my-project --resolution 1.5 # יותר קהילות, קטנות יותר
|
||||
graphify cluster-only ./my-project --exclude-hubs 99 # החרגת צומתי p99 מהחלוקה
|
||||
graphify cluster-only ./my-project --no-label # השארת מצייני "Community N"
|
||||
graphify cluster-only ./my-project --backend=gemini # backend לשמות הקהילות
|
||||
graphify cluster-only ./my-project --backend=gemini --model gemini-2.5-pro # מודל מסוים
|
||||
graphify label ./my-project # מתן שמות (מחדש) לקהילות עם ה-backend המוגדר
|
||||
graphify label ./my-project --backend=openai --model gpt-4o # כפיית backend ומודל מסוימים
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> **שמות קהילות:** בתוך סוכן (Claude Code, Gemini CLI) הסוכן נותן שמות לקהילות בעצמו. בהרצת ה-CLI החשוף, `cluster-only` נותן שמות אוטומטית עם ה-backend המוגדר (מובנה או ספק תואם-OpenAI מותאם) — העבירו `--no-label` להשארת `Community N`, או הריצו `graphify label` ליצירת שמות מחדש לפי דרישה.
|
||||
|
||||
---
|
||||
|
||||
## ללמוד עוד
|
||||
|
||||
- [איך זה עובד](../how-it-works.md) — צינור החילוץ, זיהוי קהילות, ניקוד ביטחון, מדדים
|
||||
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — פירוק מודולים, איך מוסיפים שפה
|
||||
- [אינטגרציות אופציונליות](../docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
|
||||
|
||||
---
|
||||
|
||||
## נבנה על graphify — Penpax
|
||||
|
||||
[**Penpax**](https://graphify.com) היא השכבה התמידית שנבנתה מעל graphify — היא מיישמת את אותה גישת גרף על כל חיי העבודה שלכם: פגישות, היסטוריית דפדפן, מיילים, קבצים וקוד, ומתעדכנת ברציפות ברקע.
|
||||
|
||||
נבנתה לאנשים שהעבודה שלהם מפוזרת על פני מאות שיחות ומסמכים שהם לעולם לא יוכלו לשחזר במלואם. ללא ענן, לגמרי על המכשיר.
|
||||
|
||||
**גרסת ניסיון חינמית תושק בקרוב.** [הצטרפו לרשימת ההמתנה ←](https://graphify.com)
|
||||
|
||||
---
|
||||
|
||||
<details>
|
||||
<summary>תרומה לפרויקט</summary>
|
||||
|
||||
### הקמת סביבת פיתוח
|
||||
|
||||
הפרויקט משתמש ב-[uv](https://docs.astral.sh/uv/) לתהליך הפיתוח. התקינו אותו פעם אחת, ואז:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
git clone https://github.com/safishamsi/graphify.git
|
||||
cd graphify
|
||||
git checkout v8 # branch הפיתוח הפעיל
|
||||
|
||||
# יצירת venv לפרויקט והתקנת graphify + כל התוספים + קבוצת dev
|
||||
# (pytest). uv מתקין את קבוצת התלויות dev כברירת מחדל; העבירו --no-dev לדילוג.
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
אימות ההתקנה במצב עריכה:
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
uv run graphify --version
|
||||
uv run python -c "import graphify; print(graphify.__file__)"
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
### הרצת בדיקות
|
||||
|
||||
</div>
|
||||
|
||||
```bash
|
||||
uv run pytest tests/ -q # הרצת החבילה המלאה
|
||||
uv run pytest tests/test_extract.py -q # מודול אחד
|
||||
uv run pytest tests/ -q -k "python" # סינון לפי שם
|
||||
```
|
||||
|
||||
<div dir="rtl">
|
||||
|
||||
> הערת macOS: חבילת הבדיקות כוללת גם `sample.f90` וגם `sample.F90`. אלו מתנגשים במערכות קבצים HFS+ / APFS שאינן רגישות לרישיות. הריצו בלינוקס או בקונטיינר Docker אם צריך לבדוק את שתי גרסאות ה-Fortran יחד.
|
||||
|
||||
### תהליך עבודה ב-Git
|
||||
|
||||
- הפיתוח הפעיל מתרחש ב-branch `v8`.
|
||||
- סגנון commit: `fix: <description>` / `feat: <description>` / `docs: <description>`
|
||||
- לפני פתיחת PR, הריצו `uv run pytest tests/ -q` וודאו שהוא עובר.
|
||||
- הוסיפו קובץ fixture ל-`tests/fixtures/` ובדיקות ל-`tests/test_languages.py` לכל מחלץ שפה חדש.
|
||||
|
||||
### מה כדאי לתרום
|
||||
|
||||
**דוגמאות עבודה (worked examples)** הן התרומה השימושית ביותר. הריצו `/graphify` על קורפוס אמיתי, שמרו את הפלט ב-`worked/{slug}/`, כתבו `review.md` כן שמכסה מה הגרף קלע ומה פספס, ופתחו PR.
|
||||
|
||||
**באגים בחילוץ** — פתחו issue עם קובץ הקלט, רשומת ה-cache (`graphify-out/cache/`) ומה חסר או שגוי.
|
||||
|
||||
ראו [ARCHITECTURE.md](../../ARCHITECTURE.md) לאחריות המודולים ואיך מוסיפים שפה.
|
||||
|
||||
</details>
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
**एक AI कोडिंग असिस्टेंट स्किल।** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro या Google Antigravity में `/graphify` टाइप करें — यह आपकी फ़ाइलें पढ़ता है, एक नॉलेज ग्राफ बनाता है, और आपको वह संरचना वापस देता है जो आप नहीं जानते थे कि मौजूद है। कोडबेस को तेज़ी से समझें। आर्किटेक्चरल निर्णयों के पीछे का "क्यों" खोजें।
|
||||
|
||||
@@ -114,7 +114,7 @@ curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/ski
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
@@ -150,7 +150,7 @@ curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/ski
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
**Uma habilidade para assistentes de código IA.** Digite `/graphify` no Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro ou Google Antigravity — ele lê seus arquivos, constrói um grafo de conhecimento e devolve a você estrutura que você não sabia que existia. Entenda uma base de código mais rapidamente. Encontre o "porquê" por trás das decisões arquiteturais.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
**Навык для AI-ассистента по написанию кода.** Введите `/graphify` в Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro или Google Antigravity — он прочитает ваши файлы, построит граф знаний и вернёт вам структуру, о существовании которой вы не подозревали. Понимайте кодовую базу быстрее. Находите «почему» за архитектурными решениями.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
<a href="https://graphifylabs.ai"><img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -13,7 +13,7 @@
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
@@ -326,12 +326,8 @@ MCP-сервер надає асистенту структурований до
|
||||
| Змінна | Використання | Коли потрібна |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | Backend Claude (Anthropic) | `--backend claude` |
|
||||
| `ANTHROPIC_BASE_URL` | URL Anthropic-сумісного endpoint (LiteLLM proxy, шлюзи, ...) | `--backend claude` (типово: `https://api.anthropic.com`) |
|
||||
| `ANTHROPIC_MODEL` | Назва моделі для backend Claude — для власних endpoint використовуйте назву/псевдонім моделі вашого сервера | `--backend claude` (типово: `claude-sonnet-4-6`) |
|
||||
| `GEMINI_API_KEY` або `GOOGLE_API_KEY` | Backend Google Gemini | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI або OpenAI-сумісні API | `--backend openai` (локальні сервери приймають будь-яке непорожнє значення) |
|
||||
| `OPENAI_BASE_URL` | URL OpenAI-сумісного сервера (llama.cpp, vLLM, LM Studio, ...) | `--backend openai` (типово: `https://api.openai.com/v1`) |
|
||||
| `OPENAI_MODEL` | Назва моделі для backend OpenAI — для self-hosted серверів використовуйте назву/псевдонім моделі, яку надає ваш сервер (див. його endpoint `/v1/models`), напр. `LFM2.5-8B-A1B-UD-Q4_K_XL` для llama.cpp | `--backend openai` (типово: `gpt-4.1-mini`) |
|
||||
| `OPENAI_API_KEY` | OpenAI або OpenAI-сумісні API | `--backend openai` |
|
||||
| `DEEPSEEK_API_KEY` | Backend DeepSeek | `--backend deepseek` |
|
||||
| `MOONSHOT_API_KEY` | Backend Kimi Code | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | URL локального виводу Ollama | `--backend ollama` (типово: `http://localhost:11434`) |
|
||||
@@ -467,8 +463,6 @@ graphify extract ./docs # headless LLM-витягуван
|
||||
graphify extract ./docs --backend gemini # явний backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock або claude-cli
|
||||
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
|
||||
graphify extract ./docs --backend ollama # локальний Ollama (встановіть OLLAMA_BASE_URL / OLLAMA_MODEL) — без API-ключа для loopback
|
||||
OPENAI_BASE_URL=http://localhost:8080/v1 OPENAI_MODEL=my-model graphify extract ./docs --backend openai # будь-який OpenAI-сумісний сервер (llama.cpp, vLLM, LM Studio)
|
||||
ANTHROPIC_BASE_URL=http://localhost:4000 ANTHROPIC_MODEL=my-model graphify extract ./docs --backend claude # будь-який Anthropic-сумісний endpoint (LiteLLM proxy, шлюзи)
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # перевизначити KV-кеш вікно (автоматично за замовчуванням)
|
||||
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # вивантажити модель після кожного шматка (економить VRAM на малих GPU)
|
||||
graphify extract ./docs --backend bedrock # AWS Bedrock через IAM — без API-ключа, використовує ланцюг облікових даних AWS
|
||||
@@ -529,11 +523,11 @@ graphify cluster-only ./my-project --exclude-hubs 99 # виключи
|
||||
|
||||
## Побудовано на graphify — Penpax
|
||||
|
||||
[**Penpax**](https://graphify.com) — це завжди активний шар поверх graphify, він застосовує той самий графовий підхід до всього робочого життя: зустрічей, історії браузера, email-ів, файлів і коду, постійно оновлюючись у фоновому режимі.
|
||||
[**Penpax**](https://graphifylabs.ai) — це завжди активний шар поверх graphify, він застосовує той самий графовий підхід до всього робочого життя: зустрічей, історії браузера, email-ів, файлів і коду, постійно оновлюючись у фоновому режимі.
|
||||
|
||||
Створений для людей, чия робота розкидана по сотнях розмов і документів, які неможливо повністю відтворити. Без хмари, повністю на пристрої.
|
||||
|
||||
**Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://graphify.com)
|
||||
**Безкоштовна пробна версія незабаром.** [Приєднайтесь до списку очікування →](https://graphifylabs.ai)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<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://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/company/graphify-labs"><img src="https://img.shields.io/badge/LinkedIn-Graphify%20Labs-0077B5?logo=linkedin" alt="LinkedIn"/></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>
|
||||
</p>
|
||||
|
||||
**Sun'iy intellektga asoslangan kod yordamchilari uchun ko'nikma.** Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro yoki Google Antigravity da `/graphify` deb yozing — u sizning fayllaringizni o'qiydi, bilim grafini quradi va siz bilmagan tuzilmani sizga qaytaradi. Kod bazasini tezroq tushuning. Arxitektura qarorlari ortidagi "nima uchun" savoliga javob toping.
|
||||
|
||||
@@ -110,7 +110,7 @@ curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/ski
|
||||
|
||||
```
|
||||
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
@@ -19,8 +19,6 @@ def __getattr__(name):
|
||||
"to_svg": ("graphify.export", "to_svg"),
|
||||
"to_canvas": ("graphify.export", "to_canvas"),
|
||||
"to_wiki": ("graphify.wiki", "to_wiki"),
|
||||
"reflect": ("graphify.reflect", "reflect"),
|
||||
"save_query_result": ("graphify.ingest", "save_query_result"),
|
||||
}
|
||||
if name in _map:
|
||||
import importlib
|
||||
|
||||
+4195
-323
File diff suppressed because it is too large.
Load diff
@@ -1,107 +0,0 @@
|
||||
"""MinHash + band-LSH — datasketch-compatible drop-in (no scipy).
|
||||
|
||||
datasketch.lsh has `from scipy.integrate import quad` at module level.
|
||||
scipy's array_api_compat layer then lazily loads numpy.testing, which calls
|
||||
platform.machine() at import time to set test-skip decorator constants — and
|
||||
that in turn spawns cmd.exe via subprocess, hanging for minutes under EDR
|
||||
software in corporate Windows environments.
|
||||
|
||||
Covers the exact MinHash/MinHashLSH API surface used by dedup.py.
|
||||
Hash family (Mersenne-prime permutations) and LSH band structure are
|
||||
equivalent to datasketch so dedup quality is unchanged.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import hashlib
|
||||
import struct
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
_MP = np.uint64((1 << 61) - 1) # Mersenne prime for the hash family
|
||||
_MH = np.uint64(0xFFFF_FFFF) # mask to 32-bit values
|
||||
|
||||
# One (a, b) coefficient array per num_perm, shared across all instances.
|
||||
_MH_COEFFS: dict[int, tuple[np.ndarray, np.ndarray]] = {}
|
||||
|
||||
|
||||
def _mh_coeffs(num_perm: int) -> tuple[np.ndarray, np.ndarray]:
|
||||
if num_perm not in _MH_COEFFS:
|
||||
rng = np.random.RandomState(1)
|
||||
a = rng.randint(1, int(_MP), num_perm, dtype=np.uint64)
|
||||
b = rng.randint(0, int(_MP), num_perm, dtype=np.uint64)
|
||||
_MH_COEFFS[num_perm] = (a, b)
|
||||
return _MH_COEFFS[num_perm]
|
||||
|
||||
|
||||
class MinHash:
|
||||
"""MinHash sketch — same API as datasketch.MinHash for the subset used here."""
|
||||
|
||||
__slots__ = ("num_perm", "hashvalues", "_a", "_b")
|
||||
|
||||
def __init__(self, num_perm: int = 128) -> None:
|
||||
self.num_perm = num_perm
|
||||
self.hashvalues = np.full(num_perm, int(_MH), dtype=np.uint64)
|
||||
self._a, self._b = _mh_coeffs(num_perm)
|
||||
|
||||
def update(self, v: bytes) -> None:
|
||||
hv = np.uint64(struct.unpack("<I", hashlib.sha1(v).digest()[:4])[0])
|
||||
phv = np.bitwise_and((self._a * hv + self._b) % _MP, _MH)
|
||||
self.hashvalues = np.minimum(self.hashvalues, phv)
|
||||
|
||||
|
||||
def _lsh_integrate(f, lo: float, hi: float, n: int = 128) -> float:
|
||||
"""Numerical integration — replaces scipy.integrate.quad for LSH param search."""
|
||||
h = (hi - lo) / n
|
||||
return h * sum(f(lo + i * h) for i in range(n))
|
||||
|
||||
|
||||
_LSH_PARAMS_CACHE: dict[tuple[float, int], tuple[int, int]] = {}
|
||||
|
||||
|
||||
def _optimal_lsh_params(threshold: float, num_perm: int) -> tuple[int, int]:
|
||||
"""Find (bands, rows) that minimise weighted FP+FN error, without scipy."""
|
||||
key = (threshold, num_perm)
|
||||
if key in _LSH_PARAMS_CACHE:
|
||||
return _LSH_PARAMS_CACHE[key]
|
||||
best_err, best = float("inf"), (1, 1)
|
||||
for b in range(1, num_perm + 1):
|
||||
for r in range(1, num_perm // b + 1):
|
||||
fp = _lsh_integrate(
|
||||
lambda s, _b=float(b), _r=float(r): 1 - (1 - s ** _r) ** _b,
|
||||
0.0, threshold,
|
||||
)
|
||||
fn = _lsh_integrate(
|
||||
lambda s, _b=float(b), _r=float(r): 1 - (1 - (1 - s ** _r) ** _b),
|
||||
threshold, 1.0,
|
||||
)
|
||||
err = 0.5 * fp + 0.5 * fn
|
||||
if err < best_err:
|
||||
best_err, best = err, (b, r)
|
||||
_LSH_PARAMS_CACHE[key] = best
|
||||
return best
|
||||
|
||||
|
||||
class MinHashLSH:
|
||||
"""Band-hashing LSH — same API as datasketch.MinHashLSH for the subset used here."""
|
||||
|
||||
def __init__(self, threshold: float = 0.5, num_perm: int = 128) -> None:
|
||||
self.b, self.r = _optimal_lsh_params(threshold, num_perm)
|
||||
self._tables: list[dict[bytes, list[str]]] = [{} for _ in range(self.b)]
|
||||
self._keys: set[str] = set()
|
||||
|
||||
def insert(self, key: str, minhash: MinHash) -> None:
|
||||
if key in self._keys:
|
||||
raise ValueError(f"Key {key!r} already exists in MinHashLSH")
|
||||
self._keys.add(key)
|
||||
hv = minhash.hashvalues
|
||||
for i, table in enumerate(self._tables):
|
||||
band = hv[i * self.r : (i + 1) * self.r].tobytes()
|
||||
table.setdefault(band, []).append(key)
|
||||
|
||||
def query(self, minhash: MinHash) -> list[str]:
|
||||
hv = minhash.hashvalues
|
||||
candidates: set[str] = set()
|
||||
for i, table in enumerate(self._tables):
|
||||
band = hv[i * self.r : (i + 1) * self.r].tobytes()
|
||||
candidates.update(table.get(band, []))
|
||||
return list(candidates)
|
||||
+5
-104
@@ -4,14 +4,12 @@ from collections import deque
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
import unicodedata
|
||||
|
||||
import networkx as nx
|
||||
|
||||
|
||||
DEFAULT_AFFECTED_RELATIONS = (
|
||||
"calls",
|
||||
"indirect_call",
|
||||
"references",
|
||||
"imports",
|
||||
"imports_from",
|
||||
@@ -45,92 +43,28 @@ def _format_location(data: dict) -> str:
|
||||
return str(source_file)
|
||||
|
||||
|
||||
def _bare_name(label: str) -> str:
|
||||
"""Lowercased label with the callable decoration (trailing "()") removed."""
|
||||
label = _normalize_label(label)
|
||||
return label[:-2] if label.endswith("()") else label
|
||||
|
||||
|
||||
def _normalize_label(label: str) -> str:
|
||||
return unicodedata.normalize("NFC", label).casefold()
|
||||
|
||||
|
||||
def _prefer_file_node(
|
||||
graph: nx.Graph,
|
||||
node_ids: list[str],
|
||||
query: str,
|
||||
) -> str | None:
|
||||
"""Return the file-level node when a source_file query matches many nodes."""
|
||||
query_basename = _normalize_label(Path(query).name)
|
||||
exact_file_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
|
||||
and _normalize_label(str(graph.nodes[node_id].get("label", ""))) == query_basename
|
||||
]
|
||||
if len(exact_file_nodes) == 1:
|
||||
return exact_file_nodes[0]
|
||||
|
||||
l1_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
if str(graph.nodes[node_id].get("source_location", "")) == "L1"
|
||||
]
|
||||
if len(l1_nodes) == 1:
|
||||
return l1_nodes[0]
|
||||
|
||||
basename_nodes = [
|
||||
node_id
|
||||
for node_id in node_ids
|
||||
if _normalize_label(str(graph.nodes[node_id].get("label", ""))) == query_basename
|
||||
]
|
||||
if len(basename_nodes) == 1:
|
||||
return basename_nodes[0]
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def resolve_seed(graph: nx.Graph, query: str) -> str | None:
|
||||
# A trailing path separator must not change a source-file match — serve's
|
||||
# _find_node tokenizes the path (which drops it), so strip it here for parity
|
||||
# (otherwise `affected "src/x.ts/"` returned None while `explain` resolved it).
|
||||
query = query.rstrip("/\\") or query
|
||||
if query in graph:
|
||||
return query
|
||||
query_lower = _normalize_label(query)
|
||||
query_lower = query.lower()
|
||||
exact_label_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if _normalize_label(str(data.get("label", ""))) == query_lower
|
||||
if str(data.get("label", "")).lower() == query_lower
|
||||
]
|
||||
if len(exact_label_matches) == 1:
|
||||
return exact_label_matches[0]
|
||||
# Callable labels are decorated ("name()"), so a bare "name" query falls
|
||||
# through exact matching and then ties with any "name*" sibling in the
|
||||
# contains pass. Match on the undecorated name before giving up.
|
||||
query_bare = _bare_name(query_lower)
|
||||
bare_name_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if _bare_name(str(data.get("label", ""))) == query_bare
|
||||
]
|
||||
if len(bare_name_matches) == 1:
|
||||
return bare_name_matches[0]
|
||||
exact_source_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if _normalize_label(str(data.get("source_file", ""))) == query_lower
|
||||
if str(data.get("source_file", "")).lower() == query_lower
|
||||
]
|
||||
if len(exact_source_matches) == 1:
|
||||
return exact_source_matches[0]
|
||||
if exact_source_matches:
|
||||
preferred_file_node = _prefer_file_node(graph, exact_source_matches, query)
|
||||
if preferred_file_node is not None:
|
||||
return preferred_file_node
|
||||
contains_matches = [
|
||||
str(node_id)
|
||||
for node_id, data in graph.nodes(data=True)
|
||||
if query_lower in _normalize_label(str(data.get("label", "")))
|
||||
if query_lower in str(data.get("label", "")).lower()
|
||||
]
|
||||
if len(contains_matches) == 1:
|
||||
return contains_matches[0]
|
||||
@@ -149,27 +83,6 @@ def affected_nodes(
|
||||
queue: deque[tuple[str, int]] = deque([(seed, 0)])
|
||||
hits: list[AffectedHit] = []
|
||||
|
||||
# #1669: seed the reverse walk with the root's own member nodes (one outward
|
||||
# `method`/`contains` hop). A caller can bind to a class's method node rather
|
||||
# than the class node itself (e.g. `Service.call` resolves to the `def
|
||||
# self.call` node, #1634), so those callers are unreachable from the class
|
||||
# otherwise. The member nodes are seeds only (not reported as hits), and
|
||||
# `method`/`contains` stay out of the general relation-filtered walk, so this
|
||||
# adds no forward noise anywhere else.
|
||||
if hasattr(graph, "out_edges"):
|
||||
member_edges = graph.out_edges(seed, data=True)
|
||||
else:
|
||||
member_edges = (
|
||||
(s, t, d) for s, t, d in graph.edges(data=True) if s == seed
|
||||
)
|
||||
for _s, member, data in member_edges:
|
||||
if str(data.get("relation", "")) not in ("method", "contains"):
|
||||
continue
|
||||
member = str(member)
|
||||
if member not in seen:
|
||||
seen.add(member)
|
||||
queue.append((member, 0))
|
||||
|
||||
while queue:
|
||||
current, current_depth = queue.popleft()
|
||||
if current_depth >= depth:
|
||||
@@ -231,22 +144,10 @@ def load_graph(path: Path) -> nx.Graph:
|
||||
import json
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise RuntimeError(
|
||||
f"Cannot read graph file {path}: {exc}. "
|
||||
"Re-run 'graphify extract' to regenerate it."
|
||||
) from exc
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
# Force directed so stored caller→callee direction survives the round-trip;
|
||||
# mirrors serve.py and __main__.py (#1174).
|
||||
raw = {**raw, "directed": True}
|
||||
# Normalize the edge key: graphify's `extract` output uses "edges" while
|
||||
# networkx's node_link_data default is "links". Without this, an edges-keyed
|
||||
# graph.json raises an uncaught KeyError: 'links' here — every other loader
|
||||
# (__main__.py) already normalizes this (#738; same class as #1198).
|
||||
if "links" not in raw and "edges" in raw:
|
||||
raw = dict(raw, links=raw["edges"])
|
||||
try:
|
||||
return json_graph.node_link_graph(raw, edges="links")
|
||||
except TypeError:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
|
||||
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
|
||||
When the user types `/graphify`, invoke the `skill` tool with `skill: "graphify"` before doing anything else.
|
||||
|
||||
Rules:
|
||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
||||
|
||||
+4
-20
@@ -13,22 +13,17 @@ _BUILTIN_NOISE_LABELS = frozenset({
|
||||
"True", "False",
|
||||
"MagicMock", "Mock", "AsyncMock", "NonCallableMock",
|
||||
"NonCallableMagicMock", "PropertyMock", "patch", "sentinel",
|
||||
# Python stdlib types commonly confused for project symbols
|
||||
"Path", "Any", "Optional", "List", "Dict", "Set", "Tuple", "Union",
|
||||
"Callable", "Type", "ClassVar", "Final", "Literal", "Protocol",
|
||||
"Counter", "defaultdict", "OrderedDict", "datetime", "Enum",
|
||||
"os", "sys", "re", "json", "io", "abc", "typing",
|
||||
})
|
||||
|
||||
# Language families — extensions sharing a runtime can legitimately call each other
|
||||
_LANG_FAMILY: dict[str, str] = {
|
||||
**{e: "python" for e in (".py", ".pyw")},
|
||||
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte")},
|
||||
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
|
||||
**{e: "go" for e in (".go",)},
|
||||
**{e: "rust" for e in (".rs",)},
|
||||
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
|
||||
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
|
||||
**{e: "ruby" for e in (".rb", ".rake")},
|
||||
**{e: "ruby" for e in (".rb",)},
|
||||
**{e: "swift" for e in (".swift",)},
|
||||
**{e: "dotnet" for e in (".cs",)},
|
||||
**{e: "php" for e in (".php",)},
|
||||
@@ -504,10 +499,7 @@ def suggest_questions(
|
||||
# 4. Isolated or weakly-connected nodes → exploration questions
|
||||
isolated = [
|
||||
n for n in G.nodes()
|
||||
if G.degree(n) <= 1
|
||||
and not _is_file_node(G, n)
|
||||
and not _is_concept_node(G, n)
|
||||
and G.nodes[n].get("file_type") != "rationale"
|
||||
if G.degree(n) <= 1 and not _is_file_node(G, n) and not _is_concept_node(G, n)
|
||||
]
|
||||
if isolated:
|
||||
labels = [G.nodes[n].get("label", n) for n in isolated[:3]]
|
||||
@@ -666,11 +658,6 @@ def find_import_cycles(
|
||||
if rel not in ("imports_from", "re_exports"):
|
||||
continue
|
||||
|
||||
# Deferred `import(...)` edges are real dependencies but do not form a
|
||||
# hard file-level cycle, so they are excluded from cycle detection (#1241).
|
||||
if data.get("deferred"):
|
||||
continue
|
||||
|
||||
src_file_attr = data.get("source_file", "")
|
||||
if not isinstance(src_file_attr, str) or not src_file_attr:
|
||||
continue
|
||||
@@ -699,11 +686,8 @@ def find_import_cycles(
|
||||
return []
|
||||
|
||||
# Step 2: Find simple cycles, bounded by length.
|
||||
# Pass length_bound so networkx prunes during enumeration rather than
|
||||
# enumerating all elementary cycles and post-filtering — avoids exponential
|
||||
# blowup on dense graphs with many long cycles (#1196).
|
||||
cycles: list[list[str]] = []
|
||||
for cycle in nx.simple_cycles(file_graph, length_bound=max_cycle_length):
|
||||
for cycle in nx.simple_cycles(file_graph):
|
||||
if len(cycle) <= max_cycle_length:
|
||||
cycles.append(cycle)
|
||||
if len(cycles) >= top_n * 10:
|
||||
|
||||
@@ -8,7 +8,6 @@ from networkx.readwrite import json_graph
|
||||
|
||||
from graphify.build import edge_data
|
||||
from graphify.serve import _query_terms
|
||||
from graphify.paths import default_graph_json as _default_graph_json
|
||||
|
||||
|
||||
_CHARS_PER_TOKEN = 4 # standard approximation
|
||||
@@ -86,7 +85,7 @@ _SAMPLE_QUESTIONS = [
|
||||
|
||||
|
||||
def run_benchmark(
|
||||
graph_path: str | None = None,
|
||||
graph_path: str = "graphify-out/graph.json",
|
||||
corpus_words: int | None = None,
|
||||
questions: list[str] | None = None,
|
||||
) -> dict:
|
||||
@@ -99,7 +98,6 @@ def run_benchmark(
|
||||
|
||||
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
|
||||
"""
|
||||
graph_path = graph_path or _default_graph_json()
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
check_graph_file_size_cap(Path(graph_path))
|
||||
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
|
||||
|
||||
+65
-675
@@ -28,31 +28,9 @@ import sys
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from .ids import make_id, normalize_id as _normalize_id
|
||||
from .paths import default_graph_json as _default_graph_json
|
||||
from .validate import validate_extraction
|
||||
|
||||
|
||||
# Language interop families, keyed by extension, for the cross-language phantom-edge
|
||||
# guard in the edge loop below. Families group by REAL interop (JS/TS share a module
|
||||
# graph; C/C++/ObjC share a compilation unit via headers; JVM langs share bytecode),
|
||||
# so a legitimate TS->JS import or C impl->header call survives, while a Python
|
||||
# `import time` binding to a `time.ts` (#1749) or a cross-language INFERRED `calls`
|
||||
# edge (#1547/#1556) is dropped. Kept local to build.py (not imported from extract.py,
|
||||
# which imports build.py — a cycle) and deliberately mirrors extract._LANG_FAMILY_BY_EXT.
|
||||
_EDGE_LANG_FAMILY: dict[str, str] = {
|
||||
".py": "py", ".pyi": "py",
|
||||
".js": "js", ".mjs": "js", ".cjs": "js", ".jsx": "js",
|
||||
".ts": "js", ".tsx": "js", ".mts": "js", ".cts": "js",
|
||||
".go": "go", ".rs": "rs",
|
||||
".java": "jvm", ".kt": "jvm", ".scala": "jvm", ".groovy": "jvm",
|
||||
".c": "c", ".h": "c", ".cc": "c", ".cpp": "c", ".hpp": "c",
|
||||
".cxx": "c", ".hh": "c", ".hxx": "c",
|
||||
".cu": "c", ".cuh": "c", ".metal": "c", ".m": "c", ".mm": "c",
|
||||
".rb": "rb", ".rake": "rb", ".php": "php", ".cs": "cs", ".swift": "swift", ".lua": "lua",
|
||||
}
|
||||
|
||||
|
||||
# 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).
|
||||
@@ -73,54 +51,18 @@ _FILE_TYPE_SYNONYMS = {
|
||||
}
|
||||
|
||||
|
||||
# Hyperedge member lists are canonically keyed `nodes` (see graphify/llm.py
|
||||
# extraction spec), but LLM/subagent drift and externally-supplied graph.json
|
||||
# sometimes emit `members` or `node_ids`. _normalize_hyperedge_members folds
|
||||
# those aliases into `nodes` at ingest so every downstream consumer reads one
|
||||
# canonical key — mirroring the `from`/`to` edge-endpoint tolerance below.
|
||||
_HE_MEMBER_ALIASES = ("members", "node_ids")
|
||||
def _normalize_id(s: str) -> str:
|
||||
r"""Normalize an ID string the same way extract._make_id does.
|
||||
|
||||
|
||||
def _normalize_hyperedge_members(he: object) -> None:
|
||||
"""Canonicalize a hyperedge's member list onto the `nodes` key, in place.
|
||||
|
||||
If `nodes` is already a list it wins (canonical), and only stray alias keys
|
||||
are dropped. Otherwise the first alias (`members`, then `node_ids`) that is a
|
||||
list is moved to `nodes`, deduped preserving order, with a single stderr
|
||||
WARNING naming the hyperedge id and alias used. Leftover alias keys are
|
||||
always removed so downstream code never re-reads them.
|
||||
Used to reconcile edge endpoints when the LLM generates IDs with slightly
|
||||
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).
|
||||
"""
|
||||
if not isinstance(he, dict):
|
||||
return
|
||||
if not isinstance(he.get("nodes"), list):
|
||||
for alias in _HE_MEMBER_ALIASES:
|
||||
val = he.get(alias)
|
||||
if isinstance(val, list):
|
||||
seen: set = set()
|
||||
deduped: list = []
|
||||
for ref in val:
|
||||
try:
|
||||
is_dupe = ref in seen
|
||||
except TypeError:
|
||||
is_dupe = False # unhashable ref: keep it, validator flags it
|
||||
if is_dupe:
|
||||
continue
|
||||
try:
|
||||
seen.add(ref)
|
||||
except TypeError:
|
||||
pass
|
||||
deduped.append(ref)
|
||||
he["nodes"] = deduped
|
||||
print(
|
||||
f"[graphify] WARNING: hyperedge "
|
||||
f"'{he.get('id', '?')}' uses field '{alias}' instead of "
|
||||
f"'nodes'; normalizing.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
break
|
||||
# Drop any leftover alias keys regardless of which branch ran above.
|
||||
for alias in _HE_MEMBER_ALIASES:
|
||||
he.pop(alias, None)
|
||||
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, root: str | None = None) -> str | None:
|
||||
@@ -137,43 +79,10 @@ def _norm_source_file(p: str | None, root: str | None = None) -> str | None:
|
||||
try:
|
||||
p = Path(p).relative_to(root).as_posix()
|
||||
except ValueError:
|
||||
# Lexical relative_to failed. Retry with both sides fully resolved:
|
||||
# a symlinked scan root (macOS /var -> /private/var, or a symlinked
|
||||
# home/worktree) makes the raw prefixes differ even though they point
|
||||
# at the same dir, which otherwise silently defeats prune/replace
|
||||
# matching. Only the slow path resolves, so the common lexical match
|
||||
# stays filesystem-free.
|
||||
try:
|
||||
p = Path(p).resolve().relative_to(Path(root).resolve()).as_posix()
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
pass
|
||||
return p
|
||||
|
||||
|
||||
def _infer_merge_root(graph_path: Path) -> str | None:
|
||||
"""Best-effort scan root for relativizing paths in build_merge when the caller
|
||||
passes no ``root`` (#1571).
|
||||
|
||||
Prefers the committed ``graphify-out/.graphify_root`` marker — the authoritative
|
||||
scan root graphify records at build/watch time (#686/#1423) — then falls back to
|
||||
the directory that contains the output dir (``graph.json``'s grandparent, i.e.
|
||||
``<root>/graphify-out/graph.json`` -> ``<root>``). Returns None if neither
|
||||
resolves, in which case normalization is a no-op (prior behavior).
|
||||
"""
|
||||
try:
|
||||
marker = graph_path.parent / ".graphify_root"
|
||||
if marker.exists():
|
||||
recorded = marker.read_text(encoding="utf-8").strip()
|
||||
if recorded:
|
||||
return str(Path(recorded).resolve())
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
return str(graph_path.parent.parent.resolve())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def edge_data(G: nx.Graph, u: str, v: str) -> dict:
|
||||
"""Return one edge attribute dict for (u, v), tolerating MultiGraph.
|
||||
|
||||
@@ -195,191 +104,6 @@ def edge_datas(G: nx.Graph, u: str, v: str) -> list[dict]:
|
||||
return [raw]
|
||||
|
||||
|
||||
def dedupe_nodes(nodes: list[dict]) -> list[dict]:
|
||||
"""Collapse nodes sharing an ``id``, last-writer-wins on attributes.
|
||||
|
||||
Mirrors what ``build_from_json``'s ``G.add_node`` does implicitly (idempotent;
|
||||
a later node overwrites an earlier one's attributes). The ``--no-cluster``
|
||||
write path dumps the raw node list without building a graph, so same-id nodes
|
||||
— e.g. a Swift ``type=module`` anchor emitted once per importing file (#1327)
|
||||
— would otherwise appear as duplicates. Insertion order follows each id's
|
||||
first appearance; the retained dict is the last one seen.
|
||||
"""
|
||||
by_id: dict = {}
|
||||
for n in nodes:
|
||||
nid = n.get("id")
|
||||
if nid is None:
|
||||
continue
|
||||
by_id[nid] = n
|
||||
return list(by_id.values())
|
||||
|
||||
|
||||
def dedupe_edges(edges: list[dict]) -> list[dict]:
|
||||
"""Collapse exact parallel edges by ``(source, target, relation)``, keeping the
|
||||
first occurrence.
|
||||
|
||||
The clustered build path runs edges through a NetworkX ``DiGraph``, which
|
||||
collapses parallel edges automatically. The ``--no-cluster`` and incremental
|
||||
``update`` write paths bypass NetworkX and concatenate edge lists raw, so
|
||||
duplicates accumulate and edge counts become non-deterministic across build
|
||||
modes / repeated updates (#1317). Deduping on the connectivity identity is
|
||||
zero-signal-loss and restores idempotency. Callers that intentionally keep
|
||||
parallel edges (multigraph output) must not use this.
|
||||
"""
|
||||
seen: set[tuple] = set()
|
||||
out: list[dict] = []
|
||||
for e in edges:
|
||||
key = (e.get("source"), e.get("target"), e.get("relation"))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def _old_file_stems(rel: Path) -> list[str]:
|
||||
"""Pre-migration stem forms a semantic fragment may have used for ``rel``.
|
||||
|
||||
Ordered longest-first so prefix stripping is greedy and unambiguous:
|
||||
- one-parent form: ``parent.stem`` (the old _file_stem rule, #550-era)
|
||||
- zero-parent form: ``stem`` (the old llm.py prompt rule, #1509)
|
||||
"""
|
||||
forms: list[str] = []
|
||||
parent = rel.parent.name
|
||||
if parent and parent not in (".", ""):
|
||||
forms.append(make_id(f"{parent}.{rel.stem}"))
|
||||
forms.append(make_id(rel.stem))
|
||||
# Dedupe while preserving order (top-level files collapse both forms).
|
||||
seen: set[str] = set()
|
||||
return [f for f in forms if f and not (f in seen or seen.add(f))]
|
||||
|
||||
|
||||
def _semantic_id_remap(nodes: list, root: str | None) -> dict:
|
||||
"""Re-derive non-AST node ids from ``source_file`` using the canonical
|
||||
full-path stem, so a cached/LLM fragment carrying a pre-migration short id
|
||||
reconciles with the AST node instead of spawning a ghost (#1504/#1509).
|
||||
|
||||
Drift-proof by construction: the new id is computed from ``source_file`` in
|
||||
code, never trusted from the fragment's own ``id`` string. AST-origin nodes
|
||||
are skipped (they are already canonical via the extract() post-pass)."""
|
||||
from graphify.extractors.base import _file_stem # local: avoid import cost at module load
|
||||
|
||||
remap: dict[str, str] = {}
|
||||
for node in nodes:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
if node.get("_origin") == "ast":
|
||||
continue
|
||||
nid = node.get("id")
|
||||
sf = node.get("source_file")
|
||||
if not nid or not isinstance(nid, str) or not sf:
|
||||
continue
|
||||
sf_norm = _norm_source_file(str(sf), root) or str(sf)
|
||||
rel = Path(sf_norm)
|
||||
if rel.is_absolute():
|
||||
continue # can't relativize (no/failed root) — leave id untouched
|
||||
if not rel.name:
|
||||
# source_file equals the scan root, so _norm_source_file relativized it
|
||||
# to Path('.') — a project-level node with no per-file identity to remap.
|
||||
# Leave its id untouched (and avoid _file_stem's empty-name crash, #1618).
|
||||
continue
|
||||
new_stem = make_id(_file_stem(rel))
|
||||
if not new_stem:
|
||||
continue
|
||||
norm_nid = _normalize_id(nid)
|
||||
new_id: str | None = None
|
||||
for old_stem in _old_file_stems(rel):
|
||||
if old_stem == new_stem:
|
||||
continue # already canonical for this form
|
||||
if norm_nid == old_stem:
|
||||
new_id = new_stem # the file node itself
|
||||
break
|
||||
prefix = old_stem + "_"
|
||||
if norm_nid.startswith(prefix):
|
||||
entity = norm_nid[len(prefix):]
|
||||
new_id = make_id(new_stem, entity)
|
||||
break
|
||||
if new_id and new_id != nid:
|
||||
remap[nid] = new_id
|
||||
return remap
|
||||
|
||||
|
||||
def graph_has_legacy_ids(nodes: list, root: str | Path | None = None, sample: int = 300) -> bool:
|
||||
"""Whether a loaded graph still uses pre-#1504 node IDs (parent-dir / filename
|
||||
stem) rather than the full repo-relative path. Read-only consumers (query,
|
||||
serve) use this to nudge the user to rebuild, since they don't re-extract.
|
||||
|
||||
Heuristic and cheap: only **file-level** nodes (source_location ``L1``) are
|
||||
inspected, because their ID is unambiguously the file stem. Symbol nodes are
|
||||
skipped — some extractors scope a symbol by package/directory (Go's
|
||||
``_make_id(pkg_dir, name)`` → ``sub_thing``), which can coincide with an old
|
||||
file-stem form and would otherwise false-positive. Returns True as soon as one
|
||||
file node's ID matches an OLD stem form but not the canonical full-path form."""
|
||||
from graphify.extractors.base import _file_stem
|
||||
_r = str(root) if root is not None else None
|
||||
checked = 0
|
||||
for node in nodes:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
if str(node.get("source_location") or "") != "L1":
|
||||
continue # only file-level nodes carry an unambiguous file-stem ID
|
||||
nid = node.get("id")
|
||||
sf = node.get("source_file")
|
||||
if not nid or not isinstance(nid, str) or not sf:
|
||||
continue
|
||||
rel = Path(_norm_source_file(str(sf), _r) or str(sf))
|
||||
if rel.is_absolute():
|
||||
continue
|
||||
if not rel.name:
|
||||
continue # source_file == scan root -> Path('.'), no file stem (#1618)
|
||||
new_stem = make_id(_file_stem(rel))
|
||||
if not new_stem:
|
||||
continue
|
||||
norm = _normalize_id(nid)
|
||||
if norm == new_stem or norm.startswith(new_stem + "_"):
|
||||
checked += 1
|
||||
else:
|
||||
for old in _old_file_stems(rel):
|
||||
if old != new_stem and (norm == old or norm.startswith(old + "_")):
|
||||
return True
|
||||
checked += 1
|
||||
if checked >= sample:
|
||||
break
|
||||
return False
|
||||
|
||||
|
||||
def _doc_twin_remap(nodes: list) -> dict[str, str]:
|
||||
"""Map a markdown quick-scan's bare doc node ``<slug>`` to the semantic
|
||||
``<slug>_doc`` node for the SAME file (#1799).
|
||||
|
||||
The markdown quick-scan (``extract_markdown``) mints a file node with the
|
||||
bare id ``_make_id(path)`` while the semantic pass mints ``<slug>_doc`` for
|
||||
the same document. A ``graphify update`` after a semantic build leaves both,
|
||||
splitting the file's edges across two disconnected nodes. Canonicalize to the
|
||||
semantic ``_doc`` node (it carries the richer references/hyperedges). Gated to
|
||||
``file_type == "document"`` on BOTH twins with an identical ``source_file``,
|
||||
so an unrelated code symbol ``foo`` and ``foo_doc`` never merge.
|
||||
"""
|
||||
by_id: dict[str, dict] = {}
|
||||
for n in nodes:
|
||||
if isinstance(n, dict) and n.get("id"):
|
||||
by_id[str(n["id"])] = n
|
||||
remap: dict[str, str] = {}
|
||||
for nid, node in by_id.items():
|
||||
if not nid.endswith("_doc"):
|
||||
continue
|
||||
bare = by_id.get(nid[:-4])
|
||||
if bare is None:
|
||||
continue
|
||||
sf = node.get("source_file")
|
||||
if not sf or bare.get("source_file") != sf:
|
||||
continue
|
||||
if node.get("file_type") != "document" or bare.get("file_type") != "document":
|
||||
continue
|
||||
remap[nid[:-4]] = nid
|
||||
return remap
|
||||
|
||||
|
||||
def build_from_json(extraction: dict, *, directed: bool = False, root: str | Path | None = None) -> nx.Graph:
|
||||
"""Build a NetworkX graph from an extraction dict.
|
||||
|
||||
@@ -421,165 +145,43 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
if ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
|
||||
node["file_type"] = _FILE_TYPE_SYNONYMS.get(ft, "concept")
|
||||
|
||||
# Canonicalize hyperedge member lists (#1561): producers sometimes key the
|
||||
# member list `members`/`node_ids` instead of `nodes`. Fold aliases onto
|
||||
# `nodes` here — BEFORE validation and the semantic-rekey loop below — so
|
||||
# every downstream consumer (rekey, source_file relativize, to_json) reads
|
||||
# one canonical key, the same way edge endpoints alias from/to at build.
|
||||
for he in extraction.get("hyperedges", []) or []:
|
||||
_normalize_hyperedge_members(he)
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
|
||||
real_errors = [e for e in errors if "does not match any node id" not in e]
|
||||
if real_errors:
|
||||
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
|
||||
# Deterministic semantic re-key (#1504/#1509): the node-ID stem is now the
|
||||
# full repo-relative path (docs/v1/api/README.md -> docs_v1_api_readme), but
|
||||
# the semantic cache is UNVERSIONED, so a cached/LLM fragment can still carry
|
||||
# an OLD short id whose stem was just the immediate parent dir (api_readme),
|
||||
# or a prompt-drifting id with zero parent dirs (readme). Rather than trust
|
||||
# LLM prose to emit the right stem, we re-derive every non-AST node's id from
|
||||
# its own source_file in code, so a drifted fragment physically reconciles
|
||||
# with the AST node instead of spawning a ghost / a re-bill. AST-origin nodes
|
||||
# already carry canonical ids (the extract() id-remap post-pass guarantees it)
|
||||
# and are left untouched.
|
||||
_rekey: dict[str, str] = _semantic_id_remap(extraction.get("nodes", []), _root)
|
||||
if _rekey:
|
||||
for node in extraction.get("nodes", []):
|
||||
if isinstance(node, dict) and node.get("id") in _rekey:
|
||||
node["id"] = _rekey[node["id"]]
|
||||
for edge in extraction.get("edges", []):
|
||||
if not isinstance(edge, dict):
|
||||
continue
|
||||
if edge.get("source") in _rekey:
|
||||
edge["source"] = _rekey[edge["source"]]
|
||||
if edge.get("target") in _rekey:
|
||||
edge["target"] = _rekey[edge["target"]]
|
||||
for he in extraction.get("hyperedges", []) or []:
|
||||
if isinstance(he, dict) and isinstance(he.get("nodes"), list):
|
||||
he["nodes"] = [_rekey.get(n, n) for n in he["nodes"]]
|
||||
|
||||
# Merge markdown quick-scan bare doc nodes into their semantic `_doc` twin
|
||||
# for the same file, so a document is one node regardless of which pipeline
|
||||
# touched it last (#1799).
|
||||
_doc_remap = _doc_twin_remap(extraction.get("nodes", []))
|
||||
if _doc_remap:
|
||||
extraction["nodes"] = [
|
||||
n for n in extraction.get("nodes", [])
|
||||
if not (isinstance(n, dict) and n.get("id") in _doc_remap)
|
||||
]
|
||||
_new_edges = []
|
||||
for edge in extraction.get("edges", []):
|
||||
if isinstance(edge, dict):
|
||||
s0, t0 = edge.get("source"), edge.get("target")
|
||||
if s0 in _doc_remap:
|
||||
edge["source"] = _doc_remap[s0]
|
||||
if t0 in _doc_remap:
|
||||
edge["target"] = _doc_remap[t0]
|
||||
# Drop only self-loops the remap itself collapsed (a bare->_doc
|
||||
# link becoming doc->doc); leave any pre-existing self-loop alone.
|
||||
if edge.get("source") == edge.get("target") and (s0 in _doc_remap or t0 in _doc_remap):
|
||||
continue
|
||||
_new_edges.append(edge)
|
||||
extraction["edges"] = _new_edges
|
||||
for he in extraction.get("hyperedges", []) or []:
|
||||
if isinstance(he, dict) and isinstance(he.get("nodes"), list):
|
||||
he["nodes"] = [_doc_remap.get(n, n) for n in he["nodes"]]
|
||||
|
||||
G: nx.Graph = nx.DiGraph() if directed else nx.Graph()
|
||||
for node in extraction.get("nodes", []):
|
||||
# Skip dict nodes with a missing or non-hashable id (e.g. a list emitted
|
||||
# by a buggy LLM extraction) so NetworkX add_node never raises
|
||||
# TypeError: unhashable type. Non-dict nodes are deliberately left to
|
||||
# raise as before, so callers that probe build for shape errors (e.g.
|
||||
# the multigraph diagnostic) still observe the malformed shape.
|
||||
if isinstance(node, dict):
|
||||
if "id" not in node:
|
||||
continue
|
||||
try:
|
||||
hash(node["id"])
|
||||
except TypeError:
|
||||
print(
|
||||
f"[graphify] WARNING: skipping node with non-hashable id "
|
||||
f"{node['id']!r} (must be a string).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
if "source_file" in node:
|
||||
node["source_file"] = _norm_source_file(node["source_file"], _root)
|
||||
if "source_file" in node:
|
||||
node["source_file"] = _norm_source_file(node["source_file"], _root)
|
||||
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
|
||||
node_set = set(G.nodes())
|
||||
|
||||
# #1145 (extended): merge LLM ghost-duplicate nodes into AST canonical nodes.
|
||||
# Original bug: AST uses parent-qualified IDs (mingpt_bpe_get_pairs) while LLM
|
||||
# uses bare-stem IDs (bpe_get_pairs) — different IDs, same symbol.
|
||||
# Original fix only caught LLM nodes with source_location=None; LLM now
|
||||
# populates source_location, so those ghosts survived. Extended fix: use
|
||||
# _origin=="ast" as the canonical signal. AST nodes always win; any non-AST
|
||||
# node sharing (basename, label) with an AST node is a ghost.
|
||||
_loc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> canonical node id
|
||||
_loc_collisions: set[tuple[str, str]] = set() # keys shared by 2+ AST nodes
|
||||
_noloc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> ghost node id
|
||||
|
||||
# Pass 1: collect canonical nodes — AST-origin nodes take precedence over LLM nodes.
|
||||
# When 2+ AST nodes share a key (same-named symbols in same-named files across
|
||||
# directories, e.g. render in two index.ts), the key is ambiguous: merging a
|
||||
# ghost would pick an arbitrary winner via set-iteration order (#1257). Track
|
||||
# those keys so Pass 2 skips them — same conservatism as
|
||||
# _rewire_unique_stub_nodes, which only merges when exactly one real def exists.
|
||||
# Iterate in a deterministic (sorted) order, not set-iteration order, so the
|
||||
# canonical winner and the ambiguity decisions below don't flip run-to-run
|
||||
# with CPython's per-process string-hash seed (#1753) — the same reason the
|
||||
# edge-iteration loop further down sorts on purpose.
|
||||
for nid in sorted(node_set):
|
||||
# #1145: merge semantic ghost-duplicate nodes into AST nodes.
|
||||
# When AST and semantic extractors emit different IDs for the same symbol
|
||||
# (one has source_location=L<n>, the other has source_location=None), find
|
||||
# pairs that share (source_file basename, label) and collapse the semantic
|
||||
# copy into the AST copy so edges re-point to a single node.
|
||||
# Two passes: first collect all AST (located) nodes, then find ghosts.
|
||||
_loc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> AST node id
|
||||
_noloc_nodes: dict[tuple[str, str], str] = {} # (basename, label) -> semantic node id
|
||||
for nid in node_set:
|
||||
attrs = G.nodes[nid]
|
||||
label = str(attrs.get("label", "")).strip()
|
||||
sf = str(attrs.get("source_file", ""))
|
||||
basename = Path(sf).name if sf else ""
|
||||
if not label or not basename:
|
||||
continue
|
||||
is_ast = attrs.get("_origin") == "ast"
|
||||
if attrs.get("source_location") or is_ast:
|
||||
key = (basename, label)
|
||||
if is_ast:
|
||||
# Two AST nodes on the same key is an ambiguous collision.
|
||||
if key in _loc_nodes and G.nodes[_loc_nodes[key]].get("_origin") == "ast":
|
||||
_loc_collisions.add(key)
|
||||
# AST-origin nodes always overwrite a prior non-AST entry.
|
||||
_loc_nodes[key] = nid
|
||||
else:
|
||||
existing = _loc_nodes.get(key)
|
||||
if existing is None:
|
||||
_loc_nodes[key] = nid
|
||||
elif (
|
||||
G.nodes[existing].get("_origin") != "ast"
|
||||
and str(G.nodes[existing].get("source_file", "")) != sf
|
||||
):
|
||||
# Two NON-AST nodes sharing (basename, label) but coming from
|
||||
# DIFFERENT files are distinct concepts (e.g. a same-named
|
||||
# concept in dir_a/update.md and dir_b/update.md), not an AST
|
||||
# ghost/canonical twin. Merging them would drop a real node
|
||||
# and pick the survivor arbitrarily via iteration order
|
||||
# (#1753). Mark the key ambiguous so Pass 2 leaves both, the
|
||||
# same conservatism the AST/AST case uses (#1257). A genuine
|
||||
# same-file duplicate (identical source_file) is not flagged
|
||||
# and still collapses.
|
||||
_loc_collisions.add(key)
|
||||
|
||||
# Pass 2: find ghosts — non-AST nodes that have an AST canonical twin.
|
||||
for nid in sorted(node_set):
|
||||
if attrs.get("source_location"):
|
||||
_loc_nodes[(basename, label)] = nid
|
||||
for nid in node_set:
|
||||
attrs = G.nodes[nid]
|
||||
if attrs.get("_origin") == "ast":
|
||||
continue # AST nodes are never ghosts
|
||||
label = str(attrs.get("label", "")).strip()
|
||||
sf = str(attrs.get("source_file", ""))
|
||||
basename = Path(sf).name if sf else ""
|
||||
if not label or not basename:
|
||||
if not label or not basename or attrs.get("source_location"):
|
||||
continue
|
||||
key = (basename, label)
|
||||
if key in _loc_collisions:
|
||||
continue # ambiguous key: no safe canonical winner, leave ghost intact
|
||||
if key in _loc_nodes and _loc_nodes[key] != nid:
|
||||
_noloc_nodes[key] = nid
|
||||
# For every ghost that has an AST counterpart, record a remap.
|
||||
@@ -601,61 +203,6 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
for ghost_id, canonical_id in _ghost_remap.items():
|
||||
norm_to_id[_normalize_id(ghost_id)] = canonical_id
|
||||
norm_to_id[ghost_id] = canonical_id
|
||||
# Pre-migration alias index (#1504): register each canonical node's OLD-stem id
|
||||
# forms as aliases so a stale-id edge endpoint coming from an un-re-keyed
|
||||
# fragment (e.g. an incremental update whose fragment references a symbol in a
|
||||
# file that was NOT re-extracted) still resolves to the migrated node instead
|
||||
# of dangling. Only fills gaps — never overrides a real node id.
|
||||
#
|
||||
# The old-stem form drops the extension and (for the file node itself) every
|
||||
# directory but the immediate parent, so it collapses easily: "ping.h" and
|
||||
# "ping.php" in different directories both alias to bare "ping". Collecting
|
||||
# every candidate for an alias BEFORE committing any of them — and only
|
||||
# committing when exactly one candidate claims it — keeps this a precise
|
||||
# re-keying aid instead of a silent cross-file (and cross-language) merge.
|
||||
# Without this, a dangling edge to a bare, deliberately-unscoped fallback id
|
||||
# (e.g. the C/C++ extractor's last-resort target for an #include it couldn't
|
||||
# resolve to a real path) could ride this alias onto whichever unrelated
|
||||
# same-stem file happened to be inserted first into ``node_set`` — a Python
|
||||
# set, so "first" is hash-order, not anything meaningful.
|
||||
#
|
||||
# A file node's OWN id is not always a clean ``new_stem`` prefix: when a
|
||||
# same-directory ``.h``/``.cpp`` pair collides on their shared pre-extension
|
||||
# id, _disambiguate_colliding_node_ids salts both apart into ids like
|
||||
# ``tools_aolserver_utility_h_tools_aolserver_utility`` — which no longer
|
||||
# string-prefixes cleanly for the suffix math below. Detecting "this IS the
|
||||
# file node" by label (every file node's label is its own basename,
|
||||
# regardless of id mangling) instead of by id shape keeps a salted file node
|
||||
# in the alias competition, so a genuine collision (a C header AND an
|
||||
# unrelated same-named PHP script) is still caught as ambiguous instead of
|
||||
# the header silently dropping out of the race and leaving the PHP file as
|
||||
# the lone (wrong) "unambiguous" winner.
|
||||
from graphify.extractors.base import _file_stem as _fs
|
||||
_alias_candidates: dict[str, set[str]] = {}
|
||||
for nid in node_set:
|
||||
attrs = G.nodes[nid]
|
||||
sf = attrs.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
rel = Path(str(sf))
|
||||
if rel.is_absolute():
|
||||
continue
|
||||
new_stem = make_id(_fs(rel))
|
||||
if str(attrs.get("label", "")) == rel.name:
|
||||
suffix = "" # this node IS the file, whatever its (possibly salted) id
|
||||
else:
|
||||
suffix = ""
|
||||
if _normalize_id(nid).startswith(new_stem):
|
||||
suffix = _normalize_id(nid)[len(new_stem):] # leading "_entity" or ""
|
||||
for old_stem in _old_file_stems(rel):
|
||||
if old_stem == new_stem:
|
||||
continue
|
||||
alias = old_stem + suffix
|
||||
_alias_candidates.setdefault(_normalize_id(alias), set()).add(nid)
|
||||
_alias_candidates.setdefault(alias, set()).add(nid)
|
||||
for alias_key, candidates in _alias_candidates.items():
|
||||
if len(candidates) == 1:
|
||||
norm_to_id.setdefault(alias_key, next(iter(candidates)))
|
||||
# Iterate edges in a deterministic order. The graph is undirected and stores
|
||||
# direction in _src/_tgt; when two edges collapse onto the same node pair the
|
||||
# last write wins, so an unstable iteration order flips _src/_tgt run-to-run
|
||||
@@ -675,19 +222,6 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
if "source" not in edge or "target" not in edge:
|
||||
continue
|
||||
src, tgt = edge["source"], edge["target"]
|
||||
# Skip edges with non-hashable endpoints (e.g. a list emitted by a buggy
|
||||
# LLM extraction) so the `not in node_set` membership test below never
|
||||
# raises TypeError: unhashable type. The validator already reported these.
|
||||
try:
|
||||
hash(src)
|
||||
hash(tgt)
|
||||
except TypeError:
|
||||
print(
|
||||
f"[graphify] WARNING: skipping edge with non-hashable endpoint "
|
||||
f"(source={src!r}, target={tgt!r}).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
# Remap mismatched IDs via normalization before dropping the edge.
|
||||
if src not in node_set:
|
||||
src = norm_to_id.get(_normalize_id(src), src)
|
||||
@@ -696,42 +230,25 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
if src not in node_set or tgt not in node_set:
|
||||
continue # skip edges to external/stdlib nodes - expected, not an error
|
||||
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
|
||||
# Backfill source_file from the endpoint nodes (every node carries one).
|
||||
# Semantic/LLM edges occasionally omit it, which downstream validation
|
||||
# flags and leaves query results with no file reference (#1279).
|
||||
if not attrs.get("source_file"):
|
||||
attrs["source_file"] = (
|
||||
G.nodes[src].get("source_file")
|
||||
or G.nodes[tgt].get("source_file")
|
||||
or ""
|
||||
)
|
||||
if "source_file" in attrs:
|
||||
attrs["source_file"] = _norm_source_file(attrs["source_file"], _root)
|
||||
# Drop cross-language phantom edges — the same short names (render, parse,
|
||||
# time, ...) recur across language boundaries, so an unresolved target can
|
||||
# bind to a same-named node in another language. The extraction spec forbids
|
||||
# this for `calls`; it is equally invalid for `imports`/`references` (a
|
||||
# Python `import time` must not bind to a `time.ts`, #1749).
|
||||
_edge_rel = attrs.get("relation")
|
||||
if _edge_rel in ("calls", "imports", "imports_from", "references"):
|
||||
# Drop cross-language INFERRED `calls` edges — same short names (render,
|
||||
# parse, etc.) appear across language boundaries in multi-language chunks,
|
||||
# producing phantom edges that don't represent real call relationships.
|
||||
if attrs.get("relation") == "calls" and attrs.get("confidence") == "INFERRED":
|
||||
_LANG_FAMILY: dict[str, str] = {
|
||||
".py": "py", ".pyi": "py",
|
||||
".js": "js", ".mjs": "js", ".cjs": "js", ".jsx": "js",
|
||||
".ts": "js", ".tsx": "js",
|
||||
".go": "go", ".rs": "rs",
|
||||
".java": "jvm", ".kt": "jvm", ".scala": "jvm", ".groovy": "jvm",
|
||||
".c": "c", ".h": "c", ".cc": "cpp", ".cpp": "cpp", ".hpp": "cpp",
|
||||
".rb": "rb", ".php": "php", ".cs": "cs", ".swift": "swift", ".lua": "lua",
|
||||
}
|
||||
src_ext = Path(G.nodes[src].get("source_file") or "").suffix.lower()
|
||||
tgt_ext = Path(G.nodes[tgt].get("source_file") or "").suffix.lower()
|
||||
src_fam = _EDGE_LANG_FAMILY.get(src_ext)
|
||||
tgt_fam = _EDGE_LANG_FAMILY.get(tgt_ext)
|
||||
if _edge_rel == "calls":
|
||||
# Unchanged #1547/#1556 behavior: only INFERRED calls, and drop as
|
||||
# soon as either family differs (an unknown ext counts as different).
|
||||
if (
|
||||
attrs.get("confidence") == "INFERRED"
|
||||
and src_ext and tgt_ext and src_fam != tgt_fam
|
||||
):
|
||||
continue
|
||||
else:
|
||||
# imports/references: drop only when BOTH endpoints are known code
|
||||
# languages of different families, so a config->code reference
|
||||
# (unknown ext, e.g. a manifest) is never mistaken for a phantom.
|
||||
if src_fam is not None and tgt_fam is not None and src_fam != tgt_fam:
|
||||
continue
|
||||
if src_ext and tgt_ext and _LANG_FAMILY.get(src_ext) != _LANG_FAMILY.get(tgt_ext):
|
||||
continue
|
||||
# Preserve original edge direction - undirected graphs lose it otherwise,
|
||||
# causing display functions to show edges backwards.
|
||||
attrs["_src"] = src
|
||||
@@ -752,12 +269,6 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
G.add_edge(src, tgt, **attrs)
|
||||
hyperedges = extraction.get("hyperedges", [])
|
||||
if hyperedges:
|
||||
# Relativize hyperedge source_file the same way nodes and edges are
|
||||
# (above), so to_json — which has no root and writes G.graph["hyperedges"]
|
||||
# verbatim — never leaks an absolute path from a semantic subagent (#1418).
|
||||
for he in hyperedges:
|
||||
if isinstance(he, dict) and he.get("source_file"):
|
||||
he["source_file"] = _norm_source_file(he["source_file"], _root)
|
||||
G.graph["hyperedges"] = hyperedges
|
||||
return G
|
||||
|
||||
@@ -800,10 +311,8 @@ def build(
|
||||
return build_from_json(combined, directed=directed, root=root)
|
||||
|
||||
|
||||
def _norm_label(label: str | None) -> str:
|
||||
def _norm_label(label: str) -> str:
|
||||
"""Canonical dedup key — Unicode-aware, preserves CJK/word characters."""
|
||||
if not isinstance(label, str):
|
||||
label = "" if label is None else str(label)
|
||||
label = unicodedata.normalize("NFKC", label)
|
||||
return re.sub(r"[\W_ ]+", " ", label.casefold(), flags=re.UNICODE).strip()
|
||||
|
||||
@@ -812,15 +321,7 @@ def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dic
|
||||
"""Merge nodes that share a normalised label, rewriting edge references.
|
||||
|
||||
Prefers IDs without chunk suffixes (_c\\d+) and shorter IDs when tied.
|
||||
Drops self-loops created by the merge.
|
||||
|
||||
Dormant: this is NOT wired into ``build()`` — the active dedup path is
|
||||
``deduplicate_entities`` (imported and called in ``build``), which supersedes
|
||||
it. The previous "Called in build() automatically" note was never true. It
|
||||
also merges by label alone with no ``file_type`` guard, so it must not be
|
||||
enabled for code nodes: same-label symbols from different files/packages
|
||||
(e.g. two ``Account`` types) would collapse into one — the cross-file
|
||||
conflation ``deduplicate_entities`` deliberately avoids for code (#1205).
|
||||
Drops self-loops created by the merge. Called in build() automatically.
|
||||
"""
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
canonical: dict[str, dict] = {} # norm_label -> surviving node
|
||||
@@ -864,7 +365,7 @@ def deduplicate_by_label(nodes: list[dict], edges: list[dict]) -> tuple[list[dic
|
||||
|
||||
def build_merge(
|
||||
new_chunks: list[dict],
|
||||
graph_path: str | Path | None = None,
|
||||
graph_path: str | Path = "graphify-out/graph.json",
|
||||
prune_sources: list[str] | None = None,
|
||||
*,
|
||||
directed: bool = False,
|
||||
@@ -874,14 +375,11 @@ def build_merge(
|
||||
) -> nx.Graph:
|
||||
"""Load existing graph.json, merge new chunks into it, and save back.
|
||||
|
||||
Re-extracted files REPLACE their prior contribution: any source_file present
|
||||
in new_chunks is dropped from the loaded graph before merging, so a changed
|
||||
file's stale nodes/edges don't accumulate. Files absent from new_chunks are
|
||||
preserved unchanged; deleted files are removed via prune_sources.
|
||||
Safe to call repeatedly.
|
||||
Never replaces - only grows (or prunes deleted-file nodes via prune_sources).
|
||||
Safe to call repeatedly: existing nodes and edges are preserved.
|
||||
root: if given, absolute source_file paths in new_chunks are made relative (#932).
|
||||
"""
|
||||
graph_path = Path(graph_path if graph_path is not None else _default_graph_json())
|
||||
graph_path = Path(graph_path)
|
||||
if graph_path.exists():
|
||||
# Read JSON directly instead of going through node_link_graph().
|
||||
# The latter rebuilds an undirected nx.Graph and then enumerating
|
||||
@@ -892,115 +390,35 @@ def build_merge(
|
||||
# NetworkX round-trip loses direction permanently (#760).
|
||||
from graphify.security import check_graph_file_size_cap
|
||||
check_graph_file_size_cap(graph_path)
|
||||
try:
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise RuntimeError(
|
||||
f"Cannot read {graph_path} for incremental merge: {exc}. "
|
||||
"Delete the file and run a full rebuild."
|
||||
) from exc
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
links_key = "links" if "links" in data else "edges"
|
||||
existing_nodes = list(data.get("nodes", []))
|
||||
existing_edges = list(data.get(links_key, []))
|
||||
existing_hyperedges = list(data.get("hyperedges", []))
|
||||
had_graph = True
|
||||
base = [{"nodes": existing_nodes, "edges": existing_edges}]
|
||||
else:
|
||||
existing_nodes = []
|
||||
existing_edges = []
|
||||
existing_hyperedges = []
|
||||
had_graph = False
|
||||
|
||||
# Effective root for relativizing absolute source_file / prune paths back to the
|
||||
# stored relative source_file keys. When the caller passes root we use it;
|
||||
# otherwise fall back to the graph's recorded scan root, so absolute
|
||||
# prune_sources and new-chunk paths still match even when a caller omits root
|
||||
# (#1571 — the skill's --update runbook calls build_merge without root, so
|
||||
# absolute deleted-file paths never matched the relative node keys and their
|
||||
# nodes survived as ghosts).
|
||||
_eff_root = (
|
||||
str(Path(root).resolve()) if root is not None
|
||||
else _infer_merge_root(graph_path)
|
||||
)
|
||||
|
||||
# Re-extracted files REPLACE their prior contribution. Every source_file
|
||||
# present in new_chunks is dropped from the loaded base before merging, so a
|
||||
# CHANGED file's stale nodes/edges don't accumulate across incremental
|
||||
# updates. Without this, build() merges old+new for the same file and only
|
||||
# exact-duplicate edges collapse — edges/nodes that disappeared from the new
|
||||
# version survive forever. Brand-new files aren't in base, so this is a no-op
|
||||
# for them; genuinely deleted files are still handled via prune_sources.
|
||||
# Matched in both raw and _norm_source_file form because new_chunks may carry
|
||||
# absolute win32 paths while the stored graph keeps relative posix (#1007).
|
||||
_replace_root = _eff_root
|
||||
new_sources: set[str] = set()
|
||||
for ch in new_chunks:
|
||||
for n in ch.get("nodes", []):
|
||||
sf = n.get("source_file")
|
||||
if not sf:
|
||||
continue
|
||||
new_sources.add(sf)
|
||||
norm = _norm_source_file(sf, _replace_root)
|
||||
if norm:
|
||||
new_sources.add(norm)
|
||||
if new_sources:
|
||||
def _kept(item: dict) -> bool:
|
||||
sf = item.get("source_file")
|
||||
return sf not in new_sources and _norm_source_file(sf, _replace_root) not in new_sources
|
||||
existing_nodes = [n for n in existing_nodes if _kept(n)]
|
||||
existing_edges = [e for e in existing_edges if _kept(e)]
|
||||
|
||||
base = [{"nodes": existing_nodes, "edges": existing_edges}] if had_graph else []
|
||||
base = []
|
||||
|
||||
all_chunks = base + list(new_chunks)
|
||||
G = build(all_chunks, directed=directed, dedup=dedup, dedup_llm_backend=dedup_llm_backend, root=root)
|
||||
|
||||
# Prune set for deleted source files — both the raw form (matches nodes that
|
||||
# kept absolute source_file) and the normalised relative form (matches nodes
|
||||
# relativised by _norm_source_file at build time). .resolve() (via _eff_root)
|
||||
# handles symlinked roots and ".." / "./" segments so Path.relative_to()
|
||||
# succeeds even when the scan root is a symlink. (#1007, #1571)
|
||||
prune_set: set[str] = set()
|
||||
for p in (prune_sources or []):
|
||||
if not p:
|
||||
continue
|
||||
prune_set.add(p)
|
||||
norm = _norm_source_file(p, _eff_root)
|
||||
if norm:
|
||||
prune_set.add(norm)
|
||||
# A file that was just re-extracted (present in new_chunks) is being REPLACED,
|
||||
# never deleted — so never prune it, even if the caller also lists it in
|
||||
# prune_sources. Otherwise its fresh, just-built nodes are silently removed
|
||||
# (data loss): common when an edit keeps a node's label and the caller follows
|
||||
# the old edit-workflow of passing the changed file in prune_sources (#1796).
|
||||
# "replace" wins over a contradictory "delete" of the same source.
|
||||
prune_set -= new_sources
|
||||
|
||||
# Carry forward hyperedges from files that were neither re-extracted nor
|
||||
# deleted (#1574). build() only sees the new chunks' hyperedges, so without
|
||||
# this every --update collapses the graph's hyperedge set down to just the
|
||||
# changed files'. Re-extracted files' prior hyperedges are dropped (their new
|
||||
# version is already in G — replace-per-source, like nodes/edges); deleted
|
||||
# files' are dropped via prune_set. id-dedup (attach_hyperedges) so a carried
|
||||
# hyperedge never duplicates one the new chunks re-emitted. Mirrors watch.py,
|
||||
# which already preserves existing hyperedges across a rebuild.
|
||||
if existing_hyperedges:
|
||||
carried = []
|
||||
for he in existing_hyperedges:
|
||||
if not isinstance(he, dict):
|
||||
continue
|
||||
sf = he.get("source_file")
|
||||
norm = _norm_source_file(sf, _eff_root)
|
||||
if sf in new_sources or norm in new_sources:
|
||||
continue # re-extracted — replaced by the new chunk's version
|
||||
if sf in prune_set or norm in prune_set:
|
||||
continue # deleted — pruned
|
||||
carried.append(he)
|
||||
if carried:
|
||||
from graphify.export import attach_hyperedges
|
||||
attach_hyperedges(G, carried)
|
||||
|
||||
# Prune nodes and edges from deleted source files
|
||||
if prune_sources:
|
||||
# Build a set containing both the raw form (matches nodes that kept
|
||||
# absolute source_file) and the normalised relative form (matches nodes
|
||||
# that were relativised by _norm_source_file at build time).
|
||||
# .resolve() handles symlinked roots and redundant ".." / "./" segments
|
||||
# so Path.relative_to() succeeds even when the scan root is a symlink.
|
||||
# (#1007: manifest absolute paths vs graph relative source_file mismatch)
|
||||
_root_str = str(Path(root).resolve()) if root is not None else None
|
||||
prune_set: set[str] = set()
|
||||
for p in prune_sources:
|
||||
if not p:
|
||||
continue
|
||||
prune_set.add(p)
|
||||
norm = _norm_source_file(p, _root_str)
|
||||
if norm:
|
||||
prune_set.add(norm)
|
||||
to_remove = [
|
||||
n for n, d in G.nodes(data=True)
|
||||
if d.get("source_file") in prune_set
|
||||
@@ -1062,34 +480,6 @@ def prefix_graph_for_global(G: nx.Graph, repo_tag: str) -> nx.Graph:
|
||||
return H
|
||||
|
||||
|
||||
def distinct_repo_tags(graph_paths: "list[Path]") -> "list[str]":
|
||||
"""Return a unique, human-meaningful repo tag per input graph for merge-graphs.
|
||||
|
||||
The naive tag (the ``graphify-out`` parent dir name) is NOT unique across
|
||||
inputs: ``src/graphify-out`` and ``frontend/src/graphify-out`` both yield
|
||||
``src``. Prefixing both node sets with ``src::`` then makes same-stem nodes
|
||||
(a backend ``src/app.js`` and a frontend ``App.jsx``, both bare ``app``)
|
||||
collide, so ``nx.compose`` silently merges two unrelated entities and invents
|
||||
cross-runtime edges (#1729). Colliding tags are widened with their own parent
|
||||
dir (``frontend_src``), then an index suffix guarantees uniqueness so no two
|
||||
graphs ever share a prefix.
|
||||
"""
|
||||
repo_dirs = [p.parent.parent for p in graph_paths] # graphify-out/.. → repo dir
|
||||
tags = [d.name or "repo" for d in repo_dirs]
|
||||
if len(set(tags)) != len(tags):
|
||||
widened: list[str] = []
|
||||
for d in repo_dirs:
|
||||
parent = d.parent.name
|
||||
widened.append(f"{parent}_{d.name}" if parent and d.name else (d.name or "repo"))
|
||||
tags = widened
|
||||
seen: dict[str, int] = {}
|
||||
unique: list[str] = []
|
||||
for t in tags:
|
||||
seen[t] = seen.get(t, 0) + 1
|
||||
unique.append(t if seen[t] == 1 else f"{t}-{seen[t]}")
|
||||
return unique
|
||||
|
||||
|
||||
def prune_repo_from_graph(G: nx.Graph, repo_tag: str) -> int:
|
||||
"""Remove all nodes tagged with repo_tag from G in-place. Returns count removed."""
|
||||
to_remove = [n for n, d in G.nodes(data=True) if d.get("repo") == repo_tag]
|
||||
|
||||
+45
-268
@@ -5,84 +5,23 @@ import atexit
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import warnings
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
# Output directory name — override with GRAPHIFY_OUT env var for worktrees or
|
||||
# shared-output setups. Accepts a relative name ("graphify-out-feature") or an
|
||||
# absolute path ("/shared/graphify-out"). Single source of truth in graphify.paths
|
||||
# (#1423); re-exported here as _GRAPHIFY_OUT for the existing call sites.
|
||||
from graphify.paths import GRAPHIFY_OUT as _GRAPHIFY_OUT
|
||||
|
||||
# AST cache entries are the output of graphify's own extractor code, so they
|
||||
# are only valid for the version that wrote them: keying purely on file
|
||||
# content means extractor fixes shipped in a new release keep serving stale
|
||||
# pre-fix results. The AST cache is therefore namespaced by package version
|
||||
# (cache/ast/v{version}/), with entries from other versions removed on first
|
||||
# use. The semantic cache is deliberately NOT versioned — its entries are
|
||||
# produced by the LLM from file contents, and invalidating them on every
|
||||
# release would re-bill extraction for unchanged files.
|
||||
try:
|
||||
from importlib.metadata import version as _pkg_version
|
||||
|
||||
_EXTRACTOR_VERSION = _pkg_version("graphifyy")
|
||||
except Exception:
|
||||
_EXTRACTOR_VERSION = "unknown"
|
||||
|
||||
# Version dirs already swept this process — cleanup runs once per (base, version).
|
||||
_cleaned_ast_dirs: set[str] = set()
|
||||
|
||||
|
||||
def _cleanup_stale_ast_entries(ast_base: Path, current_dir: Path) -> None:
|
||||
"""Remove AST cache entries left behind by other graphify versions.
|
||||
|
||||
Sweeps sibling ``v*/`` directories and unversioned ``*.json`` entries
|
||||
(the pre-versioning layout) under ``cache/ast/``. Best-effort: failures
|
||||
are ignored, stragglers are retried on the next run.
|
||||
"""
|
||||
key = str(current_dir)
|
||||
if key in _cleaned_ast_dirs:
|
||||
return
|
||||
_cleaned_ast_dirs.add(key)
|
||||
if not ast_base.is_dir():
|
||||
return
|
||||
import shutil
|
||||
|
||||
for child in ast_base.iterdir():
|
||||
if child == current_dir:
|
||||
continue
|
||||
try:
|
||||
if child.is_dir() and child.name.startswith("v"):
|
||||
shutil.rmtree(child, ignore_errors=True)
|
||||
elif child.suffix == ".json":
|
||||
child.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# A frontmatter delimiter is a whole line of exactly three dashes (optional
|
||||
# trailing whitespace). Substring checks like startswith("---") /
|
||||
# find("\n---") also match `----` thematic breaks and `--- text` prose,
|
||||
# silently dropping everything above them from the hash (#1259).
|
||||
_FRONTMATTER_DELIM = re.compile(r"^---[ \t]*\r?$", re.MULTILINE)
|
||||
# absolute path ("/shared/graphify-out").
|
||||
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
|
||||
|
||||
|
||||
def _body_content(content: bytes) -> bytes:
|
||||
"""Strip YAML frontmatter from Markdown content, returning only the body."""
|
||||
text = content.decode(errors="replace")
|
||||
opener = _FRONTMATTER_DELIM.match(text)
|
||||
if opener is None:
|
||||
return content
|
||||
closer = _FRONTMATTER_DELIM.search(text, opener.end())
|
||||
if closer is None:
|
||||
return content
|
||||
# Slice right after the closing `---` (not after its line) so the output
|
||||
# stays byte-identical with the historical implementation for well-formed
|
||||
# frontmatter -- existing semantic-cache hashes must not churn.
|
||||
return text[closer.start() + 3:].encode()
|
||||
if text.startswith("---"):
|
||||
end = text.find("\n---", 3)
|
||||
if end != -1:
|
||||
return text[end + 4:].encode()
|
||||
return content
|
||||
|
||||
|
||||
# Stat-based index: maps absolute path → {size, mtime_ns, hash}.
|
||||
@@ -102,15 +41,11 @@ def _stat_index_file(root: Path) -> Path:
|
||||
return base / "cache" / "stat-index.json"
|
||||
|
||||
|
||||
def _ensure_stat_index(root: Path, cache_root: "Path | None" = None) -> None:
|
||||
def _ensure_stat_index(root: Path) -> None:
|
||||
global _stat_index, _stat_index_root, _stat_index_dirty
|
||||
if _stat_index_root is not None:
|
||||
return
|
||||
# The stat index only determines the cache FILE location (entry keys are
|
||||
# absolute paths), so honoring an explicit cache_root keeps detect()'s
|
||||
# word-count cache under the requested --out dir instead of polluting the
|
||||
# scanned corpus with a stray graphify-out/ (#1747).
|
||||
_stat_index_root = Path(cache_root if cache_root is not None else root).resolve()
|
||||
_stat_index_root = Path(root).resolve()
|
||||
p = _stat_index_file(_stat_index_root)
|
||||
if p.exists():
|
||||
try:
|
||||
@@ -159,7 +94,7 @@ def _normalize_path(path: Path) -> Path:
|
||||
return Path(os.path.normcase(s))
|
||||
|
||||
|
||||
def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = None) -> str:
|
||||
def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
"""SHA256 of file contents + path relative to root.
|
||||
|
||||
Uses a stat-based fastpath (size + mtime_ns) to skip full reads when the
|
||||
@@ -179,18 +114,13 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
|
||||
if not p.is_file():
|
||||
raise IsADirectoryError(f"file_hash requires a file, got: {p}")
|
||||
|
||||
# The stat index is a cache artifact, so it must follow the cache location
|
||||
# (cache_root), not the key-anchor root — otherwise it leaves a stray
|
||||
# graphify-out/cache/stat-index.json inside the analyzed source tree even when
|
||||
# the AST cache itself is redirected to CWD (#1774 completion).
|
||||
_ensure_stat_index(root, cache_root=cache_root)
|
||||
_ensure_stat_index(root)
|
||||
abs_key = str(p.resolve())
|
||||
st: "os.stat_result | None" = None
|
||||
try:
|
||||
st = p.stat()
|
||||
entry = _stat_index.get(abs_key)
|
||||
if (entry
|
||||
and entry.get("hash") is not None # word-count-only entries carry no hash
|
||||
and entry.get("size") == st.st_size
|
||||
and entry.get("mtime_ns") == st.st_mtime_ns):
|
||||
return entry["hash"]
|
||||
@@ -210,65 +140,12 @@ def file_hash(path: Path, root: Path = Path("."), cache_root: "Path | None" = No
|
||||
digest = h.hexdigest()
|
||||
|
||||
if st is not None:
|
||||
entry = _stat_index.get(abs_key)
|
||||
if (entry is not None
|
||||
and entry.get("size") == st.st_size
|
||||
and entry.get("mtime_ns") == st.st_mtime_ns):
|
||||
entry["hash"] = digest # preserve a co-located word_count
|
||||
else:
|
||||
_stat_index[abs_key] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns, "hash": digest}
|
||||
_stat_index[abs_key] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns, "hash": digest}
|
||||
_stat_index_dirty = True
|
||||
|
||||
return digest
|
||||
|
||||
|
||||
def cached_word_count(path: Path, root: Path, compute, cache_root: "Path | None" = None) -> int:
|
||||
"""Word count with the same (size, mtime_ns) stat-fastpath cache as
|
||||
:func:`file_hash`, persisted in the shared stat index.
|
||||
|
||||
``detect()`` counts words in every PDF/docx/text file to size the corpus,
|
||||
which re-opens and re-parses every binary on each run — minutes on a large
|
||||
docs corpus even when only a handful of files changed (#1656). This caches
|
||||
the count against the file's stat signature so an unchanged file is counted
|
||||
once and read from the index thereafter. ``compute(path)`` produces the
|
||||
count on a miss. A file that can't be stat'd (e.g. a Windows long path the
|
||||
index normalization can't reach) simply recomputes and isn't cached —
|
||||
correct, just not accelerated.
|
||||
"""
|
||||
global _stat_index_dirty
|
||||
p = _normalize_path(Path(path))
|
||||
root = _normalize_path(Path(root))
|
||||
_ensure_stat_index(root, cache_root=cache_root)
|
||||
abs_key = str(p.resolve())
|
||||
st: "os.stat_result | None" = None
|
||||
try:
|
||||
st = p.stat()
|
||||
entry = _stat_index.get(abs_key)
|
||||
if (entry
|
||||
and entry.get("size") == st.st_size
|
||||
and entry.get("mtime_ns") == st.st_mtime_ns
|
||||
and "word_count" in entry):
|
||||
return entry["word_count"]
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
wc = compute(Path(path))
|
||||
|
||||
if st is not None:
|
||||
entry = _stat_index.get(abs_key)
|
||||
if (entry
|
||||
and entry.get("size") == st.st_size
|
||||
and entry.get("mtime_ns") == st.st_mtime_ns):
|
||||
entry["word_count"] = wc # augment the existing hash entry in place
|
||||
else:
|
||||
_stat_index[abs_key] = {
|
||||
"size": st.st_size, "mtime_ns": st.st_mtime_ns, "word_count": wc,
|
||||
}
|
||||
_stat_index_dirty = True
|
||||
|
||||
return wc
|
||||
|
||||
|
||||
def _relativize_source_files_in(payload: dict, root: Path) -> None:
|
||||
"""Mutate ``payload`` to rewrite absolute ``source_file`` fields as
|
||||
forward-slash relative paths from ``root``.
|
||||
@@ -286,11 +163,7 @@ def _relativize_source_files_in(payload: dict, root: Path) -> None:
|
||||
root_resolved = Path(root).resolve()
|
||||
except OSError:
|
||||
return
|
||||
# raw_calls (#: Pascal/Delphi cross-file inherited-call resolution) carries
|
||||
# source_file the same way nodes/edges/hyperedges do, so it needs the same
|
||||
# portable-path treatment for cache entries to round-trip correctly across
|
||||
# machines/checkout directories.
|
||||
for bucket in ("nodes", "edges", "hyperedges", "raw_calls"):
|
||||
for bucket in ("nodes", "edges", "hyperedges"):
|
||||
for item in payload.get(bucket, []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
@@ -321,7 +194,7 @@ def _absolutize_source_files_in(payload: dict, root: Path) -> None:
|
||||
root_resolved = Path(root).resolve()
|
||||
except OSError:
|
||||
return
|
||||
for bucket in ("nodes", "edges", "hyperedges", "raw_calls"):
|
||||
for bucket in ("nodes", "edges", "hyperedges"):
|
||||
for item in payload.get(bucket, []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
@@ -338,53 +211,33 @@ def _absolutize_source_files_in(payload: dict, root: Path) -> None:
|
||||
|
||||
|
||||
def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
|
||||
"""Returns the cache directory for ``kind`` - creates it if needed.
|
||||
"""Returns graphify-out/cache/{kind}/ - creates it if needed.
|
||||
|
||||
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
|
||||
entries from overwriting AST cache entries for the same source_file (#582).
|
||||
|
||||
AST entries live in graphify-out/cache/ast/v{version}/ — namespaced by
|
||||
graphify version because they depend on extractor code, not just file
|
||||
contents. Semantic entries live unversioned in graphify-out/cache/semantic/
|
||||
(re-extraction costs LLM calls).
|
||||
"""
|
||||
_out = Path(_GRAPHIFY_OUT)
|
||||
base = _out if _out.is_absolute() else Path(root).resolve() / _out
|
||||
d = base / "cache" / kind
|
||||
if kind == "ast":
|
||||
d = d / f"v{_EXTRACTOR_VERSION}"
|
||||
_cleanup_stale_ast_entries(d.parent, d)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast",
|
||||
cache_root: Path | None = None) -> dict | None:
|
||||
def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict | None:
|
||||
"""Return cached extraction for this file if hash matches, else None.
|
||||
|
||||
Cache key: SHA256 of file contents.
|
||||
Cache value: stored as graphify-out/cache/{kind}/{hash}.json (AST entries
|
||||
under the per-version subdirectory, see :func:`cache_dir`).
|
||||
Cache value: stored as graphify-out/cache/{kind}/{hash}.json
|
||||
|
||||
``root`` anchors the content-hash key and source_file relativization (it
|
||||
must stay the inferred common parent so keys remain portable). ``cache_root``
|
||||
decouples *where* the cache directory lives from that anchor — the cache is
|
||||
an output and must not land inside a read-only/analyzed source tree (#1774).
|
||||
When ``cache_root`` is None the location falls back to ``root`` (unchanged
|
||||
behavior for existing callers).
|
||||
|
||||
AST entries written by other graphify versions — including the legacy
|
||||
flat cache/ layout (pre-0.5.3) and the unversioned cache/ast/ layout —
|
||||
are deliberately not consulted: they were produced by a different
|
||||
extractor and may be stale.
|
||||
For kind="ast", also checks the legacy flat cache/ directory so users
|
||||
upgrading from pre-0.5.3 don't lose their existing AST cache entries.
|
||||
Returns None if no cache entry or file has changed.
|
||||
"""
|
||||
location = cache_root if cache_root is not None else root
|
||||
try:
|
||||
h = file_hash(path, root, cache_root=cache_root)
|
||||
h = file_hash(path, root)
|
||||
except OSError:
|
||||
return None
|
||||
entry = cache_dir(location, kind) / f"{h}.json"
|
||||
entry = cache_dir(root, kind) / f"{h}.json"
|
||||
if entry.exists():
|
||||
try:
|
||||
result = json.loads(entry.read_text(encoding="utf-8"))
|
||||
@@ -396,20 +249,26 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast",
|
||||
if isinstance(result, dict):
|
||||
_absolutize_source_files_in(result, root)
|
||||
return result
|
||||
# Migration fallback: check legacy flat cache/ dir for AST entries
|
||||
if kind == "ast":
|
||||
legacy = Path(root).resolve() / _GRAPHIFY_OUT / "cache" / f"{h}.json"
|
||||
if legacy.exists():
|
||||
try:
|
||||
result = json.loads(legacy.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError):
|
||||
return None
|
||||
if isinstance(result, dict):
|
||||
_absolutize_source_files_in(result, root)
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast",
|
||||
cache_root: Path | None = None) -> None:
|
||||
def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "ast") -> None:
|
||||
"""Save extraction result for this file.
|
||||
|
||||
Stores as graphify-out/cache/{kind}/{hash}.json where hash = SHA256 of current file contents.
|
||||
result should be a dict with 'nodes' and 'edges' lists.
|
||||
|
||||
``root`` anchors the content-hash key and source_file relativization;
|
||||
``cache_root`` (when given) is where the cache directory is written, decoupled
|
||||
from ``root`` so the cache never lands inside the analyzed source tree (#1774).
|
||||
|
||||
No-ops if `path` is not a regular file. Subagent-produced semantic fragments
|
||||
occasionally carry a directory path in `source_file`; skipping them prevents
|
||||
IsADirectoryError from aborting the whole batch.
|
||||
@@ -428,13 +287,12 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
|
||||
# source_file field's original absolute form. Mutating the input here would
|
||||
# silently break those remaps on the first extraction pass.
|
||||
on_disk = result
|
||||
if isinstance(result, dict) and any(result.get(k) for k in ("nodes", "edges", "hyperedges", "raw_calls")):
|
||||
if isinstance(result, dict) and any(result.get(k) for k in ("nodes", "edges", "hyperedges")):
|
||||
import copy as _copy
|
||||
on_disk = _copy.deepcopy(result)
|
||||
_relativize_source_files_in(on_disk, root)
|
||||
h = file_hash(p, root, cache_root=cache_root)
|
||||
location = cache_root if cache_root is not None else root
|
||||
target_dir = cache_dir(location, kind)
|
||||
h = file_hash(p, root)
|
||||
target_dir = cache_dir(root, kind)
|
||||
entry = target_dir / f"{h}.json"
|
||||
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
|
||||
try:
|
||||
@@ -467,11 +325,11 @@ def cached_files(root: Path = Path(".")) -> set[str]:
|
||||
# Legacy flat entries
|
||||
if base.is_dir():
|
||||
hashes.update(p.stem for p in base.glob("*.json"))
|
||||
# Namespaced entries (ast/ recursively, covering per-version subdirs)
|
||||
for kind, pattern in (("ast", "**/*.json"), ("semantic", "*.json")):
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
hashes.update(p.stem for p in d.glob(pattern))
|
||||
hashes.update(p.stem for p in d.glob("*.json"))
|
||||
return hashes
|
||||
|
||||
|
||||
@@ -482,52 +340,14 @@ def clear_cache(root: Path = Path(".")) -> None:
|
||||
if base.is_dir():
|
||||
for f in base.glob("*.json"):
|
||||
f.unlink()
|
||||
# Namespaced entries (ast/ recursively, covering per-version subdirs)
|
||||
for kind, pattern in (("ast", "**/*.json"), ("semantic", "*.json")):
|
||||
# Namespaced entries
|
||||
for kind in ("ast", "semantic"):
|
||||
d = base / kind
|
||||
if d.is_dir():
|
||||
for f in d.glob(pattern):
|
||||
for f in d.glob("*.json"):
|
||||
f.unlink()
|
||||
|
||||
|
||||
def prune_semantic_cache(root: Path, live_hashes: set[str]) -> int:
|
||||
"""Remove orphaned semantic cache entries, returning the count pruned.
|
||||
|
||||
The semantic cache is content-hash-keyed (``{file_hash}.json`` under
|
||||
``cache/semantic/``) and deliberately UNVERSIONED — entries are produced by
|
||||
the LLM from file contents, so invalidating them on every release would
|
||||
re-bill extraction. Because it is unversioned it is also never swept by the
|
||||
AST version-cleanup, so every content change or file deletion leaves a
|
||||
permanent orphan entry that accumulates unbounded.
|
||||
|
||||
This sweeps ``cache/semantic/*.json`` and deletes any entry whose stem (the
|
||||
content hash) is not in ``live_hashes`` — the hashes of the current live
|
||||
document set. ``*.tmp`` atomic-write temporaries are skipped, and only this
|
||||
directory is touched (never ``cache/ast/**`` or anything else). The
|
||||
unversioned design is preserved: we prune by liveness, not by version.
|
||||
|
||||
Best-effort, mirroring :func:`_cleanup_stale_ast_entries`: each unlink is
|
||||
wrapped in ``try/except OSError`` and a failure is ignored. The worst-case
|
||||
failure mode is benign — a surviving orphan costs only one re-extraction of
|
||||
one doc on a future run, never incorrect output.
|
||||
"""
|
||||
_out = Path(_GRAPHIFY_OUT)
|
||||
base = _out if _out.is_absolute() else Path(root).resolve() / _out
|
||||
semantic_dir = base / "cache" / "semantic"
|
||||
if not semantic_dir.is_dir():
|
||||
return 0
|
||||
pruned = 0
|
||||
for entry in semantic_dir.glob("*.json"):
|
||||
if entry.stem in live_hashes:
|
||||
continue
|
||||
try:
|
||||
entry.unlink()
|
||||
pruned += 1
|
||||
except OSError:
|
||||
pass
|
||||
return pruned
|
||||
|
||||
|
||||
def check_semantic_cache(
|
||||
files: list[str],
|
||||
root: Path = Path("."),
|
||||
@@ -562,24 +382,12 @@ def save_semantic_cache(
|
||||
edges: list[dict],
|
||||
hyperedges: list[dict] | None = None,
|
||||
root: Path = Path("."),
|
||||
merge_existing: bool = False,
|
||||
allowed_source_files: Iterable[str | Path] | None = None,
|
||||
) -> int:
|
||||
"""Save semantic extraction results to cache, keyed by source_file.
|
||||
|
||||
Groups nodes and edges by source_file, then saves one cache entry per file
|
||||
under cache/semantic/ (separate from AST entries in cache/ast/) to prevent
|
||||
hash-key collisions (#582).
|
||||
|
||||
When ``merge_existing`` is True, any already-cached entry for a file is
|
||||
unioned with the new results before saving instead of being overwritten.
|
||||
This lets callers checkpoint incrementally (e.g. once per chunk) without
|
||||
dropping a prior slice of a large file that was split across chunks.
|
||||
|
||||
When ``allowed_source_files`` is provided, only those files may be used as
|
||||
cache-write keys. Semantic nodes can legitimately mention another corpus
|
||||
file, but a model must not be able to replace that file's complete cache
|
||||
entry unless the file was part of the current extraction batch (#1757).
|
||||
Returns the number of files cached.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
@@ -598,43 +406,12 @@ def save_semantic_cache(
|
||||
if src:
|
||||
by_file[src]["hyperedges"].append(h)
|
||||
|
||||
root_path = Path(root).resolve()
|
||||
|
||||
def resolved_source_path(value: str | Path) -> Path:
|
||||
path = Path(value)
|
||||
if not path.is_absolute():
|
||||
path = root_path / path
|
||||
try:
|
||||
return path.resolve()
|
||||
except (OSError, RuntimeError):
|
||||
# Keep the cache write best-effort for inaccessible paths or a
|
||||
# symlink loop emitted by an untrusted semantic result.
|
||||
return Path(os.path.abspath(path))
|
||||
|
||||
allowed_paths = None
|
||||
if allowed_source_files is not None:
|
||||
allowed_paths = {resolved_source_path(path) for path in allowed_source_files}
|
||||
|
||||
saved = 0
|
||||
for fpath, result in by_file.items():
|
||||
p = resolved_source_path(fpath)
|
||||
p = Path(fpath)
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
if p.is_file():
|
||||
if allowed_paths is not None and p not in allowed_paths:
|
||||
warnings.warn(
|
||||
"semantic cache skipped out-of-scope source_file "
|
||||
f"{fpath!r}; the file was not dispatched for extraction",
|
||||
RuntimeWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
continue
|
||||
if merge_existing:
|
||||
prev = load_cached(p, root, kind="semantic")
|
||||
if prev:
|
||||
result = {
|
||||
"nodes": (prev.get("nodes", []) or []) + result["nodes"],
|
||||
"edges": (prev.get("edges", []) or []) + result["edges"],
|
||||
"hyperedges": (prev.get("hyperedges", []) or []) + result["hyperedges"],
|
||||
}
|
||||
save_cached(p, result, root, kind="semantic")
|
||||
saved += 1
|
||||
return saved
|
||||
@@ -30,8 +30,6 @@ from collections import Counter, defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from html import escape
|
||||
|
||||
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# 1. CSS template (fixed, project-agnostic)
|
||||
@@ -406,7 +404,7 @@ def infer_project_name(graph_path: str, meta: dict) -> str:
|
||||
if meta.get("project_name"):
|
||||
return meta["project_name"]
|
||||
path = Path(graph_path).resolve()
|
||||
if path.parent.name == GRAPHIFY_OUT_NAME and len(path.parents) > 1:
|
||||
if path.parent.name == "graphify-out" and len(path.parents) > 1:
|
||||
return path.parents[1].name
|
||||
return path.parent.name or "Project"
|
||||
|
||||
@@ -421,9 +419,9 @@ def resolve_graphify_paths(args) -> dict:
|
||||
elif (base / "graph.json").exists():
|
||||
graphify_out = base
|
||||
else:
|
||||
graphify_out = base / GRAPHIFY_OUT
|
||||
graphify_out = base / "graphify-out"
|
||||
|
||||
project_root = graphify_out.parent if graphify_out.name == GRAPHIFY_OUT_NAME else base
|
||||
project_root = graphify_out.parent if graphify_out.name == "graphify-out" else base
|
||||
graph = Path(args.graph).expanduser() if args.graph else graphify_out / "graph.json"
|
||||
report = Path(args.report).expanduser() if args.report else graphify_out / "GRAPH_REPORT.md"
|
||||
labels = Path(args.labels).expanduser() if args.labels else graphify_out / ".graphify_labels.json"
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
"""Cargo manifest introspection for workspace-internal crate dependencies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
_CONFIDENCE_EXTRACTED = "EXTRACTED"
|
||||
|
||||
|
||||
def _load_toml(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
import tomllib # type: ignore[import-not-found]
|
||||
except ModuleNotFoundError:
|
||||
try:
|
||||
import tomli as tomllib # type: ignore[import-not-found,no-redef]
|
||||
except ModuleNotFoundError:
|
||||
raise ImportError(
|
||||
"--cargo on Python 3.10 needs tomli. Install with: pip install tomli"
|
||||
) from None
|
||||
|
||||
with path.open("rb") as manifest:
|
||||
return tomllib.load(manifest)
|
||||
|
||||
|
||||
def _member_manifest_paths(root: Path, root_data: dict[str, Any]) -> list[Path]:
|
||||
paths: list[Path] = []
|
||||
if isinstance(root_data.get("package"), dict):
|
||||
paths.append(root / "Cargo.toml")
|
||||
|
||||
workspace = root_data.get("workspace")
|
||||
members = workspace.get("members", []) if isinstance(workspace, dict) else []
|
||||
if not isinstance(members, list):
|
||||
return paths
|
||||
|
||||
for pattern in members:
|
||||
if not isinstance(pattern, str):
|
||||
continue
|
||||
for member in sorted(root.glob(pattern)):
|
||||
manifest = member / "Cargo.toml"
|
||||
if manifest.is_file() and manifest not in paths:
|
||||
paths.append(manifest)
|
||||
return paths
|
||||
|
||||
|
||||
def introspect_cargo(root: str | Path) -> dict[str, Any]:
|
||||
"""Return crate nodes and internal dependency edges from Cargo manifests."""
|
||||
root_path = Path(root).resolve()
|
||||
root_manifest = root_path / "Cargo.toml"
|
||||
root_data = _load_toml(root_manifest)
|
||||
|
||||
manifests = _member_manifest_paths(root_path, root_data)
|
||||
crates: dict[str, tuple[str, Path, dict[str, Any]]] = {}
|
||||
|
||||
for manifest in manifests:
|
||||
data = root_data if manifest == root_manifest else _load_toml(manifest)
|
||||
package = data.get("package")
|
||||
if not isinstance(package, dict):
|
||||
continue
|
||||
name = package.get("name")
|
||||
if isinstance(name, str):
|
||||
crates[name] = (f"crate:{name}", manifest, data)
|
||||
|
||||
nodes = [
|
||||
{
|
||||
"id": crate_id,
|
||||
"label": name,
|
||||
"source_file": manifest.relative_to(root_path).as_posix(),
|
||||
"source_location": "L1",
|
||||
}
|
||||
for name, (crate_id, manifest, _data) in sorted(crates.items())
|
||||
]
|
||||
|
||||
edges: list[dict[str, Any]] = []
|
||||
for source_name, (source_id, manifest, data) in sorted(crates.items()):
|
||||
dependencies = data.get("dependencies", {})
|
||||
if not isinstance(dependencies, dict):
|
||||
continue
|
||||
source_file = manifest.relative_to(root_path).as_posix()
|
||||
for dependency_name in sorted(dependencies):
|
||||
target = crates.get(dependency_name)
|
||||
if target is None:
|
||||
continue
|
||||
edges.append(
|
||||
{
|
||||
"source": source_id,
|
||||
"target": target[0],
|
||||
"relation": "crate_depends_on",
|
||||
"context": "cargo_dependency",
|
||||
"weight": 1.0,
|
||||
"confidence": _CONFIDENCE_EXTRACTED,
|
||||
"source_file": source_file,
|
||||
"source_location": "L1",
|
||||
}
|
||||
)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
-2773
File diff suppressed because it is too large.
Load diff
@@ -83,54 +83,6 @@ _COHESION_SPLIT_THRESHOLD = 0.05 # re-split communities with cohesion below this
|
||||
_COHESION_SPLIT_MIN_SIZE = 50 # only cohesion-split if community has at least this many nodes
|
||||
|
||||
|
||||
def label_communities_by_hub(
|
||||
G: nx.Graph, communities: dict[int, list[str]]
|
||||
) -> dict[int, str]:
|
||||
"""Deterministic, LLM-free community labels: name each community after its
|
||||
highest-degree member — the structural hub — so a report reads ``auth`` /
|
||||
``log_action`` instead of ``Community 70``. Degree is measured on the full graph
|
||||
``G``; ties break by node id for run-to-run stability. A community whose members
|
||||
are all absent from ``G`` falls back to ``Community {cid}``.
|
||||
|
||||
Used as the default (no-backend) labeler; an LLM naming pass, when configured,
|
||||
overrides these with richer names.
|
||||
"""
|
||||
labels: dict[int, str] = {}
|
||||
for cid, members in communities.items():
|
||||
present = [n for n in members if n in G]
|
||||
if not present:
|
||||
labels[cid] = f"Community {cid}"
|
||||
continue
|
||||
# highest degree wins; ties broken by node id (ascending) for determinism
|
||||
hub = min(present, key=lambda n: (-G.degree(n), str(n)))
|
||||
name = str(G.nodes[hub].get("label") or hub).strip()
|
||||
if name.endswith("()"):
|
||||
name = name[:-2]
|
||||
labels[cid] = name or f"Community {cid}"
|
||||
return labels
|
||||
|
||||
|
||||
def community_member_sigs(communities: dict[int, list[str]]) -> dict[int, str]:
|
||||
"""Per-community membership fingerprints: ``{cid: sha256(sorted member ids)}``.
|
||||
|
||||
Persisted next to ``.graphify_labels.json`` so a later ``cluster-only`` can tell
|
||||
which communities actually changed since labeling. A cid whose members no longer
|
||||
hash the same is a different community — reusing its old (LLM) label there is the
|
||||
"stale label after re-scoping" bug this guards against. Deterministic; independent
|
||||
of cid index, node order, and machine.
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
sigs: dict[int, str] = {}
|
||||
for cid, members in communities.items():
|
||||
h = hashlib.sha256()
|
||||
for nid in sorted(str(n) for n in members):
|
||||
h.update(nid.encode("utf-8", "replace"))
|
||||
h.update(b"\x00")
|
||||
sigs[cid] = h.hexdigest()[:16]
|
||||
return sigs
|
||||
|
||||
|
||||
def cluster(
|
||||
G: nx.Graph,
|
||||
resolution: float = 1.0,
|
||||
|
||||
+17
-156
@@ -6,20 +6,17 @@ Jaro-Winkler verification → same-community boost → union-find merge.
|
||||
from __future__ import annotations
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
from collections import defaultdict
|
||||
|
||||
from graphify._minhash import MinHash, MinHashLSH
|
||||
from rapidfuzz.distance import Jaro, JaroWinkler
|
||||
from datasketch import MinHash, MinHashLSH
|
||||
from rapidfuzz.distance import JaroWinkler
|
||||
|
||||
|
||||
# ── helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def _norm(label: str | None) -> str:
|
||||
def _norm(label: str) -> str:
|
||||
"""Lowercase + collapse non-alphanumeric runs to space (Unicode-aware)."""
|
||||
if not isinstance(label, str):
|
||||
label = "" if label is None else str(label)
|
||||
label = unicodedata.normalize("NFKC", label)
|
||||
return re.sub(r"[\W_]+", " ", label.casefold(), flags=re.UNICODE).strip()
|
||||
|
||||
@@ -90,52 +87,6 @@ def _short_label_blocked(a: str, b: str, jw_score: float) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
_DIGIT_RUN = re.compile(r"\d+")
|
||||
|
||||
|
||||
def _numeric_tokens_differ(a: str, b: str) -> bool:
|
||||
"""True when two labels carry different embedded numbers (#1284).
|
||||
|
||||
Long labels that differ only in their digit runs ("ADR 0011 §D5" vs
|
||||
"ADR 0013 D4", "3.1 Product Goals" vs "1.1 Product Goals", "block3" vs
|
||||
"block13", "40%+ retention" vs "<20% retention") are numbered/versioned
|
||||
siblings, not duplicates -- but the long shared boilerplate keeps
|
||||
Jaro-Winkler above _MERGE_THRESHOLD, and _is_variant_pair only covers
|
||||
short trailing suffixes. Digit runs are compared as multisets with
|
||||
leading zeros stripped, so zero-padding ("09" vs "9") does not count as
|
||||
a difference. (String comparison, not int(): a pathological label with a
|
||||
>4300-digit run would crash int() on Python's conversion limit.) Labels
|
||||
with identical numbers, or none at all, are unaffected.
|
||||
"""
|
||||
if a == b:
|
||||
return False
|
||||
return sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(a)) != \
|
||||
sorted(t.lstrip("0") or "0" for t in _DIGIT_RUN.findall(b))
|
||||
|
||||
|
||||
# file_type values whose identity is anchored to their source location, not
|
||||
# their label text. Like code (#1205), these must not be label-merged across
|
||||
# files: rationale = module/class docstrings, document = headings/positional
|
||||
# content. `concept` is intentionally excluded -- it is the type meant to unify
|
||||
# across files (protected from over-merge by the numeric/Jaro guards instead).
|
||||
_FILE_ANCHORED_NONCODE = frozenset({"rationale", "document"})
|
||||
|
||||
|
||||
def _crossfile_fileanchored_blocked(node: dict, neighbor: dict) -> bool:
|
||||
"""Block label-based merging of file-anchored non-code nodes across files (#1284).
|
||||
|
||||
rationale/document nodes are docstring- and heading-derived and as
|
||||
file-anchored as the code they describe (#1205's reasoning, one layer up):
|
||||
parallel modules carry near-identical boilerplate ("Django app config for
|
||||
apps.<name>. No business logic here...") that differs by one word and sails
|
||||
past the JW threshold. Same-file duplicates of these types may still merge.
|
||||
"""
|
||||
if (node.get("file_type") not in _FILE_ANCHORED_NONCODE
|
||||
and neighbor.get("file_type") not in _FILE_ANCHORED_NONCODE):
|
||||
return False
|
||||
return (node.get("source_file") or "") != (neighbor.get("source_file") or "")
|
||||
|
||||
|
||||
# ── union-find ────────────────────────────────────────────────────────────────
|
||||
|
||||
class _UF:
|
||||
@@ -173,20 +124,6 @@ _NUM_PERM = 128
|
||||
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
|
||||
|
||||
|
||||
def _is_code(node: dict) -> bool:
|
||||
"""True for AST-extracted code symbols.
|
||||
|
||||
Code-node identity is the node ID (which already encodes the fully
|
||||
qualified path: module/class/symbol). The label is only a display name
|
||||
(e.g. a bare ``.draw()`` method name, or a function name shared by two
|
||||
parallel backends), so label-based merging conflates distinct symbols
|
||||
(#1205). Genuine duplicates — the same symbol re-extracted — share an ID
|
||||
and are already collapsed by the exact-ID ``seen_ids`` pre-dedup above,
|
||||
so code never needs label-based merging.
|
||||
"""
|
||||
return node.get("file_type") == "code"
|
||||
|
||||
|
||||
# ── main entry point ──────────────────────────────────────────────────────────
|
||||
|
||||
def deduplicate_entities(
|
||||
@@ -220,29 +157,12 @@ def deduplicate_entities(
|
||||
if len(nodes) <= 1:
|
||||
return nodes, edges
|
||||
|
||||
# Pre-deduplicate: keep first occurrence of each id.
|
||||
# Warn when two nodes share an ID but originate from different source files —
|
||||
# this indicates a cross-chunk ID collision (#1504) where silent data loss occurs.
|
||||
# Pre-deduplicate: keep first occurrence of each id
|
||||
seen_ids: dict[str, dict] = {}
|
||||
for node in nodes:
|
||||
nid = node.get("id", "")
|
||||
if not nid:
|
||||
continue
|
||||
if nid not in seen_ids:
|
||||
if nid and nid not in seen_ids:
|
||||
seen_ids[nid] = node
|
||||
else:
|
||||
existing_sf = seen_ids[nid].get("source_file") or ""
|
||||
new_sf = node.get("source_file") or ""
|
||||
if existing_sf != new_sf:
|
||||
print(
|
||||
f"[graphify] WARNING: node '{nid}' from '{new_sf}' collides with "
|
||||
f"node from '{existing_sf}' — the second node will be dropped. "
|
||||
f"This is a cross-chunk ID collision caused by two files with the "
|
||||
f"same name in different directories. To avoid data loss, run "
|
||||
f"'graphify extract' per subfolder and merge with "
|
||||
f"'graphify merge-graphs'.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
unique_nodes = list(seen_ids.values())
|
||||
|
||||
if len(unique_nodes) <= 1:
|
||||
@@ -251,10 +171,6 @@ def deduplicate_entities(
|
||||
# ── pass 1: exact normalization ───────────────────────────────────────────
|
||||
norm_to_nodes: dict[str, list[dict]] = defaultdict(list)
|
||||
for node in unique_nodes:
|
||||
# Code symbols are keyed by ID, never by label — skip them entirely so
|
||||
# distinct same-named symbols are never merged by string similarity (#1205).
|
||||
if _is_code(node):
|
||||
continue
|
||||
key = _norm(node.get("label", node.get("id", "")))
|
||||
if key:
|
||||
norm_to_nodes[key].append(node)
|
||||
@@ -285,12 +201,6 @@ def deduplicate_entities(
|
||||
candidates: list[dict] = []
|
||||
seen_norms: set[str] = set()
|
||||
for node in unique_nodes:
|
||||
# Code symbols are excluded from fuzzy matching too: two functions with
|
||||
# similar long names in different files (parallel backends, sibling
|
||||
# classes) must not be fuzzy-merged, and a code↔concept fuzzy match must
|
||||
# not transitively union two distinct code symbols via a concept (#1205).
|
||||
if _is_code(node):
|
||||
continue
|
||||
key = _norm(node.get("label", node.get("id", "")))
|
||||
if key and key not in seen_norms:
|
||||
seen_norms.add(key)
|
||||
@@ -301,26 +211,19 @@ def deduplicate_entities(
|
||||
if len(candidates) >= 2:
|
||||
lsh = MinHashLSH(threshold=_LSH_THRESHOLD, num_perm=_NUM_PERM)
|
||||
minhashes: dict[str, MinHash] = {}
|
||||
# Pre-build O(1) lookup structures so the query loop below doesn't scan
|
||||
# the candidates list linearly for every LSH neighbor (was O(n²×B)).
|
||||
candidates_by_id: dict[str, dict] = {}
|
||||
norm_cache: dict[str, str] = {}
|
||||
|
||||
for node in candidates:
|
||||
node_id = node["id"]
|
||||
candidates_by_id[node_id] = node
|
||||
nl = _norm(node.get("label", node.get("id", "")))
|
||||
norm_cache[node_id] = nl
|
||||
m = _make_minhash(nl)
|
||||
minhashes[node_id] = m
|
||||
norm_label = _norm(node.get("label", node.get("id", "")))
|
||||
m = _make_minhash(norm_label)
|
||||
minhashes[node["id"]] = m
|
||||
try:
|
||||
lsh.insert(node_id, m)
|
||||
lsh.insert(node["id"], m)
|
||||
except ValueError:
|
||||
pass # duplicate key in LSH — already inserted
|
||||
|
||||
for node in candidates:
|
||||
node_id = node["id"]
|
||||
norm_label = norm_cache[node_id]
|
||||
norm_label = _norm(node.get("label", node.get("id", "")))
|
||||
neighbors = lsh.query(minhashes[node_id])
|
||||
|
||||
for neighbor_id in neighbors:
|
||||
@@ -329,44 +232,17 @@ def deduplicate_entities(
|
||||
if uf.find(node_id) == uf.find(neighbor_id):
|
||||
continue
|
||||
|
||||
neighbor = candidates_by_id.get(neighbor_id)
|
||||
neighbor = next((n for n in candidates if n["id"] == neighbor_id), None)
|
||||
if neighbor is None:
|
||||
continue
|
||||
|
||||
neighbor_norm = norm_cache.get(neighbor_id) or _norm(neighbor.get("label", neighbor.get("id", "")))
|
||||
# Cross-file long labels score on plain Jaro (no prefix bonus).
|
||||
# Jaro-Winkler's leading-prefix bonus lifts pairs that share a
|
||||
# prefix but diverge in a distinguishing token ("testing-library
|
||||
# jest-native" vs "react-native") past threshold, fabricating
|
||||
# destructive cross-file merges; on Jaro alone they fall short
|
||||
# while true cross-file duplicates still clear it (#1243). Same-file
|
||||
# near-duplicates keep Jaro-Winkler (low-risk, and a mid-string
|
||||
# stopword insertion needs the prefix bonus to merge); short labels
|
||||
# keep Jaro-Winkler too (gated by _short_label_blocked).
|
||||
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
|
||||
if _xfile and max(len(norm_label), len(neighbor_norm)) >= 12:
|
||||
score = Jaro.normalized_similarity(norm_label, neighbor_norm) * 100
|
||||
else:
|
||||
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
|
||||
neighbor_norm = _norm(neighbor.get("label", neighbor.get("id", "")))
|
||||
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
|
||||
|
||||
if _is_variant_pair(norm_label, neighbor_norm):
|
||||
continue
|
||||
if _short_label_blocked(norm_label, neighbor_norm, score):
|
||||
continue
|
||||
# Prefix-extension pairs (getActiveSession / getActiveSessions,
|
||||
# parseConfig / parseConfigFile) are almost never duplicates —
|
||||
# one is a strict suffix-extension of the other. Block the merge
|
||||
# regardless of JW score (#1201).
|
||||
_lo, _hi = sorted((norm_label, neighbor_norm), key=len)
|
||||
if _hi.startswith(_lo) and _hi != _lo:
|
||||
continue
|
||||
# Numbered/versioned siblings and cross-file file-anchored
|
||||
# boilerplate (rationale/document) are decisively distinct
|
||||
# regardless of score (#1284).
|
||||
if _numeric_tokens_differ(norm_label, neighbor_norm):
|
||||
continue
|
||||
if _crossfile_fileanchored_blocked(node, neighbor):
|
||||
continue
|
||||
|
||||
c1 = communities.get(node_id)
|
||||
c2 = communities.get(neighbor_id)
|
||||
@@ -384,11 +260,9 @@ def deduplicate_entities(
|
||||
sf_b = neighbor.get("source_file") or ""
|
||||
if sf_a != sf_b:
|
||||
continue
|
||||
# Pick the winner from the verified pair only. Selecting it
|
||||
# from the union of both normalized-label groups pulls
|
||||
# never-compared nodes (same label, different source_file)
|
||||
# into the merge, bypassing the #1046/#1178 guards.
|
||||
winner = _pick_winner([node, neighbor])
|
||||
all_group = norm_to_nodes.get(norm_label, [node]) + \
|
||||
norm_to_nodes.get(neighbor_norm, [neighbor])
|
||||
winner = _pick_winner(all_group)
|
||||
uf.union(winner["id"], node_id)
|
||||
uf.union(winner["id"], neighbor_id)
|
||||
fuzzy_merges += 1
|
||||
@@ -491,24 +365,11 @@ def _llm_tiebreak(
|
||||
if uf.find(node["id"]) == uf.find(neighbor["id"]):
|
||||
continue
|
||||
norm_j = _norm(neighbor.get("label", neighbor.get("id", "")))
|
||||
# Mirror pass 2: plain Jaro for cross-file long labels (#1243).
|
||||
_xfile = (node.get("source_file") or "") != (neighbor.get("source_file") or "")
|
||||
if _xfile and max(len(norm_i), len(norm_j)) >= 12:
|
||||
score = Jaro.normalized_similarity(norm_i, norm_j) * 100
|
||||
else:
|
||||
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
|
||||
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
|
||||
if _is_variant_pair(norm_i, norm_j):
|
||||
continue
|
||||
if _short_label_blocked(norm_i, norm_j, score):
|
||||
continue
|
||||
_lo, _hi = sorted((norm_i, norm_j), key=len)
|
||||
if _hi.startswith(_lo) and _hi != _lo:
|
||||
continue
|
||||
# Mirror pass 2: decisively-distinct pairs never reach the LLM (#1284).
|
||||
if _numeric_tokens_differ(norm_i, norm_j):
|
||||
continue
|
||||
if _crossfile_fileanchored_blocked(node, neighbor):
|
||||
continue
|
||||
c1 = communities.get(node["id"])
|
||||
c2 = communities.get(neighbor["id"])
|
||||
if (c1 is not None and c2 is not None and c1 == c2
|
||||
|
||||
+70
-318
@@ -5,7 +5,6 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
|
||||
@@ -14,7 +13,6 @@ from graphify.google_workspace import (
|
||||
convert_google_workspace_file,
|
||||
google_workspace_enabled,
|
||||
)
|
||||
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME, out_path
|
||||
|
||||
|
||||
class FileType(str, Enum):
|
||||
@@ -25,9 +23,9 @@ class FileType(str, Enum):
|
||||
VIDEO = "video"
|
||||
|
||||
|
||||
_MANIFEST_PATH = str(out_path("manifest.json"))
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.cu', '.cuh', '.metal', '.rb', '.rake', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.psm1', '.psd1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.xaml', '.razor', '.cshtml', '.cls', '.trigger'}
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.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', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml', '.cls', '.trigger'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
@@ -125,15 +123,6 @@ _GENERIC_KEYWORD_PATTERNS = [
|
||||
re.compile(r'(?<![a-zA-Z0-9])tokens?(?![a-zA-Z])', re.IGNORECASE),
|
||||
]
|
||||
|
||||
# Data/serialization extensions that commonly ARE secret stores when their name
|
||||
# hits a generic keyword (credentials.json, secrets.yaml, token.toml). These stay
|
||||
# subject to the Stage 3 keyword drop even though some route through the CODE path
|
||||
# for manifest parsing — only real programming-language source is exempt (#1666).
|
||||
_SECRET_PRONE_DATA_EXTS = frozenset({
|
||||
".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".config",
|
||||
".xml", ".properties", ".env", ".txt",
|
||||
})
|
||||
|
||||
# Word separators for the load-bearing check (underscore intentionally included;
|
||||
# multi-word keywords like private_key are handled by the end-of-stem check,
|
||||
# which runs before word counting).
|
||||
@@ -193,19 +182,8 @@ def _is_sensitive(path: Path) -> bool:
|
||||
name = path.name
|
||||
if any(p.search(name) for p in _SENSITIVE_PATTERNS):
|
||||
return True
|
||||
# Stage 3: generic keywords, only when load-bearing in the name. Do NOT let a
|
||||
# bare name keyword silently drop a genuine programming-language source file:
|
||||
# a .rb/.py named device_token or passwords_controller is a module, not a secret
|
||||
# store (#1666). Data/config formats (.json, .yaml, .toml, ...) are deliberately
|
||||
# NOT exempt even though .json routes through the CODE path for manifest parsing,
|
||||
# because credentials.json / oauth_token.json / secrets.yaml are exactly the
|
||||
# secret stores this stage must catch. The specific Stage 2 patterns (.env, .pem,
|
||||
# id_rsa, ...) still apply to everything regardless of extension.
|
||||
if _generic_keyword_hit(name):
|
||||
ext = path.suffix.lower()
|
||||
is_source_code = classify_file(path) == FileType.CODE and ext not in _SECRET_PRONE_DATA_EXTS
|
||||
return not is_source_code
|
||||
return False
|
||||
# Stage 3: generic keywords, only when load-bearing in the name
|
||||
return _generic_keyword_hit(name)
|
||||
|
||||
|
||||
def _looks_like_paper(path: Path) -> bool:
|
||||
@@ -404,13 +382,6 @@ def _shebang_file_type(path: Path) -> FileType | None:
|
||||
|
||||
|
||||
def classify_file(path: Path) -> FileType | None:
|
||||
# Package manifests (apm.yml, pyproject.toml, go.mod, pom.xml) are parsed
|
||||
# deterministically, so route them to the AST path (CODE) rather than the LLM
|
||||
# document path — otherwise apm.yml (a .yml "document") would be LLM-extracted
|
||||
# and a package would split into duplicate file-anchored nodes (#1377).
|
||||
from graphify.manifest_ingest import is_package_manifest_path
|
||||
if is_package_manifest_path(path):
|
||||
return FileType.CODE
|
||||
# Compound extensions must be checked before simple suffix lookup
|
||||
if path.name.lower().endswith(".blade.php"):
|
||||
return FileType.CODE
|
||||
@@ -639,30 +610,10 @@ def convert_office_file(path: Path, out_dir: Path) -> Path | None:
|
||||
return None
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Use a stable name derived from the original path to avoid collisions.
|
||||
# Normalize the resolved path to NFC before hashing: on macOS (HFS+/APFS)
|
||||
# os.walk/rglob return filenames in NFD, while Python string literals and
|
||||
# directly-constructed Path objects are NFC, so the same source file would
|
||||
# otherwise hash to different sidecar names across runs — causing --update
|
||||
# to treat every Office file as new and re-extract it (#1226).
|
||||
# Use a stable name derived from the original path to avoid collisions
|
||||
import hashlib
|
||||
import unicodedata
|
||||
normalized_path = unicodedata.normalize("NFC", str(path.resolve()))
|
||||
name_hash = hashlib.sha256(normalized_path.encode()).hexdigest()[:8]
|
||||
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
|
||||
out_path = out_dir / f"{path.stem}_{name_hash}.md"
|
||||
# Skip re-writing only when the sidecar is present AND at least as new as the
|
||||
# source. detect_incremental tracks the SIDECAR (not the Office source), so a
|
||||
# sidecar that is never rewritten after the source changes leaves the doc
|
||||
# reported "unchanged" forever and freezes the graph (#1649). Re-converting
|
||||
# when the source is newer bumps the sidecar's mtime/content, which the
|
||||
# incremental hash check then correctly picks up. An unchanged source keeps
|
||||
# its (newer-or-equal) sidecar untouched so it never churns (#1226).
|
||||
try:
|
||||
if out_path.exists() and os.stat(_os_path(out_path)).st_mtime >= os.stat(_os_path(path)).st_mtime:
|
||||
return out_path
|
||||
except OSError:
|
||||
if out_path.exists():
|
||||
return out_path
|
||||
out_path.write_text(
|
||||
f"<!-- converted from {path.name} -->\n\n{text}",
|
||||
encoding="utf-8",
|
||||
@@ -679,8 +630,7 @@ def count_words(path: Path) -> int:
|
||||
return len(docx_to_markdown(path).split())
|
||||
if ext == ".xlsx":
|
||||
return len(xlsx_to_markdown(path).split())
|
||||
with open(_os_path(path), encoding="utf-8", errors="ignore") as f:
|
||||
return len(f.read().split())
|
||||
return len(path.read_text(encoding="utf-8", errors="ignore").split())
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
@@ -692,12 +642,12 @@ _SKIP_DIRS = {
|
||||
"dist", "build", "target", "out",
|
||||
"site-packages", "lib64",
|
||||
".pytest_cache", ".mypy_cache", ".ruff_cache",
|
||||
".tox", ".nox", ".eggs", "*.egg-info", # nox is tox's successor, same .nox/ venv shape (#1804)
|
||||
"graphify-out", GRAPHIFY_OUT_NAME, # never treat own output as source input (#524); honour GRAPHIFY_OUT (#1423)
|
||||
".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__", # Jest/Vitest snapshot dir (unambiguous)
|
||||
"__snapshots__", "snapshots", # Jest/Vitest snapshot dirs
|
||||
"storybook-static", # Storybook production build output
|
||||
"dist-protected", # Protected dist variants (same noise as dist)
|
||||
# Framework cache/build dirs — generated, never architecturally meaningful (#873)
|
||||
@@ -714,31 +664,10 @@ _SKIP_FILES = {
|
||||
"composer.lock", "go.sum", "go.work.sum",
|
||||
}
|
||||
|
||||
# A bare "snapshots" dir is a Jest/Vitest artifact only when it actually holds
|
||||
# snapshot files or lives directly under a JS test root. Elsewhere it is often a
|
||||
# real code namespace (e.g. Rails app/services/snapshots/), so pruning it by name
|
||||
# silently dropped legitimate source from the graph (#1666). "__snapshots__" stays
|
||||
# unconditionally pruned above; only the ambiguous bare name is gated here.
|
||||
_JS_SNAPSHOT_TEST_ROOTS = frozenset({"__tests__", "__test__"})
|
||||
|
||||
|
||||
def _is_noise_dir(part: str, parent: "Path | None" = None) -> bool:
|
||||
"""Return True if this directory name looks like a venv, cache, or dep dir."""
|
||||
if part in _SKIP_DIRS:
|
||||
return True
|
||||
if part == "snapshots":
|
||||
# Prune only when it looks like an actual JS/Vitest snapshot dir.
|
||||
if parent is None:
|
||||
return False # cannot verify; keep a possibly-real code dir
|
||||
snap_dir = parent / part
|
||||
if parent.name in _JS_SNAPSHOT_TEST_ROOTS:
|
||||
return True
|
||||
try:
|
||||
if next(snap_dir.glob("*.snap"), None) is not None:
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
return False
|
||||
# Catch *_venv, *_repo/site-packages patterns
|
||||
if part.endswith("_venv") or part.endswith("_env"):
|
||||
return True
|
||||
@@ -790,48 +719,6 @@ def _find_vcs_root(start: Path) -> Path | None:
|
||||
current = parent
|
||||
|
||||
|
||||
def _git_info_exclude(vcs_root: Path) -> Path | None:
|
||||
"""Resolve ``$GIT_DIR/info/exclude`` for the repo rooted at ``vcs_root``.
|
||||
|
||||
``info/exclude`` is where git records local-only, uncommitted excludes — and
|
||||
where ``git worktree add`` writes nested worktree paths — so a repo can ignore
|
||||
a directory without any ``.gitignore`` entry. graphify only read
|
||||
``.gitignore``/``.graphifyignore``, so it walked into those worktree copies and
|
||||
the graph exploded (#1810). Handles the linked-worktree/submodule case where
|
||||
``.git`` is a file (``gitdir: <path>``) and the real excludes live in the
|
||||
shared common git dir. Returns None when there is no readable exclude file.
|
||||
"""
|
||||
dot_git = vcs_root / ".git"
|
||||
git_dir: Path | None = None
|
||||
if dot_git.is_dir():
|
||||
git_dir = dot_git
|
||||
elif dot_git.is_file():
|
||||
try:
|
||||
content = dot_git.read_text(encoding="utf-8", errors="ignore").strip()
|
||||
except OSError:
|
||||
content = ""
|
||||
if content.startswith("gitdir:"):
|
||||
gd = Path(content[len("gitdir:"):].strip())
|
||||
if not gd.is_absolute():
|
||||
gd = (vcs_root / gd).resolve()
|
||||
git_dir = gd
|
||||
# A linked worktree's gitdir holds a `commondir` file pointing at the
|
||||
# shared git dir, where info/exclude actually lives.
|
||||
commondir = gd / "commondir"
|
||||
if commondir.exists():
|
||||
try:
|
||||
cd_raw = commondir.read_text(encoding="utf-8", errors="ignore").strip()
|
||||
except OSError:
|
||||
cd_raw = ""
|
||||
if cd_raw:
|
||||
cd = Path(cd_raw)
|
||||
git_dir = cd if cd.is_absolute() else (gd / cd).resolve()
|
||||
if git_dir is None:
|
||||
return None
|
||||
exclude = git_dir / "info" / "exclude"
|
||||
return exclude if exclude.is_file() else None
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore files and return (anchor_dir, pattern) pairs.
|
||||
|
||||
@@ -856,46 +743,21 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
dirs.reverse() # ceiling first, scan root last
|
||||
|
||||
patterns: list[tuple[Path, str]] = []
|
||||
|
||||
# $GIT_DIR/info/exclude is repo-root-scoped and, per git, ranks below every
|
||||
# per-directory .gitignore/.graphifyignore — so load it first (lowest priority
|
||||
# under last-match-wins) anchored at the VCS root, letting a nearer `!`
|
||||
# re-include still override it (#1810).
|
||||
info_exclude = _git_info_exclude(ceiling)
|
||||
if info_exclude is not None:
|
||||
for raw in info_exclude.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = _parse_gitignore_line(raw)
|
||||
if line:
|
||||
patterns.append((ceiling, line))
|
||||
|
||||
for d in dirs:
|
||||
# Merge .gitignore and .graphifyignore for this dir (#1363). Previously
|
||||
# the presence of a .graphifyignore made graphify skip that dir's
|
||||
# .gitignore entirely, so a file excluded only by .gitignore (e.g. a
|
||||
# neutrally-named secret like prod-dump.sql) silently got indexed into
|
||||
# the graph — whose artifacts embed file contents and are often
|
||||
# committed. .gitignore is read first and .graphifyignore last, so
|
||||
# .graphifyignore patterns (including `!` negations) win on conflict via
|
||||
# last-match-wins; adding a .graphifyignore can only ever exclude MORE,
|
||||
# never re-include a .gitignore-excluded file (#945 kept: a project with
|
||||
# only a .gitignore still gets sensible defaults).
|
||||
for fname in (".gitignore", ".graphifyignore"):
|
||||
ignore_file = d / fname
|
||||
if ignore_file.exists():
|
||||
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = _parse_gitignore_line(raw)
|
||||
if line:
|
||||
patterns.append((d, line))
|
||||
# Prefer .graphifyignore; fall back to .gitignore so projects that already
|
||||
# maintain a .gitignore get sensible defaults without duplicating it (#945).
|
||||
ignore_file = d / ".graphifyignore"
|
||||
if not ignore_file.exists():
|
||||
ignore_file = d / ".gitignore"
|
||||
if ignore_file.exists():
|
||||
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = _parse_gitignore_line(raw)
|
||||
if line:
|
||||
patterns.append((d, line))
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_ignored(
|
||||
path: Path,
|
||||
root: Path,
|
||||
patterns: list[tuple[Path, str]],
|
||||
*,
|
||||
_cache: dict[Path, bool] | None = None,
|
||||
) -> bool:
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if the path should be ignored per .graphifyignore patterns.
|
||||
|
||||
Uses gitignore last-match-wins semantics: all patterns are evaluated in
|
||||
@@ -904,18 +766,12 @@ def _is_ignored(
|
||||
|
||||
Enforces gitignore's parent-exclusion rule: a ! pattern cannot re-include
|
||||
a file whose ancestor directory is already excluded.
|
||||
|
||||
_cache: optional dict shared across calls within the same scan. Ancestor
|
||||
directory results are memoised so files under the same subtree don't
|
||||
re-evaluate the same patterns repeatedly.
|
||||
"""
|
||||
if not patterns:
|
||||
return False
|
||||
|
||||
def _eval(target: Path) -> bool:
|
||||
"""Apply last-match-wins to a single target path."""
|
||||
if _cache is not None and target in _cache:
|
||||
return _cache[target]
|
||||
def _matches(rel: str, p: str, anchored: bool) -> bool:
|
||||
if anchored:
|
||||
return fnmatch.fnmatch(rel, p)
|
||||
@@ -962,8 +818,6 @@ def _is_ignored(
|
||||
|
||||
if matched:
|
||||
result = not negated # last match wins; ! flips to un-ignore
|
||||
if _cache is not None:
|
||||
_cache[target] = result
|
||||
return result
|
||||
|
||||
# Gitignore parent-exclusion rule: a ! re-include cannot rescue a file
|
||||
@@ -1095,11 +949,14 @@ def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Pa
|
||||
|
||||
|
||||
def _auto_follow_symlinks(root: Path) -> bool:
|
||||
"""Return whether ``root`` has any direct symlinked child.
|
||||
"""Auto-detect: ``True`` if ``root`` has any direct symlinked child.
|
||||
|
||||
Kept for callers that import the private helper, but detection no longer
|
||||
enables symlink following automatically. Following symlinks is now an
|
||||
explicit opt-in, and out-of-root symlink targets are never indexed.
|
||||
Allows "fake working dir" patterns (e.g. a folder full of symlinks pointing
|
||||
at scattered source dirs across the user's machine) to work transparently
|
||||
without the caller having to know to pass ``follow_symlinks=True``.
|
||||
|
||||
Override is always possible by passing an explicit ``follow_symlinks=True``
|
||||
or ``follow_symlinks=False`` to :func:`detect` / :func:`detect_incremental`.
|
||||
"""
|
||||
try:
|
||||
for p in root.iterdir():
|
||||
@@ -1110,19 +967,10 @@ def _auto_follow_symlinks(root: Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _resolves_under_root(path: Path, root: Path) -> bool:
|
||||
"""True when ``path`` resolves to a target inside ``root``."""
|
||||
try:
|
||||
path.resolve().relative_to(root.resolve())
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace: bool | None = None, extra_excludes: list[str] | None = None, cache_root: Path | None = None) -> dict:
|
||||
def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace: bool | None = None, extra_excludes: list[str] | None = None) -> dict:
|
||||
root = root.resolve()
|
||||
if follow_symlinks is None:
|
||||
follow_symlinks = False
|
||||
follow_symlinks = _auto_follow_symlinks(root)
|
||||
google_workspace = google_workspace_enabled() if google_workspace is None else google_workspace
|
||||
files: dict[FileType, list[str]] = {
|
||||
FileType.CODE: [],
|
||||
@@ -1133,18 +981,8 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
}
|
||||
total_words = 0
|
||||
|
||||
def _wc(path: Path) -> int:
|
||||
# Cache word counts against each file's stat signature so unchanged
|
||||
# PDFs/docx aren't re-parsed on every run just to size the corpus (#1656).
|
||||
# cache_root (when given, e.g. from `extract --out`) keeps this cache out
|
||||
# of the scanned corpus (#1747).
|
||||
from graphify import cache as _cache
|
||||
return _cache.cached_word_count(path, root, count_words, cache_root=cache_root)
|
||||
|
||||
skipped_sensitive: list[str] = []
|
||||
unclassified: list[str] = []
|
||||
ignore_patterns = _load_graphifyignore(root)
|
||||
ignore_cache: dict[Path, bool] = {} # shared across all _is_ignored calls in this scan
|
||||
# CLI --exclude patterns are anchored at the scan root and appended last
|
||||
# so they win over any .graphifyignore/.gitignore rules (#947).
|
||||
if extra_excludes:
|
||||
@@ -1155,7 +993,7 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
include_patterns = _load_graphifyinclude(root)
|
||||
|
||||
# Always include graphify-out/memory/ - query results filed back into the graph
|
||||
memory_dir = root / GRAPHIFY_OUT / "memory"
|
||||
memory_dir = root / "graphify-out" / "memory"
|
||||
scan_paths = [root]
|
||||
if memory_dir.exists():
|
||||
scan_paths.append(memory_dir)
|
||||
@@ -1163,29 +1001,9 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
seen: set[Path] = set()
|
||||
all_files: list[Path] = []
|
||||
|
||||
# os.walk swallows os.scandir errors by default (no onerror -> the failing
|
||||
# directory subtree is silently skipped). That turns a transient
|
||||
# PermissionError, or a directory created/deleted mid-walk (e.g. concurrent
|
||||
# writes racing the scan), into a partial file list and, downstream, a
|
||||
# silently partial graph.json. Record and surface every skipped directory
|
||||
# so an incomplete enumeration is visible rather than silent.
|
||||
walk_errors: list[str] = []
|
||||
|
||||
def _on_walk_error(err: OSError) -> None:
|
||||
import sys as _sys
|
||||
target = getattr(err, "filename", None) or "<unknown>"
|
||||
walk_errors.append(f"{target}: {err}")
|
||||
print(
|
||||
f"[graphify] WARNING: could not scan {target} ({err}); "
|
||||
f"its files are missing from this run's enumeration.",
|
||||
file=_sys.stderr,
|
||||
)
|
||||
|
||||
for scan_root in scan_paths:
|
||||
in_memory_tree = memory_dir.exists() and str(scan_root).startswith(str(memory_dir))
|
||||
for dirpath, dirnames, filenames in os.walk(
|
||||
scan_root, followlinks=follow_symlinks, onerror=_on_walk_error
|
||||
):
|
||||
for dirpath, dirnames, filenames in os.walk(scan_root, followlinks=follow_symlinks):
|
||||
dp = Path(dirpath)
|
||||
if follow_symlinks and os.path.islink(dirpath):
|
||||
real = os.path.realpath(dirpath)
|
||||
@@ -1197,29 +1015,14 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
# Prune noise dirs in-place so os.walk never descends into them.
|
||||
# Dot dirs are allowed — users often want .github/, .claude/, etc.
|
||||
# Framework caches (.next, .nuxt, …) are caught by _is_noise_dir.
|
||||
# Negations need no special-casing here: _is_ignored already applies
|
||||
# last-match-wins (so `!dir/` un-ignores a directory and it won't be
|
||||
# pruned) and the gitignore parent-exclusion rule (a `!` cannot rescue
|
||||
# a file beneath an excluded dir), so descending an ignored directory to
|
||||
# look for a re-included file is never necessary. The previous blanket
|
||||
# `has_negation` disabled directory pruning for EVERY ignored dir whenever
|
||||
# any `!` rule existed — e.g. a single `!docs/**` made the walk descend
|
||||
# bin/, obj/, wwwroot/, generated/, … : a pathological slowdown on large
|
||||
# repos for no correctness gain.
|
||||
# When negation patterns (!) exist, skip directory-level ignore
|
||||
# pruning so negated files inside can still be reached.
|
||||
has_negation = any(p.startswith("!") for _, p in ignore_patterns)
|
||||
dirnames[:] = [
|
||||
d for d in dirnames
|
||||
if not _is_noise_dir(d, dp)
|
||||
and not _is_ignored(dp / d, root, ignore_patterns, _cache=ignore_cache)
|
||||
and (has_negation or not _is_ignored(dp / d, root, ignore_patterns))
|
||||
]
|
||||
if follow_symlinks:
|
||||
safe_dirs: list[str] = []
|
||||
for d in dirnames:
|
||||
child = dp / d
|
||||
if child.is_symlink() and not _resolves_under_root(child, root):
|
||||
skipped_sensitive.append(str(child) + " [symlink target outside scan root]")
|
||||
continue
|
||||
safe_dirs.append(d)
|
||||
dirnames[:] = safe_dirs
|
||||
for fname in filenames:
|
||||
if fname in _SKIP_FILES:
|
||||
continue
|
||||
@@ -1230,7 +1033,7 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
|
||||
all_files.sort(key=lambda p: str(p))
|
||||
|
||||
converted_dir = root / GRAPHIFY_OUT / "converted"
|
||||
converted_dir = root / "graphify-out" / "converted"
|
||||
|
||||
for p in all_files:
|
||||
# For memory dir files, skip hidden/noise filtering
|
||||
@@ -1239,22 +1042,12 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
|
||||
if str(p).startswith(str(converted_dir)):
|
||||
continue
|
||||
if not in_memory and _is_ignored(p, root, ignore_patterns, _cache=ignore_cache):
|
||||
continue
|
||||
if not _resolves_under_root(p, root):
|
||||
skipped_sensitive.append(str(p) + " [symlink target outside scan root]")
|
||||
if not in_memory and _is_ignored(p, root, ignore_patterns):
|
||||
continue
|
||||
if _is_sensitive(p):
|
||||
skipped_sensitive.append(str(p))
|
||||
continue
|
||||
ftype = classify_file(p)
|
||||
if not ftype:
|
||||
# Considered but unclassifiable: an extension not in any supported set,
|
||||
# or an extensionless, non-shebang file (Dockerfile, Gemfile, Makefile,
|
||||
# Rakefile, LICENSE, ...). Previously these left no trace at all — not
|
||||
# counted, not listed — so a user couldn't tell they were seen (#1692).
|
||||
unclassified.append(str(p))
|
||||
continue
|
||||
if ftype:
|
||||
if p.suffix.lower() in GOOGLE_WORKSPACE_EXTENSIONS:
|
||||
if not google_workspace:
|
||||
@@ -1270,10 +1063,10 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
skipped_sensitive.append(str(p) + f" [Google Workspace export failed: {exc}]")
|
||||
continue
|
||||
if md_path:
|
||||
if _is_ignored(md_path, root, ignore_patterns, _cache=ignore_cache):
|
||||
if _is_ignored(md_path, root, ignore_patterns):
|
||||
continue
|
||||
files[ftype].append(str(md_path))
|
||||
total_words += _wc(md_path)
|
||||
total_words += count_words(md_path)
|
||||
else:
|
||||
skipped_sensitive.append(str(p) + " [Google Workspace export produced no readable text]")
|
||||
continue
|
||||
@@ -1281,17 +1074,17 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
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, _cache=ignore_cache):
|
||||
if _is_ignored(md_path, root, ignore_patterns):
|
||||
continue
|
||||
files[ftype].append(str(md_path))
|
||||
total_words += _wc(md_path)
|
||||
total_words += count_words(md_path)
|
||||
else:
|
||||
# Conversion failed (library not installed) - skip with note
|
||||
skipped_sensitive.append(str(p) + " [office conversion failed - pip install graphifyy[office]]")
|
||||
continue
|
||||
files[ftype].append(str(p))
|
||||
if ftype != FileType.VIDEO:
|
||||
total_words += _wc(p)
|
||||
total_words += count_words(p)
|
||||
|
||||
for ftype in files:
|
||||
files[ftype].sort()
|
||||
@@ -1320,47 +1113,17 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
|
||||
"needs_graph": needs_graph,
|
||||
"warning": warning,
|
||||
"skipped_sensitive": skipped_sensitive,
|
||||
"unclassified": sorted(unclassified),
|
||||
"walk_errors": walk_errors,
|
||||
"graphifyignore_patterns": len(ignore_patterns),
|
||||
"scan_root": str(root.resolve()),
|
||||
}
|
||||
|
||||
|
||||
def _os_path(path: Path) -> str:
|
||||
r"""Return an OS path string safe for open()/stat() on Windows long paths.
|
||||
|
||||
On win32, paths longer than the legacy MAX_PATH (260 chars) are rejected by
|
||||
the plain file APIs unless prefixed with the extended-length marker ``\\?\``
|
||||
(which also requires a fully-qualified path). Without it, _md5_file /
|
||||
save_manifest / count_words silently fail to hash deeply-nested files, so
|
||||
their manifest entry never stabilizes and detect_incremental re-flags them
|
||||
as changed on every run (#1655). cache._normalize_path strips this prefix
|
||||
for stable KEYS; this adds it for I/O. Non-win32 and already-prefixed paths
|
||||
pass through unchanged.
|
||||
"""
|
||||
import sys
|
||||
if sys.platform != "win32":
|
||||
return str(path)
|
||||
s = str(path)
|
||||
if s.startswith("\\\\?\\"):
|
||||
return s
|
||||
try:
|
||||
s = os.path.abspath(s) # \\?\ requires a fully-qualified path
|
||||
except Exception:
|
||||
return str(path)
|
||||
if s.startswith("\\\\"):
|
||||
# UNC share \\server\share -> \\?\UNC\server\share
|
||||
return "\\\\?\\UNC\\" + s[2:]
|
||||
return "\\\\?\\" + s
|
||||
|
||||
|
||||
def _md5_file(path: Path) -> str:
|
||||
"""MD5 of file contents streamed in 64KB chunks — for change detection only."""
|
||||
import hashlib as _hl
|
||||
h = _hl.md5(usedforsecurity=False)
|
||||
try:
|
||||
with open(_os_path(path), "rb") as f:
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(65536), b""):
|
||||
h.update(chunk)
|
||||
except OSError:
|
||||
@@ -1368,15 +1131,6 @@ def _md5_file(path: Path) -> str:
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _stat_and_hash(path_str: str) -> tuple[str, float, str] | None:
|
||||
"""Stat + MD5 a single file; returns None on OSError (e.g. deleted mid-run)."""
|
||||
try:
|
||||
p = Path(path_str)
|
||||
return path_str, os.stat(_os_path(p)).st_mtime, _md5_file(p)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _to_relative_for_storage(key: str, root: Path) -> str:
|
||||
"""Return ``key`` as a forward-slash relative path from ``root``.
|
||||
|
||||
@@ -1492,29 +1246,26 @@ def save_manifest(
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
all_files = [f for file_list in files.values() for f in file_list]
|
||||
with ThreadPoolExecutor() as pool:
|
||||
raw = pool.map(_stat_and_hash, all_files)
|
||||
hashed: dict[str, tuple[float, str]] = {
|
||||
r[0]: (r[1], r[2]) for r in raw if r is not None
|
||||
}
|
||||
|
||||
for f in all_files:
|
||||
if f not in hashed:
|
||||
continue # file deleted between detect() and manifest write
|
||||
mtime, h = hashed[f]
|
||||
prev = _normalise_entry(existing.get(f, {})) or {}
|
||||
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
|
||||
for file_list in files.values():
|
||||
for f in file_list:
|
||||
try:
|
||||
p = Path(f)
|
||||
mtime = p.stat().st_mtime
|
||||
h = _md5_file(p)
|
||||
except OSError:
|
||||
continue # file deleted between detect() and manifest write
|
||||
prev = _normalise_entry(existing.get(f, {})) or {}
|
||||
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
|
||||
if root is not None:
|
||||
# Persist in portable form: forward-slash relative paths. Keys outside
|
||||
# ``root`` (out-of-tree symlinked corpora, --include sources) keep
|
||||
@@ -1551,10 +1302,11 @@ def detect_incremental(
|
||||
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 in-root
|
||||
symlinked sub-trees are scanned consistently between full and incremental
|
||||
runs. ``None`` (default) does not follow symlinked directories; callers must
|
||||
opt in explicitly, and resolved targets outside the scan root are skipped.
|
||||
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
|
||||
directory outside the scan root) are scanned consistently between full and
|
||||
incremental runs. ``None`` (default) means auto-detect: ``True`` when ``root``
|
||||
contains at least one direct symlinked child, ``False`` otherwise.
|
||||
"""
|
||||
full = detect(root, follow_symlinks=follow_symlinks, google_workspace=google_workspace, extra_excludes=extra_excludes)
|
||||
# Pass ``root`` so a manifest written with relative keys (post-#777) is
|
||||
@@ -1577,7 +1329,7 @@ def detect_incremental(
|
||||
for f in file_list:
|
||||
stored = manifest.get(f)
|
||||
try:
|
||||
current_mtime = os.stat(_os_path(Path(f))).st_mtime
|
||||
current_mtime = Path(f).stat().st_mtime
|
||||
except Exception:
|
||||
current_mtime = 0
|
||||
|
||||
|
||||
@@ -274,13 +274,7 @@ def _read_json_file(path: str | Path) -> dict[str, Any]:
|
||||
|
||||
json_path = Path(path)
|
||||
check_graph_file_size_cap(json_path)
|
||||
try:
|
||||
data = json.loads(json_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise RuntimeError(
|
||||
f"Cannot parse {json_path}: {exc}. "
|
||||
"The file may be corrupted — re-run 'graphify extract'."
|
||||
) from exc
|
||||
data = json.loads(json_path.read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("diagnostic input must be a JSON object")
|
||||
return data
|
||||
|
||||
+627
-240
File diff suppressed because it is too large.
Load diff
@@ -1 +0,0 @@
|
||||
"""exporters package."""
|
||||
@@ -1,14 +0,0 @@
|
||||
"""Shared constants/helpers for the graphify exporters package.
|
||||
|
||||
Symbols used by more than one exporter live here so each exporter module can be
|
||||
split out of graphify/export.py without a circular import (export.py and the
|
||||
per-format modules both import from here, never from each other).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# Categorical palette for community coloring, shared by the HTML, SVG, and
|
||||
# Obsidian exporters. Moved verbatim from graphify/export.py.
|
||||
COMMUNITY_COLORS = [
|
||||
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
|
||||
"#EDC948", "#B07AA1", "#FF9DA7", "#9C755F", "#BAB0AC",
|
||||
]
|
||||
@@ -1,173 +0,0 @@
|
||||
"""graphdb — moved verbatim from graphify/export.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from graphify.analyze import _node_community_map
|
||||
import networkx as nx
|
||||
import re
|
||||
|
||||
|
||||
def push_to_neo4j(
|
||||
G: nx.Graph,
|
||||
uri: str,
|
||||
user: str,
|
||||
password: str,
|
||||
communities: dict[int, list[str]] | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Push graph directly to a running Neo4j instance via the Python driver.
|
||||
|
||||
Requires: pip install neo4j
|
||||
|
||||
Uses MERGE so re-running is safe - nodes and edges are upserted, not duplicated.
|
||||
Returns a dict with counts of nodes and edges pushed.
|
||||
"""
|
||||
try:
|
||||
from neo4j import GraphDatabase
|
||||
except ImportError as e:
|
||||
raise ImportError(
|
||||
"neo4j driver not installed. Run: pip install neo4j"
|
||||
) from e
|
||||
|
||||
node_community = _node_community_map(communities) if communities else {}
|
||||
|
||||
def _safe_rel(relation: str) -> str:
|
||||
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
|
||||
|
||||
def _safe_label(label: str) -> str:
|
||||
"""Sanitize a Neo4j node label to prevent Cypher injection."""
|
||||
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
|
||||
return sanitized if sanitized else "Entity"
|
||||
|
||||
driver = GraphDatabase.driver(uri, auth=(user, password))
|
||||
nodes_pushed = 0
|
||||
edges_pushed = 0
|
||||
|
||||
with driver.session() as session:
|
||||
for node_id, data in G.nodes(data=True):
|
||||
props = {
|
||||
k: v for k, v in data.items()
|
||||
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
|
||||
}
|
||||
props["id"] = node_id
|
||||
cid = node_community.get(node_id)
|
||||
if cid is not None:
|
||||
props["community"] = cid
|
||||
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
|
||||
session.run(
|
||||
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
|
||||
id=node_id,
|
||||
props=props,
|
||||
)
|
||||
nodes_pushed += 1
|
||||
|
||||
for u, v, data in G.edges(data=True):
|
||||
rel = _safe_rel(data.get("relation", "RELATED_TO"))
|
||||
props = {
|
||||
k: v for k, v in data.items()
|
||||
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
|
||||
}
|
||||
session.run(
|
||||
f"MATCH (a {{id: $src}}), (b {{id: $tgt}}) "
|
||||
f"MERGE (a)-[r:{rel}]->(b) SET r += $props",
|
||||
src=u,
|
||||
tgt=v,
|
||||
props=props,
|
||||
)
|
||||
edges_pushed += 1
|
||||
|
||||
driver.close()
|
||||
return {"nodes": nodes_pushed, "edges": edges_pushed}
|
||||
|
||||
def push_to_falkordb(
|
||||
G: nx.Graph,
|
||||
uri: str,
|
||||
user: str | None = None,
|
||||
password: str | None = None,
|
||||
communities: dict[int, list[str]] | None = None,
|
||||
graph_name: str = "graphify",
|
||||
) -> dict[str, int]:
|
||||
"""Push graph directly to a running FalkorDB instance via the Python SDK.
|
||||
|
||||
Requires: pip install falkordb
|
||||
|
||||
FalkorDB is OpenCypher-compatible, so the MERGE/SET upsert queries are
|
||||
identical to push_to_neo4j. Differences from the Neo4j path:
|
||||
- connects with FalkorDB(host, port, username, password) instead of a bolt
|
||||
driver; only the host/port are read from the URI, so the scheme is
|
||||
informational - "falkordb://localhost:6379", "redis://localhost:6379"
|
||||
and a bare "localhost:6379" are all equivalent (default port 6379).
|
||||
- a named graph is selected via db.select_graph(graph_name) (default
|
||||
"graphify"); FalkorDB keys each graph by name in the same instance.
|
||||
- queries run via graph.query(cypher, params) - there is no session object.
|
||||
- auth is optional (FalkorDB runs without credentials by default), so user
|
||||
and password may be None.
|
||||
- no APOC: the Neo4j path does not use APOC either, so nothing to port.
|
||||
|
||||
Uses MERGE so re-running is safe - nodes and edges are upserted, not
|
||||
duplicated. Returns a dict with counts of nodes and edges pushed.
|
||||
"""
|
||||
try:
|
||||
from falkordb import FalkorDB
|
||||
except ImportError as e:
|
||||
raise ImportError(
|
||||
"falkordb SDK not installed. Run: pip install falkordb"
|
||||
) from e
|
||||
|
||||
from urllib.parse import urlparse
|
||||
|
||||
node_community = _node_community_map(communities) if communities else {}
|
||||
|
||||
def _safe_rel(relation: str) -> str:
|
||||
return re.sub(r"[^A-Z0-9_]", "_", relation.upper().replace(" ", "_").replace("-", "_")) or "RELATED_TO"
|
||||
|
||||
def _safe_label(label: str) -> str:
|
||||
"""Sanitize a FalkorDB node label to prevent Cypher injection."""
|
||||
sanitized = re.sub(r"[^A-Za-z0-9_]", "", label)
|
||||
return sanitized if sanitized else "Entity"
|
||||
|
||||
parsed = urlparse(uri if "://" in uri else f"redis://{uri}")
|
||||
# FalkorDB auth is optional. Only send credentials when a password is
|
||||
# provided; otherwise connect anonymously and ignore any bolt-style default
|
||||
# username (e.g. Neo4j's "neo4j"), which FalkorDB rejects as an unknown ACL
|
||||
# user. Credentials embedded in the URI take precedence over the args.
|
||||
connect_user = parsed.username or (user if password else None)
|
||||
connect_password = parsed.password or (password or None)
|
||||
db = FalkorDB(
|
||||
host=parsed.hostname or "localhost",
|
||||
port=parsed.port or 6379,
|
||||
username=connect_user,
|
||||
password=connect_password,
|
||||
)
|
||||
graph = db.select_graph(graph_name)
|
||||
nodes_pushed = 0
|
||||
edges_pushed = 0
|
||||
|
||||
for node_id, data in G.nodes(data=True):
|
||||
props = {
|
||||
k: v for k, v in data.items()
|
||||
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
|
||||
}
|
||||
props["id"] = node_id
|
||||
cid = node_community.get(node_id)
|
||||
if cid is not None:
|
||||
props["community"] = cid
|
||||
ftype = _safe_label(data.get("file_type", "Entity").capitalize())
|
||||
graph.query(
|
||||
f"MERGE (n:{ftype} {{id: $id}}) SET n += $props",
|
||||
{"id": node_id, "props": props},
|
||||
)
|
||||
nodes_pushed += 1
|
||||
|
||||
for u, v, data in G.edges(data=True):
|
||||
rel = _safe_rel(data.get("relation", "RELATED_TO"))
|
||||
props = {
|
||||
k: v for k, v in data.items()
|
||||
if isinstance(v, (str, int, float, bool)) and not k.startswith("_")
|
||||
}
|
||||
graph.query(
|
||||
f"MATCH (a {{id: $src}}), (b {{id: $tgt}}) "
|
||||
f"MERGE (a)-[r:{rel}]->(b) SET r += $props",
|
||||
{"src": u, "tgt": v, "props": props},
|
||||
)
|
||||
edges_pushed += 1
|
||||
|
||||
return {"nodes": nodes_pushed, "edges": edges_pushed}
|
||||
@@ -1,547 +0,0 @@
|
||||
"""html — moved verbatim from graphify/export.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from graphify.exporters.base import COMMUNITY_COLORS # noqa: E402,F401
|
||||
from pathlib import Path
|
||||
import html as _html
|
||||
from graphify.analyze import _node_community_map
|
||||
import json
|
||||
import networkx as nx
|
||||
from graphify.security import sanitize_label
|
||||
|
||||
|
||||
MAX_NODES_FOR_VIZ = 5_000
|
||||
|
||||
def _viz_node_limit() -> int:
|
||||
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
|
||||
|
||||
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
|
||||
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
|
||||
"""
|
||||
import os
|
||||
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
|
||||
if raw is None or not raw.strip():
|
||||
return MAX_NODES_FOR_VIZ
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
return MAX_NODES_FOR_VIZ
|
||||
|
||||
def _html_styles() -> str:
|
||||
return """<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
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>"""
|
||||
|
||||
def _hyperedge_script(hyperedges_json: str) -> str:
|
||||
return f"""<script>
|
||||
// Render hyperedges as shaded regions
|
||||
const hyperedges = {hyperedges_json};
|
||||
// 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>"""
|
||||
|
||||
def _html_script(nodes_json: str, edges_json: str, legend_json: str) -> str:
|
||||
return f"""<script>
|
||||
const RAW_NODES = {nodes_json};
|
||||
const RAW_EDGES = {edges_json};
|
||||
const LEGEND = {legend_json};
|
||||
|
||||
// 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>"""
|
||||
|
||||
def to_html(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
output_path: str,
|
||||
community_labels: dict[int, str] | None = None,
|
||||
member_counts: dict[int, int] | None = None,
|
||||
node_limit: int | None = None,
|
||||
learning_overlay: dict | None = None,
|
||||
) -> None:
|
||||
"""Generate an interactive vis.js HTML visualization of the graph.
|
||||
|
||||
Features: node size by degree, click-to-inspect panel, search box,
|
||||
community filter, physics clustering by community, confidence-styled edges.
|
||||
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
|
||||
|
||||
If member_counts is provided (aggregated community view), node sizes are
|
||||
based on community member counts rather than graph degree.
|
||||
|
||||
If node_limit is set and the graph exceeds it, automatically builds an
|
||||
aggregated community-level meta-graph instead of raising ValueError.
|
||||
"""
|
||||
limit = node_limit if node_limit is not None else _viz_node_limit()
|
||||
if G.number_of_nodes() > limit:
|
||||
if node_limit is not None:
|
||||
# Build aggregated community meta-graph
|
||||
from collections import Counter as _Counter
|
||||
import networkx as _nx
|
||||
print(f"Graph has {G.number_of_nodes()} nodes (above {limit} limit). Building aggregated community view...")
|
||||
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
|
||||
meta = _nx.Graph()
|
||||
for cid, members in communities.items():
|
||||
meta.add_node(str(cid), label=(community_labels or {}).get(cid, f"Community {cid}"))
|
||||
edge_counts = _Counter()
|
||||
for u, v in G.edges():
|
||||
cu, cv = node_to_community.get(u), node_to_community.get(v)
|
||||
if cu is not None and cv is not None and cu != cv:
|
||||
edge_counts[(min(cu, cv), max(cu, cv))] += 1
|
||||
for (cu, cv), w in edge_counts.items():
|
||||
meta.add_edge(str(cu), str(cv), weight=w,
|
||||
relation=f"{w} cross-community edges", confidence="AGGREGATED")
|
||||
if meta.number_of_nodes() <= 1:
|
||||
print("Single community - aggregated view not useful. Skipping graph.html.")
|
||||
return
|
||||
meta_communities = {cid: [str(cid)] for cid in communities}
|
||||
mc = {cid: len(members) for cid, members in communities.items()}
|
||||
# Remap hyperedges from semantic node IDs to community IDs
|
||||
raw_hyperedges = G.graph.get("hyperedges", [])
|
||||
if raw_hyperedges:
|
||||
remapped = []
|
||||
for he in raw_hyperedges:
|
||||
he_members = he.get("nodes", [])
|
||||
comm_ids, seen = [], set()
|
||||
for nid in he_members:
|
||||
c = node_to_community.get(nid)
|
||||
if c is None:
|
||||
continue
|
||||
s = str(c)
|
||||
if s in seen:
|
||||
continue
|
||||
seen.add(s)
|
||||
comm_ids.append(s)
|
||||
if len(comm_ids) < 2:
|
||||
continue
|
||||
remapped.append({
|
||||
"id": he.get("id", ""),
|
||||
"label": he.get("label") or he.get("relation", "").replace("_", " "),
|
||||
"nodes": comm_ids,
|
||||
})
|
||||
meta.graph["hyperedges"] = remapped
|
||||
to_html(meta, meta_communities, output_path,
|
||||
community_labels=community_labels, member_counts=mc)
|
||||
print(f"graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)")
|
||||
print("Tip: run with --obsidian for full node-level detail.")
|
||||
return
|
||||
raise ValueError(
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
|
||||
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
|
||||
f"or reduce input size."
|
||||
)
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
degree = dict(G.degree())
|
||||
max_deg = max(degree.values(), default=1) or 1
|
||||
max_mc = (max(member_counts.values(), default=1) or 1) if member_counts else 1
|
||||
|
||||
# Work-memory overlay (derived sidecar). When not passed explicitly, load it
|
||||
# best-effort from the sibling .graphify_learning.json next to the output
|
||||
# graph.html (which lives beside graph.json). Empty/missing => no learning
|
||||
# fields, so the un-annotated render is byte-identical to pre-feature.
|
||||
if learning_overlay is None:
|
||||
learning_overlay = {}
|
||||
try:
|
||||
from graphify.reflect import load_learning_overlay as _llo
|
||||
learning_overlay = _llo(Path(output_path))
|
||||
except Exception:
|
||||
learning_overlay = {}
|
||||
# Status -> ring color. preferred=green, contested=amber. Tentative gets no
|
||||
# ring (it's not yet trustworthy enough to highlight in the map).
|
||||
_RING = {"preferred": "#22c55e", "contested": "#f59e0b"}
|
||||
|
||||
# Build nodes list for vis.js
|
||||
vis_nodes = []
|
||||
for node_id, data in G.nodes(data=True):
|
||||
cid = node_community.get(node_id, 0)
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
label = sanitize_label(data.get("label", node_id))
|
||||
deg = degree.get(node_id, 1)
|
||||
if member_counts:
|
||||
mc = member_counts.get(cid, 1)
|
||||
size = 10 + 30 * (mc / max_mc)
|
||||
font_size = 12
|
||||
else:
|
||||
size = 10 + 30 * (deg / max_deg)
|
||||
# Only show label for high-degree nodes by default; others show on hover
|
||||
font_size = 12 if deg >= max_deg * 0.15 else 0
|
||||
node = {
|
||||
"id": node_id,
|
||||
"label": label,
|
||||
"color": {"background": color, "border": color, "highlight": {"background": "#ffffff", "border": color}},
|
||||
"size": round(size, 1),
|
||||
"font": {"size": font_size, "color": "#ffffff"},
|
||||
"title": _html.escape(label),
|
||||
"community": cid,
|
||||
"community_name": sanitize_label((community_labels or {}).get(cid, f"Community {cid}")),
|
||||
"source_file": sanitize_label(str(data.get("source_file") or "")),
|
||||
"file_type": data.get("file_type", ""),
|
||||
"degree": deg,
|
||||
}
|
||||
# Conditional learning fields — only present for annotated nodes, so
|
||||
# un-annotated output keeps the exact pre-feature node dict shape.
|
||||
entry = learning_overlay.get(str(node_id)) if learning_overlay else None
|
||||
if entry:
|
||||
status = sanitize_label(str(entry.get("status", "")))
|
||||
stale = bool(entry.get("stale"))
|
||||
node["learning_status"] = status
|
||||
node["learning_stale"] = stale
|
||||
ring = _RING.get(status)
|
||||
if ring:
|
||||
# Status-colored ring via the border; stale => desaturated +
|
||||
# dashed (vis.js supports per-node `shapeProperties.borderDashes`).
|
||||
if stale:
|
||||
ring = "#9ca3af"
|
||||
node["shapeProperties"] = {"borderDashes": [4, 4]}
|
||||
node["borderWidth"] = 3
|
||||
node["color"] = {
|
||||
"background": color, "border": ring,
|
||||
"highlight": {"background": "#ffffff", "border": ring},
|
||||
}
|
||||
# Lesson line appended to the hover title.
|
||||
if status == "contested":
|
||||
lesson = f"Lesson: contested (useful {entry.get('uses', 0)} / dead-end {entry.get('neg', 0)})"
|
||||
elif status == "preferred":
|
||||
lesson = f"Lesson: preferred source ({entry.get('uses', 0)} useful, score={entry.get('score', 0)})"
|
||||
else:
|
||||
lesson = f"Lesson: {status} ({entry.get('uses', 0)} useful)"
|
||||
if stale:
|
||||
lesson += " [code changed — re-verify]"
|
||||
node["title"] = _html.escape(label) + "\n" + _html.escape(sanitize_label(lesson))
|
||||
vis_nodes.append(node)
|
||||
|
||||
# Build edges list. Restore original edge direction from _src/_tgt
|
||||
# (stashed by build.py for exactly this reason): undirected NetworkX
|
||||
# canonicalizes endpoint order, which would otherwise flip the arrow
|
||||
# for `calls` and `rationale_for` in the rendered graph (#563).
|
||||
vis_edges = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
relation = data.get("relation", "")
|
||||
true_src = data.get("_src", u)
|
||||
true_tgt = data.get("_tgt", v)
|
||||
vis_edges.append({
|
||||
"from": true_src,
|
||||
"to": true_tgt,
|
||||
"label": relation,
|
||||
"title": _html.escape(f"{relation} [{confidence}]"),
|
||||
"dashes": confidence != "EXTRACTED",
|
||||
"width": 2 if confidence == "EXTRACTED" else 1,
|
||||
"color": {"opacity": 0.7 if confidence == "EXTRACTED" else 0.35},
|
||||
"confidence": confidence,
|
||||
})
|
||||
|
||||
# Build community legend data
|
||||
legend_data = []
|
||||
for cid in sorted((community_labels or {}).keys()):
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
lbl = _html.escape(sanitize_label((community_labels or {}).get(cid, f"Community {cid}")))
|
||||
n = member_counts.get(cid, len(communities.get(cid, []))) if member_counts else len(communities.get(cid, []))
|
||||
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
|
||||
|
||||
# Escape </script> sequences so embedded JSON cannot break out of the script tag
|
||||
def _js_safe(obj) -> str:
|
||||
return json.dumps(obj).replace("</", "<\\/")
|
||||
|
||||
nodes_json = _js_safe(vis_nodes)
|
||||
edges_json = _js_safe(vis_edges)
|
||||
legend_json = _js_safe(legend_data)
|
||||
hyperedges_json = _js_safe(getattr(G, "graph", {}).get("hyperedges", []))
|
||||
title = _html.escape(sanitize_label(str(output_path)))
|
||||
stats = f"{G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities"
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>graphify - {title}</title>
|
||||
<script src="https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js"
|
||||
integrity="sha384-Ux6phic9PEHJ38YtrijhkzyJ8yQlH8i/+buBR8s3mAZOJrP1gwyvAcIYl3GWtpX1"
|
||||
crossorigin="anonymous"></script>
|
||||
{_html_styles()}
|
||||
</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">{stats}</div>
|
||||
</div>
|
||||
{_html_script(nodes_json, edges_json, legend_json)}
|
||||
{_hyperedge_script(hyperedges_json)}
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
Path(output_path).write_text(html, encoding="utf-8") # nosec
|
||||
+9255
-2646
File diff suppressed because it is too large.
Load diff
@@ -1,107 +0,0 @@
|
||||
# Migrating a language extractor out of extract.py
|
||||
|
||||
`graphify/extract.py` is being split into this package, one language per PR
|
||||
(upstream issue #1212). This is the playbook for porting ONE language. It is
|
||||
written so an AI agent can execute it in a single session.
|
||||
|
||||
## Status
|
||||
|
||||
| module | migrated |
|
||||
|---|---|
|
||||
| blade | yes |
|
||||
| zig | yes |
|
||||
| elixir | yes |
|
||||
| razor | yes |
|
||||
| dart | yes |
|
||||
| rust | yes |
|
||||
| go | yes |
|
||||
| powershell (ps1 + psd1 manifest) | yes |
|
||||
| fortran | yes |
|
||||
| sql | yes |
|
||||
| dm (dm/dmm/dmi/dmf) | yes |
|
||||
| bash | yes |
|
||||
| apex | yes |
|
||||
| terraform | yes |
|
||||
| sln | yes |
|
||||
| pascal_forms (dfm + lfm) | yes |
|
||||
| json_config | yes |
|
||||
| (config-driven core: python, js, java, c, cpp, csharp, kotlin, scala, php, lua, swift, groovy, vue, svelte, astro, xaml, groovy) | no — shared _extract_generic core, move as one batch |
|
||||
| (other bespoke: julia, verilog, markdown, objc, csproj, slnx, lazarus_package, pascal) | no |
|
||||
|
||||
Note: config-driven extractors (python, js, java, c, cpp, ruby, csharp,
|
||||
kotlin, scala, php, lua, swift, groovy) depend on the shared
|
||||
`_extract_generic` core (~1,300 lines). Do NOT port them one-by-one; the core
|
||||
must move first as its own coordinated batch. Pick a bespoke extractor.
|
||||
|
||||
## Invariants (non-negotiable)
|
||||
|
||||
1. **Verbatim moves only.** No renames, no docstring edits, no reformatting,
|
||||
no added annotations, no "improvements". Verify: save the block before
|
||||
cutting and confirm the pasted block is byte-identical.
|
||||
2. **One language per PR.** Small diffs keep review trivial and avoid
|
||||
conflicts with other in-flight ports.
|
||||
3. **Facade re-export is mandatory.** `extract.py` must keep exporting every
|
||||
moved name (`from graphify.extractors.<mod> import extract_<lang> # noqa: F401`
|
||||
in the marked migration block, kept alphabetical). Existing importers
|
||||
(`__main__.py`, `watch.py`, `pg_introspect.py`, tests) must not change.
|
||||
4. **Never import from `graphify.extract` inside this package.** Import
|
||||
direction is strictly extract.py -> extractors/. If you need a helper that
|
||||
lives in extract.py, classify it (below) and move it.
|
||||
5. **Zero test edits** outside `tests/test_extractors_registry.py`. The
|
||||
untouched language tests passing IS the proof of behavior preservation.
|
||||
|
||||
## Helper classification
|
||||
|
||||
For every `_name` your function references that is defined OUTSIDE it:
|
||||
|
||||
- run `grep -c '_name' graphify/extract.py` AFTER your candidate move;
|
||||
- remaining uses > 0 -> **shared**: move it to `base.py` and add it to the
|
||||
facade re-import in extract.py;
|
||||
- remaining uses = 0 -> **private**: move it into your language module.
|
||||
|
||||
Closures, constants, and `import` statements defined INSIDE your function
|
||||
move with it for free — leave them exactly where they are. Only add a
|
||||
module-header import for names the pasted code references at module scope
|
||||
that are not satisfied internally, and verify each header import is used.
|
||||
|
||||
## Pre-flight
|
||||
|
||||
1. Check upstream for conflicts: open PRs/issues mentioning your language,
|
||||
and churn: `git log --oneline --since="3 months ago" upstream/<default> | grep -i <lang>`.
|
||||
High churn -> pick another language.
|
||||
2. Confirm your extractor is bespoke (its `extract_<lang>` is a full function,
|
||||
not a 5-line `_extract_generic(path, LanguageConfig(...))` wrapper).
|
||||
3. Check whether tests/ exercises your language's behavior (grep for
|
||||
`test_<lang>`). If it has no behavioral tests, the byte-identity check in
|
||||
step 3 below is the ENTIRE proof of preservation — include the
|
||||
`git diff --color-moved` evidence in your PR description.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Append a failing test to `tests/test_extractors_registry.py`:
|
||||
module import + facade identity + registry identity (copy an existing
|
||||
`test_<lang>_migrated` as the template).
|
||||
2. `grep -n 'def extract_<lang>' graphify/extract.py`; the span ends at the
|
||||
line before the next top-level statement (`^def ` or `^_CONST`). Beware
|
||||
neighbors: top-level constants AFTER your function may belong to the NEXT
|
||||
function (e.g. `_CONFIG_JSON_*` sit after where extract_razor used to be
|
||||
but were never razor's).
|
||||
3. Save the span to a temp file. Create `graphify/extractors/<lang>.py` with
|
||||
module docstring (`"""<Lang> extractor. Moved verbatim from graphify/extract.py."""`),
|
||||
`from __future__ import annotations`, minimal stdlib imports, base imports,
|
||||
then paste the function. Verify byte-identity against the temp file.
|
||||
4. Delete the span from extract.py, leaving exactly two blank lines between
|
||||
the now-adjacent top-level definitions; add the facade re-import; add the
|
||||
registry entry in `__init__.py` (alphabetical); update the Status table
|
||||
above.
|
||||
5. `uv run pytest -q` -> 0 failures, no test file changed except the registry
|
||||
test. If ImportError/NameError: a helper was misclassified — go to
|
||||
Helper classification.
|
||||
6. One commit: `refactor(extract): move extract_<lang> to extractors/<lang>.py (verbatim)`.
|
||||
|
||||
## What NOT to do
|
||||
|
||||
- Do not rewire dispatch, add classes, or add lazy imports — mechanism layers
|
||||
come later, by separate agreement (see #1212 discussion).
|
||||
- Do not port two languages in one PR "while you're at it".
|
||||
- Do not touch `__main__.py`.
|
||||
@@ -1,64 +0,0 @@
|
||||
"""Per-language extractors, incrementally migrated out of graphify/extract.py.
|
||||
|
||||
Dispatch still flows through graphify.extract (the facade re-exports every
|
||||
moved name), so importing from graphify.extract keeps working unchanged.
|
||||
LANGUAGE_EXTRACTORS is the registry seed; wiring dispatch through it is a
|
||||
later, separate step. See MIGRATION.md for how to port another language.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from graphify.extractors.apex import extract_apex
|
||||
from graphify.extractors.bash import extract_bash
|
||||
from graphify.extractors.blade import extract_blade
|
||||
from graphify.extractors.dart import extract_dart
|
||||
from graphify.extractors.dm import extract_dm, extract_dmf, extract_dmi, extract_dmm
|
||||
from graphify.extractors.elixir import extract_elixir
|
||||
from graphify.extractors.fortran import extract_fortran
|
||||
from graphify.extractors.go import extract_go
|
||||
from graphify.extractors.json_config import extract_json
|
||||
from graphify.extractors.julia import extract_julia
|
||||
from graphify.extractors.markdown import extract_markdown
|
||||
from graphify.extractors.objc import extract_objc
|
||||
from graphify.extractors.pascal import extract_pascal
|
||||
from graphify.extractors.pascal_forms import extract_delphi_form, extract_lazarus_form
|
||||
from graphify.extractors.powershell import extract_powershell, extract_powershell_manifest
|
||||
from graphify.extractors.razor import extract_razor
|
||||
from graphify.extractors.rust import extract_rust
|
||||
from graphify.extractors.sln import extract_sln
|
||||
from graphify.extractors.sql import extract_sql
|
||||
from graphify.extractors.terraform import extract_terraform
|
||||
from graphify.extractors.verilog import extract_verilog
|
||||
from graphify.extractors.zig import extract_zig
|
||||
|
||||
LANGUAGE_EXTRACTORS: dict[str, Callable[[Path], dict]] = {
|
||||
"apex": extract_apex,
|
||||
"bash": extract_bash,
|
||||
"blade": extract_blade,
|
||||
"dart": extract_dart,
|
||||
"delphi_form": extract_delphi_form,
|
||||
"dm": extract_dm,
|
||||
"dmf": extract_dmf,
|
||||
"dmi": extract_dmi,
|
||||
"dmm": extract_dmm,
|
||||
"elixir": extract_elixir,
|
||||
"fortran": extract_fortran,
|
||||
"go": extract_go,
|
||||
"json": extract_json,
|
||||
"julia": extract_julia,
|
||||
"lazarus_form": extract_lazarus_form,
|
||||
"markdown": extract_markdown,
|
||||
"objc": extract_objc,
|
||||
"pascal": extract_pascal,
|
||||
"powershell": extract_powershell,
|
||||
"powershell_manifest": extract_powershell_manifest,
|
||||
"razor": extract_razor,
|
||||
"rust": extract_rust,
|
||||
"sln": extract_sln,
|
||||
"sql": extract_sql,
|
||||
"terraform": extract_terraform,
|
||||
"verilog": extract_verilog,
|
||||
"zig": extract_zig,
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
"""Apex extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_apex(path: Path) -> dict:
|
||||
"""Extract classes, interfaces, enums, methods, and Salesforce constructs from
|
||||
Apex .cls and .trigger files using regex (no tree-sitter grammar on PyPI)."""
|
||||
import re as _re
|
||||
try:
|
||||
source = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return {"nodes": [], "edges": []}
|
||||
|
||||
str_path = str(path)
|
||||
stem = _file_stem(path)
|
||||
file_nid = _make_id(str_path)
|
||||
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED") -> None:
|
||||
edges.append({
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
"relation": relation,
|
||||
"confidence": confidence,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
lines = source.splitlines()
|
||||
|
||||
_ACCESS = r"(?:public|private|protected|global|webService)?"
|
||||
_SHARING = r"(?:\s+(?:with|without|inherited)\s+sharing)?"
|
||||
_MOD = r"(?:\s+(?:abstract|virtual|override|static|final|transient|testMethod))?"
|
||||
_ANNOTATION = r"(?:\s*@\w+(?:\s*\([^)]*\))?\s*)*"
|
||||
|
||||
cls_re = _re.compile(
|
||||
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*class\s+(\w+)"
|
||||
rf"(?:\s+extends\s+(\w+))?(?:\s+implements\s+([\w,\s]+))?\s*\{{?",
|
||||
_re.IGNORECASE,
|
||||
)
|
||||
iface_re = _re.compile(
|
||||
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*interface\s+(\w+)"
|
||||
rf"(?:\s+extends\s+([\w,\s]+))?\s*\{{?",
|
||||
_re.IGNORECASE,
|
||||
)
|
||||
enum_re = _re.compile(
|
||||
rf"^{_ANNOTATION}\s*{_ACCESS}{_SHARING}{_MOD}\s*enum\s+(\w+)\s*\{{?",
|
||||
_re.IGNORECASE,
|
||||
)
|
||||
trigger_re = _re.compile(
|
||||
r"^\s*trigger\s+(\w+)\s+on\s+(\w+)\s*\(",
|
||||
_re.IGNORECASE,
|
||||
)
|
||||
method_re = _re.compile(
|
||||
rf"^{_ANNOTATION}\s*{_ACCESS}{_MOD}\s*(?:static\s+)?[\w<>\[\]]+\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+\w+\s*)?\{{?",
|
||||
_re.IGNORECASE,
|
||||
)
|
||||
annotation_re = _re.compile(r"@(\w+)", _re.IGNORECASE)
|
||||
soql_re = _re.compile(r"\[\s*SELECT\b[^\]]+FROM\s+(\w+)", _re.IGNORECASE)
|
||||
dml_re = _re.compile(r"\b(insert|update|delete|upsert|merge|undelete)\s+\w", _re.IGNORECASE)
|
||||
|
||||
_CONTROL_FLOW = frozenset({
|
||||
"if", "else", "for", "while", "do", "switch", "try", "catch",
|
||||
"finally", "return", "throw", "new", "void", "null",
|
||||
"true", "false", "this", "super", "class", "interface", "enum",
|
||||
"trigger", "on",
|
||||
})
|
||||
|
||||
current_class_nid: str | None = None
|
||||
pending_annotations: list[str] = []
|
||||
|
||||
for lineno, line_text in enumerate(lines, start=1):
|
||||
stripped = line_text.strip()
|
||||
|
||||
if stripped.startswith("@"):
|
||||
for m in annotation_re.finditer(stripped):
|
||||
pending_annotations.append(m.group(1).lower())
|
||||
continue
|
||||
|
||||
tm = trigger_re.match(stripped)
|
||||
if tm:
|
||||
trig_name, sobject = tm.group(1), tm.group(2)
|
||||
trig_nid = _make_id(stem, trig_name)
|
||||
add_node(trig_nid, trig_name, lineno)
|
||||
add_edge(file_nid, trig_nid, "contains", lineno)
|
||||
sob_nid = _make_id(sobject)
|
||||
if sob_nid not in seen_ids:
|
||||
add_node(sob_nid, sobject, lineno)
|
||||
add_edge(trig_nid, sob_nid, "uses", lineno, confidence="INFERRED")
|
||||
current_class_nid = trig_nid
|
||||
pending_annotations = []
|
||||
continue
|
||||
|
||||
cm = cls_re.match(stripped)
|
||||
if cm:
|
||||
class_name = cm.group(1)
|
||||
if class_name.lower() in _CONTROL_FLOW:
|
||||
pending_annotations = []
|
||||
continue
|
||||
class_nid = _make_id(stem, class_name)
|
||||
add_node(class_nid, class_name, lineno)
|
||||
add_edge(file_nid, class_nid, "contains", lineno)
|
||||
if cm.group(2):
|
||||
base = cm.group(2).strip()
|
||||
base_nid = _make_id(stem, base)
|
||||
if base_nid not in seen_ids:
|
||||
base_nid = _make_id(base)
|
||||
if base_nid not in seen_ids:
|
||||
add_node(base_nid, base, lineno)
|
||||
add_edge(class_nid, base_nid, "extends", lineno, confidence="INFERRED")
|
||||
if cm.group(3):
|
||||
for iface in cm.group(3).split(","):
|
||||
iface = iface.strip()
|
||||
if iface:
|
||||
iface_nid = _make_id(stem, iface)
|
||||
if iface_nid not in seen_ids:
|
||||
iface_nid = _make_id(iface)
|
||||
if iface_nid not in seen_ids:
|
||||
add_node(iface_nid, iface, lineno)
|
||||
add_edge(class_nid, iface_nid, "implements", lineno, confidence="INFERRED")
|
||||
current_class_nid = class_nid
|
||||
pending_annotations = []
|
||||
continue
|
||||
|
||||
im = iface_re.match(stripped)
|
||||
if im:
|
||||
iface_name = im.group(1)
|
||||
if iface_name.lower() in _CONTROL_FLOW:
|
||||
pending_annotations = []
|
||||
continue
|
||||
iface_nid = _make_id(stem, iface_name)
|
||||
add_node(iface_nid, iface_name, lineno)
|
||||
add_edge(file_nid if current_class_nid is None else current_class_nid,
|
||||
iface_nid, "contains", lineno)
|
||||
if im.group(2):
|
||||
for parent in im.group(2).split(","):
|
||||
parent = parent.strip()
|
||||
if parent:
|
||||
parent_nid = _make_id(stem, parent)
|
||||
if parent_nid not in seen_ids:
|
||||
parent_nid = _make_id(parent)
|
||||
if parent_nid not in seen_ids:
|
||||
add_node(parent_nid, parent, lineno)
|
||||
add_edge(iface_nid, parent_nid, "extends", lineno, confidence="INFERRED")
|
||||
pending_annotations = []
|
||||
continue
|
||||
|
||||
em = enum_re.match(stripped)
|
||||
if em:
|
||||
enum_name = em.group(1)
|
||||
if enum_name.lower() in _CONTROL_FLOW:
|
||||
pending_annotations = []
|
||||
continue
|
||||
enum_nid = _make_id(stem, enum_name)
|
||||
add_node(enum_nid, enum_name, lineno)
|
||||
add_edge(file_nid if current_class_nid is None else current_class_nid,
|
||||
enum_nid, "contains", lineno)
|
||||
pending_annotations = []
|
||||
continue
|
||||
|
||||
if current_class_nid is not None:
|
||||
mm = method_re.match(stripped)
|
||||
if mm:
|
||||
method_name = mm.group(1)
|
||||
if method_name.lower() not in _CONTROL_FLOW:
|
||||
method_nid = _make_id(current_class_nid, method_name)
|
||||
method_label = f".{method_name}()"
|
||||
add_node(method_nid, method_label, lineno)
|
||||
add_edge(current_class_nid, method_nid, "method", lineno)
|
||||
if "auraenabled" in pending_annotations or "invocablemethod" in pending_annotations:
|
||||
add_edge(file_nid, method_nid, "contains", lineno, confidence="INFERRED")
|
||||
pending_annotations = []
|
||||
continue
|
||||
|
||||
pending_annotations = []
|
||||
|
||||
for sm in soql_re.finditer(line_text):
|
||||
sobject = sm.group(1)
|
||||
sob_nid = _make_id(sobject)
|
||||
if sob_nid not in seen_ids:
|
||||
add_node(sob_nid, sobject, lineno)
|
||||
src = current_class_nid or file_nid
|
||||
add_edge(src, sob_nid, "uses", lineno, confidence="INFERRED")
|
||||
|
||||
for dm in dml_re.finditer(line_text):
|
||||
dml_op = dm.group(1).lower()
|
||||
dml_nid = _make_id(f"dml_{dml_op}")
|
||||
if dml_nid not in seen_ids:
|
||||
add_node(dml_nid, dml_op, lineno)
|
||||
src = current_class_nid or file_nid
|
||||
add_edge(src, dml_nid, "uses", lineno, confidence="INFERRED")
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,66 +0,0 @@
|
||||
# DO NOT import from graphify.extract here — direction is extract.py → extractors/ only.
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.ids import make_id
|
||||
|
||||
# Language built-in globals that AST may classify as call targets when used as
|
||||
# constructors or coercion functions (e.g. String(x), Number(x), Boolean(x)).
|
||||
# Without this filter they become god-nodes accumulating spurious edges from
|
||||
# every call site. Filter applied at same-file and cross-file resolution.
|
||||
# See issue #726.
|
||||
_LANGUAGE_BUILTIN_GLOBALS: frozenset[str] = frozenset({
|
||||
# JavaScript / TypeScript ECMAScript built-ins
|
||||
"String", "Number", "Boolean", "Object", "Array", "Symbol", "BigInt",
|
||||
"Date", "RegExp", "Error", "TypeError", "RangeError", "SyntaxError",
|
||||
"ReferenceError", "EvalError", "URIError",
|
||||
"Promise", "Map", "Set", "WeakMap", "WeakSet", "JSON", "Math",
|
||||
"Reflect", "Proxy", "Intl",
|
||||
"parseInt", "parseFloat", "isNaN", "isFinite",
|
||||
"encodeURIComponent", "decodeURIComponent", "encodeURI", "decodeURI",
|
||||
# Browser / Node common globals
|
||||
"URL", "URLSearchParams", "FormData", "Blob", "File",
|
||||
"Headers", "Request", "Response", "AbortController", "AbortSignal",
|
||||
"TextEncoder", "TextDecoder", "console",
|
||||
# Python built-in callables
|
||||
"str", "int", "float", "bool", "list", "dict", "set", "tuple", "bytes",
|
||||
"len", "range", "enumerate", "zip", "map", "filter", "sum", "min", "max",
|
||||
"print", "open", "isinstance", "type", "super", "sorted", "reversed",
|
||||
"any", "all", "abs", "round", "next", "iter", "hash", "id", "repr",
|
||||
"callable", "getattr", "setattr", "hasattr", "delattr", "vars", "dir",
|
||||
})
|
||||
|
||||
|
||||
def _make_id(*parts: str) -> str:
|
||||
return make_id(*parts)
|
||||
|
||||
|
||||
def _file_stem(path: Path) -> str:
|
||||
"""Stem used as the node-ID prefix for a file and its symbols.
|
||||
|
||||
The full path (extension dropped) is preserved as path segments; ``make_id``
|
||||
later collapses the separators to underscores. Using every segment — not just
|
||||
the immediate parent dir (#1504) — means same-named files in different
|
||||
directories get distinct IDs instead of colliding into one
|
||||
last-writer-wins node:
|
||||
|
||||
docs/v1/api/README.md -> docs/v1/api/README -> docs_v1_api_readme
|
||||
docs/v2/api/README.md -> docs/v2/api/README -> docs_v2_api_readme
|
||||
|
||||
Top-level files keep a bare stem (``setup.py`` -> ``setup``). When passed an
|
||||
absolute path the whole path is encoded; the extract() id-remap post-pass
|
||||
re-derives the canonical repo-relative form from ``source_file`` so the on-disk
|
||||
location can't leak into the persisted IDs (#502).
|
||||
|
||||
Returns "" for a path with no name (``Path('.')`` — a source_file that equals
|
||||
the scan root, so it has no per-file stem). Guarding here keeps
|
||||
``path.with_suffix("")`` from raising ``ValueError: '.' has an empty name`` and
|
||||
protects every caller, not just ``_semantic_id_remap`` (#1618)."""
|
||||
if not path.name:
|
||||
return ""
|
||||
return path.with_suffix("").as_posix()
|
||||
|
||||
|
||||
def _read_text(node, source: bytes) -> str:
|
||||
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
|
||||
@@ -1,248 +0,0 @@
|
||||
"""Bash extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
def extract_bash(path: Path) -> dict:
|
||||
"""Extract functions, source imports, and cross-function calls from a .sh file."""
|
||||
try:
|
||||
import tree_sitter_bash as tsbash
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-bash not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsbash.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any]] = []
|
||||
defined_functions: set[str] = set()
|
||||
|
||||
from graphify.security import sanitize_metadata # module-level cached import
|
||||
|
||||
def add_node(nid: str, label: str, line: int, kind: str = "code") -> None:
|
||||
if nid and nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
"metadata": sanitize_metadata({"language": "bash", "kind": kind})}) # noqa: E501
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
if not src or not tgt or src == tgt:
|
||||
return
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
# file_nid is fully path-derived and never produced by _make_id(stem, func_name),
|
||||
# so appending "__entry" guarantees a distinct ID from any function node.
|
||||
entry_nid = file_nid + "__entry"
|
||||
add_node(file_nid, path.name, 1, kind="file")
|
||||
add_node(entry_nid, f"{path.name} script", 1, kind="bash_entrypoint")
|
||||
add_edge(file_nid, entry_nid, "contains", 1)
|
||||
|
||||
_BASH_SOURCE_COMMANDS = frozenset({"source", "."})
|
||||
_BASH_SCRIPT_RUNNERS = frozenset({"bash", "sh", "zsh", "ksh", "dash"})
|
||||
# Parent node types that mean a contained command is part of a substitution
|
||||
# or expansion, not a real function call. Token-level filtering misses
|
||||
# these because `$(build)` exposes `build` as a child command whose name
|
||||
# token has no metacharacters — only the parent does.
|
||||
_BASH_EXPANSION_PARENTS = frozenset({
|
||||
"command_substitution",
|
||||
"process_substitution",
|
||||
})
|
||||
|
||||
def text(node) -> str:
|
||||
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
|
||||
|
||||
def is_inside_expansion(node) -> bool:
|
||||
parent = node.parent
|
||||
while parent is not None:
|
||||
if parent.type in _BASH_EXPANSION_PARENTS:
|
||||
return True
|
||||
parent = parent.parent
|
||||
return False
|
||||
|
||||
def literal(node) -> str | None:
|
||||
# Token-level filter: rejects names containing shell metacharacters.
|
||||
# Combined with `is_inside_expansion` for parent-context rejection.
|
||||
raw = text(node).strip()
|
||||
if not raw:
|
||||
return None
|
||||
if raw[0:1] in {"'", '"'} and raw[-1:] == raw[0]:
|
||||
raw = raw[1:-1]
|
||||
if any(token in raw for token in ("$", "`", "$(", "<(", ">", "|", ";", "&")):
|
||||
return None
|
||||
return raw
|
||||
|
||||
def _bash_func_name(node) -> str | None:
|
||||
"""Get the name from a function_definition node."""
|
||||
# bash grammar: function_definition has a word child (the name)
|
||||
for child in node.children:
|
||||
if child.type == "word":
|
||||
return literal(child)
|
||||
return None
|
||||
|
||||
def walk_calls(body_node, func_nid: str, seen_calls: set) -> None:
|
||||
if body_node is None:
|
||||
return
|
||||
for child in body_node.children:
|
||||
if child.type == "function_definition":
|
||||
# Skip nested function definitions — their bodies are walked
|
||||
# separately, so we don't attribute their calls to the
|
||||
# enclosing scope.
|
||||
continue
|
||||
if child.type == "command" and not is_inside_expansion(child):
|
||||
cmd_name_node = child.child_by_field_name("name")
|
||||
if cmd_name_node is None and child.children:
|
||||
cmd_name_node = child.children[0]
|
||||
if cmd_name_node:
|
||||
name = literal(cmd_name_node)
|
||||
# Defined-functions wins. Skip-lists for external commands
|
||||
# would create false negatives when a user defines a
|
||||
# function shadowing an external (`install`, `find`, etc.).
|
||||
if name and name in defined_functions:
|
||||
tgt = _make_id(stem, name)
|
||||
key = (func_nid, tgt)
|
||||
if tgt and key not in seen_calls:
|
||||
seen_calls.add(key)
|
||||
add_edge(func_nid, tgt, "calls",
|
||||
child.start_point[0] + 1,
|
||||
confidence="EXTRACTED", context="call")
|
||||
walk_calls(child, func_nid, seen_calls)
|
||||
|
||||
def walk(node, parent_nid: str) -> None:
|
||||
t = node.type
|
||||
if t == "function_definition":
|
||||
name = _bash_func_name(node)
|
||||
if name:
|
||||
fn_nid = _make_id(stem, name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(fn_nid, f"{name}()", line, kind="bash_function")
|
||||
add_edge(parent_nid, fn_nid, "defines", line)
|
||||
defined_functions.add(name)
|
||||
# find the compound_statement body
|
||||
body = None
|
||||
for child in node.children:
|
||||
if child.type == "compound_statement":
|
||||
body = child
|
||||
break
|
||||
function_bodies.append((fn_nid, body))
|
||||
# Recurse into the body so nested function definitions are discovered
|
||||
# and added to function_bodies for the second-pass walk_calls.
|
||||
if body is not None:
|
||||
walk(body, fn_nid)
|
||||
return
|
||||
|
||||
if t == "command":
|
||||
if is_inside_expansion(node):
|
||||
return
|
||||
cmd_name_node = node.child_by_field_name("name")
|
||||
if cmd_name_node is None and node.children:
|
||||
cmd_name_node = node.children[0]
|
||||
if cmd_name_node:
|
||||
cmd = literal(cmd_name_node)
|
||||
args = [c for c in node.children
|
||||
if c.type in ("word", "string", "concatenation")
|
||||
and c != cmd_name_node]
|
||||
if cmd in _BASH_SOURCE_COMMANDS and cmd not in defined_functions:
|
||||
# find the path argument (first word after command name)
|
||||
if args:
|
||||
raw = _read_text(args[0], source).strip().strip("'\"")
|
||||
line = node.start_point[0] + 1
|
||||
if raw.startswith((".", "/")):
|
||||
resolved = (path.parent / raw).resolve()
|
||||
# Only emit the edge if the target actually exists on
|
||||
# disk — prevents graph pollution from crafted paths
|
||||
# like `source ../../etc/passwd` that traverse outside
|
||||
# the project tree (B-1).
|
||||
if resolved.exists():
|
||||
tgt_nid = _make_id(str(resolved))
|
||||
add_edge(file_nid, tgt_nid, "imports_from", line,
|
||||
context="import")
|
||||
else:
|
||||
tgt_nid = _make_id(raw)
|
||||
if tgt_nid:
|
||||
add_edge(file_nid, tgt_nid, "imports", line,
|
||||
context="import")
|
||||
elif cmd and cmd not in defined_functions:
|
||||
raw = cmd if cmd.endswith(".sh") else None
|
||||
if cmd in _BASH_SCRIPT_RUNNERS and args:
|
||||
raw = literal(args[0])
|
||||
if raw and raw.endswith(".sh"):
|
||||
resolved = (path.parent / raw).resolve()
|
||||
if resolved.is_file():
|
||||
target_path = resolved
|
||||
if not path.is_absolute():
|
||||
try:
|
||||
target_path = resolved.relative_to(Path.cwd().resolve())
|
||||
except ValueError:
|
||||
pass
|
||||
caller_nid = entry_nid if parent_nid == file_nid else parent_nid
|
||||
add_edge(caller_nid, _make_id(str(target_path)) + "__entry",
|
||||
"calls", node.start_point[0] + 1,
|
||||
context="script_invocation")
|
||||
return
|
||||
|
||||
if t == "declaration_command":
|
||||
# export/declare/readonly VAR=value at program level
|
||||
if node.parent and node.parent.type == "program":
|
||||
for child in node.children:
|
||||
if child.type == "variable_assignment":
|
||||
var_node = child.child_by_field_name("name")
|
||||
if var_node:
|
||||
var = _read_text(var_node, source).strip()
|
||||
if var:
|
||||
var_nid = _make_id(stem, var)
|
||||
line = child.start_point[0] + 1
|
||||
add_node(var_nid, var, line)
|
||||
add_edge(file_nid, var_nid, "defines", line)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
|
||||
# Pre-pass: collect all defined function names so the source-command handler
|
||||
# in walk() can detect user-defined functions that shadow 'source' / '.'
|
||||
# regardless of definition order in the file.
|
||||
def _prescan_functions(node) -> None:
|
||||
if node.type == "function_definition":
|
||||
name = _bash_func_name(node)
|
||||
if name:
|
||||
defined_functions.add(name)
|
||||
for child in node.children:
|
||||
_prescan_functions(child)
|
||||
else:
|
||||
for child in node.children:
|
||||
_prescan_functions(child)
|
||||
|
||||
_prescan_functions(root)
|
||||
walk(root, file_nid)
|
||||
|
||||
# Second pass: cross-function calls
|
||||
top_seen: set = set()
|
||||
walk_calls(root, entry_nid, top_seen) # top-level calls attributed to the entrypoint
|
||||
for fn_nid, body in function_bodies:
|
||||
walk_calls(body, fn_nid, set())
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,53 +0,0 @@
|
||||
"""Laravel Blade template extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _make_id
|
||||
|
||||
|
||||
def extract_blade(path: Path) -> dict:
|
||||
"""Extract @include, <livewire:> components, and wire:click bindings from Blade templates."""
|
||||
import re
|
||||
try:
|
||||
src = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return {"error": f"cannot read {path}"}
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
nodes = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str(path), "source_location": None}]
|
||||
edges = []
|
||||
|
||||
# @include('path.to.partial') or @include("path.to.partial")
|
||||
for m in re.finditer(r"@include\(['\"]([^'\"]+)['\"]", src):
|
||||
tgt = m.group(1).replace(".", "/")
|
||||
tgt_nid = _make_id(tgt)
|
||||
if tgt_nid not in {n["id"] for n in nodes}:
|
||||
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
|
||||
"source_file": str(path), "source_location": None})
|
||||
edges.append({"source": file_nid, "target": tgt_nid, "relation": "includes",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str(path), "source_location": None, "weight": 1.0})
|
||||
|
||||
# <livewire:component.name /> or <livewire:component.name>
|
||||
for m in re.finditer(r"<livewire:([\w.\-]+)", src):
|
||||
tgt_nid = _make_id(m.group(1))
|
||||
if tgt_nid not in {n["id"] for n in nodes}:
|
||||
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
|
||||
"source_file": str(path), "source_location": None})
|
||||
edges.append({"source": file_nid, "target": tgt_nid, "relation": "uses_component",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str(path), "source_location": None, "weight": 1.0})
|
||||
|
||||
# wire:click="methodName"
|
||||
for m in re.finditer(r'wire:click=["\']([^"\']+)["\']', src):
|
||||
tgt_nid = _make_id(m.group(1))
|
||||
if tgt_nid not in {n["id"] for n in nodes}:
|
||||
nodes.append({"id": tgt_nid, "label": m.group(1), "file_type": "code",
|
||||
"source_file": str(path), "source_location": None})
|
||||
edges.append({"source": file_nid, "target": tgt_nid, "relation": "binds_method",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str(path), "source_location": None, "weight": 1.0})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,393 +0,0 @@
|
||||
"""C# cross-file resolution.
|
||||
|
||||
The config-driven C# *extractor* (``extract_csharp`` → ``_extract_generic``)
|
||||
still lives in ``graphify/extract.py``; per ``extractors/MIGRATION.md`` the
|
||||
config-driven languages cannot be ported one-by-one until the shared
|
||||
``_extract_generic`` core moves as its own coordinated batch. This module is
|
||||
the C# home for the parts that *are* cleanly separable — today, the cross-file
|
||||
type-reference resolver below — and is where ``extract_csharp`` will land when
|
||||
the core migration happens.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _make_id
|
||||
|
||||
|
||||
def _build_csharp_type_def_index(all_nodes: list[dict]) -> dict[tuple[str, str], str]:
|
||||
"""Return deterministic ``(namespace, name) -> node_id`` C# type definitions."""
|
||||
candidates: dict[tuple[str, str], list[dict]] = {}
|
||||
for node in all_nodes:
|
||||
if node.get("type") == "namespace":
|
||||
continue
|
||||
metadata = node.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
metadata = {}
|
||||
if metadata.get("is_nested_type"):
|
||||
continue
|
||||
nid = node.get("id")
|
||||
label = node.get("label")
|
||||
if not (isinstance(nid, str) and nid and isinstance(label, str) and label):
|
||||
continue
|
||||
source_file = node.get("source_file")
|
||||
if (
|
||||
not isinstance(source_file, str)
|
||||
or not source_file.endswith(".cs")
|
||||
or node.get("file_type") != "code"
|
||||
):
|
||||
continue
|
||||
if label.endswith(")") or label.startswith(".") or "." in label:
|
||||
continue
|
||||
namespace = metadata.get("namespace", "")
|
||||
if not isinstance(namespace, str):
|
||||
namespace = ""
|
||||
candidates.setdefault((namespace, label), []).append(node)
|
||||
|
||||
return {
|
||||
key: sorted(
|
||||
nodes,
|
||||
key=lambda node: (
|
||||
str(node.get("source_file") or ""),
|
||||
str(node.get("source_location") or ""),
|
||||
str(node.get("id") or ""),
|
||||
),
|
||||
)[0]["id"]
|
||||
for key, nodes in candidates.items()
|
||||
}
|
||||
|
||||
|
||||
def _strip_trailing_csharp_generic_args(target_fqn: str) -> str:
|
||||
target_fqn = target_fqn.strip()
|
||||
if not target_fqn.endswith(">"):
|
||||
return target_fqn
|
||||
depth = 0
|
||||
for index in range(len(target_fqn) - 1, -1, -1):
|
||||
char = target_fqn[index]
|
||||
if char == ">":
|
||||
depth += 1
|
||||
elif char == "<":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return target_fqn[:index].strip()
|
||||
return target_fqn
|
||||
|
||||
|
||||
def _resolve_cross_file_csharp_imports(
|
||||
per_file: list[dict],
|
||||
paths: list[Path],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Re-point resolvable C# ``using`` import edges to canonical internal nodes.
|
||||
|
||||
Namespace imports resolve only to canonical C# namespace nodes. Alias imports
|
||||
resolve only when the alias target's prefix is a known canonical namespace and
|
||||
the simple type name exists in the shared C# type-definition index. ``using
|
||||
static`` and nested type aliases remain deliberate gaps because they need
|
||||
member/nested-type modeling beyond this import pass.
|
||||
"""
|
||||
_ = (per_file, paths)
|
||||
namespace_id_by_label: dict[str, str] = {}
|
||||
for node in sorted(
|
||||
all_nodes,
|
||||
key=lambda node: (
|
||||
str(node.get("source_file") or ""),
|
||||
str(node.get("source_location") or ""),
|
||||
str(node.get("id") or ""),
|
||||
),
|
||||
):
|
||||
if node.get("type") != "namespace":
|
||||
continue
|
||||
label = node.get("label")
|
||||
nid = node.get("id")
|
||||
if isinstance(label, str) and label and isinstance(nid, str) and nid:
|
||||
namespace_id_by_label.setdefault(label, nid)
|
||||
|
||||
type_def_index = _build_csharp_type_def_index(all_nodes)
|
||||
if not namespace_id_by_label and not type_def_index:
|
||||
return
|
||||
|
||||
repointed_from: set[str] = set()
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") != "imports":
|
||||
continue
|
||||
metadata = edge.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
continue
|
||||
using_kind = metadata.get("using_kind")
|
||||
target_fqn = metadata.get("target_fqn")
|
||||
if not using_kind or not isinstance(target_fqn, str) or not target_fqn:
|
||||
continue
|
||||
|
||||
resolved = None
|
||||
if using_kind == "namespace":
|
||||
resolved = namespace_id_by_label.get(target_fqn)
|
||||
elif using_kind == "alias":
|
||||
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
prefix, sep, name = base_fqn.rpartition(".")
|
||||
if sep and prefix in namespace_id_by_label:
|
||||
resolved = type_def_index.get((prefix, name))
|
||||
|
||||
old_target = edge.get("target")
|
||||
if resolved and resolved != old_target:
|
||||
edge["target"] = resolved
|
||||
if isinstance(old_target, str) and old_target:
|
||||
repointed_from.add(old_target)
|
||||
|
||||
if not repointed_from:
|
||||
return
|
||||
|
||||
still_referenced: set[str] = set()
|
||||
for edge in all_edges:
|
||||
still_referenced.add(edge.get("source"))
|
||||
still_referenced.add(edge.get("target"))
|
||||
all_nodes[:] = [
|
||||
node for node in all_nodes
|
||||
if node.get("id") not in repointed_from or node.get("id") in still_referenced
|
||||
]
|
||||
|
||||
|
||||
def _resolve_csharp_type_references(
|
||||
per_file: list[dict],
|
||||
paths: list[Path],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Arbitrate all C# ``inherits``/``implements``/``references`` targets.
|
||||
|
||||
The extractor emits provisional same-file bindings and sourceless stubs. This
|
||||
pass is the single soundness gate: it uses only graph-stamped namespace/import
|
||||
facts, keeps a binding only when the referenced simple name resolves to one
|
||||
in-scope real type definition, and otherwise leaves the edge on a dangling stub.
|
||||
"""
|
||||
_ = (per_file, paths)
|
||||
|
||||
def _is_cs_file(value: object) -> bool:
|
||||
return isinstance(value, str) and value.endswith(".cs")
|
||||
|
||||
def _metadata(value: object) -> dict:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
def _namespace(node: dict | None) -> str:
|
||||
metadata = _metadata((node or {}).get("metadata"))
|
||||
namespace = metadata.get("namespace", "")
|
||||
return namespace if isinstance(namespace, str) else ""
|
||||
|
||||
def _append_unique(items: list[str], value: str) -> None:
|
||||
if value not in items:
|
||||
items.append(value)
|
||||
|
||||
node_by_id = {
|
||||
node["id"]: node
|
||||
for node in all_nodes
|
||||
if isinstance(node.get("id"), str) and node.get("id")
|
||||
}
|
||||
type_def_index = _build_csharp_type_def_index(all_nodes)
|
||||
known_namespaces = {
|
||||
node.get("label")
|
||||
for node in all_nodes
|
||||
if node.get("type") == "namespace" and isinstance(node.get("label"), str)
|
||||
}
|
||||
|
||||
# Each using carries its lexical scope: ("file", None) applies file-wide;
|
||||
# ("namespace", scope_id) applies only where scope_id is in the ref's scope_chain.
|
||||
namespace_usings_by_file: dict[str, list[tuple[str, str, str | None]]] = {}
|
||||
aliases_by_file: dict[str, dict[str, list[tuple[str, str, str | None]]]] = {}
|
||||
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") != "imports":
|
||||
continue
|
||||
source_node = node_by_id.get(edge.get("source"))
|
||||
if not (
|
||||
source_node
|
||||
and isinstance(source_node.get("label"), str)
|
||||
and source_node.get("label", "").endswith(".cs")
|
||||
):
|
||||
continue
|
||||
source_file = source_node.get("source_file")
|
||||
if not _is_cs_file(source_file):
|
||||
continue
|
||||
metadata = _metadata(edge.get("metadata"))
|
||||
target_fqn = metadata.get("target_fqn")
|
||||
if not isinstance(target_fqn, str) or not target_fqn:
|
||||
continue
|
||||
scope_kind = metadata.get("scope_kind") or "file"
|
||||
scope_id = metadata.get("scope_id")
|
||||
using_kind = metadata.get("using_kind")
|
||||
if using_kind == "namespace":
|
||||
entry = (target_fqn, scope_kind, scope_id)
|
||||
bucket = namespace_usings_by_file.setdefault(source_file, [])
|
||||
if entry not in bucket:
|
||||
bucket.append(entry)
|
||||
elif using_kind == "alias":
|
||||
alias = metadata.get("alias")
|
||||
if isinstance(alias, str) and alias:
|
||||
entry = (target_fqn, scope_kind, scope_id)
|
||||
bucket = aliases_by_file.setdefault(source_file, {}).setdefault(alias, [])
|
||||
if entry not in bucket:
|
||||
bucket.append(entry)
|
||||
|
||||
def _scope_chain(node: dict) -> list[str]:
|
||||
chain = _metadata(node.get("metadata")).get("scope_chain")
|
||||
return chain if isinstance(chain, list) else []
|
||||
|
||||
def _using_in_scope(scope_kind: str, scope_id: str | None, source_node: dict) -> bool:
|
||||
if scope_kind == "file":
|
||||
return True
|
||||
return scope_id is not None and scope_id in _scope_chain(source_node)
|
||||
|
||||
def _scopes_for(source_node: dict, source_file: str) -> list[str]:
|
||||
scopes: list[str] = []
|
||||
_append_unique(scopes, _namespace(source_node))
|
||||
_append_unique(scopes, "")
|
||||
for namespace, scope_kind, scope_id in namespace_usings_by_file.get(source_file, []):
|
||||
if _using_in_scope(scope_kind, scope_id, source_node):
|
||||
_append_unique(scopes, namespace)
|
||||
return scopes
|
||||
|
||||
def _resolve_alias(label: str, source_node: dict, source_file: str) -> str | None:
|
||||
hits = set()
|
||||
for target_fqn, scope_kind, scope_id in aliases_by_file.get(source_file, {}).get(label, []):
|
||||
if not _using_in_scope(scope_kind, scope_id, source_node):
|
||||
continue
|
||||
base_fqn = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
namespace, sep, simple_name = base_fqn.rpartition(".")
|
||||
if not sep:
|
||||
simple_name = namespace
|
||||
namespace = ""
|
||||
if not simple_name:
|
||||
continue
|
||||
hit = type_def_index.get((namespace, simple_name))
|
||||
if hit:
|
||||
hits.add(hit)
|
||||
return next(iter(hits)) if len(hits) == 1 else None
|
||||
|
||||
def _resolve_label(label: str, source_node: dict, source_file: str) -> str | None:
|
||||
if label in aliases_by_file.get(source_file, {}):
|
||||
return _resolve_alias(label, source_node, source_file)
|
||||
candidates: list[str] = []
|
||||
for namespace in _scopes_for(source_node, source_file):
|
||||
hit = type_def_index.get((namespace, label))
|
||||
if hit and hit not in candidates:
|
||||
candidates.append(hit)
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
|
||||
def _resolve_qualified(label: str, qualifier: object, source_node: dict, source_file: str) -> str | None:
|
||||
# Sound qualified resolution: an in-scope alias for Q shadows the namespace Q. For a qualified
|
||||
# ref Q.label, look up (alias_target_namespace, label). If no in-scope alias, fall through to an
|
||||
# exact known namespace. Dangle on ambiguity / no hit / unknown qualifier.
|
||||
if not isinstance(qualifier, str) or not qualifier:
|
||||
return None
|
||||
in_scope = [
|
||||
entry for entry in aliases_by_file.get(source_file, {}).get(qualifier, [])
|
||||
if _using_in_scope(entry[1], entry[2], source_node)
|
||||
]
|
||||
if in_scope:
|
||||
hits = set()
|
||||
for target_fqn, _scope_kind, _scope_id in in_scope:
|
||||
alias_ns = _strip_trailing_csharp_generic_args(html.unescape(target_fqn))
|
||||
hit = type_def_index.get((alias_ns, label))
|
||||
if hit:
|
||||
hits.add(hit)
|
||||
return next(iter(hits)) if len(hits) == 1 else None
|
||||
if qualifier in known_namespaces:
|
||||
return type_def_index.get((qualifier, label))
|
||||
return None
|
||||
|
||||
def _is_placeholder(node: dict | None) -> bool:
|
||||
return bool(node) and not node.get("source_file")
|
||||
|
||||
def _is_csharp_relevant_target(node: dict) -> bool:
|
||||
if node.get("type") == "namespace":
|
||||
return True
|
||||
source_file = node.get("source_file")
|
||||
return not source_file or _is_cs_file(source_file)
|
||||
|
||||
def _label_for_type_ref_target(target_node: dict, source_file: str) -> str | None:
|
||||
label = target_node.get("label")
|
||||
if not isinstance(label, str) or not label:
|
||||
return None
|
||||
if not label.endswith(".cs"):
|
||||
return label
|
||||
|
||||
stem = label[:-3]
|
||||
for alias in aliases_by_file.get(source_file, {}):
|
||||
if alias.lower() == stem.lower() or _make_id(alias) == _make_id(stem):
|
||||
return alias
|
||||
return stem or None
|
||||
|
||||
def _dangling_stub_id(label: str, current_target: object) -> str:
|
||||
current = node_by_id.get(current_target)
|
||||
if _is_placeholder(current) and current.get("label") == label:
|
||||
return str(current_target)
|
||||
|
||||
for node in all_nodes:
|
||||
nid = node.get("id")
|
||||
if (
|
||||
isinstance(nid, str)
|
||||
and node.get("label") == label
|
||||
and _is_placeholder(node)
|
||||
):
|
||||
return nid
|
||||
|
||||
stem = _make_id(label)
|
||||
stub_id = stem
|
||||
if stub_id in node_by_id:
|
||||
stub_id = _make_id("csharp_type_ref", label)
|
||||
suffix = 2
|
||||
while stub_id in node_by_id:
|
||||
stub_id = _make_id("csharp_type_ref", label, str(suffix))
|
||||
suffix += 1
|
||||
node = {
|
||||
"id": stub_id,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
}
|
||||
all_nodes.append(node)
|
||||
node_by_id[stub_id] = node
|
||||
return stub_id
|
||||
|
||||
REPOINT_RELATIONS = {"implements", "inherits", "references"}
|
||||
repointed_from: set[str] = set()
|
||||
for edge in all_edges:
|
||||
if edge.get("relation") not in REPOINT_RELATIONS:
|
||||
continue
|
||||
source_file = edge.get("source_file")
|
||||
if not _is_cs_file(source_file):
|
||||
continue
|
||||
source_node = node_by_id.get(edge.get("source"))
|
||||
target_node = node_by_id.get(edge.get("target"))
|
||||
if not source_node or not target_node:
|
||||
continue
|
||||
if not _is_csharp_relevant_target(target_node):
|
||||
continue
|
||||
metadata = _metadata(edge.get("metadata"))
|
||||
label = metadata.get("ref_token") or _label_for_type_ref_target(target_node, source_file)
|
||||
if not label:
|
||||
continue
|
||||
if metadata.get("qualified"):
|
||||
resolved = _resolve_qualified(label, metadata.get("ref_qualifier"), source_node, source_file)
|
||||
else:
|
||||
resolved = _resolve_label(label, source_node, source_file)
|
||||
target = edge.get("target")
|
||||
desired = resolved or _dangling_stub_id(label, target)
|
||||
if desired != target:
|
||||
edge["target"] = desired
|
||||
if isinstance(target, str) and _is_placeholder(target_node):
|
||||
repointed_from.add(target)
|
||||
|
||||
if not repointed_from:
|
||||
return
|
||||
|
||||
still_referenced: set[str] = set()
|
||||
for edge in all_edges:
|
||||
still_referenced.add(edge.get("source"))
|
||||
still_referenced.add(edge.get("target"))
|
||||
all_nodes[:] = [
|
||||
node for node in all_nodes
|
||||
if node.get("id") not in repointed_from or node.get("id") in still_referenced
|
||||
]
|
||||
@@ -1,528 +0,0 @@
|
||||
"""Dart extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_dart(path: Path) -> dict:
|
||||
"""Extract classes, mixins, functions, imports, generic calls, and annotations from a .dart file using regex."""
|
||||
try:
|
||||
src = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return {"error": f"cannot read {path}"}
|
||||
|
||||
# Remove inline and multi-line comments while leaving string literals untouched to prevent stripping URLs/paths inside strings
|
||||
comment_string_pattern = re.compile(
|
||||
r'"""(?:\\.|[\s\S])*?"""'
|
||||
r"|'''(?:\\.|[\s\S])*?'''"
|
||||
r'|"(?:\\.|[^"\\])*"'
|
||||
r"|'(?:\\.|[^'\\])*'"
|
||||
r"|/\*[\s\S]*?\*/"
|
||||
r"|//[^\n]*"
|
||||
)
|
||||
def _comment_replace(match: re.Match) -> str:
|
||||
token = match.group(0)
|
||||
if token.startswith("/"):
|
||||
return ""
|
||||
return token
|
||||
src_clean = comment_string_pattern.sub(_comment_replace, src)
|
||||
|
||||
stem = _file_stem(path)
|
||||
file_nid = _make_id(str(path))
|
||||
|
||||
# Check if this is a part-of file and redirect to parent
|
||||
part_of_match = re.search(r"^\s*part\s+of\s+['\"]([^'\"]+)['\"]", src_clean, re.MULTILINE)
|
||||
is_part = False
|
||||
if part_of_match:
|
||||
parent_ref = part_of_match.group(1)
|
||||
if parent_ref.endswith(".dart"):
|
||||
try:
|
||||
parent_path = (path.parent / parent_ref).resolve()
|
||||
if parent_path.exists():
|
||||
stem = _file_stem(parent_path)
|
||||
file_nid = _make_id(str(parent_path))
|
||||
is_part = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
nodes = []
|
||||
if not is_part:
|
||||
nodes.append({"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str(path), "source_location": None})
|
||||
edges = []
|
||||
defined: set[str] = set()
|
||||
|
||||
def add_node(nid: str, label: str, ftype: str = "code", source_file: str | None = str(path)) -> None:
|
||||
if nid not in defined:
|
||||
nodes.append({"id": nid, "label": label, "file_type": ftype,
|
||||
"source_file": source_file, "source_location": None})
|
||||
defined.add(nid)
|
||||
|
||||
def add_edge(src_id: str, tgt_id: str, relation: str, weight: float = 1.0, context: str | None = None) -> None:
|
||||
edge = {"source": src_id, "target": tgt_id, "relation": relation,
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str(path), "source_location": None, "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
def _split_types(text: str) -> list[str]:
|
||||
parts = []
|
||||
current = []
|
||||
depth = 0
|
||||
for char in text:
|
||||
if char == "<":
|
||||
depth += 1
|
||||
current.append(char)
|
||||
elif char == ">":
|
||||
depth -= 1
|
||||
current.append(char)
|
||||
elif char == "," and depth == 0:
|
||||
parts.append("".join(current).strip())
|
||||
current = []
|
||||
else:
|
||||
current.append(char)
|
||||
if current:
|
||||
parts.append("".join(current).strip())
|
||||
return [p for p in parts if p]
|
||||
|
||||
def _find_matching_brace(text: str, start_pos: int) -> int:
|
||||
brace_count = 0
|
||||
in_double_quote = False
|
||||
in_single_quote = False
|
||||
escape = False
|
||||
|
||||
first_brace = text.find("{", start_pos)
|
||||
if first_brace == -1:
|
||||
return len(text)
|
||||
|
||||
brace_count = 1
|
||||
i = first_brace + 1
|
||||
n = len(text)
|
||||
while i < n:
|
||||
char = text[i]
|
||||
if escape:
|
||||
escape = False
|
||||
i += 1
|
||||
continue
|
||||
if char == "\\":
|
||||
escape = True
|
||||
i += 1
|
||||
continue
|
||||
if text[i:i+3] == '"""' and not in_single_quote:
|
||||
i += 3
|
||||
end = text.find('"""', i)
|
||||
i = end + 3 if end != -1 else n
|
||||
continue
|
||||
if text[i:i+3] == "'''" and not in_double_quote:
|
||||
i += 3
|
||||
end = text.find("'''", i)
|
||||
i = end + 3 if end != -1 else n
|
||||
continue
|
||||
if char == '"' and not in_single_quote:
|
||||
in_double_quote = not in_double_quote
|
||||
elif char == "'" and not in_double_quote:
|
||||
in_single_quote = not in_single_quote
|
||||
elif not in_double_quote and not in_single_quote:
|
||||
if char == "{":
|
||||
brace_count += 1
|
||||
elif char == "}":
|
||||
brace_count -= 1
|
||||
if brace_count == 0:
|
||||
return i + 1
|
||||
i += 1
|
||||
return len(text)
|
||||
|
||||
# 1. Classes, mixins, and enums declarations (with inheritance, mixins, interfaces, and generics)
|
||||
# Supports multiple combined modifiers (e.g., abstract base class, mixin class) without capturing "class" as a name
|
||||
class_pattern = r"^\s*(?:(?:abstract|sealed|base|interface|final|mixin)\s+)*(?:class|mixin|enum|extension\s+type)\s+(\w+)"
|
||||
for m in re.finditer(class_pattern, src_clean, re.MULTILINE):
|
||||
class_name = m.group(1)
|
||||
class_nid = _make_id(stem, class_name)
|
||||
add_node(class_nid, class_name)
|
||||
add_edge(file_nid, class_nid, "defines")
|
||||
|
||||
# Manually parse extends/on, with, and implements in header to handle nested generics brackets balanced
|
||||
start_idx = m.end()
|
||||
rest = src_clean[start_idx : start_idx + 500]
|
||||
|
||||
# Skip class generic parameters
|
||||
if rest.lstrip().startswith("<"):
|
||||
offset = rest.find("<")
|
||||
depth = 1
|
||||
i = offset + 1
|
||||
while i < len(rest) and depth > 0:
|
||||
if rest[i] == "<": depth += 1
|
||||
elif rest[i] == ">": depth -= 1
|
||||
i += 1
|
||||
rest = rest[i:]
|
||||
|
||||
# Skip primary constructor (e.g. extension type MyExt(int id))
|
||||
if rest.lstrip().startswith("("):
|
||||
offset = rest.find("(")
|
||||
depth = 1
|
||||
i = offset + 1
|
||||
while i < len(rest) and depth > 0:
|
||||
if rest[i] == "(": depth += 1
|
||||
elif rest[i] == ")": depth -= 1
|
||||
i += 1
|
||||
rest = rest[i:]
|
||||
|
||||
header_end = rest.find("{")
|
||||
if header_end == -1:
|
||||
header_end = rest.find(";")
|
||||
if header_end == -1:
|
||||
header_end = len(rest)
|
||||
header = rest[:header_end]
|
||||
|
||||
base_class = None
|
||||
generics = None
|
||||
mixins_list = []
|
||||
interfaces_list = []
|
||||
|
||||
# Parse extends or on
|
||||
extends_m = re.search(r"^\s*(?:extends|on)\s+([a-zA-Z0-9_.]+)", header)
|
||||
if extends_m:
|
||||
base_class = extends_m.group(1)
|
||||
rest_header = header[extends_m.end():]
|
||||
if rest_header.strip().startswith("<"):
|
||||
start_idx = rest_header.find("<")
|
||||
depth = 1
|
||||
i = start_idx + 1
|
||||
while i < len(rest_header) and depth > 0:
|
||||
if rest_header[i] == "<":
|
||||
depth += 1
|
||||
elif rest_header[i] == ">":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
generics = rest_header[start_idx + 1 : i]
|
||||
break
|
||||
i += 1
|
||||
if generics is not None:
|
||||
header = rest_header[i + 1:]
|
||||
else:
|
||||
header = rest_header
|
||||
else:
|
||||
header = rest_header
|
||||
|
||||
# Parse with
|
||||
with_m = re.search(r"^\s*with\s+", header)
|
||||
if with_m:
|
||||
rest_header = header[with_m.end():]
|
||||
impl_idx = rest_header.find("implements")
|
||||
if impl_idx != -1:
|
||||
mixins_str = rest_header[:impl_idx]
|
||||
header = rest_header[impl_idx:]
|
||||
else:
|
||||
mixins_str = rest_header
|
||||
header = ""
|
||||
mixins_list = _split_types(mixins_str)
|
||||
|
||||
# Parse implements
|
||||
impl_m = re.search(r"^\s*implements\s+", header)
|
||||
if impl_m:
|
||||
interfaces_list = _split_types(header[impl_m.end():])
|
||||
|
||||
# Map extends inheritance relation
|
||||
if base_class:
|
||||
base_nid = _make_id(base_class)
|
||||
add_node(base_nid, base_class, source_file=None)
|
||||
add_edge(class_nid, base_nid, "inherits")
|
||||
|
||||
# Map generic type arguments (e.g. MyBloc extends Bloc<MyEvent, MyState>)
|
||||
if generics:
|
||||
for gen in _split_types(generics):
|
||||
gen_clean = gen.split("<")[0].strip()
|
||||
if gen_clean not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
|
||||
gen_nid = _make_id(gen_clean)
|
||||
add_node(gen_nid, gen_clean, source_file=None)
|
||||
add_edge(class_nid, gen_nid, "references")
|
||||
|
||||
# Map mixins
|
||||
for mixin in mixins_list:
|
||||
mixin_clean = mixin.split("<")[0].strip()
|
||||
mixin_nid = _make_id(mixin_clean)
|
||||
add_node(mixin_nid, mixin_clean, source_file=None)
|
||||
add_edge(class_nid, mixin_nid, "mixes_in")
|
||||
|
||||
# Map interfaces
|
||||
for interface in interfaces_list:
|
||||
interface_clean = interface.split("<")[0].strip()
|
||||
interface_nid = _make_id(interface_clean)
|
||||
add_node(interface_nid, interface_clean, source_file=None)
|
||||
add_edge(class_nid, interface_nid, "implements")
|
||||
|
||||
# Extract class body for precise framework dependencies and event handling
|
||||
start_idx = m.start()
|
||||
brace_pos = src_clean.find("{", start_idx)
|
||||
semi_pos = src_clean.find(";", start_idx)
|
||||
|
||||
has_body = brace_pos != -1
|
||||
if has_body and semi_pos != -1 and semi_pos < brace_pos:
|
||||
has_body = False
|
||||
|
||||
if has_body:
|
||||
end_pos = _find_matching_brace(src_clean, start_idx)
|
||||
class_body = src_clean[brace_pos:end_pos]
|
||||
|
||||
# Bloc event registration: on<MyEvent>()
|
||||
for em in re.finditer(r"\bon<(\w+)>\s*\(", class_body):
|
||||
event_name = em.group(1)
|
||||
event_nid = _make_id(event_name)
|
||||
add_node(event_nid, event_name, source_file=None)
|
||||
add_edge(class_nid, event_nid, "calls", context="bloc_event")
|
||||
|
||||
# Bloc state emissions: emit(MyState) or yield MyState
|
||||
for sm in re.finditer(r"\b(?:emit|yield)\s*\(?\s*(?:const\s+)?([A-Z]\w*)\b", class_body):
|
||||
state_name = sm.group(1)
|
||||
if state_name not in {"String", "List", "Map", "Set", "Future", "Stream", "Object"}:
|
||||
state_nid = _make_id(state_name)
|
||||
add_node(state_nid, state_name, source_file=None)
|
||||
add_edge(class_nid, state_nid, "calls", context="emit_state")
|
||||
|
||||
# Bloc event additions: widget.add(MyEvent()) or bloc.add(MyEvent())
|
||||
for am in re.finditer(r"\b(?:\w*[Bb]loc\w*|context\.read<\w+>\(\))\.add\(\s*(?:const\s+)?([A-Z]\w*)\b", class_body):
|
||||
event_name = am.group(1)
|
||||
if event_name not in {"String", "List", "Map", "Set", "Future", "Stream", "Object"}:
|
||||
event_nid = _make_id(event_name)
|
||||
add_node(event_nid, event_name, source_file=None)
|
||||
add_edge(class_nid, event_nid, "calls", context="bloc_add_event")
|
||||
|
||||
# Riverpod provider references: ref.watch(provider)
|
||||
for rm in re.finditer(r"\bref\.(?:watch|read|listen)\s*\(\s*(\w+)\b", class_body):
|
||||
provider_name = rm.group(1)
|
||||
provider_nid = _make_id(provider_name)
|
||||
add_node(provider_nid, provider_name, source_file=None)
|
||||
add_edge(class_nid, provider_nid, "references", context="riverpod_reference")
|
||||
|
||||
# Widget to Bloc references: BlocBuilder<MyBloc, ...>
|
||||
for bm in re.finditer(r"\bBloc(?:Builder|Listener|Consumer|Provider|Selector)\s*<\s*([a-zA-Z0-9_]+)\b", class_body):
|
||||
bloc_name = bm.group(1)
|
||||
if bloc_name not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
|
||||
bloc_nid = _make_id(bloc_name)
|
||||
add_node(bloc_nid, bloc_name, source_file=None)
|
||||
add_edge(class_nid, bloc_nid, "references", context="bloc_widget_binding")
|
||||
|
||||
# context.read<MyBloc>() or BlocProvider.of<MyBloc>(context)
|
||||
for lm in re.finditer(r"\b(?:read|watch|select|of)\s*<([a-zA-Z0-9_]+)>", class_body):
|
||||
bloc_name = lm.group(1)
|
||||
if bloc_name not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
|
||||
bloc_nid = _make_id(bloc_name)
|
||||
add_node(bloc_nid, bloc_name, source_file=None)
|
||||
add_edge(class_nid, bloc_nid, "references", context="bloc_lookup")
|
||||
|
||||
# 2. Annotations mapping (class, mixin, enum, or function level annotations)
|
||||
# Support: @riverpod, @Riverpod(...), @injectable, @singleton, @RoutePage(), @HiveType(typeId: 0), @RestApi()
|
||||
# Matches `@annotation` and links it to the next class/mixin/enum/function declaration in the file
|
||||
annotation_pattern = r"@(\w+)(?:\([^)]*\))?"
|
||||
for am in re.finditer(annotation_pattern, src_clean):
|
||||
annotation_name = am.group(1)
|
||||
if annotation_name in {"override", "deprecated", "required", "protected", "mustCallSuper"}:
|
||||
continue
|
||||
annotation_pos = am.end()
|
||||
intervening_text = src_clean[annotation_pos : annotation_pos + 300]
|
||||
|
||||
class_m = re.search(r"^\s*(?:(?:abstract|sealed|base|interface|final|mixin)\s+)*(?:class|mixin|enum|extension\s+type)\s+(\w+)", intervening_text, re.MULTILINE)
|
||||
func_m = re.search(r"^\s*(?:factory\s+|static\s+|async\s+|external\s+|abstract\s+)?(?:\([^)]+\)|[a-zA-Z0-9_<>,.?]+)(?:\s+[a-zA-Z0-9_<>,.?]+){0,3}\s+(\w+)\s*\(", intervening_text, re.MULTILINE)
|
||||
|
||||
target_nid = None
|
||||
target_name = None
|
||||
target_type = None
|
||||
|
||||
if class_m and func_m:
|
||||
if class_m.start() < func_m.start():
|
||||
target_name = class_m.group(1)
|
||||
target_type = "class"
|
||||
target_nid = _make_id(stem, target_name)
|
||||
else:
|
||||
target_name = func_m.group(1)
|
||||
target_type = "function"
|
||||
target_nid = _make_id(stem, target_name)
|
||||
elif class_m:
|
||||
target_name = class_m.group(1)
|
||||
target_type = "class"
|
||||
target_nid = _make_id(stem, target_name)
|
||||
elif func_m:
|
||||
target_name = func_m.group(1)
|
||||
target_type = "function"
|
||||
target_nid = _make_id(stem, target_name)
|
||||
|
||||
if target_nid and target_name:
|
||||
actual_intervening = intervening_text[:min(class_m.start() if class_m else 300, func_m.start() if func_m else 300)]
|
||||
if ";" not in actual_intervening and "}" not in actual_intervening and "{" not in actual_intervening:
|
||||
annotation_nid = _make_id("annotation", annotation_name.lower())
|
||||
add_node(annotation_nid, f"@{annotation_name}", ftype="concept", source_file=None)
|
||||
add_edge(target_nid, annotation_nid, "configures")
|
||||
|
||||
# Riverpod specific provider generation mapping (supports camelCase class and functional providers)
|
||||
if annotation_name.lower() == "riverpod":
|
||||
if target_type == "class":
|
||||
provider_name = target_name[0].lower() + target_name[1:] + "Provider" if len(target_name) > 1 else target_name.lower() + "Provider"
|
||||
else:
|
||||
provider_name = target_name + "Provider"
|
||||
provider_nid = _make_id(provider_name)
|
||||
add_node(provider_nid, provider_name, ftype="concept", source_file=str(path))
|
||||
add_edge(target_nid, provider_nid, "defines", context="riverpod_provider")
|
||||
|
||||
# 2.5 Typedefs (Type Aliases)
|
||||
typedef_pattern = r"^\s*typedef\s+(\w+)\s*(?:<[^>]+>)?\s*=\s*([a-zA-Z0-9_<>,.?\s]+);"
|
||||
for m in re.finditer(typedef_pattern, src_clean, re.MULTILINE):
|
||||
typedef_name = m.group(1)
|
||||
target_type = m.group(2).split("<")[0].split(".")[-1].strip()
|
||||
if target_type not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "List", "Map", "Set", "void", "Function"}:
|
||||
typedef_nid = _make_id(stem, typedef_name)
|
||||
add_node(typedef_nid, typedef_name)
|
||||
add_edge(file_nid, typedef_nid, "defines")
|
||||
target_nid = _make_id(target_type)
|
||||
add_node(target_nid, target_type, source_file=None)
|
||||
add_edge(typedef_nid, target_nid, "references", context="typedef")
|
||||
|
||||
# 3. Extensions (extension MyExt on MyClass)
|
||||
ext_pattern = r"^\s{0,4}extension\s+(\w+)?(?:<[^>]+>)?\s+on\s+(\w+)"
|
||||
for m in re.finditer(ext_pattern, src_clean, re.MULTILINE):
|
||||
ext_name = m.group(1) or f"{stem}_anonymous_extension"
|
||||
target_class = m.group(2)
|
||||
|
||||
ext_nid = _make_id(stem, ext_name)
|
||||
label = m.group(1) or f"Extension on {target_class}"
|
||||
add_node(ext_nid, label)
|
||||
add_edge(file_nid, ext_nid, "defines")
|
||||
|
||||
target_nid = _make_id(target_class)
|
||||
add_node(target_nid, target_class, source_file=None)
|
||||
add_edge(ext_nid, target_nid, "extends")
|
||||
|
||||
# 4. Top-level and class-level variable declarations (generic variables, records, late, and destructuring)
|
||||
# Restrict indentation to 0-2 spaces to avoid matching local variables inside functions or switch expressions
|
||||
var_pattern = r"^\s{0,2}(?:late\s+)?(?:(?:final|const|var)\s+)?(?:\([^)]+\)\s+|([a-zA-Z0-9_<>,.?]+(?:\s+[a-zA-Z0-9_<>,.?]+){0,3})\s+)?(?:(\w+)|(?:\w+\s*)?\(([^)]+)\))\s*(?:=|$|;)"
|
||||
for m in re.finditer(var_pattern, src_clean, re.MULTILINE):
|
||||
var_type = m.group(1)
|
||||
single_name = m.group(2)
|
||||
destructured_names = m.group(3)
|
||||
|
||||
if not re.match(r"^\s*(?:late|final|const|var)\b", m.group(0)) and not var_type:
|
||||
continue
|
||||
|
||||
if single_name:
|
||||
if single_name not in {"if", "for", "while", "switch", "catch", "return"}:
|
||||
var_nid = _make_id(stem, single_name)
|
||||
add_node(var_nid, single_name)
|
||||
add_edge(file_nid, var_nid, "defines")
|
||||
|
||||
if var_type and var_type not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "List", "Map", "Set", "void"}:
|
||||
clean_type = var_type.split("<")[0].split(".")[-1].strip()
|
||||
type_nid = _make_id(clean_type)
|
||||
add_node(type_nid, clean_type, source_file=None)
|
||||
add_edge(file_nid, type_nid, "references", context="variable_type")
|
||||
elif destructured_names:
|
||||
for name in [n.strip() for n in destructured_names.split(",") if n.strip()]:
|
||||
if ":" in name:
|
||||
name = name.split(":")[-1].strip()
|
||||
if re.match(r"^[a-zA-Z_]\w*$", name) and not re.match(r"^[A-Z]", name):
|
||||
if name not in {"if", "for", "while", "switch", "catch", "return"}:
|
||||
var_nid = _make_id(stem, name)
|
||||
add_node(var_nid, name)
|
||||
add_edge(file_nid, var_nid, "defines")
|
||||
|
||||
# 5. Top-level and member functions/methods (supports typed/generic/record return types and Riverpod/Bloc references)
|
||||
# Restrict indentation to 0-2 spaces to avoid matching nested local functions or methods inside multiline switch statements
|
||||
method_pattern = r"^\s{0,2}(?:factory\s+|static\s+|async\s+|external\s+|abstract\s+)?(?:\([^)]+\)|[a-zA-Z0-9_<>,.?]+)(?:\s+[a-zA-Z0-9_<>,.?]+){0,3}\s+(\w+(?:\.\w+)?)\s*\("
|
||||
for m in re.finditer(method_pattern, src_clean, re.MULTILINE):
|
||||
raw_name = m.group(1)
|
||||
name = raw_name.split(".")[-1]
|
||||
if name in {"if", "for", "while", "switch", "catch", "return", "void", "dynamic", "final", "const", "get", "set"}:
|
||||
continue
|
||||
if re.match(r"^[A-Z]", name):
|
||||
continue
|
||||
nid = _make_id(stem, name)
|
||||
add_node(nid, name)
|
||||
add_edge(file_nid, nid, "defines")
|
||||
|
||||
# Get function body using matching brace to extract Riverpod reference patterns
|
||||
start_idx = m.start()
|
||||
brace_pos = src_clean.find("{", start_idx)
|
||||
semi_pos = src_clean.find(";", start_idx)
|
||||
arrow_pos = src_clean.find("=>", start_idx)
|
||||
|
||||
has_body = brace_pos != -1
|
||||
if has_body and semi_pos != -1 and semi_pos < brace_pos:
|
||||
has_body = False
|
||||
if has_body and arrow_pos != -1 and arrow_pos < brace_pos:
|
||||
has_body = False
|
||||
|
||||
if has_body:
|
||||
end_pos = _find_matching_brace(src_clean, start_idx)
|
||||
func_body = src_clean[brace_pos:end_pos]
|
||||
|
||||
# Extract Riverpod provider references: ref.watch(provider)
|
||||
for rm in re.finditer(r"\bref\.(?:watch|read|listen)\s*\(\s*(\w+)\b", func_body):
|
||||
provider_name = rm.group(1)
|
||||
provider_nid = _make_id(provider_name)
|
||||
add_node(provider_nid, provider_name, source_file=None)
|
||||
add_edge(nid, provider_nid, "references", context="riverpod_reference")
|
||||
|
||||
# Extract Bloc event additions: widget.add(MyEvent()) or bloc.add(MyEvent())
|
||||
for am in re.finditer(r"\b(?:\w*[Bb]loc\w*|context\.read<\w+>\(\))\.add\(\s*(?:const\s+)?([A-Z]\w*)\b", func_body):
|
||||
event_name = am.group(1)
|
||||
if event_name not in {"String", "List", "Map", "Set", "Future", "Stream", "Object"}:
|
||||
event_nid = _make_id(event_name)
|
||||
add_node(event_nid, event_name, source_file=None)
|
||||
add_edge(nid, event_nid, "calls", context="bloc_add_event")
|
||||
|
||||
# context.read<MyBloc>() or BlocProvider.of<MyBloc>(context)
|
||||
for lm in re.finditer(r"\b(?:read|watch|select|of)\s*<([a-zA-Z0-9_]+)>", func_body):
|
||||
bloc_name = lm.group(1)
|
||||
if bloc_name not in {"String", "int", "double", "bool", "num", "dynamic", "Object", "void"}:
|
||||
bloc_nid = _make_id(bloc_name)
|
||||
add_node(bloc_nid, bloc_name, source_file=None)
|
||||
add_edge(nid, bloc_nid, "references", context="bloc_lookup")
|
||||
|
||||
# Universal Navigation Patters (GoRouter, AutoRoute, Navigator)
|
||||
for nm in re.finditer(r"\b(?:go|push|goNamed|pushNamed|replace|replaceNamed)\s*\(\s*(?:context\s*,\s*)?['\"]([a-zA-Z0-9_/?=&%-]+)['\"]", func_body):
|
||||
route_path = nm.group(1)
|
||||
route_nid = _make_id("route", route_path.replace("/", "_").replace("?", "_").replace("=", "_").replace("&", "_"))
|
||||
add_node(route_nid, f"Route {route_path}", ftype="concept", source_file=None)
|
||||
add_edge(nid, route_nid, "navigates", context="route_path")
|
||||
|
||||
for cm in re.finditer(r"\b(?:go|push|goNamed|pushNamed|replace|replaceNamed)\s*\(\s*(?:context\s*,\s*)?([A-Z][a-zA-Z0-9_]*\.[a-zA-Z0-9_]+)", func_body):
|
||||
route_const = cm.group(1)
|
||||
route_nid = _make_id("route", route_const.replace(".", "_"))
|
||||
add_node(route_nid, route_const, ftype="concept", source_file=None)
|
||||
add_edge(nid, route_nid, "navigates", context="route_const")
|
||||
|
||||
for om in re.finditer(r"\b(?:push|replace)\s*\(\s*(?:context\s*,\s*)?.*?\b([A-Z]\w*(?:Route|Screen|Page))\b", func_body):
|
||||
route_class = om.group(1)
|
||||
route_nid = _make_id(route_class)
|
||||
add_node(route_nid, route_class, source_file=None)
|
||||
add_edge(nid, route_nid, "navigates", context="route_object")
|
||||
|
||||
# 6. Imports and Exports
|
||||
for m in re.finditer(r"""^\s*import\s+['"]([^'"]+)['"]""", src_clean, re.MULTILINE):
|
||||
pkg = m.group(1)
|
||||
tgt_nid = _make_id(pkg)
|
||||
add_node(tgt_nid, pkg, source_file=None)
|
||||
add_edge(file_nid, tgt_nid, "imports")
|
||||
|
||||
for m in re.finditer(r"""^\s*export\s+['"]([^'"]+)['"]""", src_clean, re.MULTILINE):
|
||||
pkg = m.group(1)
|
||||
tgt_nid = _make_id(pkg)
|
||||
add_node(tgt_nid, pkg, source_file=None)
|
||||
add_edge(file_nid, tgt_nid, "exports")
|
||||
|
||||
# 7. Generic Invocations / Type Lookups (Universal Dependency Lookup)
|
||||
# Matches any method call with type parameters: methodName<Type>() or object.methodName<Type>()
|
||||
# Automatically extracts GetIt, Injectable, Riverpod, Provider, BlocProvider, and InheritedWidget type lookups!
|
||||
generic_call_pattern = r"\b\w+<([a-zA-Z0-9_.]+(?:<[a-zA-Z0-9_.,\s<>]+>)?)\s*>\s*\("
|
||||
type_blacklist = {"String", "int", "double", "bool", "num", "dynamic", "Object", "List", "Map", "Set", "Future", "Stream", "void"}
|
||||
for m in re.finditer(generic_call_pattern, src_clean):
|
||||
type_name = m.group(1).split(".")[-1].strip()
|
||||
clean_name = type_name.split("<")[0].strip()
|
||||
if clean_name not in type_blacklist:
|
||||
target_nid = _make_id(clean_name)
|
||||
add_node(target_nid, clean_name, source_file=None)
|
||||
add_edge(file_nid, target_nid, "references", context="type_lookup")
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,494 +0,0 @@
|
||||
"""Dm extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
def extract_dm(path: Path) -> dict:
|
||||
"""Extract types, procs, includes, and calls from a .dm/.dme file."""
|
||||
try:
|
||||
import tree_sitter_dm as tsdm
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-dm not installed"}
|
||||
try:
|
||||
language = Language(tsdm.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any, "str | None"]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid and nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
if not src or not tgt or src == tgt:
|
||||
return
|
||||
edge: dict = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def _type_path_text(node) -> str:
|
||||
return _read_text(node, source).strip()
|
||||
|
||||
def _ensure_type(path_text: str, line: int) -> str:
|
||||
nid = _make_id(stem, path_text)
|
||||
add_node(nid, path_text, line)
|
||||
return nid
|
||||
|
||||
def _find_child(node, type_name: str):
|
||||
for c in node.children:
|
||||
if c.type == type_name:
|
||||
return c
|
||||
return None
|
||||
|
||||
def _read_include_path(file_node) -> str:
|
||||
if file_node is None:
|
||||
return ""
|
||||
if file_node.type == "string_literal":
|
||||
parts = []
|
||||
for c in file_node.children:
|
||||
if c.type == "string_content":
|
||||
parts.append(_read_text(c, source))
|
||||
return "".join(parts)
|
||||
return _read_text(file_node, source).strip("'\"")
|
||||
|
||||
def walk(node, parent_type_path: "str | None" = None,
|
||||
parent_type_nid: "str | None" = None) -> None:
|
||||
t = node.type
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
if t == "preproc_include":
|
||||
file_node = node.child_by_field_name("file")
|
||||
raw = _read_include_path(file_node)
|
||||
if raw:
|
||||
norm = raw.replace("\\", "/").lstrip("./")
|
||||
resolved = (path.parent / norm).resolve()
|
||||
edge: dict = {
|
||||
"source": file_nid,
|
||||
"target": _make_id(str(resolved)) if resolved.exists() else _make_id(norm),
|
||||
"relation": "imports_from" if resolved.exists() else "imports",
|
||||
"context": "import",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
}
|
||||
if not resolved.exists():
|
||||
edge["external"] = True
|
||||
edges.append(edge)
|
||||
return
|
||||
|
||||
if t == "type_definition":
|
||||
tp_node = _find_child(node, "type_path")
|
||||
if tp_node is None:
|
||||
return
|
||||
type_path_str = _type_path_text(tp_node)
|
||||
type_nid = _ensure_type(type_path_str, line)
|
||||
add_edge(file_nid, type_nid, "contains", line)
|
||||
body = _find_child(node, "type_body")
|
||||
if body is not None:
|
||||
for c in body.children:
|
||||
walk(c, parent_type_path=type_path_str, parent_type_nid=type_nid)
|
||||
return
|
||||
|
||||
if t in ("type_body_intended", "type_body_braced"):
|
||||
for c in node.children:
|
||||
walk(c, parent_type_path, parent_type_nid)
|
||||
return
|
||||
|
||||
if t in ("type_proc_definition", "type_proc_override"):
|
||||
if parent_type_nid is None or parent_type_path is None:
|
||||
return
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node is None:
|
||||
return
|
||||
proc_name = _read_text(name_node, source)
|
||||
proc_nid = _make_id(stem, parent_type_path, proc_name)
|
||||
add_node(proc_nid, f"{parent_type_path}/{proc_name}()", line)
|
||||
add_edge(parent_type_nid, proc_nid, "method", line)
|
||||
block = _find_child(node, "block")
|
||||
if block is not None:
|
||||
function_bodies.append((proc_nid, block, parent_type_path))
|
||||
return
|
||||
|
||||
if t in ("proc_definition", "proc_override"):
|
||||
tp_node = _find_child(node, "type_path")
|
||||
owner_path: "str | None" = None
|
||||
owner_nid: "str | None" = None
|
||||
if tp_node is not None:
|
||||
owner_path = _type_path_text(tp_node)
|
||||
owner_nid = _ensure_type(owner_path, line)
|
||||
add_edge(file_nid, owner_nid, "contains", line)
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node is None:
|
||||
return
|
||||
proc_name = _read_text(name_node, source)
|
||||
if owner_path and owner_nid:
|
||||
proc_nid = _make_id(stem, owner_path, proc_name)
|
||||
add_node(proc_nid, f"{owner_path}/{proc_name}()", line)
|
||||
add_edge(owner_nid, proc_nid, "method", line)
|
||||
else:
|
||||
proc_nid = _make_id(stem, proc_name)
|
||||
add_node(proc_nid, f"{proc_name}()", line)
|
||||
add_edge(file_nid, proc_nid, "contains", line)
|
||||
block = _find_child(node, "block")
|
||||
if block is not None:
|
||||
function_bodies.append((proc_nid, block, owner_path))
|
||||
return
|
||||
|
||||
if t in ("operator_override", "type_operator_override"):
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_type_path, parent_type_nid)
|
||||
|
||||
walk(root)
|
||||
|
||||
label_to_nids: dict[str, list[str]] = {}
|
||||
path_to_nids: dict[str, list[str]] = {}
|
||||
for n in nodes:
|
||||
label = n["label"].strip("()")
|
||||
last = label.rsplit("/", 1)[-1] if "/" in label else label
|
||||
if last:
|
||||
label_to_nids.setdefault(last.lower(), []).append(n["id"])
|
||||
if label.startswith("/"):
|
||||
path_to_nids.setdefault(label.lower(), []).append(n["id"])
|
||||
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def _emit_call(caller_nid: str, callee: str, line: int, is_member: bool) -> None:
|
||||
candidates = label_to_nids.get(callee.lower(), [])
|
||||
tgt_nid = candidates[0] if len(candidates) == 1 else None
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair in seen_call_pairs:
|
||||
return
|
||||
seen_call_pairs.add(pair)
|
||||
edges.append({
|
||||
"source": caller_nid, "target": tgt_nid, "relation": "calls",
|
||||
"context": "call", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "source_location": f"L{line}", "weight": 1.0,
|
||||
})
|
||||
else:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid, "callee": callee,
|
||||
"is_member_call": is_member, "source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def walk_calls(body_node, caller_nid: str) -> None:
|
||||
if body_node is None:
|
||||
return
|
||||
t = body_node.type
|
||||
if t in ("proc_definition", "proc_override", "type_proc_definition",
|
||||
"type_proc_override", "type_definition"):
|
||||
return
|
||||
if t == "call_expression":
|
||||
name_node = body_node.child_by_field_name("name")
|
||||
if name_node is not None:
|
||||
callee = _read_text(name_node, source)
|
||||
if callee and callee != "..":
|
||||
_emit_call(caller_nid, callee, body_node.start_point[0] + 1,
|
||||
is_member=False)
|
||||
elif t == "field_proc_expression":
|
||||
proc_field = body_node.child_by_field_name("proc")
|
||||
if proc_field is not None:
|
||||
callee = _read_text(proc_field, source)
|
||||
if callee:
|
||||
_emit_call(caller_nid, callee, body_node.start_point[0] + 1,
|
||||
is_member=True)
|
||||
elif t == "new_expression":
|
||||
tp_node = _find_child(body_node, "type_path")
|
||||
if tp_node is not None:
|
||||
target_text = _type_path_text(tp_node)
|
||||
candidates = path_to_nids.get(target_text.lower(), [])
|
||||
tgt_nid = candidates[0] if len(candidates) == 1 else None
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
edges.append({
|
||||
"source": caller_nid, "target": tgt_nid,
|
||||
"relation": "instantiates", "context": "call",
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{body_node.start_point[0] + 1}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
for child in body_node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for proc_nid, block, _owner_path in function_bodies:
|
||||
walk_calls(block, proc_nid)
|
||||
|
||||
return {"nodes": nodes, "edges": edges, "raw_calls": raw_calls}
|
||||
|
||||
def _read_dmi_description(data: bytes) -> str:
|
||||
"""Pull the BYOND metadata text out of a .dmi PNG, or empty string on failure."""
|
||||
import struct
|
||||
import zlib as _zlib
|
||||
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return ""
|
||||
i = 8
|
||||
while i + 8 <= len(data):
|
||||
length = struct.unpack(">I", data[i:i + 4])[0]
|
||||
chunk_type = data[i + 4:i + 8]
|
||||
payload = data[i + 8:i + 8 + length]
|
||||
if chunk_type in (b"tEXt", b"zTXt"):
|
||||
try:
|
||||
null = payload.index(b"\x00")
|
||||
except ValueError:
|
||||
return ""
|
||||
keyword = payload[:null]
|
||||
if keyword == b"Description":
|
||||
if chunk_type == b"zTXt":
|
||||
return _zlib.decompressobj().decompress(payload[null + 2:], max_length=1024 * 1024).decode("utf-8", errors="replace")
|
||||
return payload[null + 1:].decode("utf-8", errors="replace")
|
||||
i += 8 + length + 4
|
||||
return ""
|
||||
|
||||
def extract_dmi(path: Path) -> dict:
|
||||
"""Extract icon state names from a .dmi (BYOND PNG icon sheet)."""
|
||||
try:
|
||||
data = path.read_bytes()
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
str_path = str(path)
|
||||
stem = _file_stem(path)
|
||||
file_nid = _make_id(str(path))
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": "L1"}]
|
||||
edges: list[dict] = []
|
||||
seen: set[str] = {file_nid}
|
||||
|
||||
description = _read_dmi_description(data)
|
||||
if not description:
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
line_no = 0
|
||||
for raw_line in description.splitlines():
|
||||
line_no += 1
|
||||
stripped = raw_line.strip()
|
||||
if not stripped.startswith("state ="):
|
||||
continue
|
||||
value = stripped.split("=", 1)[1].strip()
|
||||
if value.startswith('"') and value.endswith('"') and len(value) >= 2:
|
||||
state_name = value[1:-1]
|
||||
else:
|
||||
state_name = value
|
||||
if not state_name:
|
||||
continue
|
||||
nid = _make_id(stem, "state", state_name)
|
||||
if nid in seen:
|
||||
continue
|
||||
seen.add(nid)
|
||||
nodes.append({"id": nid, "label": f'"{state_name}"', "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line_no}"})
|
||||
edges.append({"source": file_nid, "target": nid, "relation": "contains",
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line_no}", "weight": 1.0})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
_DMM_GRID_RE = re.compile(r"^\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)\s*=", re.MULTILINE)
|
||||
|
||||
def _split_dmm_tile(body: str) -> list[str]:
|
||||
out: list[str] = []
|
||||
buf: list[str] = []
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
for ch in body:
|
||||
if escape:
|
||||
buf.append(ch)
|
||||
escape = False
|
||||
continue
|
||||
if in_string:
|
||||
buf.append(ch)
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_string = False
|
||||
continue
|
||||
if ch == '"':
|
||||
in_string = True
|
||||
buf.append(ch)
|
||||
elif ch in "({[":
|
||||
depth += 1
|
||||
buf.append(ch)
|
||||
elif ch in ")}]":
|
||||
depth -= 1
|
||||
buf.append(ch)
|
||||
elif ch == "," and depth == 0:
|
||||
out.append("".join(buf).strip())
|
||||
buf = []
|
||||
else:
|
||||
buf.append(ch)
|
||||
tail = "".join(buf).strip()
|
||||
if tail:
|
||||
out.append(tail)
|
||||
return out
|
||||
|
||||
def _dmm_type_path(entry: str) -> str:
|
||||
brace = entry.find("{")
|
||||
if brace != -1:
|
||||
entry = entry[:brace]
|
||||
return entry.strip()
|
||||
|
||||
def extract_dmm(path: Path) -> dict:
|
||||
"""Extract type-path references from a .dmm map file's tile dictionary."""
|
||||
try:
|
||||
if path.stat().st_size > 50 * 1024 * 1024:
|
||||
return {"nodes": [], "edges": [], "error": "file too large (>50 MB)"}
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
str_path = str(path)
|
||||
file_nid = _make_id(str(path))
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": "L1"}]
|
||||
edges: list[dict] = []
|
||||
|
||||
grid_match = _DMM_GRID_RE.search(text)
|
||||
dict_text = text[:grid_match.start()] if grid_match else text
|
||||
|
||||
seen_targets: set[str] = set()
|
||||
buf: list[str] = []
|
||||
open_line = 0
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
for line_idx, line in enumerate(dict_text.splitlines(), start=1):
|
||||
for ch in line:
|
||||
if escape:
|
||||
escape = False
|
||||
elif in_string:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_string = False
|
||||
elif ch == '"':
|
||||
in_string = True
|
||||
elif ch == "(":
|
||||
if depth == 0:
|
||||
open_line = line_idx
|
||||
depth += 1
|
||||
elif ch == ")":
|
||||
depth -= 1
|
||||
buf.append(ch)
|
||||
buf.append("\n")
|
||||
if depth == 0 and buf:
|
||||
chunk = "".join(buf)
|
||||
buf = []
|
||||
lp = chunk.find("(")
|
||||
rp = chunk.rfind(")")
|
||||
if lp == -1 or rp == -1 or rp <= lp:
|
||||
continue
|
||||
inner = chunk[lp + 1:rp]
|
||||
for entry in _split_dmm_tile(inner):
|
||||
tpath = _dmm_type_path(entry)
|
||||
if not tpath.startswith("/"):
|
||||
continue
|
||||
tgt = _make_id(tpath)
|
||||
if tgt in seen_targets:
|
||||
continue
|
||||
seen_targets.add(tgt)
|
||||
edges.append({"source": file_nid, "target": tgt, "relation": "uses",
|
||||
"context": "map", "confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{open_line}", "weight": 1.0})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
_DMF_WINDOW_RE = re.compile(r'^\s*window\s+"([^"]+)"\s*$')
|
||||
|
||||
_DMF_ELEM_RE = re.compile(r'^\s*elem\s+"([^"]+)"\s*$')
|
||||
|
||||
_DMF_TYPE_RE = re.compile(r'^\s*type\s*=\s*(\S+)\s*$')
|
||||
|
||||
def extract_dmf(path: Path) -> dict:
|
||||
"""Extract windows and controls from a .dmf interface file."""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
str_path = str(path)
|
||||
stem = _file_stem(path)
|
||||
file_nid = _make_id(str(path))
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": "L1"}]
|
||||
edges: list[dict] = []
|
||||
seen: set[str] = {file_nid}
|
||||
|
||||
current_window_nid: str | None = None
|
||||
current_elem_nid: str | None = None
|
||||
current_elem_name: str | None = None
|
||||
|
||||
for line_idx, line in enumerate(text.splitlines(), start=1):
|
||||
m = _DMF_WINDOW_RE.match(line)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
nid = _make_id(stem, "window", name)
|
||||
if nid not in seen:
|
||||
seen.add(nid)
|
||||
nodes.append({"id": nid, "label": f'window "{name}"', "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line_idx}"})
|
||||
edges.append({"source": file_nid, "target": nid, "relation": "contains",
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line_idx}", "weight": 1.0})
|
||||
current_window_nid = nid
|
||||
current_elem_nid = None
|
||||
current_elem_name = None
|
||||
continue
|
||||
m = _DMF_ELEM_RE.match(line)
|
||||
if m and current_window_nid is not None:
|
||||
name = m.group(1)
|
||||
nid = _make_id(stem, "elem", current_window_nid, name)
|
||||
if nid not in seen:
|
||||
seen.add(nid)
|
||||
nodes.append({"id": nid, "label": f'elem "{name}"', "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line_idx}"})
|
||||
edges.append({"source": current_window_nid, "target": nid,
|
||||
"relation": "contains", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "source_location": f"L{line_idx}",
|
||||
"weight": 1.0})
|
||||
current_elem_nid = nid
|
||||
current_elem_name = name
|
||||
continue
|
||||
m = _DMF_TYPE_RE.match(line)
|
||||
if m and current_elem_nid is not None and current_elem_name is not None:
|
||||
ctype = m.group(1)
|
||||
for n in nodes:
|
||||
if n["id"] == current_elem_nid and " [" not in n["label"]:
|
||||
n["label"] = f'elem "{current_elem_name}" [{ctype}]'
|
||||
break
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,228 +0,0 @@
|
||||
"""Elixir extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS, _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_elixir(path: Path) -> dict:
|
||||
"""Extract modules, functions, imports, and calls from a .ex/.exs file."""
|
||||
try:
|
||||
import tree_sitter_elixir as tselixir
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_elixir not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tselixir.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
_IMPORT_KEYWORDS = frozenset({"alias", "import", "require", "use"})
|
||||
|
||||
def _get_alias_text(node) -> str | None:
|
||||
for child in node.children:
|
||||
if child.type == "alias":
|
||||
return source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
return None
|
||||
|
||||
def _get_alias_modules(node) -> list[str]:
|
||||
"""Every module named by an alias/import/require/use argument.
|
||||
|
||||
Handles the single form (``alias Foo.Bar`` -> ``["Foo.Bar"]``) and the
|
||||
multi-alias brace form (``alias Foo.{Bar, Baz}`` ->
|
||||
``["Foo.Bar", "Foo.Baz"]``), which the grammar represents as a ``dot``
|
||||
node holding the base alias and a trailing ``tuple`` of member aliases.
|
||||
"""
|
||||
def _text(n) -> str:
|
||||
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
|
||||
|
||||
for child in node.children:
|
||||
if child.type == "alias":
|
||||
return [_text(child)]
|
||||
if child.type == "dot":
|
||||
base = None
|
||||
tuple_node = None
|
||||
for sub in child.children:
|
||||
if sub.type == "alias" and base is None:
|
||||
base = _text(sub)
|
||||
elif sub.type == "tuple":
|
||||
tuple_node = sub
|
||||
if base and tuple_node is not None:
|
||||
members = [_text(m) for m in tuple_node.children if m.type == "alias"]
|
||||
if members:
|
||||
return [f"{base}.{m}" for m in members]
|
||||
return [_text(child)]
|
||||
return []
|
||||
|
||||
def walk(node, parent_module_nid: str | None = None) -> None:
|
||||
if node.type != "call":
|
||||
for child in node.children:
|
||||
walk(child, parent_module_nid)
|
||||
return
|
||||
|
||||
identifier_node = None
|
||||
arguments_node = None
|
||||
do_block_node = None
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
identifier_node = child
|
||||
elif child.type == "arguments":
|
||||
arguments_node = child
|
||||
elif child.type == "do_block":
|
||||
do_block_node = child
|
||||
|
||||
if identifier_node is None:
|
||||
for child in node.children:
|
||||
walk(child, parent_module_nid)
|
||||
return
|
||||
|
||||
keyword = source[identifier_node.start_byte:identifier_node.end_byte].decode("utf-8", errors="replace")
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
if keyword == "defmodule":
|
||||
module_name = _get_alias_text(arguments_node) if arguments_node else None
|
||||
if not module_name:
|
||||
return
|
||||
module_nid = _make_id(stem, module_name)
|
||||
add_node(module_nid, module_name, line)
|
||||
add_edge(file_nid, module_nid, "contains", line)
|
||||
if do_block_node:
|
||||
for child in do_block_node.children:
|
||||
walk(child, parent_module_nid=module_nid)
|
||||
return
|
||||
|
||||
if keyword in ("def", "defp"):
|
||||
func_name = None
|
||||
if arguments_node:
|
||||
for child in arguments_node.children:
|
||||
if child.type == "call":
|
||||
for sub in child.children:
|
||||
if sub.type == "identifier":
|
||||
func_name = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
|
||||
break
|
||||
elif child.type == "identifier":
|
||||
func_name = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
break
|
||||
if not func_name:
|
||||
return
|
||||
container = parent_module_nid or file_nid
|
||||
func_nid = _make_id(container, func_name)
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
if parent_module_nid:
|
||||
add_edge(parent_module_nid, func_nid, "method", line)
|
||||
else:
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
if do_block_node:
|
||||
function_bodies.append((func_nid, do_block_node))
|
||||
return
|
||||
|
||||
if keyword in _IMPORT_KEYWORDS and arguments_node:
|
||||
for module_name in _get_alias_modules(arguments_node):
|
||||
tgt_nid = _make_id(module_name)
|
||||
add_edge(file_nid, tgt_nid, "imports", line, context="import")
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_module_nid)
|
||||
|
||||
walk(root)
|
||||
|
||||
label_to_nid: dict[str, str] = {}
|
||||
for n in nodes:
|
||||
normalised = n["label"].strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
_SKIP_KEYWORDS = frozenset({
|
||||
"def", "defp", "defmodule", "defmacro", "defmacrop",
|
||||
"defstruct", "defprotocol", "defimpl", "defguard",
|
||||
"alias", "import", "require", "use",
|
||||
"if", "unless", "case", "cond", "with", "for",
|
||||
})
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
if node.type != "call":
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
return
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
kw = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
if kw in _SKIP_KEYWORDS:
|
||||
for c in node.children:
|
||||
walk_calls(c, caller_nid)
|
||||
return
|
||||
break
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
for child in node.children:
|
||||
if child.type == "dot":
|
||||
is_member_call = True
|
||||
dot_text = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
parts = dot_text.rstrip(".").split(".")
|
||||
if parts:
|
||||
callee_name = parts[-1]
|
||||
break
|
||||
if child.type == "identifier":
|
||||
callee_name = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
|
||||
break
|
||||
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
|
||||
tgt_nid = label_to_nid.get(callee_name)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
add_edge(caller_nid, tgt_nid, "calls",
|
||||
node.start_point[0] + 1, confidence="EXTRACTED", weight=1.0,
|
||||
context="call")
|
||||
else:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for caller_nid, body in function_bodies:
|
||||
walk_calls(body, caller_nid)
|
||||
|
||||
clean_edges = [e for e in edges if e["source"] in seen_ids and
|
||||
(e["target"] in seen_ids or e["relation"] == "imports")]
|
||||
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls, "input_tokens": 0, "output_tokens": 0}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,309 +0,0 @@
|
||||
"""Fortran extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
_FORTRAN_CPP_EXTS = {".F", ".F90", ".F95", ".F03", ".F08"}
|
||||
|
||||
def _cpp_preprocess(path: Path) -> bytes:
|
||||
"""Run cpp -w -P on a capital-F Fortran file and return preprocessed bytes.
|
||||
|
||||
Falls back to raw file bytes if cpp is not available. Capital-F extensions
|
||||
conventionally require C preprocessor expansion (#ifdef MPI, #define REAL8, etc.)
|
||||
before parsing.
|
||||
|
||||
Security (F-007): we pass `-nostdinc` and `-I /dev/null` so a malicious
|
||||
source file containing `#include "/home/victim/.ssh/id_rsa"` (or any other
|
||||
include directive) cannot inline arbitrary host files into the output that
|
||||
we then ship to an LLM. Without these flags `cpp` happily resolves any
|
||||
relative or absolute include path it can read, which is a corpus-side
|
||||
file-exfiltration vector.
|
||||
"""
|
||||
import shutil
|
||||
import subprocess
|
||||
if not shutil.which("cpp"):
|
||||
return path.read_bytes()
|
||||
try:
|
||||
# Pass an absolute path so a corpus file named like "-I/etc/x.F90" cannot
|
||||
# be parsed by cpp as an option (cpp does not accept a "--" end-of-options
|
||||
# terminator). An absolute path always begins with "/".
|
||||
result = subprocess.run(
|
||||
["cpp", "-w", "-P", "-nostdinc", "-I", "/dev/null", str(path.resolve())],
|
||||
capture_output=True,
|
||||
timeout=30,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout:
|
||||
return result.stdout
|
||||
except Exception:
|
||||
pass
|
||||
return path.read_bytes()
|
||||
|
||||
def extract_fortran(path: Path) -> dict:
|
||||
"""Extract programs, modules, subroutines, functions, use statements, and calls from Fortran files.
|
||||
|
||||
Capital-F extensions (.F, .F90, etc.) are run through the C preprocessor before
|
||||
parsing so #ifdef/#define macros are resolved.
|
||||
"""
|
||||
try:
|
||||
import tree_sitter_fortran as tsfortran
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-fortran not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsfortran.language())
|
||||
parser = Parser(language)
|
||||
source = _cpp_preprocess(path) if path.suffix in _FORTRAN_CPP_EXTS else path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
scope_bodies: list[tuple[str, object]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
"relation": relation,
|
||||
"confidence": confidence,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": weight,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def _fortran_name(stmt_node) -> str | None:
|
||||
"""Extract name from a *_statement node. Fortran is case-insensitive; lowercase."""
|
||||
for child in stmt_node.children:
|
||||
if child.type in ("name", "identifier"):
|
||||
return _read_text(child, source).lower()
|
||||
return None
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
if nid in seen_ids:
|
||||
return nid
|
||||
nid = _make_id(name)
|
||||
if nid not in seen_ids:
|
||||
# The name isn't defined in this file, so this is a cross-file reference
|
||||
# (e.g. a `Thing` type annotation imported from another module). Emit a
|
||||
# SOURCELESS stub — like the inheritance-base path below — so the
|
||||
# corpus-level rewire can collapse it onto the real definition. A sourced
|
||||
# stub here makes _disambiguate_colliding_node_ids bake the referencing
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
return nid
|
||||
|
||||
def emit_signature_refs(scope_node, fn_nid: str, is_function: bool) -> None:
|
||||
"""Emit references[parameter_type] / references[return_type] edges for
|
||||
a subroutine/function based on its variable_declaration siblings."""
|
||||
stmt_type = "function_statement" if is_function else "subroutine_statement"
|
||||
stmt = next((c for c in scope_node.children if c.type == stmt_type), None)
|
||||
if stmt is None:
|
||||
return
|
||||
param_names: set[str] = set()
|
||||
params_node = next((c for c in stmt.children if c.type == "parameters"), None)
|
||||
if params_node is not None:
|
||||
for c in params_node.children:
|
||||
if c.type == "identifier":
|
||||
param_names.add(_read_text(c, source).lower())
|
||||
result_name: str | None = None
|
||||
if is_function:
|
||||
result_node = next((c for c in stmt.children if c.type == "function_result"), None)
|
||||
if result_node is not None:
|
||||
res_id = next((c for c in result_node.children if c.type == "identifier"), None)
|
||||
if res_id is not None:
|
||||
result_name = _read_text(res_id, source).lower()
|
||||
else:
|
||||
# implicit result variable: same name as the function
|
||||
result_name = _fortran_name(stmt)
|
||||
for child in scope_node.children:
|
||||
if child.type != "variable_declaration":
|
||||
continue
|
||||
derived = next((c for c in child.children if c.type == "derived_type"), None)
|
||||
if derived is None:
|
||||
continue
|
||||
type_name_node = next((c for c in derived.children if c.type == "type_name"), None)
|
||||
if type_name_node is None:
|
||||
continue
|
||||
type_name = _read_text(type_name_node, source).lower()
|
||||
for var in child.children:
|
||||
if var.type != "identifier":
|
||||
continue
|
||||
var_name = _read_text(var, source).lower()
|
||||
var_line = var.start_point[0] + 1
|
||||
if var_name in param_names:
|
||||
tgt = ensure_named_node(type_name, var_line)
|
||||
if tgt != fn_nid:
|
||||
add_edge(fn_nid, tgt, "references", var_line, context="parameter_type")
|
||||
elif is_function and var_name == result_name:
|
||||
tgt = ensure_named_node(type_name, var_line)
|
||||
if tgt != fn_nid:
|
||||
add_edge(fn_nid, tgt, "references", var_line, context="return_type")
|
||||
|
||||
def walk_calls(node, scope_nid: str) -> None:
|
||||
if node is None:
|
||||
return
|
||||
t = node.type
|
||||
if t in ("subroutine", "function", "module", "program", "internal_procedures"):
|
||||
return
|
||||
# call FOO(args) — tree-sitter-fortran uses subroutine_call
|
||||
if t == "subroutine_call":
|
||||
name_node = next((c for c in node.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
callee = _read_text(name_node, source).lower()
|
||||
target_nid = _make_id(stem, callee)
|
||||
add_edge(scope_nid, target_nid, "calls", node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", context="call")
|
||||
# x = compute(args) — function invocations are `call_expression`, which
|
||||
# shares Fortran's `name(...)` syntax with array indexing. Only emit a
|
||||
# call edge when the callee resolves to a procedure defined in this file
|
||||
# (an array variable produces no matching node), so array accesses can't
|
||||
# fabricate spurious `calls` edges.
|
||||
elif t == "call_expression":
|
||||
name_node = next((c for c in node.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
callee = _read_text(name_node, source).lower()
|
||||
target_nid = _make_id(stem, callee)
|
||||
if target_nid in seen_ids and target_nid != scope_nid:
|
||||
add_edge(scope_nid, target_nid, "calls", node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", context="call")
|
||||
for child in node.children:
|
||||
walk_calls(child, scope_nid)
|
||||
|
||||
def walk(node, scope_nid: str) -> None:
|
||||
t = node.type
|
||||
|
||||
if t == "program":
|
||||
stmt = next((c for c in node.children if c.type == "program_statement"), None)
|
||||
name = _fortran_name(stmt) if stmt else None
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(nid, name, line)
|
||||
add_edge(file_nid, nid, "defines", line)
|
||||
scope_bodies.append((nid, node))
|
||||
for child in node.children:
|
||||
walk(child, nid)
|
||||
return
|
||||
|
||||
if t == "module":
|
||||
stmt = next((c for c in node.children if c.type == "module_statement"), None)
|
||||
name = _fortran_name(stmt) if stmt else None
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(nid, name, line)
|
||||
add_edge(file_nid, nid, "defines", line)
|
||||
for child in node.children:
|
||||
walk(child, nid)
|
||||
return
|
||||
|
||||
# subroutines/functions inside a module live under internal_procedures
|
||||
if t == "internal_procedures":
|
||||
for child in node.children:
|
||||
walk(child, scope_nid)
|
||||
return
|
||||
|
||||
if t == "derived_type_definition":
|
||||
stmt = next((c for c in node.children if c.type == "derived_type_statement"), None)
|
||||
if stmt is not None:
|
||||
name_node = next((c for c in stmt.children if c.type == "type_name"), None)
|
||||
if name_node is not None:
|
||||
type_name = _read_text(name_node, source).lower()
|
||||
type_nid = _make_id(stem, type_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(type_nid, type_name, line)
|
||||
add_edge(scope_nid, type_nid, "defines", line)
|
||||
return
|
||||
|
||||
if t == "subroutine":
|
||||
stmt = next((c for c in node.children if c.type == "subroutine_statement"), None)
|
||||
name = _fortran_name(stmt) if stmt else None
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(nid, f"{name}()", line)
|
||||
add_edge(scope_nid, nid, "defines", line)
|
||||
scope_bodies.append((nid, node))
|
||||
emit_signature_refs(node, nid, is_function=False)
|
||||
for child in node.children:
|
||||
walk(child, nid)
|
||||
return
|
||||
|
||||
if t == "function":
|
||||
stmt = next((c for c in node.children if c.type == "function_statement"), None)
|
||||
name = _fortran_name(stmt) if stmt else None
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(nid, f"{name}()", line)
|
||||
add_edge(scope_nid, nid, "defines", line)
|
||||
scope_bodies.append((nid, node))
|
||||
emit_signature_refs(node, nid, is_function=True)
|
||||
for child in node.children:
|
||||
walk(child, nid)
|
||||
return
|
||||
|
||||
if t == "use_statement":
|
||||
line = node.start_point[0] + 1
|
||||
# tree-sitter-fortran uses module_name node for the used module
|
||||
name_node = next((c for c in node.children if c.type in ("module_name", "name", "identifier")), None)
|
||||
if name_node:
|
||||
mod_name = _read_text(name_node, source).lower()
|
||||
imp_nid = _make_id(mod_name)
|
||||
add_node(imp_nid, mod_name, line)
|
||||
add_edge(scope_nid, imp_nid, "imports", line, context="use")
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, scope_nid)
|
||||
|
||||
walk(root, file_nid)
|
||||
|
||||
_stmt_headers = {
|
||||
"subroutine_statement", "function_statement",
|
||||
"program_statement", "module_statement",
|
||||
}
|
||||
for scope_nid, body_node in scope_bodies:
|
||||
for child in body_node.children:
|
||||
if child.type not in _stmt_headers:
|
||||
walk_calls(child, scope_nid)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,396 +0,0 @@
|
||||
"""Go extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS, _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
_GO_PREDECLARED_TYPES = frozenset({
|
||||
"bool", "byte", "complex64", "complex128", "error", "float32", "float64",
|
||||
"int", "int8", "int16", "int32", "int64", "rune", "string",
|
||||
"uint", "uint8", "uint16", "uint32", "uint64", "uintptr", "any", "comparable",
|
||||
})
|
||||
|
||||
def _go_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[str, str]]) -> None:
|
||||
"""Walk a Go type expression; append (name, role) tuples."""
|
||||
if node is None:
|
||||
return
|
||||
t = node.type
|
||||
if t == "type_identifier":
|
||||
text = _read_text(node, source)
|
||||
if text and text not in _GO_PREDECLARED_TYPES:
|
||||
out.append((text, "generic_arg" if generic else "type"))
|
||||
return
|
||||
if t == "qualified_type":
|
||||
text = _read_text(node, source).rsplit(".", 1)[-1]
|
||||
if text and text not in _GO_PREDECLARED_TYPES:
|
||||
out.append((text, "generic_arg" if generic else "type"))
|
||||
return
|
||||
if t == "generic_type":
|
||||
type_field = node.child_by_field_name("type")
|
||||
if type_field is not None:
|
||||
sub: list[tuple[str, str]] = []
|
||||
_go_collect_type_refs(type_field, source, generic, sub)
|
||||
out.extend(sub)
|
||||
for c in node.children:
|
||||
if c.type == "type_arguments":
|
||||
for arg in c.children:
|
||||
if arg.is_named:
|
||||
_go_collect_type_refs(arg, source, True, out)
|
||||
return
|
||||
if t in ("pointer_type", "slice_type", "array_type", "map_type",
|
||||
"channel_type", "parenthesized_type"):
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_go_collect_type_refs(c, source, generic, out)
|
||||
return
|
||||
if node.is_named:
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_go_collect_type_refs(c, source, generic, out)
|
||||
|
||||
def extract_go(path: Path) -> dict:
|
||||
"""Extract functions, methods, type declarations, and imports from a .go file."""
|
||||
try:
|
||||
import tree_sitter_go as tsgo
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-go not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsgo.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
# Use directory name as package scope so methods on the same type across
|
||||
# multiple files in a package share one canonical type node.
|
||||
pkg_scope = path.parent.name or stem
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
go_imported_pkgs: set[str] = set() # local names of imported packages
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
"relation": relation,
|
||||
"confidence": confidence,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": weight,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(pkg_scope, name)
|
||||
if nid in seen_ids:
|
||||
return nid
|
||||
nid = _make_id(name)
|
||||
if nid not in seen_ids:
|
||||
# The name isn't declared in this file, so this is a cross-file reference
|
||||
# (e.g. a type defined in another file of the package). Emit a SOURCELESS
|
||||
# stub — like the inheritance-base path in the other extractors — so the
|
||||
# corpus-level rewire can collapse it onto the real definition. A sourced
|
||||
# stub here makes _disambiguate_colliding_node_ids bake the referencing
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
return nid
|
||||
|
||||
def emit_go_method_refs(func_node, func_nid: str, line: int) -> None:
|
||||
params = func_node.child_by_field_name("parameters")
|
||||
if params is not None:
|
||||
for p in params.children:
|
||||
if p.type != "parameter_declaration":
|
||||
continue
|
||||
type_node = p.child_by_field_name("type")
|
||||
refs: list[tuple[str, str]] = []
|
||||
_go_collect_type_refs(type_node, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "parameter_type"
|
||||
tgt = ensure_named_node(ref_name, line)
|
||||
if tgt != func_nid:
|
||||
add_edge(func_nid, tgt, "references", line, context=ctx)
|
||||
result = func_node.child_by_field_name("result")
|
||||
if result is not None:
|
||||
if result.type == "parameter_list":
|
||||
for p in result.children:
|
||||
if p.type != "parameter_declaration":
|
||||
continue
|
||||
type_node = p.child_by_field_name("type")
|
||||
if type_node is None:
|
||||
for c in p.children:
|
||||
if c.is_named:
|
||||
type_node = c
|
||||
break
|
||||
refs = []
|
||||
_go_collect_type_refs(type_node, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "return_type"
|
||||
tgt = ensure_named_node(ref_name, line)
|
||||
if tgt != func_nid:
|
||||
add_edge(func_nid, tgt, "references", line, context=ctx)
|
||||
else:
|
||||
refs = []
|
||||
_go_collect_type_refs(result, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "return_type"
|
||||
tgt = ensure_named_node(ref_name, line)
|
||||
if tgt != func_nid:
|
||||
add_edge(func_nid, tgt, "references", line, context=ctx)
|
||||
|
||||
def walk(node) -> None:
|
||||
t = node.type
|
||||
|
||||
if t == "function_declaration":
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
func_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
func_nid = _make_id(stem, func_name)
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
emit_go_method_refs(node, func_nid, line)
|
||||
body = node.child_by_field_name("body")
|
||||
if body:
|
||||
function_bodies.append((func_nid, body))
|
||||
return
|
||||
|
||||
if t == "method_declaration":
|
||||
receiver = node.child_by_field_name("receiver")
|
||||
receiver_type: str | None = None
|
||||
if receiver:
|
||||
for param in receiver.children:
|
||||
if param.type == "parameter_declaration":
|
||||
type_node = param.child_by_field_name("type")
|
||||
if type_node:
|
||||
receiver_type = _read_text(type_node, source).lstrip("*").strip()
|
||||
break
|
||||
name_node = node.child_by_field_name("name")
|
||||
if not name_node:
|
||||
return
|
||||
method_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
if receiver_type:
|
||||
parent_nid = _make_id(pkg_scope, receiver_type)
|
||||
add_node(parent_nid, receiver_type, line)
|
||||
method_nid = _make_id(parent_nid, method_name)
|
||||
add_node(method_nid, f".{method_name}()", line)
|
||||
add_edge(parent_nid, method_nid, "method", line)
|
||||
else:
|
||||
method_nid = _make_id(stem, method_name)
|
||||
add_node(method_nid, f"{method_name}()", line)
|
||||
add_edge(file_nid, method_nid, "contains", line)
|
||||
|
||||
emit_go_method_refs(node, method_nid, line)
|
||||
body = node.child_by_field_name("body")
|
||||
if body:
|
||||
function_bodies.append((method_nid, body))
|
||||
return
|
||||
|
||||
if t == "type_declaration":
|
||||
for child in node.children:
|
||||
if child.type != "type_spec":
|
||||
continue
|
||||
name_node = child.child_by_field_name("name")
|
||||
if not name_node:
|
||||
continue
|
||||
type_name = _read_text(name_node, source)
|
||||
line = child.start_point[0] + 1
|
||||
type_nid = _make_id(pkg_scope, type_name)
|
||||
add_node(type_nid, type_name, line)
|
||||
add_edge(file_nid, type_nid, "contains", line)
|
||||
# Type body: struct fields (with embeds) or interface embedding.
|
||||
type_body = None
|
||||
for tc in child.children:
|
||||
if tc.type in ("struct_type", "interface_type"):
|
||||
type_body = tc
|
||||
break
|
||||
if type_body is None:
|
||||
continue
|
||||
if type_body.type == "struct_type":
|
||||
for fdl in type_body.children:
|
||||
if fdl.type != "field_declaration_list":
|
||||
continue
|
||||
for field in fdl.children:
|
||||
if field.type != "field_declaration":
|
||||
continue
|
||||
has_name = any(
|
||||
fc.type == "field_identifier" for fc in field.children
|
||||
)
|
||||
type_node = field.child_by_field_name("type")
|
||||
if type_node is None:
|
||||
for fc in field.children:
|
||||
if fc.is_named and fc.type != "field_identifier":
|
||||
type_node = fc
|
||||
break
|
||||
refs: list[tuple[str, str]] = []
|
||||
_go_collect_type_refs(type_node, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
tgt = ensure_named_node(ref_name, field.start_point[0] + 1)
|
||||
if tgt == type_nid:
|
||||
continue
|
||||
if not has_name and role == "type":
|
||||
add_edge(type_nid, tgt, "embeds",
|
||||
field.start_point[0] + 1)
|
||||
else:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "field"
|
||||
add_edge(type_nid, tgt, "references",
|
||||
field.start_point[0] + 1, context=ctx)
|
||||
elif type_body.type == "interface_type":
|
||||
for elem in type_body.children:
|
||||
if elem.type != "type_elem":
|
||||
continue
|
||||
refs = []
|
||||
for sub in elem.children:
|
||||
if sub.is_named:
|
||||
_go_collect_type_refs(sub, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
tgt = ensure_named_node(ref_name, elem.start_point[0] + 1)
|
||||
if tgt == type_nid:
|
||||
continue
|
||||
if role == "type":
|
||||
add_edge(type_nid, tgt, "embeds",
|
||||
elem.start_point[0] + 1)
|
||||
else:
|
||||
add_edge(type_nid, tgt, "references",
|
||||
elem.start_point[0] + 1, context="generic_arg")
|
||||
return
|
||||
|
||||
if t == "import_declaration":
|
||||
for child in node.children:
|
||||
if child.type == "import_spec_list":
|
||||
for spec in child.children:
|
||||
if spec.type == "import_spec":
|
||||
path_node = spec.child_by_field_name("path")
|
||||
if path_node:
|
||||
raw = _read_text(path_node, source).strip('"')
|
||||
# Prefix with go_pkg_ so stdlib names (e.g. "context")
|
||||
# don't collide with local files of the same basename.
|
||||
tgt_nid = _make_id("go", "pkg", raw)
|
||||
add_edge(file_nid, tgt_nid, "imports_from", spec.start_point[0] + 1, context="import")
|
||||
# Track local name (alias or last path segment)
|
||||
alias = spec.child_by_field_name("name")
|
||||
local_name = _read_text(alias, source) if alias else raw.split("/")[-1]
|
||||
if local_name and local_name != "_" and local_name != ".":
|
||||
go_imported_pkgs.add(local_name)
|
||||
elif child.type == "import_spec":
|
||||
path_node = child.child_by_field_name("path")
|
||||
if path_node:
|
||||
raw = _read_text(path_node, source).strip('"')
|
||||
tgt_nid = _make_id("go", "pkg", raw)
|
||||
add_edge(file_nid, tgt_nid, "imports_from", child.start_point[0] + 1, context="import")
|
||||
alias = child.child_by_field_name("name")
|
||||
local_name = _read_text(alias, source) if alias else raw.split("/")[-1]
|
||||
if local_name and local_name != "_" and local_name != ".":
|
||||
go_imported_pkgs.add(local_name)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child)
|
||||
|
||||
walk(root)
|
||||
|
||||
label_to_nid: dict[str, str] = {}
|
||||
for n in nodes:
|
||||
raw = n["label"]
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
if node.type in ("function_declaration", "method_declaration"):
|
||||
return
|
||||
if node.type == "call_expression":
|
||||
func_node = node.child_by_field_name("function")
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type == "selector_expression":
|
||||
field = func_node.child_by_field_name("field")
|
||||
operand = func_node.child_by_field_name("operand")
|
||||
receiver_name = _read_text(operand, source) if operand else ""
|
||||
# Package-qualified call (e.g. fmt.Println) → allow cross-file resolution.
|
||||
# Receiver method call (e.g. s.logger.Log) → skip, no import evidence.
|
||||
is_member_call = receiver_name not in go_imported_pkgs
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
|
||||
tgt_nid = label_to_nid.get(callee_name)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
line = node.start_point[0] + 1
|
||||
edges.append({
|
||||
"source": caller_nid,
|
||||
"target": tgt_nid,
|
||||
"relation": "calls",
|
||||
"context": "call",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
elif callee_name:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for caller_nid, body_node in function_bodies:
|
||||
walk_calls(body_node, caller_nid)
|
||||
|
||||
valid_ids = seen_ids
|
||||
clean_edges = []
|
||||
for edge in edges:
|
||||
src, tgt = edge["source"], edge["target"]
|
||||
if src in valid_ids and (tgt in valid_ids or edge["relation"] in ("imports", "imports_from")):
|
||||
clean_edges.append(edge)
|
||||
|
||||
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
|
||||
@@ -1,209 +0,0 @@
|
||||
"""Json_config extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
_CONFIG_JSON_NAMES = frozenset({
|
||||
"package.json", "tsconfig.json", "jsconfig.json", "composer.json",
|
||||
"deno.json", "deno.jsonc", "bower.json", "manifest.json",
|
||||
"app.json", "now.json", "vercel.json", "angular.json", "nest-cli.json",
|
||||
"biome.json", "biome.jsonc", "renovate.json", ".babelrc", ".babelrc.json",
|
||||
".eslintrc.json", ".prettierrc.json", ".prettierrc", "babel.config.json",
|
||||
})
|
||||
|
||||
_CONFIG_JSON_KEYS = frozenset({
|
||||
"dependencies", "devDependencies", "peerDependencies",
|
||||
"optionalDependencies", "bundleDependencies", "bundledDependencies",
|
||||
"extends", "$ref", "$schema", "compilerOptions",
|
||||
})
|
||||
|
||||
def _is_config_json(path: Path, obj_node, source: bytes) -> bool:
|
||||
"""True if a .json file is a recognized config/manifest worth AST-extracting.
|
||||
|
||||
Matches by filename first (cheap), then falls back to a top-level key probe
|
||||
so arbitrarily-named config files (e.g. ``api.tsconfig.json``,
|
||||
``foo.eslintrc.json``) are still picked up. Returns False for data JSON so it
|
||||
is skipped by the structural pass (#1224)."""
|
||||
name = path.name.casefold()
|
||||
if name in _CONFIG_JSON_NAMES:
|
||||
return True
|
||||
# Common compound config names: *.eslintrc.json, *.prettierrc.json, etc.
|
||||
if name.endswith((".eslintrc.json", ".prettierrc.json", ".babelrc.json",
|
||||
"tsconfig.json", "jsconfig.json")):
|
||||
return True
|
||||
# Top-level key probe: scan the root object's immediate keys (no deep walk).
|
||||
for top_key in obj_node.children:
|
||||
if top_key.type != "pair":
|
||||
continue
|
||||
key_node = top_key.child_by_field_name("key")
|
||||
if key_node is None:
|
||||
continue
|
||||
kc = key_node.child_by_field_name("string_content")
|
||||
text = _read_text(kc, source) if kc else _read_text(key_node, source).strip('"\'')
|
||||
if text in _CONFIG_JSON_KEYS:
|
||||
return True
|
||||
return False
|
||||
|
||||
def extract_json(path: Path) -> dict:
|
||||
"""Extract structure and dependency edges from a *config/manifest* .json file.
|
||||
|
||||
Data-shaped JSON (eval fixtures, datasets, GeoJSON, API response dumps) is
|
||||
deliberately skipped — AST-walking it produced hundreds of orphan key-nodes
|
||||
and duplicate communities that swamped real structure (#1224). Recognition
|
||||
is by filename (package.json, tsconfig.json, …) or a top-level key probe
|
||||
(dependencies / extends / $ref / $schema / compilerOptions)."""
|
||||
_JSON_MAX_BYTES = 1_048_576 # 1 MiB — skip large fixture dumps / GeoJSON blobs
|
||||
|
||||
try:
|
||||
import tree_sitter_json as tsjson
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-json not installed"}
|
||||
|
||||
try:
|
||||
# Bounded read instead of stat()+read() to eliminate TOCTOU (J-1):
|
||||
# read one byte beyond the limit so we can detect oversized files even
|
||||
# if the file grows between stat and read.
|
||||
with path.open("rb") as _f:
|
||||
source = _f.read(_JSON_MAX_BYTES + 1)
|
||||
if len(source) > _JSON_MAX_BYTES:
|
||||
return {"nodes": [], "edges": [], "error": "json file too large to index"}
|
||||
language = Language(tsjson.language())
|
||||
parser = Parser(language)
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
# Keys whose string values become imports (package.json dep blocks)
|
||||
_DEP_KEYS = frozenset({
|
||||
"dependencies", "devDependencies", "peerDependencies",
|
||||
"optionalDependencies", "bundleDependencies", "bundledDependencies",
|
||||
})
|
||||
|
||||
def add_node(nid: str, label: str, line: int, file_type: str = "code") -> None:
|
||||
if nid and nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": file_type,
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
context: str | None = None) -> None:
|
||||
if not src or not tgt or src == tgt:
|
||||
return
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def _key_text(pair_node) -> str | None:
|
||||
"""Extract the string content of a pair's key."""
|
||||
key_node = pair_node.child_by_field_name("key")
|
||||
if key_node is None:
|
||||
return None
|
||||
if key_node.type == "string":
|
||||
content = key_node.child_by_field_name("string_content")
|
||||
if content:
|
||||
return _read_text(content, source)
|
||||
# fallback: strip surrounding quotes
|
||||
raw = _read_text(key_node, source)
|
||||
return raw.strip('"\'')
|
||||
return _read_text(key_node, source)
|
||||
|
||||
def _val_node(pair_node):
|
||||
return pair_node.child_by_field_name("value")
|
||||
|
||||
def walk_object(obj_node, parent_nid: str, parent_key: str | None,
|
||||
depth: int, pair_count: list) -> None:
|
||||
if depth > 6:
|
||||
return
|
||||
for child in obj_node.children:
|
||||
if child.type != "pair":
|
||||
continue
|
||||
if pair_count[0] >= 500: # check per-pair so the cap is honoured exactly (J-3)
|
||||
return
|
||||
pair_count[0] += 1
|
||||
key = _key_text(child)
|
||||
if not key:
|
||||
continue
|
||||
key_nid = _make_id(stem, *(([parent_key] if parent_key else []) + [key]))
|
||||
if not key_nid:
|
||||
continue
|
||||
line = child.start_point[0] + 1
|
||||
add_node(key_nid, key, line)
|
||||
add_edge(parent_nid, key_nid, "contains", line)
|
||||
|
||||
val = _val_node(child)
|
||||
if val is None:
|
||||
continue
|
||||
|
||||
if val.type == "object":
|
||||
walk_object(val, key_nid, key, depth + 1, pair_count)
|
||||
|
||||
elif val.type == "array":
|
||||
# For "extends" arrays (tsconfig, eslint): each string element.
|
||||
# Prefix with "ref_" so external refs don't collide with real
|
||||
# code/file node IDs that share the same collapsed _make_id (J-4).
|
||||
for item in val.children:
|
||||
if item.type == "string":
|
||||
content = item.child_by_field_name("string_content")
|
||||
ref = _read_text(content, source) if content else _read_text(item, source).strip('"\'')
|
||||
if ref:
|
||||
ref_nid = _make_id("ref", ref)
|
||||
if ref_nid:
|
||||
add_node(ref_nid, ref, line, file_type="concept")
|
||||
add_edge(key_nid, ref_nid, "extends", line, context="import")
|
||||
|
||||
elif val.type == "string":
|
||||
content = val.child_by_field_name("string_content")
|
||||
val_text = _read_text(content, source) if content else _read_text(val, source).strip('"\'')
|
||||
|
||||
if key == "extends" and val_text:
|
||||
# Namespace external refs to avoid ID collision with file nodes (J-4)
|
||||
ref_nid = _make_id("ref", val_text)
|
||||
if ref_nid:
|
||||
add_node(ref_nid, val_text, line, file_type="concept")
|
||||
add_edge(file_nid, ref_nid, "extends", line, context="import")
|
||||
|
||||
elif key == "$ref" and val_text:
|
||||
# Namespace $ref values to prevent edge hijacking into code nodes (J-4)
|
||||
ref_nid = _make_id("ref", val_text)
|
||||
if ref_nid:
|
||||
add_edge(parent_nid, ref_nid, "references", line)
|
||||
|
||||
elif parent_key in _DEP_KEYS and val_text:
|
||||
dep_nid = _make_id(key)
|
||||
if dep_nid:
|
||||
add_node(dep_nid, key, line, file_type="concept")
|
||||
add_edge(key_nid, dep_nid, "imports", line, context="import")
|
||||
|
||||
# Entry: find root document → object
|
||||
doc = root
|
||||
if doc.type == "document" and doc.child_count > 0:
|
||||
doc = doc.children[0]
|
||||
if doc.type == "object":
|
||||
# Only AST-extract recognized config/manifest JSON. Data JSON (fixtures,
|
||||
# datasets, GeoJSON, API dumps) is skipped so it doesn't explode into
|
||||
# orphan key-nodes (#1224); it's left to the LLM semantic pass.
|
||||
if not _is_config_json(path, doc, source):
|
||||
return {"nodes": [], "edges": [], "skipped": "data json (not a config/manifest)"}
|
||||
walk_object(doc, file_nid, None, 0, [0])
|
||||
else:
|
||||
# Top-level array or scalar => data JSON, never a config/manifest.
|
||||
return {"nodes": [], "edges": [], "skipped": "data json (non-object root)"}
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,275 +0,0 @@
|
||||
"""julia — moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
from graphify.extractors.engine import _semantic_reference_edge
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def extract_julia(path: Path) -> dict:
|
||||
"""Extract modules, structs, functions, imports, and calls from a .jl file."""
|
||||
try:
|
||||
import tree_sitter_julia as tsjulia
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-julia not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsjulia.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
"relation": relation,
|
||||
"confidence": confidence,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": weight,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
if nid in seen_ids:
|
||||
return nid
|
||||
nid = _make_id(name)
|
||||
if nid not in seen_ids:
|
||||
# The name isn't defined in this file, so this is a cross-file reference
|
||||
# (e.g. a `Thing` type annotation imported from another module). Emit a
|
||||
# SOURCELESS stub — like the inheritance-base path below — so the
|
||||
# corpus-level rewire can collapse it onto the real definition. A sourced
|
||||
# stub here makes _disambiguate_colliding_node_ids bake the referencing
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
return nid
|
||||
|
||||
def _func_name_from_signature(sig_node) -> str | None:
|
||||
"""Extract function name from a Julia signature node (call_expression > identifier)."""
|
||||
for child in sig_node.children:
|
||||
if child.type == "call_expression":
|
||||
callee = child.children[0] if child.children else None
|
||||
if callee and callee.type == "identifier":
|
||||
return _read_text(callee, source)
|
||||
return None
|
||||
|
||||
def walk_calls(body_node, func_nid: str) -> None:
|
||||
if body_node is None:
|
||||
return
|
||||
t = body_node.type
|
||||
if t in ("function_definition", "short_function_definition"):
|
||||
return
|
||||
if t == "call_expression" and body_node.children:
|
||||
callee = body_node.children[0]
|
||||
# Direct call: foo(...)
|
||||
if callee.type == "identifier":
|
||||
callee_name = _read_text(callee, source)
|
||||
target_nid = _make_id(stem, callee_name)
|
||||
add_edge(func_nid, target_nid, "calls", body_node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", context="call")
|
||||
# Method call: obj.method(...)
|
||||
elif callee.type == "field_expression" and len(callee.children) >= 3:
|
||||
method_node = callee.children[-1]
|
||||
method_name = _read_text(method_node, source)
|
||||
target_nid = _make_id(stem, method_name)
|
||||
add_edge(func_nid, target_nid, "calls", body_node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", context="call")
|
||||
for child in body_node.children:
|
||||
walk_calls(child, func_nid)
|
||||
|
||||
def walk(node, scope_nid: str) -> None:
|
||||
t = node.type
|
||||
|
||||
# Module
|
||||
if t == "module_definition":
|
||||
name_node = next((c for c in node.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
mod_name = _read_text(name_node, source)
|
||||
mod_nid = _make_id(stem, mod_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(mod_nid, mod_name, line)
|
||||
add_edge(file_nid, mod_nid, "defines", line)
|
||||
for child in node.children:
|
||||
walk(child, mod_nid)
|
||||
return
|
||||
|
||||
# Struct (struct / mutable struct — both map to struct_definition in tree-sitter-julia)
|
||||
if t == "struct_definition":
|
||||
# type_head may contain: identifier (simple) or binary_expression (Foo <: Bar)
|
||||
type_head = next((c for c in node.children if c.type == "type_head"), None)
|
||||
if not type_head:
|
||||
return
|
||||
struct_name: str | None = None
|
||||
super_name: str | None = None
|
||||
bin_expr = next((c for c in type_head.children if c.type == "binary_expression"), None)
|
||||
if bin_expr:
|
||||
identifiers = [c for c in bin_expr.children if c.type == "identifier"]
|
||||
if identifiers:
|
||||
struct_name = _read_text(identifiers[0], source)
|
||||
if len(identifiers) >= 2:
|
||||
super_name = _read_text(identifiers[-1], source)
|
||||
else:
|
||||
name_node = next((c for c in type_head.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
struct_name = _read_text(name_node, source)
|
||||
if not struct_name:
|
||||
return
|
||||
struct_nid = _make_id(stem, struct_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(struct_nid, struct_name, line)
|
||||
add_edge(scope_nid, struct_nid, "defines", line)
|
||||
if super_name:
|
||||
add_edge(struct_nid, ensure_named_node(super_name, line),
|
||||
"inherits", line, confidence="EXTRACTED")
|
||||
# Field types: each `name::Type` lowers to a typed_expression child of struct_definition
|
||||
for child in node.children:
|
||||
if child.type == "typed_expression":
|
||||
type_ids = [c for c in child.children if c.type == "identifier"]
|
||||
if len(type_ids) >= 2:
|
||||
field_line = child.start_point[0] + 1
|
||||
type_name = _read_text(type_ids[-1], source)
|
||||
type_nid = ensure_named_node(type_name, field_line)
|
||||
edges.append(_semantic_reference_edge(
|
||||
struct_nid, type_nid, "field", str_path, field_line))
|
||||
return
|
||||
|
||||
# Abstract type
|
||||
if t == "abstract_definition":
|
||||
# type_head > identifier
|
||||
type_head = next((c for c in node.children if c.type == "type_head"), None)
|
||||
if type_head:
|
||||
name_node = next((c for c in type_head.children if c.type == "identifier"), None)
|
||||
if name_node:
|
||||
abs_name = _read_text(name_node, source)
|
||||
abs_nid = _make_id(stem, abs_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(abs_nid, abs_name, line)
|
||||
add_edge(scope_nid, abs_nid, "defines", line)
|
||||
return
|
||||
|
||||
# Function: function foo(...) ... end
|
||||
if t == "function_definition":
|
||||
sig_node = next((c for c in node.children if c.type == "signature"), None)
|
||||
if sig_node:
|
||||
func_name = _func_name_from_signature(sig_node)
|
||||
if func_name:
|
||||
func_nid = _make_id(stem, func_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(scope_nid, func_nid, "defines", line)
|
||||
function_bodies.append((func_nid, node))
|
||||
return
|
||||
|
||||
# Short function: foo(x) = expr
|
||||
if t == "assignment":
|
||||
lhs = node.children[0] if node.children else None
|
||||
if lhs and lhs.type == "call_expression" and lhs.children:
|
||||
callee = lhs.children[0]
|
||||
if callee.type == "identifier":
|
||||
func_name = _read_text(callee, source)
|
||||
func_nid = _make_id(stem, func_name)
|
||||
line = node.start_point[0] + 1
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(scope_nid, func_nid, "defines", line)
|
||||
# Only walk the RHS (index 2 after lhs and operator) to avoid self-loops
|
||||
rhs = node.children[-1] if len(node.children) >= 3 else None
|
||||
if rhs:
|
||||
function_bodies.append((func_nid, rhs))
|
||||
return
|
||||
|
||||
# Using / Import
|
||||
if t in ("using_statement", "import_statement"):
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
def _julia_mod_name(n):
|
||||
# identifier (`Foo`), scoped_identifier (`Base.Threads`), or
|
||||
# import_path (relative `..Sibling`) -> the module name. Only bare
|
||||
# identifiers were handled, so qualified/relative imports — and the
|
||||
# scoped package of a `selected_import` — were silently dropped.
|
||||
if n.type == "import_path":
|
||||
ids = [c for c in n.children if c.type == "identifier"]
|
||||
return _read_text(ids[-1], source) if ids else None
|
||||
if n.type in ("identifier", "scoped_identifier"):
|
||||
return _read_text(n, source)
|
||||
return None
|
||||
|
||||
def _emit_import(name):
|
||||
if not name:
|
||||
return
|
||||
imp_nid = _make_id(name)
|
||||
add_node(imp_nid, name, line)
|
||||
add_edge(scope_nid, imp_nid, "imports", line, context="import")
|
||||
|
||||
for child in node.children:
|
||||
if child.type in ("identifier", "scoped_identifier", "import_path"):
|
||||
_emit_import(_julia_mod_name(child))
|
||||
elif child.type == "selected_import":
|
||||
# `import Base.Threads: nthreads` — the package (first named
|
||||
# child) may itself be a scoped_identifier/import_path.
|
||||
pkg = next(
|
||||
(c for c in child.children
|
||||
if c.type in ("identifier", "scoped_identifier", "import_path")),
|
||||
None,
|
||||
)
|
||||
if pkg is not None:
|
||||
_emit_import(_julia_mod_name(pkg))
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, scope_nid)
|
||||
|
||||
walk(root, file_nid)
|
||||
|
||||
for func_nid, body_node in function_bodies:
|
||||
# For function_definition nodes, walk children directly to avoid
|
||||
# the boundary check returning early on the top-level node itself.
|
||||
# Skip the "signature" child — it contains the function's own call_expression
|
||||
# which would create a self-loop.
|
||||
if body_node.type == "function_definition":
|
||||
for child in body_node.children:
|
||||
if child.type != "signature":
|
||||
walk_calls(child, func_nid)
|
||||
else:
|
||||
walk_calls(body_node, func_nid)
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,176 +0,0 @@
|
||||
"""Markdown extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import os
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
|
||||
|
||||
_MD_INLINE_LINK_RE = re.compile(r'(?<!\!)\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+[^)]*)?\)')
|
||||
|
||||
_MD_REF_DEF_RE = re.compile(r'^\s{0,3}\[[^\]]+\]:\s*<?([^\s>]+)>?')
|
||||
|
||||
_MD_WIKILINK_RE = re.compile(r'(?<!\!)\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]')
|
||||
|
||||
_MD_LINKABLE_EXTS = {".md", ".mdx", ".qmd", ".markdown", ".rst", ".txt"}
|
||||
|
||||
def _resolve_markdown_link(raw: str, source_dir: Path) -> "Path | None":
|
||||
"""Resolve a markdown link target to the absolute path of a sibling document.
|
||||
|
||||
Returns the resolved (normalized, not necessarily existing) path when the
|
||||
target is a *local* relative/absolute file-path link to a document, or None
|
||||
when it should be skipped: external URLs (http/https/mailto/protocol-
|
||||
relative/data), pure in-page anchors (``#section``), and links to non-doc
|
||||
file types (code/assets are handled by their own extractors).
|
||||
|
||||
The anchor fragment (``#section``) and query (``?x=1``) are stripped before
|
||||
resolution so ``./repo.md#setup`` resolves to the same node as ``./repo.md``.
|
||||
Extension-less targets (typical of wikilinks) are treated as sibling ``.md``.
|
||||
"""
|
||||
target = raw.strip()
|
||||
if not target:
|
||||
return None
|
||||
# Drop anchor / query so #section links still resolve to the target doc.
|
||||
target = target.split("#", 1)[0].split("?", 1)[0].strip()
|
||||
if not target:
|
||||
return None
|
||||
low = target.lower()
|
||||
if "://" in target or low.startswith(("mailto:", "tel:", "//", "data:")):
|
||||
return None
|
||||
suffix = Path(target).suffix.lower()
|
||||
if suffix == "":
|
||||
target = target + ".md"
|
||||
suffix = ".md"
|
||||
if suffix not in _MD_LINKABLE_EXTS:
|
||||
return None
|
||||
candidate = Path(target)
|
||||
if not candidate.is_absolute():
|
||||
candidate = source_dir / candidate
|
||||
return Path(os.path.normpath(str(candidate)))
|
||||
|
||||
def extract_markdown(path: Path) -> dict:
|
||||
"""Extract structural nodes and edges from a Markdown file.
|
||||
|
||||
Produces nodes for:
|
||||
- The file itself
|
||||
- Each heading (# / ## / ### etc.)
|
||||
|
||||
Produces edges for:
|
||||
- file --contains--> heading
|
||||
- parent heading --contains--> child heading (nesting by level)
|
||||
- heading --references--> other node (when backtick `Name` matches a known pattern)
|
||||
- file --references--> linked document, for inline ``[text](./other.md)``,
|
||||
reference-style ``[label]: ./other.md`` and ``[[wikilink]]`` links, so a
|
||||
hub doc (``index.md`` / ``table-of-contents.md``) becomes a real hub node
|
||||
instead of an under-connected orphan (#1376). The target node ID is built
|
||||
from the resolved target path with the same recipe as the target file's
|
||||
own node, so the edge merges into that node (no ghost node). External
|
||||
URLs, in-page anchors, images and non-document targets are skipped.
|
||||
|
||||
Fenced code blocks (``` ... ```) are skipped during parsing so their
|
||||
contents don't get treated as headings, but no node is emitted for
|
||||
them — they were always orphans (only a single contains edge to the
|
||||
parent doc) and inflated the disconnected-component count (#1077).
|
||||
|
||||
No tree-sitter dependency — pure line-by-line parsing.
|
||||
"""
|
||||
try:
|
||||
source = path.read_text(encoding="utf-8", errors="replace")
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
def add_node(nid: str, label: str, line: int, file_type: str = "document") -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": file_type,
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0) -> None:
|
||||
edges.append({"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight})
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
source_dir = path.parent
|
||||
# Dedup link edges by resolved target node so a hub doc that links to the
|
||||
# same sibling many times yields one edge, not N (keeps weights meaningful).
|
||||
linked_targets: set[str] = set()
|
||||
|
||||
def add_link(raw: str, line: int) -> None:
|
||||
resolved = _resolve_markdown_link(raw, source_dir)
|
||||
if resolved is None:
|
||||
return
|
||||
# Build the target ID with the SAME recipe as the target file's own
|
||||
# node (_make_id(str(path)) at extract time, canonicalized to
|
||||
# _file_node_id(rel) by the extract() post-pass). Using the absolute
|
||||
# resolved path means both endpoints get remapped identically, so the
|
||||
# edge merges into the existing doc node instead of spawning a ghost.
|
||||
tgt_nid = _make_id(str(resolved))
|
||||
if tgt_nid == file_nid or tgt_nid in linked_targets:
|
||||
return
|
||||
linked_targets.add(tgt_nid)
|
||||
add_edge(file_nid, tgt_nid, "references", line)
|
||||
|
||||
# Track heading stack for nesting: [(level, nid), ...]
|
||||
heading_stack: list[tuple[int, str]] = []
|
||||
in_code_block = False
|
||||
|
||||
lines = source.splitlines()
|
||||
for line_num_0, line_text in enumerate(lines):
|
||||
line_num = line_num_0 + 1
|
||||
|
||||
# Skip over fenced code blocks so their contents are not parsed as
|
||||
# headings, but do not emit nodes/edges for them (#1077).
|
||||
stripped = line_text.strip()
|
||||
if stripped.startswith("```"):
|
||||
in_code_block = not in_code_block
|
||||
continue
|
||||
|
||||
if in_code_block:
|
||||
continue
|
||||
|
||||
# Markdown links -> document references (#1376). Scanned on every
|
||||
# non-fenced line (including heading lines, which the heading branch
|
||||
# below `continue`s past) so links anywhere in the doc are captured.
|
||||
for m in _MD_INLINE_LINK_RE.finditer(line_text):
|
||||
add_link(m.group(1), line_num)
|
||||
for m in _MD_WIKILINK_RE.finditer(line_text):
|
||||
add_link(m.group(1), line_num)
|
||||
ref_def = _MD_REF_DEF_RE.match(line_text)
|
||||
if ref_def:
|
||||
add_link(ref_def.group(1), line_num)
|
||||
|
||||
# Detect headings: # Heading, ## Heading, etc.
|
||||
heading_match = re.match(r'^(#{1,6})\s+(.+)', line_text)
|
||||
if heading_match:
|
||||
level = len(heading_match.group(1))
|
||||
title = heading_match.group(2).strip()
|
||||
h_nid = _make_id(stem, title)
|
||||
# Avoid duplicate heading IDs by appending line number
|
||||
if h_nid in seen_ids:
|
||||
h_nid = _make_id(stem, title, str(line_num))
|
||||
add_node(h_nid, title, line_num)
|
||||
|
||||
# Pop headings at same or deeper level
|
||||
while heading_stack and heading_stack[-1][0] >= level:
|
||||
heading_stack.pop()
|
||||
|
||||
# Connect to parent heading or file
|
||||
parent = heading_stack[-1][1] if heading_stack else file_nid
|
||||
add_edge(parent, h_nid, "contains", line_num)
|
||||
|
||||
heading_stack.append((level, h_nid))
|
||||
continue
|
||||
|
||||
return {"nodes": nodes, "edges": edges, "input_tokens": 0, "output_tokens": 0}
|
||||
@@ -1,119 +0,0 @@
|
||||
"""models — moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
_WORKSPACE_PACKAGE_CACHE: dict[str, dict[str, Path]] = {}
|
||||
|
||||
_JS_CACHE_BYPASS_SUFFIXES = {".js", ".jsx", ".mjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte"}
|
||||
|
||||
@dataclass
|
||||
class LanguageConfig:
|
||||
ts_module: str # e.g. "tree_sitter_python"
|
||||
ts_language_fn: str = "language" # attr to call: e.g. tslang.language()
|
||||
|
||||
class_types: frozenset = frozenset()
|
||||
function_types: frozenset = frozenset()
|
||||
import_types: frozenset = frozenset()
|
||||
call_types: frozenset = frozenset()
|
||||
static_prop_types: frozenset = frozenset()
|
||||
helper_fn_names: frozenset = frozenset()
|
||||
container_bind_methods: frozenset = frozenset()
|
||||
event_listener_properties: frozenset = frozenset()
|
||||
|
||||
# Name extraction
|
||||
name_field: str = "name"
|
||||
name_fallback_child_types: tuple = ()
|
||||
|
||||
# Body detection
|
||||
body_field: str = "body"
|
||||
body_fallback_child_types: tuple = () # e.g. ("declaration_list", "compound_statement")
|
||||
|
||||
# Call name extraction
|
||||
call_function_field: str = "function" # field on call node for callee
|
||||
call_accessor_node_types: frozenset = frozenset() # member/attribute nodes
|
||||
call_accessor_field: str = "attribute" # field on accessor for method name
|
||||
call_accessor_object_field: str = "" # field on accessor for the receiver/object
|
||||
|
||||
# Stop recursion at these types in walk_calls
|
||||
function_boundary_types: frozenset = frozenset()
|
||||
|
||||
# Import handler: called for import nodes instead of generic handling
|
||||
import_handler: Callable | None = None
|
||||
|
||||
# Optional custom name resolver for functions (C, C++ declarator unwrapping)
|
||||
resolve_function_name_fn: Callable | None = None
|
||||
|
||||
# Extra label formatting for functions: if True, functions get "name()" label
|
||||
function_label_parens: bool = True
|
||||
|
||||
# Extra walk hook called after generic dispatch (for JS arrow functions, C# namespaces, etc.)
|
||||
extra_walk_fn: Callable | None = None
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SymbolDeclarationFact:
|
||||
file_path: Path
|
||||
name: str
|
||||
line: int
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SymbolImportFact:
|
||||
file_path: Path
|
||||
local_name: str
|
||||
target_path: Path
|
||||
imported_name: str
|
||||
line: int
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SymbolAliasFact:
|
||||
file_path: Path
|
||||
alias: str
|
||||
target_name: str
|
||||
line: int
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SymbolExportFact:
|
||||
file_path: Path
|
||||
exported_name: str
|
||||
line: int
|
||||
local_name: str | None = None
|
||||
target_path: Path | None = None
|
||||
target_name: str | None = None
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _StarExportFact:
|
||||
file_path: Path
|
||||
target_path: Path
|
||||
line: int
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _NamespaceExportFact:
|
||||
file_path: Path
|
||||
exported_name: str
|
||||
target_path: Path
|
||||
line: int
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _SymbolUseFact:
|
||||
file_path: Path
|
||||
source_id: str
|
||||
local_name: str
|
||||
relation: str
|
||||
context: str
|
||||
line: int
|
||||
|
||||
@dataclass
|
||||
class _SymbolResolutionFacts:
|
||||
declarations: list[_SymbolDeclarationFact] = field(default_factory=list)
|
||||
imports: list[_SymbolImportFact] = field(default_factory=list)
|
||||
aliases: list[_SymbolAliasFact] = field(default_factory=list)
|
||||
exports: list[_SymbolExportFact] = field(default_factory=list)
|
||||
star_exports: list[_StarExportFact] = field(default_factory=list)
|
||||
namespace_exports: list[_NamespaceExportFact] = field(default_factory=list)
|
||||
uses: list[_SymbolUseFact] = field(default_factory=list)
|
||||
# File-to-file submodule imports from `from pkg import submod` (#1146).
|
||||
# Each entry is (importing_file, submodule_file, line).
|
||||
module_imports: list[tuple[Path, Path, int]] = field(default_factory=list)
|
||||
@@ -1,430 +0,0 @@
|
||||
"""objc — moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
from graphify.extractors.engine import _cpp_declarator_name, _semantic_reference_edge
|
||||
from graphify.extractors.resolution import _resolve_c_include_path
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _objc_local_var_types(body_node, source: bytes, table: dict[str, str]) -> None:
|
||||
"""Collect ``var -> ClassName`` from ObjC local declarations (``Foo *f = ...;``)
|
||||
in a method body, for receiver typing in the cross-file message-send pass
|
||||
(#1556). Only a capitalized ``type_identifier`` with a single named declarator
|
||||
is recorded; a built-in/lower-cased type or an un-nameable declarator is skipped
|
||||
(precision over recall). Reuses the C++ declarator unwrapper (identical grammar).
|
||||
"""
|
||||
stack = [body_node]
|
||||
while stack:
|
||||
n = stack.pop()
|
||||
if n.type == "method_definition" and n is not body_node:
|
||||
continue
|
||||
if n.type == "declaration":
|
||||
type_node = n.child_by_field_name("type")
|
||||
if type_node is None:
|
||||
for c in n.children:
|
||||
if c.type == "type_identifier":
|
||||
type_node = c
|
||||
break
|
||||
if type_node is not None and type_node.type == "type_identifier":
|
||||
type_name = _read_text(type_node, source).strip()
|
||||
declarators = [
|
||||
c for c in n.children
|
||||
if c.type in ("identifier", "pointer_declarator", "init_declarator")
|
||||
]
|
||||
if type_name and type_name[:1].isupper() and len(declarators) == 1:
|
||||
var = _cpp_declarator_name(declarators[0], source)
|
||||
if var and var not in table:
|
||||
table[var] = type_name
|
||||
for c in n.children:
|
||||
stack.append(c)
|
||||
|
||||
def extract_objc(path: Path) -> dict:
|
||||
"""Extract interfaces, implementations, protocols, methods, and imports from .m/.mm/.h files."""
|
||||
try:
|
||||
import tree_sitter_objc as tsobjc
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_objc not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsobjc.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
# tree-sitter-objc cannot expand these argument-less annotation macros (no
|
||||
# trailing ';'), and their presence before @interface makes the parser fail to
|
||||
# emit a class_interface node (#1475). Blank them to equal-length spaces so byte
|
||||
# offsets / line numbers are preserved and the interface parses.
|
||||
_OBJC_BLANK_MACROS = (b"NS_ASSUME_NONNULL_BEGIN", b"NS_ASSUME_NONNULL_END")
|
||||
for _m in _OBJC_BLANK_MACROS:
|
||||
source = source.replace(_m, b" " * len(_m))
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
method_bodies: list[tuple[str, Any, str]] = []
|
||||
# #1556: unresolved message sends saved for the cross-file ObjC resolver, plus a
|
||||
# per-file `var -> ClassName` table from `Foo *f = ...;` local declarations.
|
||||
raw_calls: list[dict] = []
|
||||
objc_type_table: dict[str, str] = {}
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def _read(node) -> str:
|
||||
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
|
||||
|
||||
def _get_name(node, field: str) -> str | None:
|
||||
n = node.child_by_field_name(field)
|
||||
return _read(n) if n else None
|
||||
|
||||
def _type_identifiers(node):
|
||||
"""Yield every type_identifier under a property's type node, descending
|
||||
through generic_specifier/type_name so NSArray<Product *> yields both
|
||||
NSArray and the element type Product (the generic case was invisible
|
||||
because the type was wrapped in a generic_specifier, not a bare
|
||||
type_identifier child) (#1475)."""
|
||||
if node.type == "type_identifier":
|
||||
yield node
|
||||
return
|
||||
for c in node.children:
|
||||
yield from _type_identifiers(c)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
if nid in seen_ids:
|
||||
return nid
|
||||
nid = _make_id(name)
|
||||
if nid not in seen_ids:
|
||||
# The name isn't defined in this file, so this is a cross-file reference
|
||||
# (e.g. a `Thing` type annotation imported from another module). Emit a
|
||||
# SOURCELESS stub — like the inheritance-base path below — so the
|
||||
# corpus-level rewire can collapse it onto the real definition. A sourced
|
||||
# stub here makes _disambiguate_colliding_node_ids bake the referencing
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
return nid
|
||||
|
||||
def walk(node, parent_nid: str | None = None) -> None:
|
||||
t = node.type
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
if t == "preproc_include":
|
||||
# #import <Foundation/Foundation.h> or #import "MyClass.h"
|
||||
for child in node.children:
|
||||
if child.type == "system_lib_string":
|
||||
raw = _read(child).strip("<>")
|
||||
module = raw.split("/")[-1].replace(".h", "")
|
||||
if module:
|
||||
tgt_nid = _make_id(module)
|
||||
add_edge(file_nid, tgt_nid, "imports", line, context="import")
|
||||
elif child.type == "string_literal":
|
||||
# recurse into string_literal to find string_content
|
||||
for sub in child.children:
|
||||
if sub.type == "string_content":
|
||||
raw = _read(sub)
|
||||
# Resolve the quoted include to a real file so the target id
|
||||
# matches the (possibly disambiguated) node id _make_id gives
|
||||
# that file; the bare-stem id never survives
|
||||
# _disambiguate_colliding_node_ids when a .h/.m pair exists,
|
||||
# so the edge dangled and was dropped (#1475).
|
||||
resolved = _resolve_c_include_path(raw, str_path)
|
||||
if resolved is not None:
|
||||
add_edge(file_nid, _make_id(str(resolved)), "imports", line, context="import")
|
||||
else:
|
||||
module = raw.split("/")[-1].replace(".h", "")
|
||||
if module:
|
||||
add_edge(file_nid, _make_id(module), "imports", line, context="import")
|
||||
return
|
||||
|
||||
if t == "module_import":
|
||||
# @import Foundation; / @import Foundation.NSString;
|
||||
path_node = node.child_by_field_name("path")
|
||||
if path_node is not None:
|
||||
module = _read(path_node).split(".")[0].strip()
|
||||
if module:
|
||||
add_edge(file_nid, _make_id(module), "imports", line, context="import")
|
||||
return
|
||||
|
||||
if t == "class_interface":
|
||||
# @interface ClassName : SuperClass <Protocols>
|
||||
# children: @interface, identifier(name), ':', identifier(super), parameterized_arguments, ...
|
||||
identifiers = [c for c in node.children if c.type == "identifier"]
|
||||
if not identifiers:
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
return
|
||||
name = _read(identifiers[0])
|
||||
cls_nid = _make_id(stem, name)
|
||||
add_node(cls_nid, name, line)
|
||||
add_edge(file_nid, cls_nid, "contains", line)
|
||||
# superclass is second identifier after ':'
|
||||
colon_seen = False
|
||||
for child in node.children:
|
||||
if child.type == ":":
|
||||
colon_seen = True
|
||||
elif colon_seen and child.type == "identifier":
|
||||
super_nid = ensure_named_node(_read(child), line)
|
||||
add_edge(cls_nid, super_nid, "inherits", line)
|
||||
colon_seen = False
|
||||
elif child.type == "parameterized_arguments":
|
||||
# protocols adopted: @interface Foo : Bar <Proto1, Proto2>
|
||||
for sub in child.children:
|
||||
if sub.type == "type_name":
|
||||
for s in sub.children:
|
||||
if s.type == "type_identifier":
|
||||
proto_nid = ensure_named_node(_read(s), line)
|
||||
add_edge(cls_nid, proto_nid, "implements", line)
|
||||
elif child.type == "property_declaration":
|
||||
prop_line = child.start_point[0] + 1
|
||||
for sub in child.children:
|
||||
if sub.type == "struct_declaration":
|
||||
# The type is either a direct type_identifier
|
||||
# (NSString *x) or wrapped in a generic_specifier
|
||||
# (NSArray<Product *> *xs). Walk every type name in the
|
||||
# type portion, skipping the declarator (the *field
|
||||
# name), so generic collections are no longer invisible.
|
||||
seen_types: set[str] = set()
|
||||
for s in sub.children:
|
||||
if s.type in ("struct_declarator", ";"):
|
||||
continue
|
||||
for ti in _type_identifiers(s):
|
||||
tname = _read(ti)
|
||||
if tname in seen_types:
|
||||
continue
|
||||
seen_types.add(tname)
|
||||
type_nid = ensure_named_node(tname, prop_line)
|
||||
edges.append(_semantic_reference_edge(
|
||||
cls_nid, type_nid, "field", str_path, prop_line))
|
||||
elif child.type == "method_declaration":
|
||||
walk(child, cls_nid)
|
||||
return
|
||||
|
||||
if t == "class_implementation":
|
||||
# @implementation ClassName
|
||||
name = None
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
name = _read(child)
|
||||
break
|
||||
if not name:
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
return
|
||||
impl_nid = _make_id(stem, name)
|
||||
if impl_nid not in seen_ids:
|
||||
add_node(impl_nid, name, line)
|
||||
add_edge(file_nid, impl_nid, "contains", line)
|
||||
for child in node.children:
|
||||
if child.type == "implementation_definition":
|
||||
for sub in child.children:
|
||||
walk(sub, impl_nid)
|
||||
return
|
||||
|
||||
if t == "protocol_declaration":
|
||||
name = None
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
name = _read(child)
|
||||
break
|
||||
if name:
|
||||
proto_nid = _make_id(stem, name)
|
||||
add_node(proto_nid, f"<{name}>", line)
|
||||
add_edge(file_nid, proto_nid, "contains", line)
|
||||
# Adopted protocols: `@protocol Derived <Base, Other>`. These
|
||||
# nest under a protocol_reference_list node (distinct from the
|
||||
# parameterized_arguments node used by @interface adoption), so
|
||||
# they were never emitted. Emit an `implements` edge for each,
|
||||
# matching how @interface protocol adoption is handled.
|
||||
for child in node.children:
|
||||
if child.type == "protocol_reference_list":
|
||||
for sub in child.children:
|
||||
if sub.type == "identifier":
|
||||
base_nid = ensure_named_node(_read(sub), line)
|
||||
if base_nid != proto_nid:
|
||||
add_edge(proto_nid, base_nid, "implements", line)
|
||||
for child in node.children:
|
||||
walk(child, proto_nid)
|
||||
return
|
||||
|
||||
if t in ("method_declaration", "method_definition"):
|
||||
container = parent_nid or file_nid
|
||||
# Class methods start with '+', instance methods with '-' (the grammar
|
||||
# emits the sigil as the first child). The selector is the concatenation
|
||||
# of the direct identifier children: one for a simple selector (-go),
|
||||
# several for a compound one (-tableView:numberOfRowsInSection: ->
|
||||
# "tableViewnumberOfRowsInSection"); method_parameter holds the arg
|
||||
# types/names, not selector keywords, so it is correctly skipped.
|
||||
prefix = "-"
|
||||
for child in node.children:
|
||||
if child.type in ("+", "-"):
|
||||
prefix = child.type
|
||||
break
|
||||
parts = [_read(c) for c in node.children if c.type == "identifier"]
|
||||
method_name = "".join(parts) if parts else None
|
||||
if method_name:
|
||||
method_nid = _make_id(container, method_name)
|
||||
add_node(method_nid, f"{prefix}{method_name}", line)
|
||||
add_edge(container, method_nid, "method", line)
|
||||
if t == "method_definition":
|
||||
method_bodies.append((method_nid, node, container))
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
|
||||
walk(root)
|
||||
|
||||
# Second pass: resolve calls inside method bodies
|
||||
all_method_nids = {n["id"] for n in nodes if n["id"] != file_nid}
|
||||
class_method_nids: dict[str, set[str]] = {}
|
||||
for m_nid, _, container_nid in method_bodies:
|
||||
class_method_nids.setdefault(container_nid, set()).add(m_nid)
|
||||
seen_calls: set[tuple[str, str]] = set()
|
||||
# #1556: per-file `var -> ClassName` table from local declarations in every
|
||||
# method body, so the cross-file resolver can type a `[f doThing]` receiver.
|
||||
for _m_nid, body_node, _container in method_bodies:
|
||||
_objc_local_var_types(body_node, source, objc_type_table)
|
||||
|
||||
for caller_nid, body_node, container_nid in method_bodies:
|
||||
sibling_nids = class_method_nids.get(container_nid, set())
|
||||
|
||||
def walk_calls(n) -> None:
|
||||
if n.type == "message_expression":
|
||||
# `[[Foo alloc] init]` is a message_expression whose method is the
|
||||
# identifier `alloc` and whose receiver is the bare class identifier
|
||||
# `Foo`; resolve that class name and emit a `references` edge so the
|
||||
# allocating method links to the allocated type. ensure_named_node
|
||||
# emits a sourceless stub for unknown names, which the corpus rewire
|
||||
# collapses ONLY when exactly one real class of that name exists, so an
|
||||
# unknown/ambiguous class produces no false resolved edge (#1475).
|
||||
meth = n.child_by_field_name("method")
|
||||
recv = n.child_by_field_name("receiver")
|
||||
if (meth is not None and meth.type == "identifier" and _read(meth) == "alloc"
|
||||
and recv is not None and recv.type == "identifier"):
|
||||
tname = _read(recv)
|
||||
ref_line = n.start_point[0] + 1
|
||||
type_nid = ensure_named_node(tname, ref_line)
|
||||
if type_nid != caller_nid:
|
||||
edges.append(_semantic_reference_edge(
|
||||
caller_nid, type_nid, "type", str_path, ref_line))
|
||||
# [receiver sel] and [receiver kw1:a kw2:b] both parse to a
|
||||
# message_expression whose selector parts carry the field name
|
||||
# "method" (one for a simple selector, several for a compound one);
|
||||
# the receiver carries field name "receiver". Reconstruct the
|
||||
# selector from every "method" child so self/super/ClassName
|
||||
# receivers are never mistaken for a selector, and compound sends
|
||||
# resolve too (the whole second pass was previously dead code for
|
||||
# ObjC because the grammar emits these as `identifier`, not
|
||||
# `selector`/`keyword_argument_list`) (#1475).
|
||||
sel_parts = [
|
||||
_read(child)
|
||||
for i, child in enumerate(n.children)
|
||||
if n.field_name_for_child(i) == "method" and child.type == "identifier"
|
||||
]
|
||||
method_name = "".join(sel_parts)
|
||||
if method_name:
|
||||
needle = _make_id("", method_name).lstrip("_")
|
||||
for candidate in all_method_nids:
|
||||
if candidate.endswith(needle):
|
||||
pair = (caller_nid, candidate)
|
||||
if pair not in seen_calls and caller_nid != candidate:
|
||||
seen_calls.add(pair)
|
||||
add_edge(caller_nid, candidate, "calls", n.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0, context="call")
|
||||
# #1556: also emit a raw_call so the cross-file resolver can type
|
||||
# the receiver and link to a method in ANOTHER file. A bare
|
||||
# identifier receiver (`f`, `self`, `Foo`) is captured; a nested
|
||||
# message send (`[[Foo alloc] init]`) has no simple receiver name
|
||||
# to type, so it is left to the alloc/init `references` edge above.
|
||||
if recv is not None and recv.type == "identifier":
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": method_name,
|
||||
"is_member_call": True,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{n.start_point[0] + 1}",
|
||||
"receiver": _read(recv),
|
||||
"lang": "objc",
|
||||
})
|
||||
elif n.type == "field_expression":
|
||||
# self.name / self.product.name — dot-syntax sugar for [self name].
|
||||
# Resolve to a sibling method of the SAME class, matched by EXACT
|
||||
# node id (a method id is _make_id(container, name)). A suffix
|
||||
# substring match would mis-resolve self.name -> -surname and would
|
||||
# let a substring-colliding sibling (-surname) suppress the real
|
||||
# -name edge, so it must be an exact match (#1475).
|
||||
for child in n.children:
|
||||
if child.type == "field_identifier":
|
||||
field_name = _read(child)
|
||||
target = _make_id(container_nid, field_name)
|
||||
if target in sibling_nids and target != caller_nid:
|
||||
pair = (caller_nid, target)
|
||||
if pair not in seen_calls:
|
||||
seen_calls.add(pair)
|
||||
add_edge(caller_nid, target, "accesses",
|
||||
n.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0)
|
||||
elif n.type == "selector_expression":
|
||||
# @selector(doSomething:withParam:) — compile-time method ref.
|
||||
# Match the selector name EXACTLY (a method id is
|
||||
# _make_id(container, name)) against every class's methods, and emit
|
||||
# only when exactly one method matches, to avoid ambiguous fan-out.
|
||||
# Exact match (not a suffix) keeps -doThing distinct from
|
||||
# -reallyDoThing (#1475).
|
||||
sel_parts = [_read(c) for c in n.children if c.type == "identifier"]
|
||||
sel_name = "".join(sel_parts)
|
||||
if sel_name:
|
||||
matches = sorted({
|
||||
m for m, _, cont in method_bodies
|
||||
if m == _make_id(cont, sel_name) and m != caller_nid
|
||||
})
|
||||
if len(matches) == 1:
|
||||
pair = (caller_nid, matches[0])
|
||||
if pair not in seen_calls:
|
||||
seen_calls.add(pair)
|
||||
add_edge(caller_nid, matches[0], "calls",
|
||||
n.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0,
|
||||
context="call")
|
||||
for child in n.children:
|
||||
walk_calls(child)
|
||||
walk_calls(body_node)
|
||||
|
||||
result = {"nodes": nodes, "edges": edges, "raw_calls": raw_calls,
|
||||
"input_tokens": 0, "output_tokens": 0}
|
||||
if objc_type_table:
|
||||
result["objc_type_table"] = {"path": str_path, "table": objc_type_table}
|
||||
return result
|
||||
@@ -1,688 +0,0 @@
|
||||
"""pascal — moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
from graphify.extractors.resolution import _pascal_resolve_class, _pascal_resolve_unit
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
_PAS_TOKEN_RE = re.compile(
|
||||
r"'(?:''|[^'])*'"
|
||||
r"|\{[^}]*\}"
|
||||
r"|\(\*.*?\*\)"
|
||||
r"|//[^\n]*",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
_PAS_MODULE_RE = re.compile(
|
||||
r"\b(unit|program|library)\s+([A-Za-z_][\w.]*)\s*;",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_PAS_USES_RE = re.compile(
|
||||
r"\buses\b\s*([^;]+);",
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
|
||||
_PAS_TYPE_HEADER_RE = re.compile(
|
||||
r"\b(?P<name>[A-Za-z_]\w*)(?:\s*<[^>]+>)?\s*=\s*(?:packed\s+)?"
|
||||
r"(?P<kind>class|interface)\b"
|
||||
r"(?:\s*\(\s*(?P<bases>[^)]*)\s*\))?",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_PAS_END_SEMI_RE = re.compile(r"\bend\s*;", re.IGNORECASE)
|
||||
|
||||
_PAS_METHOD_DECL_RE = re.compile(
|
||||
r"\b(?:procedure|function|constructor|destructor)\s+"
|
||||
r"(?P<name>[A-Za-z_]\w*)"
|
||||
r"(?:\s*\([^)]*\))?"
|
||||
r"(?:\s*:\s*[\w<>,\s.]+)?"
|
||||
r"\s*;",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_PAS_IMPL_HEADER_RE = re.compile(
|
||||
r"\b(?:procedure|function|constructor|destructor)\s+"
|
||||
r"(?P<qual>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)"
|
||||
r"(?:\s*<[^>]+>)?"
|
||||
r"(?:\s*\([^)]*\))?"
|
||||
r"(?:\s*:\s*[\w<>,\s.]+)?"
|
||||
r"\s*;",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_PAS_BEGIN_END_TOKEN_RE = re.compile(
|
||||
r"\b(begin|end|case|try|asm|record)\b", re.IGNORECASE
|
||||
)
|
||||
|
||||
_PAS_CALL_RE = re.compile(r"\b([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*[(;]")
|
||||
|
||||
_PAS_KEYWORDS = frozenset({
|
||||
"begin", "end", "if", "then", "else", "while", "do", "for", "to",
|
||||
"downto", "repeat", "until", "case", "of", "try", "finally", "except",
|
||||
"with", "inherited", "result", "var", "const", "type", "nil", "true",
|
||||
"false", "exit", "break", "continue", "uses", "unit", "program",
|
||||
"library", "interface", "implementation", "initialization", "finalization",
|
||||
"procedure", "function", "constructor", "destructor", "class", "record",
|
||||
"object", "array", "string", "integer", "boolean", "real", "char",
|
||||
"writeln", "write", "readln", "read", "assigned", "length", "high",
|
||||
"low", "inc", "dec", "new", "dispose", "setlength", "copy", "pos",
|
||||
"trim", "format", "inttostr", "strtoint", "ord", "chr", "sizeof",
|
||||
"create", "free", "destroy",
|
||||
})
|
||||
|
||||
def _pascal_strip_comments(text: str) -> str:
|
||||
"""Strip Pascal comments ({}, (* *), //) while preserving newlines."""
|
||||
def _sub(m: re.Match) -> str:
|
||||
tok = m.group(0)
|
||||
if tok.startswith("'"):
|
||||
return tok
|
||||
return "".join(c if c == "\n" else " " for c in tok)
|
||||
return _PAS_TOKEN_RE.sub(_sub, text)
|
||||
|
||||
def _pascal_split_sections(text: str) -> tuple[str, int, str, int]:
|
||||
"""Split into (iface_text, iface_offset, impl_text, impl_offset).
|
||||
Files without interface/implementation sections (dpr/lpr/inc) return
|
||||
the whole text as impl with offset 0.
|
||||
"""
|
||||
iface_m = re.search(r"\binterface\b", text, re.IGNORECASE)
|
||||
impl_m = re.search(r"\bimplementation\b", text, re.IGNORECASE)
|
||||
if iface_m and impl_m:
|
||||
iface_off = iface_m.end()
|
||||
impl_off = impl_m.end()
|
||||
end_m = re.search(
|
||||
r"\b(initialization|finalization)\b", text[impl_off:], re.IGNORECASE
|
||||
)
|
||||
impl_end = impl_off + end_m.start() if end_m else len(text)
|
||||
return text[iface_off:impl_m.start()], iface_off, text[impl_off:impl_end], impl_off
|
||||
return "", 0, text, 0
|
||||
|
||||
def _pascal_split_uses(s: str) -> list[str]:
|
||||
"""Split a uses list string, handling 'Foo in ''bar.pas''' syntax."""
|
||||
out = []
|
||||
for chunk in s.split(","):
|
||||
name = re.split(r"\s+in\s+", chunk.strip(), maxsplit=1, flags=re.IGNORECASE)[0]
|
||||
name = name.strip().strip(";")
|
||||
if name and re.match(r"[A-Za-z_][\w.]*$", name):
|
||||
out.append(name)
|
||||
return out
|
||||
|
||||
def _pascal_split_bases(s: str) -> list[str]:
|
||||
"""Split inheritance list, handling generics like TList<T, U>."""
|
||||
out, depth, buf = [], 0, []
|
||||
for ch in s:
|
||||
if ch == "<":
|
||||
depth += 1
|
||||
buf.append(ch)
|
||||
elif ch == ">":
|
||||
depth -= 1
|
||||
buf.append(ch)
|
||||
elif ch == "," and depth == 0:
|
||||
name = re.sub(r"<.*$", "", "".join(buf).strip())
|
||||
if name:
|
||||
out.append(name)
|
||||
buf = []
|
||||
else:
|
||||
buf.append(ch)
|
||||
name = re.sub(r"<.*$", "", "".join(buf).strip())
|
||||
if name:
|
||||
out.append(name)
|
||||
return [n for n in out if re.match(r"[A-Za-z_]\w*$", n)]
|
||||
|
||||
def _pascal_find_body(text: str, start: int) -> tuple[int, int]:
|
||||
"""Find balanced begin..end after start. Returns (body_start, body_end).
|
||||
Returns (0, 0) if no begin found.
|
||||
"""
|
||||
m = re.search(r"\bbegin\b", text[start:], re.IGNORECASE)
|
||||
if not m:
|
||||
return (0, 0)
|
||||
body_start = start + m.end()
|
||||
depth = 1
|
||||
for tok in _PAS_BEGIN_END_TOKEN_RE.finditer(text, body_start):
|
||||
kw = tok.group(1).lower()
|
||||
if kw in ("begin", "case", "try", "asm", "record"):
|
||||
depth += 1
|
||||
elif kw == "end":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return (body_start, tok.start())
|
||||
return (body_start, len(text))
|
||||
|
||||
def _resolve_pascal_callee_factory(
|
||||
records: list[tuple],
|
||||
edges: list[dict],
|
||||
module_nid: str,
|
||||
) -> Callable[[str, str], str | None]:
|
||||
"""Build a scoped call resolver for a single Pascal/Delphi file.
|
||||
|
||||
``records`` is the list of raw per-procedure tuples produced by either
|
||||
Pascal extractor; only the trailing ``(..., container, name_lower)``
|
||||
fields and the leading ``proc_nid`` are used, so both extractors' tuple
|
||||
shapes work unmodified (regex: proc_nid, line, body_text, container,
|
||||
name_lower; tree-sitter: proc_nid, body_node, container, name_lower).
|
||||
|
||||
Resolution order for a call to ``name_lower`` from ``caller_nid``:
|
||||
1. A method declared on the caller's own class.
|
||||
2. A method declared on an ancestor class (BFS up ``inherits`` edges,
|
||||
which are already resolved by this point).
|
||||
3. A file-level free function (declared directly under the module).
|
||||
4. A global by-name match, but only when unambiguous (exactly one
|
||||
procedure with that name anywhere in the file).
|
||||
|
||||
Returns None (no edge emitted) when the name is ambiguous at every
|
||||
level -- guessing at a same-named method on an unrelated class is worse
|
||||
than omitting the edge. Same-named methods on unrelated classes are a
|
||||
common Pascal/Delphi pattern (property accessors, generated wrapper
|
||||
classes such as TLB import units): without this scoping, a flat
|
||||
file-wide by-name lookup silently collapses onto whichever declaration
|
||||
happens to be inserted last, producing wrong cross-class edges. Mirrors
|
||||
the "god-node guard" already used by ``resolve_ruby_member_calls`` for
|
||||
the analogous Ruby ambiguous-method-name problem.
|
||||
"""
|
||||
class_bases: dict[str, list[str]] = {}
|
||||
for e in edges:
|
||||
if e.get("relation") == "inherits":
|
||||
class_bases.setdefault(e["source"], []).append(e["target"])
|
||||
|
||||
class_procs: dict[str, dict[str, list[str]]] = {}
|
||||
module_procs: dict[str, list[str]] = {}
|
||||
global_procs: dict[str, list[str]] = {}
|
||||
proc_owner: dict[str, str] = {}
|
||||
for rec in records:
|
||||
proc_nid, container, name_lower = rec[0], rec[-2], rec[-1]
|
||||
proc_owner[proc_nid] = container
|
||||
global_procs.setdefault(name_lower, []).append(proc_nid)
|
||||
if container == module_nid:
|
||||
module_procs.setdefault(name_lower, []).append(proc_nid)
|
||||
else:
|
||||
class_procs.setdefault(container, {}).setdefault(name_lower, []).append(proc_nid)
|
||||
|
||||
def _resolve(caller_nid: str, name_lower: str) -> str | None:
|
||||
owner = proc_owner.get(caller_nid)
|
||||
if owner is not None:
|
||||
candidates = class_procs.get(owner, {}).get(name_lower)
|
||||
if candidates:
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
seen_bases: set[str] = set()
|
||||
queue = list(class_bases.get(owner, []))
|
||||
while queue:
|
||||
base = queue.pop(0)
|
||||
if base in seen_bases:
|
||||
continue
|
||||
seen_bases.add(base)
|
||||
candidates = class_procs.get(base, {}).get(name_lower)
|
||||
if candidates:
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
queue.extend(class_bases.get(base, []))
|
||||
candidates = module_procs.get(name_lower)
|
||||
if candidates:
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
candidates = global_procs.get(name_lower)
|
||||
if candidates and len(candidates) == 1:
|
||||
return candidates[0]
|
||||
return None
|
||||
|
||||
return _resolve
|
||||
|
||||
|
||||
def _extract_pascal_regex(path: Path) -> dict:
|
||||
"""Regex fallback for Pascal/Delphi extraction when tree-sitter-pascal
|
||||
is unavailable. Produces the same node/edge schema as the tree-sitter pass.
|
||||
"""
|
||||
try:
|
||||
raw = path.read_text(encoding="utf-8", errors="replace")
|
||||
except Exception as exc:
|
||||
return {"nodes": [], "edges": [], "error": str(exc)}
|
||||
|
||||
str_path = str(path)
|
||||
stem = _file_stem(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
seen_edges: set[tuple[str, str, str]] = set()
|
||||
|
||||
def _add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def _add_edge(src: str, tgt: str, relation: str, line: int, context: str | None = None) -> None:
|
||||
# A class method declared in the interface section and defined in the
|
||||
# implementation section both emit a `method` edge to the same node, so
|
||||
# dedup on (src, tgt, relation) to keep the graph from carrying doubled
|
||||
# method/contains/inherits edges (mirrors _add_node's seen_ids guard).
|
||||
key = (src, tgt, relation)
|
||||
if key in seen_edges:
|
||||
return
|
||||
seen_edges.add(key)
|
||||
edge: dict = {
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
"relation": relation,
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
def _lineno(text: str, offset: int) -> int:
|
||||
return text.count("\n", 0, offset) + 1
|
||||
|
||||
file_nid = _make_id(str_path)
|
||||
_add_node(file_nid, path.name, 1)
|
||||
|
||||
stripped = _pascal_strip_comments(raw)
|
||||
|
||||
# Module header
|
||||
module_nid = file_nid
|
||||
mod_m = _PAS_MODULE_RE.search(stripped)
|
||||
if mod_m:
|
||||
mod_name = mod_m.group(2)
|
||||
module_nid = _make_id(stem, mod_name)
|
||||
_add_node(module_nid, mod_name, _lineno(stripped, mod_m.start()))
|
||||
_add_edge(file_nid, module_nid, "contains", _lineno(stripped, mod_m.start()))
|
||||
|
||||
iface_text, iface_off, impl_text, impl_off = _pascal_split_sections(stripped)
|
||||
|
||||
# Uses clauses
|
||||
for section_text, section_off in ((iface_text, iface_off), (impl_text, impl_off)):
|
||||
for um in _PAS_USES_RE.finditer(section_text):
|
||||
line = _lineno(stripped, section_off + um.start())
|
||||
for unit_name in _pascal_split_uses(um.group(1)):
|
||||
tgt_nid = _pascal_resolve_unit(path, unit_name)
|
||||
_add_edge(module_nid, tgt_nid, "imports", line, context="import")
|
||||
|
||||
# Type declarations (classes / interfaces) in interface section
|
||||
search_text = iface_text if iface_text else stripped
|
||||
search_off = iface_off if iface_text else 0
|
||||
pos = 0
|
||||
while pos < len(search_text):
|
||||
hm = _PAS_TYPE_HEADER_RE.search(search_text, pos)
|
||||
if not hm:
|
||||
break
|
||||
type_name = hm.group("name")
|
||||
bases_raw = hm.group("bases") or ""
|
||||
line = _lineno(stripped, search_off + hm.start())
|
||||
cls_nid = _make_id(stem, type_name)
|
||||
_add_node(cls_nid, type_name, line)
|
||||
_add_edge(module_nid, cls_nid, "contains", line)
|
||||
|
||||
for base_name in _pascal_split_bases(bases_raw):
|
||||
same_file_nid = _make_id(stem, base_name)
|
||||
if same_file_nid in seen_ids:
|
||||
# Base class already declared earlier in this same file --
|
||||
# reuse its real node instead of the cross-file/stub lookup
|
||||
# below (which assumes one-class-per-file and would create a
|
||||
# duplicate node for a base class that shares this file).
|
||||
base_nid = same_file_nid
|
||||
else:
|
||||
resolved = _pascal_resolve_class(path, base_name)
|
||||
if resolved:
|
||||
# Cross-file base class found on disk -- its real node
|
||||
# arrives via THAT file's own extraction. Do not add a
|
||||
# duplicate stub here: it would carry this file's
|
||||
# source_file (wrong -- it belongs to the base class's
|
||||
# own file) and collide with the real node under
|
||||
# cross-file id disambiguation, producing two different
|
||||
# salted ids for what should be one class (breaks
|
||||
# cross-file `inherits`-chain resolution downstream).
|
||||
base_nid = resolved
|
||||
else:
|
||||
base_nid = _make_id(base_name)
|
||||
if base_nid not in seen_ids:
|
||||
_add_node(base_nid, base_name, line)
|
||||
_add_edge(cls_nid, base_nid, "inherits", line)
|
||||
|
||||
# Find class body (up to next end;)
|
||||
end_m = _PAS_END_SEMI_RE.search(search_text, hm.end())
|
||||
body_text = search_text[hm.end():end_m.start()] if end_m else ""
|
||||
body_off = search_off + hm.end()
|
||||
|
||||
# Forward method declarations inside the class body
|
||||
for mm in _PAS_METHOD_DECL_RE.finditer(body_text):
|
||||
mname = mm.group("name")
|
||||
mline = _lineno(stripped, body_off + mm.start())
|
||||
method_nid = _make_id(cls_nid, mname)
|
||||
_add_node(method_nid, f"{mname}()", mline)
|
||||
_add_edge(cls_nid, method_nid, "method", mline)
|
||||
|
||||
pos = end_m.end() if end_m else len(search_text)
|
||||
|
||||
# Implementation headers (procedure/function/constructor/destructor)
|
||||
impl_records: list[tuple[str, int, str, str, str]] = []
|
||||
# (proc_nid, line, body_text, container, name_lower)
|
||||
for fm in _PAS_IMPL_HEADER_RE.finditer(impl_text):
|
||||
qualified = fm.group("qual")
|
||||
line = _lineno(stripped, impl_off + fm.start())
|
||||
if "." in qualified:
|
||||
cls_part, method_part = qualified.split(".", 1)
|
||||
cls_nid = _make_id(stem, cls_part)
|
||||
container = cls_nid if cls_nid in seen_ids else module_nid
|
||||
relation = "method" if cls_nid in seen_ids else "contains"
|
||||
label = f"{method_part}()"
|
||||
name_lower = method_part.lower()
|
||||
else:
|
||||
container, relation = module_nid, "contains"
|
||||
label = f"{qualified}()"
|
||||
name_lower = qualified.lower()
|
||||
proc_nid = _make_id(stem, qualified)
|
||||
_add_node(proc_nid, label, line)
|
||||
_add_edge(container, proc_nid, relation, line)
|
||||
|
||||
body_start, body_end = _pascal_find_body(impl_text, fm.end())
|
||||
body_text = impl_text[body_start:body_end] if body_start else ""
|
||||
impl_records.append((proc_nid, line, body_text, container, name_lower))
|
||||
|
||||
# Intra-file call edges, scoped by the caller's own class, then its
|
||||
# ancestor chain (via `inherits` edges already emitted above), then
|
||||
# file-level free functions; fall back to a global by-name match only
|
||||
# when it is unambiguous (single owner across the file). Prevents
|
||||
# same-named methods on unrelated classes (property accessors, generated
|
||||
# wrapper classes such as TLB import units, etc. -- a common Pascal/Delphi
|
||||
# pattern) from collapsing into an arbitrary cross-class edge.
|
||||
callee_nid = _resolve_pascal_callee_factory(impl_records, edges, module_nid)
|
||||
raw_calls: list[dict] = []
|
||||
for caller_nid, caller_line, body_text, _container, _name_lower in impl_records:
|
||||
for cm in _PAS_CALL_RE.finditer(body_text):
|
||||
callee_name = cm.group(1).split(".")[-1].lower()
|
||||
if callee_name in _PAS_KEYWORDS:
|
||||
continue
|
||||
call_line = caller_line + body_text.count("\n", 0, cm.start())
|
||||
target_nid = callee_nid(caller_nid, callee_name)
|
||||
if target_nid == caller_nid:
|
||||
continue
|
||||
if not target_nid:
|
||||
# Not resolvable within this file (e.g. inherited from a base
|
||||
# class declared in another file) -- report for the
|
||||
# cross-file resolver (graphify.pascal_resolution) instead of
|
||||
# guessing or dropping it silently.
|
||||
raw_calls.append({
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{call_line}",
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
})
|
||||
continue
|
||||
pair = (caller_nid, target_nid)
|
||||
if pair in seen_call_pairs:
|
||||
continue
|
||||
seen_call_pairs.add(pair)
|
||||
_add_edge(caller_nid, target_nid, "calls", call_line, context="call")
|
||||
|
||||
return {
|
||||
"nodes": nodes, "edges": edges, "input_tokens": 0, "output_tokens": 0,
|
||||
"raw_calls": raw_calls,
|
||||
}
|
||||
|
||||
def extract_pascal(path: Path) -> dict:
|
||||
"""Extract units, classes, procedures, uses-imports, and calls from Pascal/Delphi files.
|
||||
|
||||
Produces nodes for:
|
||||
- The file itself
|
||||
- unit / program / library declarations
|
||||
- class and interface type declarations
|
||||
- procedure / function implementations (including qualified TClass.Method names)
|
||||
|
||||
Produces edges for:
|
||||
- file --contains--> module
|
||||
- module --imports--> other file node (via uses clause, resolved to path-based IDs)
|
||||
- class --inherits--> base class
|
||||
- class/module --contains--> method forward declaration
|
||||
- class/module --contains--> procedure/function implementation
|
||||
- procedure --calls--> other procedure (within the same file)
|
||||
|
||||
Uses tree-sitter-pascal when available; falls back to a regex-based extractor
|
||||
(_extract_pascal_regex) when it isn't installed or fails to parse, so Pascal
|
||||
extraction works out of the box without an extra pip install.
|
||||
"""
|
||||
try:
|
||||
import tree_sitter_pascal as tspascal
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return _extract_pascal_regex(path)
|
||||
|
||||
try:
|
||||
language = Language(tspascal.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception:
|
||||
return _extract_pascal_regex(path)
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
seen_edges: set[tuple[str, str, str]] = set()
|
||||
proc_bodies: list[tuple[str, Any, str, str]] = []
|
||||
# (proc_nid, body_node, container, name_lower)
|
||||
|
||||
def _read(node) -> str: # type: ignore[no-untyped-def]
|
||||
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(
|
||||
src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None,
|
||||
) -> None:
|
||||
# A class method declared in the interface section and defined in the
|
||||
# implementation section both emit a `method` edge to the same node, so
|
||||
# dedup on (src, tgt, relation) to keep the graph from carrying doubled
|
||||
# method/contains/inherits edges (mirrors add_node's seen_ids guard).
|
||||
key = (src, tgt, relation)
|
||||
if key in seen_edges:
|
||||
return
|
||||
seen_edges.add(key)
|
||||
edge: dict[str, Any] = {
|
||||
"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
module_nid = file_nid
|
||||
|
||||
def _proc_name(header_node) -> str | None: # type: ignore[no-untyped-def]
|
||||
name_node = header_node.child_by_field_name("name")
|
||||
if name_node:
|
||||
return _read(name_node)
|
||||
for child in header_node.children:
|
||||
if child.type in ("identifier", "genericDot", "genericTpl"):
|
||||
return _read(child)
|
||||
return None
|
||||
|
||||
def walk(node, parent_nid: str) -> None: # type: ignore[no-untyped-def]
|
||||
nonlocal module_nid
|
||||
t = node.type
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
if t in ("unit", "program", "library"):
|
||||
name_node = next((c for c in node.children if c.type == "moduleName"), None)
|
||||
mod_name = _read(name_node) if name_node else path.stem
|
||||
mod_nid = _make_id(stem, mod_name)
|
||||
add_node(mod_nid, mod_name, line)
|
||||
add_edge(file_nid, mod_nid, "contains", line)
|
||||
module_nid = mod_nid
|
||||
for child in node.children:
|
||||
walk(child, mod_nid)
|
||||
return
|
||||
|
||||
if t == "declUses":
|
||||
for child in node.children:
|
||||
if child.type == "moduleName":
|
||||
mod_name = _read(child)
|
||||
tgt_nid = _pascal_resolve_unit(path, mod_name)
|
||||
add_edge(parent_nid, tgt_nid, "imports", line, context="import")
|
||||
return
|
||||
|
||||
if t == "declType":
|
||||
type_name = None
|
||||
kind_node = None
|
||||
for child in node.children:
|
||||
if child.type == "identifier" and type_name is None:
|
||||
type_name = _read(child)
|
||||
elif child.type in ("declClass", "declIntf", "declHelper") and kind_node is None:
|
||||
kind_node = child
|
||||
if type_name and kind_node:
|
||||
cls_nid = _make_id(stem, type_name)
|
||||
add_node(cls_nid, type_name, line)
|
||||
add_edge(parent_nid, cls_nid, "contains", line)
|
||||
for child in kind_node.children:
|
||||
if child.type == "typeref":
|
||||
base_name = _read(child)
|
||||
base_nid = _make_id(stem, base_name)
|
||||
if base_nid not in seen_ids:
|
||||
# Try cross-file resolution (TFooBar → FooBar.pas)
|
||||
resolved = _pascal_resolve_class(path, base_name)
|
||||
if resolved:
|
||||
# Cross-file base class found on disk -- its
|
||||
# real node arrives via THAT file's own
|
||||
# extraction. Do not add a duplicate stub
|
||||
# here: it would carry this file's
|
||||
# source_file (wrong) and collide with the
|
||||
# real node under cross-file id
|
||||
# disambiguation, producing two different
|
||||
# salted ids for what should be one class.
|
||||
base_nid = resolved
|
||||
else:
|
||||
base_nid = _make_id(base_name)
|
||||
if base_nid not in seen_ids:
|
||||
# Stub for RTL/external base classes.
|
||||
add_node(base_nid, base_name, line)
|
||||
add_edge(cls_nid, base_nid, "inherits", line)
|
||||
for child in kind_node.children:
|
||||
walk(child, cls_nid)
|
||||
return
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
return
|
||||
|
||||
if t == "declProcFwd":
|
||||
header = next((c for c in node.children if c.type == "declProc"), None)
|
||||
if header:
|
||||
name = _proc_name(header)
|
||||
if name and "." not in name:
|
||||
method_nid = _make_id(parent_nid, name)
|
||||
add_node(method_nid, f"{name}()", line)
|
||||
add_edge(parent_nid, method_nid, "method", line)
|
||||
return
|
||||
|
||||
if t == "defProc":
|
||||
header = next((c for c in node.children if c.type == "declProc"), None)
|
||||
body_node = next((c for c in node.children if c.type == "block"), None)
|
||||
if not header:
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
return
|
||||
name = _proc_name(header)
|
||||
if not name:
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
return
|
||||
container = parent_nid
|
||||
if "." in name:
|
||||
parts = name.split(".", 1)
|
||||
cls_nid = _make_id(stem, parts[0])
|
||||
if cls_nid in seen_ids:
|
||||
container = cls_nid
|
||||
label = f"{parts[-1]}()"
|
||||
else:
|
||||
label = f"{name}()"
|
||||
proc_nid = _make_id(stem, name)
|
||||
add_node(proc_nid, label, line)
|
||||
add_edge(
|
||||
container, proc_nid,
|
||||
"method" if container != parent_nid else "contains",
|
||||
line,
|
||||
)
|
||||
if body_node:
|
||||
proc_bodies.append((proc_nid, body_node, container, label.removesuffix("()").lower()))
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_nid)
|
||||
|
||||
walk(root, file_nid)
|
||||
|
||||
# Second pass: resolve calls inside procedure/function bodies, scoped by
|
||||
# the caller's own class, then its ancestor chain, then file-level free
|
||||
# functions, falling back to an unambiguous global match (see
|
||||
# _resolve_pascal_callee_factory).
|
||||
resolve_callee = _resolve_pascal_callee_factory(proc_bodies, edges, module_nid)
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def _emit_or_report(caller_nid: str, name_lower: str, line: int) -> None:
|
||||
target = resolve_callee(caller_nid, name_lower)
|
||||
if target == caller_nid:
|
||||
return
|
||||
if not target:
|
||||
# Not resolvable within this file (e.g. inherited from a base
|
||||
# class declared in another file) -- report for the cross-file
|
||||
# resolver (graphify.pascal_resolution) instead of guessing or
|
||||
# dropping it silently.
|
||||
raw_calls.append({
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"caller_nid": caller_nid,
|
||||
"callee": name_lower,
|
||||
})
|
||||
return
|
||||
pair = (caller_nid, target)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
add_edge(caller_nid, target, "calls", line, context="call")
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None: # type: ignore[no-untyped-def]
|
||||
if node.type == "exprCall":
|
||||
callee_text = None
|
||||
for child in node.children:
|
||||
if child.is_named and child.type not in ("exprArgs",):
|
||||
callee_text = _read(child).split(".")[-1]
|
||||
break
|
||||
if callee_text:
|
||||
_emit_or_report(caller_nid, callee_text.lower(), node.start_point[0] + 1)
|
||||
elif node.type == "statement":
|
||||
# Pascal bare procedure calls with no args: `Reset;`
|
||||
# tree-sitter represents these as statement → identifier (no exprCall wrapper)
|
||||
named = [c for c in node.children if c.is_named]
|
||||
if len(named) == 1 and named[0].type == "identifier":
|
||||
callee_text = _read(named[0])
|
||||
_emit_or_report(caller_nid, callee_text.lower(), node.start_point[0] + 1)
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for proc_nid, body_node, _container, _name_lower in proc_bodies:
|
||||
walk_calls(body_node, proc_nid)
|
||||
|
||||
return {
|
||||
"nodes": nodes, "edges": edges, "input_tokens": 0, "output_tokens": 0,
|
||||
"raw_calls": raw_calls,
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
"""Pascal_forms extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_lazarus_form(path: Path) -> dict:
|
||||
"""Extract component hierarchy from Lazarus .lfm form files.
|
||||
|
||||
.lfm is a text-based declarative format for UI component trees, structured as:
|
||||
object ComponentName: TClassName
|
||||
PropertyName = Value
|
||||
OnEvent = HandlerName
|
||||
object ChildName: TChildClass
|
||||
...
|
||||
end
|
||||
end
|
||||
|
||||
Produces nodes for:
|
||||
- The form file itself
|
||||
- Each component class encountered (TForm1, TButton, TPanel, ...)
|
||||
- Event handler names referenced by OnXxx properties
|
||||
|
||||
Produces edges for:
|
||||
- file --contains--> root form class
|
||||
- parent component --contains--> child component class
|
||||
- component --references--> event handler (context: "event")
|
||||
"""
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
import re
|
||||
str_path = str(path)
|
||||
stem = _file_stem(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
seen_edge_pairs: set[tuple[str, str, str]] = set()
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(
|
||||
src: str, tgt: str, relation: str, line: int,
|
||||
context: str | None = None,
|
||||
) -> None:
|
||||
key = (src, tgt, relation)
|
||||
if key in seen_edge_pairs:
|
||||
return
|
||||
seen_edge_pairs.add(key)
|
||||
edge: dict[str, Any] = {
|
||||
"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
obj_re = re.compile(r"^\s*object\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
|
||||
event_re = re.compile(r"^\s*On\w+\s*=\s*(\w+)", re.IGNORECASE)
|
||||
end_re = re.compile(r"^\s*end\s*$", re.IGNORECASE)
|
||||
|
||||
# Stack of node IDs representing the nesting of object...end blocks
|
||||
stack: list[str] = [file_nid]
|
||||
|
||||
for lineno, line in enumerate(text.splitlines(), 1):
|
||||
m = obj_re.match(line)
|
||||
if m:
|
||||
class_name = m.group(1)
|
||||
nid = _make_id(stem, class_name)
|
||||
add_node(nid, class_name, lineno)
|
||||
add_edge(stack[-1], nid, "contains", lineno)
|
||||
stack.append(nid)
|
||||
continue
|
||||
|
||||
m = event_re.match(line)
|
||||
if m and len(stack) > 1:
|
||||
handler = m.group(1)
|
||||
handler_nid = _make_id(stem, handler)
|
||||
add_node(handler_nid, f"{handler}()", lineno)
|
||||
add_edge(stack[-1], handler_nid, "references", lineno, context="event")
|
||||
continue
|
||||
|
||||
if end_re.match(line) and len(stack) > 1:
|
||||
stack.pop()
|
||||
|
||||
return {"nodes": nodes, "edges": edges, "input_tokens": 0, "output_tokens": 0}
|
||||
|
||||
def extract_delphi_form(path: Path) -> dict:
|
||||
"""Extract component hierarchy from Delphi .dfm form files.
|
||||
|
||||
.dfm files come in two formats:
|
||||
- Text (same `object Name: TClassName ... end` syntax as .lfm)
|
||||
- Binary (starts with a TPF0/FF0A magic header — unreadable as text)
|
||||
|
||||
Binary .dfm files are skipped gracefully: an empty result is returned
|
||||
so the rest of the pipeline is unaffected. Convert binary forms to
|
||||
text in the Delphi IDE via File → Save As (Text DFM) if you want them
|
||||
indexed.
|
||||
|
||||
Text .dfm files are parsed identically to .lfm: component containment
|
||||
(`contains`) and event handler references (`references`, context "event").
|
||||
"""
|
||||
try:
|
||||
raw = path.read_bytes()
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
# Detect binary DFM: Delphi binary resource streams start with FF 0A
|
||||
if raw[:2] == b"\xff\x0a":
|
||||
return {
|
||||
"nodes": [], "edges": [],
|
||||
"error": f"binary DFM (convert to text in Delphi IDE to index): {path.name}",
|
||||
}
|
||||
|
||||
# Text DFM — delegate to the shared form parser (same syntax as .lfm)
|
||||
try:
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
import re
|
||||
str_path = str(path)
|
||||
stem = _file_stem(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
seen_edge_pairs: set[tuple[str, str, str]] = set()
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(
|
||||
src: str, tgt: str, relation: str, line: int,
|
||||
context: str | None = None,
|
||||
) -> None:
|
||||
key = (src, tgt, relation)
|
||||
if key in seen_edge_pairs:
|
||||
return
|
||||
seen_edge_pairs.add(key)
|
||||
edge: dict[str, Any] = {
|
||||
"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
obj_re = re.compile(r"^\s*object\s+\w+\s*:\s*(\w+)", re.IGNORECASE)
|
||||
event_re = re.compile(r"^\s*On\w+\s*=\s*(\w+)", re.IGNORECASE)
|
||||
end_re = re.compile(r"^\s*end\s*$", re.IGNORECASE)
|
||||
stack: list[str] = [file_nid]
|
||||
|
||||
for lineno, line in enumerate(text.splitlines(), 1):
|
||||
m = obj_re.match(line)
|
||||
if m:
|
||||
class_name = m.group(1)
|
||||
nid = _make_id(stem, class_name)
|
||||
add_node(nid, class_name, lineno)
|
||||
add_edge(stack[-1], nid, "contains", lineno)
|
||||
stack.append(nid)
|
||||
continue
|
||||
m = event_re.match(line)
|
||||
if m and len(stack) > 1:
|
||||
handler = m.group(1)
|
||||
handler_nid = _make_id(stem, handler)
|
||||
add_node(handler_nid, f"{handler}()", lineno)
|
||||
add_edge(stack[-1], handler_nid, "references", lineno, context="event")
|
||||
continue
|
||||
if end_re.match(line) and len(stack) > 1:
|
||||
stack.pop()
|
||||
|
||||
return {"nodes": nodes, "edges": edges, "input_tokens": 0, "output_tokens": 0}
|
||||
@@ -1,496 +0,0 @@
|
||||
"""Powershell extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
def extract_powershell(path: Path) -> dict:
|
||||
"""Extract functions, classes, methods, and using statements from a .ps1 file."""
|
||||
try:
|
||||
import tree_sitter_powershell as tsps
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_powershell not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsps.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
_PS_SKIP = frozenset({
|
||||
"using", "return", "if", "else", "elseif", "foreach", "for",
|
||||
"while", "do", "switch", "try", "catch", "finally", "throw",
|
||||
"break", "continue", "exit", "param", "begin", "process", "end",
|
||||
# Import commands — handled as import edges, not function calls
|
||||
"import-module",
|
||||
})
|
||||
|
||||
def _find_script_block_body(node):
|
||||
for child in node.children:
|
||||
if child.type == "script_block":
|
||||
for sc in child.children:
|
||||
if sc.type == "script_block_body":
|
||||
return sc
|
||||
return child
|
||||
return None
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
if nid in seen_ids:
|
||||
return nid
|
||||
nid = _make_id(name)
|
||||
if nid not in seen_ids:
|
||||
# The name isn't defined in this file, so this is a cross-file reference
|
||||
# (e.g. a `Thing` type annotation imported from another module). Emit a
|
||||
# SOURCELESS stub — like the inheritance-base path below — so the
|
||||
# corpus-level rewire can collapse it onto the real definition. A sourced
|
||||
# stub here makes _disambiguate_colliding_node_ids bake the referencing
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
return nid
|
||||
|
||||
def _ps_type_name(type_literal_node) -> str | None:
|
||||
"""Drill into a type_literal node and return the inner type_identifier text."""
|
||||
if type_literal_node is None:
|
||||
return None
|
||||
for spec in type_literal_node.children:
|
||||
if spec.type != "type_spec":
|
||||
continue
|
||||
for tname in spec.children:
|
||||
if tname.type != "type_name":
|
||||
continue
|
||||
for tid in tname.children:
|
||||
if tid.type == "type_identifier":
|
||||
return _read_text(tid, source)
|
||||
return None
|
||||
|
||||
def walk(node, parent_class_nid: str | None = None) -> None:
|
||||
t = node.type
|
||||
|
||||
if t == "function_statement":
|
||||
name_node = next((c for c in node.children if c.type == "function_name"), None)
|
||||
if name_node:
|
||||
func_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
func_nid = _make_id(stem, func_name)
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
body = _find_script_block_body(node)
|
||||
if body:
|
||||
function_bodies.append((func_nid, body))
|
||||
# Also walk the body during the main pass so that
|
||||
# Import-Module / dot-source inside functions emit
|
||||
# file-level imports_from edges (#1331).
|
||||
walk(body, parent_class_nid)
|
||||
return
|
||||
|
||||
if t == "class_statement":
|
||||
name_node = next((c for c in node.children if c.type == "simple_name"), None)
|
||||
if name_node:
|
||||
class_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
class_nid = _make_id(stem, class_name)
|
||||
add_node(class_nid, class_name, line)
|
||||
add_edge(file_nid, class_nid, "contains", line)
|
||||
# Base type(s) after ':'. PowerShell has no syntactic base vs
|
||||
# interface split, so (matching the C# convention) treat the
|
||||
# first base as the superclass (inherits) and the rest as
|
||||
# interfaces (implements). Bases are the simple_name children
|
||||
# after the ':' token.
|
||||
colon_seen = False
|
||||
base_index = 0
|
||||
for child in node.children:
|
||||
if child.type == ":":
|
||||
colon_seen = True
|
||||
elif colon_seen and child.type == "simple_name":
|
||||
base_nid = ensure_named_node(_read_text(child, source), line)
|
||||
if base_nid != class_nid:
|
||||
rel = "inherits" if base_index == 0 else "implements"
|
||||
add_edge(class_nid, base_nid, rel, line)
|
||||
base_index += 1
|
||||
for child in node.children:
|
||||
walk(child, parent_class_nid=class_nid)
|
||||
return
|
||||
|
||||
if t == "class_property_definition" and parent_class_nid:
|
||||
type_literal = next((c for c in node.children if c.type == "type_literal"), None)
|
||||
type_name = _ps_type_name(type_literal)
|
||||
if type_name:
|
||||
line = node.start_point[0] + 1
|
||||
target_nid = ensure_named_node(type_name, line)
|
||||
if target_nid != parent_class_nid:
|
||||
add_edge(parent_class_nid, target_nid, "references",
|
||||
line, context="field")
|
||||
return
|
||||
|
||||
if t == "class_method_definition":
|
||||
name_node = next((c for c in node.children if c.type == "simple_name"), None)
|
||||
if name_node:
|
||||
method_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
if parent_class_nid:
|
||||
method_nid = _make_id(parent_class_nid, method_name)
|
||||
add_node(method_nid, f".{method_name}()", line)
|
||||
add_edge(parent_class_nid, method_nid, "method", line)
|
||||
else:
|
||||
method_nid = _make_id(stem, method_name)
|
||||
add_node(method_nid, f"{method_name}()", line)
|
||||
add_edge(file_nid, method_nid, "contains", line)
|
||||
# Return type: type_literal sibling of simple_name
|
||||
return_type_literal = next(
|
||||
(c for c in node.children if c.type == "type_literal"), None)
|
||||
return_type_name = _ps_type_name(return_type_literal)
|
||||
if return_type_name:
|
||||
target_nid = ensure_named_node(return_type_name, line)
|
||||
if target_nid != method_nid:
|
||||
add_edge(method_nid, target_nid, "references",
|
||||
line, context="return_type")
|
||||
# Parameter types: class_method_parameter_list
|
||||
param_list = next(
|
||||
(c for c in node.children if c.type == "class_method_parameter_list"), None)
|
||||
if param_list is not None:
|
||||
for p in param_list.children:
|
||||
if p.type != "class_method_parameter":
|
||||
continue
|
||||
ptype_literal = next(
|
||||
(c for c in p.children if c.type == "type_literal"), None)
|
||||
ptype_name = _ps_type_name(ptype_literal)
|
||||
if not ptype_name:
|
||||
continue
|
||||
p_line = p.start_point[0] + 1
|
||||
target_nid = ensure_named_node(ptype_name, p_line)
|
||||
if target_nid != method_nid:
|
||||
add_edge(method_nid, target_nid, "references",
|
||||
p_line, context="parameter_type")
|
||||
body = _find_script_block_body(node)
|
||||
if body:
|
||||
function_bodies.append((method_nid, body))
|
||||
return
|
||||
|
||||
if t == "command":
|
||||
# Dot-sourcing: `. ./Shared.psm1`
|
||||
# Uses command_invokation_operator '.' + command_name_expr (not command_name)
|
||||
invoke_op = next(
|
||||
(c for c in node.children if c.type == "command_invokation_operator"), None
|
||||
)
|
||||
if invoke_op is not None and _read_text(invoke_op, source).strip() == ".":
|
||||
name_expr = next(
|
||||
(c for c in node.children if c.type == "command_name_expr"), None
|
||||
)
|
||||
if name_expr is not None:
|
||||
name_node = next(
|
||||
(c for c in name_expr.children if c.type == "command_name"), None
|
||||
)
|
||||
if name_node:
|
||||
raw_path = _read_text(name_node, source)
|
||||
# Strip relative path prefix (./ or .\ or just the dot)
|
||||
module_stem = re.sub(r'^[./\\]+', '', raw_path)
|
||||
# Drop extension to get bare module name
|
||||
module_stem = re.sub(r'\.[^.]+$', '', module_stem).replace('\\', '/')
|
||||
module_name = module_stem.split('/')[-1]
|
||||
if module_name:
|
||||
add_edge(file_nid, _make_id(module_name), "imports_from",
|
||||
node.start_point[0] + 1)
|
||||
return
|
||||
|
||||
cmd_name_node = next((c for c in node.children if c.type == "command_name"), None)
|
||||
if cmd_name_node:
|
||||
cmd_text = _read_text(cmd_name_node, source).lower()
|
||||
if cmd_text == "using":
|
||||
tokens = []
|
||||
for child in node.children:
|
||||
if child.type == "command_elements":
|
||||
for el in child.children:
|
||||
if el.type == "generic_token":
|
||||
tokens.append(_read_text(el, source))
|
||||
module_tokens = [t for t in tokens
|
||||
if t.lower() not in ("namespace", "module", "assembly")]
|
||||
if module_tokens:
|
||||
module_name = module_tokens[-1].split(".")[-1]
|
||||
add_edge(file_nid, _make_id(module_name), "imports_from",
|
||||
node.start_point[0] + 1)
|
||||
elif cmd_text == "import-module":
|
||||
# Collect generic_token args; skip command_parameter flags like -Name
|
||||
# The module name is the first generic_token (or the one after -Name)
|
||||
module_name: str | None = None
|
||||
expect_name = False
|
||||
for child in node.children:
|
||||
if child.type != "command_elements":
|
||||
continue
|
||||
for el in child.children:
|
||||
if el.type == "command_parameter":
|
||||
param_text = _read_text(el, source).lstrip("-").lower()
|
||||
expect_name = param_text in ("name", "n")
|
||||
elif el.type == "generic_token":
|
||||
token = _read_text(el, source)
|
||||
if module_name is None or expect_name:
|
||||
module_name = token
|
||||
expect_name = False
|
||||
if module_name:
|
||||
# Strip extension; keep only the stem for the node ID
|
||||
bare = re.sub(r'\.[^.]+$', '', module_name).split('/')[-1].split('\\')[-1]
|
||||
if bare:
|
||||
add_edge(file_nid, _make_id(bare), "imports_from",
|
||||
node.start_point[0] + 1)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_class_nid)
|
||||
|
||||
walk(root)
|
||||
|
||||
label_to_nid = {n["label"].strip("()").lstrip(".").lower(): n["id"] for n in nodes}
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
if node.type in ("function_statement", "class_statement"):
|
||||
return
|
||||
if node.type == "command":
|
||||
cmd_name_node = next((c for c in node.children if c.type == "command_name"), None)
|
||||
if cmd_name_node:
|
||||
cmd_text = _read_text(cmd_name_node, source)
|
||||
if cmd_text.lower() not in _PS_SKIP:
|
||||
tgt_nid = label_to_nid.get(cmd_text.lower())
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
add_edge(caller_nid, tgt_nid, "calls",
|
||||
node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0)
|
||||
elif cmd_text:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": cmd_text,
|
||||
"is_member_call": False,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for caller_nid, body_node in function_bodies:
|
||||
walk_calls(body_node, caller_nid)
|
||||
|
||||
clean_edges = [e for e in edges if e["source"] in seen_ids and
|
||||
(e["target"] in seen_ids or e["relation"] in ("imports_from", "imports"))]
|
||||
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
|
||||
|
||||
_PSD1_IMPORT_KEYS = frozenset({"RootModule", "NestedModules", "RequiredModules"})
|
||||
|
||||
def _psd1_collect_string_literals(node, source: bytes) -> list[str]:
|
||||
"""Recursively collect all string_literal text values under *node*."""
|
||||
results: list[str] = []
|
||||
|
||||
def _walk(n) -> None:
|
||||
if n.type == "string_literal":
|
||||
raw = source[n.start_byte:n.end_byte].decode(errors="replace")
|
||||
# Strip surrounding quote chars (' or ")
|
||||
results.append(raw.strip("'\""))
|
||||
return
|
||||
for child in n.children:
|
||||
_walk(child)
|
||||
|
||||
_walk(node)
|
||||
return results
|
||||
|
||||
def _psd1_module_name(raw: str) -> str:
|
||||
"""Derive a bare module name from a raw string value.
|
||||
|
||||
e.g. 'MyModule.psm1' → 'MyModule', './sub/Util.psm1' → 'Util', 'PSReadLine' → 'PSReadLine'
|
||||
"""
|
||||
# Strip path prefix and extension
|
||||
name = raw.replace("\\", "/").split("/")[-1]
|
||||
name = re.sub(r"\.[^.]+$", "", name) # remove last extension
|
||||
return name.strip()
|
||||
|
||||
def extract_powershell_manifest(path: Path) -> dict:
|
||||
"""Extract module dependency edges from a PowerShell .psd1 manifest file.
|
||||
|
||||
.psd1 files are PowerShell data hashtables, not scripts. tree-sitter-powershell
|
||||
parses them correctly (they are syntactically valid PS). We walk the AST looking
|
||||
for RootModule, NestedModules, and RequiredModules keys and emit imports_from
|
||||
edges for every referenced module.
|
||||
|
||||
RequiredModules supports two forms:
|
||||
- Simple string: 'PSReadLine'
|
||||
- Module specification: @{ ModuleName = 'Pester'; ModuleVersion = '5.0' }
|
||||
For the hashtable form we only follow the ModuleName key.
|
||||
"""
|
||||
try:
|
||||
import tree_sitter_powershell as tsps
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_powershell not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsps.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_import_edge(src: str, module_raw: str, line: int) -> None:
|
||||
name = _psd1_module_name(module_raw)
|
||||
if not name:
|
||||
return
|
||||
tgt_nid = _make_id(name)
|
||||
edges.append({
|
||||
"source": src,
|
||||
"target": tgt_nid,
|
||||
"relation": "imports_from",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
"context": "import",
|
||||
})
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def walk_manifest(node) -> None:
|
||||
"""Walk the AST and emit edges for import-relevant hash_entry nodes."""
|
||||
if node.type != "hash_entry":
|
||||
for child in node.children:
|
||||
walk_manifest(child)
|
||||
return
|
||||
|
||||
# Identify the key
|
||||
key_node = next((c for c in node.children if c.type == "key_expression"), None)
|
||||
if key_node is None:
|
||||
return
|
||||
key_text = source[key_node.start_byte:key_node.end_byte].decode(errors="replace").strip()
|
||||
|
||||
if key_text not in _PSD1_IMPORT_KEYS:
|
||||
# Still recurse in case there are nested hashes (e.g. ModuleVersion entries
|
||||
# contain sub-hashes, but we only care about top-level keys for imports)
|
||||
return
|
||||
|
||||
line = node.start_point[0] + 1
|
||||
value_node = next((c for c in node.children if c.type == "pipeline"), None)
|
||||
if value_node is None:
|
||||
return
|
||||
|
||||
if key_text == "RootModule":
|
||||
# Value is a single string
|
||||
strings = _psd1_collect_string_literals(value_node, source)
|
||||
for s in strings:
|
||||
add_import_edge(file_nid, s, line)
|
||||
|
||||
elif key_text == "NestedModules":
|
||||
# Value is a string or @('a', 'b', ...) array — collect all string literals
|
||||
strings = _psd1_collect_string_literals(value_node, source)
|
||||
for s in strings:
|
||||
add_import_edge(file_nid, s, line)
|
||||
|
||||
elif key_text == "RequiredModules":
|
||||
# Two forms:
|
||||
# 1) 'SimpleModule' — direct string literals in the array
|
||||
# 2) @{ ModuleName = 'Foo'; ModuleVersion = '2.0' } — use ModuleName only
|
||||
#
|
||||
# Strategy: walk the value for hash_entry nodes whose key is 'ModuleName';
|
||||
# collect their string values. For the remaining string_literal nodes that
|
||||
# are NOT inside a hash_entry subtree, treat them as simple module names.
|
||||
module_name_strings: list[str] = []
|
||||
inside_hash_entries: set[int] = set() # byte offsets of handled strings
|
||||
|
||||
def find_modulename_entries(n) -> None:
|
||||
if n.type == "hash_entry":
|
||||
sub_key = next((c for c in n.children if c.type == "key_expression"), None)
|
||||
if sub_key is not None:
|
||||
sk_text = source[sub_key.start_byte:sub_key.end_byte].decode(errors="replace").strip()
|
||||
# Collect strings inside *all* sub-keys so we can exclude them
|
||||
for c in n.children:
|
||||
if c.type == "pipeline":
|
||||
for s_node in _collect_string_nodes(c):
|
||||
inside_hash_entries.add(s_node.start_byte)
|
||||
if sk_text == "ModuleName":
|
||||
for c in n.children:
|
||||
if c.type == "pipeline":
|
||||
for s in _psd1_collect_string_literals(c, source):
|
||||
module_name_strings.append(s)
|
||||
return # don't recurse further into this hash_entry
|
||||
for child in n.children:
|
||||
find_modulename_entries(child)
|
||||
|
||||
def _collect_string_nodes(n):
|
||||
"""Return all string_literal nodes in subtree."""
|
||||
if n.type == "string_literal":
|
||||
yield n
|
||||
return
|
||||
for child in n.children:
|
||||
yield from _collect_string_nodes(child)
|
||||
|
||||
find_modulename_entries(value_node)
|
||||
|
||||
# Now gather direct string literals not inside hash entries
|
||||
direct_strings: list[str] = []
|
||||
for s_node in _collect_string_nodes(value_node):
|
||||
if s_node.start_byte not in inside_hash_entries:
|
||||
raw = source[s_node.start_byte:s_node.end_byte].decode(errors="replace")
|
||||
direct_strings.append(raw.strip("'\""))
|
||||
|
||||
for s in direct_strings + module_name_strings:
|
||||
add_import_edge(file_nid, s, line)
|
||||
|
||||
walk_manifest(root)
|
||||
|
||||
return {"nodes": nodes, "edges": edges, "raw_calls": []}
|
||||
@@ -1,119 +0,0 @@
|
||||
"""ASP.NET Razor component extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_razor(path: Path) -> dict:
|
||||
"""Extract directives, component refs, and @code methods from .razor/.cshtml."""
|
||||
try:
|
||||
src = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return {"nodes": [], "edges": [], "error": f"cannot read {path}"}
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": None}]
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
seen_ids.add(file_nid)
|
||||
|
||||
def _add_ref(target_name: str, relation: str, line: int) -> None:
|
||||
tgt_nid = _make_id(target_name)
|
||||
if not tgt_nid:
|
||||
return
|
||||
if tgt_nid not in seen_ids:
|
||||
seen_ids.add(tgt_nid)
|
||||
nodes.append({"id": tgt_nid, "label": target_name,
|
||||
"file_type": "code", "source_file": str_path,
|
||||
"source_location": f"L{line}"})
|
||||
edges.append({"source": file_nid, "target": tgt_nid,
|
||||
"relation": relation, "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
"weight": 1.0})
|
||||
|
||||
for i, line in enumerate(src.splitlines(), 1):
|
||||
m = re.match(r'@using\s+([\w.]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "imports", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@inject\s+([\w.<>\[\]]+)\s+(\w+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "imports", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@inherits\s+([\w.<>\[\]]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "inherits", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@model\s+([\w.<>\[\]]+)', line)
|
||||
if m:
|
||||
_add_ref(m.group(1), "references", i)
|
||||
continue
|
||||
|
||||
m = re.match(r'@page\s+"([^"]+)"', line)
|
||||
if m:
|
||||
route = m.group(1)
|
||||
route_nid = _make_id("route", route)
|
||||
if route_nid and route_nid not in seen_ids:
|
||||
seen_ids.add(route_nid)
|
||||
nodes.append({"id": route_nid, "label": f"route:{route}",
|
||||
"file_type": "concept", "source_file": str_path,
|
||||
"source_location": f"L{i}"})
|
||||
edges.append({"source": file_nid, "target": route_nid,
|
||||
"relation": "references", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "weight": 1.0})
|
||||
continue
|
||||
|
||||
_COMPONENT_RE = re.compile(r'<([A-Z][A-Za-z0-9]+)[\s/>]')
|
||||
_HTML_TAGS = frozenset({
|
||||
"DOCTYPE", "Html", "Head", "Body", "Div", "Span", "Table", "Form",
|
||||
"Input", "Button", "Select", "Option", "Label", "Textarea",
|
||||
"Script", "Style", "Link", "Meta", "Title", "Header", "Footer",
|
||||
"Nav", "Main", "Section", "Article", "Aside",
|
||||
})
|
||||
for m in _COMPONENT_RE.finditer(src):
|
||||
comp_name = m.group(1)
|
||||
if comp_name in _HTML_TAGS:
|
||||
continue
|
||||
line_num = src[:m.start()].count("\n") + 1
|
||||
_add_ref(comp_name, "calls", line_num)
|
||||
|
||||
_CODE_BLOCK_RE = re.compile(r'@code\s*\{', re.MULTILINE)
|
||||
for m in _CODE_BLOCK_RE.finditer(src):
|
||||
block_start = m.end()
|
||||
depth = 1
|
||||
pos = block_start
|
||||
while pos < len(src) and depth > 0:
|
||||
if src[pos] == '{':
|
||||
depth += 1
|
||||
elif src[pos] == '}':
|
||||
depth -= 1
|
||||
pos += 1
|
||||
code_block = src[block_start:pos - 1] if depth == 0 else ""
|
||||
|
||||
_METHOD_RE = re.compile(
|
||||
r'(?:public|private|protected|internal|static|async|override|virtual|abstract)\s+'
|
||||
r'[\w<>\[\],\s]+\s+(\w+)\s*\('
|
||||
)
|
||||
for mm in _METHOD_RE.finditer(code_block):
|
||||
method_name = mm.group(1)
|
||||
abs_pos = block_start + mm.start()
|
||||
method_line = src[:abs_pos].count("\n") + 1
|
||||
method_nid = _make_id(_file_stem(path), method_name)
|
||||
if method_nid and method_nid not in seen_ids:
|
||||
seen_ids.add(method_nid)
|
||||
nodes.append({"id": method_nid, "label": method_name,
|
||||
"file_type": "code", "source_file": str_path,
|
||||
"source_location": f"L{method_line}"})
|
||||
edges.append({"source": file_nid, "target": method_nid,
|
||||
"relation": "contains", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "weight": 1.0})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,410 +0,0 @@
|
||||
"""Rust extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS, _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
def _rust_collect_type_refs(node, source: bytes, generic: bool, out: list[tuple[str, str]]) -> None:
|
||||
"""Walk a Rust type expression; append (name, role) tuples."""
|
||||
if node is None:
|
||||
return
|
||||
t = node.type
|
||||
if t == "primitive_type":
|
||||
return
|
||||
if t == "type_identifier":
|
||||
text = _read_text(node, source)
|
||||
if text:
|
||||
out.append((text, "generic_arg" if generic else "type"))
|
||||
return
|
||||
if t == "scoped_type_identifier":
|
||||
text = _read_text(node, source).rsplit("::", 1)[-1]
|
||||
if text:
|
||||
out.append((text, "generic_arg" if generic else "type"))
|
||||
return
|
||||
if t == "generic_type":
|
||||
name_node = node.child_by_field_name("type")
|
||||
if name_node is None:
|
||||
for c in node.children:
|
||||
if c.type in ("type_identifier", "scoped_type_identifier"):
|
||||
name_node = c
|
||||
break
|
||||
if name_node is not None:
|
||||
text = _read_text(name_node, source).rsplit("::", 1)[-1]
|
||||
if text:
|
||||
out.append((text, "generic_arg" if generic else "type"))
|
||||
for c in node.children:
|
||||
if c.type == "type_arguments":
|
||||
for arg in c.children:
|
||||
if arg.is_named:
|
||||
_rust_collect_type_refs(arg, source, True, out)
|
||||
return
|
||||
if t in ("reference_type", "pointer_type", "array_type", "tuple_type", "slice_type"):
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_rust_collect_type_refs(c, source, generic, out)
|
||||
return
|
||||
if node.is_named:
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_rust_collect_type_refs(c, source, generic, out)
|
||||
|
||||
_RUST_TRAIT_METHOD_BLOCKLIST: frozenset[str] = frozenset({
|
||||
"new", "default", "parse", "from_str", "now", "clone", "into", "from",
|
||||
"to_string", "to_owned", "len", "is_empty", "iter", "next", "build",
|
||||
"start", "run", "init", "app", "get", "set", "push", "pop", "insert",
|
||||
"remove", "contains", "collect", "map", "filter", "unwrap", "expect",
|
||||
"ok", "err", "some", "none", "send", "recv", "lock", "read", "write",
|
||||
})
|
||||
|
||||
def extract_rust(path: Path) -> dict:
|
||||
"""Extract functions, structs, enums, traits, impl methods, and use declarations from a .rs file."""
|
||||
try:
|
||||
import tree_sitter_rust as tsrust
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree-sitter-rust not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsrust.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, object]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": label,
|
||||
"file_type": "code",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {
|
||||
"source": src,
|
||||
"target": tgt,
|
||||
"relation": relation,
|
||||
"confidence": confidence,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": weight,
|
||||
}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def ensure_named_node(name: str, line: int) -> str:
|
||||
nid = _make_id(stem, name)
|
||||
if nid in seen_ids:
|
||||
return nid
|
||||
nid = _make_id(name)
|
||||
if nid not in seen_ids:
|
||||
# The name isn't defined in this file, so this is a cross-file reference
|
||||
# (e.g. a `Thing` type annotation imported from another module). Emit a
|
||||
# SOURCELESS stub — like the inheritance-base path below — so the
|
||||
# corpus-level rewire can collapse it onto the real definition. A sourced
|
||||
# stub here makes _disambiguate_colliding_node_ids bake the referencing
|
||||
# file's path (with extension) into the id and blocks the rewire, which is
|
||||
# the phantom-duplicate-node bug (#1402).
|
||||
seen_ids.add(nid)
|
||||
nodes.append({
|
||||
"id": nid,
|
||||
"label": name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
"origin_file": str_path,
|
||||
})
|
||||
return nid
|
||||
|
||||
def emit_param_return_refs(func_node, func_nid: str, line: int) -> None:
|
||||
params = func_node.child_by_field_name("parameters")
|
||||
if params is not None:
|
||||
for p in params.children:
|
||||
if p.type != "parameter":
|
||||
continue
|
||||
type_node = p.child_by_field_name("type")
|
||||
refs: list[tuple[str, str]] = []
|
||||
_rust_collect_type_refs(type_node, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "parameter_type"
|
||||
tgt = ensure_named_node(ref_name, line)
|
||||
if tgt != func_nid:
|
||||
add_edge(func_nid, tgt, "references", line, context=ctx)
|
||||
return_type = func_node.child_by_field_name("return_type")
|
||||
if return_type is not None:
|
||||
refs = []
|
||||
_rust_collect_type_refs(return_type, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "return_type"
|
||||
tgt = ensure_named_node(ref_name, line)
|
||||
if tgt != func_nid:
|
||||
add_edge(func_nid, tgt, "references", line, context=ctx)
|
||||
|
||||
def walk(node, parent_impl_nid: str | None = None) -> None:
|
||||
t = node.type
|
||||
|
||||
if t == "function_item":
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
func_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
if parent_impl_nid:
|
||||
func_nid = _make_id(parent_impl_nid, func_name)
|
||||
add_node(func_nid, f".{func_name}()", line)
|
||||
add_edge(parent_impl_nid, func_nid, "method", line)
|
||||
else:
|
||||
func_nid = _make_id(stem, func_name)
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
emit_param_return_refs(node, func_nid, line)
|
||||
body = node.child_by_field_name("body")
|
||||
if body:
|
||||
function_bodies.append((func_nid, body))
|
||||
return
|
||||
|
||||
if t in ("struct_item", "enum_item", "trait_item"):
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
item_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
item_nid = _make_id(stem, item_name)
|
||||
add_node(item_nid, item_name, line)
|
||||
add_edge(file_nid, item_nid, "contains", line)
|
||||
if t == "trait_item":
|
||||
for c in node.children:
|
||||
if c.type != "trait_bounds":
|
||||
continue
|
||||
for sub in c.children:
|
||||
if not sub.is_named:
|
||||
continue
|
||||
refs: list[tuple[str, str]] = []
|
||||
_rust_collect_type_refs(sub, source, False, refs)
|
||||
for idx, (ref_name, _role) in enumerate(refs):
|
||||
tgt = ensure_named_node(ref_name, line)
|
||||
if tgt == item_nid:
|
||||
continue
|
||||
rel = "inherits" if idx == 0 else "references"
|
||||
if rel == "inherits":
|
||||
add_edge(item_nid, tgt, "inherits", line)
|
||||
else:
|
||||
add_edge(item_nid, tgt, "references", line,
|
||||
context="generic_arg")
|
||||
if t == "struct_item":
|
||||
for c in node.children:
|
||||
if c.type != "field_declaration_list":
|
||||
continue
|
||||
for field in c.children:
|
||||
if field.type != "field_declaration":
|
||||
continue
|
||||
type_node = field.child_by_field_name("type")
|
||||
if type_node is None:
|
||||
for fc in field.children:
|
||||
if fc.type in ("type_identifier", "generic_type",
|
||||
"scoped_type_identifier",
|
||||
"reference_type", "primitive_type"):
|
||||
type_node = fc
|
||||
break
|
||||
refs = []
|
||||
_rust_collect_type_refs(type_node, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "field"
|
||||
tgt = ensure_named_node(ref_name, field.start_point[0] + 1)
|
||||
if tgt != item_nid:
|
||||
add_edge(item_nid, tgt, "references",
|
||||
field.start_point[0] + 1, context=ctx)
|
||||
# Tuple structs (`struct Wrapper(pub Logger, Config);`) nest their
|
||||
# positional field types directly under ordered_field_declaration_list
|
||||
# with no field_declaration wrapper -- the same shape handled for tuple
|
||||
# enum variants below. Without this branch these field type references
|
||||
# are silently dropped.
|
||||
for c in node.children:
|
||||
if c.type != "ordered_field_declaration_list":
|
||||
continue
|
||||
fline = c.start_point[0] + 1
|
||||
for tc in c.children:
|
||||
if tc.type not in ("type_identifier", "generic_type",
|
||||
"scoped_type_identifier", "reference_type",
|
||||
"primitive_type", "tuple_type", "array_type"):
|
||||
continue
|
||||
refs = []
|
||||
_rust_collect_type_refs(tc, source, False, refs)
|
||||
for ref_name, role in refs:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "field"
|
||||
tgt = ensure_named_node(ref_name, fline)
|
||||
if tgt != item_nid:
|
||||
add_edge(item_nid, tgt, "references", fline, context=ctx)
|
||||
if t == "enum_item":
|
||||
# Variant payload types nest under enum_variant_list ->
|
||||
# enum_variant -> ordered_field_declaration_list (tuple variant,
|
||||
# `Click(Logger)`) | field_declaration_list (struct variant,
|
||||
# `Resize { size: Dim }`). Neither was traversed, so every
|
||||
# enum-variant type reference was silently dropped.
|
||||
_TYPE_NODES = ("type_identifier", "generic_type",
|
||||
"scoped_type_identifier", "reference_type",
|
||||
"primitive_type", "tuple_type", "array_type")
|
||||
|
||||
def _emit_enum_type(type_node, at_line):
|
||||
if type_node is None:
|
||||
return
|
||||
refs2: list[tuple[str, str]] = []
|
||||
_rust_collect_type_refs(type_node, source, False, refs2)
|
||||
for ref_name, role in refs2:
|
||||
ctx = "generic_arg" if role == "generic_arg" else "field"
|
||||
tgt = ensure_named_node(ref_name, at_line)
|
||||
if tgt != item_nid:
|
||||
add_edge(item_nid, tgt, "references", at_line, context=ctx)
|
||||
|
||||
for c in node.children:
|
||||
if c.type != "enum_variant_list":
|
||||
continue
|
||||
for variant in c.children:
|
||||
if variant.type != "enum_variant":
|
||||
continue
|
||||
vline = variant.start_point[0] + 1
|
||||
for vc in variant.children:
|
||||
if vc.type == "ordered_field_declaration_list":
|
||||
for tc in vc.children:
|
||||
if tc.type in _TYPE_NODES:
|
||||
_emit_enum_type(tc, vline)
|
||||
elif vc.type == "field_declaration_list":
|
||||
for field in vc.children:
|
||||
if field.type != "field_declaration":
|
||||
continue
|
||||
type_node = field.child_by_field_name("type")
|
||||
_emit_enum_type(type_node, field.start_point[0] + 1)
|
||||
return
|
||||
|
||||
if t == "impl_item":
|
||||
type_node = node.child_by_field_name("type")
|
||||
trait_node = node.child_by_field_name("trait")
|
||||
impl_nid: str | None = None
|
||||
if type_node:
|
||||
type_name = _read_text(type_node, source).strip()
|
||||
impl_nid = _make_id(stem, type_name)
|
||||
add_node(impl_nid, type_name, node.start_point[0] + 1)
|
||||
if trait_node is not None and impl_nid is not None:
|
||||
refs: list[tuple[str, str]] = []
|
||||
_rust_collect_type_refs(trait_node, source, False, refs)
|
||||
for idx, (ref_name, _role) in enumerate(refs):
|
||||
tgt = ensure_named_node(ref_name, node.start_point[0] + 1)
|
||||
if tgt == impl_nid:
|
||||
continue
|
||||
if idx == 0:
|
||||
add_edge(impl_nid, tgt, "implements", node.start_point[0] + 1)
|
||||
else:
|
||||
add_edge(impl_nid, tgt, "references", node.start_point[0] + 1,
|
||||
context="generic_arg")
|
||||
body = node.child_by_field_name("body")
|
||||
if body:
|
||||
for child in body.children:
|
||||
walk(child, parent_impl_nid=impl_nid)
|
||||
return
|
||||
|
||||
if t == "use_declaration":
|
||||
arg = node.child_by_field_name("argument")
|
||||
if arg:
|
||||
raw = _read_text(arg, source)
|
||||
clean = raw.split("{")[0].rstrip(":").rstrip("*").rstrip(":")
|
||||
module_name = clean.split("::")[-1].strip()
|
||||
if module_name:
|
||||
tgt_nid = _make_id(module_name)
|
||||
add_edge(file_nid, tgt_nid, "imports_from", node.start_point[0] + 1, context="import")
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_impl_nid=None)
|
||||
|
||||
walk(root)
|
||||
|
||||
label_to_nid: dict[str, str] = {}
|
||||
for n in nodes:
|
||||
raw = n["label"]
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
label_to_nid[normalised] = n["id"]
|
||||
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
if node.type == "function_item":
|
||||
return
|
||||
if node.type == "call_expression":
|
||||
func_node = node.child_by_field_name("function")
|
||||
callee_name: str | None = None
|
||||
is_member_call: bool = False
|
||||
is_scoped_call: bool = False
|
||||
if func_node:
|
||||
if func_node.type == "identifier":
|
||||
callee_name = _read_text(func_node, source)
|
||||
elif func_node.type == "field_expression":
|
||||
is_member_call = True
|
||||
field = func_node.child_by_field_name("field")
|
||||
if field:
|
||||
callee_name = _read_text(field, source)
|
||||
elif func_node.type == "scoped_identifier":
|
||||
# Type::method() — still allow in-file EXTRACTED match, but
|
||||
# skip cross-file resolution: bare last-segment lookup ignores
|
||||
# crate boundaries and produces spurious INFERRED edges (#908).
|
||||
is_scoped_call = True
|
||||
name = func_node.child_by_field_name("name")
|
||||
if name:
|
||||
callee_name = _read_text(name, source)
|
||||
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
|
||||
tgt_nid = label_to_nid.get(callee_name)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
line = node.start_point[0] + 1
|
||||
edges.append({
|
||||
"source": caller_nid,
|
||||
"target": tgt_nid,
|
||||
"relation": "calls",
|
||||
"context": "call",
|
||||
"confidence": "EXTRACTED",
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{line}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
elif not is_scoped_call and callee_name.lower() not in _RUST_TRAIT_METHOD_BLOCKLIST:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for caller_nid, body_node in function_bodies:
|
||||
walk_calls(body_node, caller_nid)
|
||||
|
||||
valid_ids = seen_ids
|
||||
clean_edges = []
|
||||
for edge in edges:
|
||||
src, tgt = edge["source"], edge["target"]
|
||||
if src in valid_ids and (tgt in valid_ids or edge["relation"] in ("imports", "imports_from")):
|
||||
clean_edges.append(edge)
|
||||
|
||||
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
|
||||
@@ -1,92 +0,0 @@
|
||||
"""Sln extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _make_id
|
||||
|
||||
|
||||
def extract_sln(path: Path) -> dict:
|
||||
"""Extract projects and inter-project dependencies from a .sln file."""
|
||||
try:
|
||||
src = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return {"nodes": [], "edges": [], "error": f"cannot read {path}"}
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": None}]
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
seen_ids.add(file_nid)
|
||||
|
||||
_PROJECT_RE = re.compile(
|
||||
r'Project\("[^"]*"\)\s*=\s*"([^"]+)"\s*,\s*"([^"]+)"\s*,\s*"([^"]*)"'
|
||||
)
|
||||
_DEP_RE = re.compile(r'\{([0-9a-fA-F-]+)\}\s*=\s*\{([0-9a-fA-F-]+)\}')
|
||||
|
||||
guid_to_nid: dict[str, str] = {}
|
||||
|
||||
for m in _PROJECT_RE.finditer(src):
|
||||
proj_name = m.group(1)
|
||||
proj_path = m.group(2).replace("\\", "/")
|
||||
proj_guid = m.group(3).strip("{}")
|
||||
|
||||
# A solution folder is a VIRTUAL grouping, not a file: Visual Studio writes
|
||||
# its name as both the display name and the "path" (proj_name == proj_path,
|
||||
# no real file). Resolving it to an absolute path and keying the node id off
|
||||
# that leaked the absolute scan path (incl. the OS username) into graph.json,
|
||||
# because the CLI's id-relativization only remaps ids of real files in the
|
||||
# scan set — a virtual folder never matches, so its absolute id survived
|
||||
# (#1789). Use the folder name itself (relative, no filesystem resolution).
|
||||
is_solution_folder = proj_path == proj_name
|
||||
if is_solution_folder:
|
||||
abs_proj = proj_name
|
||||
else:
|
||||
try:
|
||||
abs_proj = str((path.parent / proj_path).resolve())
|
||||
except Exception:
|
||||
abs_proj = proj_path
|
||||
proj_nid = _make_id(abs_proj)
|
||||
if proj_nid and proj_nid not in seen_ids:
|
||||
seen_ids.add(proj_nid)
|
||||
nodes.append({"id": proj_nid, "label": proj_name,
|
||||
"file_type": "code", "source_file": abs_proj,
|
||||
"source_location": None})
|
||||
edges.append({"source": file_nid, "target": proj_nid,
|
||||
"relation": "contains", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "weight": 1.0})
|
||||
if proj_guid:
|
||||
guid_to_nid[proj_guid.lower()] = proj_nid
|
||||
|
||||
in_dep_section = False
|
||||
current_proj_guid: str | None = None
|
||||
_PROJECT_LINE_RE = re.compile(r'Project\("[^"]*"\)\s*=\s*"[^"]+"\s*,\s*"[^"]+"\s*,\s*"\{([^}]+)\}"')
|
||||
for line in src.splitlines():
|
||||
proj_line_m = _PROJECT_LINE_RE.search(line)
|
||||
if proj_line_m:
|
||||
current_proj_guid = proj_line_m.group(1).lower()
|
||||
continue
|
||||
if line.strip() == "EndProject":
|
||||
current_proj_guid = None
|
||||
continue
|
||||
if "ProjectSection(ProjectDependencies)" in line:
|
||||
in_dep_section = True
|
||||
continue
|
||||
if in_dep_section and "EndProjectSection" in line:
|
||||
in_dep_section = False
|
||||
continue
|
||||
if in_dep_section and current_proj_guid:
|
||||
dep_m = _DEP_RE.search(line)
|
||||
if dep_m:
|
||||
to_guid = dep_m.group(1).lower()
|
||||
from_nid = guid_to_nid.get(current_proj_guid)
|
||||
to_nid = guid_to_nid.get(to_guid)
|
||||
if from_nid and to_nid and from_nid != to_nid:
|
||||
edges.append({"source": from_nid, "target": to_nid,
|
||||
"relation": "imports", "confidence": "EXTRACTED",
|
||||
"source_file": str_path, "weight": 1.0})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,276 +0,0 @@
|
||||
"""Sql extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _file_stem, _make_id
|
||||
|
||||
|
||||
def extract_sql(path: Path, content: str | bytes | None = None) -> dict:
|
||||
"""Extract tables, views, functions, and relationships from .sql files via tree-sitter."""
|
||||
try:
|
||||
import tree_sitter_sql as tssql
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_sql not installed. Run: pip install tree-sitter-sql"}
|
||||
|
||||
try:
|
||||
language = Language(tssql.language())
|
||||
parser = Parser(language)
|
||||
source = (
|
||||
content.encode("utf-8") if isinstance(content, str)
|
||||
else content if content is not None
|
||||
else path.read_bytes()
|
||||
)
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
file_nid = _make_id(str_path)
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": None}]
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = {file_nid}
|
||||
table_nids: dict[str, str] = {} # name → nid for reference resolution
|
||||
|
||||
def _read(n) -> str:
|
||||
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
|
||||
|
||||
def _obj_name(n) -> str | None:
|
||||
for c in n.children:
|
||||
if c.type == "object_reference":
|
||||
return _read(c)
|
||||
return None
|
||||
|
||||
def _add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
edges.append({"source": file_nid, "target": nid, "relation": "contains",
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0})
|
||||
|
||||
def _add_edge(src: str, tgt: str, relation: str, line: int) -> None:
|
||||
edges.append({"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0})
|
||||
|
||||
def walk(node) -> None:
|
||||
t = node.type
|
||||
line = node.start_point[0] + 1
|
||||
|
||||
if t == "create_table":
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, name, line)
|
||||
table_nids[name.lower()] = nid
|
||||
# Foreign key REFERENCES
|
||||
for col in node.children:
|
||||
if col.type == "column_definitions":
|
||||
has_error = any(cd.type == "ERROR" for cd in col.children)
|
||||
seen_refs: set[str] = set()
|
||||
for cd in col.children:
|
||||
if cd.type == "column_definition":
|
||||
# Inline column-level REFERENCES
|
||||
ref_name: str | None = None
|
||||
found_ref = False
|
||||
for cc in cd.children:
|
||||
if cc.type == "keyword_references":
|
||||
found_ref = True
|
||||
elif found_ref and cc.type == "object_reference":
|
||||
ref_name = _read(cc)
|
||||
break
|
||||
if ref_name:
|
||||
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
|
||||
_add_edge(nid, ref_nid, "references", line)
|
||||
seen_refs.add(ref_name.lower())
|
||||
elif cd.type == "constraints":
|
||||
# Table-level FOREIGN KEY ... REFERENCES ... constraints
|
||||
for constraint in cd.children:
|
||||
if constraint.type != "constraint":
|
||||
continue
|
||||
ref_name = None
|
||||
found_ref = False
|
||||
for cc in constraint.children:
|
||||
if cc.type == "keyword_references":
|
||||
found_ref = True
|
||||
elif found_ref and cc.type == "object_reference":
|
||||
ref_name = _read(cc)
|
||||
break
|
||||
if ref_name:
|
||||
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
|
||||
_add_edge(nid, ref_nid, "references", line)
|
||||
seen_refs.add(ref_name.lower())
|
||||
if has_error:
|
||||
# Dialect-specific syntax (e.g. Firebird COMPUTED BY) causes ERROR
|
||||
# nodes that make the parser drop the trailing constraints block.
|
||||
# Regex-scan the raw column_definitions text as fallback.
|
||||
col_text = _read(col)
|
||||
for rm in re.finditer(r"\bREFERENCES\s+([\w$]+)", col_text, re.IGNORECASE):
|
||||
ref_name = rm.group(1)
|
||||
if ref_name.lower() not in seen_refs:
|
||||
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
|
||||
_add_edge(nid, ref_nid, "references", line)
|
||||
seen_refs.add(ref_name.lower())
|
||||
|
||||
elif t == "create_view":
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, name, line)
|
||||
table_nids[name.lower()] = nid
|
||||
# FROM/JOIN table references inside view body
|
||||
_walk_from_refs(node, nid, line)
|
||||
|
||||
elif t == "create_function":
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, f"{name}()", line)
|
||||
_walk_from_refs(node, nid, line)
|
||||
|
||||
elif t == "create_procedure":
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
nid = _make_id(stem, name)
|
||||
_add_node(nid, f"{name}()", line)
|
||||
_walk_from_refs(node, nid, line)
|
||||
|
||||
elif t == "alter_table":
|
||||
name = _obj_name(node)
|
||||
if name:
|
||||
src_nid = table_nids.get(name.lower())
|
||||
if not src_nid:
|
||||
src_nid = _make_id(stem, name)
|
||||
_add_node(src_nid, name, line)
|
||||
table_nids[name.lower()] = src_nid
|
||||
for child in node.children:
|
||||
if child.type == "add_constraint":
|
||||
for cc in child.children:
|
||||
if cc.type != "constraint":
|
||||
continue
|
||||
found_ref = False
|
||||
ref_name: str | None = None
|
||||
for ccc in cc.children:
|
||||
if ccc.type == "keyword_references":
|
||||
found_ref = True
|
||||
elif found_ref and ccc.type == "object_reference":
|
||||
ref_name = _read(ccc)
|
||||
break
|
||||
if ref_name:
|
||||
ref_nid = table_nids.get(ref_name.lower())
|
||||
if not ref_nid:
|
||||
ref_nid = _make_id(stem, ref_name)
|
||||
_add_edge(src_nid, ref_nid, "references", line)
|
||||
|
||||
elif t == "create_trigger":
|
||||
trig_name: str | None = None
|
||||
tbl_name: str | None = None
|
||||
after_trigger = False
|
||||
after_for = False
|
||||
for c in node.children:
|
||||
if c.type == "keyword_trigger":
|
||||
after_trigger = True
|
||||
elif after_trigger and not trig_name and c.type == "object_reference":
|
||||
trig_name = _read(c)
|
||||
elif c.type == "keyword_for":
|
||||
after_for = True
|
||||
elif after_for and not tbl_name and c.type == "object_reference":
|
||||
tbl_name = _read(c)
|
||||
if trig_name:
|
||||
trig_nid = _make_id(stem, trig_name)
|
||||
_add_node(trig_nid, trig_name, line)
|
||||
if tbl_name:
|
||||
tbl_nid = table_nids.get(tbl_name.lower()) or _make_id(stem, tbl_name)
|
||||
_add_edge(trig_nid, tbl_nid, "triggers", line)
|
||||
|
||||
elif t == "fb_proc_or_trigger":
|
||||
text = _read(node)
|
||||
m = re.match(
|
||||
r"CREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?"
|
||||
r"(PROCEDURE|TRIGGER|FUNCTION)\s+([\w$]+)",
|
||||
text, re.IGNORECASE,
|
||||
)
|
||||
if m:
|
||||
obj_type = m.group(1).upper()
|
||||
obj_name = m.group(2)
|
||||
obj_nid = _make_id(stem, obj_name)
|
||||
label = obj_name if obj_type == "TRIGGER" else f"{obj_name}()"
|
||||
_add_node(obj_nid, label, line)
|
||||
if obj_type == "TRIGGER":
|
||||
fm = re.search(r"\bFOR\s+([\w$]+)", text, re.IGNORECASE)
|
||||
if fm:
|
||||
tbl = fm.group(1)
|
||||
tbl_nid = table_nids.get(tbl.lower()) or _make_id(stem, tbl)
|
||||
_add_edge(obj_nid, tbl_nid, "triggers", line)
|
||||
_NON_TABLES = {
|
||||
"select", "where", "set", "dual", "null", "true", "false",
|
||||
"first", "skip", "rows", "next", "only", "lateral",
|
||||
}
|
||||
seen_tbls: set[str] = set()
|
||||
for rm in re.finditer(r"\b(?:FROM|JOIN|INTO)\s+([\w$]+)", text, re.IGNORECASE):
|
||||
tbl = rm.group(1)
|
||||
if tbl.lower() not in _NON_TABLES and tbl.lower() not in seen_tbls:
|
||||
seen_tbls.add(tbl.lower())
|
||||
tbl_nid = table_nids.get(tbl.lower()) or _make_id(stem, tbl)
|
||||
_add_edge(obj_nid, tbl_nid, "reads_from", line)
|
||||
for rm in re.finditer(r"\bUPDATE\s+([\w$]+)", text, re.IGNORECASE):
|
||||
tbl = rm.group(1)
|
||||
if tbl.lower() not in _NON_TABLES and tbl.lower() not in seen_tbls:
|
||||
seen_tbls.add(tbl.lower())
|
||||
tbl_nid = table_nids.get(tbl.lower()) or _make_id(stem, tbl)
|
||||
_add_edge(obj_nid, tbl_nid, "reads_from", line)
|
||||
|
||||
for child in node.children:
|
||||
walk(child)
|
||||
|
||||
def _walk_from_refs(node, caller_nid: str, line: int) -> None:
|
||||
"""Recursively find FROM/JOIN table references inside a node."""
|
||||
if node.type in ("from", "join"):
|
||||
for c in node.children:
|
||||
if c.type == "relation":
|
||||
for cc in c.children:
|
||||
if cc.type == "object_reference":
|
||||
tbl = _read(cc)
|
||||
tbl_nid = _make_id(stem, tbl)
|
||||
_add_edge(caller_nid, tbl_nid, "reads_from",
|
||||
c.start_point[0] + 1)
|
||||
for child in node.children:
|
||||
_walk_from_refs(child, caller_nid, line)
|
||||
|
||||
for stmt in root.children:
|
||||
if stmt.type == "statement":
|
||||
for child in stmt.children:
|
||||
walk(child)
|
||||
elif stmt.type in ("fb_proc_or_trigger", "set_term", "declare_external_function"):
|
||||
walk(stmt)
|
||||
|
||||
# Global regex fallback: catch any REFERENCES missed due to ERROR nodes in the parse tree
|
||||
# (e.g. Firebird COMPUTED BY columns push constraints out of the tree entirely).
|
||||
# Snapshot after tree walk so we don't re-emit edges already captured above.
|
||||
emitted = {(e["source"], e["target"]) for e in edges if e["relation"] == "references"}
|
||||
src_text = source.decode("utf-8", errors="replace")
|
||||
for m in re.finditer(r"CREATE\s+TABLE\s+([\w$]+)\s*\(", src_text, re.IGNORECASE):
|
||||
tbl_name = m.group(1)
|
||||
tbl_nid = table_nids.get(tbl_name.lower())
|
||||
if tbl_nid is None:
|
||||
continue
|
||||
tbl_line = src_text[: m.start()].count("\n") + 1
|
||||
tail = src_text[m.start():]
|
||||
end = re.search(r"(?:^|\n)(?:CREATE|SET\s+TERM|ALTER)\s", tail[1:], re.IGNORECASE)
|
||||
block = tail[: end.start() + 1] if end else tail
|
||||
for rm in re.finditer(r"\bREFERENCES\s+([\w$]+)", block, re.IGNORECASE):
|
||||
ref_name = rm.group(1)
|
||||
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
|
||||
if (tbl_nid, ref_nid) not in emitted:
|
||||
_add_edge(tbl_nid, ref_nid, "references", tbl_line)
|
||||
emitted.add((tbl_nid, ref_nid))
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,181 +0,0 @@
|
||||
"""Terraform extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _make_id
|
||||
|
||||
|
||||
_TF_META_HEADS = frozenset({"count", "each", "self", "path", "terraform"})
|
||||
|
||||
def extract_terraform(path: Path) -> dict:
|
||||
"""Extract Terraform/HCL blocks and the references between them via tree-sitter.
|
||||
|
||||
Nodes: resources, data sources, modules, variables, outputs, providers, and
|
||||
locals. Edges: `contains` (file -> block), `references` (block -> the blocks
|
||||
it interpolates, e.g. `aws_instance.web` -> `var.region`), and `depends_on`
|
||||
(explicit dependency edges).
|
||||
|
||||
Node IDs are scoped by the parent directory, not the file stem, because
|
||||
Terraform resources are module(directory)-scoped: a resource defined in
|
||||
main.tf is referenced from other .tf files in the same directory. Directory
|
||||
scoping lets those cross-file references resolve when per-file extractions
|
||||
are merged (stem scoping would split a definition from its references).
|
||||
"""
|
||||
try:
|
||||
import tree_sitter_hcl as tshcl
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_hcl not installed. Run: pip install tree-sitter-hcl"}
|
||||
|
||||
try:
|
||||
language = Language(tshcl.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
str_path = str(path)
|
||||
file_nid = _make_id(str_path)
|
||||
scope = path.parent.name or "tf"
|
||||
|
||||
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
|
||||
"source_file": str_path, "source_location": None}]
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = {file_nid}
|
||||
seen_edges: set[tuple[str, str, str]] = set()
|
||||
|
||||
def _read(n) -> str:
|
||||
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
|
||||
|
||||
def _label_text(n) -> str:
|
||||
return _read(n).strip().strip('"')
|
||||
|
||||
def _add_node(address: str, label: str, line: int) -> str:
|
||||
nid = _make_id(scope, address)
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
edges.append({"source": file_nid, "target": nid, "relation": "contains",
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0})
|
||||
return nid
|
||||
|
||||
def _add_edge(src: str, address: str, relation: str, line: int) -> None:
|
||||
tgt = _make_id(scope, address)
|
||||
if src == tgt:
|
||||
return
|
||||
key = (src, tgt, relation)
|
||||
if key in seen_edges:
|
||||
return
|
||||
seen_edges.add(key)
|
||||
edges.append({"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": 1.0})
|
||||
|
||||
def _block_parts(block) -> tuple:
|
||||
btype = None
|
||||
labels: list[str] = []
|
||||
for c in block.children:
|
||||
if c.type in ("block_start", "body", "block_end"):
|
||||
break
|
||||
if c.type == "identifier" and btype is None:
|
||||
btype = _read(c)
|
||||
elif c.type in ("string_lit", "identifier"):
|
||||
labels.append(_label_text(c))
|
||||
return btype, labels
|
||||
|
||||
def _ref_address(expr):
|
||||
head = _read(expr)
|
||||
parent = expr.parent
|
||||
attrs: list[str] = []
|
||||
if parent is not None:
|
||||
seen_self = False
|
||||
for c in parent.children:
|
||||
if c.id == expr.id:
|
||||
seen_self = True
|
||||
continue
|
||||
if seen_self and c.type == "get_attr":
|
||||
name = None
|
||||
for gc in c.children:
|
||||
if gc.type == "identifier":
|
||||
name = _read(gc)
|
||||
break
|
||||
if name is None:
|
||||
break
|
||||
attrs.append(name)
|
||||
elif seen_self and c.type not in ("get_attr",):
|
||||
break
|
||||
if head in _TF_META_HEADS or not head:
|
||||
return None
|
||||
if head == "var":
|
||||
return f"var.{attrs[0]}" if attrs else None
|
||||
if head == "local":
|
||||
return f"local.{attrs[0]}" if attrs else None
|
||||
if head == "module":
|
||||
return f"module.{attrs[0]}" if attrs else None
|
||||
if head == "data":
|
||||
return f"data.{attrs[0]}.{attrs[1]}" if len(attrs) >= 2 else None
|
||||
return f"{head}.{attrs[0]}" if attrs else None
|
||||
|
||||
def _collect_refs(node, owner_nid: str, relation: str) -> None:
|
||||
rel = relation
|
||||
if node.type == "attribute":
|
||||
key_node = node.child_by_field_name("key") or (
|
||||
node.children[0] if node.children else None
|
||||
)
|
||||
if key_node is not None and _read(key_node) == "depends_on":
|
||||
rel = "depends_on"
|
||||
if node.type == "variable_expr":
|
||||
addr = _ref_address(node)
|
||||
if addr:
|
||||
_add_edge(owner_nid, addr, rel, node.start_point[0] + 1)
|
||||
for c in node.children:
|
||||
if c.is_named:
|
||||
_collect_refs(c, owner_nid, rel)
|
||||
|
||||
def _body_of(block):
|
||||
for c in block.children:
|
||||
if c.type == "body":
|
||||
return c
|
||||
return None
|
||||
|
||||
body = next((c for c in root.children if c.type == "body"), root)
|
||||
for block in body.children:
|
||||
if block.type != "block":
|
||||
continue
|
||||
btype, labels = _block_parts(block)
|
||||
line = block.start_point[0] + 1
|
||||
blk_body = _body_of(block)
|
||||
if btype == "resource" and len(labels) >= 2:
|
||||
owner = _add_node(f"{labels[0]}.{labels[1]}", f"{labels[0]}.{labels[1]}", line)
|
||||
elif btype == "data" and len(labels) >= 2:
|
||||
owner = _add_node(f"data.{labels[0]}.{labels[1]}", f"data.{labels[0]}.{labels[1]}", line)
|
||||
elif btype == "module" and labels:
|
||||
owner = _add_node(f"module.{labels[0]}", f"module.{labels[0]}", line)
|
||||
elif btype == "variable" and labels:
|
||||
owner = _add_node(f"var.{labels[0]}", f"var.{labels[0]}", line)
|
||||
elif btype == "output" and labels:
|
||||
owner = _add_node(f"output.{labels[0]}", f"output.{labels[0]}", line)
|
||||
elif btype == "provider" and labels:
|
||||
owner = _add_node(f"provider.{labels[0]}", f"provider.{labels[0]}", line)
|
||||
elif btype == "locals" and blk_body is not None:
|
||||
for attr in blk_body.children:
|
||||
if attr.type != "attribute":
|
||||
continue
|
||||
key_node = attr.children[0] if attr.children else None
|
||||
if key_node is None:
|
||||
continue
|
||||
key = _read(key_node)
|
||||
lnid = _add_node(f"local.{key}", f"local.{key}", attr.start_point[0] + 1)
|
||||
_collect_refs(attr, lnid, "references")
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
if blk_body is not None:
|
||||
_collect_refs(blk_body, owner, "references")
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,329 +0,0 @@
|
||||
"""Verilog extractor. Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
def _sv_first_identifier(node, source: bytes) -> str | None:
|
||||
"""First `simple_identifier` under node in pre-order, or None.
|
||||
|
||||
tree-sitter-verilog 1.0.3 nests declaration names a few levels deep instead
|
||||
of exposing a `name` field. Scope the search to the right child node (e.g.
|
||||
`function_identifier`) or this returns the return-type instead of the name.
|
||||
"""
|
||||
if node is None:
|
||||
return None
|
||||
for child in node.children:
|
||||
if child.type == "simple_identifier":
|
||||
return _read_text(child, source)
|
||||
found = _sv_first_identifier(child, source)
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
def _sv_child(node, type_name: str) -> object | None:
|
||||
if node is None:
|
||||
return None
|
||||
for child in node.children:
|
||||
if child.type == type_name:
|
||||
return child
|
||||
return None
|
||||
|
||||
_SV_BUILTIN_TYPES = frozenset({
|
||||
"bit", "logic", "reg", "wire", "int", "integer", "shortint", "longint",
|
||||
"byte", "time", "real", "shortreal", "void", "string", "type", "event",
|
||||
"mailbox", "semaphore", "process", "chandle",
|
||||
})
|
||||
|
||||
_SV_NON_TYPE_WORDS = frozenset({
|
||||
"return", "if", "else", "for", "foreach", "while", "case", "begin", "end",
|
||||
"function", "task", "class", "endclass", "endfunction", "endtask",
|
||||
})
|
||||
|
||||
_SV_PARENS_INNER = r"(?:[^()]|\([^()]*\))*"
|
||||
|
||||
_SV_PARENS = r"\(" + _SV_PARENS_INNER + r"\)"
|
||||
|
||||
_SV_FUNC_RE = re.compile(
|
||||
r"\bfunction\s+([A-Za-z_]\w*(?:\s*#\s*" + _SV_PARENS + r")?)\s+(\w+)\s*"
|
||||
r"\((" + _SV_PARENS_INNER + r")\)\s*;",
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
_SV_PARAM_RE = re.compile(
|
||||
r"\s*(?:input|output|inout|ref|const\s+ref)?\s*"
|
||||
r"([A-Za-z_]\w*(?:\s*#\s*" + _SV_PARENS + r")?)\s+\w+"
|
||||
)
|
||||
|
||||
def _sv_strip_comments(text: str) -> str:
|
||||
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
|
||||
return re.sub(r"//.*", "", text)
|
||||
|
||||
def _sv_split_type_list(text: str) -> list[str]:
|
||||
parts: list[str] = []
|
||||
depth = 0
|
||||
start = 0
|
||||
for idx, ch in enumerate(text):
|
||||
if ch == "(":
|
||||
depth += 1
|
||||
elif ch == ")":
|
||||
depth = max(0, depth - 1)
|
||||
elif ch == "," and depth == 0:
|
||||
item = text[start:idx].strip()
|
||||
if item:
|
||||
parts.append(item)
|
||||
start = idx + 1
|
||||
item = text[start:].strip()
|
||||
if item:
|
||||
parts.append(item)
|
||||
return parts
|
||||
|
||||
def _sv_collect_type_refs(type_text: str, generic: bool = False,
|
||||
skip: frozenset[str] = frozenset()) -> list[tuple[str, str]]:
|
||||
refs: list[tuple[str, str]] = []
|
||||
text = type_text.strip()
|
||||
if not text:
|
||||
return refs
|
||||
head = re.match(r"([A-Za-z_]\w*)", text)
|
||||
if head:
|
||||
name = head.group(1)
|
||||
# `skip` carries the enclosing class's `#(type T = ...)` parameters so
|
||||
# they are not mistaken for referenced types.
|
||||
if name not in _SV_BUILTIN_TYPES and name not in _SV_NON_TYPE_WORDS and name not in skip:
|
||||
refs.append((name, "generic_arg" if generic else "type"))
|
||||
params = re.search(r"#\s*\((" + _SV_PARENS_INNER + r")\)", text)
|
||||
if params:
|
||||
for arg in _sv_split_type_list(params.group(1)):
|
||||
refs.extend(_sv_collect_type_refs(arg, generic=True, skip=skip))
|
||||
return refs
|
||||
|
||||
def _augment_systemverilog_semantics(
|
||||
raw: str,
|
||||
stem: str,
|
||||
str_path: str,
|
||||
file_nid: str,
|
||||
nodes: list[dict],
|
||||
edges: list[dict],
|
||||
seen_ids: set[str],
|
||||
) -> None:
|
||||
label_to_nid = {node["label"]: node["id"] for node in nodes}
|
||||
|
||||
def line_for(offset: int) -> int:
|
||||
return raw.count("\n", 0, offset) + 1
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
"confidence_score": 1.0})
|
||||
label_to_nid[label] = nid
|
||||
|
||||
def ensure_type(label: str, line: int) -> str:
|
||||
if label in label_to_nid:
|
||||
return label_to_nid[label]
|
||||
nid = _make_id(stem, label)
|
||||
add_node(nid, label, line)
|
||||
return nid
|
||||
|
||||
def add_edge(src: str, target_label: str, relation: str, line: int, context: str | None = None) -> None:
|
||||
tgt = ensure_type(target_label, line)
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str_path, "source_location": f"L{line}", "weight": 1.0}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
text = _sv_strip_comments(raw)
|
||||
# Consuming `endclass` (rather than a lookahead) makes each match own its
|
||||
# terminator, so back-to-back or malformed classes cannot bleed bodies.
|
||||
class_re = re.compile(
|
||||
r"\b(?:(interface)\s+)?class\s+(\w+)([^;{]*)\s*;(.*?)\bendclass\b",
|
||||
re.DOTALL,
|
||||
)
|
||||
for match in class_re.finditer(text):
|
||||
class_name = match.group(2)
|
||||
header = match.group(3) or ""
|
||||
body = match.group(4) or ""
|
||||
line = line_for(match.start())
|
||||
# `#(type T = Payload)` declares `T` as a class type parameter, not a
|
||||
# referenced type — collect these to skip below.
|
||||
type_params = frozenset(re.findall(r"\btype\s+(\w+)", header))
|
||||
class_nid = _make_id(stem, class_name)
|
||||
add_node(class_nid, class_name, line)
|
||||
edges.append({"source": file_nid, "target": class_nid, "relation": "defines",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str_path, "source_location": f"L{line}", "weight": 1.0})
|
||||
|
||||
ext = re.search(r"\bextends\s+(\w+)", header)
|
||||
if ext:
|
||||
add_edge(class_nid, ext.group(1), "inherits", line)
|
||||
impl = re.search(r"\bimplements\s+([^;{]+)", header)
|
||||
if impl:
|
||||
for iface_name in _sv_split_type_list(impl.group(1)):
|
||||
add_edge(class_nid, iface_name.split("#", 1)[0].strip(), "implements", line)
|
||||
|
||||
body_without_functions = re.sub(
|
||||
r"\bfunction\b.*?\bendfunction\b",
|
||||
lambda m: "\n" * m.group(0).count("\n"),
|
||||
body,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
# Optional leading class-property qualifiers (rand/local/protected/etc.)
|
||||
# must be consumed: otherwise a qualified field like `rand Config x;`
|
||||
# (three tokens) fails the `<type> <name>;` shape and its type reference
|
||||
# is silently dropped.
|
||||
for field in re.finditer(r"^\s*(?:(?:rand|randc|local|protected|static|const|automatic|var)\s+)*([A-Za-z_]\w*(?:\s*#\s*\([^;]+?\))?)\s+\w+\s*;", body_without_functions, re.MULTILINE):
|
||||
# Count to the start of the type token (group 1), not the match
|
||||
# start: `^\s*` consumes the leading newline(s), so field.start()
|
||||
# would resolve to the class's line instead of the field's.
|
||||
field_line = line + body_without_functions.count("\n", 0, field.start(1))
|
||||
for ref_name, role in _sv_collect_type_refs(field.group(1), skip=type_params):
|
||||
add_edge(class_nid, ref_name, "references", field_line, "generic_arg" if role == "generic_arg" else "field")
|
||||
|
||||
for fm in _SV_FUNC_RE.finditer(body):
|
||||
return_type, func_name, params = fm.group(1), fm.group(2), fm.group(3)
|
||||
func_line = line + body.count("\n", 0, fm.start())
|
||||
func_nid = _make_id(class_nid, func_name)
|
||||
add_node(func_nid, func_name, func_line)
|
||||
edges.append({"source": class_nid, "target": func_nid, "relation": "method",
|
||||
"confidence": "EXTRACTED", "confidence_score": 1.0,
|
||||
"source_file": str_path, "source_location": f"L{func_line}", "weight": 1.0})
|
||||
for ref_name, role in _sv_collect_type_refs(return_type, skip=type_params):
|
||||
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "return_type")
|
||||
for param in _sv_split_type_list(params):
|
||||
pm = _SV_PARAM_RE.match(param)
|
||||
if not pm:
|
||||
continue
|
||||
for ref_name, role in _sv_collect_type_refs(pm.group(1), skip=type_params):
|
||||
add_edge(func_nid, ref_name, "references", func_line, "generic_arg" if role == "generic_arg" else "parameter_type")
|
||||
|
||||
def extract_verilog(path: Path) -> dict:
|
||||
"""Extract modules, functions, tasks, package imports, instantiations, and
|
||||
SystemVerilog class semantics (inherits/implements edges, field/parameter/
|
||||
return-type references) from .v/.sv files."""
|
||||
try:
|
||||
import tree_sitter_verilog as tsverilog
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_verilog not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tsverilog.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}",
|
||||
"confidence_score": 1.0})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", score: float = 1.0) -> None:
|
||||
edges.append({"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "confidence_score": score,
|
||||
"source_file": str_path, "source_location": f"L{line}", "weight": 1.0})
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def walk(node, module_nid: str | None = None) -> None:
|
||||
t = node.type
|
||||
|
||||
# SystemVerilog class bodies are handled by _augment_systemverilog_semantics
|
||||
# (regex over source text). Skip their subtrees so in-class methods are not
|
||||
# double-emitted here — and with the wrong, return-type-derived name.
|
||||
if t in ("class_declaration", "interface_class_declaration"):
|
||||
return
|
||||
|
||||
if t == "module_declaration":
|
||||
mod_name = _sv_first_identifier(_sv_child(node, "module_header"), source)
|
||||
if mod_name:
|
||||
line = node.start_point[0] + 1
|
||||
nid = _make_id(stem, mod_name)
|
||||
add_node(nid, mod_name, line)
|
||||
add_edge(file_nid, nid, "defines", line)
|
||||
for child in node.children:
|
||||
walk(child, nid)
|
||||
return
|
||||
|
||||
# `function_prototype` only appears inside class/interface-class bodies
|
||||
# (skipped above) and nests its name differently; it is intentionally not
|
||||
# handled here.
|
||||
elif t == "function_declaration":
|
||||
fn_body = _sv_child(node, "function_body_declaration")
|
||||
func_name = _sv_first_identifier(_sv_child(fn_body, "function_identifier"), source)
|
||||
if func_name:
|
||||
line = node.start_point[0] + 1
|
||||
parent = module_nid or file_nid
|
||||
nid = _make_id(parent, func_name)
|
||||
add_node(nid, f"{func_name}()", line)
|
||||
add_edge(parent, nid, "contains", line)
|
||||
|
||||
elif t == "task_declaration":
|
||||
tk_body = _sv_child(node, "task_body_declaration")
|
||||
task_name = _sv_first_identifier(_sv_child(tk_body, "task_identifier"), source)
|
||||
if task_name:
|
||||
line = node.start_point[0] + 1
|
||||
parent = module_nid or file_nid
|
||||
nid = _make_id(parent, task_name)
|
||||
add_node(nid, task_name, line)
|
||||
add_edge(parent, nid, "contains", line)
|
||||
|
||||
elif t == "package_import_declaration":
|
||||
for child in node.children:
|
||||
if child.type == "package_import_item":
|
||||
pkg_text = _read_text(child, source)
|
||||
pkg_name = pkg_text.split("::")[0].strip()
|
||||
if pkg_name:
|
||||
line = node.start_point[0] + 1
|
||||
tgt_nid = _make_id(pkg_name)
|
||||
add_node(tgt_nid, pkg_name, line)
|
||||
src_nid = module_nid or file_nid
|
||||
add_edge(src_nid, tgt_nid, "imports_from", line)
|
||||
|
||||
elif t in ("module_instantiation", "checker_instantiation"):
|
||||
# `leaf u_leaf();` parses as checker_instantiation in 1.0.3;
|
||||
# module_instantiation (when it occurs) exposes a `module_type` field.
|
||||
# Both reduce to the first identifier under the node — the instantiated
|
||||
# type, not the instance name (which appears later).
|
||||
if module_nid:
|
||||
type_node = node.child_by_field_name("module_type")
|
||||
inst_type = (_read_text(type_node, source).strip() if type_node
|
||||
else _sv_first_identifier(node, source))
|
||||
if inst_type:
|
||||
line = node.start_point[0] + 1
|
||||
tgt_nid = _make_id(inst_type)
|
||||
add_node(tgt_nid, inst_type, line)
|
||||
add_edge(module_nid, tgt_nid, "instantiates", line)
|
||||
|
||||
for child in node.children:
|
||||
walk(child, module_nid)
|
||||
|
||||
walk(root)
|
||||
_augment_systemverilog_semantics(
|
||||
source.decode("utf-8", errors="replace"),
|
||||
stem,
|
||||
str_path,
|
||||
file_nid,
|
||||
nodes,
|
||||
edges,
|
||||
seen_ids,
|
||||
)
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
@@ -1,175 +0,0 @@
|
||||
"""Zig extractor (tree-sitter). Moved verbatim from graphify/extract.py."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_text
|
||||
|
||||
|
||||
def extract_zig(path: Path) -> dict:
|
||||
"""Extract functions, structs, enums, unions, and imports from a .zig file."""
|
||||
try:
|
||||
import tree_sitter_zig as tszig
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return {"nodes": [], "edges": [], "error": "tree_sitter_zig not installed"}
|
||||
|
||||
try:
|
||||
language = Language(tszig.language())
|
||||
parser = Parser(language)
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
root = tree.root_node
|
||||
except Exception as e:
|
||||
return {"nodes": [], "edges": [], "error": str(e)}
|
||||
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
nodes: list[dict] = []
|
||||
edges: list[dict] = []
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
context: str | None = None) -> None:
|
||||
edge = {"source": src, "target": tgt, "relation": relation,
|
||||
"confidence": confidence, "source_file": str_path,
|
||||
"source_location": f"L{line}", "weight": weight}
|
||||
if context:
|
||||
edge["context"] = context
|
||||
edges.append(edge)
|
||||
|
||||
file_nid = _make_id(str(path))
|
||||
add_node(file_nid, path.name, 1)
|
||||
|
||||
def _extract_import(node) -> None:
|
||||
for child in node.children:
|
||||
if child.type == "builtin_function":
|
||||
bi = None
|
||||
args = None
|
||||
for c in child.children:
|
||||
if c.type == "builtin_identifier":
|
||||
bi = _read_text(c, source)
|
||||
elif c.type == "arguments":
|
||||
args = c
|
||||
if bi in ("@import", "@cImport") and args:
|
||||
for arg in args.children:
|
||||
if arg.type in ("string_literal", "string"):
|
||||
raw = _read_text(arg, source).strip('"')
|
||||
module_name = raw.split("/")[-1].split(".")[0]
|
||||
if module_name:
|
||||
tgt_nid = _make_id(module_name)
|
||||
add_edge(file_nid, tgt_nid, "imports_from",
|
||||
node.start_point[0] + 1)
|
||||
return
|
||||
elif child.type == "field_expression":
|
||||
_extract_import(child)
|
||||
return
|
||||
|
||||
def walk(node, parent_struct_nid: str | None = None) -> None:
|
||||
t = node.type
|
||||
|
||||
if t == "function_declaration":
|
||||
name_node = node.child_by_field_name("name")
|
||||
if name_node:
|
||||
func_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
if parent_struct_nid:
|
||||
func_nid = _make_id(parent_struct_nid, func_name)
|
||||
add_node(func_nid, f".{func_name}()", line)
|
||||
add_edge(parent_struct_nid, func_nid, "method", line)
|
||||
else:
|
||||
func_nid = _make_id(stem, func_name)
|
||||
add_node(func_nid, f"{func_name}()", line)
|
||||
add_edge(file_nid, func_nid, "contains", line)
|
||||
body = node.child_by_field_name("body")
|
||||
if body:
|
||||
function_bodies.append((func_nid, body))
|
||||
return
|
||||
|
||||
if t == "variable_declaration":
|
||||
name_node = None
|
||||
value_node = None
|
||||
for child in node.children:
|
||||
if child.type == "identifier":
|
||||
name_node = child
|
||||
elif child.type in ("struct_declaration", "enum_declaration",
|
||||
"union_declaration", "builtin_function",
|
||||
"field_expression"):
|
||||
value_node = child
|
||||
|
||||
if value_node and value_node.type == "struct_declaration":
|
||||
if name_node:
|
||||
struct_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
struct_nid = _make_id(stem, struct_name)
|
||||
add_node(struct_nid, struct_name, line)
|
||||
add_edge(file_nid, struct_nid, "contains", line)
|
||||
for child in value_node.children:
|
||||
walk(child, parent_struct_nid=struct_nid)
|
||||
return
|
||||
|
||||
if value_node and value_node.type in ("enum_declaration", "union_declaration"):
|
||||
if name_node:
|
||||
type_name = _read_text(name_node, source)
|
||||
line = node.start_point[0] + 1
|
||||
type_nid = _make_id(stem, type_name)
|
||||
add_node(type_nid, type_name, line)
|
||||
add_edge(file_nid, type_nid, "contains", line)
|
||||
return
|
||||
|
||||
if value_node and value_node.type in ("builtin_function", "field_expression"):
|
||||
_extract_import(node)
|
||||
return
|
||||
|
||||
for child in node.children:
|
||||
walk(child, parent_struct_nid)
|
||||
|
||||
walk(root)
|
||||
|
||||
seen_call_pairs: set[tuple[str, str]] = set()
|
||||
raw_calls: list[dict] = []
|
||||
|
||||
def walk_calls(node, caller_nid: str) -> None:
|
||||
if node.type == "function_declaration":
|
||||
return
|
||||
if node.type == "call_expression":
|
||||
fn = node.child_by_field_name("function")
|
||||
if fn:
|
||||
fn_text = _read_text(fn, source)
|
||||
callee = fn_text.split(".")[-1]
|
||||
is_member_call = "." in fn_text
|
||||
tgt_nid = next((n["id"] for n in nodes if n["label"] in
|
||||
(f"{callee}()", f".{callee}()")), None)
|
||||
if tgt_nid and tgt_nid != caller_nid:
|
||||
pair = (caller_nid, tgt_nid)
|
||||
if pair not in seen_call_pairs:
|
||||
seen_call_pairs.add(pair)
|
||||
add_edge(caller_nid, tgt_nid, "calls",
|
||||
node.start_point[0] + 1,
|
||||
confidence="EXTRACTED", weight=1.0)
|
||||
elif callee:
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
|
||||
for caller_nid, body_node in function_bodies:
|
||||
walk_calls(body_node, caller_nid)
|
||||
|
||||
clean_edges = [e for e in edges if e["source"] in seen_ids and
|
||||
(e["target"] in seen_ids or e["relation"] == "imports_from")]
|
||||
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
|
||||
@@ -1,162 +0,0 @@
|
||||
"""Intra-file slicing for oversized text documents (#1369).
|
||||
|
||||
The extraction packer (`_pack_chunks_by_tokens`) treats each file as atomic and
|
||||
`_read_files` caps every file at ``_FILE_CHAR_CAP`` characters, so a document
|
||||
larger than that cap had everything past the cap silently dropped — the model
|
||||
never saw it, and nothing in the adaptive-retry path could recover it ("a single
|
||||
file larger than the budget ... packing can't shrink one big file").
|
||||
|
||||
This module splits an oversized *splittable text* document (Markdown, plain
|
||||
text, reStructuredText) into contiguous ``FileSlice`` units at heading /
|
||||
paragraph / line boundaries so the whole file gets extracted across several
|
||||
units. Every slice of a file reports the **parent file path** as its source, so
|
||||
the resulting nodes are never fragmented per-slice — they merge by source_file
|
||||
exactly as if the file had been extracted in one pass.
|
||||
|
||||
Only plain-text documents are sliced: code files need whole-symbol context, and
|
||||
PDFs/images are read through their own extractors and have no char-offset model.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# Plain-text document types where boundary-based slicing is meaningful and where
|
||||
# `_file_to_text` is a straight ``read_text`` (so a char range matches the bytes
|
||||
# the model is shown). Deliberately excludes code (.py, .ts, ...) and binary
|
||||
# docs (.pdf) — those are never sliced.
|
||||
_SPLITTABLE_TEXT_SUFFIXES = frozenset({".md", ".mdx", ".markdown", ".txt", ".rst"})
|
||||
|
||||
# Boundary preferences, strongest first. A Markdown heading (``\n#``) keeps a
|
||||
# section with its title; a blank line keeps a paragraph intact; a bare newline
|
||||
# avoids cutting mid-line. If none is found in the window we hard-cut.
|
||||
_BOUNDARY_SEPARATORS = ("\n#", "\n\n", "\n")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileSlice:
|
||||
"""A contiguous ``[start, end)`` character range of a splittable text file.
|
||||
|
||||
``index``/``total`` are for logging only. ``path`` is the real file on disk;
|
||||
the slice always reports ``path`` as its source so slices don't fragment the
|
||||
graph.
|
||||
"""
|
||||
|
||||
path: Path
|
||||
start: int
|
||||
end: int
|
||||
index: int
|
||||
total: int
|
||||
|
||||
|
||||
# A unit of extraction work: either a whole file (``Path``) or one slice of one.
|
||||
Unit = "Path | FileSlice"
|
||||
|
||||
|
||||
def unit_path(unit: "Path | FileSlice") -> Path:
|
||||
"""The on-disk path a unit belongs to (the parent file for a slice)."""
|
||||
return unit.path if isinstance(unit, FileSlice) else unit
|
||||
|
||||
|
||||
def is_splittable_text(path: Path) -> bool:
|
||||
"""True for plain-text document types that may be sliced."""
|
||||
return path.suffix.lower() in _SPLITTABLE_TEXT_SUFFIXES
|
||||
|
||||
|
||||
def _best_cut(text: str, start: int, end: int) -> int:
|
||||
"""Return a cut index in ``(start, end]`` at the strongest nearby boundary.
|
||||
|
||||
Searches the window ``text[start:end]`` for the latest heading, then blank
|
||||
line, then newline, and returns the index just *after* it (a heading cuts
|
||||
just *before* the ``#`` so the heading leads the next slice). Falls back to a
|
||||
hard cut at ``end`` when the window has no usable boundary, which still makes
|
||||
forward progress because ``end > start``.
|
||||
"""
|
||||
window = text[start:end]
|
||||
for sep in _BOUNDARY_SEPARATORS:
|
||||
idx = window.rfind(sep)
|
||||
if idx > 0: # a boundary strictly inside the window (non-empty prev slice)
|
||||
if sep == "\n#":
|
||||
return start + idx + 1 # keep the newline with the previous slice
|
||||
return start + idx + len(sep)
|
||||
return end
|
||||
|
||||
|
||||
def slice_boundaries(text: str, max_chars: int) -> list[tuple[int, int]]:
|
||||
"""Contiguous ``(start, end)`` ranges covering all of ``text``, each ≤ max_chars.
|
||||
|
||||
Ranges are gap-free and non-overlapping, so concatenating the slices
|
||||
reproduces ``text`` exactly — no content is dropped.
|
||||
"""
|
||||
n = len(text)
|
||||
if n <= max_chars:
|
||||
return [(0, n)]
|
||||
bounds: list[tuple[int, int]] = []
|
||||
pos = 0
|
||||
while pos < n:
|
||||
hard = min(pos + max_chars, n)
|
||||
end = _best_cut(text, pos, hard) if hard < n else n
|
||||
if end <= pos: # defensive: never stall
|
||||
end = hard
|
||||
bounds.append((pos, end))
|
||||
pos = end
|
||||
return bounds
|
||||
|
||||
|
||||
def expand_oversized_files(
|
||||
files: list[Path], max_chars: int
|
||||
) -> list["Path | FileSlice"]:
|
||||
"""Replace each oversized splittable-text file with a list of ``FileSlice``s.
|
||||
|
||||
Files at or below ``max_chars`` (and all non-splittable files) pass through
|
||||
unchanged as ``Path``, so behaviour is identical for everything that already
|
||||
fit. Unreadable files pass through untouched (the reader handles the error).
|
||||
"""
|
||||
out: list["Path | FileSlice"] = []
|
||||
for f in files:
|
||||
if not is_splittable_text(f):
|
||||
out.append(f)
|
||||
continue
|
||||
try:
|
||||
text = f.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
out.append(f)
|
||||
continue
|
||||
if len(text) <= max_chars:
|
||||
out.append(f)
|
||||
continue
|
||||
ranges = slice_boundaries(text, max_chars)
|
||||
total = len(ranges)
|
||||
for i, (s, e) in enumerate(ranges):
|
||||
out.append(FileSlice(path=f, start=s, end=e, index=i, total=total))
|
||||
return out
|
||||
|
||||
|
||||
def read_slice_text(fs: FileSlice) -> str:
|
||||
"""Read just this slice's characters from its parent file."""
|
||||
text = fs.path.read_text(encoding="utf-8", errors="replace")
|
||||
return text[fs.start:fs.end]
|
||||
|
||||
|
||||
def bisect_slice(fs: FileSlice) -> tuple[FileSlice, FileSlice] | None:
|
||||
"""Split a slice into two halves at a newline near its midpoint, or None.
|
||||
|
||||
Used by the adaptive-retry path when a single slice still overflows the
|
||||
model's output: halving it produces a smaller response. Returns None when the
|
||||
slice is already too small to split meaningfully.
|
||||
"""
|
||||
if fs.end - fs.start <= 1:
|
||||
return None
|
||||
try:
|
||||
text = fs.path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return None
|
||||
mid = (fs.start + fs.end) // 2
|
||||
nl = text.find("\n", mid, fs.end)
|
||||
cut = nl + 1 if (nl != -1 and fs.start < nl + 1 < fs.end) else mid
|
||||
if not (fs.start < cut < fs.end):
|
||||
return None
|
||||
left = FileSlice(fs.path, fs.start, cut, fs.index, fs.total)
|
||||
right = FileSlice(fs.path, cut, fs.end, fs.index, fs.total)
|
||||
return left, right
|
||||
@@ -16,27 +16,8 @@ def _load_manifest() -> dict:
|
||||
if _GLOBAL_MANIFEST.exists():
|
||||
try:
|
||||
return json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
|
||||
except Exception as exc:
|
||||
# Don't silently wipe the user's manifest on a parse error: that
|
||||
# deletes every tracked repo. Back the bad file up and surface the
|
||||
# error so the user can recover or report it.
|
||||
backup = _GLOBAL_MANIFEST.with_suffix(
|
||||
_GLOBAL_MANIFEST.suffix + f".corrupt.{int(datetime.now(timezone.utc).timestamp())}"
|
||||
)
|
||||
try:
|
||||
_GLOBAL_MANIFEST.rename(backup)
|
||||
print(
|
||||
f"[graphify global] manifest at {_GLOBAL_MANIFEST} failed to parse ({exc}); "
|
||||
f"moved to {backup} and starting fresh. Restore from the backup if this was "
|
||||
f"unexpected.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
except Exception as rename_exc:
|
||||
print(
|
||||
f"[graphify global] manifest at {_GLOBAL_MANIFEST} failed to parse ({exc}) "
|
||||
f"and could not be backed up ({rename_exc}). Starting fresh.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return {"version": 1, "repos": {}}
|
||||
|
||||
|
||||
@@ -124,24 +105,20 @@ def global_add(source_path: Path, repo_tag: str) -> dict:
|
||||
for n, d in G.nodes(data=True)
|
||||
if not d.get("source_file") and d.get("label")
|
||||
}
|
||||
# Map each deduplicated external onto the existing global node so that
|
||||
# edges incident to it can be rewired instead of dropped.
|
||||
remap = {}
|
||||
nodes_to_skip = set()
|
||||
for node, data in prefixed.nodes(data=True):
|
||||
if not data.get("source_file") and data.get("label") in external_labels:
|
||||
remap[node] = external_labels[data["label"]]
|
||||
nodes_to_skip.add(node)
|
||||
|
||||
# Compose: add prefixed nodes (except deduplicated externals) into global graph
|
||||
for node, data in prefixed.nodes(data=True):
|
||||
if node not in remap:
|
||||
if node not in nodes_to_skip:
|
||||
G.add_node(node, **data)
|
||||
for u, v, data in prefixed.edges(data=True):
|
||||
u = remap.get(u, u)
|
||||
v = remap.get(v, v)
|
||||
if u != v: # don't introduce self-loops via remapping
|
||||
if u not in nodes_to_skip and v not in nodes_to_skip:
|
||||
G.add_edge(u, v, **data)
|
||||
|
||||
added = prefixed.number_of_nodes() - len(remap)
|
||||
added = prefixed.number_of_nodes() - len(nodes_to_skip)
|
||||
_save_global_graph(G)
|
||||
|
||||
manifest["repos"][repo_tag] = {
|
||||
|
||||
+12
-127
@@ -1,7 +1,6 @@
|
||||
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
|
||||
from __future__ import annotations
|
||||
import configparser
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -21,18 +20,9 @@ _PYTHON_DETECT = """\
|
||||
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs).
|
||||
# _PINNED was recorded at hook-install time; tried first so the hook works even
|
||||
# when the graphify launcher is not on PATH (common in GUI clients and CI).
|
||||
#
|
||||
# Probes check availability with importlib.util.find_spec instead of importing
|
||||
# the package: a probe that imports graphify wholesale executes the full package
|
||||
# import (10s+ cold on machines with AV-scanned or large site-packages) and used
|
||||
# to run up to FOUR times synchronously, stalling every commit before the
|
||||
# detached launch even started. find_spec locates the package without executing
|
||||
# it, so each probe costs interpreter startup only. The detached rebuild still
|
||||
# fails loudly in the log if the package is broken under that interpreter.
|
||||
_GFY_PROBE="import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('graphify') else 1)"
|
||||
GRAPHIFY_PYTHON=""
|
||||
_PINNED='__PINNED_PYTHON__'
|
||||
if [ -n "$_PINNED" ] && [ -x "$_PINNED" ] && "$_PINNED" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
if [ -n "$_PINNED" ] && [ -x "$_PINNED" ] && "$_PINNED" -c "import graphify" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_PINNED"
|
||||
fi
|
||||
# Second probe: read graphify-out/.graphify_python (written by the skill and
|
||||
@@ -44,34 +34,18 @@ if [ -z "$GRAPHIFY_PYTHON" ]; then
|
||||
case "$_FROM_FILE" in
|
||||
*[!a-zA-Z0-9/_.@:\\-]*) _FROM_FILE="" ;; # allowlist (covers Windows paths)
|
||||
esac
|
||||
if [ -n "$_FROM_FILE" ] && [ -x "$_FROM_FILE" ] && "$_FROM_FILE" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
if [ -n "$_FROM_FILE" ] && [ -x "$_FROM_FILE" ] && "$_FROM_FILE" -c "import graphify" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_FROM_FILE"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
# Third probe: resolve via the graphify launcher on PATH.
|
||||
# Third probe: resolve via the graphify launcher on PATH (shebang probe).
|
||||
if [ -z "$GRAPHIFY_PYTHON" ]; then
|
||||
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
# Windows pip layout: Scripts/graphify(.exe) sits beside ..\\python.exe
|
||||
# (or .\\python.exe inside a venv's Scripts dir). NOTE: command -v may
|
||||
# return the launcher path WITHOUT the .exe suffix, so this cannot key
|
||||
# on the extension.
|
||||
_GFY_BINDIR=$(dirname "$GRAPHIFY_BIN")
|
||||
if [ -x "$_GFY_BINDIR/../python.exe" ] && "$_GFY_BINDIR/../python.exe" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_GFY_BINDIR/../python.exe"
|
||||
elif [ -x "$_GFY_BINDIR/python.exe" ] && "$_GFY_BINDIR/python.exe" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="$_GFY_BINDIR/python.exe"
|
||||
fi
|
||||
fi
|
||||
if [ -z "$GRAPHIFY_PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
|
||||
# POSIX launcher: parse the shebang. head -c + tr strip NUL bytes first —
|
||||
# when the launcher is a Windows binary reached without its .exe suffix,
|
||||
# a raw `head -1` reads binary into the command substitution and the
|
||||
# shell warns about ignored null bytes on every commit.
|
||||
case "$GRAPHIFY_BIN" in
|
||||
*.exe) _SHEBANG="" ;;
|
||||
*) _SHEBANG=$(head -c 256 "$GRAPHIFY_BIN" 2>/dev/null | tr -d '\\000' | head -n 1 | sed 's/^#![[:space:]]*//') ;;
|
||||
*) _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//') ;;
|
||||
esac
|
||||
case "$_SHEBANG" in
|
||||
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
|
||||
@@ -82,16 +56,16 @@ if [ -z "$GRAPHIFY_PYTHON" ]; then
|
||||
case "$GRAPHIFY_PYTHON" in
|
||||
*[!a-zA-Z0-9/_.@-]*) GRAPHIFY_PYTHON="" ;;
|
||||
esac
|
||||
if [ -n "$GRAPHIFY_PYTHON" ] && ! "$GRAPHIFY_PYTHON" -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
if [ -n "$GRAPHIFY_PYTHON" ] && ! "$GRAPHIFY_PYTHON" -c "import graphify" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON=""
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
# Last resort: try python3 / python (works for system/venv installs on PATH).
|
||||
if [ -z "$GRAPHIFY_PYTHON" ]; then
|
||||
if command -v python3 >/dev/null 2>&1 && python3 -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
if command -v python3 >/dev/null 2>&1 && python3 -c "import graphify" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="python3"
|
||||
elif command -v python >/dev/null 2>&1 && python -c "$_GFY_PROBE" 2>/dev/null; then
|
||||
elif command -v python >/dev/null 2>&1 && python -c "import graphify" 2>/dev/null; then
|
||||
GRAPHIFY_PYTHON="python"
|
||||
else
|
||||
echo "[graphify hook] could not locate a Python with graphify installed. Add the graphify bin dir to PATH or re-run 'graphify hook install' from the env where graphify lives." >&2
|
||||
@@ -125,24 +99,12 @@ try:
|
||||
signal.alarm(_timeout)
|
||||
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
|
||||
_root = Path('.')
|
||||
_out = os.environ.get('GRAPHIFY_OUT', 'graphify-out')
|
||||
_saved = Path(_out) / '.graphify_root'
|
||||
_saved = Path('graphify-out/.graphify_root')
|
||||
if _saved.exists():
|
||||
_txt = _saved.read_text(encoding='utf-8').strip()
|
||||
if _txt:
|
||||
_root = Path(_txt)
|
||||
_rebuild_code(_root, changed_paths=changed, force=_force)
|
||||
# Refresh the work-memory lessons doc when saved Q&A outcomes exist
|
||||
# (best-effort; never fails the hook).
|
||||
try:
|
||||
_md = (_root / _out) / 'memory'
|
||||
if _md.is_dir() and any(_md.glob('*.md')):
|
||||
from graphify.reflect import reflect as _reflect
|
||||
_gj = (_root / _out) / 'graph.json'
|
||||
_reflect(memory_dir=_md, out_path=(_root / _out) / 'reflections' / 'LESSONS.md',
|
||||
graph_path=_gj if _gj.exists() else None)
|
||||
except Exception:
|
||||
pass
|
||||
except TimeoutError as exc:
|
||||
print(f'[graphify hook] {exc}')
|
||||
sys.exit(1)
|
||||
@@ -166,24 +128,12 @@ try:
|
||||
# (no changed_paths) is correct here. The flock inside _rebuild_code still
|
||||
# prevents pile-ups when commit + checkout fire back-to-back.
|
||||
_root = Path('.')
|
||||
_out = os.environ.get('GRAPHIFY_OUT', 'graphify-out')
|
||||
_saved = Path(_out) / '.graphify_root'
|
||||
_saved = Path('graphify-out/.graphify_root')
|
||||
if _saved.exists():
|
||||
_txt = _saved.read_text(encoding='utf-8').strip()
|
||||
if _txt:
|
||||
_root = Path(_txt)
|
||||
_rebuild_code(_root, force=_force)
|
||||
# Refresh the work-memory lessons doc when saved Q&A outcomes exist
|
||||
# (best-effort; never fails the hook).
|
||||
try:
|
||||
_md = (_root / _out) / 'memory'
|
||||
if _md.is_dir() and any(_md.glob('*.md')):
|
||||
from graphify.reflect import reflect as _reflect
|
||||
_gj = (_root / _out) / 'graph.json'
|
||||
_reflect(memory_dir=_md, out_path=(_root / _out) / 'reflections' / 'LESSONS.md',
|
||||
graph_path=_gj if _gj.exists() else None)
|
||||
except Exception:
|
||||
pass
|
||||
except TimeoutError as exc:
|
||||
print(f'[graphify] {exc}')
|
||||
sys.exit(1)
|
||||
@@ -240,25 +190,6 @@ def _detached_launch(rebuild_body: str) -> str:
|
||||
return '"$GRAPHIFY_PYTHON" -c "' + launcher + '"\n'
|
||||
|
||||
|
||||
# Skip the rebuild inside a linked worktree (git worktree add), shared by both
|
||||
# hooks. With core.hooksPath shared across worktrees a commit in any worktree
|
||||
# fires these hooks; the canonical graphify-out/ belongs to the primary checkout,
|
||||
# so rebuilding from a worktree is wasteful, writes a rogue delta-only graph the
|
||||
# user never asked for, and races deploy/CI `git clean` against the detached
|
||||
# rebuild ("failed to remove graphify-out/: Directory not empty") (#1809, #1806).
|
||||
# A linked worktree has git-dir != git-common-dir. Both are resolved to absolute
|
||||
# via `cd ... && pwd` before comparing: git's exported GIT_DIR / --git-dir can be
|
||||
# absolute while --git-common-dir is the relative ".git", and a raw compare would
|
||||
# false-positive on the PRIMARY checkout and wrongly skip it.
|
||||
_WORKTREE_GUARD = """\
|
||||
_GFY_GITDIR=$(cd "$(git rev-parse --git-dir 2>/dev/null)" 2>/dev/null && pwd)
|
||||
_GFY_COMMONDIR=$(cd "$(git rev-parse --git-common-dir 2>/dev/null)" 2>/dev/null && pwd)
|
||||
if [ -n "$_GFY_COMMONDIR" ] && [ "$_GFY_GITDIR" != "$_GFY_COMMONDIR" ]; then
|
||||
exit 0
|
||||
fi
|
||||
"""
|
||||
|
||||
|
||||
_HOOK_SCRIPT = """\
|
||||
# graphify-hook-start
|
||||
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
|
||||
@@ -269,17 +200,8 @@ _HOOK_SCRIPT = """\
|
||||
# churn run-to-run. Pinning it makes graphify-out reproducible.
|
||||
export PYTHONHASHSEED=0
|
||||
|
||||
# Git for Windows/MSYS hooks can inherit fragile pipe handles from GUI clients
|
||||
# and agent shells. Keep hook-triggered rebuilds sequential by default there;
|
||||
# explicit GRAPHIFY_MAX_WORKERS still wins for users who want parallelism.
|
||||
if [ -n "${WINDIR:-}" ] || [ -n "${MSYSTEM:-}" ]; then
|
||||
export GRAPHIFY_MAX_WORKERS="${GRAPHIFY_MAX_WORKERS:-1}"
|
||||
fi
|
||||
|
||||
# Skip during rebase/merge/cherry-pick to avoid blocking --continue with unstaged changes
|
||||
# git exports GIT_DIR to hooks; the rev-parse fallback only runs when invoked by
|
||||
# hand (each git exec costs 1s+ on AV-scanned Windows machines).
|
||||
GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
|
||||
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
|
||||
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
|
||||
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
|
||||
@@ -287,7 +209,6 @@ GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
|
||||
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
|
||||
|
||||
""" + _WORKTREE_GUARD + """
|
||||
CHANGED=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || git diff --name-only HEAD 2>/dev/null)
|
||||
if [ -z "$CHANGED" ]; then
|
||||
exit 0
|
||||
@@ -324,13 +245,6 @@ _CHECKOUT_SCRIPT = """\
|
||||
# churn run-to-run. Pinning it makes graphify-out reproducible.
|
||||
export PYTHONHASHSEED=0
|
||||
|
||||
# Git for Windows/MSYS hooks can inherit fragile pipe handles from GUI clients
|
||||
# and agent shells. Keep hook-triggered rebuilds sequential by default there;
|
||||
# explicit GRAPHIFY_MAX_WORKERS still wins for users who want parallelism.
|
||||
if [ -n "${WINDIR:-}" ] || [ -n "${MSYSTEM:-}" ]; then
|
||||
export GRAPHIFY_MAX_WORKERS="${GRAPHIFY_MAX_WORKERS:-1}"
|
||||
fi
|
||||
|
||||
PREV_HEAD=$1
|
||||
NEW_HEAD=$2
|
||||
BRANCH_SWITCH=$3
|
||||
@@ -346,19 +260,13 @@ if [ ! -d "graphify-out" ]; then
|
||||
fi
|
||||
|
||||
# Skip during rebase/merge/cherry-pick
|
||||
# git exports GIT_DIR to hooks; the rev-parse fallback only runs when invoked by
|
||||
# hand (each git exec costs 1s+ on AV-scanned Windows machines).
|
||||
GIT_DIR=${GIT_DIR:-$(git rev-parse --git-dir 2>/dev/null)}
|
||||
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
|
||||
[ -d "$GIT_DIR/rebase-merge" ] && exit 0
|
||||
[ -d "$GIT_DIR/rebase-apply" ] && exit 0
|
||||
[ -f "$GIT_DIR/MERGE_HEAD" ] && exit 0
|
||||
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
|
||||
|
||||
# Honor the same opt-out as post-commit: without this, GRAPHIFY_SKIP_HOOK=1
|
||||
# suppressed commit-triggered rebuilds but not branch-switch ones (#1809).
|
||||
[ "${GRAPHIFY_SKIP_HOOK:-0}" = "1" ] && exit 0
|
||||
|
||||
""" + _WORKTREE_GUARD + _PYTHON_DETECT + """
|
||||
""" + _PYTHON_DETECT + """
|
||||
_GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
|
||||
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
|
||||
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
|
||||
@@ -376,27 +284,6 @@ def _git_root(path: Path) -> Path | None:
|
||||
return None
|
||||
|
||||
|
||||
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")
|
||||
|
||||
|
||||
def _reject_windows_path(value: str, source: str) -> None:
|
||||
"""Raise if a hooks path looks like a Windows absolute path (#1385).
|
||||
|
||||
On POSIX/WSL ``Path("C:\\Users\\...").is_absolute()`` is False, so an absolute
|
||||
Windows hooks path gets joined under the repo root and mkdir'd as a literal
|
||||
junk directory (backslashes and all), while install reports success and the
|
||||
real ``.git/hooks`` gets nothing. Fail loudly instead so the user can fix it.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
return
|
||||
if _WINDOWS_DRIVE_RE.match(value) or "\\" in value:
|
||||
raise RuntimeError(
|
||||
f"git hooks path from {source} looks like a Windows path: {value!r}. "
|
||||
f"On WSL/POSIX this can't resolve to a real directory. Unset it with "
|
||||
f"`git config --local --unset core.hooksPath`, or set a POSIX path."
|
||||
)
|
||||
|
||||
|
||||
def _hooks_dir(root: Path) -> Path:
|
||||
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
|
||||
try:
|
||||
@@ -405,7 +292,6 @@ def _hooks_dir(root: Path) -> Path:
|
||||
# configparser lowercases option names; git's hooksPath becomes hookspath
|
||||
custom = cfg.get("core", "hookspath", fallback="").strip()
|
||||
if custom:
|
||||
_reject_windows_path(custom, "core.hooksPath")
|
||||
p = Path(custom).expanduser()
|
||||
if not p.is_absolute():
|
||||
p = root / p
|
||||
@@ -445,7 +331,6 @@ def _hooks_dir(root: Path) -> Path:
|
||||
# A valid hooks path can never contain newlines or NUL. Their presence
|
||||
# means git echoed an unrecognised flag back (old git behaviour).
|
||||
if res.returncode == 0 and raw and not any(c in raw for c in ("\n", "\r", "\x00")):
|
||||
_reject_windows_path(raw, "git rev-parse --git-path hooks")
|
||||
d = (root / raw).resolve()
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
"""Single source of truth for node-ID normalization.
|
||||
|
||||
Three independent producers must agree on node IDs or the graph splits a single
|
||||
entity into disconnected ghost nodes:
|
||||
|
||||
1. The AST extractor (``extract._make_id``) — deterministic, per-language.
|
||||
2. The semantic subagents (LLM) — follow the node-ID spec in the skill prompt.
|
||||
3. The graph builder (``build._normalize_id``) — reconciles edge endpoints when
|
||||
the LLM emits IDs with slightly different punctuation or casing than the AST.
|
||||
|
||||
Historically the normalization recipe was copy-pasted into ``extract._make_id``
|
||||
and ``build._normalize_id`` and kept in sync only by mirrored docstrings, which
|
||||
is exactly how the recurring ID-drift bug class crept in (#811 Unicode collapse,
|
||||
#550 same-filename collisions, #1033 AST-vs-LLM file-node mismatch, #1104). This
|
||||
module exists so the recipe lives in one place and the two callers can no longer
|
||||
diverge.
|
||||
|
||||
The recipe: NFKC-normalize (so composed/decomposed Unicode forms collapse),
|
||||
replace runs of non-word characters with a single underscore (``re.UNICODE`` so
|
||||
CJK/Cyrillic/Arabic/accented-Latin letters survive instead of collapsing to a
|
||||
per-file node), collapse repeated underscores, strip leading/trailing
|
||||
underscores, and casefold.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
__all__ = ["normalize_id", "make_id"]
|
||||
|
||||
|
||||
def normalize_id(s: str) -> str:
|
||||
r"""Normalize a single ID string to its canonical form.
|
||||
|
||||
Idempotent: ``normalize_id(normalize_id(s)) == normalize_id(s)``.
|
||||
"""
|
||||
s = unicodedata.normalize("NFKC", s)
|
||||
s = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
|
||||
s = re.sub(r"_+", "_", s)
|
||||
return s.strip("_").casefold()
|
||||
|
||||
|
||||
def make_id(*parts: str) -> str:
|
||||
"""Build a canonical node ID from one or more name parts.
|
||||
|
||||
Parts are joined with ``_`` (after stripping stray ``_``/``.`` edges from each
|
||||
part) and then run through :func:`normalize_id`, so the result is identical to
|
||||
what the builder produces from the joined string.
|
||||
"""
|
||||
return normalize_id("_".join(p.strip("_.") for p in parts if p))
|
||||
+1
-23
@@ -268,8 +268,6 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
|
||||
print(f"Saved {url_type}: {out_path.name}")
|
||||
return out_path
|
||||
|
||||
OUTCOMES = ("useful", "dead_end", "corrected")
|
||||
|
||||
|
||||
def save_query_result(
|
||||
question: str,
|
||||
@@ -277,23 +275,13 @@ def save_query_result(
|
||||
memory_dir: Path,
|
||||
query_type: str = "query",
|
||||
source_nodes: list[str] | None = None,
|
||||
outcome: str | None = None,
|
||||
correction: str | None = None,
|
||||
) -> Path:
|
||||
"""Save a Q&A result as markdown so it gets extracted into the graph on next --update.
|
||||
|
||||
Files are stored in memory_dir (typically graphify-out/memory/) with YAML frontmatter
|
||||
that graphify's extractor reads as node metadata. This closes the feedback loop:
|
||||
the system grows smarter from both what you add AND what you ask.
|
||||
|
||||
``outcome`` (one of :data:`OUTCOMES`) and ``correction`` are optional work-memory
|
||||
signals: they are written both to the frontmatter (so `graphify reflect` can
|
||||
aggregate them deterministically) and to an ``## Outcome`` body section (so the
|
||||
signal round-trips into the graph on the next semantic re-extraction).
|
||||
"""
|
||||
if outcome is not None and outcome not in OUTCOMES:
|
||||
raise ValueError(f"outcome must be one of {OUTCOMES}, got {outcome!r}")
|
||||
|
||||
memory_dir = Path(memory_dir)
|
||||
memory_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -308,12 +296,8 @@ def save_query_result(
|
||||
f'question: "{_yaml_str(question)}"',
|
||||
'contributor: "graphify"',
|
||||
]
|
||||
if outcome:
|
||||
frontmatter_lines.append(f'outcome: "{_yaml_str(outcome)}"')
|
||||
if correction:
|
||||
frontmatter_lines.append(f'correction: "{_yaml_str(correction)}"')
|
||||
if source_nodes:
|
||||
nodes_str = ", ".join(f'"{_yaml_str(n)}"' for n in source_nodes[:10])
|
||||
nodes_str = ", ".join(f'"{n}"' for n in source_nodes[:10])
|
||||
frontmatter_lines.append(f"source_nodes: [{nodes_str}]")
|
||||
frontmatter_lines.append("---")
|
||||
|
||||
@@ -325,12 +309,6 @@ def save_query_result(
|
||||
"",
|
||||
answer,
|
||||
]
|
||||
if outcome or correction:
|
||||
body_lines += ["", "## Outcome", ""]
|
||||
if outcome:
|
||||
body_lines.append(f"- Signal: {outcome}")
|
||||
if correction:
|
||||
body_lines.append(f"- Correction: {correction}")
|
||||
if source_nodes:
|
||||
body_lines += ["", "## Source Nodes", ""]
|
||||
body_lines += [f"- {n}" for n in source_nodes]
|
||||
|
||||
-2148
File diff suppressed because it is too large.
Load diff
+127
-832
File diff suppressed because it is too large.
Load diff
@@ -1,247 +0,0 @@
|
||||
"""Deterministic package-manifest ingestion (#1377).
|
||||
|
||||
Package manifests (``apm.yml``, ``pyproject.toml``, ``go.mod``, ``pom.xml``)
|
||||
declare a package and its dependencies. Left to the LLM document path, the same
|
||||
package gets a different file-anchored node id from its own manifest than from
|
||||
each dependent's dependency reference, so it splits into duplicate nodes. This
|
||||
module parses manifests deterministically and emits ONE canonical package node
|
||||
per package -- keyed by NAME via :func:`graphify.ids.make_id` -- plus
|
||||
``depends_on`` edges, so a package referenced from N manifests collapses to a
|
||||
single hub node (the dependency stub and the package's own definition node share
|
||||
the canonical id and merge at build time).
|
||||
|
||||
Mirrors ``mcp_ingest``: recognized by filename, routed to the deterministic AST
|
||||
path (never the LLM), so a manifest is extracted exactly once.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.ids import make_id
|
||||
|
||||
__all__ = ["is_package_manifest_path", "extract_package_manifest", "PACKAGE_MANIFEST_NAMES"]
|
||||
|
||||
# manifest filename (lowercased) -> ecosystem tag
|
||||
PACKAGE_MANIFEST_NAMES: dict[str, str] = {
|
||||
"apm.yml": "apm",
|
||||
"apm.yaml": "apm",
|
||||
"pyproject.toml": "python",
|
||||
"go.mod": "go",
|
||||
"pom.xml": "maven",
|
||||
}
|
||||
|
||||
_MAX_MANIFEST_BYTES = 2_000_000 # 2 MB cap — manifests are small; this rejects junk
|
||||
|
||||
|
||||
def is_package_manifest_path(path: Path) -> bool:
|
||||
"""True if ``path`` is a recognized package manifest (by filename)."""
|
||||
return path.name.lower() in PACKAGE_MANIFEST_NAMES
|
||||
|
||||
|
||||
def _pkg_id(name: str) -> str:
|
||||
"""Canonical package node id, keyed by package NAME so every reference to the
|
||||
same package -- its own manifest and any dependent's dependency line -- maps
|
||||
to one node."""
|
||||
return make_id("pkg", name)
|
||||
|
||||
|
||||
def extract_package_manifest(path: Path) -> dict[str, Any]:
|
||||
"""Parse a package manifest into a canonical package node + ``depends_on`` edges."""
|
||||
try:
|
||||
if path.stat().st_size > _MAX_MANIFEST_BYTES:
|
||||
return {"nodes": [], "edges": [], "error": "manifest too large to index"}
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError as exc:
|
||||
return {"nodes": [], "edges": [], "error": f"manifest read error: {exc}"}
|
||||
|
||||
eco = PACKAGE_MANIFEST_NAMES[path.name.lower()]
|
||||
try:
|
||||
info = _PARSERS[eco](text)
|
||||
except Exception as exc: # noqa: BLE001 — a malformed manifest must not abort extraction
|
||||
return {"nodes": [], "edges": [], "error": f"manifest parse error: {exc}"}
|
||||
if not info or not info.get("name"):
|
||||
return {"nodes": [], "edges": []}
|
||||
|
||||
name = info["name"]
|
||||
str_path = str(path)
|
||||
pkg_nid = _pkg_id(name)
|
||||
node: dict[str, Any] = {
|
||||
"id": pkg_nid,
|
||||
"label": name,
|
||||
"file_type": "code", # valid schema type; `type` distinguishes packages
|
||||
"type": "package",
|
||||
"ecosystem": eco,
|
||||
"source_file": str_path,
|
||||
"source_location": "L1",
|
||||
}
|
||||
if info.get("version"):
|
||||
node["version"] = info["version"]
|
||||
nodes: list[dict] = [node]
|
||||
edges: list[dict] = []
|
||||
|
||||
seen: set[str] = set()
|
||||
for dep in info.get("deps", []):
|
||||
if not dep:
|
||||
continue
|
||||
dep_nid = _pkg_id(dep)
|
||||
if dep_nid == pkg_nid or dep_nid in seen:
|
||||
continue
|
||||
seen.add(dep_nid)
|
||||
# The edge targets the dependency's canonical package id. If that package's
|
||||
# own manifest is in the corpus, the edge resolves to its (single) node; if
|
||||
# the dependency is external, build_from_json prunes the dangling edge. We
|
||||
# deliberately do NOT emit a stub node — a stub with an empty source_file
|
||||
# would risk clobbering the real node's source_file under id-dedup.
|
||||
edges.append({
|
||||
"source": pkg_nid,
|
||||
"target": dep_nid,
|
||||
"relation": "depends_on",
|
||||
"context": "dependency",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": str_path,
|
||||
"source_location": "L1",
|
||||
"weight": 1.0,
|
||||
})
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
# ── per-ecosystem parsers: text -> {"name", "version"?, "deps": [str]} | None ──
|
||||
|
||||
def _coerce_deps(value: Any) -> list[str]:
|
||||
"""A dependency block may be a list of names or a name->spec map."""
|
||||
if isinstance(value, dict):
|
||||
return [str(k) for k in value]
|
||||
if isinstance(value, list):
|
||||
out: list[str] = []
|
||||
for item in value:
|
||||
if isinstance(item, str):
|
||||
out.append(item)
|
||||
elif isinstance(item, dict) and item:
|
||||
out.append(str(next(iter(item))))
|
||||
return out
|
||||
return []
|
||||
|
||||
|
||||
def _parse_apm(text: str) -> dict | None:
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
return _parse_apm_fallback(text)
|
||||
data = yaml.safe_load(text)
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
return {
|
||||
"name": data.get("name"),
|
||||
"version": data.get("version"),
|
||||
"deps": _coerce_deps(data.get("dependencies")),
|
||||
}
|
||||
|
||||
|
||||
def _parse_apm_fallback(text: str) -> dict | None:
|
||||
"""Minimal line parser for apm.yml when PyYAML is unavailable: a top-level
|
||||
``name:`` plus a simple ``dependencies:`` block (list items or a name map)."""
|
||||
name = None
|
||||
deps: list[str] = []
|
||||
in_deps = False
|
||||
for line in text.splitlines():
|
||||
if not in_deps:
|
||||
m = re.match(r'^name:\s*["\']?([^"\'\s#]+)', line)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
continue
|
||||
if re.match(r'^dependencies:\s*$', line):
|
||||
in_deps = True
|
||||
continue
|
||||
if in_deps:
|
||||
dm = (re.match(r'^\s*-\s*["\']?([^"\'\s#:]+)', line)
|
||||
or re.match(r'^\s{2,}([A-Za-z0-9._/@-]+)\s*:', line))
|
||||
if dm:
|
||||
deps.append(dm.group(1))
|
||||
elif re.match(r'^\S', line): # next top-level key ends the block
|
||||
in_deps = False
|
||||
return {"name": name, "version": None, "deps": deps} if name else None
|
||||
|
||||
|
||||
def _pep508_name(spec: str) -> str:
|
||||
"""`requests>=2.0` -> `requests`; `pkg[extra]==1; python_version<'3.9'` -> `pkg`."""
|
||||
return re.split(r'[\s<>=!~;\[\(]', spec.strip(), maxsplit=1)[0]
|
||||
|
||||
|
||||
def _parse_pyproject(text: str) -> dict | None:
|
||||
try:
|
||||
import tomllib as _toml
|
||||
except ImportError:
|
||||
try:
|
||||
import tomli as _toml # type: ignore
|
||||
except ImportError:
|
||||
return None
|
||||
data = _toml.loads(text)
|
||||
proj = data.get("project", {}) if isinstance(data.get("project"), dict) else {}
|
||||
poetry = (data.get("tool", {}) or {}).get("poetry", {}) if isinstance(data.get("tool"), dict) else {}
|
||||
name = proj.get("name") or (poetry.get("name") if isinstance(poetry, dict) else None)
|
||||
if not name:
|
||||
return None
|
||||
deps: list[str] = [_pep508_name(s) for s in (proj.get("dependencies") or []) if isinstance(s, str)]
|
||||
if isinstance(poetry, dict):
|
||||
for dep in (poetry.get("dependencies") or {}):
|
||||
if str(dep).lower() != "python":
|
||||
deps.append(str(dep))
|
||||
return {"name": name, "version": proj.get("version") or (poetry.get("version") if isinstance(poetry, dict) else None), "deps": deps}
|
||||
|
||||
|
||||
def _parse_gomod(text: str) -> dict | None:
|
||||
name = None
|
||||
deps: list[str] = []
|
||||
in_block = False
|
||||
for line in text.splitlines():
|
||||
s = line.strip()
|
||||
if name is None:
|
||||
m = re.match(r'^module\s+(\S+)', s)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
continue
|
||||
if re.match(r'^require\s*\(', s):
|
||||
in_block = True
|
||||
continue
|
||||
if in_block:
|
||||
if s.startswith(')'):
|
||||
in_block = False
|
||||
continue
|
||||
dm = re.match(r'^(\S+)\s+v\S+', s)
|
||||
if dm:
|
||||
deps.append(dm.group(1))
|
||||
else:
|
||||
dm = re.match(r'^require\s+(\S+)\s+v\S+', s)
|
||||
if dm:
|
||||
deps.append(dm.group(1))
|
||||
return {"name": name, "version": None, "deps": deps} if name else None
|
||||
|
||||
|
||||
def _parse_pom(text: str) -> dict | None:
|
||||
# Drop the default namespace so findtext/findall don't need the {uri} prefix.
|
||||
text = re.sub(r'\sxmlns="[^"]*"', '', text, count=1)
|
||||
root = ET.fromstring(text)
|
||||
aid = root.findtext("artifactId")
|
||||
gid = root.findtext("groupId")
|
||||
if not aid:
|
||||
return None
|
||||
name = f"{gid}:{aid}" if gid else aid
|
||||
deps: list[str] = []
|
||||
for dep in root.findall(".//dependencies/dependency"):
|
||||
da = dep.findtext("artifactId")
|
||||
dg = dep.findtext("groupId")
|
||||
if da:
|
||||
deps.append(f"{dg}:{da}" if dg else da)
|
||||
return {"name": name, "version": root.findtext("version"), "deps": deps}
|
||||
|
||||
|
||||
_PARSERS = {
|
||||
"apm": _parse_apm,
|
||||
"python": _parse_pyproject,
|
||||
"go": _parse_gomod,
|
||||
"maven": _parse_pom,
|
||||
}
|
||||
+12
-6
@@ -63,7 +63,6 @@ import unicodedata
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.ids import make_id as _shared_make_id
|
||||
from graphify.security import sanitize_label
|
||||
|
||||
|
||||
@@ -377,10 +376,17 @@ def _add_edge(
|
||||
|
||||
|
||||
def _make_id(*parts: str) -> str:
|
||||
"""Build a stable node ID via the single shared recipe (#1378)."""
|
||||
return _shared_make_id(*parts)
|
||||
"""Build a stable node ID. Must match extract._make_id's normalisation rules."""
|
||||
combined = "_".join(p.strip("_.") for p in parts if p)
|
||||
combined = unicodedata.normalize("NFKC", combined)
|
||||
cleaned = re.sub(r"[^\w]+", "_", combined, flags=re.UNICODE)
|
||||
cleaned = re.sub(r"_+", "_", cleaned)
|
||||
return cleaned.strip("_").casefold()
|
||||
|
||||
|
||||
# Canonical recipe imported directly (no import cycle: extractors.base imports
|
||||
# only graphify.ids), so this can no longer drift from extract._file_stem.
|
||||
from graphify.extractors.base import _file_stem # noqa: E402
|
||||
def _file_stem(path: Path) -> str:
|
||||
"""Mirror extract._file_stem: include parent dir name to disambiguate."""
|
||||
parent = path.parent.name
|
||||
if parent and parent not in (".", ""):
|
||||
return f"{parent}.{path.stem}"
|
||||
return path.stem
|
||||
@@ -1,129 +0,0 @@
|
||||
"""Cross-file resolution for Pascal/Delphi calls to inherited methods.
|
||||
|
||||
The per-file Pascal/Delphi extractors (``extract_pascal``,
|
||||
``_extract_pascal_regex``) resolve calls to a method on the caller's own
|
||||
class, its ancestor chain, or a file-level free function -- but only within
|
||||
the single file being extracted (each file is extracted independently; see
|
||||
``_resolve_pascal_callee_factory`` in ``extract.py``). Real Delphi/MTM-style
|
||||
codebases very commonly split a class across two files -- a code-generator
|
||||
base class (e.g. Sistec's ``Th0Xxx``) and a manual descendant that extends it
|
||||
in a separate unit (``Th5Xxx``) -- so a call from the manual descendant to a
|
||||
method it inherits from the generated base falls outside any one file's own
|
||||
scope. The per-file pass reports these as ``raw_calls`` instead of guessing.
|
||||
|
||||
This resolver runs after all files are extracted (registered in
|
||||
``graphify.resolver_registry``), with the full merged node/edge corpus
|
||||
available, so it can walk an ``inherits`` chain across file boundaries. It
|
||||
intentionally does NOT fall back to a global by-name match the way the
|
||||
per-file pass's final tier does -- an unqualified call resolving to a
|
||||
specific ancestor mirrors Delphi's actual method-lookup semantics (nearest
|
||||
ancestor in the chain), so walking `inherits` is a structurally justified
|
||||
resolution, not a heuristic guess; guessing by name across an entire
|
||||
multi-thousand-file corpus is not the same bet.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
_PASCAL_SUFFIXES = (".pas", ".pp", ".dpr", ".dpk", ".inc")
|
||||
|
||||
|
||||
def _pascal_raw_calls(per_file: list[dict]) -> list[dict]:
|
||||
calls: list[dict] = []
|
||||
for result in per_file:
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
for rc in result.get("raw_calls", []):
|
||||
if not isinstance(rc, dict):
|
||||
continue
|
||||
if str(rc.get("source_file", "")).endswith(_PASCAL_SUFFIXES):
|
||||
calls.append(rc)
|
||||
return calls
|
||||
|
||||
|
||||
def resolve_pascal_inherited_calls(
|
||||
per_file: list[dict],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Resolve Pascal/Delphi calls to a method inherited across file boundaries.
|
||||
|
||||
Purely additive: only emits edges for raw calls the per-file pass could
|
||||
not resolve locally (see module docstring). Each emission requires a
|
||||
single owning class at the nearest matching level of the caller's
|
||||
``inherits`` chain (god-node guard, same principle as
|
||||
``resolve_ruby_member_calls``) -- an ambiguous or unresolved name
|
||||
produces no edge rather than a guess.
|
||||
"""
|
||||
node_by_id = {n.get("id"): n for n in all_nodes}
|
||||
|
||||
class_bases: dict[str, list[str]] = {}
|
||||
# method_nid -> its owning class nid, so a raw call's caller_nid (a method
|
||||
# or free-function nid) can be mapped to the CLASS whose inherits chain
|
||||
# should be walked. Derived from `all_edges` (already remapped/finalized
|
||||
# by the id-disambiguation passes that run before resolvers, same as
|
||||
# caller_nid itself) rather than carried as a separate field on the raw
|
||||
# call -- a field the generic id-remap machinery would not know to update.
|
||||
owner_of: dict[str, str] = {}
|
||||
class_procs: dict[str, dict[str, list[str]]] = {}
|
||||
for e in all_edges:
|
||||
if e.get("relation") == "inherits":
|
||||
class_bases.setdefault(e["source"], []).append(e["target"])
|
||||
elif e.get("relation") == "method":
|
||||
owner, method_nid = e.get("source"), e.get("target")
|
||||
owner_of[method_nid] = owner
|
||||
mnode = node_by_id.get(method_nid)
|
||||
if mnode is None:
|
||||
continue
|
||||
name_lower = str(mnode.get("label", "")).removesuffix("()").lower()
|
||||
# Count DISTINCT methods, not edge multiplicity: the tree-sitter
|
||||
# Pascal extractor emits one `method` edge for the interface
|
||||
# declaration and one for the implementation, so the same
|
||||
# method_nid arrives twice. Deduping keeps the single-owner
|
||||
# god-node guard below (`len(candidates) == 1`) measuring real
|
||||
# same-name collisions across classes, not the same method
|
||||
# double-counted -- otherwise every inherited call looks ambiguous.
|
||||
bucket = class_procs.setdefault(owner, {}).setdefault(name_lower, [])
|
||||
if method_nid not in bucket:
|
||||
bucket.append(method_nid)
|
||||
|
||||
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
|
||||
|
||||
def _resolve(owner: str, name_lower: str) -> str | None:
|
||||
seen_bases: set[str] = set()
|
||||
queue = list(class_bases.get(owner, []))
|
||||
while queue:
|
||||
base = queue.pop(0)
|
||||
if base in seen_bases:
|
||||
continue
|
||||
seen_bases.add(base)
|
||||
candidates = class_procs.get(base, {}).get(name_lower)
|
||||
if candidates:
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
queue.extend(class_bases.get(base, []))
|
||||
return None
|
||||
|
||||
for rc in _pascal_raw_calls(per_file):
|
||||
caller = rc.get("caller_nid")
|
||||
name_lower = rc.get("callee")
|
||||
if not caller or not name_lower:
|
||||
continue
|
||||
owner = owner_of.get(caller)
|
||||
if not owner:
|
||||
continue
|
||||
target = _resolve(str(owner), str(name_lower))
|
||||
if not target or target == caller:
|
||||
continue
|
||||
pair = (caller, target)
|
||||
if pair in existing_pairs:
|
||||
continue
|
||||
existing_pairs.add(pair)
|
||||
all_edges.append({
|
||||
"source": caller,
|
||||
"target": target,
|
||||
"relation": "calls",
|
||||
"context": "call",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": rc.get("source_file", ""),
|
||||
"source_location": rc.get("source_location"),
|
||||
"weight": 1.0,
|
||||
})
|
||||
@@ -1,234 +0,0 @@
|
||||
"""Single source of truth for the graphify output-directory name.
|
||||
|
||||
The output directory is ``graphify-out`` by default and overridable with the
|
||||
``GRAPHIFY_OUT`` env var (worktrees or shared-output setups, #686). It accepts a
|
||||
relative name (``"graphify-out-feature"``) or an absolute path
|
||||
(``"/shared/graphify-out"``).
|
||||
|
||||
This used to be duplicated as an identical ``_GRAPHIFY_OUT`` constant in
|
||||
``__main__``, ``cache``, and ``watch``, while ``security`` and ``callflow_html``
|
||||
hardcoded the literal ``"graphify-out"`` and silently ignored the override
|
||||
(#1423). Centralising it here keeps the name in one place. The value is read
|
||||
once at import time, matching the previous per-module constants — set
|
||||
``GRAPHIFY_OUT`` before the process starts (the normal worktree/shared-output
|
||||
flow) and every reader honours it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
|
||||
|
||||
# Directory segments that, when they appear as a whole path component, mark the
|
||||
# whole path as a test location. Matched against path *segments* (not raw
|
||||
# substrings) so "src/contest.py" / "latest/x.py" / "src/greatest/x.py" do NOT
|
||||
# match — only a segment that *equals* one of these names (case-insensitively).
|
||||
_TEST_DIR_SEGMENTS = frozenset({"tests", "test", "spec", "specs", "__tests__"})
|
||||
|
||||
# Filename patterns marking a file as a test, matched against the *filename*
|
||||
# only (case-insensitive). These are conventions across ecosystems:
|
||||
# test_*.py pytest / unittest
|
||||
# *_test.* Go / Python / Rust
|
||||
# *.test.* JS/TS (jest, vitest)
|
||||
# *.spec.* / *_spec.* Jasmine / RSpec / Karma
|
||||
# *.Tests.ps1 PowerShell Pester
|
||||
# *Test.java / *Tests.cs (case-sensitive convention, handled below)
|
||||
_TEST_FILENAME_PATTERNS = (
|
||||
re.compile(r"^test_.*", re.IGNORECASE),
|
||||
re.compile(r".*_test\..+$", re.IGNORECASE),
|
||||
re.compile(r".*\.test\..+$", re.IGNORECASE),
|
||||
re.compile(r".*\.spec\..+$", re.IGNORECASE),
|
||||
re.compile(r".*_spec\..+$", re.IGNORECASE),
|
||||
re.compile(r".*\.tests\.ps1$", re.IGNORECASE),
|
||||
# Java `FooTest.java` / `FooTests.java`, C# `FooTests.cs` style. Require an
|
||||
# uppercase-led `Test`/`Tests` immediately before the extension so plain
|
||||
# words like "greatest"/"contest.cs" do not match.
|
||||
re.compile(r".*Test\.java$"),
|
||||
re.compile(r".*Tests\.java$"),
|
||||
re.compile(r".*Tests\.cs$"),
|
||||
)
|
||||
|
||||
|
||||
def _is_test_path(path: str) -> bool:
|
||||
"""Classify a source path as a test path (case-insensitive, segment-aware).
|
||||
|
||||
Shared by extract.py and symbol_resolution.py so cross-file call resolution
|
||||
treats test mocks/stubs identically. A path is a test path when:
|
||||
* any whole path segment equals a known test dir name
|
||||
(``tests``/``test``/``spec``/``specs``/``__tests__``), or
|
||||
* the filename matches a known test-file naming convention.
|
||||
|
||||
Conservative on purpose: matches segments/filenames, never raw substrings,
|
||||
so ``latest.py``, ``src/contest.py`` and ``src/greatest/x.py`` are NON-test.
|
||||
"""
|
||||
if not path:
|
||||
return False
|
||||
# Accept both POSIX and Windows separators regardless of host OS so the
|
||||
# classifier is stable across the mixed paths that flow through extraction.
|
||||
norm = str(path).replace("\\", "/")
|
||||
pure = PurePosixPath(norm)
|
||||
segments = list(pure.parts)
|
||||
# Strip a leading drive/anchor segment (e.g. "C:/") that PureWindowsPath
|
||||
# would surface; with the manual "\\"->"/" swap above PurePosixPath keeps
|
||||
# the path body intact, but guard against a Windows drive embedded as a
|
||||
# segment just in case.
|
||||
for segment in segments:
|
||||
if segment.lower() in _TEST_DIR_SEGMENTS:
|
||||
return True
|
||||
# A drive-letter colon segment like "c:" is never a test dir.
|
||||
filename = pure.name
|
||||
if not filename:
|
||||
return False
|
||||
for pattern in _TEST_FILENAME_PATTERNS:
|
||||
if pattern.match(filename):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _path_proximity_winner(call_site_file: str, candidate_files: dict[str, str]) -> str | None:
|
||||
"""Pick the candidate whose source file is closest to the call site.
|
||||
|
||||
``candidate_files`` maps candidate id -> its source_file. Returns a single
|
||||
winning candidate id, or ``None`` when no proximity tier yields a unique
|
||||
winner. Tiers, in order:
|
||||
|
||||
1. same file as the call site,
|
||||
2. same directory,
|
||||
3. longest common path-prefix (must be a strict, unique maximum).
|
||||
|
||||
Used only as a secondary tie-break after the test/non-test filter, so the
|
||||
god-node guard still holds when proximity is genuinely ambiguous.
|
||||
"""
|
||||
if not call_site_file:
|
||||
return None
|
||||
call_norm = str(call_site_file).replace("\\", "/")
|
||||
call_dir = PurePosixPath(call_norm).parent
|
||||
|
||||
# Tier 1: exact same file.
|
||||
same_file = [cid for cid, f in candidate_files.items()
|
||||
if str(f).replace("\\", "/") == call_norm]
|
||||
if len(same_file) == 1:
|
||||
return same_file[0]
|
||||
if len(same_file) > 1:
|
||||
return None # genuinely ambiguous within one file; bail
|
||||
|
||||
# Tier 2: same directory.
|
||||
same_dir = [cid for cid, f in candidate_files.items()
|
||||
if PurePosixPath(str(f).replace("\\", "/")).parent == call_dir]
|
||||
if len(same_dir) == 1:
|
||||
return same_dir[0]
|
||||
if len(same_dir) > 1:
|
||||
return None
|
||||
|
||||
# Tier 3: longest common path-prefix, computed over path segments. The
|
||||
# winner must be a strict unique maximum, else we bail (guard holds).
|
||||
call_parts = call_dir.parts
|
||||
|
||||
def _common_prefix_len(f: str) -> int:
|
||||
parts = PurePosixPath(str(f).replace("\\", "/")).parent.parts
|
||||
n = 0
|
||||
for a, b in zip(call_parts, parts):
|
||||
if a != b:
|
||||
break
|
||||
n += 1
|
||||
return n
|
||||
|
||||
scored = sorted(
|
||||
((cid, _common_prefix_len(f)) for cid, f in candidate_files.items()),
|
||||
key=lambda kv: kv[1],
|
||||
reverse=True,
|
||||
)
|
||||
if not scored:
|
||||
return None
|
||||
best = scored[0][1]
|
||||
winners = [cid for cid, score in scored if score == best]
|
||||
if len(winners) == 1 and best > 0:
|
||||
return winners[0]
|
||||
return None
|
||||
|
||||
|
||||
def disambiguate_ambiguous_candidates(
|
||||
candidates: list[str],
|
||||
candidate_files: dict[str, str],
|
||||
call_site_file: str,
|
||||
) -> str | None:
|
||||
"""Resolve an ambiguous bare-name call to one candidate, or ``None``.
|
||||
|
||||
Shared god-node tie-breaker (#1553) used by both the inline cross-file call
|
||||
pass in ``extract.py`` and ``symbol_resolution.resolve_cross_file_raw_calls``
|
||||
so the heuristics stay aligned across languages. ``candidates`` is the list
|
||||
of node ids sharing the callee's name; ``candidate_files`` maps each id ->
|
||||
its source_file. Returns the surviving candidate id only when exactly one
|
||||
survives; otherwise ``None`` (caller keeps the god-node guard / ``continue``).
|
||||
|
||||
Tie-breakers, in order:
|
||||
1. NON-TEST preference. Classify the call site and each candidate as
|
||||
test/non-test. When the call site is NON-test, drop test candidates.
|
||||
When the call site IS a test file, prefer test-local candidates
|
||||
(same file first, then any test candidate); fall back to the full set
|
||||
only if no test candidate exists.
|
||||
2. PATH PROXIMITY over whatever survived step 1.
|
||||
"""
|
||||
if not candidates:
|
||||
return None
|
||||
if len(candidates) == 1:
|
||||
return candidates[0]
|
||||
|
||||
call_is_test = _is_test_path(call_site_file)
|
||||
test_cands = [c for c in candidates if _is_test_path(candidate_files.get(c, ""))]
|
||||
nontest_cands = [c for c in candidates if c not in set(test_cands)]
|
||||
|
||||
if call_is_test:
|
||||
# Prefer a test-local definition (same file) first.
|
||||
call_norm = str(call_site_file).replace("\\", "/")
|
||||
same_file_test = [
|
||||
c for c in test_cands
|
||||
if str(candidate_files.get(c, "")).replace("\\", "/") == call_norm
|
||||
]
|
||||
if len(same_file_test) == 1:
|
||||
return same_file_test[0]
|
||||
if test_cands:
|
||||
survivors = test_cands
|
||||
else:
|
||||
survivors = nontest_cands or candidates
|
||||
else:
|
||||
# Non-test call site: drop test mocks/stubs entirely.
|
||||
survivors = nontest_cands
|
||||
|
||||
if len(survivors) == 1:
|
||||
return survivors[0]
|
||||
if not survivors:
|
||||
return None
|
||||
|
||||
# Step 2: path proximity over the survivors.
|
||||
return _path_proximity_winner(
|
||||
call_site_file,
|
||||
{c: candidate_files.get(c, "") for c in survivors},
|
||||
)
|
||||
|
||||
# Bare directory name even when GRAPHIFY_OUT is an absolute path. Used by the
|
||||
# path guards that walk parents looking for the output dir by name, and by the
|
||||
# detect scan-exclude so a custom output dir is never re-ingested as source.
|
||||
GRAPHIFY_OUT_NAME = os.path.basename(os.path.normpath(GRAPHIFY_OUT))
|
||||
|
||||
|
||||
def out_path(*parts: str) -> Path:
|
||||
"""A path inside the configured output dir, e.g. ``out_path("cache")``.
|
||||
|
||||
``Path(GRAPHIFY_OUT) / ...`` resolves correctly for both a relative name
|
||||
("graphify-out") and an absolute override ("/shared/graphify-out").
|
||||
"""
|
||||
return Path(GRAPHIFY_OUT, *parts)
|
||||
|
||||
|
||||
def default_graph_json() -> str:
|
||||
"""Default ``graph.json`` path under the configured output dir.
|
||||
|
||||
The package-wide fallback used by serve/build/benchmark/prs and the CLI read
|
||||
commands so a ``GRAPHIFY_OUT`` override is honoured everywhere, not just where
|
||||
the path is passed explicitly (#1423).
|
||||
"""
|
||||
return str(out_path("graph.json"))
|
||||
+27
-36
@@ -1,5 +1,5 @@
|
||||
from __future__ import annotations
|
||||
from pathlib import Path, PurePosixPath
|
||||
from pathlib import Path
|
||||
from graphify.extract import extract_sql
|
||||
|
||||
|
||||
@@ -58,42 +58,33 @@ def introspect_postgres(dsn: str | None = None) -> dict:
|
||||
""")
|
||||
routines = cur.fetchall()
|
||||
|
||||
# 4. Query foreign keys — grouped by constraint to handle composites.
|
||||
# Read pg_catalog.pg_constraint, NOT information_schema.referential_
|
||||
# constraints: that view only shows constraints where the current
|
||||
# user has WRITE access to the referencing table (owner or a
|
||||
# privilege other than SELECT), so a read-only introspection role
|
||||
# sees zero FK rows while tables/views/routines all appear — the
|
||||
# graph then silently loses every 'references' edge (#1746).
|
||||
# pg_constraint is not privilege-filtered. It also keys constraints
|
||||
# by oid rather than by name (constraint names are only unique per
|
||||
# table, so the old name-based key_column_usage joins could
|
||||
# cross-match same-named constraints on sibling tables).
|
||||
# 4. Query foreign keys — grouped by constraint to handle composites
|
||||
cur.execute("""
|
||||
SELECT
|
||||
con.conname AS constraint_name,
|
||||
ns.nspname AS table_schema,
|
||||
rel.relname AS table_name,
|
||||
(SELECT ARRAY_AGG(att.attname ORDER BY k.ord)
|
||||
FROM UNNEST(con.conkey) WITH ORDINALITY AS k(attnum, ord)
|
||||
JOIN pg_catalog.pg_attribute att
|
||||
ON att.attrelid = con.conrelid AND att.attnum = k.attnum
|
||||
) AS columns,
|
||||
fns.nspname AS foreign_table_schema,
|
||||
frel.relname AS foreign_table_name,
|
||||
(SELECT ARRAY_AGG(att.attname ORDER BY k.ord)
|
||||
FROM UNNEST(con.confkey) WITH ORDINALITY AS k(attnum, ord)
|
||||
JOIN pg_catalog.pg_attribute att
|
||||
ON att.attrelid = con.confrelid AND att.attnum = k.attnum
|
||||
) AS foreign_columns
|
||||
FROM pg_catalog.pg_constraint con
|
||||
JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
|
||||
JOIN pg_catalog.pg_namespace ns ON ns.oid = rel.relnamespace
|
||||
JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
|
||||
JOIN pg_catalog.pg_namespace fns ON fns.oid = frel.relnamespace
|
||||
WHERE con.contype = 'f'
|
||||
AND ns.nspname NOT IN ('pg_catalog', 'information_schema')
|
||||
ORDER BY ns.nspname, rel.relname, con.conname;
|
||||
tc.constraint_name,
|
||||
kcu1.table_schema,
|
||||
kcu1.table_name,
|
||||
ARRAY_AGG(kcu1.column_name ORDER BY kcu1.ordinal_position) AS columns,
|
||||
kcu2.table_schema AS foreign_table_schema,
|
||||
kcu2.table_name AS foreign_table_name,
|
||||
ARRAY_AGG(kcu2.column_name ORDER BY kcu2.ordinal_position) AS foreign_columns
|
||||
FROM
|
||||
information_schema.table_constraints AS tc
|
||||
JOIN information_schema.referential_constraints AS rc
|
||||
ON tc.constraint_name = rc.constraint_name
|
||||
AND tc.table_schema = rc.constraint_schema
|
||||
JOIN information_schema.key_column_usage AS kcu1
|
||||
ON tc.constraint_name = kcu1.constraint_name
|
||||
AND tc.table_schema = kcu1.table_schema
|
||||
JOIN information_schema.key_column_usage AS kcu2
|
||||
ON rc.unique_constraint_name = kcu2.constraint_name
|
||||
AND rc.unique_constraint_schema = kcu2.table_schema
|
||||
AND kcu1.position_in_unique_constraint = kcu2.ordinal_position
|
||||
WHERE tc.constraint_type = 'FOREIGN KEY'
|
||||
AND tc.table_schema NOT IN ('pg_catalog', 'information_schema')
|
||||
GROUP BY tc.constraint_name, kcu1.table_schema, kcu1.table_name,
|
||||
kcu2.table_schema, kcu2.table_name
|
||||
ORDER BY kcu1.table_schema, kcu1.table_name;
|
||||
""")
|
||||
fks = cur.fetchall()
|
||||
finally:
|
||||
@@ -144,7 +135,7 @@ def introspect_postgres(dsn: str | None = None) -> dict:
|
||||
info = psycopg.conninfo.conninfo_to_dict(dsn or "")
|
||||
host = info.get("host", "localhost")
|
||||
dbname = info.get("dbname", "db")
|
||||
virtual_path = PurePosixPath(f"postgresql://{host}/{dbname}")
|
||||
virtual_path = Path(f"postgresql://{host}/{dbname}")
|
||||
|
||||
# Pass virtual path and in-memory DDL content to extract_sql
|
||||
result = extract_sql(virtual_path, content=ddl_string)
|
||||
|
||||
+3
-12
@@ -25,12 +25,6 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import networkx as nx
|
||||
|
||||
from graphify.paths import default_graph_json as _default_graph_json
|
||||
|
||||
|
||||
# ── ANSI colours ─────────────────────────────────────────────────────────────
|
||||
@@ -649,12 +643,9 @@ def triage_with_opus(prs: list[PRInfo], base: str) -> None:
|
||||
print("\n")
|
||||
|
||||
elif backend == "claude-cli":
|
||||
import platform as _platform, shutil as _shutil, subprocess as _sp
|
||||
_claude = "claude"
|
||||
if _platform.system() == "Windows":
|
||||
_claude = _shutil.which("claude.cmd") or _shutil.which("claude") or "claude"
|
||||
import subprocess as _sp
|
||||
proc = _sp.run(
|
||||
[_claude, "-p", "--no-session-persistence"],
|
||||
["claude", "-p", "--no-session-persistence"],
|
||||
input=prompt, capture_output=True, text=True, timeout=120,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
@@ -682,7 +673,7 @@ def cmd_prs(argv: list[str]) -> None:
|
||||
do_conflicts = False
|
||||
show_wrong_base = False
|
||||
pr_number: int | None = None
|
||||
graph_path = Path(_default_graph_json())
|
||||
graph_path = Path("graphify-out/graph.json")
|
||||
|
||||
i = 0
|
||||
while i < len(argv):
|
||||
|
||||
+1
-11
@@ -13,22 +13,12 @@ _NODES_RE = re.compile(r"(\d+)\s+nodes?\s+found")
|
||||
|
||||
|
||||
def _log_path() -> Path | None:
|
||||
# Opt-in only (#1797). The log records every query/path/explain question and
|
||||
# corpus path (and full responses if GRAPHIFY_QUERY_LOG_RESPONSES) in a
|
||||
# plaintext file under ~/.cache — outside any repo's .gitignore/retention. A
|
||||
# default-on record of proprietary queries contradicts graphify's on-device,
|
||||
# no-telemetry posture, so it is OFF unless explicitly enabled:
|
||||
# GRAPHIFY_QUERY_LOG=<path> log to that path, or
|
||||
# GRAPHIFY_QUERY_LOG_ENABLE=1 log to ~/.cache/graphify-queries.log.
|
||||
# GRAPHIFY_QUERY_LOG_DISABLE=1 still forces it off (back-compat, wins).
|
||||
if os.environ.get("GRAPHIFY_QUERY_LOG_DISABLE", "").lower() in ("1", "true", "yes"):
|
||||
return None
|
||||
override = os.environ.get("GRAPHIFY_QUERY_LOG", "").strip()
|
||||
if override:
|
||||
return Path(override).expanduser()
|
||||
if os.environ.get("GRAPHIFY_QUERY_LOG_ENABLE", "").lower() in ("1", "true", "yes"):
|
||||
return Path.home() / ".cache" / "graphify-queries.log"
|
||||
return None
|
||||
return Path.home() / ".cache" / "graphify-queries.log"
|
||||
|
||||
|
||||
def _log_responses() -> bool:
|
||||
|
||||
@@ -1,882 +0,0 @@
|
||||
"""Deterministic "work memory" reflection over graphify-out/memory/.
|
||||
|
||||
`graphify reflect` reads the Q&A memory docs that `graphify save-result` files back
|
||||
into the graph, aggregates their outcome signals (useful / dead_end / corrected), and
|
||||
writes a single lessons artifact an agent can load at the start of the next session:
|
||||
|
||||
- **Preferred sources** — nodes corroborated by multiple ``useful`` answers.
|
||||
- **Tentative** — nodes seen useful only once (not yet corroborated).
|
||||
- **Contested** — nodes with both positive and negative signals; recency decides.
|
||||
- **Known dead ends** — questions/sources marked ``dead_end``; don't re-derive them.
|
||||
- **Corrections** — answers the user corrected, and what the right answer was.
|
||||
|
||||
Source nodes are scored, not counted: each citation contributes a signed,
|
||||
time-decayed value (``useful`` positive, ``dead_end``/``corrected`` negative, with a
|
||||
half-life so a fresh dead end outweighs a months-old useful). A node is only promoted
|
||||
to "preferred" once corroborated by enough distinct results; one save can't mint a
|
||||
trusted lesson. When a graph is in hand, source nodes that no longer exist are dropped.
|
||||
|
||||
It is deterministic: no LLM, stable sort orders, byte-stable output for a given input
|
||||
and a given ``now``. When a graph (`graph.json` + `.graphify_analysis.json`) is available
|
||||
the lessons are also grouped by community label; without it they degrade to a single
|
||||
flat section.
|
||||
|
||||
The artifact lands at ``graphify-out/reflections/LESSONS.md`` rather than inside the wiki
|
||||
because ``graphify export wiki`` deletes every ``wiki/*.md`` on each run — a lessons file
|
||||
written there would be clobbered on the next export.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from graphify.ingest import OUTCOMES
|
||||
from graphify.paths import GRAPHIFY_OUT_NAME
|
||||
|
||||
_UNCATEGORIZED = "Uncategorized"
|
||||
|
||||
# Derived experiential layer written alongside graph.json (a SIDECAR, kept
|
||||
# separate from the durable structural truth in graph.json — no learning_*
|
||||
# fields are ever stamped into the graph itself). Read-surface annotations are
|
||||
# merged in at display time from this file.
|
||||
LEARNING_SIDECAR_NAME = ".graphify_learning.json"
|
||||
_LEARNING_SCHEMA_VERSION = 1
|
||||
_PROVENANCE_CAP = 5 # most-recent (question, date, outcome) entries per node
|
||||
|
||||
# Scoring defaults (both exposed as CLI flags).
|
||||
_DEFAULT_HALF_LIFE_DAYS = 30.0 # a signal's weight halves every 30 days
|
||||
_DEFAULT_MIN_CORROBORATION = 2 # distinct useful results needed to "prefer" a node
|
||||
|
||||
# Rounding for the signed score keeps sort order and the contested verdict stable
|
||||
# across platforms (C pow can differ in the last ULP).
|
||||
_SCORE_NDIGITS = 9
|
||||
|
||||
|
||||
# --- frontmatter parsing -------------------------------------------------------
|
||||
#
|
||||
# save_query_result writes a tiny, hand-built YAML subset (no PyYAML dependency),
|
||||
# so we parse the same subset by hand rather than adding a dependency: scalar
|
||||
# `key: "value"` lines and a `source_nodes: ["a", "b"]` flow list. Anything we
|
||||
# don't recognise is ignored, so foreign .md files in memory/ are skipped cleanly.
|
||||
|
||||
_SCALAR_RE = re.compile(r'^([A-Za-z_][\w-]*):\s*"(.*)"\s*$')
|
||||
_LIST_RE = re.compile(r"^([A-Za-z_][\w-]*):\s*\[(.*)\]\s*$")
|
||||
_DQ_ITEM_RE = re.compile(r'"((?:[^"\\]|\\.)*)"')
|
||||
|
||||
|
||||
def _yaml_unescape(s: str) -> str:
|
||||
"""Reverse the double-quoted escaping that ingest._yaml_str applies."""
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
simple = {"n": "\n", "r": "\r", "t": "\t", "0": "\0", '"': '"', "\\": "\\",
|
||||
"L": "\u2028", "P": "\u2029"} # YAML line/paragraph separators
|
||||
while i < len(s):
|
||||
ch = s[i]
|
||||
if ch == "\\" and i + 1 < len(s):
|
||||
nxt = s[i + 1]
|
||||
if nxt in simple:
|
||||
out.append(simple[nxt])
|
||||
i += 2
|
||||
continue
|
||||
if nxt == "x" and i + 3 < len(s):
|
||||
try:
|
||||
out.append(chr(int(s[i + 2:i + 4], 16)))
|
||||
i += 4
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
if nxt == "u" and i + 5 < len(s):
|
||||
try:
|
||||
out.append(chr(int(s[i + 2:i + 6], 16)))
|
||||
i += 6
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
out.append(ch)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def parse_memory_doc(text: str) -> dict[str, Any] | None:
|
||||
"""Parse the frontmatter of a memory doc into a dict, or None if it has none.
|
||||
|
||||
Returns the recognised fields (``type``, ``date``, ``question``, ``outcome``,
|
||||
``correction``, ``source_nodes``). ``source_nodes`` is always a list.
|
||||
"""
|
||||
if not text.startswith("---"):
|
||||
return None
|
||||
lines = text.splitlines()
|
||||
if not lines or lines[0].strip() != "---":
|
||||
return None
|
||||
fields: dict[str, Any] = {"source_nodes": []}
|
||||
for line in lines[1:]:
|
||||
if line.strip() == "---":
|
||||
break
|
||||
m = _LIST_RE.match(line)
|
||||
if m and m.group(1) == "source_nodes":
|
||||
fields["source_nodes"] = [
|
||||
_yaml_unescape(item) for item in _DQ_ITEM_RE.findall(m.group(2))
|
||||
]
|
||||
continue
|
||||
m = _SCALAR_RE.match(line)
|
||||
if m:
|
||||
key, val = m.group(1), _yaml_unescape(m.group(2))
|
||||
if key in ("type", "date", "question", "outcome", "correction", "contributor"):
|
||||
fields[key] = val
|
||||
return fields
|
||||
|
||||
|
||||
def load_memory_docs(memory_dir: Path) -> list[dict[str, Any]]:
|
||||
"""Parse every memory doc under ``memory_dir``, sorted by date then filename.
|
||||
|
||||
Each record is the parsed frontmatter plus ``_path`` (the source file). Docs
|
||||
without recognisable frontmatter (foreign .md files, the LESSONS.md artifact)
|
||||
are skipped.
|
||||
"""
|
||||
memory_dir = Path(memory_dir)
|
||||
if not memory_dir.exists():
|
||||
return []
|
||||
docs: list[dict[str, Any]] = []
|
||||
for path in sorted(memory_dir.glob("*.md")):
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError):
|
||||
continue
|
||||
parsed = parse_memory_doc(text)
|
||||
if parsed is None:
|
||||
continue
|
||||
parsed["_path"] = path.name
|
||||
docs.append(parsed)
|
||||
# Stable order: by (date, filename) so output is deterministic across runs.
|
||||
docs.sort(key=lambda d: (d.get("date", ""), d["_path"]))
|
||||
return docs
|
||||
|
||||
|
||||
# --- graph / community lookup (optional) ---------------------------------------
|
||||
|
||||
|
||||
def _load_node_community(graph_path: Path, analysis_path: Path,
|
||||
labels_path: Path) -> dict[str, str] | None:
|
||||
"""Build a lookup from node id AND node label -> community label, or None if the
|
||||
graph isn't available.
|
||||
|
||||
Mirrors how `graphify export wiki` reads graph.json + .graphify_analysis.json +
|
||||
.graphify_labels.json. Community membership in the analysis sidecar is keyed by
|
||||
node id, but `save-result` cites nodes by label, so both are mapped — otherwise a
|
||||
cited ``build_from_json()`` never finds its community and every lesson collapses
|
||||
into Uncategorized. Best-effort: any missing/unparseable artifact disables grouping.
|
||||
"""
|
||||
if not graph_path.exists() or not analysis_path.exists():
|
||||
return None
|
||||
try:
|
||||
analysis = json.loads(analysis_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
communities = analysis.get("communities", {})
|
||||
if not communities:
|
||||
return None
|
||||
labels: dict[str, str] = {}
|
||||
if labels_path.exists():
|
||||
try:
|
||||
labels = json.loads(labels_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
labels = {}
|
||||
# id -> label from the graph, so a label-form citation resolves to a community too.
|
||||
id_to_label: dict[str, str] = {}
|
||||
try:
|
||||
gdata = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
for n in gdata.get("nodes", []):
|
||||
if isinstance(n, dict) and n.get("id") is not None and n.get("label") is not None:
|
||||
id_to_label[str(n["id"])] = str(n["label"])
|
||||
except (OSError, ValueError):
|
||||
id_to_label = {}
|
||||
# Sorted cid iteration + setdefault makes any label collision resolve
|
||||
# deterministically (smallest community id wins).
|
||||
node_community: dict[str, str] = {}
|
||||
for cid in sorted(communities, key=str):
|
||||
label = labels.get(str(cid)) or labels.get(cid) or f"Community {cid}"
|
||||
for nid in communities[cid]:
|
||||
nid = str(nid)
|
||||
node_community.setdefault(nid, label)
|
||||
nlabel = id_to_label.get(nid)
|
||||
if nlabel is not None:
|
||||
node_community.setdefault(nlabel, label)
|
||||
return node_community
|
||||
|
||||
|
||||
def _load_known_nodes(graph_path: Path) -> set[str] | None:
|
||||
"""The set of node ids AND labels in the current graph, or None if unavailable.
|
||||
|
||||
Used to drop source nodes from lessons once the code they pointed at is gone
|
||||
(deleted/renamed) — a stale lesson shouldn't keep getting recommended. Both ids
|
||||
and labels are collected because `save-result` records source nodes by their
|
||||
human-readable label (what an agent cites, e.g. ``build_from_json()``), while
|
||||
graph nodes are keyed by id (e.g. ``module_build_from_json``). Matching on either
|
||||
keeps a still-present node and only drops one that survives under neither name —
|
||||
indexing ids alone silently dropped every label-form citation (the common case).
|
||||
"""
|
||||
try:
|
||||
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
nodes = data.get("nodes")
|
||||
if not isinstance(nodes, list):
|
||||
return None
|
||||
known: set[str] = set()
|
||||
for n in nodes:
|
||||
if not isinstance(n, dict):
|
||||
continue
|
||||
if n.get("id") is not None:
|
||||
known.add(str(n["id"]))
|
||||
if n.get("label") is not None:
|
||||
known.add(str(n["label"]))
|
||||
return known or None
|
||||
|
||||
|
||||
def _doc_community(nodes: list[str],
|
||||
node_community: dict[str, str] | None) -> str:
|
||||
"""The community a doc belongs to: the plurality community of its source nodes.
|
||||
|
||||
Ties break to the lexicographically-smallest label, so the result is
|
||||
deterministic regardless of source-node order. Docs with no resolvable
|
||||
community (no source nodes, or no graph) fall into the Uncategorized bucket.
|
||||
"""
|
||||
if not node_community:
|
||||
return _UNCATEGORIZED
|
||||
labels = [node_community[n] for n in nodes if n in node_community]
|
||||
if not labels:
|
||||
return _UNCATEGORIZED
|
||||
counts = Counter(labels)
|
||||
# Highest count wins; on a tie, the smaller label (most-negative count first,
|
||||
# then ascending label) — a plain min() over (-count, label).
|
||||
return min(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0]
|
||||
|
||||
|
||||
# --- scoring helpers -----------------------------------------------------------
|
||||
|
||||
|
||||
def _parse_dt(date_str: str) -> datetime | None:
|
||||
"""Parse an ISO date/datetime to an aware UTC datetime, or None if unparseable."""
|
||||
if not date_str:
|
||||
return None
|
||||
try:
|
||||
dt = datetime.fromisoformat(date_str)
|
||||
except ValueError:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt
|
||||
|
||||
|
||||
def _decay(date_str: str, now: datetime, half_life_days: float) -> float:
|
||||
"""Time-decay weight in (0, 1]: halves every ``half_life_days``.
|
||||
|
||||
Undated/unparseable signals keep full weight (1.0); future-dated ones are
|
||||
clamped to age 0 (also 1.0).
|
||||
"""
|
||||
dt = _parse_dt(date_str)
|
||||
if dt is None or half_life_days <= 0:
|
||||
return 1.0
|
||||
age_days = max(0.0, (now - dt).total_seconds() / 86400.0)
|
||||
return 0.5 ** (age_days / half_life_days)
|
||||
|
||||
|
||||
# --- aggregation ---------------------------------------------------------------
|
||||
|
||||
|
||||
def _empty_bucket() -> dict[str, Any]:
|
||||
return {
|
||||
"counts": {k: 0 for k in (*OUTCOMES, "unmarked")},
|
||||
# node -> running signed, time-decayed score
|
||||
"node_score": {},
|
||||
# node -> distinct positive / negative result counts (for corroboration)
|
||||
"node_pos": Counter(),
|
||||
"node_neg": Counter(),
|
||||
# node -> most recent event date seen (for the contested verdict line)
|
||||
"node_last": {},
|
||||
# node -> list of (date, question, outcome) for useful/corrected citations.
|
||||
# Feeds the sidecar overlay's per-node provenance; never read by LESSONS.md,
|
||||
# so it doesn't touch the aggregate's public shape.
|
||||
"node_provenance": {},
|
||||
"dead_ends": [],
|
||||
"corrections": [],
|
||||
}
|
||||
|
||||
|
||||
def _record_node(bucket: dict[str, Any], node: str, sign: int,
|
||||
weight: float, date: str, *, outcome: str | None = None,
|
||||
question: str = "") -> None:
|
||||
bucket["node_score"][node] = bucket["node_score"].get(node, 0.0) + sign * weight
|
||||
if sign > 0:
|
||||
bucket["node_pos"][node] += 1
|
||||
elif sign < 0:
|
||||
bucket["node_neg"][node] += 1
|
||||
if date > bucket["node_last"].get(node, ""):
|
||||
bucket["node_last"][node] = date
|
||||
# Provenance: only useful/corrected events are recorded (the experiential
|
||||
# trail an agent cares about — what cited this node, and how it turned out).
|
||||
if outcome in ("useful", "corrected"):
|
||||
bucket["node_provenance"].setdefault(node, []).append(
|
||||
(date, question, outcome))
|
||||
|
||||
|
||||
def _finalize_sources(bucket: dict[str, Any],
|
||||
min_corroboration: int) -> dict[str, list]:
|
||||
"""Split a bucket's scored nodes into preferred / tentative / contested lists."""
|
||||
preferred, tentative, contested = [], [], []
|
||||
for node in bucket["node_score"]:
|
||||
pos = bucket["node_pos"][node]
|
||||
neg = bucket["node_neg"][node]
|
||||
score = round(bucket["node_score"][node], _SCORE_NDIGITS)
|
||||
if pos and neg:
|
||||
verdict = "useful" if score > 0 else "dead end" if score < 0 else "even"
|
||||
contested.append({"node": node, "pos": pos, "neg": neg,
|
||||
"score": score, "verdict": verdict,
|
||||
"last": bucket["node_last"].get(node, "")})
|
||||
elif pos: # positive-only
|
||||
entry = {"node": node, "n": pos, "score": score}
|
||||
(preferred if pos >= min_corroboration else tentative).append(entry)
|
||||
# negative-only nodes are surfaced via the dead-ends questions, not here.
|
||||
preferred.sort(key=lambda e: (-e["score"], e["node"]))
|
||||
tentative.sort(key=lambda e: (-e["score"], e["node"]))
|
||||
contested.sort(key=lambda e: (-e["score"], e["node"]))
|
||||
return {"preferred": preferred, "tentative": tentative, "contested": contested}
|
||||
|
||||
|
||||
def _dedupe_by_question(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Collapse repeated questions to one entry. Docs are processed oldest-first, so
|
||||
the last write per question wins (recency — e.g. the most recent correction text).
|
||||
Output is deterministically ordered by (date, question). Without this, saving the
|
||||
same Q&A twice duplicated lines in the dead-ends / corrections lists, even though
|
||||
node scoring already dedups by node.
|
||||
"""
|
||||
latest: dict[str, dict[str, Any]] = {}
|
||||
for it in items:
|
||||
latest[it.get("question", "")] = it
|
||||
return sorted(latest.values(),
|
||||
key=lambda it: (it.get("date", ""), it.get("question", "")))
|
||||
|
||||
|
||||
def aggregate_lessons(docs: list[dict[str, Any]],
|
||||
node_community: dict[str, str] | None = None,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
half_life_days: float = _DEFAULT_HALF_LIFE_DAYS,
|
||||
min_corroboration: int = _DEFAULT_MIN_CORROBORATION,
|
||||
known_nodes: set[str] | None = None) -> dict[str, Any]:
|
||||
"""Aggregate parsed memory docs into a deterministic lessons structure.
|
||||
|
||||
``now`` anchors the time-decay (pass it explicitly for byte-stable output).
|
||||
``known_nodes`` (when given) gates out source nodes no longer in the graph.
|
||||
Returns ``{"total", "counts", "min_corroboration", "preferred", "tentative",
|
||||
"contested", "dead_ends", "corrections", "by_community"}``; ``by_community`` is
|
||||
empty unless a graph is supplied.
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(timezone.utc)
|
||||
elif now.tzinfo is None:
|
||||
now = now.replace(tzinfo=timezone.utc)
|
||||
|
||||
overall = _empty_bucket()
|
||||
by_community: dict[str, dict[str, Any]] = {}
|
||||
|
||||
for doc in docs:
|
||||
outcome = doc.get("outcome")
|
||||
date = doc.get("date", "")
|
||||
# One event per node per doc; drop nodes the graph no longer knows about.
|
||||
raw = doc.get("source_nodes", [])
|
||||
nodes = list(dict.fromkeys(
|
||||
n for n in raw if known_nodes is None or n in known_nodes))
|
||||
community = _doc_community(nodes, node_community)
|
||||
bucket = by_community.setdefault(community, _empty_bucket())
|
||||
|
||||
sign = 1 if outcome == "useful" else -1 if outcome in ("dead_end", "corrected") else 0
|
||||
weight = _decay(date, now, half_life_days) if sign else 0.0
|
||||
|
||||
for target in (overall, bucket):
|
||||
target["counts"][outcome if outcome in OUTCOMES else "unmarked"] += 1
|
||||
if sign:
|
||||
for n in nodes:
|
||||
_record_node(target, n, sign, weight, date,
|
||||
outcome=outcome, question=doc.get("question", ""))
|
||||
if outcome == "dead_end":
|
||||
target["dead_ends"].append(
|
||||
{"question": doc.get("question", ""), "nodes": nodes, "date": date})
|
||||
elif outcome == "corrected":
|
||||
target["corrections"].append(
|
||||
{"question": doc.get("question", ""),
|
||||
"correction": doc.get("correction", ""), "date": date})
|
||||
|
||||
# Only surface per-community grouping when a graph was actually supplied;
|
||||
# without one every doc falls into Uncategorized and the section would just
|
||||
# duplicate the flat "Lessons" block.
|
||||
community_out: dict[str, dict[str, Any]] = {}
|
||||
if node_community:
|
||||
community_out = {
|
||||
label: {"counts": b["counts"], **_finalize_sources(b, min_corroboration),
|
||||
"dead_ends": _dedupe_by_question(b["dead_ends"]),
|
||||
"corrections": _dedupe_by_question(b["corrections"])}
|
||||
for label, b in by_community.items()
|
||||
}
|
||||
|
||||
return {
|
||||
"total": len(docs),
|
||||
"counts": overall["counts"],
|
||||
"min_corroboration": min_corroboration,
|
||||
**_finalize_sources(overall, min_corroboration),
|
||||
"dead_ends": _dedupe_by_question(overall["dead_ends"]),
|
||||
"corrections": _dedupe_by_question(overall["corrections"]),
|
||||
"by_community": community_out,
|
||||
# Private: per-node (date, question, outcome) trail for the sidecar
|
||||
# overlay's provenance. Underscore-prefixed and not rendered by
|
||||
# render_lessons_md, so the public aggregate shape is unchanged.
|
||||
"_node_provenance": overall["node_provenance"],
|
||||
}
|
||||
|
||||
|
||||
# --- rendering -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _render_bucket(out: list[str], data: dict[str, Any], k: int) -> None:
|
||||
preferred = data["preferred"]
|
||||
tentative = data["tentative"]
|
||||
contested = data["contested"]
|
||||
dead_ends = data["dead_ends"]
|
||||
corrections = data["corrections"]
|
||||
|
||||
if preferred:
|
||||
out += [f"**Preferred sources** — corroborated by ≥{k} useful results; "
|
||||
"start here.", ""]
|
||||
for e in preferred:
|
||||
out.append(f"- `{e['node']}` ({e['n']}× useful)")
|
||||
out.append("")
|
||||
if tentative:
|
||||
out += [f"**Tentative** — useful in fewer than {k} results; verify before "
|
||||
"relying.", ""]
|
||||
for e in tentative:
|
||||
out.append(f"- `{e['node']}` ({e['n']}× useful)")
|
||||
out.append("")
|
||||
if contested:
|
||||
out += ["**Contested** — mixed signals; recency decides.", ""]
|
||||
for e in contested:
|
||||
day = e["last"][:10]
|
||||
verdict = ("evenly split" if e["verdict"] == "even"
|
||||
else f"recency leans **{e['verdict']}**")
|
||||
out.append(
|
||||
f"- `{e['node']}` — {e['pos']}× useful, {e['neg']}× "
|
||||
f"dead end/corrected → {verdict}"
|
||||
+ (f" (latest {day})" if day else ""))
|
||||
out.append("")
|
||||
if dead_ends:
|
||||
out += ["**Known dead ends** — led nowhere; don't re-derive.", ""]
|
||||
for d in dead_ends:
|
||||
nodes = ", ".join(f"`{n}`" for n in d["nodes"])
|
||||
out.append(f"- \"{d['question']}\"" + (f" — {nodes}" if nodes else ""))
|
||||
out.append("")
|
||||
if corrections:
|
||||
out += ["**Corrections** — do these differently.", ""]
|
||||
for c in corrections:
|
||||
out.append(f"- \"{c['question']}\" → {c['correction']}")
|
||||
out.append("")
|
||||
if not (preferred or tentative or contested or dead_ends or corrections):
|
||||
out += ["_No marked outcomes yet._", ""]
|
||||
|
||||
|
||||
def render_lessons_md(agg: dict[str, Any]) -> str:
|
||||
"""Render the aggregate into the deterministic LESSONS.md markdown body."""
|
||||
c = agg["counts"]
|
||||
k = agg.get("min_corroboration", _DEFAULT_MIN_CORROBORATION)
|
||||
out: list[str] = [
|
||||
"# Lessons",
|
||||
"",
|
||||
f"_Auto-generated by `graphify reflect` from {agg['total']} session "
|
||||
f"{'memory' if agg['total'] == 1 else 'memories'} in graphify-out/memory/. "
|
||||
"Deterministic; no LLM. Use for orientation — verify before relying, and "
|
||||
"revisit dead ends if the code has changed since._",
|
||||
"",
|
||||
"## Summary",
|
||||
"",
|
||||
f"- {c['useful']} useful · {c['dead_end']} dead ends · "
|
||||
f"{c['corrected']} corrected · {c['unmarked']} unmarked",
|
||||
"",
|
||||
"## Lessons",
|
||||
"",
|
||||
]
|
||||
_render_bucket(out, agg, k)
|
||||
|
||||
if agg["by_community"]:
|
||||
out += ["## By topic", ""]
|
||||
# Uncategorized sorts last; everything else alphabetically.
|
||||
def _topic_key(label: str) -> tuple[int, str]:
|
||||
return (1 if label == _UNCATEGORIZED else 0, label)
|
||||
for label in sorted(agg["by_community"], key=_topic_key):
|
||||
out += [f"### {label}", ""]
|
||||
_render_bucket(out, agg["by_community"][label], k)
|
||||
|
||||
# Single trailing newline, no trailing whitespace lines.
|
||||
return "\n".join(out).rstrip("\n") + "\n"
|
||||
|
||||
|
||||
# --- orchestrator --------------------------------------------------------------
|
||||
|
||||
|
||||
def lessons_fresh(out_path: Path, memory_dir: Path,
|
||||
graph_path: Path | None = None,
|
||||
analysis_path: Path | None = None,
|
||||
labels_path: Path | None = None) -> bool:
|
||||
"""True if ``out_path`` exists and is at least as new as every input that
|
||||
feeds it (the memory docs, and the graph/sidecars when one is used).
|
||||
|
||||
Lets ``graphify reflect --if-stale`` skip a redundant run — e.g. when the git
|
||||
post-commit hook just regenerated ``LESSONS.md`` and an agent then runs reflect
|
||||
again at the start of a session. A missing output is never fresh (it must be
|
||||
built). Mtime-based and best-effort; it only gates whether to *recompute*, not
|
||||
what the recomputation produces (that stays deterministic).
|
||||
"""
|
||||
out_path = Path(out_path)
|
||||
try:
|
||||
out_mtime = out_path.stat().st_mtime
|
||||
except OSError:
|
||||
return False # missing/unreadable -> must build
|
||||
newest = 0.0
|
||||
md = Path(memory_dir)
|
||||
if md.is_dir():
|
||||
for f in md.glob("*.md"):
|
||||
try:
|
||||
newest = max(newest, f.stat().st_mtime)
|
||||
except OSError:
|
||||
pass
|
||||
for input_path in (graph_path, analysis_path, labels_path):
|
||||
if input_path is None:
|
||||
continue
|
||||
gp = Path(input_path)
|
||||
try:
|
||||
newest = max(newest, gp.stat().st_mtime)
|
||||
except OSError:
|
||||
pass
|
||||
return out_mtime >= newest
|
||||
|
||||
|
||||
def reflect(memory_dir: Path, out_path: Path,
|
||||
graph_path: Path | None = None,
|
||||
analysis_path: Path | None = None,
|
||||
labels_path: Path | None = None,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
half_life_days: float = _DEFAULT_HALF_LIFE_DAYS,
|
||||
min_corroboration: int = _DEFAULT_MIN_CORROBORATION,
|
||||
) -> tuple[Path, dict[str, Any]]:
|
||||
"""Scan ``memory_dir``, write the lessons doc to ``out_path``, return (path, agg).
|
||||
|
||||
If ``graph_path`` is given lessons are grouped by community and source nodes no
|
||||
longer in the graph are dropped; otherwise the doc is a single flat section.
|
||||
"""
|
||||
docs = load_memory_docs(memory_dir)
|
||||
|
||||
node_community = None
|
||||
known_nodes = None
|
||||
if graph_path is not None:
|
||||
graph_path = Path(graph_path)
|
||||
analysis_path = Path(analysis_path) if analysis_path else (
|
||||
graph_path.parent / ".graphify_analysis.json")
|
||||
labels_path = Path(labels_path) if labels_path else (
|
||||
graph_path.parent / ".graphify_labels.json")
|
||||
node_community = _load_node_community(graph_path, analysis_path, labels_path)
|
||||
known_nodes = _load_known_nodes(graph_path)
|
||||
|
||||
if now is None:
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
agg = aggregate_lessons(docs, node_community, now=now,
|
||||
half_life_days=half_life_days,
|
||||
min_corroboration=min_corroboration,
|
||||
known_nodes=known_nodes)
|
||||
out_path = Path(out_path)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(render_lessons_md(agg), encoding="utf-8")
|
||||
|
||||
# Also project a derived experiential sidecar next to graph.json when a graph
|
||||
# is in hand. Best-effort: a sidecar failure must never break LESSONS.md.
|
||||
if graph_path is not None:
|
||||
try:
|
||||
write_learning_sidecar(agg, Path(graph_path), now=now)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return out_path, agg
|
||||
|
||||
|
||||
# --- work-memory overlay sidecar ------------------------------------------------
|
||||
#
|
||||
# A derived, experiential projection of the reflect aggregate, written next to
|
||||
# graph.json as ``.graphify_learning.json``. It carries which nodes have proven
|
||||
# preferred/tentative/contested, a code fingerprint for staleness detection, and
|
||||
# a short provenance trail. graph.json (durable structural truth) is never
|
||||
# touched — read surfaces merge this overlay in only at display time.
|
||||
|
||||
|
||||
def _build_id_label_maps(graph_path: Path) -> tuple[dict[str, str], dict[str, list[str]],
|
||||
dict[str, dict[str, Any]]]:
|
||||
"""From graph.json build:
|
||||
|
||||
- ``id_set``: id -> id (every node id, so an id-form citation resolves to itself)
|
||||
- ``label_to_ids``: label -> [ids] (so a label-form citation can be resolved,
|
||||
and ambiguity — one label, many ids — can be detected and skipped)
|
||||
- ``node_by_id``: id -> node dict (for source_file lookup)
|
||||
|
||||
Best-effort; an unreadable/garbage graph yields empty maps.
|
||||
"""
|
||||
id_set: dict[str, str] = {}
|
||||
label_to_ids: dict[str, list[str]] = {}
|
||||
node_by_id: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
data = json.loads(Path(graph_path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return id_set, label_to_ids, node_by_id
|
||||
for n in data.get("nodes", []):
|
||||
if not isinstance(n, dict) or n.get("id") is None:
|
||||
continue
|
||||
nid = str(n["id"])
|
||||
id_set[nid] = nid
|
||||
node_by_id[nid] = n
|
||||
label = n.get("label")
|
||||
if label is not None:
|
||||
label_to_ids.setdefault(str(label), []).append(nid)
|
||||
return id_set, label_to_ids, node_by_id
|
||||
|
||||
|
||||
def _resolve_canonical_id(cited: str, id_set: dict[str, str],
|
||||
label_to_ids: dict[str, list[str]]) -> str | None:
|
||||
"""Resolve a cited node (a label OR an id) to a single canonical node id.
|
||||
|
||||
Returns None if the citation is unresolved (stale — gone from the graph) or
|
||||
ambiguous (a label shared by >1 node id). Such citations can't be displayed
|
||||
against a single node, so the caller skips them.
|
||||
"""
|
||||
if cited in id_set:
|
||||
return id_set[cited]
|
||||
ids = label_to_ids.get(cited)
|
||||
if ids and len(ids) == 1:
|
||||
return ids[0]
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_source_path(src: str, graph_path: Path) -> Path | None:
|
||||
"""Locate a node's ``source_file`` on disk, returning an existing file or None.
|
||||
|
||||
``source_file`` is stored relative to the PROJECT root, but graph.json may
|
||||
live in ``<root>/graphify-out/`` (so its own dir is not the root) or directly
|
||||
at the root (``extract --out .``). Resolve the root in the most-likely order
|
||||
and return the first candidate where the file actually exists, so a defeated
|
||||
heuristic or a stale marker can never strand the file (every node would then
|
||||
look "changed"). The same search runs at write and read time, so the writer
|
||||
and reader resolve to the same file.
|
||||
|
||||
Order: the committed ``.graphify_root`` marker (#686/#1423 — authoritative for
|
||||
an absolute/elsewhere ``GRAPHIFY_OUT`` override); then the layout-appropriate
|
||||
root *first* — graph.json's parent's parent for the ``graphify-out`` layout,
|
||||
or graph.json's own dir for a flat layout — which avoids matching a same-named
|
||||
file one directory up; then the other of the two; then the cwd.
|
||||
"""
|
||||
if not src:
|
||||
return None
|
||||
p = Path(src)
|
||||
if p.is_absolute():
|
||||
return p if p.is_file() else None
|
||||
gp = Path(graph_path)
|
||||
out_dir = gp.parent
|
||||
candidates: list[Path] = []
|
||||
try:
|
||||
recorded = (out_dir / ".graphify_root").read_text(encoding="utf-8").strip()
|
||||
if recorded:
|
||||
candidates.append(Path(recorded))
|
||||
except (OSError, ValueError):
|
||||
pass # unreadable/non-UTF-8 marker -> fall through (best-effort)
|
||||
# Layout-appropriate root first (precision), then the other (robustness).
|
||||
if out_dir.name == GRAPHIFY_OUT_NAME:
|
||||
candidates += [out_dir.parent, out_dir]
|
||||
else:
|
||||
candidates += [out_dir, out_dir.parent]
|
||||
candidates.append(Path("."))
|
||||
seen: set[str] = set()
|
||||
for base in candidates:
|
||||
key = str(base)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
cand = base / p
|
||||
if cand.is_file():
|
||||
return cand
|
||||
return None
|
||||
|
||||
|
||||
def _content_hash(path: Path) -> str:
|
||||
"""SHA256 of file CONTENT only (no path mixed in), so the fingerprint is
|
||||
independent of which root resolved the file — write and read agree, and a
|
||||
committed sidecar stays valid across machines/checkouts."""
|
||||
import hashlib
|
||||
try:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def _code_fingerprint(node: dict[str, Any] | None, graph_path: Path) -> str:
|
||||
"""Content hash of the node's ``source_file``, or '' if unavailable.
|
||||
|
||||
Coarse on purpose — a file-level hash over-flags (any edit to the file marks
|
||||
every node in it stale) rather than under-flags, which is the safe direction
|
||||
for a "re-verify" hint.
|
||||
"""
|
||||
if not node:
|
||||
return ""
|
||||
sp = _resolve_source_path(node.get("source_file") or "", graph_path)
|
||||
return _content_hash(sp) if sp is not None else ""
|
||||
|
||||
|
||||
def _provenance_for(node: str, prov_map: dict[str, list],
|
||||
fallback_outcome: str) -> list[dict[str, str]]:
|
||||
"""Most-recent-first, capped provenance entries for a node.
|
||||
|
||||
``prov_map`` is the aggregate's private per-node (date, question, outcome)
|
||||
trail. ``fallback_outcome`` covers an entry with no recorded trail (shouldn't
|
||||
happen for preferred/tentative/contested, which all have ≥1 positive event).
|
||||
"""
|
||||
events = prov_map.get(node, [])
|
||||
# Sort recent-first; (date desc, then question for a stable tiebreak).
|
||||
ordered = sorted(events, key=lambda e: (e[0], e[1]), reverse=True)
|
||||
out: list[dict[str, str]] = []
|
||||
for date, question, outcome in ordered[:_PROVENANCE_CAP]:
|
||||
out.append({"q": question, "date": date, "outcome": outcome})
|
||||
return out
|
||||
|
||||
|
||||
def build_learning_overlay(agg: dict[str, Any], graph_path: Path,
|
||||
*, now: datetime | None = None) -> dict[str, Any]:
|
||||
"""Project the reflect aggregate into the sidecar's ``{version, generated_at,
|
||||
nodes}`` structure, keyed by canonical node id.
|
||||
|
||||
Built from preferred + tentative + contested (NOT dead_ends — those stay
|
||||
query-scoped, surfaced only in the report). Citations that don't resolve to
|
||||
exactly one node id are skipped.
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(timezone.utc)
|
||||
elif now.tzinfo is None:
|
||||
now = now.replace(tzinfo=timezone.utc)
|
||||
|
||||
graph_path = Path(graph_path)
|
||||
id_set, label_to_ids, node_by_id = _build_id_label_maps(graph_path)
|
||||
prov_map = agg.get("_node_provenance", {})
|
||||
|
||||
# id -> entry; a canonical id can be cited under both its id and label form,
|
||||
# but the aggregate dedups per node string, so collisions here are benign and
|
||||
# resolved deterministically by iteration order (preferred, tentative, contested).
|
||||
nodes_out: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def _add(entry_src: dict[str, Any], status: str) -> None:
|
||||
cited = entry_src["node"]
|
||||
cid = _resolve_canonical_id(cited, id_set, label_to_ids)
|
||||
if cid is None:
|
||||
return # ambiguous or stale — can't display against a single node
|
||||
if cid in nodes_out:
|
||||
return # first status wins (preferred > tentative > contested order)
|
||||
node = node_by_id.get(cid)
|
||||
out: dict[str, Any] = {
|
||||
"status": status,
|
||||
"score": entry_src["score"],
|
||||
"uses": entry_src.get("n", entry_src.get("pos", 0)),
|
||||
"last": entry_src.get("last", ""),
|
||||
"label": str(node.get("label", cited)) if node else str(cited),
|
||||
"source_file": str(node.get("source_file") or "") if node else "",
|
||||
"code_fingerprint": _code_fingerprint(node, graph_path),
|
||||
"provenance": _provenance_for(cited, prov_map, status),
|
||||
}
|
||||
if status == "contested":
|
||||
out["verdict"] = entry_src.get("verdict", "even")
|
||||
out["neg"] = entry_src.get("neg", 0)
|
||||
else:
|
||||
# preferred/tentative carry no contested verdict; derive `last` from
|
||||
# provenance if the finalizer didn't (positive-only buckets do track it
|
||||
# via node_last for contested only).
|
||||
if not out["last"] and out["provenance"]:
|
||||
out["last"] = out["provenance"][0]["date"]
|
||||
nodes_out[cid] = out
|
||||
|
||||
for e in agg.get("preferred", []):
|
||||
_add(e, "preferred")
|
||||
for e in agg.get("tentative", []):
|
||||
_add(e, "tentative")
|
||||
for e in agg.get("contested", []):
|
||||
_add(e, "contested")
|
||||
|
||||
return {
|
||||
"version": _LEARNING_SCHEMA_VERSION,
|
||||
"generated_at": now.isoformat(),
|
||||
"nodes": nodes_out,
|
||||
}
|
||||
|
||||
|
||||
def write_learning_sidecar(agg: dict[str, Any], graph_path: Path,
|
||||
*, now: datetime | None = None) -> Path:
|
||||
"""Write ``.graphify_learning.json`` next to ``graph_path`` deterministically.
|
||||
|
||||
Sorted keys + indent=2 so re-runs on identical input (and a fixed ``now``)
|
||||
are byte-identical. Returns the sidecar path.
|
||||
"""
|
||||
overlay = build_learning_overlay(agg, graph_path, now=now)
|
||||
sidecar = Path(graph_path).parent / LEARNING_SIDECAR_NAME
|
||||
sidecar.write_text(
|
||||
json.dumps(overlay, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
return sidecar
|
||||
|
||||
|
||||
def load_learning_overlay(graph_path: Path) -> dict[str, dict[str, Any]]:
|
||||
"""Load the sidecar next to ``graph_path`` and return ``{node_id -> entry}``
|
||||
with a recomputed ``stale: bool`` per entry. Best-effort -> {} on any error.
|
||||
|
||||
Staleness: recompute ``file_hash(source_file)`` and compare to the entry's
|
||||
stored ``code_fingerprint``. Matching fingerprints -> not stale. Differing,
|
||||
missing-but-recomputable, or a vanished file -> stale (the safe, over-flagging
|
||||
direction). An entry with no stored fingerprint AND no current file is not
|
||||
marked stale (nothing to re-verify).
|
||||
"""
|
||||
sidecar = Path(graph_path).parent / LEARNING_SIDECAR_NAME
|
||||
try:
|
||||
data = json.loads(sidecar.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
nodes = data.get("nodes")
|
||||
if not isinstance(nodes, dict):
|
||||
return {}
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for nid, entry in nodes.items():
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
merged = dict(entry)
|
||||
merged["stale"] = _is_stale(entry, graph_path)
|
||||
out[str(nid)] = merged
|
||||
return out
|
||||
|
||||
|
||||
def _is_stale(entry: dict[str, Any], graph_path: Path) -> bool:
|
||||
"""True if the node's source file changed (or vanished) since the fingerprint
|
||||
was taken. Uses the same file resolution + content hash as the writer, so a
|
||||
freshly-written verdict on unchanged code is never spuriously stale."""
|
||||
src = entry.get("source_file", "")
|
||||
if not src:
|
||||
# No file to track — nothing to re-verify.
|
||||
return False
|
||||
sp = _resolve_source_path(src, graph_path)
|
||||
if sp is None:
|
||||
return True # file gone / unfindable — re-verify
|
||||
stored = entry.get("code_fingerprint", "")
|
||||
if not stored:
|
||||
return True # had a file but never fingerprinted it -> can't trust -> stale
|
||||
return _content_hash(sp) != stored
|
||||
+18
-100
@@ -12,62 +12,6 @@ def _safe_community_name(label: str) -> str:
|
||||
return cleaned or "unnamed"
|
||||
|
||||
|
||||
def load_learning_for_report(graph_path) -> dict | None:
|
||||
"""Assemble the report's work-memory inputs from sibling artifacts.
|
||||
|
||||
Reads the ``.graphify_learning.json`` overlay (preferred sources) next to
|
||||
``graph_path`` and re-aggregates the memory docs for the query-scoped
|
||||
dead-ends. Best-effort: returns None if neither is available, so the report
|
||||
simply omits the section. Never raises.
|
||||
"""
|
||||
from pathlib import Path as _Path
|
||||
try:
|
||||
gp = _Path(graph_path)
|
||||
from graphify.reflect import load_learning_overlay, load_memory_docs, aggregate_lessons
|
||||
overlay = load_learning_overlay(gp)
|
||||
dead_ends: list[dict] = []
|
||||
mem = gp.parent / "memory"
|
||||
if mem.is_dir():
|
||||
agg = aggregate_lessons(load_memory_docs(mem))
|
||||
dead_ends = agg.get("dead_ends", [])
|
||||
if not overlay and not dead_ends:
|
||||
return None
|
||||
return {"overlay": overlay, "dead_ends": dead_ends}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _learning_section(lines: list, learning: dict | None, top_n: int = 10) -> None:
|
||||
"""Append the ``## Work-memory lessons`` section, or nothing when empty."""
|
||||
if not learning:
|
||||
return
|
||||
overlay = learning.get("overlay") or {}
|
||||
dead_ends = learning.get("dead_ends") or []
|
||||
preferred = [
|
||||
(nid, e) for nid, e in overlay.items()
|
||||
if isinstance(e, dict) and e.get("status") == "preferred"
|
||||
]
|
||||
# Most-corroborated first (uses desc), then by score, then id for stability.
|
||||
preferred.sort(key=lambda kv: (-kv[1].get("uses", 0),
|
||||
-float(kv[1].get("score", 0) or 0), kv[0]))
|
||||
if not preferred and not dead_ends:
|
||||
return
|
||||
lines += ["", "## Work-memory lessons"]
|
||||
if preferred:
|
||||
lines += ["", "**Preferred sources** — corroborated by past sessions; start here."]
|
||||
for nid, e in preferred[:top_n]:
|
||||
label = e.get("label") or nid
|
||||
stale = " _(code changed — re-verify)_" if e.get("stale") else ""
|
||||
lines.append(f"- `{label}` ({e.get('uses', 0)}× useful, "
|
||||
f"score={e.get('score', 0)}){stale}")
|
||||
if dead_ends:
|
||||
lines += ["", "**Known dead ends** — questions that led nowhere; don't re-derive."]
|
||||
for d in dead_ends:
|
||||
nodes = ", ".join(f"`{n}`" for n in d.get("nodes", []))
|
||||
lines.append(f"- \"{d.get('question', '')}\""
|
||||
+ (f" -> {nodes}" if nodes else ""))
|
||||
|
||||
|
||||
def generate(
|
||||
G: nx.Graph,
|
||||
communities: dict[int, list[str]],
|
||||
@@ -81,8 +25,6 @@ def generate(
|
||||
suggested_questions: list[dict] | None = None,
|
||||
min_community_size: int = 3,
|
||||
built_at_commit: str | None = None,
|
||||
learning: dict | None = None,
|
||||
obsidian: bool = False,
|
||||
) -> str:
|
||||
today = date.today().isoformat()
|
||||
|
||||
@@ -141,21 +83,14 @@ def generate(
|
||||
"- Run `graphify update .` after code changes (no API cost).",
|
||||
]
|
||||
|
||||
# Community hub navigation. The `_COMMUNITY_*.md` notes these wikilinks target
|
||||
# are only created by the opt-in `--obsidian` export, and the report is written
|
||||
# at build time (before any export runs), so emitting wikilinks by default left
|
||||
# every link dangling — polluting an Obsidian vault's graph view and rendering as
|
||||
# literal brackets everywhere else (#1712). Emit wikilinks only when the caller
|
||||
# signals Obsidian output; otherwise a plain list, which navigates nowhere-to-break.
|
||||
# Community hub navigation - links to _COMMUNITY_*.md files in the Obsidian vault.
|
||||
# Without these, GRAPH_REPORT.md is a dead-end and the vault splits into disconnected components.
|
||||
if non_empty:
|
||||
lines += ["", "## Community Hubs (Navigation)"]
|
||||
for cid in non_empty:
|
||||
label = community_labels.get(cid, f"Community {cid}")
|
||||
if obsidian:
|
||||
safe = _safe_community_name(label)
|
||||
lines.append(f"- [[_COMMUNITY_{safe}|{label}]]")
|
||||
else:
|
||||
lines.append(f"- {label}")
|
||||
safe = _safe_community_name(label)
|
||||
lines.append(f"- [[_COMMUNITY_{safe}|{label}]]")
|
||||
|
||||
lines += [
|
||||
"",
|
||||
@@ -184,30 +119,20 @@ def generate(
|
||||
else:
|
||||
lines.append("- None detected - all connections are within the same source files.")
|
||||
|
||||
# Circular imports surfaced from file-level dependency graph. Only meaningful
|
||||
# for code — a documents-only corpus has no imports, so the section is pure
|
||||
# noise there ("None detected" on every run). Emit it only when the graph
|
||||
# actually contains code (#1657).
|
||||
_has_code = any(
|
||||
d.get("file_type") == "code" for _, d in G.nodes(data=True)
|
||||
) or any(
|
||||
d.get("relation") in ("imports", "imports_from")
|
||||
for *_e, d in G.edges(data=True)
|
||||
)
|
||||
if _has_code:
|
||||
from .analyze import find_import_cycles
|
||||
cycles = find_import_cycles(G)
|
||||
lines += ["", "## Import Cycles"]
|
||||
if cycles:
|
||||
for c in cycles:
|
||||
cycle = c.get("cycle", [])
|
||||
length = c.get("length", len(cycle))
|
||||
if not cycle:
|
||||
continue
|
||||
cycle_path = " -> ".join(cycle + [cycle[0]])
|
||||
lines.append(f"- {length}-file cycle: `{cycle_path}`")
|
||||
else:
|
||||
lines.append("- None detected.")
|
||||
# Circular imports surfaced from file-level dependency graph.
|
||||
from .analyze import find_import_cycles
|
||||
cycles = find_import_cycles(G)
|
||||
lines += ["", "## Import Cycles"]
|
||||
if cycles:
|
||||
for c in cycles:
|
||||
cycle = c.get("cycle", [])
|
||||
length = c.get("length", len(cycle))
|
||||
if not cycle:
|
||||
continue
|
||||
cycle_path = " -> ".join(cycle + [cycle[0]])
|
||||
lines.append(f"- {length}-file cycle: `{cycle_path}`")
|
||||
else:
|
||||
lines.append("- None detected.")
|
||||
|
||||
hyperedges = G.graph.get("hyperedges", [])
|
||||
if hyperedges:
|
||||
@@ -277,13 +202,6 @@ def generate(
|
||||
if amb_pct > 20:
|
||||
lines.append(f"- **High ambiguity: {amb_pct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.")
|
||||
|
||||
# --- Work-memory lessons (derived overlay) ---
|
||||
# Preferred sources come from the .graphify_learning.json sidecar; the
|
||||
# query-scoped dead-ends come from the reflect aggregate. Section omitted
|
||||
# entirely when neither is present, so a graph with no work-memory is
|
||||
# byte-identical to the pre-feature report.
|
||||
_learning_section(lines, learning)
|
||||
|
||||
if suggested_questions:
|
||||
lines += ["", "## Suggested Questions"]
|
||||
no_signal = len(suggested_questions) == 1 and suggested_questions[0].get("type") == "no_signal"
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
"""Registry for cross-file, language-specific resolution passes.
|
||||
|
||||
Some call/reference edges can only be resolved with language-specific knowledge
|
||||
(receiver typing, qualified member calls, framework conventions). Historically
|
||||
these ran as a hand-wired sequence of suffix-gated
|
||||
``if <lang>_paths: try: _resolve_<lang>(...)`` blocks at the tail of
|
||||
``extract.extract()``. That pattern is the de-facto extension point for
|
||||
per-language resolution; this module formalizes it so a new language plugs in by
|
||||
registering one ``LanguageResolver`` instead of editing ``extract()``'s body.
|
||||
|
||||
This module deliberately knows nothing about any specific language — languages
|
||||
register themselves (see ``extract.py``), keeping the dependency direction one
|
||||
way (``extract`` → ``resolver_registry``) and this seam small and reviewable on
|
||||
its own, separate from the multi-thousand-line ``extract`` module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LanguageResolver:
|
||||
"""One cross-file, language-specific resolution pass.
|
||||
|
||||
``resolve`` has the signature ``(per_file, all_nodes, all_edges) -> None`` and
|
||||
mutates ``all_nodes`` / ``all_edges`` in place, matching the existing
|
||||
member-call resolvers. ``suffixes`` gates activation: the pass runs only when
|
||||
the corpus contains at least one file with one of these extensions.
|
||||
"""
|
||||
|
||||
name: str
|
||||
suffixes: frozenset
|
||||
resolve: Callable
|
||||
|
||||
|
||||
# Module-level registry, populated by callers via register(). Ordered: resolvers
|
||||
# run in registration order, preserving any required sequencing between passes.
|
||||
_REGISTRY: list[LanguageResolver] = []
|
||||
|
||||
|
||||
def register(resolver: LanguageResolver) -> LanguageResolver:
|
||||
"""Append a resolver to the global registry and return it (for inline use)."""
|
||||
_REGISTRY.append(resolver)
|
||||
return resolver
|
||||
|
||||
|
||||
def registered_resolvers() -> list[LanguageResolver]:
|
||||
"""Return a copy of the registered resolvers, in registration order."""
|
||||
return list(_REGISTRY)
|
||||
|
||||
|
||||
def run_language_resolvers(
|
||||
paths: Sequence[Path],
|
||||
per_file: list[dict],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
*,
|
||||
resolvers: Sequence[LanguageResolver] | None = None,
|
||||
) -> None:
|
||||
"""Run every resolver whose suffix appears in ``paths``.
|
||||
|
||||
Behaviorally identical to the prior hand-wired sequence of suffix-gated,
|
||||
try/except-wrapped passes: same activation rule (suffix present), same
|
||||
failure handling (log a warning and continue to the next pass), same
|
||||
execution order (registration order).
|
||||
|
||||
``resolvers`` defaults to the global registry; tests pass an explicit list to
|
||||
exercise the driver in isolation.
|
||||
"""
|
||||
active = _REGISTRY if resolvers is None else resolvers
|
||||
suffixes_present = {p.suffix for p in paths}
|
||||
for resolver in active:
|
||||
if not (resolver.suffixes & suffixes_present):
|
||||
continue
|
||||
try:
|
||||
resolver.resolve(per_file, all_nodes, all_edges)
|
||||
except Exception as exc:
|
||||
_LOG.warning("%s resolution failed, skipping: %s", resolver.name, exc)
|
||||
@@ -1,169 +0,0 @@
|
||||
"""Type-aware cross-file resolution for Ruby member calls.
|
||||
|
||||
Ruby has no type annotations and reuses method names heavily, so resolving
|
||||
``obj.method()`` by globally-unique name is both lossy (drops on collision) and
|
||||
unsafe (can attach to the wrong same-named method). This resolver instead uses
|
||||
the receiver's *type*, inferred at extraction time from local
|
||||
``var = ClassName.new`` bindings and carried on each member-call raw_call as
|
||||
``receiver_type``.
|
||||
|
||||
It resolves two shapes, both at EXTRACTED (1.0) confidence and only when the
|
||||
target is certain (single owning class, single owned method) — bail otherwise:
|
||||
|
||||
* ``Processor.new`` -> a ``calls`` edge to the ``Processor`` class
|
||||
* ``p.run`` where ``p`` is a ``Processor`` -> a ``calls`` edge to ``Processor#run``
|
||||
|
||||
Registered into graphify.resolver_registry and run by extract() after id
|
||||
disambiguation, so node ids and raw_call caller_nids are final.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _key(label: str) -> str:
|
||||
"""Normalize a class/method label to a comparison key (drop punctuation)."""
|
||||
return re.sub(r"[^a-zA-Z0-9]+", "", str(label)).lower()
|
||||
|
||||
|
||||
# A Ruby class/module container node is labelled with a bare constant
|
||||
# (``Processor``, ``TaxCalculator``); methods end in ``()`` and files in ``.rb``.
|
||||
# Lets us register method-less containers (a ``Class.new(StandardError)`` error
|
||||
# class, an empty module) that have no `method` edge to be found by.
|
||||
_BARE_CONST_RE = re.compile(r"^[A-Z][A-Za-z0-9_]*$")
|
||||
|
||||
|
||||
def _ruby_raw_calls(per_file: list[dict]) -> list[dict]:
|
||||
calls: list[dict] = []
|
||||
for result in per_file:
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
for rc in result.get("raw_calls", []):
|
||||
if not isinstance(rc, dict):
|
||||
continue
|
||||
sf = str(rc.get("source_file", ""))
|
||||
if sf.endswith((".rb", ".rake")):
|
||||
calls.append(rc)
|
||||
return calls
|
||||
|
||||
|
||||
def resolve_ruby_member_calls(
|
||||
per_file: list[dict],
|
||||
all_nodes: list[dict],
|
||||
all_edges: list[dict],
|
||||
) -> None:
|
||||
"""Resolve Ruby ``Class.new`` and typed ``var.method`` calls by receiver type.
|
||||
|
||||
Purely additive: only emits edges the shared (name-based) call pass skips
|
||||
because they are member calls. Each emission requires a single owning class
|
||||
(god-node guard) so an ambiguous class name resolves to nothing rather than a
|
||||
wrong edge.
|
||||
"""
|
||||
node_by_id: dict[str, dict] = {n.get("id"): n for n in all_nodes}
|
||||
|
||||
# class label key -> [class node ids]; (class_node_id, method_key) -> method id
|
||||
class_def_nids: dict[str, list[str]] = {}
|
||||
method_index: dict[tuple[str, str], str] = {}
|
||||
for e in all_edges:
|
||||
if e.get("relation") != "method":
|
||||
continue
|
||||
src, tgt = e.get("source"), e.get("target")
|
||||
cnode = node_by_id.get(src)
|
||||
if cnode is not None:
|
||||
class_def_nids.setdefault(_key(cnode.get("label", "")), []).append(str(src))
|
||||
tnode = node_by_id.get(tgt)
|
||||
if tnode is not None:
|
||||
method_index[(str(src), _key(tnode.get("label", "")))] = str(tgt)
|
||||
# Also register class/module container nodes that own no `method` edge — a
|
||||
# method-less `Class.new(StandardError)` or an empty module — so a constant
|
||||
# receiver still resolves to a real node (#1640/#1634). External base stubs
|
||||
# carry an empty source_file, so the `.rb` filter keeps them out.
|
||||
for n in all_nodes:
|
||||
nid = n.get("id")
|
||||
sf = str(n.get("source_file", ""))
|
||||
if nid and sf.endswith((".rb", ".rake")) and _BARE_CONST_RE.match(str(n.get("label", ""))):
|
||||
class_def_nids.setdefault(_key(n.get("label", "")), []).append(str(nid))
|
||||
for k in list(class_def_nids):
|
||||
class_def_nids[k] = sorted(set(class_def_nids[k]))
|
||||
|
||||
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
|
||||
|
||||
def _unique_class(name: str) -> str | None:
|
||||
nids = class_def_nids.get(_key(name), [])
|
||||
return nids[0] if len(nids) == 1 else None
|
||||
|
||||
def _emit(caller: str, target: str, rc: dict[str, Any],
|
||||
relation: str = "calls", context: str = "call") -> None:
|
||||
if not caller or not target or caller == target:
|
||||
return
|
||||
if (caller, target) in existing_pairs:
|
||||
return
|
||||
existing_pairs.add((caller, target))
|
||||
all_edges.append({
|
||||
"source": caller,
|
||||
"target": target,
|
||||
"relation": relation,
|
||||
"context": context,
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": rc.get("source_file", ""),
|
||||
"source_location": rc.get("source_location"),
|
||||
"weight": 1.0,
|
||||
})
|
||||
|
||||
# `include`/`extend`/`prepend <Const>` mixins (#1668): resolve the module by
|
||||
# its constant name to the single owning module/class node and emit a
|
||||
# `mixes_in` edge, under the same single-definition god-node guard. An
|
||||
# ambiguous or unresolved constant produces no edge.
|
||||
for rc in _ruby_raw_calls(per_file):
|
||||
if not rc.get("is_mixin"):
|
||||
continue
|
||||
caller = str(rc.get("caller_nid", ""))
|
||||
module_name = rc.get("callee")
|
||||
if not caller or not module_name:
|
||||
continue
|
||||
target = _unique_class(str(module_name))
|
||||
if target is not None:
|
||||
_emit(caller, target, rc, relation="mixes_in", context="mixin")
|
||||
|
||||
for rc in _ruby_raw_calls(per_file):
|
||||
if not rc.get("is_member_call"):
|
||||
continue
|
||||
caller = str(rc.get("caller_nid", ""))
|
||||
callee = rc.get("callee")
|
||||
if not caller or not callee:
|
||||
continue
|
||||
|
||||
# Constant receiver: `Processor.new` (instantiation) or `Service.call` /
|
||||
# `Model.where` (singleton / class method). The bare method name would
|
||||
# collide with unrelated same-named methods, so we resolve by the
|
||||
# receiver's class under the single-owning-class god-node guard.
|
||||
receiver = rc.get("receiver")
|
||||
if receiver and str(receiver)[:1].isupper():
|
||||
class_nid = _unique_class(str(receiver))
|
||||
if class_nid is not None:
|
||||
if callee == "new":
|
||||
_emit(caller, class_nid, rc)
|
||||
else:
|
||||
# Emit to the singleton/instance method the class owns
|
||||
# (`def self.call`, which the extractor indexes); otherwise
|
||||
# to the class node itself, so inherited/dynamic class methods
|
||||
# like ActiveRecord `where`/`find_by` still give correct
|
||||
# blast-radius. An ambiguous receiver bails to nothing.
|
||||
method_nid = method_index.get((class_nid, _key(str(callee))))
|
||||
_emit(caller, method_nid or class_nid, rc)
|
||||
continue
|
||||
|
||||
# `p.run` where p's type is known -> edge to that class's method.
|
||||
receiver_type = rc.get("receiver_type")
|
||||
if not receiver_type:
|
||||
continue
|
||||
class_nid = _unique_class(str(receiver_type))
|
||||
if class_nid is None:
|
||||
continue
|
||||
method_nid = method_index.get((class_nid, _key(str(callee))))
|
||||
if method_nid is None:
|
||||
continue
|
||||
_emit(caller, method_nid, rc)
|
||||
+40
-164
@@ -1,9 +1,8 @@
|
||||
# Security helpers - URL validation, safe fetch, path guards, label sanitisation
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import html
|
||||
import http.client
|
||||
import os
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
@@ -15,8 +14,6 @@ from typing import Any
|
||||
import ipaddress
|
||||
import socket
|
||||
|
||||
from graphify.paths import GRAPHIFY_OUT, GRAPHIFY_OUT_NAME
|
||||
|
||||
_ALLOWED_SCHEMES = {"http", "https"}
|
||||
_MAX_FETCH_BYTES = 52_428_800 # 50 MB hard cap for binary downloads
|
||||
_MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
|
||||
@@ -25,46 +22,8 @@ _MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
|
||||
# JSON-parsing them into a dict. Without this, a multi-gigabyte (or
|
||||
# specifically crafted) graph.json can exhaust process memory during
|
||||
# json.loads + node_link_graph rehydration.
|
||||
# Default fallback cap. Kept as a module-level constant so the value is
|
||||
# discoverable and so existing callers/tests that reference it directly keep
|
||||
# working; the effective cap is resolved at call time by
|
||||
# ``_max_graph_file_bytes`` (which lets ``GRAPHIFY_MAX_GRAPH_BYTES`` override it).
|
||||
_MAX_GRAPH_FILE_BYTES = 512 * 1024 * 1024 # 512 MiB
|
||||
|
||||
|
||||
def _max_graph_file_bytes() -> int:
|
||||
"""Return the graph.json size cap in bytes.
|
||||
|
||||
Honors the ``GRAPHIFY_MAX_GRAPH_BYTES`` environment variable so users with
|
||||
large codebases can raise the limit without editing source. The value may
|
||||
be plain bytes (``671088640``) or carry an ``MB`` / ``GB`` suffix
|
||||
(``640MB``, ``2GB`` — case-insensitive, binary multipliers: ``MB`` is
|
||||
1024*1024 and ``GB`` is 1024*1024*1024, i.e. MiB / GiB).
|
||||
Falls back to ``_MAX_GRAPH_FILE_BYTES`` (512 MiB) when the env var is unset,
|
||||
blank, or unparseable.
|
||||
|
||||
Read fresh on every call so the env var can be set before import and still
|
||||
take effect.
|
||||
"""
|
||||
raw = os.environ.get("GRAPHIFY_MAX_GRAPH_BYTES", "").strip()
|
||||
if not raw:
|
||||
return _MAX_GRAPH_FILE_BYTES
|
||||
text = raw.upper()
|
||||
multiplier = 1
|
||||
if text.endswith("GB"):
|
||||
multiplier = 1024 * 1024 * 1024
|
||||
text = text[:-2].strip()
|
||||
elif text.endswith("MB"):
|
||||
multiplier = 1024 * 1024
|
||||
text = text[:-2].strip()
|
||||
try:
|
||||
value = int(text)
|
||||
except ValueError:
|
||||
return _MAX_GRAPH_FILE_BYTES
|
||||
if value <= 0:
|
||||
return _MAX_GRAPH_FILE_BYTES
|
||||
return value * multiplier
|
||||
|
||||
# AWS metadata, link-local, and common cloud metadata endpoints
|
||||
_BLOCKED_HOSTS = {"metadata.google.internal", "metadata.google.com"}
|
||||
|
||||
@@ -80,26 +39,6 @@ _NAT64_WKP = ipaddress.ip_network("64:ff9b::/96")
|
||||
# URL validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _ip_is_blocked(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
||||
"""Return True if *ip* falls in a private/reserved/internal range.
|
||||
|
||||
Shared by validate_url (pre-flight DNS check) and the SSRF-guarded
|
||||
connection classes (connect-time check) so both use identical logic.
|
||||
NAT64 well-known-prefix addresses are unwrapped to their embedded IPv4
|
||||
before the check, since those carry legitimate public traffic.
|
||||
"""
|
||||
# For NAT64 addresses, check the embedded IPv4 instead of the wrapper
|
||||
if isinstance(ip, ipaddress.IPv6Address) and ip in _NAT64_WKP:
|
||||
ip = ipaddress.ip_address(int(ip) & 0xFFFFFFFF)
|
||||
return (
|
||||
ip.is_private
|
||||
or ip.is_reserved
|
||||
or ip.is_loopback
|
||||
or ip.is_link_local
|
||||
or ip in _CGN_NETWORK
|
||||
)
|
||||
|
||||
|
||||
def validate_url(url: str) -> str:
|
||||
"""Raise ValueError if *url* is not http or https, or targets a private/internal IP.
|
||||
|
||||
@@ -130,7 +69,11 @@ def validate_url(url: str) -> str:
|
||||
for info in infos:
|
||||
addr = info[4][0]
|
||||
ip = ipaddress.ip_address(addr)
|
||||
if _ip_is_blocked(ip):
|
||||
# For NAT64 addresses, check the embedded IPv4 instead of the wrapper
|
||||
if isinstance(ip, ipaddress.IPv6Address) and ip in _NAT64_WKP:
|
||||
embedded = ipaddress.ip_address(int(ip) & 0xFFFFFFFF)
|
||||
ip = embedded
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local or ip in _CGN_NETWORK:
|
||||
raise ValueError(
|
||||
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
|
||||
f"Got: {url!r}"
|
||||
@@ -143,89 +86,35 @@ def validate_url(url: str) -> str:
|
||||
return url
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SSRF-guarded connections
|
||||
#
|
||||
# Instead of monkey-patching the process-global socket.getaddrinfo (a
|
||||
# non-thread-safe TOCTOU hazard when multiple fetches run concurrently),
|
||||
# we subclass the HTTP(S) connection so each connection resolves DNS exactly
|
||||
# once, validates the resulting IP, and then connects to that exact IP. There
|
||||
# is no second resolution, so a DNS-rebind attack cannot swap in a private
|
||||
# address (e.g. 169.254.169.254) between validation and connection.
|
||||
# ---------------------------------------------------------------------------
|
||||
@contextlib.contextmanager
|
||||
def _ssrf_guarded_socket():
|
||||
"""Patch socket.getaddrinfo for the duration of a fetch to catch DNS rebinding.
|
||||
|
||||
|
||||
def _resolve_and_validate(host: str, port: int) -> tuple[int, str]:
|
||||
"""Resolve *host* once and return (family, validated_ip) for the first
|
||||
address that is not in a blocked range.
|
||||
|
||||
Raises OSError if every resolved address is private/reserved/internal,
|
||||
matching the failure mode urllib/http.client expect from connect().
|
||||
Validates every IP that urllib resolves so a DNS server cannot return a public IP
|
||||
for validate_url and swap to a private IP for the actual connection (TOCTOU fix).
|
||||
Not thread-safe, but graphify is a single-threaded CLI tool.
|
||||
"""
|
||||
infos = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
|
||||
for family, _type, _proto, _canon, sockaddr in infos:
|
||||
addr = sockaddr[0]
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except ValueError:
|
||||
continue
|
||||
if _ip_is_blocked(ip):
|
||||
raise OSError(
|
||||
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
|
||||
)
|
||||
return family, addr
|
||||
raise OSError(f"SSRF blocked: no usable address resolved from '{host}'")
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def _guarded(host, port, *args, **kwargs):
|
||||
results = original(host, port, *args, **kwargs)
|
||||
for info in results:
|
||||
addr = info[4][0]
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except ValueError:
|
||||
continue
|
||||
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local or ip in _CGN_NETWORK:
|
||||
raise OSError(
|
||||
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
|
||||
)
|
||||
return results
|
||||
|
||||
class _SSRFGuardedHTTPConnection(http.client.HTTPConnection):
|
||||
"""HTTPConnection that resolves + validates DNS once, then connects to the
|
||||
exact validated IP (no second resolution = no DNS-rebind TOCTOU)."""
|
||||
|
||||
def connect(self) -> None:
|
||||
family, ip = _resolve_and_validate(self.host, self.port)
|
||||
self.sock = socket.create_connection(
|
||||
(ip, self.port),
|
||||
self.timeout,
|
||||
self.source_address,
|
||||
)
|
||||
if self._tunnel_host:
|
||||
self._tunnel()
|
||||
|
||||
|
||||
class _SSRFGuardedHTTPSConnection(http.client.HTTPSConnection):
|
||||
"""HTTPSConnection variant of _SSRFGuardedHTTPConnection.
|
||||
|
||||
Connects to the validated IP but performs the TLS handshake with
|
||||
server_hostname set to the original hostname so SNI / certificate
|
||||
validation work correctly (validating against the IP would break TLS).
|
||||
"""
|
||||
|
||||
def connect(self) -> None:
|
||||
family, ip = _resolve_and_validate(self.host, self.port)
|
||||
sock = socket.create_connection(
|
||||
(ip, self.port),
|
||||
self.timeout,
|
||||
self.source_address,
|
||||
)
|
||||
if self._tunnel_host:
|
||||
self.sock = sock
|
||||
self._tunnel()
|
||||
sock = self.sock
|
||||
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
|
||||
|
||||
|
||||
class _SSRFGuardedHTTPHandler(urllib.request.HTTPHandler):
|
||||
"""urllib handler that routes http:// through _SSRFGuardedHTTPConnection."""
|
||||
|
||||
def http_open(self, req):
|
||||
return self.do_open(_SSRFGuardedHTTPConnection, req)
|
||||
|
||||
|
||||
class _SSRFGuardedHTTPSHandler(urllib.request.HTTPSHandler):
|
||||
"""urllib handler that routes https:// through _SSRFGuardedHTTPSConnection."""
|
||||
|
||||
def https_open(self, req):
|
||||
return self.do_open(_SSRFGuardedHTTPSConnection, req)
|
||||
socket.getaddrinfo = _guarded
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
socket.getaddrinfo = original
|
||||
|
||||
|
||||
class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
@@ -241,14 +130,7 @@ class _NoFileRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
|
||||
|
||||
def _build_opener() -> urllib.request.OpenerDirector:
|
||||
# build_opener replaces the default HTTP(S)Handlers with our SSRF-guarded
|
||||
# subclasses, so every connection resolves+validates DNS once and connects
|
||||
# to that exact IP. Thread-safe: no process-global state is mutated.
|
||||
return urllib.request.build_opener(
|
||||
_SSRFGuardedHTTPHandler,
|
||||
_SSRFGuardedHTTPSHandler,
|
||||
_NoFileRedirectHandler,
|
||||
)
|
||||
return urllib.request.build_opener(_NoFileRedirectHandler)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -275,7 +157,7 @@ def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -
|
||||
opener = _build_opener()
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 graphify/1.0"})
|
||||
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
with _ssrf_guarded_socket(), opener.open(req, timeout=timeout) as resp:
|
||||
# urllib raises HTTPError for non-2xx when using urlopen directly;
|
||||
# with a custom opener we check manually to be safe.
|
||||
status = getattr(resp, "status", None) or getattr(resp, "code", None)
|
||||
@@ -326,11 +208,11 @@ def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
|
||||
if base is None:
|
||||
resolved_hint = Path(path).resolve()
|
||||
for candidate in [resolved_hint, *resolved_hint.parents]:
|
||||
if candidate.name == GRAPHIFY_OUT_NAME:
|
||||
if candidate.name == "graphify-out":
|
||||
base = candidate
|
||||
break
|
||||
if base is None:
|
||||
base = Path(GRAPHIFY_OUT).resolve()
|
||||
base = Path("graphify-out").resolve()
|
||||
|
||||
base = base.resolve()
|
||||
if not base.exists():
|
||||
@@ -355,31 +237,25 @@ def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
|
||||
|
||||
|
||||
def check_graph_file_size_cap(path: Path) -> None:
|
||||
"""Reject *path* if its size exceeds the configured graph-file cap.
|
||||
"""Reject *path* if its size exceeds ``_MAX_GRAPH_FILE_BYTES``.
|
||||
|
||||
Protects callers from memory bombs by failing fast before a multi-GiB
|
||||
graph.json is read into memory and JSON-parsed. Silently returns when
|
||||
``path.stat()`` cannot be read — the caller's own existence/path check
|
||||
is expected to surface a clearer error in that case.
|
||||
|
||||
The cap is resolved on every call via :func:`_max_graph_file_bytes`, so the
|
||||
``GRAPHIFY_MAX_GRAPH_BYTES`` env var can be set before import and still
|
||||
apply.
|
||||
|
||||
Raises:
|
||||
ValueError - file size exceeds the cap. The message includes the
|
||||
observed size, the cap, and how to raise the limit.
|
||||
observed size and the cap so callers can show a usable error.
|
||||
"""
|
||||
cap = _max_graph_file_bytes()
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
except OSError:
|
||||
return
|
||||
if size > cap:
|
||||
if size > _MAX_GRAPH_FILE_BYTES:
|
||||
raise ValueError(
|
||||
f"graph file {path} is {size:_d} bytes, exceeds {cap:_d}-byte cap\n"
|
||||
f"(set GRAPHIFY_MAX_GRAPH_BYTES=<bytes> or "
|
||||
f"GRAPHIFY_MAX_GRAPH_BYTES=<N>GB to raise the limit)"
|
||||
f"graph file {path} is {size:_d} bytes, "
|
||||
f"exceeds {_MAX_GRAPH_FILE_BYTES:_d}-byte cap"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -12,8 +12,6 @@ import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from .build import _normalize_hyperedge_members
|
||||
|
||||
# Labels longer than this many characters, or containing >= this many words,
|
||||
# are candidates for being sentence-like rationale text rather than entity names.
|
||||
_RATIONALE_MIN_CHARS = 80
|
||||
@@ -103,10 +101,6 @@ def validate_semantic_fragment(fragment: object) -> list[str]:
|
||||
if not isinstance(he, dict):
|
||||
errors.append(f"hyperedges[{i}] must be an object")
|
||||
continue
|
||||
# Fold alias member keys (members/node_ids) onto `nodes` (#1561) so
|
||||
# an alias-keyed hyperedge isn't rejected here for "nodes must be a
|
||||
# list" before it ever reaches build's normalization.
|
||||
_normalize_hyperedge_members(he)
|
||||
_validate_semantic_id(errors, f"hyperedges[{i}].id", he.get("id"))
|
||||
he_nodes = he.get("nodes")
|
||||
if not isinstance(he_nodes, list):
|
||||
@@ -271,10 +265,6 @@ def sanitize_semantic_fragment(fragment: dict) -> dict:
|
||||
for he in hyperedges:
|
||||
if not isinstance(he, dict):
|
||||
continue
|
||||
# Fold alias member keys (members/node_ids) onto `nodes` (#1561) so an
|
||||
# alias-keyed hyperedge isn't silently dropped below for a missing
|
||||
# `nodes` list before build can canonicalize it.
|
||||
_normalize_hyperedge_members(he)
|
||||
he_nodes = he.get("nodes")
|
||||
if not isinstance(he_nodes, list):
|
||||
continue
|
||||
|
||||
+69
-479
@@ -4,13 +4,11 @@ import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
from array import array
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from graphify.security import sanitize_label, check_graph_file_size_cap
|
||||
from graphify.build import edge_data
|
||||
from graphify.paths import default_graph_json as _default_graph_json
|
||||
|
||||
try:
|
||||
import jieba as _jieba # type: ignore[import-untyped]
|
||||
@@ -32,28 +30,9 @@ def _load_graph(graph_path: str) -> nx.Graph:
|
||||
data = dict(data, links=data["edges"])
|
||||
data = {**data, "directed": True}
|
||||
try:
|
||||
from graphify.build import graph_has_legacy_ids as _legacy
|
||||
if _legacy(data.get("nodes", [])):
|
||||
print(
|
||||
"[graphify] note: this graph uses the pre-#1504 node-ID scheme; "
|
||||
"rebuild with `graphify extract --force` for path-qualified IDs.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
G = json_graph.node_link_graph(data, edges="links")
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
G = json_graph.node_link_graph(data)
|
||||
# Attach the work-memory overlay (derived sidecar next to graph.json) so
|
||||
# the query/MCP read surface can annotate NODE lines display-only. Empty
|
||||
# when no sidecar exists, leaving un-annotated output byte-identical.
|
||||
try:
|
||||
from graphify.reflect import load_learning_overlay as _llo
|
||||
G.graph["_learning_overlay"] = _llo(resolved)
|
||||
except Exception:
|
||||
G.graph["_learning_overlay"] = {}
|
||||
return G
|
||||
return json_graph.node_link_graph(data)
|
||||
except (ValueError, FileNotFoundError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -72,10 +51,8 @@ def _communities_from_graph(G: nx.Graph) -> dict[int, list[str]]:
|
||||
return communities
|
||||
|
||||
|
||||
def _strip_diacritics(text: str | None) -> str:
|
||||
def _strip_diacritics(text: str) -> str:
|
||||
import unicodedata
|
||||
if not isinstance(text, str):
|
||||
text = "" if text is None else str(text)
|
||||
nfkd = unicodedata.normalize("NFKD", text)
|
||||
return "".join(c for c in nfkd if not unicodedata.combining(c))
|
||||
|
||||
@@ -107,29 +84,8 @@ def _is_searchable(term: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
# English question/filler words dropped from query terms so content words drive
|
||||
# BFS seeding. Without this, "how does the frontier cache work" seeds on "how"/
|
||||
# "the"/"work" (which prefix-match prose labels like "Working Principles" at 100x)
|
||||
# instead of "frontier"/"cache", and lands in the wrong part of the graph. Applied
|
||||
# to query terms only — node text is never filtered, so a symbol literally named
|
||||
# `work` stays findable via explain/path. `work`/`works`/`working` are included
|
||||
# because "how does X work" / "how X works" is the most common question phrasing.
|
||||
_QUERY_STOPWORDS = frozenset({
|
||||
"how", "what", "why", "when", "where", "which", "who", "whom", "whose",
|
||||
"does", "did", "is", "are", "was", "were", "be", "been", "being",
|
||||
"can", "could", "should", "would", "will", "shall", "may", "might", "must",
|
||||
"has", "have", "had", "the", "and", "but", "not", "for", "from", "with",
|
||||
"without", "into", "onto", "off", "that", "this", "these", "those", "there",
|
||||
"here", "its", "their", "them", "they", "about", "any", "all", "some",
|
||||
"work", "works", "working",
|
||||
})
|
||||
|
||||
|
||||
def _query_terms(question: str) -> list[str]:
|
||||
"""Split a query into searchable terms, segmenting Chinese text, then drop
|
||||
English question/filler words (`_QUERY_STOPWORDS`) so content words drive
|
||||
seeding. Falls back to the unfiltered terms if the query is all stopwords, so
|
||||
a question like "how does it work" still seeds on something."""
|
||||
"""Split a query into searchable terms, segmenting Chinese text."""
|
||||
terms: list[str] = []
|
||||
for raw in question.split():
|
||||
if _has_chinese(raw):
|
||||
@@ -142,8 +98,7 @@ def _query_terms(question: str) -> list[str]:
|
||||
for tok in re.findall(r"\w+", raw.lower()):
|
||||
if _is_searchable(tok):
|
||||
terms.append(tok)
|
||||
content = [t for t in terms if t not in _QUERY_STOPWORDS]
|
||||
return content or terms
|
||||
return terms
|
||||
|
||||
|
||||
_EXACT_MATCH_BONUS = 1000.0
|
||||
@@ -158,7 +113,7 @@ def _compute_idf(G: nx.Graph, terms: list[str]) -> dict[str, float]:
|
||||
Common terms like 'error' or 'exception' that match hundreds of nodes get
|
||||
low weights; rare identifiers like 'FooBarService' get high weights.
|
||||
Cache is stored on the graph object itself so it auto-invalidates when
|
||||
a hot-reload replaces G with a new object.
|
||||
_maybe_reload() replaces G with a new object.
|
||||
"""
|
||||
cache: dict[str, float] = G.graph.setdefault("_idf_cache", {})
|
||||
N = G.number_of_nodes() or 1
|
||||
@@ -177,135 +132,16 @@ def _compute_idf(G: nx.Graph, terms: list[str]) -> dict[str, float]:
|
||||
return {t: cache.get(t, math.log(1 + N)) for t in terms}
|
||||
|
||||
|
||||
def _trigrams(text: str) -> set[str]:
|
||||
"""Character trigrams of `text`; for <3-char text the whole string is the key."""
|
||||
if len(text) < 3:
|
||||
return {text} if text else set()
|
||||
return {text[i:i + 3] for i in range(len(text) - 2)}
|
||||
|
||||
|
||||
def _node_search_text(data: dict, nid: str) -> str:
|
||||
"""Concatenate every field _score_nodes / _find_node match a query against, so
|
||||
one trigram index over this text is a complete candidate generator for both.
|
||||
|
||||
- `norm_label` and `source_file` feed _score_nodes' per-term substring tiers.
|
||||
- `label_tokens` (the space-joined token form) feeds _find_node's
|
||||
`term in label_tokens` branch, where a multi-word `term` can span a token
|
||||
boundary that punctuation hides in `norm_label` (e.g. query "foo bar" matches
|
||||
label "foo.bar" only via its tokenized form).
|
||||
- `source_tokens` feeds _find_node's exact source-file path lookup, where a
|
||||
query like "app/api/example/route.ts" tokenizes to "app api example route ts".
|
||||
- `nid` feeds the whole-query `joined == nid_lower` tier.
|
||||
|
||||
NUL separators stop a trigram from spanning two fields (a query never contains
|
||||
NUL, so a cross-field trigram can never be a real match).
|
||||
"""
|
||||
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
|
||||
label_tokens = " ".join(_search_tokens(data.get("label") or ""))
|
||||
source = (data.get("source_file") or "").lower()
|
||||
source_tokens = " ".join(_search_tokens(data.get("source_file") or ""))
|
||||
return "\x00".join((norm_label, label_tokens, str(nid).lower(), source, source_tokens))
|
||||
|
||||
|
||||
def _get_trigram_index(G: nx.Graph) -> dict:
|
||||
"""Lazily build and cache a trigram -> node-position postings map on the graph.
|
||||
|
||||
Cached on `G.graph` so it auto-invalidates when a hot-reload swaps in a
|
||||
fresh graph object, exactly like `_idf_cache`. `set_cache` memoizes per-trigram
|
||||
id-sets across queries within one graph generation.
|
||||
"""
|
||||
idx = G.graph.get("_trigram_index")
|
||||
if idx is not None:
|
||||
return idx
|
||||
ids = list(G.nodes())
|
||||
postings: dict[str, array] = {}
|
||||
for i, nid in enumerate(ids):
|
||||
for g in _trigrams(_node_search_text(G.nodes[nid], nid)):
|
||||
bucket = postings.get(g)
|
||||
if bucket is None:
|
||||
bucket = array("i")
|
||||
postings[g] = bucket
|
||||
bucket.append(i)
|
||||
idx = {"ids": ids, "postings": postings, "set_cache": {}}
|
||||
G.graph["_trigram_index"] = idx
|
||||
return idx
|
||||
|
||||
|
||||
def _trigram_candidates(G: nx.Graph, needles: list[str], *, guard_frac: float = 0.10) -> list[str] | None:
|
||||
"""Node IDs whose text could contain any `needle` as a substring, via the
|
||||
trigram index — a *superset* the caller then re-scores with the exact predicates.
|
||||
|
||||
Returns candidates in graph-iteration order (so order-sensitive callers like
|
||||
_find_node stay byte-identical to a full scan), or **None** when the index isn't
|
||||
worth it — a needle is too short to trigram, or its rarest trigram is still
|
||||
common enough that the candidate set would approach the whole graph. The caller
|
||||
falls back to the full scan, preserving the never-worse contract. The guard is
|
||||
cheap: postings-length lookups only, no set intersection.
|
||||
"""
|
||||
idx = _get_trigram_index(G)
|
||||
ids, postings, set_cache = idx["ids"], idx["postings"], idx["set_cache"]
|
||||
n = len(ids)
|
||||
if n == 0:
|
||||
return []
|
||||
needles = [s for s in needles if s]
|
||||
thresh = int(n * guard_frac)
|
||||
for s in needles:
|
||||
tgs = _trigrams(s)
|
||||
if not tgs or any(len(g) < 3 for g in tgs):
|
||||
return None # too short to trigram-filter
|
||||
present = [len(postings[g]) for g in tgs if g in postings]
|
||||
if not present:
|
||||
continue # this needle matches nothing — contributes no candidates
|
||||
if min(present) > thresh:
|
||||
return None # rarest trigram still too common -> not worth the index
|
||||
cand: set[int] = set()
|
||||
for s in needles:
|
||||
sets: list[set] | None = []
|
||||
for g in _trigrams(s):
|
||||
bucket = postings.get(g)
|
||||
if bucket is None:
|
||||
sets = None # a trigram absent everywhere -> needle matches nothing
|
||||
break
|
||||
cached = set_cache.get(g)
|
||||
if cached is None:
|
||||
cached = set(bucket)
|
||||
set_cache[g] = cached
|
||||
sets.append(cached)
|
||||
if not sets:
|
||||
continue
|
||||
sets.sort(key=len) # intersect smallest-first
|
||||
hit = set(sets[0])
|
||||
for other in sets[1:]:
|
||||
hit &= other
|
||||
if not hit:
|
||||
break
|
||||
cand |= hit
|
||||
return [ids[i] for i in sorted(cand)]
|
||||
|
||||
|
||||
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
scored = []
|
||||
# Dedupe tokens, order-preserving (as _pick_seeds already does): a repeated
|
||||
# query word must not double-count every tier, and with coverage scaling
|
||||
# below it would also inflate the matched-term ratio (#1602).
|
||||
norm_terms = list(dict.fromkeys(tok for t in terms for tok in _search_tokens(t)))
|
||||
n_terms = len(norm_terms)
|
||||
norm_terms = [tok for t in terms for tok in _search_tokens(t)]
|
||||
idf = _compute_idf(G, norm_terms)
|
||||
# Whole-query string for full-label matching (mirrors _find_node's `term`).
|
||||
joined = " ".join(norm_terms)
|
||||
# Weight the full-query bonus by the rarest constituent term so a specific
|
||||
# multi-word label still outweighs common-token noise; floor at 1.0.
|
||||
joined_w = max((idf.get(t, 1.0) for t in norm_terms), default=1.0)
|
||||
# Trigram prefilter: score only nodes whose text could match a term, falling
|
||||
# back to the whole graph when the index isn't selective. The result is
|
||||
# identical either way — the per-node scoring below is unchanged and a
|
||||
# non-candidate node always scores 0. (IDF above stays a whole-graph statistic.)
|
||||
candidate_ids = _trigram_candidates(G, norm_terms + ([joined] if joined else []))
|
||||
node_iter = (
|
||||
G.nodes(data=True) if candidate_ids is None
|
||||
else ((nid, G.nodes[nid]) for nid in candidate_ids)
|
||||
)
|
||||
for nid, data in node_iter:
|
||||
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("()")
|
||||
# Tokenized form of the label (punctuation stripped, same transform as the
|
||||
@@ -332,38 +168,18 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
or label_tokens.startswith(joined)
|
||||
):
|
||||
score += _PREFIX_MATCH_BONUS * 10 * joined_w
|
||||
# Term coverage (#1602): scale the per-term exact/prefix tiers by the
|
||||
# squared fraction of query terms the node's LABEL matches, so a lone
|
||||
# generic word that happens to equal a short label (query term "home"
|
||||
# vs. a home() leaf) cannot bury nodes that match several of the
|
||||
# query's terms. Squaring matters because the exact tier is 10x the
|
||||
# prefix tier: at linear coverage a 1-of-10-terms exact match still
|
||||
# outscores a 3-of-10 prefix+substring match. Single-term and
|
||||
# full-coverage queries are unchanged (coverage == 1), so identifier
|
||||
# lookups keep exact-match dominance. Source-file hits score but do
|
||||
# not count as coverage: a colliding leaf whose directory shares
|
||||
# tokens with the query (common near the intended target) must not
|
||||
# win back its exact tier via path fragments. The substring/source
|
||||
# bonuses and the full-query tier above stay unscaled.
|
||||
matched = 0
|
||||
tiered = 0.0
|
||||
for t in norm_terms:
|
||||
w = idf.get(t, 1.0)
|
||||
# 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:
|
||||
tiered += _EXACT_MATCH_BONUS * w
|
||||
matched += 1
|
||||
score += _EXACT_MATCH_BONUS * w
|
||||
elif norm_label.startswith(t) or bare_label.startswith(t):
|
||||
tiered += _PREFIX_MATCH_BONUS * w
|
||||
matched += 1
|
||||
score += _PREFIX_MATCH_BONUS * w
|
||||
elif t in norm_label:
|
||||
score += _SUBSTRING_MATCH_BONUS * w
|
||||
matched += 1
|
||||
if t in source:
|
||||
score += _SOURCE_MATCH_BONUS * w
|
||||
if tiered:
|
||||
score += tiered * (matched / n_terms) ** 2
|
||||
if score > 0:
|
||||
scored.append((score, nid))
|
||||
# Sort by score desc; break ties toward the shorter label so a concise exact
|
||||
@@ -372,113 +188,22 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
return scored
|
||||
|
||||
|
||||
def _pick_scored_endpoint(G: nx.Graph, scored: list[tuple[float, str]], query: str) -> str:
|
||||
"""Pick a path endpoint from a _score_nodes result, preferring full-token matches.
|
||||
|
||||
The full-query tier in _score_nodes only fires when the query equals or
|
||||
prefixes a label, so a query that is a token *subset* of the intended label
|
||||
(query "Reject-everything judge" vs. label "Degenerate Reject-Everything
|
||||
Judge") gets no bonus, and a node prefix-matching one rare token (label
|
||||
"Rejection Summary") can out-score it on IDF alone. Committing to scored[0]
|
||||
then anchors the path on an unrelated — often disconnected — node and yields
|
||||
a false "No path found". Scan the score-ordered list and take the first
|
||||
candidate whose label contains EVERY query token; when the top candidate
|
||||
already full-matches, or no candidate does, this is exactly scored[0].
|
||||
|
||||
`scored` must be non-empty (both callers return early on no match).
|
||||
"""
|
||||
qtokens = set(_search_tokens(query))
|
||||
if not qtokens:
|
||||
return scored[0][1]
|
||||
for _score, nid in scored:
|
||||
if qtokens <= set(_search_tokens(G.nodes[nid].get("label") or nid)):
|
||||
return nid
|
||||
return scored[0][1]
|
||||
|
||||
|
||||
def _pick_seeds(
|
||||
scored: list[tuple[float, str]],
|
||||
max_k: int = 3,
|
||||
gap_ratio: float = 0.2,
|
||||
*,
|
||||
G: "nx.Graph | None" = None,
|
||||
terms: list[str] | None = None,
|
||||
) -> list[str]:
|
||||
def _pick_seeds(scored: list[tuple[float, str]], max_k: int = 3, gap_ratio: float = 0.2) -> list[str]:
|
||||
"""Select BFS seed nodes, stopping when score drops too far below the top.
|
||||
|
||||
Prevents high-frequency noise terms (error, exception) from stealing seed
|
||||
slots from a dominant identifier match. When FooBarService scores 1000 and
|
||||
error nodes score 1.0, only FooBarService is seeded — the score gap is 99.9%
|
||||
which is well above the 20% threshold that would allow additional seeds.
|
||||
|
||||
That same gap_ratio cutoff has a failure mode on multi-term natural-language
|
||||
queries: if one term happens to hit an EXACT label match on a node that is
|
||||
otherwise unrelated to the query's intent (e.g. a common word that is also
|
||||
used as an unrelated identifier or field name elsewhere in the corpus), it
|
||||
can outscore every SUBSTRING match on the query's other, actually-relevant
|
||||
terms by ~1000x (see `_EXACT_MATCH_BONUS` vs. `_SUBSTRING_MATCH_BONUS`).
|
||||
The 20%-gap cutoff then silently discards all of those substring-tier
|
||||
seeds, so the BFS traversal only ever explores the neighborhood of the one
|
||||
unrelated exact match — see #1445.
|
||||
|
||||
When `G` and `terms` are supplied, this guarantees at least one seed per
|
||||
distinct query term that has any match at all, so one term's incidental
|
||||
collision cannot starve out the others. Ties within a term are broken by
|
||||
graph degree (structural centrality), so an isolated incidental match
|
||||
doesn't out-rank a real, well-connected hub for that term.
|
||||
|
||||
Coverage scaling in _score_nodes (#1602) now dampens a lone collision's
|
||||
exact tier on multi-term queries, which brings label-matching relevant
|
||||
nodes back inside the gap window; this per-term guarantee remains
|
||||
load-bearing for relevant nodes matched only via substrings, whose flat
|
||||
scores a dampened collision can still exceed.
|
||||
"""
|
||||
if not scored:
|
||||
return []
|
||||
|
||||
# Deduplicate seeds by (normalized) label so a generic, homonymous symbol —
|
||||
# e.g. dozens of route handlers all labelled `GET`/`POST`, or a `handler`
|
||||
# repeated across a framework — contributes at most one seed instead of
|
||||
# consuming every slot and flooding the BFS with near-identical neighborhoods
|
||||
# (#1766). The key mirrors _score_nodes' normalization so `GET`/`Get`/`get`
|
||||
# collapse together. When G is absent we can't read labels, so fall back to
|
||||
# the (unique) node id, which is a no-op — preserving the old behavior.
|
||||
def _seed_label_key(nid: str) -> str:
|
||||
if G is None:
|
||||
return nid
|
||||
data = G.nodes[nid]
|
||||
return (data.get("norm_label")
|
||||
or _strip_diacritics(data.get("label") or "").lower()) or nid
|
||||
|
||||
top_score = scored[0][0]
|
||||
seeds: list[str] = []
|
||||
seen_labels: set[str] = set()
|
||||
for score, nid in scored:
|
||||
if len(seeds) >= max_k:
|
||||
break
|
||||
seeds = []
|
||||
for score, nid in scored[:max_k]:
|
||||
if seeds and score < top_score * gap_ratio:
|
||||
break
|
||||
key = _seed_label_key(nid)
|
||||
if key in seen_labels:
|
||||
continue
|
||||
seen_labels.add(key)
|
||||
seeds.append(nid)
|
||||
|
||||
if G is not None and terms:
|
||||
norm_terms = sorted({tok for t in terms for tok in _search_tokens(t)})
|
||||
for term in norm_terms:
|
||||
term_scored = _score_nodes(G, [term])
|
||||
if not term_scored:
|
||||
continue
|
||||
best_score = term_scored[0][0]
|
||||
tied = [nid for s, nid in term_scored if s == best_score]
|
||||
best_nid = max(tied, key=lambda n: G.degree(n)) if len(tied) > 1 else term_scored[0][1]
|
||||
# Honor the same per-label cap so the per-term guarantee can't
|
||||
# reintroduce a second copy of an already-seeded generic label.
|
||||
key = _seed_label_key(best_nid)
|
||||
if best_nid not in seeds and key not in seen_labels:
|
||||
seen_labels.add(key)
|
||||
seeds.append(best_nid)
|
||||
return seeds
|
||||
|
||||
|
||||
@@ -649,9 +374,6 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
|
||||
"""
|
||||
char_budget = token_budget * 3
|
||||
lines = []
|
||||
# Work-memory overlay (derived sidecar) stashed on the graph at load time.
|
||||
# Empty when no sidecar exists, so un-annotated output stays byte-identical.
|
||||
overlay = getattr(G, "graph", {}).get("_learning_overlay", {}) or {}
|
||||
seed_set = set(seeds or [])
|
||||
ordered = [n for n in (seeds or []) if n in nodes] + \
|
||||
sorted(nodes - seed_set, key=lambda n: G.degree(n), reverse=True)
|
||||
@@ -662,20 +384,11 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
|
||||
# corpus document can otherwise inject ANSI escapes, fake graphify-out
|
||||
# log lines, or prompt-injection markup into the model's context via
|
||||
# source_file / source_location / community.
|
||||
# The learning= suffix is appended INSIDE the bracket and BEFORE the
|
||||
# budget check below, so it counts in char_budget accounting.
|
||||
entry = overlay.get(str(nid))
|
||||
learning_suffix = ""
|
||||
if entry:
|
||||
status = sanitize_label(str(entry.get("status", "")))
|
||||
if status:
|
||||
learning_suffix = f" learning={status}{':stale' if entry.get('stale') else ''}"
|
||||
line = (
|
||||
f"NODE {sanitize_label(d.get('label', nid))} "
|
||||
f"[src={sanitize_label(str(d.get('source_file', '')))} "
|
||||
f"loc={sanitize_label(str(d.get('source_location', '')))} "
|
||||
f"community={sanitize_label(str(d.get('community_name') or d.get('community', '')))}"
|
||||
f"{learning_suffix}]"
|
||||
f"community={sanitize_label(str(d.get('community', '')))}]"
|
||||
)
|
||||
lines.append(line)
|
||||
for u, v in edges:
|
||||
@@ -717,7 +430,7 @@ def _query_graph_text(
|
||||
) -> str:
|
||||
terms = _query_terms(question)
|
||||
scored = _score_nodes(G, terms)
|
||||
start_nodes = _pick_seeds(scored, G=G, terms=terms)
|
||||
start_nodes = _pick_seeds(scored)
|
||||
if not start_nodes:
|
||||
return "No matching nodes found."
|
||||
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
|
||||
@@ -737,69 +450,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).
|
||||
|
||||
Results are ordered by precedence: exact source-file path match first, then
|
||||
exact (label/ID) match, then prefix match, then substring match. Node-ID exact
|
||||
matches are grouped with label exact matches.
|
||||
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 = " ".join(_search_tokens(label))
|
||||
if not term:
|
||||
return []
|
||||
# Punctuation-preserving normalized query. `term` tokenizes on \w+ (so
|
||||
# "blockStream.ts" -> "blockstream ts", space where the '.' was), but a node's
|
||||
# stored `norm_label` keeps punctuation ("blockstream.ts"). Matching only via
|
||||
# `term`/`label_tokens` works when the node label tokenizes the same way, but is
|
||||
# fragile if `label` and `norm_label` diverge. `norm_query` matches `norm_label`
|
||||
# symmetrically so an exactly-typed punctuated label always resolves (#1704).
|
||||
norm_query = _strip_diacritics(str(label)).lower().strip()
|
||||
source_exact: list[str] = []
|
||||
exact: list[str] = []
|
||||
prefix: list[str] = []
|
||||
substring: list[str] = []
|
||||
# Trigram prefilter (graph-iteration order preserved so exact/prefix/substring
|
||||
# ordering — and thus matches[0] — is byte-identical to the full scan).
|
||||
candidate_ids = _trigram_candidates(G, [term, norm_query])
|
||||
node_iter = (
|
||||
G.nodes(data=True) if candidate_ids is None
|
||||
else ((nid, G.nodes[nid]) for nid in candidate_ids)
|
||||
)
|
||||
for nid, d in node_iter:
|
||||
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("()")
|
||||
label_tokens = " ".join(_search_tokens(d.get("label") or ""))
|
||||
source_tokens = " ".join(_search_tokens(d.get("source_file") or ""))
|
||||
nid_lower = nid.lower()
|
||||
if term == source_tokens:
|
||||
source_exact.append(nid)
|
||||
elif (
|
||||
term == norm_label or term == bare_label or term == label_tokens or term == nid_lower
|
||||
or norm_query == norm_label or norm_query == bare_label
|
||||
):
|
||||
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 label_tokens.startswith(term)
|
||||
or nid_lower.startswith(term)
|
||||
or norm_label.startswith(norm_query)
|
||||
or bare_label.startswith(norm_query)
|
||||
):
|
||||
elif norm_label.startswith(term) or bare_label.startswith(term) or nid_lower.startswith(term):
|
||||
prefix.append(nid)
|
||||
elif term in norm_label or term in label_tokens or norm_query in norm_label:
|
||||
elif term in norm_label:
|
||||
substring.append(nid)
|
||||
|
||||
if source_exact:
|
||||
query_basename = _strip_diacritics(Path(label).name).lower()
|
||||
preferred = [
|
||||
nid
|
||||
for nid in source_exact
|
||||
if str(G.nodes[nid].get("source_location", "")) == "L1"
|
||||
and _strip_diacritics(str(G.nodes[nid].get("label") or "")).lower()
|
||||
== query_basename
|
||||
]
|
||||
if len(preferred) == 1:
|
||||
source_exact = preferred + [nid for nid in source_exact if nid != preferred[0]]
|
||||
|
||||
return source_exact + exact + prefix + substring
|
||||
return exact + prefix + substring
|
||||
|
||||
|
||||
def _filter_blank_stdin() -> None:
|
||||
@@ -832,21 +502,6 @@ def _filter_blank_stdin() -> None:
|
||||
sys.stdin = open(0, "r", closefd=False)
|
||||
|
||||
|
||||
def _community_header(cid: int, community_name) -> str:
|
||||
# Header for get_community: "Community N — Name", matching get_node / query
|
||||
# output which read the community_name attribute to_json writes onto nodes.
|
||||
# Skip the name when it is just the "Community N" placeholder (written for
|
||||
# unnamed communities) so the header never reads "Community 12 — Community 12";
|
||||
# also falls back to the bare id when there is no name. Name is sanitised
|
||||
# (F-010) like every other LLM-derived field.
|
||||
base = f"Community {cid}"
|
||||
if community_name:
|
||||
clean = sanitize_label(str(community_name))
|
||||
if clean and clean != base:
|
||||
return f"{base} — {clean}"
|
||||
return base
|
||||
|
||||
|
||||
def _build_server(graph_path: str):
|
||||
"""Build the configured low-level MCP Server (shared by every transport).
|
||||
|
||||
@@ -864,81 +519,49 @@ def _build_server(graph_path: str):
|
||||
except ImportError as e:
|
||||
raise ImportError('mcp not installed. Run: pip install "graphifyy[mcp]"') from e
|
||||
|
||||
from graphify import paths as _paths
|
||||
G = _load_graph(graph_path)
|
||||
communities = _communities_from_graph(G)
|
||||
|
||||
# Per-graph context cache: resolved graph.json path -> {key, G, communities}.
|
||||
# The server's default graph is just the first entry; a tool call carrying a
|
||||
# project_path adds its own. Routing every graph through one cache means the
|
||||
# eager trigram index and the mtime+size hot-reload behave identically for
|
||||
# the default graph and for any project graph.
|
||||
_default_graph_path = graph_path
|
||||
_ctx_lock = threading.Lock()
|
||||
_ctx_cache: dict[str, dict] = {}
|
||||
# Hot-reload state: mtime+size key lets us detect graph.json changes without
|
||||
# polling. Initialised from the file stat at startup so the first tool call
|
||||
# never triggers a redundant reload.
|
||||
_reload_lock = threading.Lock()
|
||||
try:
|
||||
_s = Path(graph_path).stat()
|
||||
_reload_state: dict = {"mtime_ns": _s.st_mtime_ns, "size": _s.st_size}
|
||||
except FileNotFoundError:
|
||||
_reload_state = {"mtime_ns": 0, "size": -1}
|
||||
|
||||
def _load_ctx(path: str):
|
||||
"""Return (G, communities) for a graph.json path, reusing a cached
|
||||
context until the file's (mtime, size) changes and then transparently
|
||||
rebuilding it. Unlike ``_load_graph`` it never exits the process on a
|
||||
missing/corrupt file — it raises, so a bad project_path surfaces as a
|
||||
tool error instead of killing a server that is happily serving other
|
||||
projects."""
|
||||
def _maybe_reload() -> None:
|
||||
nonlocal G, communities
|
||||
try:
|
||||
s = Path(path).stat()
|
||||
s = Path(graph_path).stat()
|
||||
key = (s.st_mtime_ns, s.st_size)
|
||||
except FileNotFoundError:
|
||||
raise FileNotFoundError(f"graph.json not found: {path}")
|
||||
ent = _ctx_cache.get(path)
|
||||
if ent is not None and ent["key"] == key:
|
||||
return ent["G"], ent["communities"]
|
||||
with _ctx_lock:
|
||||
ent = _ctx_cache.get(path)
|
||||
if ent is not None and ent["key"] == key:
|
||||
return ent["G"], ent["communities"] # another thread built it
|
||||
return
|
||||
if key == (_reload_state["mtime_ns"], _reload_state["size"]):
|
||||
return
|
||||
with _reload_lock:
|
||||
try:
|
||||
new_G = _load_graph(path)
|
||||
except SystemExit as e: # _load_graph exits on missing/corrupt file
|
||||
raise RuntimeError(f"could not load graph.json at {path}") from e
|
||||
# Warm the trigram index before exposing the graph so the first query
|
||||
# against it is fast (same rationale as the original startup warm-up).
|
||||
_get_trigram_index(new_G)
|
||||
comm = _communities_from_graph(new_G)
|
||||
_ctx_cache[path] = {"key": key, "G": new_G, "communities": comm}
|
||||
return new_G, comm
|
||||
|
||||
def _resolve_graph_path(project_path) -> str:
|
||||
"""Map an optional project_path to a concrete graph.json path. ``None``
|
||||
keeps the server's default graph (backward-compatible); a project_path
|
||||
resolves to ``<project_path>/<GRAPHIFY_OUT>/graph.json``, honouring the
|
||||
GRAPHIFY_OUT override so worktree/shared-output setups keep working."""
|
||||
if not project_path:
|
||||
return _default_graph_path
|
||||
return str(Path(project_path) / _paths.GRAPHIFY_OUT / "graph.json")
|
||||
|
||||
# Active per-request context, rebound by _select_graph() and read by the tool
|
||||
# handlers below. No lock needed on the hot path: _select_graph and the
|
||||
# handler run in one synchronous stretch of each call_tool coroutine (no
|
||||
# await between them), so a concurrent call never observes a half-applied
|
||||
# swap.
|
||||
active_graph_path = _default_graph_path
|
||||
try:
|
||||
G, communities = _load_ctx(_default_graph_path)
|
||||
except (FileNotFoundError, RuntimeError):
|
||||
# No default graph at startup → run as a pure multi-project server. Tools
|
||||
# then require project_path; a call without one gets a clear error rather
|
||||
# than the process refusing to start (which is what _load_graph would do).
|
||||
G, communities = None, {}
|
||||
|
||||
def _select_graph(project_path) -> None:
|
||||
nonlocal G, communities, active_graph_path
|
||||
path = _resolve_graph_path(project_path)
|
||||
G, communities = _load_ctx(path)
|
||||
active_graph_path = path
|
||||
s = Path(graph_path).stat()
|
||||
key = (s.st_mtime_ns, s.st_size)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
if key == (_reload_state["mtime_ns"], _reload_state["size"]):
|
||||
return # another thread already reloaded
|
||||
try:
|
||||
new_G = _load_graph(graph_path)
|
||||
except SystemExit:
|
||||
return # keep serving stale graph on transient read error
|
||||
G = new_G
|
||||
communities = _communities_from_graph(new_G)
|
||||
_reload_state["mtime_ns"], _reload_state["size"] = key
|
||||
|
||||
server = Server("graphify")
|
||||
|
||||
@server.list_tools()
|
||||
async def list_tools() -> list[types.Tool]:
|
||||
_tools = [
|
||||
return [
|
||||
types.Tool(
|
||||
name="query_graph",
|
||||
description="Search the knowledge graph using BFS or DFS. Returns relevant nodes and edges as text context.",
|
||||
@@ -1059,20 +682,6 @@ def _build_server(graph_path: str):
|
||||
},
|
||||
),
|
||||
]
|
||||
# Multi-project support: every tool accepts an optional project_path.
|
||||
# Injected here (rather than repeated in 11 literal schemas) so the set
|
||||
# stays in lockstep as tools are added. Omitting it keeps the historical
|
||||
# single-graph behaviour, so this is purely additive for existing callers.
|
||||
for _t in _tools:
|
||||
_t.inputSchema.setdefault("properties", {})["project_path"] = {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"Absolute path to a project directory containing "
|
||||
"graphify-out/graph.json. Optional — defaults to the graph "
|
||||
"this server was started with."
|
||||
),
|
||||
}
|
||||
return _tools
|
||||
|
||||
def _tool_query_graph(arguments: dict) -> str:
|
||||
import time as _time
|
||||
@@ -1094,7 +703,7 @@ def _build_server(graph_path: str):
|
||||
querylog.log_query(
|
||||
kind="mcp_query",
|
||||
question=question,
|
||||
corpus=str(active_graph_path),
|
||||
corpus=str(graph_path),
|
||||
result=result,
|
||||
mode=mode,
|
||||
depth=depth,
|
||||
@@ -1116,7 +725,7 @@ def _build_server(graph_path: str):
|
||||
f" ID: {sanitize_label(nid)}",
|
||||
f" Source: {sanitize_label(str(d.get('source_file', '')))} {sanitize_label(str(d.get('source_location', '')))}",
|
||||
f" Type: {sanitize_label(str(d.get('file_type', '')))}",
|
||||
f" Community: {sanitize_label(str(d.get('community_name') or d.get('community', '')))}",
|
||||
f" Community: {sanitize_label(str(d.get('community', '')))}",
|
||||
f" Degree: {G.degree(nid)}",
|
||||
])
|
||||
|
||||
@@ -1153,8 +762,7 @@ def _build_server(graph_path: str):
|
||||
nodes = communities.get(cid, [])
|
||||
if not nodes:
|
||||
return f"Community {cid} not found."
|
||||
header = _community_header(cid, G.nodes[nodes[0]].get("community_name"))
|
||||
lines = [f"{header} ({len(nodes)} nodes):"]
|
||||
lines = [f"Community {cid} ({len(nodes)} nodes):"]
|
||||
for n in nodes:
|
||||
d = G.nodes[n]
|
||||
# Sanitise label and source_file (F-010).
|
||||
@@ -1190,8 +798,7 @@ def _build_server(graph_path: str):
|
||||
return f"No node matching source '{arguments['source']}' found."
|
||||
if not tgt_scored:
|
||||
return f"No node matching target '{arguments['target']}' found."
|
||||
src_nid = _pick_scored_endpoint(G, src_scored, arguments["source"])
|
||||
tgt_nid = _pick_scored_endpoint(G, tgt_scored, arguments["target"])
|
||||
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).
|
||||
@@ -1201,13 +808,8 @@ def _build_server(graph_path: str):
|
||||
f"the same node '{src_nid}'. Use a more specific label or the exact node ID."
|
||||
)
|
||||
warnings: list[str] = []
|
||||
for name, scored, nid in (
|
||||
("source", src_scored, src_nid),
|
||||
("target", tgt_scored, tgt_nid),
|
||||
):
|
||||
# Only meaningful when the raw score head is what got picked — a
|
||||
# full-token override was chosen on token coverage, not score.
|
||||
if len(scored) >= 2 and nid == scored[0][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:
|
||||
warnings.append(
|
||||
@@ -1343,7 +945,7 @@ def _build_server(graph_path: str):
|
||||
}
|
||||
|
||||
def _load_community_labels() -> dict[int, str]:
|
||||
labels_path = Path(active_graph_path).parent / ".graphify_labels.json"
|
||||
labels_path = Path(graph_path).parent / ".graphify_labels.json"
|
||||
if labels_path.exists():
|
||||
try:
|
||||
return {int(k): v for k, v in json.loads(labels_path.read_text(encoding="utf-8")).items()}
|
||||
@@ -1364,10 +966,10 @@ def _build_server(graph_path: str):
|
||||
|
||||
@server.read_resource()
|
||||
async def read_resource(uri: AnyUrl) -> str:
|
||||
_select_graph(None) # resources read the server's default graph
|
||||
_maybe_reload()
|
||||
uri_str = str(uri)
|
||||
if uri_str == "graphify://report":
|
||||
report_path = Path(active_graph_path).parent / "GRAPH_REPORT.md"
|
||||
report_path = Path(graph_path).parent / "GRAPH_REPORT.md"
|
||||
if report_path.exists():
|
||||
return report_path.read_text(encoding="utf-8")
|
||||
return "GRAPH_REPORT.md not found. Run graphify extract first."
|
||||
@@ -1416,13 +1018,11 @@ def _build_server(graph_path: str):
|
||||
|
||||
@server.call_tool()
|
||||
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
|
||||
arguments = dict(arguments or {})
|
||||
project_path = arguments.pop("project_path", None)
|
||||
_maybe_reload()
|
||||
handler = _handlers.get(name)
|
||||
if not handler:
|
||||
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
|
||||
try:
|
||||
_select_graph(project_path) # bind G/communities to the target graph
|
||||
return [types.TextContent(type="text", text=handler(arguments))]
|
||||
except Exception as exc:
|
||||
return [types.TextContent(type="text", text=f"Error executing {name}: {exc}")]
|
||||
@@ -1430,9 +1030,8 @@ def _build_server(graph_path: str):
|
||||
return server
|
||||
|
||||
|
||||
def serve(graph_path: str | None = None) -> None:
|
||||
def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
"""Start the MCP server over stdio (the default, per-developer transport)."""
|
||||
graph_path = graph_path or _default_graph_json()
|
||||
try:
|
||||
from mcp.server.stdio import stdio_server
|
||||
except ImportError as e:
|
||||
@@ -1589,7 +1188,7 @@ def _build_http_app(
|
||||
|
||||
|
||||
def serve_http(
|
||||
graph_path: str | None = None,
|
||||
graph_path: str = "graphify-out/graph.json",
|
||||
*,
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 8080,
|
||||
@@ -1610,7 +1209,6 @@ def serve_http(
|
||||
deliberate follow-up. Binding ``0.0.0.0`` exposes the server beyond
|
||||
localhost — set an api_key when you do.
|
||||
"""
|
||||
graph_path = graph_path or _default_graph_json()
|
||||
try:
|
||||
import uvicorn
|
||||
except ImportError as e:
|
||||
@@ -1657,16 +1255,9 @@ def _main(argv: list[str] | None = None) -> None:
|
||||
parser.add_argument(
|
||||
"graph_path",
|
||||
nargs="?",
|
||||
default=None,
|
||||
default="graphify-out/graph.json",
|
||||
help="Path to graph.json (default: graphify-out/graph.json)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--graph",
|
||||
dest="graph_flag",
|
||||
default=None,
|
||||
metavar="PATH",
|
||||
help="Path to graph.json — alias for the positional argument",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--transport",
|
||||
choices=["stdio", "http"],
|
||||
@@ -1698,11 +1289,10 @@ def _main(argv: list[str] | None = None) -> None:
|
||||
help="Reap stateful sessions idle this many seconds (default: 3600; 0 disables)",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
graph_path = args.graph_flag or args.graph_path or _default_graph_json()
|
||||
|
||||
if args.transport == "http":
|
||||
serve_http(
|
||||
graph_path,
|
||||
args.graph_path,
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
api_key=args.api_key,
|
||||
@@ -1712,7 +1302,7 @@ def _main(argv: list[str] | None = None) -> None:
|
||||
session_timeout=args.session_timeout,
|
||||
)
|
||||
else:
|
||||
serve(graph_path)
|
||||
serve(args.graph_path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,675 +0,0 @@
|
||||
---
|
||||
name: graphify
|
||||
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
|
||||
---
|
||||
|
||||
# /graphify
|
||||
|
||||
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
|
||||
/graphify <path> # full pipeline on specific path
|
||||
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
|
||||
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
|
||||
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
|
||||
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
|
||||
/graphify <path> --update # incremental - re-extract only new/changed files
|
||||
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
|
||||
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
|
||||
/graphify <path> --cluster-only # rerun clustering on existing graph
|
||||
/graphify <path> --no-viz # skip visualization, just report + JSON
|
||||
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
|
||||
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
|
||||
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
|
||||
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
|
||||
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
|
||||
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
|
||||
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
|
||||
/graphify <path> --mcp # start MCP stdio server for agent access
|
||||
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
|
||||
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
|
||||
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
|
||||
/graphify add <url> # fetch URL, save to ./raw, update graph
|
||||
/graphify add <url> --author "Name" # tag who wrote it
|
||||
/graphify add <url> --contributor "Name" # tag who added it to the corpus
|
||||
/graphify query "<question>" # BFS traversal - broad context
|
||||
/graphify query "<question>" --dfs # DFS - trace a specific path
|
||||
/graphify query "<question>" --budget 1500 # cap answer at N tokens
|
||||
/graphify path "AuthModule" "Database" # shortest path between two concepts
|
||||
/graphify explain "SwinTransformer" # plain-language explanation of a node
|
||||
```
|
||||
|
||||
## What graphify is for
|
||||
|
||||
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
|
||||
|
||||
## What You Must Do When Invoked
|
||||
|
||||
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
|
||||
|
||||
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
|
||||
|
||||
If no path was given, use `.` (current directory). Do not ask the user for a path.
|
||||
|
||||
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
|
||||
|
||||
Follow these steps in order. Do not skip steps.
|
||||
|
||||
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
|
||||
|
||||
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
|
||||
|
||||
### Step 1 - Ensure graphify is installed
|
||||
|
||||
```bash
|
||||
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
|
||||
PYTHON=""
|
||||
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
|
||||
# 1. uv tool installs — most reliable on modern Mac/Linux
|
||||
if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
|
||||
_UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
|
||||
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
|
||||
fi
|
||||
# 2. Read shebang from graphify binary (pipx and direct pip installs)
|
||||
if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
|
||||
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
case "$_SHEBANG" in
|
||||
*[!a-zA-Z0-9/_.@-]*) ;;
|
||||
*) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
|
||||
esac
|
||||
fi
|
||||
# 3. Fall back to python3
|
||||
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
|
||||
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 --from 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', 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
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
result = detect(Path('INPUT_PATH'))
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
" > graphify-out/.graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
|
||||
```
|
||||
Corpus: X files · ~Y words
|
||||
code: N files (.py .ts .go ...)
|
||||
docs: N files (.md .txt ...)
|
||||
papers: N files (.pdf ...)
|
||||
images: N files
|
||||
video: N files (.mp4 .mp3 ...)
|
||||
```
|
||||
|
||||
Omit any category with 0 files from the summary.
|
||||
|
||||
Then act on it:
|
||||
- If `total_files` is 0: stop with "No supported files found in [path]."
|
||||
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
|
||||
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
|
||||
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
|
||||
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
|
||||
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
|
||||
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
|
||||
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
|
||||
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
|
||||
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
|
||||
|
||||
### Step 2.5 - Video and audio (only if video files detected)
|
||||
|
||||
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
|
||||
|
||||
### Step 3 - Extract entities and relationships
|
||||
|
||||
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
|
||||
|
||||
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
|
||||
|
||||
> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
|
||||
|
||||
**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
|
||||
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
|
||||
|
||||
Print it once, then continue — do not wait for the user to supply a key. 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 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.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
|
||||
|
||||
**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.
|
||||
|
||||
#### Part A - Structural extraction for code files
|
||||
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
code_files = []
|
||||
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('INPUT_PATH'))
|
||||
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}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print('No code files - skipping AST extraction')
|
||||
"
|
||||
```
|
||||
|
||||
#### Part B - Semantic extraction (parallel subagents)
|
||||
|
||||
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
|
||||
"
|
||||
```
|
||||
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
|
||||
Before dispatching subagents, print a timing estimate:
|
||||
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
|
||||
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
|
||||
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
|
||||
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
|
||||
|
||||
**Step B0 - Check extraction cache first**
|
||||
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
# Only content files go to semantic extraction. Code is already covered structurally
|
||||
# by the AST pass (Part A); flattening every category here makes subagents re-read
|
||||
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
|
||||
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
|
||||
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH')
|
||||
|
||||
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
|
||||
# run so Part C never merges a stale .graphify_cached.json (#1392).
|
||||
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}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
else:
|
||||
Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
|
||||
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')
|
||||
"
|
||||
```
|
||||
|
||||
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message**
|
||||
|
||||
> Uses the `Task` tool for parallel subagent dispatch.
|
||||
> Call `Task` once per chunk — ALL in the same response so they run in parallel.
|
||||
|
||||
Pass the extraction prompt as the task description:
|
||||
|
||||
```
|
||||
Task(description="Your task is to perform the following. Follow the instructions below exactly.\n\n<agent-instructions>\n[extraction prompt, with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE substituted]\n</agent-instructions>\n\nExecute this now. Output ONLY the structured JSON response.")
|
||||
```
|
||||
|
||||
Each subagent writes its result to its own `graphify-out/.graphify_chunk_NN.json`. Collect results as each `Task` completes and parse each as JSON.
|
||||
|
||||
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
|
||||
```bash
|
||||
PROJECT_ROOT=$(pwd) # cwd — where Part C globs graphify-out/ (NOT .graphify_root/scan dir, #1392)
|
||||
# Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json"
|
||||
```
|
||||
|
||||
Subagent prompt template:
|
||||
|
||||
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
|
||||
Wait for all subagents. For each result:
|
||||
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
|
||||
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
|
||||
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
|
||||
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
|
||||
|
||||
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
|
||||
|
||||
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, glob
|
||||
from pathlib import Path
|
||||
|
||||
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(encoding=\"utf-8\"))
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
total_in += d.get('input_tokens', 0)
|
||||
total_out += d.get('output_tokens', 0)
|
||||
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, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
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(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding=\"utf-8\").splitlines() if line]
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached)
|
||||
print(f'Cached {saved} files')
|
||||
"
|
||||
```
|
||||
|
||||
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
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', [])
|
||||
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
|
||||
seen = set()
|
||||
deduped = []
|
||||
for n in all_nodes:
|
||||
if n['id'] not in seen:
|
||||
seen.add(n['id'])
|
||||
deduped.append(n)
|
||||
|
||||
merged = {
|
||||
'nodes': deduped,
|
||||
'edges': all_edges,
|
||||
'hyperedges': all_hyperedges,
|
||||
'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, 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)')
|
||||
"
|
||||
```
|
||||
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
|
||||
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
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']}
|
||||
merged_nodes = list(ast['nodes'])
|
||||
for n in sem['nodes']:
|
||||
if n['id'] not in seen:
|
||||
merged_nodes.append(n)
|
||||
seen.add(n['id'])
|
||||
|
||||
merged_edges = ast['edges'] + sem['edges']
|
||||
merged_hyperedges = sem.get('hyperedges', [])
|
||||
merged = {
|
||||
'nodes': merged_nodes,
|
||||
'edges': merged_edges,
|
||||
'hyperedges': merged_hyperedges,
|
||||
'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, 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)')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 4 - Build graph, cluster, analyze, generate outputs
|
||||
|
||||
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
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(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
|
||||
# root= mirrors the --update runbook (#1361): relativize source_file to the same
|
||||
# base so the full build and incremental --update never drift apart on re-extract.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
|
||||
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
|
||||
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.')
|
||||
raise SystemExit(1)
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
# Placeholder questions - regenerated with real labels in Step 5
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
|
||||
# nothing) when the new graph is smaller than the existing graph.json. Only write
|
||||
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
|
||||
# they never describe a graph that graph.json doesn't contain (#1392).
|
||||
wrote = to_json(G, communities, 'graphify-out/graph.json')
|
||||
if not wrote:
|
||||
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
|
||||
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
|
||||
raise SystemExit(1)
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
analysis = {
|
||||
'communities': {str(k): v for k, v in communities.items()},
|
||||
'cohesion': {str(k): v for k, v in cohesion.items()},
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
|
||||
"
|
||||
```
|
||||
|
||||
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
|
||||
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 4.5 - Graph health check (read-only integrity gate)
|
||||
|
||||
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
|
||||
print(format_diagnostic_report(summary))
|
||||
flags = [f'{summary[k]} {label}' for k, label in (
|
||||
('dangling_endpoint_edges', 'dangling-endpoint edges'),
|
||||
('missing_endpoint_edges', 'missing-endpoint edges'),
|
||||
('self_loop_edges', 'self-loop edges'),
|
||||
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
|
||||
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
|
||||
) if summary.get(k, 0)]
|
||||
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
|
||||
"
|
||||
```
|
||||
|
||||
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from pathlib import Path
|
||||
|
||||
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\"))
|
||||
|
||||
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
|
||||
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
|
||||
|
||||
# LABELS - replace these with the names you chose above
|
||||
labels = LABELS_DICT
|
||||
|
||||
# Regenerate questions with real community labels (labels affect question phrasing)
|
||||
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, 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')
|
||||
"
|
||||
```
|
||||
|
||||
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
|
||||
Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 6 - Generate Obsidian vault (opt-in) + HTML
|
||||
|
||||
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
|
||||
|
||||
If `--obsidian` was given:
|
||||
|
||||
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
|
||||
|
||||
```bash
|
||||
graphify export obsidian
|
||||
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
|
||||
```
|
||||
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
graphify export html # auto-aggregates to community view if graph > 5000 nodes
|
||||
# or: graphify export html --no-viz
|
||||
```
|
||||
|
||||
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
|
||||
|
||||
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
|
||||
|
||||
---
|
||||
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
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(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.
|
||||
# root= relativizes the manifest keys to the scan root (same base as the build),
|
||||
# so the on-disk manifest is portable across clones/machines and a later --update
|
||||
# matches cached files instead of missing every one (#1417).
|
||||
save_manifest(detect.get('all_files') or detect['files'], root='INPUT_PATH')
|
||||
|
||||
# Update cumulative cost tracker
|
||||
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(encoding=\"utf-8\"))
|
||||
else:
|
||||
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
|
||||
|
||||
cost['runs'].append({
|
||||
'date': datetime.now(timezone.utc).isoformat(),
|
||||
'input_tokens': input_tok,
|
||||
'output_tokens': output_tok,
|
||||
'files': detect.get('total_files', 0),
|
||||
})
|
||||
cost['total_input_tokens'] += input_tok
|
||||
cost['total_output_tokens'] += output_tok
|
||||
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)')
|
||||
"
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json
|
||||
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
|
||||
|
||||
Tell the user (omit the obsidian line unless --obsidian was given):
|
||||
```
|
||||
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
|
||||
|
||||
graph.html - interactive graph, open in browser
|
||||
GRAPH_REPORT.md - audit report
|
||||
graph.json - raw graph data
|
||||
obsidian/ - Obsidian vault (only if --obsidian was given)
|
||||
```
|
||||
|
||||
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
|
||||
|
||||
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
|
||||
|
||||
Then paste these sections from GRAPH_REPORT.md directly into the chat:
|
||||
- God Nodes
|
||||
- Surprising Connections
|
||||
- Suggested Questions
|
||||
|
||||
Do NOT paste the full report - just those three sections. Keep it concise.
|
||||
|
||||
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
|
||||
|
||||
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
|
||||
|
||||
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
|
||||
|
||||
The graph is the map. Your job after the pipeline is to be the guide.
|
||||
|
||||
---
|
||||
|
||||
## Interpreter guard for subcommands
|
||||
|
||||
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
|
||||
|
||||
```bash
|
||||
if [ ! -f graphify-out/.graphify_python ]; then
|
||||
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
|
||||
case "$PYTHON" in *[!a-zA-Z0-9/_.@-]*) PYTHON="python3" ;; esac
|
||||
else
|
||||
PYTHON="python3"
|
||||
fi
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
|
||||
fi
|
||||
```
|
||||
|
||||
## For --update and --cluster-only
|
||||
|
||||
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
|
||||
|
||||
---
|
||||
|
||||
## For /graphify query
|
||||
|
||||
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
|
||||
|
||||
```bash
|
||||
graphify query "<question>"
|
||||
```
|
||||
|
||||
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
|
||||
|
||||
---
|
||||
|
||||
## For /graphify add and --watch
|
||||
|
||||
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
|
||||
|
||||
---
|
||||
|
||||
## For the commit hook and native AGENTS.md integration
|
||||
|
||||
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's AGENTS.md, see `references/hooks.md`.
|
||||
|
||||
---
|
||||
|
||||
## Honesty Rules
|
||||
|
||||
- Never invent an edge. If unsure, use AMBIGUOUS.
|
||||
- Never skip the corpus check warning.
|
||||
- Always show token cost in the report.
|
||||
- Never hide cohesion scores behind symbols - show the raw number.
|
||||
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
|
||||
Loaded 100 of 501 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user