Compare commits

..
Author SHA1 Message Date
Safi 8d3457130a Merge origin/v8 into pr-1136 — resolve codex .codex path + version bump 2026-06-07 14:32:01 +01:00
DevinZeng 5d24fef4bf fix: align codebuddy install with claude install logic
codebuddy_install now uses _always_on('claude-md') instead of hardcoded
_CODEBUDDY_MD_SECTION, so CODEBUDDY.md content matches CLAUDE.md.
2026-06-06 12:11:12 +08:00
DevinZeng 2c32a4ef3c Address PR feedback: Add PreToolUse hook, uninstall handler, idempotency, and tests 2026-06-06 10:19:50 +08:00
DevinZeng 2a102bc75b Merge official v8 (v0.8.32) with CodeBuddy support 2026-06-06 09:58:11 +08:00
DevinZeng c299f31032 Add CodeBuddy platform support
CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as
Claude Code. Installs skill to ~/.codebuddy/skills/, writes CODEBUDDY.md
section, and registers a Glob|Grep PreToolUse hook in
.codebuddy/settings.json.
2026-06-05 19:15:09 +08:00
686 changed files with 19133 additions and 138179 deletions

No files matched your search

+1 -28
View File
@@ -50,7 +50,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.12", "3.13", "3.14"]
python-version: ["3.10", "3.12"]
steps:
- uses: actions/checkout@v6
@@ -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
-55
View File
@@ -1,55 +0,0 @@
name: Publish to PyPI
# Publishes graphifyy to PyPI via OpenID Connect (trusted publishing) — no API
# token or password. Fires when a GitHub Release is published (i.e. after
# `gh release create ... --latest`), builds the sdist + wheel, guards that the
# package version matches the release tag, then uploads with an OIDC token.
#
# One-time PyPI setup (Manage project -> Publishing -> Add a GitHub publisher):
# Owner: Graphify-Labs
# Repository: graphify
# Workflow name: publish.yml
# Environment name: pypi
on:
release:
types: [published]
# Manual re-run escape hatch (still requires the release tag to be checked out).
workflow_dispatch:
permissions:
contents: read
jobs:
publish:
name: Build and publish graphifyy
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/project/graphifyy/
permissions:
id-token: write # REQUIRED: mint the OIDC token PyPI verifies. Nothing else.
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
- name: Build sdist + wheel
run: uv build --sdist --wheel
- name: Guard — package version must match the release tag
if: github.event_name == 'release'
run: |
VERSION=$(grep -m1 '^version = ' pyproject.toml | sed -E 's/^version = "(.*)"/\1/')
TAG="${GITHUB_REF_NAME#v}"
echo "pyproject version: $VERSION | release tag: $TAG"
if [ "$VERSION" != "$TAG" ]; then
echo "::error::pyproject version ($VERSION) does not match release tag ($TAG); refusing to publish."
exit 1
fi
- name: Twine metadata check
run: uvx twine check dist/*
- name: Publish to PyPI (trusted publishing)
uses: pypa/gh-action-pypi-publish@release/v1
-64
View File
@@ -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
-3
View File
@@ -37,6 +37,3 @@ scripts/llm.py
scripts/benchmark_kimi*.json
scripts/benchmark_kimi*.py
paper/
# macOS Finder metadata
.DS_Store
+20 -37
View File
@@ -5,48 +5,31 @@ graphify is a Claude Code skill backed by a Python library. The skill orchestrat
## Pipeline
```
detect() → extract() → build() → cluster() → analyze helpers → report.generate() → export.to_*()
detect() → extract() → build_graph() → cluster() → analyze() → report() → export()
```
Each stage lives in its own module and they communicate through plain Python dicts and NetworkX graphs - no shared state, no side effects outside `graphify-out/`. Most stages are a single function; `analyze.py` and `export.py` are sets of sibling functions rather than one entry point.
Each stage is a single function in its own module. They communicate through plain Python dicts and NetworkX graphs - no shared state, no side effects outside `graphify-out/`.
## Module responsibilities
Signatures below are the real ones - `tests/test_architecture_doc.py` imports every symbol named here, so this table cannot drift from the code.
| Module | Entry point(s) | Input → Output |
|--------|----------------|----------------|
| `detect.py` | `detect(root)` | directory → scan summary dict: `files` grouped by category, plus `total_files`, `total_words`, `warning`, `scan_root`, … |
| `extract.py` | `extract(paths, *, root=None, ...)`, `collect_files(target)` | **list** of file paths → `{nodes, edges}` dict. `collect_files` expands a directory into that list, and lives here, not in `detect.py` |
| `build.py` | `build(extractions)`, `build_from_json(extraction)` | extraction dict(s) → `nx.Graph` |
| `cluster.py` | `cluster(G)` | graph → `{community_id: [node_id, ...]}` (the graph is not mutated) |
| `analyze.py` | `god_nodes(G)`, `surprising_connections(G)`, `suggest_questions(G, communities, community_labels)`, `find_import_cycles(G)`, `graph_diff(G_old, G_new)` | graph → one list/dict per analysis. There is no single `analyze()` entry point |
| `report.py` | `generate(G, communities, cohesion_scores, community_labels, ...)` | graph + analysis → GRAPH_REPORT.md string |
| `export.py` | `to_json`, `to_html`, `to_obsidian`, `to_svg`, `to_graphml`, `to_canvas`, `to_cypher` | graph → graph.json, graph.html, Obsidian vault, graph.svg, … one function per format |
| `wiki.py` | `to_wiki(G, communities, output_dir, ...)` | graph → one markdown article per community + `index.md` |
| Module | Function | Input → Output |
|--------|----------|----------------|
| `detect.py` | `collect_files(root)` | directory → `[Path]` filtered list |
| `extract.py` | `extract(path)` | file path → `{nodes, edges}` dict |
| `build.py` | `build_graph(extractions)` | list of extraction dicts → `nx.Graph` |
| `cluster.py` | `cluster(G)` | graph → graph with `community` attr on each node |
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
| `callflow_html.py` | `write_callflow_html(...)` | graphify-out files → Mermaid architecture/call-flow HTML |
| `ingest.py` | `ingest(url, target_dir, ...)` | URL → file saved to corpus dir |
| `cache.py` | `check_semantic_cache(files, root)`, `save_semantic_cache(nodes, edges, ...)` | files → cached nodes / edges / hyperedges + the list of files still needing extraction |
| `security.py` | `validate_url`, `safe_fetch`, `validate_graph_path`, `sanitize_label` | URL / path / label → validated value, or raises |
| `validate.py` | `validate_extraction(data)`, `assert_valid(data)` | extraction dict → **list of schema error strings** (`validate_extraction` returns them; `assert_valid` raises) |
| `serve.py` | `serve(graph_path)`, `serve_http(graph_path, *, host, port, ...)` | graph file path → MCP stdio server / HTTP server |
| `watch.py` | `watch(watch_path, debounce=3.0)`, `check_update(watch_path)` | directory → rebuild on change; `check_update` reports whether a re-extraction is pending |
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
| `security.py` | validation helpers | URL / path / label → validated or raises |
| `validate.py` | `validate_extraction(data)` | extraction dict → raises on schema errors |
| `serve.py` | `start_server(graph_path)` | graph file path → MCP stdio server |
| `watch.py` | `watch(root, flag_path)` | directory → writes flag file on change |
| `benchmark.py` | `run_benchmark(graph_path)` | graph file → corpus vs subgraph token comparison |
### Calling `extract()` from your own code
`extract()` takes a **list** of paths, and `root` is keyword-only and optional:
```python
from pathlib import Path
from graphify.extract import extract
paths = [Path("src/lib/content.ts"), Path("src/pages/index.astro")]
result = extract(paths, root=Path(".").resolve()) # pass root explicitly
```
Always pass `root`. Node ids and `source_file` values are derived relative to it; when it is omitted, `extract()` infers one from the paths you passed, which is the common parent of *that list* rather than your project root. A single-file call therefore anchors to that file's own directory, and ids can end up carrying path segments from the machine they were extracted on.
## Extraction output schema
Every extractor returns:
@@ -62,7 +45,7 @@ Every extractor returns:
}
```
`validate.py` enforces this schema before `build()` consumes it.
`validate.py` enforces this schema before `build_graph()` consumes it.
## Confidence labels
@@ -74,8 +57,8 @@ Every extractor returns:
## Adding a new language extractor
1. Add an `extract_<lang>(path: Path) -> dict` function following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges). New languages go in their own module under `graphify/extractors/` - see `graphify/extractors/MIGRATION.md`; `extract.py` re-exports them while the existing ones are ported out of it.
2. Register the file suffix in `extract()`'s dispatch table and in `collect_files()` (both in `extract.py`).
1. Add a `extract_<lang>(path: Path) -> dict` function in `extract.py` following the existing pattern (tree-sitter parse → walk nodes → collect `nodes` and `edges` → call-graph second pass for INFERRED `calls` edges).
2. Register the file suffix in `extract()` dispatch and `collect_files()`.
3. Add the suffix to `CODE_EXTENSIONS` in `detect.py` and `_WATCHED_EXTENSIONS` in `watch.py`.
4. Add the tree-sitter package to `pyproject.toml` dependencies.
5. Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py`.
-187
View File
@@ -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>
```
-1046
View File
File diff suppressed because it is too large. Load diff
+17 -198
View File
@@ -1,202 +1,21 @@
MIT License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2026 Safi Shamsi
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 Safi Shamsi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-8
View File
@@ -1,8 +0,0 @@
Graphify
Copyright 2026 Safi Shamsi and the Graphify contributors.
This product is licensed under the Apache License, Version 2.0 (see LICENSE).
Portions of this software were contributed under the MIT License prior to the
relicensing and remain available under those terms. The original MIT license
text is retained in LICENSE-MIT.
+60 -320
View File
@@ -1,61 +1,37 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-card.png" width="300" height="214" 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&amp;utm_medium=badge&amp;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/2DDrEgvZb4"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></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.ycombinator.com/companies/graphify-labs"><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/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>
<p align="center">
<b>Early access to the graphify platform is open before the public v1 launch: <a href="https://app.graphify.com/login">app.graphify.com</a></b>
<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>
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.
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.
> Want this always-on, updating in the background across your code, docs, and meetings rather than only on demand? That is what we are building at **[graphify.com](https://graphify.com)**, and early access is open now at **[app.graphify.com](https://app.graphify.com/login)**.
<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>
</p>
**Get started** (30 seconds):
```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/
@@ -64,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
@@ -162,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:
@@ -195,18 +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.
> **Strict mode (Claude Code):** `graphify install --project --strict` makes the assistant actually use the graph. The default install *nudges* it to run `graphify query` before reading files; strict mode *blocks* the first raw source read of a session and redirects it to the graph, then reverts to the nudge (so it fires at most once per session and never gets stuck). Toggle at runtime with `GRAPHIFY_HOOK_STRICT=1`/`0`; the default install is unchanged (soft nudge).
<details>
<summary><b>Pick your platform</b> (20+ assistants, click to expand)</summary>
### Pick your platform
| Platform | Install command |
|----------|----------------|
@@ -227,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 |
|---|---|---|
@@ -253,9 +164,8 @@ 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 (graspologic on Python < 3.13; native backend on 3.13+) | `uv tool install "graphifyy[leiden]"` |
| `leiden` | Leiden community detection (Python < 3.13 only) | `uv tool install "graphifyy[leiden]"` |
| `ollama` | Ollama local inference | `uv tool install "graphifyy[ollama]"` |
| `openai` | OpenAI / OpenAI-compatible APIs | `uv tool install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `uv tool install "graphifyy[gemini]"` |
@@ -266,15 +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]"` |
| `ocaml` | OCaml `.ml`/`.mli` AST extraction | `uv tool install "graphifyy[ocaml]"` |
| `commonlisp` | Common Lisp `.lisp`/`.cl`/`.lsp`/`.asd` AST extraction | `uv tool install "graphifyy[commonlisp]"` |
| `robot` | Robot Framework `.robot`/`.resource` extraction (suites, test cases, keywords, keyword-call and resource/library import edges) | `uv tool install "graphifyy[robot]"` |
| `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
@@ -300,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`, which is what actually carries the always-on graph guidance on this platform. `graphify codex install` also registers a `PreToolUse` hook in `.codex/hooks.json` (`graphify hook-check`), but that entry is deliberately a **no-op**: Codex Desktop rejects `hookSpecificOutput.additionalContext` on `PreToolUse`, so emitting a nudge there would break Bash tool calls. Unlike Claude Code, where the hook (`graphify hook-guard`) does the nudging, on Codex the hook fires and intentionally does nothing, and `AGENTS.md` is the always-on mechanism.
**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.
@@ -339,15 +237,11 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| Type | Extensions |
|------|-----------|
| Code (37 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 .ml .mli .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]`, `.ml`/`.mli` requires `uv tool install graphifyy[ocaml]`; `.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]`) |
| OCaml | `.ml .mli` (requires `uv tool install graphifyy[ocaml]`) |
| Common Lisp | `.lisp .cl .lsp .asd` (requires `uv tool install graphifyy[commonlisp]`) |
| Robot Framework | `.robot .resource` (via the official `robot.api` parser, requires `uv tool install graphifyy[robot]`; suites, test cases, user keywords, keyword-call and Resource/Library/Variables import edges) |
| 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` |
@@ -355,22 +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]`) |
Terraform module calls with a literal local `source` (`./...` or `../...`) link
to a directory module node through an `EXTRACTED` `module_source` edge. Each
directory node contains its scanned `.tf` files, so nested calls expose paths
such as environment → application → base → resource. Scan the common repository
root to include both callers and implementations. Paths resolve relative to the
calling module, and excluded or out-of-root files are never loaded implicitly.
Remote sources and source expressions are not resolved; `.tfvars`, generic
`.hcl`, and `.tf.json` files do not define module-source targets. References to
`module.app.output` still target the module call rather than its implementation's
output. The graph represents source configuration, not evaluated Terraform
instances. Incremental Terraform changes reconcile the scanned `.tf` corpus,
reusing cached syntax for unchanged files. After upgrading an existing graph,
run `graphify update .` once to regenerate Terraform IDs and topology.
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
@@ -407,7 +286,7 @@ graphify export callflow-html # Mermaid architecture/call-flow HTML (auto-r
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper and add it
/graphify add <youtube-url> # transcribe and add a video
graphify hook install # auto-rebuild on commit + branch checkout (run `graphify update .` after `git pull` — see "Recommended workflow" below)
graphify hook install # auto-rebuild on git commit
graphify merge-graphs a.json b.json # combine two graphs
graphify prs # PR dashboard: CI state, review status, worktree mapping
@@ -424,9 +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.
Pass `--no-gitignore` to `graphify extract` when git-ignored generated or transpiled code belongs in the graph. This disables `.gitignore` and `.git/info/exclude`; `.graphifyignore` still applies.
**`.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
@@ -454,29 +331,11 @@ graphify-out/cost.json # local only
> `manifest.json` is now portable — keys are stored as relative paths and re-anchored on load, so committing it is safe and avoids a full rebuild on first checkout.
### Recommended workflow
Set this up once per clone. From then on, three of your normal git commands keep the graph current by themselves, and one keeps it in sync with your team:
| you do | graphify does |
|---|---|
| `graphify hook install` (once, right after cloning) | installs the hooks below, plus a merge driver so `graph.json` never shows conflict markers |
| `git commit` | rebuilds automatically — AST only, no API cost |
| `git checkout` / `git switch` (branches) | rebuilds automatically (a file-only `git checkout -- <path>` does not) |
| `git pull` / `git merge` | run `graphify update .` right after |
| `git push` | nothing to do |
The commit and branch-switch rebuilds run in the background and return immediately, so on a large repo the graph can lag the commit by a few seconds — step 5 covers the rare case where you query before it catches up.
**Step by step:**
1. Clone the repo and run `graphify hook install` once.
2. Commit and switch branches as normal — the graph stays current on its own.
3. After every `git pull` (or merge), run `graphify update .` to bring the graph in sync with what you just pulled. On a large or active repo, put it on autopilot with a pull alias:
```bash
git config --global alias.gpull '!git pull && graphify update .'
```
4. When docs or papers change, run `/graphify --update` to refresh those nodes too (code and docs update independently).
5. If a query ever seems to be missing something you just added, run `graphify update .` first, then ask again.
**Workflow:**
1. One person runs `/graphify .` and commits `graphify-out/`.
2. Everyone pulls — their assistant reads the graph immediately.
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost). This also sets up a git merge driver so `graph.json` is never left with conflict markers — two devs committing in parallel get their graphs union-merged automatically.
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
---
@@ -489,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
@@ -538,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`) |
@@ -557,58 +411,38 @@ These are only needed for **headless / CI extraction** (`graphify extract`). Whe
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — standard credential chain | `--backend bedrock` (no API key, uses IAM) |
| `GRAPHIFY_MAX_WORKERS` | AST parallelism thread count | optional — also `--max-workers` flag |
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Raise output cap for dense corpora | optional — e.g. `32768` for large files |
| `GRAPHIFY_API_TIMEOUT` | Per-call timeout in seconds for HTTP, claude-cli, Anthropic SDK, and Bedrock 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_MAX_RETRY_DEPTH` | How deep a truncated chunk may be bisected and re-extracted (default: 3, so up to 8x sub-calls for one chunk) | optional — lower it to cap worst-case spend; `0` disables every retry (no bisection, no hollow-response retry), so a chunk costs exactly one call |
| `GRAPHIFY_API_TIMEOUT` | Per-call timeout in seconds for HTTP, claude-cli, and Anthropic SDK backends (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_FORCE` | Force graph rebuild even with fewer nodes | optional — also `--force` flag |
| `GRAPHIFY_GOOGLE_WORKSPACE` | Auto-enable Google Workspace export | optional — set to `1` |
| `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_MAX_CONTEXTS` | Maximum number of non-default project graphs retained by one multi-project MCP server | optional — default: `8`; invalid values use `8`, and values below `1` use `1` |
| `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 |
---
## Privacy
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine. A code-only corpus requires no API key — `graphify extract` runs fully offline. On a mixed repo, add `--code-only` to index just the code and skip the docs/PDFs/images that would otherwise need an LLM.
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine. A code-only corpus requires no API key — `graphify extract` runs fully offline.
- **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.
**`uv run --with graphifyy python -m graphify` silently runs an older install**
`uv run` uses your *system* Python, so if an older `graphifyy` also lives there (e.g. a past `pip install graphifyy`), Python can find that copy first on `sys.path` and `--with graphifyy` won't override it. It runs with no error, but you get the *old* version's behavior — e.g. env overrides like `OPENAI_BASE_URL` are silently ignored, so requests hit the default endpoint and fail with a 401 that looks like a bad key. The fingerprint is a `warning: skill is from graphify <newer>, package is <older>` line — that means a different install was loaded, not just a stale skill. Check which copy actually loaded:
```bash
python -c "import graphify; print(graphify.__file__)"
```
Then run the installed command directly (it uses the uv-managed copy), or drop the stale system copy:
```bash
uvx --from graphifyy graphify extract . --backend openai # names the package explicitly
pip uninstall graphifyy # or remove the old system install
```
**`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.
@@ -616,9 +450,6 @@ PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash)
**Graph has fewer nodes after `--update` or rebuild**
If a refactor deleted files, the old nodes linger. Pass `--force` (or set `GRAPHIFY_FORCE=1`) to overwrite even when the rebuild has fewer nodes.
**`extract` exits with "extraction was incomplete ... refusing to overwrite"**
When an extraction pass crashes or a walk can't fully read the corpus, the run would be smaller than a complete one, so `graphify extract` refuses to overwrite a larger existing graph with the partial result (protecting your `graph.json`). Fix the underlying failure and re-run, or pass `--allow-partial` to overwrite anyway.
**Graph has duplicate nodes for the same entity (ghost duplicates)**
Ghost duplicates (same symbol appearing twice — once from AST extraction with a source location, once from semantic extraction without) are now automatically merged at build time. If you see this in a graph built before v0.8.33, run a full re-extract to clean up:
```bash
@@ -631,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
@@ -649,13 +472,6 @@ graphify query "..."
**`graph.json` has conflict markers after two devs commit at once**
Run `graphify hook install` — it sets up a git merge driver that union-merges `graph.json` automatically so conflicts never happen.
**Graph doesn't reflect a teammate's recent changes**
Run `graphify update .` right after `git pull` or any merge — see [Recommended workflow](#recommended-workflow). Commits and branch switches update the graph automatically via the installed hooks; syncing with a pull is the one step you run yourself. Fold it into a pull alias so it's one command either way:
```bash
git config --global alias.gpull '!git pull && graphify update .'
```
Confirm the hooks are active with `graphify hook status`; re-run `graphify hook install` after an interpreter upgrade/reinstall to refresh them.
**Extraction returns empty nodes/edges for docs or PDFs**
Docs, PDFs, and images require an LLM call — code-only corpora need no key. Check that your API key is set and the backend is correct:
```bash
@@ -669,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
@@ -685,20 +493,16 @@ graphify-out/
/graphify # run on current directory
/graphify ./raw # run on a specific folder
/graphify ./raw --mode deep # more aggressive relationship extraction
graphify extract ./raw --code-only # index code only — local AST, no API key (skips docs/PDFs/images); an `extract` flag, not a skill flag
/graphify ./raw --update # re-extract only changed files
/graphify ./raw --directed # preserve edge direction
/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
@@ -711,14 +515,6 @@ graphify extract ./raw --code-only # index code only — local AST, no API key (
/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
@@ -756,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)
@@ -771,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
@@ -780,18 +572,14 @@ 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 ./src --no-gitignore # include git-ignored source; still honor .graphifyignore
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 ./src --no-dedup # skip entity dedup; on an incremental merge this also arms the shrink guard that refuses to drop untouched files' nodes
graphify extract ./docs --global --as myrepo # extract and register into the cross-project global graph
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # raise output cap for dense corpora
@@ -800,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
@@ -824,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.
@@ -843,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
---
## graphify Enterprise
## Built on graphify — Penpax
[**graphify Enterprise**](https://graphify.com) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working context: meetings, files, docs, 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 and teams whose work lives across hundreds of conversations and documents they can never fully reconstruct.
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
**[Join the waitlist at graphify.com](https://graphify.com).** Free trial launching soon.
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
---
@@ -889,40 +674,8 @@ uv run pytest tests/test_extract.py -q # one module
uv run pytest tests/ -q -k "python" # filter by name
```
### CI parity checks
The authoritative CI commands live in [`.github/workflows/`](.github/workflows/).
For local CI-style verification, use Python 3.10, 3.12, 3.13, or 3.14 and run:
```bash
uv sync --all-extras --frozen
uv run --frozen pytest tests/ -q --tb=short
uv run --frozen python -m tools.skillgen --check
uv run --frozen python -m tools.skillgen --audit-coverage
uv run --frozen python -m tools.skillgen --schema-singleton
uv run --frozen python -m tools.skillgen --monolith-roundtrip
uv run --frozen python -m tools.skillgen --always-on-roundtrip
uv run --frozen graphify --help
uv run --frozen graphify install
```
Ruff is useful as an additional local check (`uv run --frozen ruff check .`),
but is not currently a blocking CI job. Pyright is also local/advisory unless it
is added to CI later. The Bandit and pip-audit CI steps currently use
`continue-on-error`, so their findings are advisory rather than blocking.
> macOS note: the test suite includes both `sample.f90` and `sample.F90` fixtures. These collide on case-insensitive HFS+ / APFS file systems. Run on Linux or in a Docker container if you need to test both Fortran variants simultaneously.
> Windows note: the native Windows test suite exercises symbolic links, long
> paths, POSIX permissions, path separators, and UTF-8 filesystem behavior.
> Enable Windows Developer Mode to allow unprivileged symbolic-link creation, or
> run the tests from an elevated shell. Enable the Windows `LongPathsEnabled`
> policy before relying on long-path tests. Restart affected shells or applications
> after changing either setting. For exact parity with the blocking GitHub Actions
> test matrix, run the suite in WSL or Linux; CI currently runs on Ubuntu with
> Python 3.10, 3.12, 3.13, and 3.14. Pyright is available as a local advisory check, but it is
> not currently a blocking CI job.
### Git workflow
- Active development happens on the `v8` branch.
@@ -939,16 +692,3 @@ is added to CI later. The Bandit and pip-audit CI steps currently use
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
</details>
---
## Community and links
<p align="center">
<a href="https://graphify.com"><img src="https://img.shields.io/badge/Website-graphify.com-4c1?style=flat&logo=googlechrome&logoColor=white" alt="Website"/></a>
<a href="https://discord.gg/2DDrEgvZb4"><img src="https://img.shields.io/badge/Discord-Join-5865F2?style=flat&logo=discord&logoColor=white" alt="Discord"/></a>
<a href="https://x.com/graphify"><img src="https://img.shields.io/badge/X-graphify-000000?logo=x&logoColor=white" alt="X"/></a>
<a href="https://www.youtube.com/@graphifylabs"><img src="https://img.shields.io/badge/YouTube-Graphify%20Labs-FF0000?style=flat&logo=youtube&logoColor=white" alt="YouTube"/></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
View File
@@ -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
View File
@@ -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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

-3
View File
@@ -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`)
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 KiB

-186
View File
@@ -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?
+1 -1
View File
@@ -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">
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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.
-572
View File
@@ -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>
+1 -1
View File
@@ -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)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+1 -1
View File
@@ -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.
-849
View File
@@ -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/2DDrEgvZb4"><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 ‏(graspologic ב-Python < 3.13; מנגנון native ב-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>
+1 -1
View File
@@ -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` टाइप करें — यह आपकी फ़ाइलें पढ़ता है, एक नॉलेज ग्राफ बनाता है, और आपको वह संरचना वापस देता है जो आप नहीं जानते थे कि मौजूद है। कोडबेस को तेज़ी से समझें। आर्किटेक्चरल निर्णयों के पीछे का "क्यों" खोजें।
+1 -1
View File
@@ -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>
+1 -1
View File
@@ -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>
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 — он прочитает ваши файлы, построит граф знаний и вернёт вам структуру, о существовании которой вы не подозревали. Понимайте кодовую базу быстрее. Находите «почему» за архитектурными решениями.
+5 -11
View File
@@ -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)
---
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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>
-2
View File
@@ -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
+4200 -374
View File
File diff suppressed because it is too large. Load diff
-107
View File
@@ -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)
+9 -173
View File
@@ -4,23 +4,15 @@ 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",
# `import('…')` — emitted by the Svelte/Astro/Vue rescue passes and (since
# #2575) by plain JS/TS too. Omitting it made every dynamic import
# invisible to blast-radius traversal even where the edge WAS in the
# graph, and dynamic import is precisely how codebases break require
# cycles, so the missing edges sat under the most load-bearing modules.
"dynamic_import",
"re_exports",
"inherits",
"extends",
@@ -28,7 +20,6 @@ DEFAULT_AFFECTED_RELATIONS = (
"uses",
"mixes_in",
"embeds",
"requires",
)
@@ -37,11 +28,6 @@ class AffectedHit:
node_id: str
depth: int
via_relation: str
# The traversed edge's location — the actual call/import/reference SITE in
# this node's file, not the node's own definition line (#BUG1). Defaults keep
# existing constructors/tests working; None falls back to the node's def line.
via_file: "str | None" = None
via_location: "str | None" = None
def _node_label(graph: nx.Graph, node_id: str) -> str:
@@ -57,130 +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 _as_repo_relative(query: str, root: Path | None = None) -> str:
"""Repo-relative form of a path query, for matching a stored `source_file`.
The graph stores repo-relative paths, so `./src/x.py` and
`/abs/repo/src/x.py` name the same file as `src/x.py` and yet matched
nothing. `affected` then printed an empty list and exited 0 — a blast-radius
tool answering "nothing depends on this" about a file with sixteen
dependents, and indistinguishable from a genuine zero or a typo.
An absolute path is anchored to `root` when given — the repo root derived
from the graph's own location — so a seed resolves regardless of the caller's
working directory (#2706: an absolute-path seed previously only matched when
cwd happened to be the analysed repo root, which no editor or script can
guarantee). `root` falls back to the current directory to preserve the prior
behaviour when a caller has no graph location to derive it from.
Non-path queries pass through unchanged: `Path("myFunc()").as_posix()` is
`"myFunc()"`, so label resolution is untouched. An absolute path rooted
outside `root` is left alone — no basename guessing.
"""
path = Path(query)
if path.is_absolute():
anchor = root if root is not None else Path.cwd()
try:
return path.relative_to(anchor).as_posix()
except ValueError:
# Rooted outside the repo: nothing here can make it repo-relative,
# so leave it alone rather than guess at a basename that would match
# some unrelated file with the same name.
return query
return path.as_posix()
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, root: Path | None = None) -> 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
def resolve_seed(graph: nx.Graph, query: str) -> str | None:
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]
# Compare paths in repo-relative form. Only this branch is path-shaped; the
# label branches above keep the query verbatim.
query_path = _normalize_label(_as_repo_relative(query, root))
exact_source_matches = [
str(node_id)
for node_id, data in graph.nodes(data=True)
if _normalize_label(str(data.get("source_file", ""))) in (query_lower, query_path)
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, _as_repo_relative(query, root)
)
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]
@@ -199,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:
@@ -240,15 +103,7 @@ def affected_nodes(
if source in seen:
continue
seen.add(source)
# Carry the matched edge's location (taken from the SAME edge dict
# whose relation passed the filter, so relation and location stay
# consistent) — that is the call/import/reference site in `source`'s
# own file, which is where the user should click (#BUG1).
hit = AffectedHit(
source, current_depth + 1, relation,
via_file=str(data.get("source_file") or "") or None,
via_location=str(data.get("source_location") or "") or None,
)
hit = AffectedHit(source, current_depth + 1, relation)
hits.append(hit)
queue.append((source, current_depth + 1))
@@ -261,10 +116,9 @@ def format_affected(
*,
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
depth: int = 2,
root: Path | None = None,
) -> str:
relation_list = tuple(relations)
seed = resolve_seed(graph, query, root)
seed = resolve_seed(graph, query)
if seed is None:
return f"No unique node match for {query}"
@@ -280,14 +134,8 @@ def format_affected(
for hit in hits:
data = graph.nodes[hit.node_id]
if hit.via_location:
# The relation SITE in this node's file (call/import/reference line),
# labeled by [via_relation] so it's never mistaken for a def line.
location = f"{hit.via_file or data.get('source_file') or '-'}:{hit.via_location}"
else:
location = _format_location(data) # honest fallback: the node's own def line
lines.append(
f"- {_node_label(graph, hit.node_id)} [{hit.via_relation}] {location}"
f"- {_node_label(graph, hit.node_id)} [{hit.via_relation}] {_format_location(data)}"
)
return "\n".join(lines)
@@ -296,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:
+1 -1
View File
@@ -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.
+8 -53
View File
@@ -13,30 +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",
# Swift / Foundation / SwiftUI framework symbols and module imports that
# otherwise dominate god-node rankings on Swift codebases (#2147)
"Foundation", "SwiftUI", "UIKit", "AppKit", "Combine",
"String", "Int", "Double", "Float", "Bool", "Data", "URL", "Date", "UUID",
"Sendable", "Codable", "Decodable", "Encodable", "Equatable", "Hashable",
"Identifiable", "Comparable", "AnyObject", "Error", "LocalizedError",
"NSObject", "NSString", "NSError", "NSLock",
"View", "Color", "Font", "DispatchQueue",
})
# 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", ".cjs", ".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",)},
@@ -72,12 +59,11 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
label = attrs.get("label", "")
if not label:
return False
# File-level hub: label matches the actual source filename — bare basename OR
# the directory-qualified form the #2032 disambiguation pass may assign.
# File-level hub: label matches the actual source filename (not just any label ending in .py)
source_file = attrs.get("source_file", "")
if source_file:
from graphify.build import _is_file_node_label
if _is_file_node_label(label, source_file):
from pathlib import Path as _Path
if label == _Path(source_file).name:
return True
# Method stub: AST extractor labels methods as '.method_name()'
if label.startswith(".") and label.endswith("()"):
@@ -106,31 +92,16 @@ def _is_json_key_node(G: nx.Graph, node_id: str) -> bool:
return label in _JSON_NOISE_LABELS
def god_nodes(G: nx.Graph, top_n: int = 10,
exclude_hubs_percentile: float | None = None) -> list[dict]:
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
"""Return the top_n most-connected real entities - the core abstractions.
File-level hub nodes are excluded: they accumulate import/contains edges
mechanically and don't represent meaningful architectural abstractions.
``exclude_hubs_percentile`` (0-100) suppresses nodes whose degree exceeds
that percentile of the graph's degree distribution, using the same
threshold computation ``cluster()`` applies (#3205) - so the one setting
suppresses utility hubs in the ranking AND in community resolution,
instead of only the latter. ``None`` keeps the historical ranking.
"""
degree = dict(G.degree())
hub_threshold: float | None = None
if exclude_hubs_percentile is not None:
degrees = sorted(degree.values())
if degrees:
idx = max(0, int(len(degrees) * exclude_hubs_percentile / 100) - 1)
hub_threshold = degrees[idx]
sorted_nodes = sorted(degree.items(), key=lambda x: x[1], reverse=True)
result = []
for node_id, deg in sorted_nodes:
if hub_threshold is not None and deg > hub_threshold:
continue
if _is_file_node(G, node_id) or _is_concept_node(G, node_id) or _is_json_key_node(G, node_id):
continue
if G.nodes[node_id].get("label", "") in _BUILTIN_NOISE_LABELS:
@@ -528,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]]
@@ -690,16 +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
# Type-only imports/re-exports (`import type` / `export type ... from`)
# are erased at compile time - a cycle that closes through one cannot
# exist at runtime (#3123). The edge itself stays in the graph.
if data.get("type_only"):
continue
src_file_attr = data.get("source_file", "")
if not isinstance(src_file_attr, str) or not src_file_attr:
continue
@@ -728,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:
+12 -9
View File
@@ -1,11 +1,13 @@
"""Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach."""
from __future__ import annotations
import json
import sys
from pathlib import Path
import networkx as nx
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
@@ -39,7 +41,7 @@ def _query_subgraph_tokens(G: nx.Graph, question: str, depth: int = 3) -> int:
terms = _query_terms(question)
scored = []
for nid, data in G.nodes(data=True):
label = (data.get("label") or "").lower()
label = data.get("label", "").lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
@@ -83,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:
@@ -96,12 +98,13 @@ def run_benchmark(
Returns dict with: corpus_tokens, avg_query_tokens, reduction_ratio, per_question
"""
graph_path = graph_path or _default_graph_json()
# Size-cap check + links/edges normalization + node-link parse. A raw
# --no-cluster graph stores edges under "edges" and used to KeyError
# here (#2212).
from graphify.paths import load_node_link_graph
G = load_node_link_graph(graph_path)
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"))
try:
G = json_graph.node_link_graph(data, edges="links")
except TypeError:
G = json_graph.node_link_graph(data)
if corpus_words is None:
# Rough estimate: each node label is ~3 words, plus source context
+122 -2049
View File
File diff suppressed because it is too large. Load diff
+112 -1477
View File
File diff suppressed because it is too large. Load diff
+14 -45
View File
@@ -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)
@@ -227,22 +225,12 @@ def _node_link_payload(data: dict) -> tuple[list, list] | None:
return None
try:
# Shared loader normalizes the raw writer's "edges" key to "links"
# before parsing; without it an edges-keyed payload raised
# KeyError: 'links' and this function silently returned None even
# though the shape check above accepts "edges" (#2212).
from graphify.paths import load_node_link_graph
from networkx.readwrite import json_graph
# Force directed/multigraph so the stored caller->callee direction and
# parallel edges survive the round-trip; mirrors affected.py,
# serve.py and cli.py (#1174) and the directed-view fix for
# path/shortest_path (#2487, #2309). graph.json is written with
# "directed": false for backward compatibility, so without this
# networkx returns an undirected Graph and edge orientation becomes
# arbitrary -- which silently swaps the Caller and Callee columns of
# the call table and drops parallel edges. The _src/_tgt override
# below still wins on legacy marker files.
graph = load_node_link_graph({**data, "directed": True, "multigraph": True})
try:
graph = json_graph.node_link_graph(data, edges="links")
except TypeError:
graph = json_graph.node_link_graph(data)
except Exception:
return None
@@ -416,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"
@@ -431,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"
@@ -1216,38 +1204,19 @@ def format_node_refs(node_ids: set, node_by_id: dict, lang: str, empty_text: str
return "<br>".join(parts)
def generate_call_table_rows(
nodes: list,
section_edges: list,
lang: str,
all_edges: list | None = None,
all_nodes: list | None = None,
) -> str:
"""Generate call table row scaffolding for a section's nodes.
The Caller/Callee columns make a claim about the whole graph ("External
entry / no inbound edge"), so they must be computed from the whole graph.
Built from ``section_edges`` alone they only see edges whose *both*
endpoints sit in this section, so a node called from anywhere else is
mislabelled an entry point. Section coverage makes that the common case
rather than a corner case: only ``max_sections`` communities are rendered,
so most callers are not in any rendered section at all.
``all_edges``/``all_nodes`` are the full graph; ``all_nodes`` also lets
out-of-section callers render as labels instead of raw node ids. Both
default to None, preserving the previous behaviour for other callers.
"""
def generate_call_table_rows(nodes: list, section_edges: list, lang: str) -> str:
"""Generate call table row scaffolding for a section's nodes."""
if not nodes:
return ""
# Build source/target lookup from edges
node_by_id = {n.get("id"): n for n in (all_nodes or nodes)}
node_by_id = {n.get("id"): n for n in nodes}
callers = defaultdict(set)
callees = defaultdict(set)
for e in (all_edges if all_edges is not None else section_edges):
for e in section_edges:
src = e.get("source", "")
tgt = e.get("target", "")
if e.get("relation") in ("calls", "imports", "imports_from", "uses", "method", "indirect_call"):
if e.get("relation") in ("calls", "imports", "imports_from", "uses", "method"):
callers[tgt].add(src)
callees[src].add(tgt)
@@ -1771,7 +1740,7 @@ def write_callflow_html(
<th style="width:20%">{callee_header}</th>
<th style="width:20%">{desc_header}</th>
</tr>
{generate_call_table_rows(sec_nodes, sec_edges, lang, edges, nodes)}
{generate_call_table_rows(sec_nodes, sec_edges, lang)}
</table>
{generate_section_cards(sec, sec_nodes, sec_edges, lang)}
-109
View File
@@ -1,109 +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 dep_key, spec in sorted(dependencies.items()):
# Cargo lets a dep table entry rename the crate via `package = "..."`:
# db = { path = "../storage", package = "internal-storage" }
# The key `db` is the name used in `use db::…;`; the actual crate
# published under `[package].name = "internal-storage"` is what
# `crates` is keyed by. Without honoring `package`, every renamed
# workspace-internal dep silently drops its edge (#1858).
real_name = dep_key
if isinstance(spec, dict):
pkg_override = spec.get("package")
if isinstance(pkg_override, str) and pkg_override:
real_name = pkg_override
target = crates.get(real_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}
-4793
View File
File diff suppressed because it is too large. Load diff
+5 -158
View File
@@ -19,95 +19,11 @@ def _suppress_output():
return contextlib.redirect_stdout(io.StringIO())
def _native_leiden(stable: nx.Graph, resolution: float) -> dict[str, int] | None:
"""Call graspologic_native.leiden() directly, bypassing graspologic's own
package import.
graspologic.partition.leiden() is a thin wrapper around exactly this
native (Rust) call. Importing the *package* — as opposed to the native
extension module it depends on — pulls in graspologic.layouts, which
imports umap, which imports pynndescent, which numba-JIT-compiles at
import time for a layout algorithm this function never calls: measured
at 7-19s of one-time import cost against a ~1s native call and a ~1.4s
full round trip (conversion + call + map-back) — see the "third update"
in GRAPHIFY_BUILD_PERF.md for the measurements this is based on.
Returns None (the caller falls through to the graspologic.partition.leiden
path, then to the networkx Louvain fallback) if graspologic_native isn't
installed, or if `stable` isn't the plain undirected, non-multigraph
input leiden actually supports — the same shape check
graspologic.partition.leiden itself makes before calling the same native
function.
"""
try:
import graspologic_native as gn
except ImportError:
return None
if stable.is_directed() or stable.is_multigraph():
return None
# graspologic_native identifies nodes by their string form; two DISTINCT
# node objects that happen to stringify the same way would silently merge
# under it (this is exactly what graspologic.partition.leiden's own
# _IdentityMapper guards against). Graphify's own node IDs are already
# unique strings by construction — extractors/resolution.py's
# _disambiguate_colliding_node_ids salts any two distinct nodes that would
# otherwise share a string id before the graph is ever built — so this is
# a defensive check on an assumption that should never actually trip, not
# an expected path. One pass over the nodes, cheaper than an
# _IdentityMapper-style dict-store-per-edge-endpoint.
id_to_node: dict[str, object] = {}
for node in stable.nodes():
key = str(node)
existing = id_to_node.get(key)
if existing is not None and existing != node:
return None # let graspologic.partition.leiden's own check handle/raise on this
id_to_node[key] = node
edges = [
(str(u), str(v), float(attrs.get("weight", 1.0)))
for u, v, attrs in stable.edges(data=True)
]
try:
old_stderr = sys.stderr
try:
sys.stderr = io.StringIO()
with _suppress_output():
_quality, native_partitions = gn.leiden(
edges=edges,
starting_communities=None,
resolution=resolution,
randomness=0.001,
iterations=1,
use_modularity=True,
seed=42,
trials=1,
)
finally:
sys.stderr = old_stderr
except Exception:
return None
partition = {
id_to_node[node_id]: community
for node_id, community in native_partitions.items()
}
next_community = max(partition.values(), default=-1) + 1
for node in stable.nodes():
if node not in partition:
partition[node] = next_community
next_community += 1
return partition
def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
"""Run community detection. Returns {node_id: community_id}.
Tries Leiden (graspologic_native directly, then graspologic) first — best
quality. Falls back to Louvain (built into networkx) if neither is
installed.
Tries Leiden (graspologic) first — best quality.
Falls back to Louvain (built into networkx) if graspologic is not installed.
resolution > 1.0 → more, smaller communities.
resolution < 1.0 → fewer, larger communities.
@@ -117,31 +33,17 @@ def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
"""
stable = nx.Graph()
stable.add_nodes_from(sorted(G.nodes(), key=str))
# Canonicalise the endpoint pair before sorting. On an undirected graph the
# (u, v) orientation each edge is yielded with comes from adjacency
# iteration, which follows CPython's per-process string-hash order - so the
# SAME edge appears as (A, B) in one run and (B, A) in the next. Sorting on
# the raw pair therefore does not canonicalise anything: the edge lands in a
# different position, `stable` is built in a different insertion order, and
# Louvain - order-sensitive even with a fixed seed - can return a different
# grouping. Measured on a 914-node graph: identical input, identical
# first-pass partition, but the cohesion-split pass produced 70 communities
# under PYTHONHASHSEED=1 and 69 under =2. Sorting the pair itself removes
# the dependency; for nx.Graph the orientation carries no meaning anyway.
edge_rows = sorted(
G.edges(data=True),
key=lambda row: (
*sorted((str(row[0]), str(row[1]))),
str(row[0]),
str(row[1]),
json.dumps(row[2], sort_keys=True, ensure_ascii=False, default=str),
),
)
for src, tgt, attrs in edge_rows:
stable.add_edge(src, tgt, **attrs)
native_result = _native_leiden(stable, resolution)
if native_result is not None:
return native_result
try:
from graspologic.partition import leiden
lsig = inspect.signature(leiden).parameters
@@ -181,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,
@@ -358,14 +212,7 @@ def cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
if n <= 1:
return 1.0
subgraph = G.subgraph(community_nodes)
# Exclude self-loops. ``build_from_json`` deliberately keeps recursive
# ``calls`` self-edges ("real program structure rather than
# import-resolution artifacts"), but ``possible`` below counts distinct
# node PAIRS only, so a self-loop adds to the numerator without adding to
# the denominator and pushes the ratio past 1.0 -- a two-node community
# holding one recursive function scores 2.0. Drop them so numerator and
# denominator measure the same thing.
actual = subgraph.number_of_edges() - nx.number_of_selfloops(subgraph)
actual = subgraph.number_of_edges()
possible = n * (n - 1) / 2
return actual / possible if possible > 0 else 0.0
-247
View File
@@ -1,247 +0,0 @@
"""Finish member calls that cross a repository boundary in a merged graph (#3152).
A single-repo build can only bind ``obj.method()`` when the receiver's type is
declared in that same build. When the type lives in another repository the
resolver holds the receiver type and drops the call anyway, so ``graph.json`` —
the only artifact ``merge-graphs`` and ``global add`` consume — records nothing,
and no merge-time pass can recover what was never written down. A two-repo call
graph was therefore missing exactly the edges that make it a call graph: eight
edges when the code sits in one corpus, seven after merging the same code from
two repos.
The resolvers now park those calls on the caller node as
``metadata.unresolved_calls`` entries (names only, no node ids — see
``_park_unresolved_member_call``). This pass reads them back after the graphs are
composed and emits the ``calls`` edge when the receiver's type resolves to
exactly one declaration in another repo, keeping the single-definition guard the
single-repo resolvers use: an ambiguous name still fabricates nothing.
Edges only, no node merging or renaming, so the pass composes with the prefixing
and pruning already in place. Every edge it adds is tagged, and it clears its own
previous output before recomputing: ``global add`` composes one repo at a time
and revisits the same pairs on every add, and recomputing from the parked entries
keeps the result identical whether three repos arrived together or one at a time.
"""
from __future__ import annotations
import os
from collections import defaultdict
from typing import TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover - typing only
import networkx as nx
CROSS_REPO_CALL_MARKER = "_cross_repo_call"
UNRESOLVED_CALLS_KEY = "unresolved_calls"
# A parked entry names the language it was written in, and the declaration that
# answers it must be written in the same one: without this a Java `Greeter` binds
# just as happily to a Python class of the same name in another repo. Extend this
# map when another extractor starts parking calls.
_LANG_SUFFIXES: dict[str, frozenset[str]] = {
"cpp": frozenset({".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx", ".h", ".cu", ".cuh"}),
"csharp": frozenset({".cs"}),
"java": frozenset({".java"}),
"swift": frozenset({".swift"}),
}
# A declaration owns its members through a `method` edge, except in C++, where an
# in-class declaration (`void bar();` in a header) is modelled as a field and
# carries `defines` instead. `method` wins when both name the same member.
_MEMBER_RELATIONS = ("defines", "method")
def _key(label: object) -> str:
"""Normalize a node label or a parked name to its bare identifier.
Type labels are plain (``Greeter``) while method labels carry the extractor's
decoration (``.greet()``). Case is preserved: every language that parks calls
here is case-sensitive, and folding case would let `greeter` answer for
`Greeter`.
"""
return str(label or "").strip().removeprefix(".").removesuffix("()")
def _suffix(source_file: object) -> str:
return os.path.splitext(str(source_file or ""))[1].lower()
def _parked_entries(data: dict) -> list[dict]:
metadata = data.get("metadata")
if not isinstance(metadata, dict):
return []
parked = metadata.get(UNRESOLVED_CALLS_KEY)
if not isinstance(parked, list):
return []
return [entry for entry in parked if isinstance(entry, dict)]
def _drop_previous_output(merged: "nx.Graph") -> None:
"""Clear the edges this pass added on an earlier run.
Recompute-from-scratch is what makes an incremental ``global add`` agree with
a single ``merge-graphs`` of the same inputs, and it is also how a repo whose
types moved stops answering for calls it no longer owns.
"""
stale = [(u, v) for u, v, data in merged.edges(data=True)
if data.get(CROSS_REPO_CALL_MARKER)]
merged.remove_edges_from(stale)
def _index_declarations(merged: "nx.Graph") -> tuple[dict[str, list[str]], set[str]]:
"""Index sourced type declarations by bare name. Returns (index, id set)."""
by_name: dict[str, list[str]] = defaultdict(list)
type_ids: set[str] = set()
for node, data in merged.nodes(data=True):
if not data.get("_callable_class") or not data.get("source_file"):
continue
if not data.get("repo"):
continue
name = _key(data.get("label"))
if not name:
continue
by_name[name].append(node)
type_ids.add(node)
return by_name, type_ids
def _index_members(
merged: "nx.Graph", type_ids: set[str]
) -> dict[str, dict[tuple[str, str], list[str]]]:
"""Index each declaration's members by relation, then by name.
The merged graph is undirected, and a ``method`` edge carries no reliable
direction once composed, so the owner is identified as the endpoint that is a
type declaration. A nested declaration puts a type on both ends; that pair is
skipped rather than guessed at.
Kept per relation rather than pooled: ``defines`` covers fields as well as
C++'s in-class member declarations, so only a language that needs it may look
there, and only when no ``method`` of that name exists.
"""
by_relation: dict[str, dict[tuple[str, str], list[str]]] = {
relation: defaultdict(list) for relation in _MEMBER_RELATIONS
}
for u, v, data in merged.edges(data=True):
relation = data.get("relation")
if relation not in by_relation:
continue
if u in type_ids and v not in type_ids:
owner, member = u, v
elif v in type_ids and u not in type_ids:
owner, member = v, u
else:
continue
name = _key(merged.nodes[member].get("label"))
if name:
by_relation[relation][(owner, name)].append(member)
return by_relation
def _member_relations(lang: str) -> tuple[str, ...]:
"""Which owner→member relations may answer a call parked by ``lang``.
Only C++ models an in-class declaration (``void bar();`` in a header) as a
field, so only a C++ entry may fall back to ``defines``; for every other
language a ``defines`` target is a field, and a field cannot answer a call.
"""
return ("method", "defines") if lang == "cpp" else ("method",)
def link_cross_repo_member_calls(merged: "nx.Graph") -> int:
"""Emit `calls` edges for parked member calls another repo answers.
Returns the number of edges added. Idempotent: the pass drops its own earlier
output first, so re-merging or adding a repo twice cannot duplicate an edge.
"""
_drop_previous_output(merged)
parked_nodes = [(node, data) for node, data in merged.nodes(data=True)
if _parked_entries(data)]
if not parked_nodes:
return 0
by_name, type_ids = _index_declarations(merged)
if not by_name:
return 0
members_by_relation = _index_members(merged, type_ids)
# C# parked calls need the same namespace/using visibility check as C# type
# references. Without it, an unresolved third-party receiver such as
# `FluentValidation.IValidator` can bind to an unrelated `IValidator` that
# happens to be declared in one merged repository (#3360). Build this only
# when needed; the other parked languages use their existing suffix guard.
csharp_resolver = None
if any(
str(entry.get("lang") or "") == "csharp"
for _, data in parked_nodes
for entry in _parked_entries(data)
):
from graphify.extractors.csharp import CsharpNameResolver
resolver_nodes = [dict(data, id=node) for node, data in merged.nodes(data=True)]
resolver_edges = [
dict(data, source=source, target=target)
for source, target, data in merged.edges(data=True)
]
csharp_resolver = CsharpNameResolver(resolver_nodes, resolver_edges)
added = 0
for caller, caller_data in parked_nodes:
caller_repo = caller_data.get("repo")
if not caller_repo:
# Without a repo tag "another repo" has no meaning, and this pass
# deliberately never re-decides a call inside one repo.
continue
for entry in _parked_entries(caller_data):
lang = str(entry.get("lang") or "")
suffixes = _LANG_SUFFIXES.get(lang)
receiver_type = _key(entry.get("receiver_type"))
callee = _key(entry.get("callee"))
if not suffixes or not receiver_type or not callee:
continue
candidates = [
node for node in by_name.get(receiver_type, [])
if merged.nodes[node].get("repo") != caller_repo
and _suffix(merged.nodes[node].get("source_file")) in suffixes
]
if len(candidates) != 1:
# The same guard the single-repo resolvers apply: two repos
# declaring the same name is an ambiguity, not a hit.
continue
if lang == "csharp":
# Reuse the extractor's authoritative C# visibility rules. A
# candidate is valid only when the caller's namespace, using,
# or alias resolves this exact receiver name to that node.
resolved, _decisive = csharp_resolver.resolve_type_name(
receiver_type,
dict(caller_data, id=caller),
str(caller_data.get("source_file") or ""),
)
if resolved != candidates[0]:
continue
targets: list[str] = []
for relation in _member_relations(lang):
targets = members_by_relation[relation].get((candidates[0], callee), [])
if targets:
break
if len(targets) != 1:
continue
target = targets[0]
if target == caller or merged.has_edge(caller, target):
continue
merged.add_edge(
caller,
target,
relation="calls",
context="cross_repo",
confidence="INFERRED",
confidence_score=0.8,
source_file=str(caller_data.get("source_file") or ""),
source_location=entry.get("line"),
weight=1.0,
_src=caller,
_tgt=target,
**{CROSS_REPO_CALL_MARKER: True},
)
added += 1
return added
-75
View File
@@ -1,75 +0,0 @@
"""Join the same declared type across repositories in a merged graph (#3007).
`merge-graphs` prefixes every node id with its repo tag, so a contract type that
two services both declare arrives as two unconnected nodes. In a message-bus
codebase that is exactly where the interesting hop lives: the producer references
`SyncProductUpsertToSearchEvent` in one repo, the consumer implements
`IConsumer<SyncProductUpsertToSearchEvent>` in the other, and the merged graph has
no way to get from one to the other even though both sides name the same type.
This pass adds a `same_type_as` edge between type declarations that share both a
namespace and a name and come from different repos. Requiring the namespace keeps
it to types that were declared identically rather than two classes that merely
picked the same short name: on a pair of .NET services with 1440 and 262 declared
types, the namespace-plus-name match produced 7 pairs, all of them the shared
`EventManager.Models.*Event` contracts, and nothing else.
Edges only, no node merging. Two repos can hold copies of a contract that have
drifted, and collapsing them would hide that; a link lets a traversal cross while
each side keeps its own members, file and provenance.
"""
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover - typing only
import networkx as nx
SHARED_TYPE_RELATION = "same_type_as"
def link_shared_type_declarations(merged: "nx.Graph") -> int:
"""Link identically declared types across repos. Returns the edge count added.
A candidate node is a sourced type declaration carrying a namespace and a
repo tag. A group qualifies when its members span at least two repos, and
every pair inside a qualifying group gets one edge. Groups are the handful of
types two repos genuinely share, so the pairwise walk stays small.
"""
by_declaration: dict[tuple[str, str], list[str]] = defaultdict(list)
for node, data in merged.nodes(data=True):
if not data.get("_callable_class") or not data.get("source_file"):
continue
namespace = str((data.get("metadata") or {}).get("namespace") or "")
label = str(data.get("label") or "")
if not namespace or not label or not data.get("repo"):
continue
by_declaration[(namespace, label)].append(node)
added = 0
for (namespace, label), nodes in by_declaration.items():
if len(nodes) < 2:
continue
if len({merged.nodes[n].get("repo") for n in nodes}) < 2:
continue
for index, left in enumerate(nodes):
for right in nodes[index + 1:]:
if merged.nodes[left].get("repo") == merged.nodes[right].get("repo"):
continue
if merged.has_edge(left, right):
continue
merged.add_edge(
left,
right,
relation=SHARED_TYPE_RELATION,
context="cross_repo",
confidence="INFERRED",
confidence_score=0.9,
source_file=str(merged.nodes[left].get("source_file") or ""),
weight=1.0,
_src=left,
_tgt=right,
)
added += 1
return added
-154
View File
@@ -1,154 +0,0 @@
"""Member-level interface dispatch for C# (#3003).
A C# call through a constructor-injected dependency lands on the interface's
method node, because that is what the call site names: `_report.Build()` where
`_report` is an `IReport` resolves to `IReport.Build()`. The implementing
`Report.Build()` is a separate node, and nothing joins the two, so a directed
walk stops at the interface and every chain through an injected dependency is
cut at that point. On a Scrutor-scanned .NET service where every dependency is
an interface, that is most chains.
This resolver runs after all files are extracted, with the merged corpus
available, and links the interface's method to the implementing method:
ireport_ireport_build --dispatches_to--> report_report_build
It only fires when the interface has exactly one implementer and that
implementer owns exactly one method of the same name, the single-owner guard
`resolve_pascal_inherited_calls` and `resolve_ruby_member_calls` already use.
Walking `implements` to the one type that can serve the call mirrors what the
runtime does; guessing among several implementers would not, so anything
ambiguous is left alone.
The join is per method rather than per call site, so one edge reconnects every
call that reaches the interface method. Confidence is `INFERRED`: the target is
forced once there is a single implementer, but the source text never names it.
"""
from __future__ import annotations
_CSHARP_SUFFIXES = (".cs",)
DISPATCH_RELATION = "dispatches_to"
def _is_csharp(node: dict | None) -> bool:
"""True when the node is a declaration that lives in a C# file.
Every end of a dispatch pair has to pass this. `implements` is resolved by
name, so in a mixed corpus a Java class declaring `implements IReport` binds
to a C# `IReport` when that is the only node with the name, and linking a C#
interface member to a Java method would be a wrong edge rather than a missing
one. A non-C# implementation of a C# interface, from VB or a Razor component,
is a real thing, but claiming it needs its own extractor evidence.
"""
if not node:
return False
source_file = node.get("source_file")
return bool(source_file) and str(source_file).endswith(_CSHARP_SUFFIXES)
def _method_label(node: dict) -> str:
"""Return a method node's bare name, for matching.
Case is kept: C# is case sensitive, and an implementing member must spell the
interface member exactly, so folding case could only pair a declaration with
a member that does not implement it.
The name is cut at the first parenthesis rather than by stripping a trailing
`()`. Today the C# extractor labels every method `.Name()`, so the two are the
same, but the pair match is keyed on this string and a label that ever carried
a signature would silently stop matching instead of failing visibly.
"""
label = str(node.get("label", "")).strip().removeprefix(".")
return label.split("(", 1)[0]
def resolve_csharp_interface_dispatch(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link each single-implementer interface method to its implementation.
Purely additive: the existing call edge to the interface method is left in
place, since the call site really does name the interface.
"""
if not any(
str(result.get("source_file", "")).endswith(_CSHARP_SUFFIXES)
for result in per_file
if isinstance(result, dict)
) and not any(
str(n.get("source_file", "")).endswith(_CSHARP_SUFFIXES) for n in all_nodes
):
return
node_by_id = {n.get("id"): n for n in all_nodes}
implementers: dict[str, set[str]] = {}
methods_of: dict[str, dict[str, set[str]]] = {}
for e in all_edges:
rel = e.get("relation")
if rel == "implements":
implementers.setdefault(e.get("target"), set()).add(e.get("source"))
elif rel == "method":
owner, method_nid = e.get("source"), e.get("target")
mnode = node_by_id.get(method_nid)
if mnode is None or not _is_csharp(mnode):
continue
name = _method_label(mnode)
if name:
# A set, so the same method arriving on two `method` edges cannot
# look like two same-named methods and trip the guard below.
methods_of.setdefault(owner, {}).setdefault(name, set()).add(method_nid)
if not implementers or not methods_of:
return
# Scoped to this relation: another edge between the two members, whatever it
# is, says nothing about whether the dispatch link is already there.
existing_pairs = {
(e.get("source"), e.get("target"))
for e in all_edges
if e.get("relation") == DISPATCH_RELATION
}
new_edges: list[dict] = []
for interface_nid, impls in implementers.items():
if len(impls) != 1:
continue
impl_nid = next(iter(impls))
interface_node = node_by_id.get(interface_nid)
impl_node = node_by_id.get(impl_nid)
if interface_node is None or impl_node is None:
continue
# Both ends must be C# declarations. A sourceless stub minted for a
# dangling reference carries no members worth dispatching to, and a
# cross-language pair is a name collision rather than an implementation.
if not _is_csharp(interface_node) or not _is_csharp(impl_node):
continue
impl_methods = methods_of.get(impl_nid, {})
for name, declared in methods_of.get(interface_nid, {}).items():
if len(declared) != 1:
continue
candidates = impl_methods.get(name, set())
if len(candidates) != 1:
continue
source = next(iter(declared))
target = next(iter(candidates))
if source == target or (source, target) in existing_pairs:
continue
existing_pairs.add((source, target))
new_edges.append({
"source": source,
"target": target,
"relation": DISPATCH_RELATION,
"context": "call",
"confidence": "INFERRED",
"confidence_score": 0.9,
"source_file": str(impl_node.get("source_file", "")),
"source_location": impl_node.get("source_location"),
"weight": 1.0,
})
all_edges.extend(new_edges)
+43 -834
View File
File diff suppressed because it is too large. Load diff
+252 -1461
View File
File diff suppressed because it is too large. Load diff
+1 -17
View File
@@ -168,14 +168,6 @@ def diagnose_extraction(
raw_edges = _edge_list(extraction)
canonical_edges = [_canonical_edge(edge) for edge in raw_edges]
# Code-typed semantic nodes the extractor could not verify against the source
# it read (#1949): likely-inferred (or hallucinated) symbols surfaced from a
# document. Count them so the flag on graph.json nodes is actually surfaced.
unverified_node_count = sum(
1 for n in extraction.get("nodes", [])
if isinstance(n, dict) and n.get("verification") == "unverified"
)
exact_counts: Counter[str] = Counter(_exact_signature(edge) for edge in raw_edges)
directed_pairs: Counter[tuple[str, str]] = Counter()
undirected_pairs: Counter[tuple[str, str]] = Counter()
@@ -247,7 +239,6 @@ def diagnose_extraction(
return {
"node_count": len(node_ids),
"unverified_node_count": unverified_node_count,
"raw_edge_count": len(raw_edges),
"non_object_edges": non_object_edges,
"missing_endpoint_edges": missing_endpoint_edges,
@@ -283,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
@@ -353,7 +338,6 @@ def format_diagnostic_report(summary: dict[str, Any]) -> str:
"input_stage: provided JSON (normal graph.json is post-build)",
f"effective_directed: {summary.get('effective_directed', '<direct-call>')}",
f"nodes: {summary['node_count']}",
f"unverified_code_nodes: {summary.get('unverified_node_count', 0)}",
f"raw_edges: {summary['raw_edge_count']}",
f"valid_candidate_edges: {summary['valid_candidate_edges']}",
f"missing_endpoint_edges: {summary['missing_endpoint_edges']}",
+652 -598
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1 +0,0 @@
"""exporters package."""
-14
View File
@@ -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",
]
-173
View File
@@ -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}
-637
View File
@@ -1,637 +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
from graphify.paths import write_text_atomic
import json
import networkx as nx
from graphify.security import sanitize_label
MAX_NODES_FOR_VIZ = 5_000
_HTML_STALE_MARKER = ".graph.html.stale"
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.
// Andrew's monotone chain. Returns the hull in counter-clockwise order, which
// is what the perimeter must be traced in. Collinear and duplicate points
// collapse to the extremes, so degenerate member sets render as a segment
// rather than a zero-area crossed path.
function convexHull(pts) {{
const p = pts.slice().sort((a, b) => (a.x - b.x) || (a.y - b.y));
if (p.length < 3) return p;
const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const build = seq => {{
const out = [];
for (const q of seq) {{
while (out.length >= 2 && cross(out[out.length - 2], out[out.length - 1], q) <= 0) out.pop();
out.push(q);
}}
out.pop();
return out;
}};
const hull = build(p).concat(build(p.slice().reverse()));
return hull.length >= 3 ? hull : p;
}}
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.
// The perimeter must follow hull order, not h.nodes order: tracing the
// raw member order self-intersects whenever the layout does not happen
// to place members in angular order, filling as crossed wedges.
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 hull = convexHull(positions);
const expanded = hull.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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}}
// 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)}}" data-nid="${{esc(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);
}}
// Neighbor links use a data attribute + one delegated listener rather than an
// inline onclick. A node id/label sourced from a document or a scraped URL
// (graphify add) can contain a double-quote; dropping the stringified id
// unescaped into a quoted onclick both broke every link and allowed a hostile
// source to inject an event handler into the local report (stored XSS, #1838).
// esc() on data-nid keeps the value inside the attribute; the listener reads it
// back verbatim. Bound to document so it survives the innerHTML rebuild that
// recreates #neighbors-list on each showInfo().
document.addEventListener('click', e => {{
const el = e.target.closest('.neighbor-link');
if (el && el.dataset.nid !== undefined) focusNode(el.dataset.nid);
}});
// 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 _html_document_title(output_path: str) -> str:
"""Return a portable label for the graph.html <title>.
Tracked artifacts must not embed the generator host absolute path
(regression of #433; reported again as #2598 on Windows). Keep from the
configured output-dir bare name (``graphify-out`` / ``GRAPHIFY_OUT``
basename) onward — portable in every case; otherwise fall back to a
cwd-relative label, and finally the filename only.
"""
from graphify.paths import GRAPHIFY_OUT_NAME
raw = str(output_path).replace("\\", "/")
# Drop Windows drive prefix so Path parts are comparable on any OS.
if len(raw) >= 3 and raw[1] == ":" and raw[0].isalpha() and raw[2] == "/":
raw = raw[2:] # "/Users/..." style after drive strip
p = Path(raw)
parts = list(Path(raw).parts)
# Path("C:/Users/..") on POSIX may keep "C:" as first part — strip it.
if parts and len(parts[0]) == 2 and parts[0][1] == ":" and parts[0][0].isalpha():
parts = parts[1:]
# Prefer keeping from the output-dir marker onward: portable in every
# case, whereas a cwd-relative path still leaks host/user segments when
# the graph is built from a directory ABOVE the project (#2598 follow-up).
marker = GRAPHIFY_OUT_NAME
for i, part in enumerate(parts):
if part == marker or part.startswith("graphify-out"):
return "/".join(parts[i:])
# No standard out-dir marker (fully custom output path): fall back to a
# cwd-relative label when the target is under cwd, else the bare filename.
try:
resolved = p if p.is_absolute() else (Path.cwd() / p)
rel = resolved.resolve().relative_to(Path.cwd().resolve())
label = rel.as_posix()
if label and label != ".":
return label
except (ValueError, OSError, RuntimeError):
pass
name = p.name
return name if name else "graph.html"
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,
) -> bool:
"""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.
Returns True when the output was written. Returns False when an aggregated
view would contain fewer than two communities and is intentionally skipped.
"""
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 False
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
written = to_html(meta, meta_communities, output_path,
community_labels=community_labels, member_counts=mc)
if not written:
return False
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 True
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(_html_document_title(output_path)))
stats = f"{G.number_of_nodes()} nodes &middot; {G.number_of_edges()} edges &middot; {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>"""
write_text_atomic(output_path, html)
return True
+9499 -6018
View File
File diff suppressed because it is too large. Load diff
-107
View File
@@ -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`.
-66
View File
@@ -1,66 +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.commonlisp import extract_commonlisp
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,
"commonlisp": extract_commonlisp,
"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,
}
-215
View File
@@ -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}
-85
View File
@@ -1,85 +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",
# Swift standard library / Foundation / SwiftUI (#2147). Value-type
# initializers (Data(x), Int(x), UUID()) and protocol conformance targets
# appear from virtually every file of a Swift codebase, exactly like the
# ECMAScript constructors above. String/Date/URL/Error are already listed.
"Int", "Int8", "Int16", "Int32", "Int64",
"UInt", "UInt8", "UInt16", "UInt32", "UInt64",
"Double", "Float", "Bool", "Character",
"Sendable", "Codable", "Decodable", "Encodable", "Equatable", "Hashable",
"Identifiable", "Comparable", "CaseIterable", "RawRepresentable",
"CustomStringConvertible", "CustomDebugStringConvertible", "AnyObject",
"LocalizedError",
"Data", "UUID", "Decimal", "Calendar", "Locale", "TimeZone", "Bundle",
"IndexPath", "IndexSet", "NotificationCenter", "UserDefaults",
"FileManager", "URLSession", "URLRequest", "URLComponents",
"JSONDecoder", "JSONEncoder", "DateFormatter", "NumberFormatter",
"ISO8601DateFormatter",
"NSObject", "NSString", "NSError", "NSLock", "NSAttributedString",
"DispatchQueue", "DispatchGroup", "OperationQueue", "RunLoop",
"View", "Color", "Font",
})
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")
-579
View File
@@ -1,579 +0,0 @@
"""Bash extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any
from graphify.extractors.base import _file_stem, _make_id, _read_text
# Leading `${VAR}` / `$VAR` expansion segment(s) of a `source` path argument. The
# canonical `BENCH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` idiom makes
# such a variable resolve to the script's own directory, so the literal suffix that
# follows (`lib/x.sh`) can be resolved against the sourcing file's own dir (#2079).
_BASH_LEADING_EXPANSION = re.compile(
r"^(?:(?:\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*)/?)+"
)
def _bash_source_suffix(raw: str, allow_dotdot: bool = False) -> str | None:
"""Return the literal path suffix of a variable-built `source` argument, or
None when the remainder is empty or still holds an expansion.
``"${DIR}/lib/x.sh"`` -> ``"lib/x.sh"``.
When *allow_dotdot* is False (the default — the base is a script-dir guess),
``..`` segments are rejected to prevent traversal outside the project tree.
When True (the base is a tracked var_bases entry — a known directory),
``..`` is permitted and the caller normalises with ``os.path.normpath``.
"""
suffix = _BASH_LEADING_EXPANSION.sub("", raw, count=1).lstrip("/")
if not suffix or "$" in suffix:
return None
if not allow_dotdot and ".." in suffix.split("/"):
return None
return suffix
def _within_tree(ceiling: Path, target: Path) -> bool:
"""True if *target* is *ceiling* or lives beneath it, compared lexically
(normpath, no filesystem access).
A ``source`` path built with ``..`` (the ``$VAR/../lib`` idiom, #2596 form 4,
or a ``$(dirname …)`` prefix) must not be allowed to walk up to an arbitrary
host path: a corpus is attacker-controllable, and both the ``is_file()``
existence probe and the recorded absolute ``target_file`` on the emitted edge
are a corpus-side information leak (``source "$VAR/../../../../etc/passwd"``).
Callers gate the probe/emit on this so a target that escapes the allowed tree
is dropped before it is ever stat-ed. Defense in depth only:
``resolve_bash_source_edges`` independently keeps a *resolved* edge only when
the target is itself a scanned corpus file."""
c = os.path.normpath(str(ceiling))
t = os.path.normpath(str(target))
return t == c or t.startswith(c + os.sep)
# Recognise ``$(dirname "$VAR")`` (or ``$(dirname "${VAR}")``) at the start of
# a ``source`` argument, capturing the variable name so the source resolver
# can treat the whole construct as ``var_bases[VAR].parent`` (#2596 form 3).
_BASH_SOURCE_DIRNAME = re.compile(
r'\$\(dirname\s+"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?"\)'
)
# Name of the leading variable of a `source` argument: `${ROOT}/lib/x.sh` -> ROOT.
_BASH_LEADING_VAR = re.compile(
r"^\$\{([A-Za-z_][A-Za-z0-9_]*)[^}]*\}|^\$([A-Za-z_][A-Za-z0-9_]*)"
)
# The `$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)` idiom, capturing the
# trailing `/..` hops applied to the dirname result.
_BASH_DIRNAME_IDIOM = re.compile(r"dirname[^)]*\)((?:/\.\.)*)")
def _bash_assignment_base(value: str, script_dir: Path) -> Path | None:
"""Resolve a top-level assignment's value to a directory, or None if untracked.
Covers the two forms that make a ``source "${VAR}/lib/x.sh"`` target knowable
statically (#2172):
* the script-dir idiom ``"$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"``,
including any number of trailing ``/..`` hops (and the ``$0`` spelling)
* a literal path, absolute or relative to the script's own directory
Anything else -- a value built from other variables, or command substitution
we do not model -- is left untracked so the caller keeps its previous
script-dir guess rather than binding somewhere invented.
"""
val = value.strip().strip("'\"")
if not val:
return None
if "dirname" in val and ("BASH_SOURCE" in val or "$0" in val):
m = _BASH_DIRNAME_IDIOM.search(val)
base = script_dir
for _ in range((m.group(1).count("..") if m else 0)):
base = base.parent
return base
if "$" in val or "`" in val:
return None
candidate = Path(val)
return candidate if candidate.is_absolute() else script_dir / candidate
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] = []
# Cross-file resolution scaffolding consumed by resolve_bash_source_edges in
# the extract pipeline: `bash_sources` records which files this one `source`s,
# `raw_calls` records calls whose callee isn't defined in this file (candidate
# calls into a sourced library). The extractor sees one file at a time and so
# can't resolve these itself (#2141).
raw_calls: list[dict] = []
bash_sources: list[dict] = []
raw_seen: set[tuple[str, str]] = set()
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,
target_file: 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
# Transient resolved-target hint (#1814/#2169), mirroring the Python/
# markdown extractors: lets the extract() id-remap pass canonicalize a
# target minted from an absolute path even when the target file is not
# in the batch (incremental run) or lives out of root (#2243). Popped
# before anything persists, never shipped into graph.json.
if target_file is not None:
edge["target_file"] = target_file
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 _bash_call_in_command_allowed(cmd_node) -> bool:
"""Whether a command node should emit call edges.
Bare ``$(fn)`` at script level and process substitutions stay suppressed
(#2141). Value capture via ``x=$(fn)`` is a real invocation (#2978).
"""
parent = cmd_node.parent
saw_command_substitution = False
while parent is not None:
if parent.type == "process_substitution":
return False
if parent.type == "command_substitution":
saw_command_substitution = True
if parent.type == "variable_assignment" and saw_command_substitution:
return True
parent = parent.parent
return not saw_command_substitution
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 _bash_call_in_command_allowed(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")
elif (name and name not in _BASH_SOURCE_COMMANDS
and name not in _BASH_SCRIPT_RUNNERS):
# Callee isn't defined in this file — it may be a function
# from a sourced library. Record an unresolved raw_call for
# resolve_bash_source_edges to bind against the files this
# script `source`s. A callee that is not a sourced function
# (a genuine external command) matches nothing there and
# yields no edge, so this can't over-connect the graph (#2141).
raw_key = (func_nid, name)
if raw_key not in raw_seen:
raw_seen.add(raw_key)
raw_calls.append({
"language": "bash",
"callee": name,
"caller_nid": func_nid,
"source_file": str_path,
"source_location": f"L{child.start_point[0] + 1}",
})
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",
target_file=str(resolved))
# Record the sourced file so resolve_bash_source_edges
# can bind calls into its functions (#2141). Gated on
# existence like the edge above, so crafted traversal
# paths never enter the resolver's data.
bash_sources.append({
"target_path": raw,
"source_file": str_path,
"source_location": f"L{line}",
})
elif "$" in raw:
# Variable-built path, e.g. the ubiquitous
# `source "${BENCH_DIR}/lib/x.sh"` idiom. The raw text
# bakes the unexpanded `${VAR}` into the id, which
# matches no node and is dropped as a dangling edge
# (#2079). Strip the leading expansion(s) and resolve
# the literal suffix against the script's own dir;
# emit INFERRED (the expansion can't be proven
# statically) only when it resolves to a real file,
# never a dead id.
# Form 3 (#2596): `source "$(dirname "$VAR")/lib/x.sh"`
# — command substitution in the source argument.
# Recognise the dirname idiom on the source line the
# same way _bash_assignment_base does on assignment
# lines: treat `$(dirname "$VAR")` as
# `var_bases[VAR].parent` (falling back to
# `script_dir.parent` when VAR is untracked), then
# resolve the literal suffix against it.
dirname_match = _BASH_SOURCE_DIRNAME.match(raw)
if dirname_match:
var_name = dirname_match.group(1)
if var_name in var_bases:
base = var_bases[var_name].parent
else:
# Untracked var: fall back to the script's
# own directory, so dirname resolves to its
# parent — matching the existing untracked-var
# fallback semantics.
base = path.parent.parent
# Strip the $(dirname ...) prefix and any leading
# slash to get the literal suffix.
suffix = raw[dirname_match.end():].lstrip("/")
# The base is a guessed script dir, so reject a
# `..` suffix outright — same policy as
# _bash_source_suffix(allow_dotdot=False); without
# it, `$(dirname "$VAR")/../../../etc/passwd`
# resolves and gets probed/recorded (#2596).
if (suffix and "$" not in suffix
and ".." not in suffix.split("/")):
resolved = (base / suffix).resolve()
if resolved.is_file():
add_edge(file_nid, _make_id(str(resolved)),
"imports_from", line,
confidence="INFERRED", context="import",
target_file=str(resolved))
bash_sources.append({
"target_path": str(resolved),
"source_file": str_path,
"source_location": f"L{line}",
})
else:
# Check if the leading variable is tracked
# before deciding whether to allow `..` in
# the suffix (Form 4, #2596). When the base
# is a known var_bases entry, `..` is safe.
var_match = _BASH_LEADING_VAR.match(raw)
allow_dotdot = False
if var_match:
_vn = var_match.group(1) or var_match.group(2)
if _vn in var_bases:
allow_dotdot = True
suffix = _bash_source_suffix(raw, allow_dotdot=allow_dotdot)
if suffix:
# Resolve against the variable's tracked base
# when we know it, else fall back to the
# script's own directory as before (#2172).
base = path.parent
if var_match:
var_name = var_match.group(1) or var_match.group(2)
if var_name in var_bases:
base = var_bases[var_name]
if var_match and var_name in var_bases:
resolved = Path(os.path.normpath(base / suffix))
# A tracked base may reach a sibling via
# `$VAR/../lib`, so the ceiling is one
# level up — but `..` must not walk past
# it to an arbitrary host path (#2596).
ceiling = base.parent
else:
resolved = (base / suffix).resolve()
# Untracked base: `..` was already rejected
# by _bash_source_suffix, so the target is
# under base; the gate is belt-and-braces.
ceiling = base
if _within_tree(ceiling, resolved) and resolved.is_file():
add_edge(file_nid, _make_id(str(resolved)),
"imports_from", line,
confidence="INFERRED", context="import",
target_file=str(resolved))
# Integration (#2141 + #2079): record
# the resolved sourced file so calls
# into its functions resolve too, not
# just the source edge. target_path is
# absolute here; resolve_bash_source_edges
# takes it as-is.
bash_sources.append({
"target_path": str(resolved),
"source_file": str_path,
"source_location": f"L{line}",
})
else:
# Bare `source lib.sh` (no leading ./ or /). Bash
# itself resolves such a name via $PATH at runtime,
# but in practice the file sits next to the script,
# so bind it when a sibling of that name exists
# (#2171). Same existence gate as the ./-prefixed
# branch above: a name that resolves to nothing keeps
# the old opaque `imports` edge and records no
# bash_sources entry, so nothing is fabricated.
sibling: Path | None = None
if raw:
try:
candidate = path.parent / raw
if candidate.is_file():
sibling = candidate.resolve()
except OSError:
sibling = None
if sibling is not None:
# A bare `source lib.sh` resolves via $PATH at
# runtime; binding it to the sibling of that name
# is a heuristic, so mark it INFERRED (#2171).
add_edge(file_nid, _make_id(str(sibling)),
"imports_from", line,
confidence="INFERRED", context="import",
target_file=str(sibling))
bash_sources.append({
"target_path": raw,
"source_file": str_path,
"source_location": f"L{line}",
})
else:
tgt_nid = _make_id(raw)
if tgt_nid:
add_edge(file_nid, tgt_nid, "imports", line,
context="import")
elif cmd not in defined_functions:
raw = cmd if (cmd and cmd.endswith(".sh")) else None
if cmd and cmd in _BASH_SCRIPT_RUNNERS and args:
raw = literal(args[0])
if raw is None:
# The command name is itself an expansion, e.g.
# `"$script_dir/x.sh" --flag`. `literal()` rejects any
# candidate containing "$", so `cmd` is None and neither
# of the two branches above can see the path. Read the
# node's raw text the way the `source` branch does and
# strip the leading ${VAR}/ segments -- the same
# script-dir assumption already used for `source
# "$DIR/lib/x.sh"` (#2079). `_bash_source_suffix`
# rejects a remainder that still holds an expansion or
# a `..` segment, and the `resolved.is_file()` gate
# below means a wrong script-dir guess emits nothing.
cand = _read_text(cmd_name_node, source).strip().strip("'\"")
if cand.endswith(".sh") and "$" in cand:
raw = _bash_source_suffix(cand) or None
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
# target_file lets the extract() remap loop learn
# this script's canonical id even when it is not in
# the batch; the "__entry"-suffixed endpoint is
# rewritten there via the suffix-aware entry
# registration (#2243).
add_edge(caller_nid, _make_id(str(target_path)) + "__entry",
"calls", node.start_point[0] + 1,
context="script_invocation",
target_file=str(target_path))
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)
# Bases for `source "${VAR}/lib/x.sh"` resolution (#2172). #2079 always resolved
# the literal suffix against the script's own directory, which is right for the
# `DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` idiom but wrong whenever
# the variable points elsewhere -- e.g. ROOT=".../scripts/.." with a same-named
# decoy under the script dir bound to the decoy. Track top-level assignments so
# the real base is used; untracked variables keep the script-dir guess.
var_bases: dict[str, Path] = {}
for _assign in root.children:
if _assign.type != "variable_assignment":
continue
_name_node = _assign.child_by_field_name("name")
_value_node = _assign.child_by_field_name("value")
if _name_node is None or _value_node is None:
continue
_name = _read_text(_name_node, source).strip()
if not _name:
continue
_base = _bash_assignment_base(_read_text(_value_node, source), path.parent)
if _base is not None:
var_bases[_name] = _base
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,
"raw_calls": raw_calls, "bash_sources": bash_sources}
-53
View File
@@ -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}
-540
View File
@@ -1,540 +0,0 @@
"""Common Lisp extractor for .lisp/.cl/.lsp/.asd, backed by tree-sitter-commonlisp."""
from __future__ import annotations
import warnings
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id
# Standard CL definer forms that introduce data/type/variable bindings
# (not callable, no body to walk for calls)
_CL_DATA_DEFINERS = frozenset({
"defstruct", "deftype", "define-condition",
"defvar", "defparameter", "defconstant",
"define-symbol-macro",
})
# Subset of data definers that take a VALUE as their second argument, which
# may itself be a string literal. For these, we must not mistake the value
# for a docstring.
_CL_VALUE_DEFINERS = frozenset({"defvar", "defparameter", "defconstant"})
# Standard CL macro-style definers
_CL_MACRO_DEFINERS = frozenset({
"define-modify-macro", "define-compiler-macro",
"define-setf-expander", "defsetf",
})
# Symbols that start with "def" but are NOT definitions (denylist for the
# def-prefix heuristic that catches custom definers like definline-maybe)
_CL_NOT_DEFINERS = frozenset({
"default", "default-value", "defaults", "define",
"defer", "deferred", "deflate", "deftest",
})
# CL special forms / macros that should not count as "calls" in the graph
_CL_SPECIAL_FORMS = frozenset({
"let", "let*", "flet", "labels", "macrolet",
"if", "when", "unless", "cond", "case", "ecase", "typecase", "etypecase",
"progn", "prog1", "prog2", "block", "return-from", "tagbody", "go",
"lambda", "function", "funcall", "apply",
"setf", "setq", "psetf", "psetq", "incf", "decf", "push", "pop",
"loop", "do", "do*", "dolist", "dotimes", "map", "mapcar", "mapc",
"format", "print", "princ", "prin1", "write", "terpri",
"and", "or", "not", "null",
"values", "multiple-value-bind", "multiple-value-setq",
"declare", "the", "locally", "eval-when",
"quote", "backquote",
"error", "signal", "warn", "assert", "check-type",
"handler-case", "handler-bind", "restart-case", "ignore-errors",
"unwind-protect", "catch", "throw",
"with-open-file", "with-output-to-string", "with-input-from-string",
"with-slots", "with-accessors",
"defvar", "defparameter", "defconstant",
"in-package", "require", "provide", "use-package",
"t", "nil",
})
def extract_commonlisp(path: Path) -> dict:
"""Extract packages, classes, functions, methods, macros, and calls from a Common Lisp file."""
try:
import tree_sitter_commonlisp as tscl
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-commonlisp not installed"}
try:
# tree-sitter-commonlisp 0.4.1 (latest) ships the old binding that returns
# an int pointer from language(); tree_sitter.Language only accepts that
# int via a deprecated path. Silence that one warning at the call site
# until the grammar ships a PyCapsule binding.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="int argument support is deprecated",
category=DeprecationWarning,
)
language = Language(tscl.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)}
# Path-qualified, not the bare `path.stem`: same-named .lisp files in
# different directories must not collide (#1504). Pre-collapsed through
# `_make_id` because `_cl_id` would otherwise map the `/` separators to
# `_slash` via _CL_CHAR_MAP.
stem = _make_id(_file_stem(path))
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
function_bodies: list[tuple[str, object]] = [] # (nid, body_nodes)
current_package: str | None = None
def _text(node) -> str:
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
# CL symbols can contain operator chars like = < > ? ! + * / that the
# generic _make_id strips. Map them to readable suffixes so upi=, upi<,
# upi> become distinct ids.
_CL_CHAR_MAP = {
'=': '_eq', '<': '_lt', '>': '_gt', '?': '_p', '!': '_bang',
'+': '_plus', '*': '_star', '/': '_slash', '%': '_pct', '&': '_amp',
}
def _cl_id(*parts: str) -> str:
normalized = []
for p in parts:
normalized.append(''.join(_CL_CHAR_MAP.get(c, c) for c in p))
return _make_id(*normalized)
def add_node(nid: str, label: str, line: int, file_type: str = "code") -> 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 = _cl_id(stem)
add_node(file_nid, path.name, 1)
def add_import_stub(mod_name: str) -> str:
"""Mint a SOURCELESS stub for an imported package so its `imports` edge
has a real target instead of dangling. The corpus rewire collapses it
onto a unique in-corpus `defpackage` of the same name; an external one
(cl, alexandria) stays a sourceless leaf. `origin_file` is stripped
before persist (no #1899 leak); a sourced bare stub would salt the id."""
nid = _cl_id(mod_name)
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": mod_name,
"file_type": "code",
"source_file": "",
"source_location": "",
"origin_file": str_path,
})
return nid
def ensure_class_ref(name: str, line: int) -> str:
"""Resolve a superclass name to a node id.
If the class is defined in THIS file, bind to its local node. Otherwise
mint a SOURCELESS stub (like `add_import_stub`) so the corpus-level
rewire can collapse it onto the real `defclass` in another file. Without
this, a cross-file superclass had no matching node and its `inherits`
edge was pruned by the dangling-edge filter — silently erasing every
inheritance edge whose parent lives in a different file."""
local = _cl_id(stem, name)
if local in seen_ids:
return local
stub = _cl_id(name)
if stub not in seen_ids:
seen_ids.add(stub)
nodes.append({
"id": stub,
"label": name,
"file_type": "code",
"source_file": "",
"source_location": "",
"origin_file": str_path,
})
return stub
def _first_sym(node) -> str | None:
"""Get the first sym_lit text from a list_lit's children."""
for child in node.children:
if child.type == "sym_lit":
return _text(child)
return None
def _kwd_text(node) -> str:
"""Extract the symbol name from a kwd_lit, stripping the leading colon."""
t = _text(node)
return t.lstrip(":").lstrip("#:")
def _handle_defpackage(node) -> None:
nonlocal current_package
children = node.children
pkg_name = None
for child in children:
if child.type == "kwd_lit" and pkg_name is None:
pkg_name = _kwd_text(child)
break
if child.type == "sym_lit" and _text(child) != "defpackage":
pkg_name = _text(child)
break
if not pkg_name:
return
current_package = pkg_name
pkg_nid = _cl_id(stem, pkg_name)
line = node.start_point[0] + 1
add_node(pkg_nid, pkg_name, line)
add_edge(file_nid, pkg_nid, "contains", line)
# Extract :use clauses as imports
for child in children:
if child.type == "list_lit":
first = _first_sym(child)
if first is None:
# Could be (:use ...) with kwd_lit
for gc in child.children:
if gc.type == "kwd_lit" and _kwd_text(gc) == "use":
for uc in child.children:
if uc.type == "kwd_lit" and uc != gc:
mod_name = _kwd_text(uc)
if mod_name != "use":
tgt_nid = add_import_stub(mod_name)
add_edge(pkg_nid, tgt_nid, "imports",
child.start_point[0] + 1)
break
def _handle_defclass(node) -> None:
children = node.children
# Find class name: second sym_lit after "defclass"
sym_lits = [c for c in children if c.type == "sym_lit"]
if len(sym_lits) < 2:
return
class_name = _text(sym_lits[1])
line = node.start_point[0] + 1
class_nid = _cl_id(stem, class_name)
add_node(class_nid, class_name, line)
parent_nid = file_nid
if current_package:
pkg_nid = _cl_id(stem, current_package)
if pkg_nid in seen_ids:
parent_nid = pkg_nid
add_edge(parent_nid, class_nid, "contains", line)
# Superclasses (third element, a list)
list_lits = [c for c in children if c.type == "list_lit"]
if list_lits:
superclass_list = list_lits[0]
for sc in superclass_list.children:
if sc.type == "sym_lit":
sc_name = _text(sc)
sc_nid = ensure_class_ref(sc_name, superclass_list.start_point[0] + 1)
add_edge(class_nid, sc_nid, "inherits",
superclass_list.start_point[0] + 1)
def _handle_defun_node(node) -> None:
"""Handle a defun AST node (covers defun, defmethod, defgeneric, defmacro)."""
header = None
for child in node.children:
if child.type == "defun_header":
header = child
break
if not header:
return
# Determine keyword type
keyword_type = "defun"
func_name = None
for child in header.children:
if child.type == "defun_keyword":
for kc in child.children:
if kc.type in ("defun", "defmethod", "defgeneric", "defmacro"):
keyword_type = kc.type
break
if child.type == "sym_lit" and func_name is None:
func_name = _text(child)
if not func_name:
return
line = node.start_point[0] + 1
func_nid = _cl_id(stem, func_name)
if keyword_type == "defmethod":
label = f".{func_name}()"
elif keyword_type == "defmacro":
label = f"{func_name} (macro)"
elif keyword_type == "defgeneric":
label = f"{func_name} (generic)"
else:
label = f"{func_name}()"
add_node(func_nid, label, line)
parent_nid = file_nid
if current_package:
pkg_nid = _cl_id(stem, current_package)
if pkg_nid in seen_ids:
parent_nid = pkg_nid
if keyword_type == "defmethod":
add_edge(parent_nid, func_nid, "method", line)
else:
add_edge(parent_nid, func_nid, "contains", line)
# Method specializers: (defmethod name ((param class) ...))
if keyword_type == "defmethod":
for child in header.children:
if child.type == "list_lit":
# This is the parameter list
for param in child.children:
if param.type == "list_lit":
syms = [c for c in param.children if c.type == "sym_lit"]
if len(syms) >= 2:
specializer_name = _text(syms[1])
spec_nid = _cl_id(stem, specializer_name)
add_edge(func_nid, spec_nid, "specializes",
param.start_point[0] + 1)
break
# Docstring
for child in node.children:
if child.type == "str_lit":
doc_text = _text(child).strip('"')
if doc_text:
doc_nid = _cl_id(func_nid, "rationale")
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
add_edge(doc_nid, func_nid, "rationale_for",
child.start_point[0] + 1)
break
# Collect body for call extraction
body_nodes = [c for c in node.children
if c.type not in ("(", ")", "defun_header", "str_lit")]
if body_nodes:
function_bodies.append((func_nid, body_nodes))
def _extract_def_name(node, def_keyword: str) -> str | None:
"""Get the name being defined. May be a sym_lit or a list_lit whose
first sym_lit is the name (e.g. (defstruct (foo :conc-name "BAR-") ...))."""
seen_keyword = False
for child in node.children:
if not seen_keyword:
if child.type == "sym_lit" and _text(child).lower() == def_keyword:
seen_keyword = True
continue
if child.type == "sym_lit":
return _text(child)
if child.type == "list_lit":
for gc in child.children:
if gc.type == "sym_lit":
return _text(gc)
return None
return None
def _collect_def_body(node, def_keyword: str) -> list:
"""Collect body forms from (DEFKEYWORD name (params) [doc] body...).
Skips the def keyword, the name, the params list (if present), and
a leading docstring str_lit."""
children = [c for c in node.children if c.type not in ("(", ")")]
idx = 0
# Skip def keyword
if idx < len(children) and children[idx].type == "sym_lit" \
and _text(children[idx]).lower() == def_keyword:
idx += 1
# Skip name (sym_lit or list_lit)
if idx < len(children) and children[idx].type in ("sym_lit", "list_lit"):
idx += 1
# Skip params list (the next list_lit, if any)
if idx < len(children) and children[idx].type == "list_lit":
idx += 1
# Skip leading docstring
if idx < len(children) and children[idx].type == "str_lit":
idx += 1
return children[idx:]
def _handle_def_form(node, def_keyword: str) -> None:
"""Handle a generic (DEFKEYWORD name ...) form. Covers standard CL
definers (defstruct, deftype, defvar, define-condition, etc.) and
custom def-prefixed macros (definline, definline-maybe, etc.)."""
name = _extract_def_name(node, def_keyword)
if not name:
return
line = node.start_point[0] + 1
nid = _cl_id(stem, name)
kw = def_keyword.lower()
if kw in _CL_DATA_DEFINERS:
label = name
is_callable = False
elif kw in _CL_MACRO_DEFINERS or "macro" in kw:
label = f"{name} (macro)"
is_callable = True
else:
# Custom def-prefixed: assume function-like
label = f"{name}()"
is_callable = True
add_node(nid, label, line)
parent_nid = file_nid
if current_package:
pkg_nid = _cl_id(stem, current_package)
if pkg_nid in seen_ids:
parent_nid = pkg_nid
add_edge(parent_nid, nid, "contains", line)
# Docstring. Skip for defvar/defparameter/defconstant — their second
# argument is a value (possibly a string literal) which would be
# wrongly captured as a docstring.
if kw not in _CL_VALUE_DEFINERS:
for child in node.children:
if child.type == "str_lit":
doc_text = _text(child).strip('"')
if doc_text:
doc_nid = _cl_id(nid, "rationale")
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
add_edge(doc_nid, nid, "rationale_for",
child.start_point[0] + 1)
break
if is_callable:
body_nodes = _collect_def_body(node, def_keyword)
if body_nodes:
function_bodies.append((nid, body_nodes))
def _is_def_prefixed(sym: str) -> bool:
"""Heuristic: does this symbol look like a definition macro?"""
if sym in _CL_NOT_DEFINERS:
return False
return sym.startswith("def") or sym.startswith("define-")
def _process_form(top) -> bool:
"""Dispatch on a single list_lit form. Returns True if it was
recognized as a definition or package directive (caller must NOT
recurse into it). Returns False if unrecognized, so the caller can
recurse to find defs nested inside wrapper macros like
(optimizing ...), (eval-when ...), (progn ...), etc."""
nonlocal current_package
# Check for defun node type inside list_lit
for child in top.children:
if child.type == "defun":
_handle_defun_node(child)
return True
first = _first_sym(top)
if not first:
return False
first_lower = first.lower()
if first_lower == "defpackage":
_handle_defpackage(top)
return True
if first_lower == "in-package":
for child in top.children:
if child.type == "kwd_lit":
current_package = _kwd_text(child)
break
if child.type == "sym_lit" and _text(child) != "in-package":
current_package = _text(child)
break
return True
if first_lower == "defclass":
_handle_defclass(top)
return True
if first_lower in ("require", "ql:quickload"):
for child in top.children:
if child.type in ("kwd_lit", "str_lit"):
mod_name = _kwd_text(child) if child.type == "kwd_lit" else _text(child).strip('"')
if mod_name:
tgt_nid = add_import_stub(mod_name)
add_edge(file_nid, tgt_nid, "imports",
top.start_point[0] + 1)
break
return True
if first_lower in _CL_DATA_DEFINERS or first_lower in _CL_MACRO_DEFINERS:
_handle_def_form(top, first_lower)
return True
if _is_def_prefixed(first_lower):
# Custom definer (definline, definline-maybe, defcomponent, etc.)
_handle_def_form(top, first_lower)
return True
return False
def _walk_forms(parent) -> None:
"""Walk list_lit children of `parent`, processing each. If a form
isn't recognized, recurse into it — many CL codebases wrap
definitions in macros like (optimizing ...), (eval-when ...), or
(progn ...) that aren't themselves definers but contain defs.
Also descends into reader conditionals (#+feature / #-feature),
which wrap their guarded form in an include_reader_macro node."""
for top in parent.children:
if top.type == "list_lit":
if not _process_form(top):
_walk_forms(top)
elif top.type == "include_reader_macro":
_walk_forms(top)
_walk_forms(root)
# Call extraction pass
label_to_nid: dict[str, str] = {}
for n in nodes:
raw = n["label"]
normalised = raw.replace(" (macro)", "").replace(" (generic)", "").strip("()").lstrip(".")
label_to_nid[normalised.lower()] = n["id"]
seen_call_pairs: set[tuple[str, str]] = set()
def walk_calls(node, caller_nid: str) -> None:
if node.type == "defun":
return
if node.type == "list_lit":
callee = _first_sym(node)
if callee and callee.lower() not in _CL_SPECIAL_FORMS:
tgt_nid = label_to_nid.get(callee.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)
for child in node.children:
walk_calls(child, caller_nid)
for caller_nid, body_nodes in function_bodies:
for body_node in body_nodes:
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", "imports_from"))]
return {"nodes": nodes, "edges": clean_edges}
-448
View File
@@ -1,448 +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
]
_DOTNET_SOURCE_EXTS = (".cs", ".razor", ".cshtml")
def _is_cs_file(value: object) -> bool:
return isinstance(value, str) and value.endswith(".cs")
def _is_dotnet_source_file(value: object) -> bool:
return isinstance(value, str) and value.endswith(_DOTNET_SOURCE_EXTS)
def _metadata(value: object) -> dict:
return value if isinstance(value, dict) else {}
class CsharpNameResolver:
"""Namespace/using/alias-aware C# simple-name resolution.
Factored out of ``_resolve_csharp_type_references`` so the member-call pass
(``_resolve_csharp_member_calls`` in ``graphify/extract.py``) can type a
receiver with the same scoping rules the type-reference side already applies
(the core of #1620), instead of bailing on any corpus-wide bare-name clash.
Built from graph-stamped facts only: the ``(namespace, name)`` type-definition
index plus the per-file ``using``/alias import edges (each carrying its lexical
scope — ``("file", None)`` applies file-wide; ``("namespace", scope_id)``
applies only where ``scope_id`` is in the referencing node's ``scope_chain``).
"""
def __init__(self, all_nodes: list[dict], all_edges: list[dict]) -> None:
self.node_by_id: dict[str, dict] = {
node["id"]: node
for node in all_nodes
if isinstance(node.get("id"), str) and node.get("id")
}
self.type_def_index = _build_csharp_type_def_index(all_nodes)
self.known_namespaces = {
node.get("label")
for node in all_nodes
if node.get("type") == "namespace" and isinstance(node.get("label"), str)
}
self.namespace_usings_by_file: dict[str, list[tuple[str, str, str | None]]] = {}
self.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 = self.node_by_id.get(edge.get("source"))
if not (
source_node
and isinstance(source_node.get("label"), str)
and source_node.get("label", "").endswith(_DOTNET_SOURCE_EXTS)
):
continue
source_file = source_node.get("source_file")
if not _is_dotnet_source_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 = self.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 = self.aliases_by_file.setdefault(source_file, {}).setdefault(alias, [])
if entry not in bucket:
bucket.append(entry)
@staticmethod
def _namespace(node: dict | None) -> str:
metadata = _metadata((node or {}).get("metadata"))
namespace = metadata.get("namespace", "")
return namespace if isinstance(namespace, str) else ""
@staticmethod
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(self, 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 self._scope_chain(source_node)
def _scopes_for(self, source_node: dict, source_file: str) -> list[str]:
def _append_unique(items: list[str], value: str) -> None:
if value not in items:
items.append(value)
scopes: list[str] = []
_append_unique(scopes, self._namespace(source_node))
_append_unique(scopes, "")
for namespace, scope_kind, scope_id in self.namespace_usings_by_file.get(source_file, []):
if self._using_in_scope(scope_kind, scope_id, source_node):
_append_unique(scopes, namespace)
return scopes
def _resolve_alias(self, label: str, source_node: dict, source_file: str) -> str | None:
hits = set()
for target_fqn, scope_kind, scope_id in self.aliases_by_file.get(source_file, {}).get(label, []):
if not self._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 = self.type_def_index.get((namespace, simple_name))
if hit:
hits.add(hit)
return next(iter(hits)) if len(hits) == 1 else None
def resolve_type_name(
self, label: str, source_node: dict, source_file: str
) -> tuple[str | None, bool]:
"""Resolve a simple type name to a definition node id, with a verdict.
Returns ``(node_id, decisive)``:
* ``(nid, True)`` — exactly one in-scope definition (or alias target).
* ``(None, True)`` — the name is claimed by this file's scoping (an
alias, or >1 in-scope candidates): genuinely ambiguous/unresolvable,
the caller must NOT fall back to a looser corpus-wide match.
* ``(None, False)`` — scoping knows nothing about the name; a caller
may fall back (e.g. to the corpus-wide unique bare-name match).
"""
if label in self.aliases_by_file.get(source_file, {}):
return self._resolve_alias(label, source_node, source_file), True
candidates: list[str] = []
for namespace in self._scopes_for(source_node, source_file):
hit = self.type_def_index.get((namespace, label))
if hit and hit not in candidates:
candidates.append(hit)
if len(candidates) == 1:
return candidates[0], True
return None, bool(candidates)
def resolve_label(self, label: str, source_node: dict, source_file: str) -> str | None:
resolved, _decisive = self.resolve_type_name(label, source_node, source_file)
return resolved
def resolve_qualified(
self, 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 self.aliases_by_file.get(source_file, {}).get(qualifier, [])
if self._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 = self.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 self.known_namespaces:
return self.type_def_index.get((qualifier, label))
return None
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)
resolver = CsharpNameResolver(all_nodes, all_edges)
node_by_id = resolver.node_by_id
aliases_by_file = resolver.aliases_by_file
def _resolve_label(label: str, source_node: dict, source_file: str) -> str | None:
return resolver.resolve_label(label, source_node, source_file)
def _resolve_qualified(label: str, qualifier: object, source_node: dict, source_file: str) -> str | None:
return resolver.resolve_qualified(label, qualifier, source_node, source_file)
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_dotnet_source_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
]
-564
View File
@@ -1,564 +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("/"):
# Blank to the SAME number of newlines the comment spanned, not
# to an empty string: every offset computed against src_clean
# below (including every source_location line number) is only
# valid if src_clean's line count tracks the original file's.
# Deleting a multi-line comment outright shifted every later
# line number up by the comment's own height (#3365).
return "\n" * token.count("\n")
return token
src_clean = comment_string_pattern.sub(_comment_replace, src)
def _line_at(offset: int) -> int:
return src_clean[:offset].count("\n") + 1
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),
line: int | None = None) -> None:
if nid not in defined:
nodes.append({"id": nid, "label": label, "file_type": ftype,
"source_file": source_file,
"source_location": f"L{line}" if line else None})
defined.add(nid)
def add_edge(src_id: str, tgt_id: str, relation: str, weight: float = 1.0, context: str | None = None,
line: int | None = None) -> None:
edge = {"source": src_id, "target": tgt_id, "relation": relation,
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path),
"source_location": f"L{line}" if line else 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)
# Anchor on the capture group, not the whole match: the pattern's
# leading ^\s* makes m.start() land before the blank/indent lines
# that precede the declaration, reporting the line too early (#3365).
class_line = _line_at(m.start(1))
class_nid = _make_id(stem, class_name)
add_node(class_nid, class_name, line=class_line)
add_edge(file_nid, class_nid, "defines", line=class_line)
# 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", line=class_line)
# 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", line=class_line)
# 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", line=class_line)
# 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", line=class_line)
# 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",
line=_line_at(brace_pos + em.start(1)))
# 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",
line=_line_at(brace_pos + sm.start(1)))
# 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",
line=_line_at(brace_pos + am.start(1)))
# 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",
line=_line_at(brace_pos + rm.start(1)))
# 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",
line=_line_at(brace_pos + bm.start(1)))
# 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",
line=_line_at(brace_pos + lm.start(1)))
# 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_line = _line_at(am.start(1))
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", line=annotation_line)
# 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), line=annotation_line)
add_edge(target_nid, provider_nid, "defines", context="riverpod_provider", line=annotation_line)
# 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)
typedef_line = _line_at(m.start(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, line=typedef_line)
add_edge(file_nid, typedef_nid, "defines", line=typedef_line)
target_nid = _make_id(target_type)
add_node(target_nid, target_type, source_file=None)
add_edge(typedef_nid, target_nid, "references", context="typedef", line=typedef_line)
# 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_line = _line_at(m.start(2))
ext_nid = _make_id(stem, ext_name)
label = m.group(1) or f"Extension on {target_class}"
add_node(ext_nid, label, line=ext_line)
add_edge(file_nid, ext_nid, "defines", line=ext_line)
target_nid = _make_id(target_class)
add_node(target_nid, target_class, source_file=None)
add_edge(ext_nid, target_nid, "extends", line=ext_line)
# 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_line = _line_at(m.start(2))
var_nid = _make_id(stem, single_name)
add_node(var_nid, single_name, line=var_line)
add_edge(file_nid, var_nid, "defines", line=var_line)
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", line=var_line)
elif destructured_names:
destructure_line = _line_at(m.start(3))
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, line=destructure_line)
add_edge(file_nid, var_nid, "defines", line=destructure_line)
# 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
method_line = _line_at(m.start(1))
nid = _make_id(stem, name)
add_node(nid, name, line=method_line)
add_edge(file_nid, nid, "defines", line=method_line)
# 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",
line=_line_at(brace_pos + rm.start(1)))
# 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",
line=_line_at(brace_pos + am.start(1)))
# 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",
line=_line_at(brace_pos + lm.start(1)))
# 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",
line=_line_at(brace_pos + nm.start(1)))
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",
line=_line_at(brace_pos + cm.start(1)))
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",
line=_line_at(brace_pos + om.start(1)))
# 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", line=_line_at(m.start(1)))
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", line=_line_at(m.start(1)))
# 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",
line=_line_at(m.start(1)))
return {"nodes": nodes, "edges": edges}
-494
View File
@@ -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 = re.sub(r"^\./", "", raw.replace("\\", "/"))
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}
-250
View File
@@ -1,250 +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, **attrs) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
node = {"id": nid, "label": label, "file_type": "code",
"source_file": str_path, "source_location": f"L{line}"}
node.update(attrs)
nodes.append(node)
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)
# Only a top-level module is a safe cross-file resolution target
# (#3603 follow-up): a nested `defmodule Supervisor` is labeled with
# its bare inner name and would otherwise capture an unrelated
# `use Supervisor` from another file. Mark just the top-level ones;
# the marker rides through incremental rebuilds via the
# resolution-context allow-list in watch.py / cli.py.
add_node(module_nid, module_name, line,
**({"_elixir_module": True} if parent_module_nid is None else {}))
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:
# tree-sitter-elixir wraps a guarded head
# (`def f(x) when guard`) in `binary_operator`;
# without unwrapping, a function whose only clause
# carries `when` is dropped (#3111).
while child.type == "binary_operator":
head = None
for sub in child.children:
if sub.type in ("call", "identifier", "binary_operator"):
head = sub
break
if head is None:
break
child = head
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
-311
View File
@@ -1,311 +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). What matters is that an absolute path cannot begin with
# "-" — not that it begins with "/", which only holds on POSIX (a Windows
# absolute path starts with a drive letter, and is equally safe).
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}
-527
View File
@@ -1,527 +0,0 @@
"""Go extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
import hashlib
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",
})
# Go predeclared functions, filtered only when the callee is a BARE identifier.
# The Go resolver looks a callee up by name, so an unexported method that happens
# to share a builtin's name (`func (h *history) append(...)`) absorbs every
# builtin call in the corpus: on an 8.9k-node Go codebase one such method
# collected 330 phantom inbound `calls` edges, inventing twelve database-layer ->
# service-layer edges — a layering violation absent from the source.
#
# Deliberately language-local (mirroring _RUST_TRAIT_METHOD_BLOCKLIST) rather
# than added to the shared _LANGUAGE_BUILTIN_GLOBALS: `new`, `close` and friends
# are ordinary method names in the ~11 other languages that consult the shared
# set — listing them there kills every in-file Rust `Type::new()` edge.
#
# Bare-identifier-only for the same reason within Go: `h.append(v)` and
# `pkg.Delete(x)` are selector_expression callees and are genuine calls, so the
# filter must not reach them. Builtin *types* stay out (see
# _GO_PREDECLARED_TYPES): Go conversions are call-shaped too, but they produced
# no phantom edges on that corpus and filtering them would suppress genuine
# constructor-like calls.
#
# The set is the Go spec's predeclared function list in full. Being Go-local and
# bare-identifier-only makes completeness safe here: `len`, `max`, `min` and
# `print` carry the same shadowing hazard as `append`, and a principled boundary
# (the spec list) beats a hand-picked subset.
_GO_PREDECLARED_FUNCS = frozenset({
"append", "cap", "clear", "close", "complex", "copy", "delete", "imag",
"len", "make", "max", "min", "new", "panic", "print", "println", "real",
"recover",
})
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":
# Keep the package qualifier so the generic stub rewire cannot attach
# `testing.T` to an unrelated local type or function named T.
text = _read_text(node, source)
if text:
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]] = []
# local package name (including aliases) -> written Go import path
go_imported_pkgs: 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 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)
# Node IDs are casefolded (ids.py), so `Run` and `run` declared in one file
# produce the same id and add_node silently dropped the second — the unexported
# half vanished from the graph and its call sites bound by bare name to a
# same-named function in another package, which Go's visibility rules make
# impossible (#2779). Salt the non-canonical member of a case-only collision
# so both survive.
#
# The EXPORTED member keeps the plain id. Only exported symbols are reachable
# across packages, so cross-package edges (and edges cached in graph.json from
# files an incremental rebuild does not touch) target the exported one — keeping
# its id stable means adding/removing an unexported sibling in an update never
# re-points them. Docs likewise reference the exported API, so the casefolded id
# a semantic node produces lands on the symbol it actually describes. Calls to
# the unexported sibling can only come from the same package and only resolve
# once the sibling exists, so salting it re-points nothing. When the collision
# has no unique exported member (`Run`/`RUN`), every member is salted rather
# than picking one arbitrarily, so the result never depends on declaration order.
case_groups: dict[str, set[str]] = {}
def _receiver_type_of(node) -> str | None:
receiver = node.child_by_field_name("receiver")
if not receiver:
return None
for param in receiver.children:
if param.type == "parameter_declaration":
type_node = param.child_by_field_name("type")
if type_node:
return _read_text(type_node, source).lstrip("*").strip()
break
return None
def _plain_symbol_nid(node) -> tuple[str, str] | None:
name_node = node.child_by_field_name("name")
if not name_node:
return None
name = _read_text(name_node, source)
if node.type == "method_declaration":
receiver_type = _receiver_type_of(node)
base = _make_id(pkg_scope, receiver_type) if receiver_type else stem
else:
base = stem
return _make_id(base, name), name
def _scan_declarations(node) -> None:
if node.type in ("function_declaration", "method_declaration"):
found = _plain_symbol_nid(node)
if found:
case_groups.setdefault(found[0], set()).add(found[1])
return
for child in node.children:
_scan_declarations(child)
def symbol_nid(plain_nid: str, name: str) -> str:
names = case_groups.get(plain_nid) or set()
if len(names) < 2:
return plain_nid
exported = [n for n in names if n[:1].isupper()]
if len(exported) == 1 and name == exported[0]:
return plain_nid
salt = hashlib.sha1(name.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
return _make_id(plain_nid, salt)
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 = symbol_nid(_make_id(stem, func_name), 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 = symbol_nid(_make_id(parent_nid, method_name), method_name)
add_node(method_nid, f".{method_name}()", line)
add_edge(parent_nid, method_nid, "method", line)
else:
method_nid = symbol_nid(_make_id(stem, method_name), 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
# A type_elem that is a generics type-set constraint -
# a union (`A | B`) or an approximation (`~T`) - is NOT
# interface embedding. Go only embeds a lone interface
# type; union/approximation terms can never be embedded,
# so they must not emit `embeds` heritage edges. Keep the
# type link as a `references` (type_constraint) edge.
is_type_set = any(
c.type == "|" or c.type == "negated_type"
for c in elem.children
)
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 is_type_set:
add_edge(type_nid, tgt, "references",
elem.start_point[0] + 1, context="type_constraint")
elif 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[local_name] = raw
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[local_name] = raw
return
for child in node.children:
walk(child)
_scan_declarations(root)
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
is_bare_identifier: bool = False
package_receiver: str | None = None
import_path: str | None = None
if func_node:
if func_node.type == "identifier":
is_bare_identifier = True
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 not is_member_call:
package_receiver = receiver_name
import_path = go_imported_pkgs[receiver_name]
if field:
callee_name = _read_text(field, source)
if is_bare_identifier and callee_name in _GO_PREDECLARED_FUNCS:
# A bare `append(s, x)` is the builtin, never the same-named
# method a sibling file happens to declare. Skipping before both
# branches drops the in-file phantom edge and keeps the name out
# of raw_calls, so the cross-file pass cannot bind it either.
callee_name = None
if callee_name and callee_name not in _LANGUAGE_BUILTIN_GLOBALS:
# Never resolve an imported selector through a bare local name.
tgt_nid = None if import_path else 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,
"language": "go",
"receiver": package_receiver,
"import_path": import_path,
"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,
"go_imports": dict(go_imported_pkgs),
}
-240
View File
@@ -1,240 +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
from graphify.ids import normalize_id
_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
# A key that normalizes to nothing (a JSONC `"//"` comment key, say)
# would collapse `_make_id(stem, key)` down to the bare file-stem id,
# which is absolute-path-derived and leaks the scan path (#1899). Such
# keys carry no graph signal, so drop them.
if not normalize_id(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" and key == "extends":
# Only a genuine `extends` array (tsconfig 5.0+, eslint) is
# inheritance. This branch used to fire for *every* array under
# a tracked key, so `compilerOptions.lib: ["dom","esnext"]` and
# `exclude: ["node_modules",".next"]` each emitted an `extends`
# edge — array membership relabelled as inheritance. The string
# branch below already gates on `key == "extends"`; this matches
# it. Non-`extends` arrays keep their `contains` edge only.
# 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:
# Two defects fixed here, both from the #1764 shape:
#
# 1. The edge ran `key_nid -> dep_nid`, and both nodes carry
# the *same label* (the dependency name), so every
# dependency produced a visually self-referential
# `react --imports--> react` (22 of them on a mid-size
# Next.js repo). The self-loop guard in
# test_extract_json_import_and_extends_targets_are_real_nodes
# compares node ids, and these two ids differ, so the
# duplicate slipped past it. Sourcing the edge at the
# manifest yields `package.json --imports--> react`.
#
# 2. `_make_id(key)` minted a *bare* id, skipping the "ref"
# namespacing every other external reference in this file
# applies (J-4). A dependency named `utils`, `colors` or
# `types` could then be collapsed onto a same-named local
# module by build.py's alias index -- the #1638 failure
# mode reached through a different door.
dep_nid = _make_id("ref", key)
if dep_nid:
add_node(dep_nid, key, line, file_type="concept")
add_edge(file_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}
-289
View File
@@ -1,289 +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 _type_head_names(type_head) -> tuple[str | None, str | None]:
"""Return (type_name, supertype_name) from a Julia `type_head`.
A bare declaration (`Foo`) exposes an `identifier`; a subtyping
declaration (`Foo <: Bar`) wraps both names in a `binary_expression`.
Both the struct and abstract-type paths need this, so parse it once.
"""
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:
name = _read_text(identifiers[0], source)
super_name = _read_text(identifiers[-1], source) if len(identifiers) >= 2 else None
return name, super_name
return None, None
name_node = next((c for c in type_head.children if c.type == "identifier"), None)
return (_read_text(name_node, source) if name_node else None), None
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, super_name = _type_head_names(type_head)
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 is a bare `identifier` (`abstract type Foo end`) or a
# `binary_expression` for the subtyping form (`abstract type Foo <: Bar end`).
# The latter was dropped entirely — abstract types are the backbone of
# Julia's dispatch hierarchies, so an intermediate `Foo <: Bar` vanishing
# broke the inheritance chain and lost the type node itself.
type_head = next((c for c in node.children if c.type == "type_head"), None)
if type_head:
abs_name, super_name = _type_head_names(type_head)
if abs_name:
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)
if super_name:
add_edge(abs_nid, ensure_named_node(super_name, line),
"inherits", line, confidence="EXTRACTED")
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}
-509
View File
@@ -1,509 +0,0 @@
"""Markdown extractor. Moved verbatim from graphify/extract.py."""
from __future__ import annotations
import re
import os
import unicodedata
from pathlib import Path
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS
from graphify.extractors.base import _file_stem, _make_id
from graphify.security import sanitize_metadata
_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"}
# Inline code spans, single or double backtick delimited. Fenced blocks are
# skipped before this runs, so a span here is prose citing a symbol by name.
_MD_CODE_SPAN_RE = re.compile(r'(?<!`)(`+)(?!`)(.+?)(?<!`)\1(?!`)')
# The two mention grammars a code span can carry. A path-qualified mention
# (``src/pkg/mod.py::Widget::render``) names the defining file and a
# ``::``-separated symbol chain, exactly as pytest node ids and cite-lint
# citations do. A bare mention (``Widget``, ``render()``, ``pkg.Widget``) names
# a symbol with no file evidence, so it resolves only on a unique match; the
# dotted form keeps its qualifiers (``pkg``) as evidence the resolver checks.
_MD_PATH_MENTION_RE = re.compile(
r'^([A-Za-z0-9_./\-]+\.[A-Za-z0-9]+)::([A-Za-z_]\w*(?:::[A-Za-z_]\w*)*)(?:\(\))?$'
)
_MD_BARE_MENTION_RE = re.compile(
r'^(?:[A-Za-z_]\w*\.)*([A-Za-z_]\w*)(?:\(\))?$'
)
# A YAML frontmatter block is only frontmatter when the opening `---` is the
# very first line of the file. A `---` further down is a horizontal rule and
# must not be mistaken for one. Bounded so a file that opens a fence and never
# closes it cannot swallow the whole document.
_MD_FRONTMATTER_CLOSE = ("---", "...")
_MD_FRONTMATTER_MAX_LINES = 200
# Flat `key: value` fallback, used only when PyYAML is unavailable. PyYAML is
# not a declared dependency of graphify (see manifest_ingest._parse_apm for the
# same defensive-import pattern), so the extractor must degrade rather than
# fail.
_MD_FM_SCALAR_RE = re.compile(r'^([A-Za-z0-9_][A-Za-z0-9_\-. ]*):\s*(.*)$')
def _split_frontmatter(lines: list[str]) -> tuple[list[str], int]:
"""Split leading YAML frontmatter off *lines*.
Returns ``(frontmatter_lines, body_start_index)``. When the file has no
frontmatter — the common case — returns ``([], 0)`` and the caller parses
from line 0 exactly as before.
"""
if not lines or lines[0].strip() != "---":
return [], 0
limit = min(len(lines), _MD_FRONTMATTER_MAX_LINES + 1)
for i in range(1, limit):
if lines[i].strip() in _MD_FRONTMATTER_CLOSE:
return lines[1:i], i + 1
# Unterminated fence: treat the `---` as ordinary content, not frontmatter.
return [], 0
def _parse_frontmatter(fm_lines: list[str]) -> dict:
"""Parse frontmatter lines into a plain dict.
Values are passed through ``sanitize_metadata`` by the caller, so nested
dicts and lists survive (a review workflow's ``coherence_check:`` block,
Obsidian ``aliases:``) while staying bounded and HTML-safe.
"""
if not fm_lines:
return {}
text = "\n".join(fm_lines)
try:
import yaml
except ImportError:
return _parse_frontmatter_fallback(fm_lines)
try:
data = yaml.safe_load(text)
except Exception:
# Malformed YAML in one document must not fail the whole extraction.
return _parse_frontmatter_fallback(fm_lines)
return data if isinstance(data, dict) else {}
def _parse_frontmatter_fallback(fm_lines: list[str]) -> dict:
"""Flat `key: value` parser for when PyYAML is not installed.
Nested blocks and list items are skipped rather than guessed at; the keys
that matter for graph filtering (``type``, ``review_status``, ``title``)
are flat scalars in practice.
"""
out: dict = {}
for raw in fm_lines:
if not raw[:1].strip():
continue # indented -> belongs to a nested block, skip
m = _MD_FM_SCALAR_RE.match(raw.strip())
if not m:
continue
key, value = m.group(1).strip(), m.group(2).strip()
if not value:
continue # a bare `key:` opens a nested block
out[key] = value.strip('"\'')
return out
# Vault-wide wikilink fallback. Obsidian-style vaults resolve a [[wikilink]]
# by vault-global filename lookup, not relative to the linking file, so a note
# in a subfolder linking [[hub]] reaches a root-level hub.md. The lexical
# sibling resolution below is correct when the target exists beside the
# source; when it does not, the reference edge kept an id derived from a
# nonexistent path, matched no node, and silently dropped at build time — the
# same lost-edge failure #1376 fixed for hub docs, reintroduced for every
# cross-folder vault link. The fallback consults a per-scan-root index of
# document files and only fires when the lexically resolved path does not
# exist, so non-vault corpora and resolvable relative links are untouched.
#
# Keyed by resolved scan root. extract() clears it at the start of each run
# (beside _WORKSPACE_PACKAGE_CACHE) so a serial rerun in one process sees
# files created since the last run; parallel workers are fresh processes.
_MD_LINK_INDEX_CACHE: "dict[str, dict[str, list[tuple[int, str, Path]]]]" = {}
def _active_scan_root() -> "Path | None":
"""The scan root of the extraction in flight, or None outside extract().
_safe_extract_with_xaml_root sets this for every extraction despite its
XAML-era name; a direct extract_markdown() call has no root and the
fallback stays off.
"""
import graphify.extract as _extract
return getattr(_extract, "_XAML_ACTIVE_EXTRACT_ROOT", None)
def _nfc(s: str) -> str:
# Filesystems disagree on Unicode normalization (macOS decomposes, others
# do not); a link typed in NFC must still find a file listed in NFD.
return unicodedata.normalize("NFC", s)
def _build_link_index(root: Path) -> "dict[str, list[tuple[int, str, Path]]]":
"""Index every linkable document under *root* by NFC-normalized basename.
Each entry maps basename -> [(depth, root-relative posix path, absolute
path)]. Directories in detect._SKIP_DIRS and dot-directories are pruned —
the same corpus boundary the scanner draws, and Obsidian itself does not
index dot-folders.
"""
from graphify.detect import _SKIP_DIRS
index: dict[str, list[tuple[int, str, Path]]] = {}
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(
d for d in dirnames if not d.startswith(".") and d not in _SKIP_DIRS
)
for fname in filenames:
if Path(fname).suffix.lower() not in _MD_LINKABLE_EXTS:
continue
abs_path = Path(dirpath) / fname
rel = os.path.relpath(str(abs_path), str(root)).replace("\\", "/")
index.setdefault(_nfc(fname), []).append(
(rel.count("/"), _nfc(rel), abs_path)
)
return index
def _vault_lookup(target: str, root: Path) -> "Path | None":
"""Resolve *target* (a normalized wikilink path, `.md` already appended)
against the corpus under *root*, or None when nothing matches.
A bare name matches by basename; a path-qualified target
(``folder/name.md``) must match its full segment suffix. Ties break to the
shallowest match, then lexicographically — mirroring Obsidian, where a
root-level file wins a bare-link name collision — so resolution is
deterministic regardless of walk order.
"""
root_key = str(root)
index = _MD_LINK_INDEX_CACHE.get(root_key)
if index is None:
try:
index = _build_link_index(root)
except OSError:
index = {}
_MD_LINK_INDEX_CACHE[root_key] = index
parts = _nfc(target.replace("\\", "/")).split("/")
candidates = index.get(parts[-1])
if not candidates:
return None
suffix = "/".join(parts)
matches = [
c for c in candidates
if c[1] == suffix or c[1].endswith("/" + suffix)
]
if not matches:
return None
return min(matches)[2]
def _resolve_markdown_link(raw: str, source_dir: Path,
wikilink: bool = False) -> "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``.
With ``wikilink=True``, a target whose lexically resolved path does not
exist is retried as a vault-global lookup across the active scan root (see
_vault_lookup) — Obsidian's own resolution order for wikilinks. Inline and
reference-style links keep pure relative semantics: for them a missing
relative target is an authoring error, not an alternate link convention.
"""
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
resolved = Path(os.path.normpath(str(candidate)))
if wikilink and not Path(target).is_absolute():
try:
missing = not resolved.is_file()
except OSError:
missing = False
if missing:
scan_root = _active_scan_root()
if scan_root is not None:
hit = _vault_lookup(target, scan_root)
if hit is not None:
return Path(os.path.normpath(str(hit)))
return resolved
def _code_span_mention(span: str) -> "tuple[str | None, list[str]] | None":
"""Classify one inline code span as a symbol mention, or None.
Returns ``(path, names)``: ``path`` is the cited file for the
``path::Name`` form and None for a bare or dotted mention; ``names`` is the
symbol chain, outermost first, so ``pkg.sub.Widget`` yields
``["pkg", "sub", "Widget"]`` and the resolver can hold the match to that
evidence. A trailing ``()`` is dropped from the last name so ``render()``
and ``render`` cite the same symbol. Spans that read as a file
(``setup.py``, ``README.md``), a shell command, an expression or prose are
not mentions and yield None.
"""
text = span.strip()
if not text or " " in text:
return None
m = _MD_PATH_MENTION_RE.match(text)
if m:
return m.group(1), m.group(2).split("::")
m = _MD_BARE_MENTION_RE.match(text)
if not m:
return None
if "." in text:
# ``a.b.Name`` is a qualified symbol; ``setup.py`` and ``README.md``
# are files. A dotted span whose last segment is a code or document
# extension is the latter. Other file-like spans (``pyproject.toml``)
# classify as a mention and are rejected at resolution, where the
# qualifier ``pyproject`` matches no callable's file or owner.
if "." + m.group(1) in CODE_EXTENSIONS or "." + m.group(1) in DOC_EXTENSIONS:
return None
return None, text.rstrip("()").split(".")
return None, [m.group(1)]
def extract_markdown(path: Path) -> dict:
"""Extract structural nodes and edges from a Markdown file.
Produces nodes for:
- The file itself, tagged ``node_kind: "page"``, carrying any YAML
frontmatter under ``frontmatter``
- Each heading (# / ## / ### etc.), tagged ``node_kind: "heading"``
``node_kind`` exists because ``file_type`` cannot carry this distinction:
it is a closed enum (build.py rewrites anything outside
``code|document|paper|image|rationale|concept`` to ``"concept"``) and
``"document"`` on both endpoints is load-bearing for the twin-merge pass.
Without a separate field, headings — typically the large majority of nodes
in a docs-heavy corpus — cannot be filtered out by a consumer.
Produces edges for:
- file --contains--> heading
- parent heading --contains--> child heading (nesting by level)
- 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.
Inline code spans on heading and body lines (backtick-quoted ``Widget``,
``render()``, ``pkg.Widget`` or ``src/mod.py::Widget::render``) are
collected as ``raw_calls`` tagged ``language: "markdown"`` rather than
edges: the symbol they cite lives in another file, so the match is made
once every file is extracted and ids are final, by the
``markdown_mentions`` language resolver (see
``graphify.markdown_resolution``). The dotted form travels with its
qualifiers, which the resolver checks against the match's owners and
file path. That pass emits
heading --references--> code symbol (page --references--> symbol for a
mention above the first heading): EXTRACTED for the path-qualified form,
INFERRED for a bare name that matches exactly one code symbol. The shared
cross-file call pass skips these raw_calls, so a mention never becomes a
``calls`` edge.
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).
Leading YAML frontmatter is parsed onto the page node and excluded from
heading detection (a `#` there is a YAML comment). Links inside it are
still followed: review workflows keep wikilinks in frontmatter and those
are genuine references.
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] = []
raw_calls: list[dict] = []
seen_ids: set[str] = set()
seen_mentions: set[tuple[str, "str | None", tuple[str, ...]]] = set()
def add_mention(caller_nid: str, span: str, line: int) -> None:
mention = _code_span_mention(span)
if mention is None:
return
cited_path, names = mention
key = (caller_nid, cited_path, tuple(names))
if key in seen_mentions:
return
seen_mentions.add(key)
raw_call = {
"caller_nid": caller_nid,
"callee": names[-1],
"is_member_call": False,
"language": "markdown",
"context": span.strip(),
"source_file": str_path,
"source_location": f"L{line}",
}
if cited_path is not None:
raw_call["path"] = cited_path
if len(names) > 1:
raw_call["qualifiers"] = names[:-1]
raw_calls.append(raw_call)
def add_node(nid: str, label: str, line: int, file_type: str = "document",
node_kind: str = "heading", extra: "dict | None" = None) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
node = {"id": nid, "label": label, "file_type": file_type,
"node_kind": node_kind,
"source_file": str_path, "source_location": f"L{line}"}
if extra:
node.update(extra)
nodes.append(node)
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0,
target_file: "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 target_file is not None:
edge["target_file"] = target_file
edges.append(edge)
lines = source.splitlines()
fm_lines, body_start = _split_frontmatter(lines)
frontmatter = sanitize_metadata(_parse_frontmatter(fm_lines))
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1, node_kind="page",
extra={"frontmatter": frontmatter} if frontmatter else None)
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, wikilink: bool = False) -> None:
resolved = _resolve_markdown_link(raw, source_dir, wikilink=wikilink)
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)
# Stamp the resolved target file (mirroring the JS/Python import
# stamps, #1814/#2213) so the #2169 remap pass can canonicalize this
# edge's target on an incremental run where the linked doc is not in
# the batch — without it the target keeps an absolute-path-derived id
# that matches no node in the merged graph and the md->md reference
# silently drops (#2211). Existence-gated: a link to a nonexistent
# doc must stay dangling, exactly as before. The stamp is transient
# and popped before graph.json ships.
target_file = None
try:
if resolved.is_file():
target_file = str(resolved)
except OSError:
pass
add_edge(file_nid, tgt_nid, "references", line, target_file=target_file)
# Track heading stack for nesting: [(level, nid), ...]
heading_stack: list[tuple[int, str]] = []
in_code_block = False
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, wikilink=True)
ref_def = _MD_REF_DEF_RE.match(line_text)
if ref_def:
add_link(ref_def.group(1), line_num)
# Inside the frontmatter block a leading `#` is a YAML comment, not an
# H1. Links above are still scanned there on purpose: review workflows
# put wikilinks in frontmatter (e.g. a `consulted:` list), and those are
# real references. Only heading detection is suppressed.
if line_num_0 < body_start:
continue
# 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))
# A code span in the heading itself is that heading's mention.
for m in _MD_CODE_SPAN_RE.finditer(title):
add_mention(h_nid, m.group(2), line_num)
continue
# Body prose: a code span cites a symbol on behalf of the enclosing
# heading (the page when the text precedes the first heading).
owner = heading_stack[-1][1] if heading_stack else file_nid
for m in _MD_CODE_SPAN_RE.finditer(line_text):
add_mention(owner, m.group(2), line_num)
return {"nodes": nodes, "edges": edges, "raw_calls": raw_calls,
"input_tokens": 0, "output_tokens": 0}
-131
View File
@@ -1,131 +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", ".cjs", ".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
# Optional symbol name sanitizer for node ID generation (e.g. Ruby suffixed methods)
sanitize_symbol_name_fn: Callable[[str], str] | 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
# `export type { X } from ...`: erased at compile time, so the re-export
# edge it produces is stamped type_only and excluded from Import Cycles
# (#3123). The fact itself still participates in symbol resolution - a
# type import resolved through a type-only barrel is itself type-only.
type_only: bool = False
@dataclass(frozen=True)
class _StarExportFact:
file_path: Path
target_path: Path
line: int
type_only: bool = False
@dataclass(frozen=True)
class _NamespaceExportFact:
file_path: Path
exported_name: str
target_path: Path
line: int
type_only: bool = False
@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, local_name) -- local_name
# is the binding introduced in the importing file: the alias when `from pkg
# import submod as alias` is used, otherwise the submodule's own name (#2082).
module_imports: list[tuple[Path, Path, int, str]] = field(default_factory=list)
-566
View File
@@ -1,566 +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
import re
# A category stem splits only when both halves look like plain ObjC identifiers, so
# `C++Bridge.h` and `Foo+.h` are left intact.
_OBJC_STEM_PART = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
def _objc_category_base_stem(stem: str) -> str:
"""Strip an ObjC category/extension suffix from a file stem (``Foo+Cat`` -> ``Foo``).
A category (``@interface Foo (Cat)``) or class extension (``@interface Foo ()``)
declares members of an EXISTING class, so its class node must key to the same id
as ``Foo.h``'s ``@interface Foo`` instead of minting a second class node (#1556).
Only the final path segment is considered, and only a well-formed
``Name+Suffix`` pair is split.
Mirrors ``_decldef_class_stem``, which already compares sibling header/impl files
by the stem before ``+``.
"""
head, sep, tail = stem.rpartition("/")
base, plus, suffix = tail.partition("+")
if not plus or not _OBJC_STEM_PART.fullmatch(base) or not _OBJC_STEM_PART.fullmatch(suffix):
return stem
return f"{head}{sep}{base}"
def _objc_is_category(node) -> bool:
"""True for ``@interface/@implementation Foo (Cat)`` and ``Foo ()``.
The grammar emits the parentheses as anonymous children only for a category or
class extension; a generic class (``@interface Box<T>``) uses
``parameterized_arguments`` instead, so it is not matched.
"""
return any(c.type == "(" for c in node.children)
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] = {}
# #1556: per-CLASS `field -> ClassName` tables from `@property Bar *bar;` and
# ivar `Bar *_bar;` declarations, keyed by the class nid the .h/.m pair share
# (preserved by _merge_decl_def_classes), so the cross-file resolver can type a
# `[self.bar doIt]` / `[_bar doIt]` receiver. A conflicting redeclaration of the
# same (class, field) tombstones the entry (None) — drop, don't guess.
objc_field_types: dict[str, dict[str, str | 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}"})
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 _field_decl_entry(sd) -> tuple[str, str] | None:
"""``(field, TypeName)`` from a property/ivar ``struct_declaration``, else None.
Precision gates (#1556): the type must be a BARE capitalized
``type_identifier`` DIRECTLY under the struct_declaration — a
``generic_specifier`` (``NSArray<Bar *>``) or ``typedefed_specifier``
(``id<P>``) wraps its type_identifier, so both are naturally excluded and
never type a receiver — and there must be exactly one ``struct_declarator``
whose name unwraps via the C++ declarator unwrapper (identical grammar).
"""
type_ids = [s for s in sd.children if s.type == "type_identifier"]
declarators = [s for s in sd.children if s.type == "struct_declarator"]
if len(type_ids) != 1 or len(declarators) != 1:
return None
type_name = _read(type_ids[0]).strip()
if not type_name or not type_name[:1].isupper():
return None
# struct_declarator wraps ONE pointer_declarator (`*bar`) or identifier
# (`bar`); anything else (bitfields, arrays) has more children -> bail.
inner = declarators[0].children
if len(inner) != 1:
return None
field = _cpp_declarator_name(inner[0], source)
if not field:
return None
return field, type_name
def _record_field_type(cls_nid: str, field: str, type_name: str) -> None:
table = objc_field_types.setdefault(cls_nid, {})
if field in table:
if table[field] != type_name:
table[field] = None # conflicting redeclaration -> drop, don't guess
else:
table[field] = type_name
def _collect_instance_variables(ivars_node, cls_nid: str) -> None:
"""Record field types from an ``instance_variables`` block (``{ Bar *_b; }``)
under an @interface or @implementation. No nodes/edges are emitted here;
the table only feeds receiver typing in the cross-file resolver (#1556).
"""
for iv in ivars_node.children:
if iv.type != "instance_variable":
continue
for sd in iv.children:
if sd.type == "struct_declaration":
entry = _field_decl_entry(sd)
if entry is not None:
_record_field_type(cls_nid, *entry)
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])
# A category / class extension extends an existing class, so key its
# class node off the BASE stem (`Foo+Cat.h` -> `Foo`). Without this,
# `Foo+Cat.h` minted a SECOND node labelled `Foo`, which made every
# `[Foo ...]` receiver ambiguous and tripped the resolver's
# single-definition god-node guard — destroying edges the same corpus
# produced fine when the members lived in `Foo.h` (#1556).
cls_stem = _objc_category_base_stem(stem) if _objc_is_category(node) else stem
cls_nid = _make_id(cls_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))
# #1556: a bare capitalized property type also types the
# `[self.field msg]` receiver in the cross-file resolver.
entry = _field_decl_entry(sub)
if entry is not None:
_record_field_type(cls_nid, *entry)
elif child.type == "instance_variables":
_collect_instance_variables(child, cls_nid)
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_stem = _objc_category_base_stem(stem) if _objc_is_category(node) else stem
impl_nid = _make_id(impl_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 == "instance_variables":
_collect_instance_variables(child, impl_nid)
elif 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 recv is not None and recv.type == "field_expression":
# `[self.bar doIt]`: capture ONLY the exact `self.<field>`
# shape and stamp the BARE field name, typed via the class's
# property/ivar table. Anything else (`obj.prop`, chains,
# `Foo.shared`) stays dropped: passing the dotted text
# through would let a capitalized `Foo.shared` enter the
# explicit-class arm, where _key strips the dot and collides
# with a real class `FooShared` — a fabricated edge (#1556).
kids = recv.children
if (len(kids) == 3 and kids[0].type == "identifier"
and _read(kids[0]) == "self" and kids[1].type == "."
and kids[2].type == "field_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(kids[2]),
"receiver_kind": "self_field",
"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}
# Drop tombstoned (conflicting) entries and empty tables before export.
field_tables = {
cls: {f: t for f, t in tbl.items() if t}
for cls, tbl in objc_field_types.items()
}
field_tables = {cls: tbl for cls, tbl in field_tables.items() if tbl}
if field_tables:
result["objc_field_types"] = {"path": str_path, "tables": field_tables}
return result
-289
View File
@@ -1,289 +0,0 @@
"""OCaml extractor (own module, optional tree-sitter-ocaml dependency).
Handles implementation files (.ml, `language_ocaml`) and interface files
(.mli, `language_ocaml_interface`). Interfaces have no expression bodies, so
they contribute definitions and `open` imports but no `calls` edges.
"""
from __future__ import annotations
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id, _read_text
def extract_ocaml(path: Path) -> dict:
"""Extract modules, values, functions, types, variant constructors, `open`
imports, and (for .ml) function calls from an OCaml source file."""
try:
import tree_sitter_ocaml as tsocaml
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-ocaml not installed"}
try:
if path.suffix == ".mli":
language = Language(tsocaml.language_ocaml_interface())
else:
language = Language(tsocaml.language_ocaml())
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()
# Same-file definition table for call resolution. A name defined more than
# once in the file is marked ambiguous and never resolved locally.
local_defs: dict[str, str] = {}
ambiguous: set[str] = set()
# Names of modules DEFINED in this file. Used to decide whether a qualified
# call `M.f` may bind to a local `f`: if `M` is not a local module it is an
# external library (e.g. `Reg_spec.create`), so binding to a same-named local
# `f` would be a false edge (and a self-loop when the caller is that `f`).
local_modules: set[str] = set()
# (caller_nid, callee_name, qualifier_root_module_or_None, full_path_text,
# line) recorded on pass 1, resolved on pass 2 so that forward references
# (e.g. `let rec ... and ...`) resolve correctly.
call_sites: list[tuple[str, str, str | None, str, int]] = []
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) -> 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)
def ref_stub(name: str) -> str:
"""Mint a SOURCELESS stub for a cross-file reference target (an `open`ed
module or a call to a name not defined in this file). The corpus-level
rewire collapses it onto the unique real definition of that name;
external names (Stdlib, Core, ...) dangle and are pruned. A *sourced*
stub here would bake this file's path into the id and block the rewire
(the #1402 phantom-duplicate bug)."""
nid = _make_id(name)
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": name,
"file_type": "code",
"source_file": "",
"source_location": "",
"origin_file": str_path,
})
return nid
def line_of(node) -> int:
return node.start_point[0] + 1
def named_child_text(node, child_type: str) -> str | None:
for child in node.children:
if child.type == child_type:
return _read_text(child, source)
return None
def last_name(path_node) -> str | None:
"""Final component of a *_path node: `Geo.area` -> `area`,
`Stdlib.List` -> `List`. The qualifier is nested under a child
`module_path`, so the final name is always a *direct* child of the path
node -- a deep search would wrongly return the module qualifier."""
found: str | None = None
for n in path_node.children:
if n.type in ("value_name", "module_name", "constructor_name"):
found = _read_text(n, source)
return found
def path_root_module(path_node) -> str | None:
"""Leftmost (outermost) module segment qualifying a *_path node:
`Reg_spec.create` -> `Reg_spec`, `Stdlib.List.map` -> `Stdlib`. Returns
None when the path is unqualified (`create`), which has no child
module_path."""
mp = next((c for c in path_node.children if c.type == "module_path"), None)
if mp is None:
return None
node = mp
while True:
inner = next((c for c in node.children if c.type == "module_path"), None)
if inner is None:
break
node = inner
mn = next((c for c in node.children if c.type == "module_name"), None)
return _read_text(mn, source) if mn is not None else None
def register_def(name: str, nid: str) -> None:
if name in ambiguous:
return
if name in local_defs and local_defs[name] != nid:
ambiguous.add(name)
local_defs.pop(name, None)
return
local_defs[name] = nid
def emit_type(binding, container_nid: str) -> None:
type_name = named_child_text(binding, "type_constructor")
if not type_name:
return
line = line_of(binding)
nid = _make_id(stem, type_name)
add_node(nid, type_name, line)
add_edge(container_nid, nid, "defines" if container_nid == file_nid else "contains", line)
register_def(type_name, nid)
# Variant constructors: variant_declaration -> constructor_declaration -> constructor_name
for vd in binding.children:
if vd.type != "variant_declaration":
continue
for cd in vd.children:
if cd.type != "constructor_declaration":
continue
cname = named_child_text(cd, "constructor_name")
if not cname:
continue
cnid = _make_id(stem, type_name, cname)
add_node(cnid, cname, line_of(cd))
add_edge(nid, cnid, "contains", line_of(cd))
def walk(node, container_nid: str, enclosing_value: str) -> None:
t = node.type
if t == "open_module":
mp = next((c for c in node.children if c.type == "module_path"), None)
name = last_name(mp) if mp is not None else None
if name:
add_edge(container_nid, ref_stub(name), "imports_from", line_of(node),
confidence="INFERRED")
return
if t == "module_definition":
binding = next((c for c in node.children if c.type == "module_binding"), None)
if binding is not None:
mname = named_child_text(binding, "module_name")
if mname:
line = line_of(node)
mnid = _make_id(stem, mname)
add_node(mnid, mname, line)
add_edge(container_nid, mnid,
"defines" if container_nid == file_nid else "contains", line)
register_def(mname, mnid)
local_modules.add(mname)
for child in binding.children:
walk(child, mnid, enclosing_value)
return
if t == "module_type_definition": # .mli
mname = named_child_text(node, "module_type_name")
if mname:
line = line_of(node)
mnid = _make_id(stem, mname)
add_node(mnid, mname, line)
add_edge(container_nid, mnid,
"defines" if container_nid == file_nid else "contains", line)
register_def(mname, mnid)
local_modules.add(mname)
for child in node.children:
walk(child, mnid, enclosing_value)
return
if t == "value_definition": # .ml
# Only structure/top-level bindings are real definitions. A local
# `let x = e in body` is also a value_definition, but nested under a
# let_expression; it must NOT mint a node or steal call attribution
# from the enclosing named function.
is_toplevel = node.parent is not None and node.parent.type in (
"compilation_unit", "structure")
for lb in node.children:
if lb.type != "let_binding":
continue
vname = named_child_text(lb, "value_name")
new_scope = enclosing_value
if vname and is_toplevel:
line = line_of(lb)
nid = _make_id(stem, vname)
add_node(nid, vname, line)
add_edge(container_nid, nid,
"defines" if container_nid == file_nid else "contains", line)
register_def(vname, nid)
new_scope = nid
# Descend into the body (unit/pattern/local bindings keep the
# outer scope) to collect nested definitions and call sites.
for child in lb.children:
walk(child, container_nid, new_scope)
return
if t == "value_specification": # .mli
vname = named_child_text(node, "value_name")
if vname:
line = line_of(node)
nid = _make_id(stem, vname)
add_node(nid, vname, line)
add_edge(container_nid, nid,
"defines" if container_nid == file_nid else "contains", line)
register_def(vname, nid)
return
if t == "type_definition":
for binding in node.children:
if binding.type == "type_binding":
emit_type(binding, container_nid)
return
if t == "application_expression":
fn = node.named_children[0] if node.named_children else None
if fn is not None and fn.type == "value_path":
callee = last_name(fn)
if callee:
caller = enclosing_value if enclosing_value else file_nid
call_sites.append((caller, callee, path_root_module(fn),
_read_text(fn, source), line_of(node)))
# Fall through: arguments may contain further applications/definitions.
for child in node.children:
walk(child, container_nid, enclosing_value)
walk(root, file_nid, "")
for caller, callee, qualifier, full_path, line in call_sites:
# A qualified call `M.f` where `M` is NOT a module defined in this file
# is an external-library call (e.g. `Reg_spec.create`). Binding it to a
# same-named local `f` would be a false edge (and a `create -> create`
# self-loop when the caller is that local `f`), so keep it distinct: a
# stub keyed by the FULL qualified name (`Reg_spec.create`) never
# collapses onto the local `f` in the corpus rewire. Unqualified calls,
# and qualified calls into a locally-defined module, still resolve to a
# local definition; a bare-name stub still allows the cross-file rewire
# to collapse `Geo.area` onto another file's `area` (#hardcaml).
if qualifier is not None and qualifier not in local_modules:
if callee in local_defs:
add_edge(caller, ref_stub(full_path), "calls", line, confidence="INFERRED")
else:
add_edge(caller, ref_stub(callee), "calls", line, confidence="INFERRED")
elif callee in local_defs:
add_edge(caller, local_defs[callee], "calls", line)
else:
add_edge(caller, ref_stub(callee), "calls", line, confidence="INFERRED")
return {"nodes": nodes, "edges": edges}
-688
View File
@@ -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,
}
-196
View File
@@ -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}
-522
View File
@@ -1,522 +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 == "enum_statement":
# PowerShell enums are first-class type definitions (referenced via
# `[Color]` type literals) but were not extracted at all, so those
# references resolved to a sourceless phantom stub instead of the real
# in-file definition — and the enum's members were lost entirely.
name_node = next((c for c in node.children if c.type == "simple_name"), None)
if name_node:
enum_name = _read_text(name_node, source)
line = node.start_point[0] + 1
enum_nid = _make_id(stem, enum_name)
add_node(enum_nid, enum_name, line)
add_edge(file_nid, enum_nid, "contains", line)
for member in node.children:
if member.type != "enum_member":
continue
mname_node = next(
(c for c in member.children if c.type == "simple_name"), None)
if mname_node is None:
continue
member_name = _read_text(mname_node, source)
m_line = member.start_point[0] + 1
member_nid = _make_id(enum_nid, member_name)
add_node(member_nid, member_name, m_line)
add_edge(enum_nid, member_nid, "contains", m_line)
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": []}
-192
View File
@@ -1,192 +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
from graphify.security import sanitize_metadata
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+(.+)', line)
if m:
raw_using = m.group(1).strip().rstrip(";")
using_kind = "namespace"
alias = None
target_fqn = raw_using
if raw_using.startswith("static "):
using_kind = "static"
target_fqn = raw_using[len("static "):].strip()
elif "=" in raw_using:
lhs, rhs = raw_using.split("=", 1)
using_kind = "alias"
alias = lhs.strip()
target_fqn = rhs.strip()
if target_fqn:
tgt_nid = _make_id(target_fqn)
if tgt_nid and tgt_nid not in seen_ids:
seen_ids.add(tgt_nid)
nodes.append({"id": tgt_nid, "label": target_fqn,
"file_type": "code", "source_file": str_path,
"source_location": f"L{i}"})
md = {
"using_kind": using_kind,
"target_fqn": target_fqn,
"scope_kind": "file",
"scope_id": None,
}
if alias:
md["alias"] = alias
edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports",
"context": "import",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{i}",
"weight": 1.0,
"metadata": sanitize_metadata({k: v for k, v in md.items() if v is not None}),
})
continue
m = re.match(r'@inject\s+([\w.<>\[\]]+)\s+(\w+)', line)
if m:
raw_type = m.group(1).strip()
base_type = raw_type.split("<", 1)[0].strip()
qualified = "." in base_type
if qualified:
prefix, _, ref_token = base_type.rpartition(".")
else:
prefix = ""
ref_token = base_type
if ref_token:
tgt_nid = _make_id(ref_token)
if tgt_nid and tgt_nid not in seen_ids:
seen_ids.add(tgt_nid)
nodes.append({
"id": tgt_nid,
"label": ref_token,
"file_type": "code",
"source_file": "",
"source_location": "",
"origin_file": str_path,
})
md = {"ref_token": ref_token}
if qualified:
md["qualified"] = True
if prefix:
md["ref_qualifier"] = prefix
edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "references",
"context": "field",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{i}",
"weight": 1.0,
"metadata": sanitize_metadata(md),
})
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
-296
View File
@@ -1,296 +0,0 @@
"""Robot Framework extractor for .robot/.resource files (issue #3192)."""
from __future__ import annotations
import os
import re
from pathlib import Path
from graphify.extractors.base import _file_stem, _make_id
# Robot Framework standard libraries - imports of these are noise (like the
# Python built-ins in _LANGUAGE_BUILTIN_GLOBALS), so only third-party
# libraries get stub nodes.
_ROBOT_STDLIBS = frozenset({
"BuiltIn", "Collections", "DateTime", "Dialogs", "Easter", "OperatingSystem",
"Process", "Remote", "Reserved", "Screenshot", "String", "Telnet", "XML",
})
_ROBOT_VAR_RE = re.compile(r"\$\{([^}]*)\}")
def _resolve_robot_import(raw: str, source_path: Path) -> Path | None:
"""Resolve a Settings-section import path relative to the importing file.
Preserves the relative/absolute form of source_path so the target ID
matches the ID the imported file's own extraction produces (same approach
as the JS relative-import resolver). Robot matches variable names case-,
space-, and underscore-insensitively, so ``${curdir}`` and ``${Cur_Dir}``
resolve like ``${CURDIR}``. Returns None when the path holds any other
(unresolvable) ${VARIABLE} or %{ENV_VAR}.
"""
s = raw.strip()
# ${CURDIR}/${EXECDIR} already anchor the path - substituting and then
# re-joining below would prefix source_path.parent twice when the scan
# uses relative paths, so track anchoring explicitly.
anchored = False
parts = []
last = 0
for m in _ROBOT_VAR_RE.finditer(s):
name = m.group(1).replace(" ", "").replace("_", "").lower()
if name == "/":
repl = "/"
elif name == "curdir":
repl = str(source_path.parent)
anchored = True
elif name == "execdir":
# ${EXECDIR} is the directory Robot was launched from - statically
# knowable only for a relative scan, where "." is the scan root
# and matches how relative file-node IDs are built. For an
# absolute source path the resolved ID could never match a node,
# so emit nothing rather than a guaranteed-dangling edge.
if source_path.is_absolute():
return None
repl = "."
anchored = True
else:
return None
parts.append(s[last:m.start()])
parts.append(repl)
last = m.end()
parts.append(s[last:])
s = "".join(parts)
if "%{" in s:
return None
p = Path(s)
if not anchored and not p.is_absolute():
p = source_path.parent / p
# normpath unconditionally so ../ segments collapse and the ID matches
# the imported file's own node ID (absolute paths included)
return Path(os.path.normpath(p))
# Robot resolves BDD-style calls (Given/When/Then/And/But <keyword>) by trying
# the full name first, then the name with one prefix stripped. English prefixes
# only - Robot's localized BDD prefixes are out of scope here.
_BDD_PREFIXES = ("given ", "when ", "then ", "and ", "but ")
def _kw_id(name: str) -> str:
"""Node ID for a keyword, normalized the way Robot Framework matches
keyword names: case-, space-, and underscore-insensitive. Stripping
spaces/underscores before _make_id means ``Open Session``,
``open_session``, and ``OpenSession`` all share one node ID, exactly as
Robot resolves them to one keyword."""
return _make_id(name.replace(" ", "").replace("_", ""))
def extract_robot(path: Path) -> dict:
"""Extract suites, test cases, user keywords, imports, and keyword calls
from Robot Framework .robot/.resource files via the official robot.api
parser (no maintained tree-sitter grammar exists for Robot Framework).
Nodes: the suite/resource file, its test cases, and its user keywords.
Edges: `contains` (file -> test case / keyword), `imports` (file -> the
Resource/Library/Variables files it pulls in, resolved onto the imported
file's own node; non-stdlib named libraries like SeleniumLibrary get stub
nodes so suites sharing a library cluster together), and `calls`
(test case / keyword / suite fixture -> the keyword it invokes).
Keyword nodes are keyed by bare keyword name (not stem-qualified),
normalized the way Robot matches keywords (case-, space-, and
underscore-insensitive, see _kw_id): Robot resolves keywords globally by
name across imported resources, so bare IDs make cross-file call edges
land on the defining node without a separate resolution pass. Two files
defining the same keyword name deliberately merge into one node - that
mirrors Robot's own single global namespace (where such duplicates are
ambiguous). Test case nodes stay stem-qualified because test names repeat
across suites. Calls to keywords never defined in the corpus (e.g.
BuiltIn's Log) are dropped by build_from_json like any external reference.
"""
try:
from robot.api import get_model, get_resource_model
from robot.api.parsing import ModelVisitor
except ImportError:
return {"nodes": [], "edges": [],
"error": "robotframework not installed. Run: pip install robotframework"}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
seen_edges: set[tuple] = 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", context: str | None = None) -> None:
if not src or not tgt or src == tgt:
return
key = (src, tgt, relation)
if key in seen_edges:
return
seen_edges.add(key)
edge = {
"source": src,
"target": tgt,
"relation": relation,
"confidence": confidence,
"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)
try:
if path.suffix.lower() == ".resource":
model = get_resource_model(str_path)
else:
model = get_model(str_path)
except Exception as e:
return {"nodes": nodes, "edges": edges, "error": str(e)}
def kw_targets(name: str) -> list:
# "SSHLibrary.Open Connection" -> keyword part only; explicit
# library/resource prefixes are common, dots inside keyword names are not.
name = name.rsplit(".", 1)[-1].strip()
targets = [_kw_id(name)]
# BDD calls: emit an edge for BOTH the full and the prefix-stripped
# candidate, mirroring Robot's try-full-then-stripped resolution.
# Whichever keyword exists receives the edge; the other candidate
# dangles and is dropped by the graph builder.
low = name.lower()
for prefix in _BDD_PREFIXES:
if low.startswith(prefix) and len(name) > len(prefix):
targets.append(_kw_id(name[len(prefix):]))
break
return targets
def add_call_edges(src: str, name: str, line: int) -> None:
for tgt in kw_targets(name):
add_edge(src, tgt, "calls", line, context="call")
class _RobotVisitor(ModelVisitor):
def __init__(self):
self.scope_nid = file_nid
# Settings-section imports
def visit_ResourceImport(self, node):
raw = (node.name or "").strip()
if not raw:
return
target = _resolve_robot_import(raw, path)
if target is not None:
add_edge(file_nid, _make_id(str(target)), "imports", node.lineno)
def visit_LibraryImport(self, node):
raw = (node.name or "").strip()
if not raw:
return
if raw.endswith(".py") or "/" in raw or "\\" in raw:
# Path-form library import -> edge onto the Python file's node
target = _resolve_robot_import(raw, path)
if target is not None:
add_edge(file_nid, _make_id(str(target)), "imports", node.lineno)
elif raw not in _ROBOT_STDLIBS:
# External library (SeleniumLibrary, RequestsLibrary, ...) -
# stub node so suites sharing a library cluster together.
# Namespace the id so a user keyword that happens to share the
# library's name cannot collide with this stub (the label keeps
# the raw library name for display).
nid = _make_id("robot_library", raw)
add_node(nid, raw, node.lineno)
add_edge(file_nid, nid, "imports", node.lineno)
def visit_VariablesImport(self, node):
raw = (node.name or "").strip()
if not raw:
return
target = _resolve_robot_import(raw, path)
if target is not None:
add_edge(file_nid, _make_id(str(target)), "imports", node.lineno)
# Suite-level fixtures (file scope)
def visit_SuiteSetup(self, node):
if node.name:
add_call_edges(file_nid, node.name, node.lineno)
def visit_SuiteTeardown(self, node):
if node.name:
add_call_edges(file_nid, node.name, node.lineno)
def visit_TestSetup(self, node):
if node.name:
add_call_edges(file_nid, node.name, node.lineno)
def visit_TestTeardown(self, node):
if node.name:
add_call_edges(file_nid, node.name, node.lineno)
def visit_TestTemplate(self, node):
# Template statements carry the keyword in .value, not .name
if node.value:
add_call_edges(file_nid, node.value, node.lineno)
# Definitions
def visit_TestCase(self, node):
if not node.name:
return
tc_nid = _make_id(stem, node.name)
add_node(tc_nid, node.name, node.lineno)
add_edge(file_nid, tc_nid, "contains", node.lineno)
prev, self.scope_nid = self.scope_nid, tc_nid
self.generic_visit(node)
self.scope_nid = prev
def visit_Keyword(self, node):
if not node.name:
return
kw_nid = _kw_id(node.name)
add_node(kw_nid, node.name, node.lineno)
add_edge(file_nid, kw_nid, "contains", node.lineno)
prev, self.scope_nid = self.scope_nid, kw_nid
self.generic_visit(node)
self.scope_nid = prev
# Calls (current test/keyword scope, file scope for suite fixtures)
def visit_KeywordCall(self, node):
if node.keyword:
add_call_edges(self.scope_nid, node.keyword, node.lineno)
self.generic_visit(node)
def visit_Setup(self, node):
if node.name:
add_call_edges(self.scope_nid, node.name, node.lineno)
def visit_Teardown(self, node):
if node.name:
add_call_edges(self.scope_nid, node.name, node.lineno)
def visit_Template(self, node):
# Template statements carry the keyword in .value, not .name
if node.value:
add_call_edges(self.scope_nid, node.value, node.lineno)
try:
_RobotVisitor().visit(model)
except Exception as e:
return {"nodes": nodes, "edges": edges, "error": str(e)}
return {"nodes": nodes, "edges": edges}
-482
View File
@@ -1,482 +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, statics/consts, 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, str | 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}",
})
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, parent_impl_type: 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, parent_impl_type))
return
if t == "function_signature_item":
# `fn greet(&self) -> String;` — a trait method with no body. This node type
# had no branch at all, so a trait's required methods were unreachable: the
# only method nodes in a graph came from impl blocks, and a trait with no
# implementor in the corpus contributed none. Mirrors function_item, minus
# the body walk (there is no body).
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)
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)
if t == "trait_item":
# The methods a trait declares are its contract, and they were not
# reached: this branch returns below, so nothing walked the body.
# Descend the same way impl_item does, attributing each method to
# the trait node — so `explain <Trait>` can list what an
# implementor must provide.
body = node.child_by_field_name("body")
if body:
for child in body.children:
walk(child, parent_impl_nid=item_nid)
return
if t in ("static_item", "const_item"):
# `static NAME: T = …;` / `const NAME: T = …;` at module level, or an
# associated const inside an impl. Neither node type had a branch, so a
# constant reached the graph only through files that referenced it,
# never from the Rust that defines it (#3471).
name_node = node.child_by_field_name("name")
if name_node:
item_name = _read_text(name_node, source)
line = node.start_point[0] + 1
if parent_impl_nid:
item_nid = _make_id(parent_impl_nid, item_name)
add_node(item_nid, f".{item_name}", line)
add_edge(parent_impl_nid, item_nid, "contains", line)
else:
item_nid = _make_id(stem, item_name)
add_node(item_nid, item_name, line)
add_edge(file_nid, item_nid, "contains", line)
type_node = node.child_by_field_name("type")
if type_node is not None:
refs: list[tuple[str, str]] = []
_rust_collect_type_refs(type_node, source, False, refs)
for ref_name, role in refs:
tgt = ensure_named_node(ref_name, line)
if tgt == item_nid:
continue
ctx = "generic_arg" if role == "generic_arg" else "field"
add_edge(item_nid, tgt, "references", line, context=ctx)
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
impl_type_bare: 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)
# Bare name (generics stripped) for typing a `self.` receiver
# inside this block's methods (#2234) — `impl Foo<T>` types
# `self` as `Foo`, not the literal `Foo<T>` text.
impl_type_bare = type_name.split("<")[0].strip()
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, parent_impl_type=impl_type_bare)
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, self_type: str | None = None) -> 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
is_self_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)
receiver = func_node.child_by_field_name("value")
if receiver is not None and receiver.type == "self":
is_self_call = True
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:
rc_entry = {
"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}",
}
if is_self_call and self_type:
rc_entry["rust_self_type"] = self_type
raw_calls.append(rc_entry)
for child in node.children:
walk_calls(child, caller_nid, self_type)
for caller_nid, body_node, impl_type in function_bodies:
walk_calls(body_node, caller_nid, impl_type)
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}
-92
View File
@@ -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}
-720
View File
@@ -1,720 +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
# Recovers CREATE FUNCTION/PROCEDURE statements the grammar could not parse
# structurally. Used by BOTH recovery sites — the walk-time ERROR-node scan and
# the whole-file has_error fallback (#2180). They MUST share one pattern: when
# they disagreed, the same statement produced two nodes with different names
# (the ERROR scan captured `dbo.[usp_Mixed]`, the fallback stopped at `dbo`,
# and _add_node's id-dedupe never fired because the ids differed).
#
# Each name part is a bare identifier, a double-quoted (delimited) one, or a
# T-SQL bracket-delimited one, so CREATE OR REPLACE FUNCTION "public"."fn"(...)
# and CREATE PROCEDURE [dbo].[usp_Load] ... are both recovered. A bare [\w$.]+
# stops dead at the leading delimiter, which silently dropped every quoted
# PL/pgSQL routine (#2180) and every bracket-named T-SQL procedure. T-SQL's
# AS BEGIN...END body idiom always lands in recovery — the grammar has no
# create_procedure parse for it — and T-SQL spells re-creation CREATE OR ALTER
# (it has no OR REPLACE), so accept that form too, mirroring fb_proc_or_trigger.
# Inside a bracket-delimited part, a literal ] is escaped by doubling
# ([a]]b] names the identifier a]b), so consume ]] before treating a
# lone ] as the closing delimiter — stopping at the first ] truncated
# the name and minted a phantom that could collide with a real [a].
# PROC is T-SQL's official shorthand for PROCEDURE and equally common in the
# wild; the optional (?:EDURE)? still requires trailing whitespace, so a word
# that merely starts with PROC cannot match.
# \bCREATE: without the boundary, CREATE matched inside a bare word, so
# 'SELECT AUTOCREATE PROCEDURE x FROM t;' in an error-bearing file minted a
# phantom routine x() (delimited identifiers are span-skipped at the scan
# site, but a bare word has no span).
_ROUTINE_RECOVERY_RX = re.compile(
r"\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?(?:FUNCTION|PROC(?:EDURE)?)\s+"
r"(?:IF\s+NOT\s+EXISTS\s+)?"
r"((?:\"(?:[^\"\n]|\"\")+\"|\[(?:[^\]\n]|\]\])+\]|[\w$]+)"
r"(?:\s*\.\s*(?:\"(?:[^\"\n]|\"\")+\"|\[(?:[^\]\n]|\]\])+\]|[\w$]+))*)",
re.IGNORECASE,
)
# _mask_sql_comments is a linear character scanner, not a regex: the four
# span kinds interact in ways a single pattern cannot express safely —
# comment-opener parity inside strings, nested block comments, and
# end-of-line abandonment of unclosed literals. Span handling:
#
# - single-quoted strings are BLANKED like comments: routine names never
# live in single quotes, and dynamic SQL (EXEC(N'CREATE PROC [dbo].[Fake]
# ...')) would otherwise fabricate a routine node whenever an unrelated
# parse error arms the whole-file scan. (Dialects where other quoting
# carries strings — MySQL double quotes, PostgreSQL dollar-quoting — are
# NOT modelled; DDL inside those still reaches the scan.)
# - double-quoted and bracket-delimited identifiers are PRESERVED verbatim —
# they are exactly the delimited names the recovery regex must see ("" and
# ]] escapes consumed, mirroring _ROUTINE_RECOVERY_RX).
# - line comments blank to end-of-line; block comments blank to their
# matching */ with NESTING tracked (SQL Server and PostgreSQL both nest
# /* */, and a lazy first-*/ match let commented-out DDL inside a nested
# comment fabricate nodes). MySQL and Oracle do NOT nest — there the
# depth tracking over-blanks, losing (never fabricating) a routine after
# an inner */; the primary T-SQL/PostgreSQL targets win that trade. An
# UNCLOSED block comment blanks to end-of-file, matching SQL semantics.
#
# Literals are deliberately line-scoped: this mask only runs on files that
# already failed to parse, where an unclosed delimiter is likely, and a
# multi-line literal span would let one unclosed quote swallow real DDL
# below it. The cost is asymmetric by kind. A single-quoted string that
# continues past its line is blanked only up to the newline, so a comment
# opener inside it cannot fire on that line — but its CONTINUATION lines are
# scanned as code, and DDL there fabricates: multi-line dynamic SQL
# (SET @sql = N\'\n CREATE PROC ...\') is a KNOWN HOLE, alongside the
# unmodelled quoting dialects above; only same-line dynamic SQL is blanked.
# Closing it would need a real string heuristic (e.g. an end-of-line opening
# quote), judged not worth the swallow risk in a recovery-only path.
def _scan_sql(text: str) -> tuple[str, list[tuple[int, int]]]:
"""Blank comment and string-literal spans, preserving every offset.
One output character per input character: non-newline characters inside
a blanked span become spaces and newlines are kept, so positions and
line numbers computed against the masked text are valid against the
original. Double-quoted and bracket-delimited identifiers are preserved
verbatim (they carry recoverable routine names); single-quoted strings,
line comments, and (nesting-aware) block comments are blanked. Used by
the routine-recovery scan so CREATE PROCEDURE/FUNCTION DDL reachable
only through a comment or a single-quoted string cannot fabricate a
routine node when an unrelated parse error arms recovery.
Returns (masked_text, ident_spans) where ident_spans holds the [start,
end) of every PRESERVED delimited identifier: preserved spans keep their
text verbatim, so DDL keywords inside one are still visible in the
masked text, and the recovery scan must skip a match that starts there
(identifier data, not DDL — 'SELECT 1 AS [CREATE PROCEDURE x pending]'
must not mint a routine).
"""
ident_spans: list[tuple[int, int]] = []
out: list[str] = []
i, n = 0, len(text)
def _blank(upto: int) -> int:
"""Blank [i, upto), keeping newlines; return upto."""
for c in text[i:upto]:
out.append("\n" if c == "\n" else " ")
return upto
def _blank_tail_and_carry(start: int) -> int:
"""Blank from start to end-of-line, carrying comment state forward.
The union-of-readings blank for an ambiguous stretch: the rest of the
line is blanked outright; if the raw text of that stretch leaves a /*
unclosed on its own line (the maximum comment depth any reading could
be left holding), blanking continues, nesting-aware, to the closing
*/ or EOF. Where a carry closes MID-line the same rule applies to the
remainder of that line — under the reading where the carry never
opened, that whole line may be a comment or a string, so emitting the
post-*/ text verbatim exposed it (found by differential fuzzing).
Repeats until a line ends with no carry pending. Appends one output
character per input character; returns the resume index.
"""
k = start
while True:
eol = text.find("\n", k)
eol = n if eol == -1 else eol
depth = 0
m2 = k
while m2 < eol:
if text.startswith("/*", m2):
depth += 1
m2 += 2
elif text.startswith("*/", m2):
if depth:
depth -= 1
m2 += 2
else:
m2 += 1
for ch in text[k:eol]:
out.append("\n" if ch == "\n" else " ")
k = eol
if not depth:
return k
j2 = k
while j2 < n and depth:
if text.startswith("/*", j2):
depth += 1
j2 += 2
elif text.startswith("*/", j2):
depth -= 1
j2 += 2
else:
j2 += 1
for ch in text[k:j2]:
out.append("\n" if ch == "\n" else " ")
k = j2
if k >= n:
return k
# the carry closed mid-line: the remainder of THIS line is the
# same ambiguous stretch — loop and blank it too
while i < n:
c = text[i]
if c == "'":
# Single-quoted string: blank it. '' is an escaped quote; a
# newline abandons the literal (see the comment above).
j = i + 1
while j < n and text[j] != "\n":
if text[j] == "'":
if j + 1 < n and text[j + 1] == "'":
j += 2
continue
j += 1
break
j += 1
i = _blank(j)
elif c == '"' or c == "[":
# Delimited identifier: preserve verbatim. Doubled closers are
# escapes. A span is DISTRUSTED when it is unterminated (no
# closer before the newline) or would swallow a comment opener
# on its way to the closer ('SELECT [Col FROM t -- CREATE PROC
# [dbo]' closes on [dbo]'s bracket) — a stray delimiter is
# ordinary in exactly the broken files this mask runs on.
#
# A distrusted span is irreducibly ambiguous (identifier data vs
# stray delimiter before real comments/strings), and any attempt
# to pick one reading exposed text the other reading blanks —
# re-emitting the delimiter and rescanning even re-paired later
# single quotes and uncovered dynamic SQL. So blank the UNION of
# every reading: the rest of the line is blanked outright, and
# any raw /* on it with no later */ on the same line carries
# forward as (nesting-aware) comment state, since some reading
# may have left it open — and where that carry closes mid-line,
# the remainder of THAT line gets the same treatment, repeated
# until a line ends carry-free (under the no-carry reading the
# close line may itself be all comment or string, so emitting its
# post-*/ tail verbatim was an exposure). Over-blanking loses at
# most routines on lines already entangled with the broken one (a
# conservative false negative; a routine named like [a--b] is
# inside that loss); under-blanking is what fabricates, and every
# reading's blank set stays a subset of this one — except where a
# */ + * versus * + /* token split makes two readings consume the
# same /, an irreducible divergence whose only closure would be
# blanking to EOF on every */* sequence (accepted, documented
# limitation; the token sequence appears in no dialect's idiom).
closer = '"' if c == '"' else "]"
j = i + 1
closed = False
while j < n and text[j] != "\n":
if text[j] == closer:
if j + 1 < n and text[j + 1] == closer:
j += 2
continue
j += 1
closed = True
break
j += 1
span = text[i:j]
if closed and "--" not in span and "/*" not in span:
ident_spans.append((i, j))
out.append(span)
i = j
else:
i = _blank_tail_and_carry(i)
elif c == "-" and i + 1 < n and text[i + 1] == "-":
j = i
while j < n and text[j] != "\n":
j += 1
i = _blank(j)
elif c == "/" and i + 1 < n and text[i + 1] == "*":
depth, j = 1, i + 2
while j < n and depth:
if text[j] == "/" and j + 1 < n and text[j + 1] == "*":
depth += 1
j += 2
elif text[j] == "*" and j + 1 < n and text[j + 1] == "/":
depth -= 1
j += 2
else:
j += 1
i = _blank(j) # unclosed comment: j == n, blanks to end-of-file
else:
out.append(c)
i += 1
return "".join(out), ident_spans
def _mask_sql_comments(text: str) -> str:
"""Masked text only — see _scan_sql for the span-reporting form."""
return _scan_sql(text)[0]
def _norm_ident(name: str) -> str:
"""Normalize a SQL identifier for name-based reference resolution.
Splits on `.`, strips one pair of surrounding delimiters from each part
(double quotes for Postgres/ANSI, backticks for MySQL, brackets for
T-SQL), lowercases, and rejoins. So `"public"."users"`, `public.users`,
and `PUBLIC.USERS` all normalize to `public.users`. Used ONLY for
`table_nids` keys and lookups — node ids and display labels keep the
original text.
"""
parts = []
for part in name.split("."):
p = part.strip()
if len(p) >= 2 and ((p[0] == p[-1] and p[0] in ('"', "`"))
or (p[0] == "[" and p[-1] == "]")):
p = p[1:-1]
parts.append(p.lower())
return ".".join(parts)
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 as e:
import importlib.util
# An installed-but-broken grammar (e.g. a C extension built for a
# different Python ABI, #2602) raises ImportError here too. Reporting
# that as "not installed" sends the user to a no-op `pip install`, so
# distinguish a genuinely-absent module from one that failed to load
# and surface the real exception in the latter case.
if importlib.util.find_spec("tree_sitter_sql") is None:
return {"nodes": [], "edges": [],
"error": "tree_sitter_sql not installed. Run: pip install tree-sitter-sql"}
return {"nodes": [], "edges": [],
"error": f"tree_sitter_sql is installed but failed to load: {e}"}
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 _ref_stub(name: str) -> str:
"""Sourceless bare-name stub for a table referenced but not defined here.
SQL references are NAME-based, so a table defined in another file (e.g.
prisma migration m2 referencing a table created in m1) can only resolve
at the corpus level. Minting `_make_id(stem, name)` under THIS file's
stem fabricated a node-less compound id — an absolute-path slug when the
input path was absolute — that could never match the real definition
(#2324). Instead emit a SOURCELESS stub, mirroring the Go extractor's
cross-file pattern (#1402): `_rewire_unique_stub_nodes` collapses it
onto the unique real table definition, and an unresolvable name survives
as a portable name-only node instead of dangling. No contains edge: a
sourced/contained stub would get the referencing file's path baked into
its id by disambiguation, blocking the rewire.
"""
nid = _make_id(name)
if nid not in seen_ids:
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) -> 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[_norm_ident(name)] = 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(_norm_ident(ref_name)) or _ref_stub(ref_name)
_add_edge(nid, ref_nid, "references", line)
seen_refs.add(_norm_ident(ref_name))
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(_norm_ident(ref_name)) or _ref_stub(ref_name)
_add_edge(nid, ref_nid, "references", line)
seen_refs.add(_norm_ident(ref_name))
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 _norm_ident(ref_name) not in seen_refs:
ref_nid = table_nids.get(_norm_ident(ref_name)) or _ref_stub(ref_name)
_add_edge(nid, ref_nid, "references", line)
seen_refs.add(_norm_ident(ref_name))
elif t == "create_view":
name = _obj_name(node)
if name:
nid = _make_id(stem, name)
_add_node(nid, name, line)
table_nids[_norm_ident(name)] = 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(_norm_ident(name))
if not src_nid:
# Subject table not defined in this file: sourceless stub,
# not a sourced wrong-stem node (#2324).
src_nid = _ref_stub(name)
table_nids[_norm_ident(name)] = 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(_norm_ident(ref_name))
or _ref_stub(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(_norm_ident(tbl_name)) or _ref_stub(tbl_name)
_add_edge(trig_nid, tbl_nid, "triggers", line)
elif t == "create_index":
# CREATE [UNIQUE] INDEX [CONCURRENTLY] [IF NOT EXISTS] <name>
# ON <table> (...). Unlike CREATE POLICY (#3401) the grammar
# parses this statement fine; the walk simply never dispatched on
# it, so every index was silently dropped (#3467). The name is the
# identifier (or a quoted literal) before ON; the table is the
# object_reference after it. An unnamed index (`CREATE INDEX ON
# t (c)`) has nothing to name a node after and is skipped.
index_name: str | None = None
index_table: str | None = None
after_on = False
for c in node.children:
if c.type == "keyword_on":
after_on = True
elif not after_on and index_name is None and c.type in ("identifier", "literal"):
index_name = _read(c).strip('"`')
elif after_on and index_table is None and c.type == "object_reference":
index_table = _read(c)
if index_name:
index_nid = _make_id(stem, index_name)
_add_node(index_nid, index_name, line)
if index_table:
index_tbl_nid = (table_nids.get(_norm_ident(index_table))
or _ref_stub(index_table))
_add_edge(index_nid, index_tbl_nid, "indexes", line)
# NOTE: there is deliberately NO recovery scan on individual ERROR
# nodes. Any ERROR node anywhere makes root.has_error true, so the
# whole-file masked scan below this walk already recovers everything
# a per-node scan could — from the SAME shared _ROUTINE_RECOVERY_RX,
# with _add_node deduping by id. A per-node scan is not just
# redundant, it is unsound: _mask_sql_comments needs file-level
# context, and an ERROR fragment can begin MID-comment (tree-sitter's
# lexer does not nest /* */, so the text after an inner */ parses as
# code and lands in an ERROR blob with no comment opener in sight),
# which let commented-out DDL fabricate routine nodes.
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(_norm_ident(tbl)) or _ref_stub(tbl)
_add_edge(obj_nid, tbl_nid, "triggers", line)
_NON_TABLES = {
"select", "where", "set", "dual", "null", "true", "false",
"first", "skip", "rows", "next", "only", "lateral",
}
# Same CTE-blindness as the AST path (#2577): a `WITH <name> AS (`
# binding is statement-local, not a table, so its name must not
# become a reads_from stub. The regex has no scope tree, so the
# skip is body-wide — the right trade for a recovery path.
for cm in re.finditer(
r"(?:\bWITH\s+(?:RECURSIVE\s+)?|,\s*)([\w$]+)\s*(?:\([^()]*\))?\s+AS\s*\(",
text, re.IGNORECASE,
):
_NON_TABLES.add(_norm_ident(cm.group(1)))
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 _norm_ident(tbl) not in _NON_TABLES and _norm_ident(tbl) not in seen_tbls:
seen_tbls.add(_norm_ident(tbl))
tbl_nid = table_nids.get(_norm_ident(tbl)) or _ref_stub(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 _norm_ident(tbl) not in _NON_TABLES and _norm_ident(tbl) not in seen_tbls:
seen_tbls.add(_norm_ident(tbl))
tbl_nid = table_nids.get(_norm_ident(tbl)) or _ref_stub(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,
cte_names: frozenset[str] = frozenset()) -> None:
"""Recursively find FROM/JOIN table references inside a node, skipping CTEs.
A name bound by `WITH <name> AS (...)` is not a table: emitting it as a
`reads_from` target minted a bare `_ref_stub`, and because that stub is
intentionally sourceless (see `_ref_stub`) it carried no schema, file, or
language namespace, so a CTE named `levels` or `slug` collided with any
same-named node from another language during the build (#2577).
Scoping matters: a CTE is visible only inside the query that declares it,
and a `WITH` inside a subquery is scoped to that subquery alone. So the
active set is extended PER SUBTREE — each node's directly-owned `cte`
children (`create_query` for a statement-level WITH, `subquery` for a
nested one) join the set passed down into that node's recursion only. A
single statement-wide pre-collect would also suppress an OUTER reference
to a real table that merely shares a subquery-CTE's name
(`... FROM t2 JOIN (WITH t2 AS (...) SELECT ...) sub`), dropping the
real `-> t2` edge.
"""
own: set[str] = set()
for c in node.children:
if c.type != "cte":
continue
# First identifier is the CTE's name; later ones are its column
# list (`WITH levels(a, b) AS (...)`), which must not be skipped.
for cc in c.children:
if cc.type in ("identifier", "object_reference"):
own.add(_norm_ident(_read(cc)))
break
if own:
cte_names = frozenset(cte_names | own)
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)
if _norm_ident(tbl) in cte_names:
continue
tbl_nid = table_nids.get(_norm_ident(tbl)) or _ref_stub(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, cte_names)
# Pre-pass: register every table/view DEFINED in this file before walking,
# so forward references (a FK to a table created later in the same file)
# still resolve to the real sourced node instead of falling back to a stub.
def _collect_defined_names(node) -> None:
if node.type in ("create_table", "create_view"):
name = _obj_name(node)
if name:
table_nids[_norm_ident(name)] = _make_id(stem, name)
for child in node.children:
_collect_defined_names(child)
_collect_defined_names(root)
# Secondary bare-name aliases: a reference written without a schema
# (`REFERENCES users`) should resolve to a schema-qualified definition
# (`public.users`) when that is unambiguous. Never shadow an explicit
# definition, and skip bare names defined under more than one schema.
bare_candidates: dict[str, str | None] = {}
for key, alias_nid in table_nids.items():
if "." in key:
bare = key.rsplit(".", 1)[1]
bare_candidates[bare] = (
alias_nid if bare_candidates.get(bare, alias_nid) == alias_nid else None
)
for bare, alias_nid in bare_candidates.items():
if alias_nid is not None and bare not in table_nids:
table_nids[bare] = alias_nid
for stmt in root.children:
if stmt.type == "statement":
for child in stmt.children:
walk(child)
elif stmt.type == "transaction":
# BEGIN; ... COMMIT; wraps DDL in a transaction node whose children
# are statement nodes, not direct create_table nodes (#2953).
walk(stmt)
elif stmt.type in ("fb_proc_or_trigger", "set_term", "declare_external_function", "ERROR"):
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(_norm_ident(tbl_name))
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(_norm_ident(ref_name)) or _ref_stub(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))
# Global regex fallback for routines (#2180). PL/pgSQL bodies break the parse
# in more than one shape, and only the first was recovered before:
# 1. the whole CREATE lands in one ERROR node -> handled in walk()
# 2. the statement is shredded into loose top-level tokens
# (keyword_create/keyword_function/object_reference/... ) and the ERROR
# node holds only the offending body line, e.g. `PERFORM x();` or
# `x := 1;` -- so no CREATE text is inside any ERROR node at all
# 3. the name is a delimited identifier — quoted ("public"."fn") or
# T-SQL-bracketed ([dbo].[usp_Load]) — which a bare [\w$.]+ pattern
# cannot match
# Shapes 2 and 3 silently dropped the routine: no node, no warning, exit 0.
# Scanning the raw source catches all three, and _add_node dedupes by id so
# routines already recovered from the tree are not emitted twice.
#
# Gate on a failed parse: a cleanly-parsing file must NOT have routines
# fabricated from MySQL `CREATE FUNCTION IF NOT EXISTS` (which would
# capture `IF`) or other shapes the mask does not model (double-quoted
# strings in MySQL's default mode, PostgreSQL dollar-quoted bodies). Every
# observed drop shape leaves an ERROR node in the tree, so has_error loses
# nothing while protecting clean corpora (#2180 follow-up).
if root.has_error:
# The mask blanks comments (nesting-aware) and single-quoted strings
# (offset-preserving), so commented-out DDL and single-quoted dynamic
# SQL cannot fabricate a routine when an unrelated error arms this
# scan; string shapes the mask does not model rely on the has_error
# gate alone. Preserved delimited identifiers keep their text
# verbatim (they carry the recoverable names), so a match whose
# CREATE keyword STARTS inside one is identifier data, not DDL
# ('SELECT 1 AS [CREATE PROCEDURE x pending]') and is skipped — the
# name a genuine statement captures is allowed to be a delimited
# identifier; its CREATE never is.
masked_src, ident_spans = _scan_sql(src_text)
for m in _ROUTINE_RECOVERY_RX.finditer(masked_src):
if any(s <= m.start() < e for s, e in ident_spans):
continue
fn_name = m.group(1)
fn_line = src_text[: m.start()].count("\n") + 1
_add_node(_make_id(stem, fn_name), f"{fn_name}()", fn_line)
return {"nodes": nodes, "edges": edges}
-311
View File
@@ -1,311 +0,0 @@
"""Terraform block extraction and local module-source topology."""
from __future__ import annotations
import hashlib
import json
from collections.abc import Sequence
from pathlib import Path
from graphify.extractors.base import _make_id
_TF_META_HEADS = frozenset({"count", "each", "self", "path", "terraform"})
def _scope_id(directory: str) -> str:
# Hash the exact path too: make_id folds case and punctuation, which must
# not merge e.g. dev/app with prod/app, or a-b with a_b.
digest = hashlib.sha256(directory.encode("utf-8")).hexdigest()[:16]
return _make_id("terraform", directory, digest)
def prepare_terraform(result: dict, path: Path, root: Path) -> None:
"""Make cached directory-scoped IDs portable before the common merge passes."""
directory = path.parent.resolve()
try:
relative = directory.relative_to(root).as_posix()
except ValueError:
return
old, new = _scope_id(directory.as_posix()), _scope_id(relative)
for node in result.get("nodes", []):
nid = node["id"]
if nid.startswith(old + "_"):
node["id"] = new + nid[len(old):]
node["_terraform_directory"] = relative
for edge in result.get("edges", []):
for key in ("source", "target"):
nid = edge[key]
if nid.startswith(old + "_"):
edge[key] = new + nid[len(old):]
# Resolve paths only here, with the scan boundary available. The per-file
# cache keeps syntax facts, never filesystem-dependent topology.
for node in result.get("nodes", []):
source = node.get("module_source", "")
if not source.startswith(("./", "../")):
continue
try:
target = (directory / source).resolve().relative_to(root)
except (ValueError, OSError, RuntimeError):
continue
node["_terraform_source_directory"] = target.as_posix()
def resolve_terraform_modules(per_file: list[dict], nodes: list[dict], edges: list[dict]) -> None:
"""Connect module calls to scanned .tf directories without reading new files."""
files: dict[str, list[dict]] = {}
anchors = {}
for node in nodes:
directory = node.get("_terraform_directory")
if directory is None:
continue
if node.get("type") == "terraform_file" and Path(node["source_file"]).suffix == ".tf":
files.setdefault(directory, []).append(node)
elif node.get("type") == "module" and node.get("language") == "terraform":
anchors[directory] = node["id"]
fresh_files = {
node["id"] for result in per_file for node in result.get("nodes", [])
if node.get("type") == "terraform_file"
}
known_ids = {n["id"] for n in nodes}
for directory, members in sorted(files.items()):
anchor = anchors.setdefault(directory, _make_id(_scope_id(directory), "directory"))
if anchor not in known_ids:
owner = min(members, key=lambda n: n["source_file"])
nodes.append({
"id": anchor, "label": f"Terraform module: {directory}",
"type": "module", "language": "terraform", "file_type": "code",
"source_file": owner["source_file"], "source_location": None,
"_terraform_directory": directory,
})
known_ids.add(anchor)
for member in members:
if member["id"] in fresh_files:
edges.append({
"source": anchor, "target": member["id"], "relation": "contains",
"confidence": "EXTRACTED", "weight": 1.0,
"source_file": member["source_file"], "source_location": None,
})
fresh_calls = {
node["id"] for result in per_file for node in result.get("nodes", [])
if "module_source" in node
}
for node in nodes:
if node["id"] not in fresh_calls:
continue
target = anchors.get(node.get("_terraform_source_directory"))
if target is not None:
edges.append({
"source": node["id"], "target": target, "relation": "module_source",
"confidence": "EXTRACTED", "weight": 1.0,
"source_file": node["source_file"],
"source_location": node["module_source_location"],
})
def refresh_terraform_paths(
changed: list[Path], corpus: list[Path], invalidated: Sequence[Path] = (),
) -> list[Path]:
"""Reconcile directory ownership and incoming links on incremental scans.
Callers pass only the permitted, live corpus. Cached syntax is reused for
unchanged Terraform files; other languages keep their incremental behavior.
"""
if not any(p.suffix == ".tf" or p.name in (".gitignore", ".graphifyignore")
for p in [*changed, *invalidated]):
return changed
return list(dict.fromkeys([*changed, *(p for p in corpus if p.suffix == ".tf")]))
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.parent.resolve() / path.name)
file_nid = _make_id(str_path)
scope = _scope_id(path.parent.resolve().as_posix())
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str_path, "source_location": None,
"type": "terraform_file"}]
edges: list[dict] = []
seen_ids: set[str] = {file_nid}
nodes_by_id = {file_nid: nodes[0]}
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}"})
nodes_by_id[nid] = nodes[-1]
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)
if blk_body is not None and path.suffix == ".tf":
for attr in blk_body.named_children:
if attr.type != "attribute" or _read(attr.named_children[0]) != "source":
continue
# Accept a plain quoted literal only, not interpolation,
# heredocs, or constant expressions requiring evaluation.
value = attr.named_children[-1]
while value.type in ("expression", "literal_value") and len(value.named_children) == 1:
value = value.named_children[0]
if value.type != "string_lit" or value.has_error:
continue
try:
module_source = json.loads(_read(value))
except (ValueError, TypeError):
continue
if not isinstance(module_source, str):
continue
nodes_by_id[owner]["module_source"] = module_source.replace("$${", "${").replace("%%{", "%{")
nodes_by_id[owner]["module_source_location"] = f"L{attr.start_point[0] + 1}"
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}
-329
View File
@@ -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}
-181
View File
@@ -1,181 +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)
# Zig enums and tagged unions can declare methods just like
# structs (`pub fn ...` inside the container). Recurse so those
# methods — and the calls made from their bodies — are captured
# rather than dropped along with the whole method layer.
for child in value_node.children:
walk(child, parent_struct_nid=type_nid)
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}
-246
View File
@@ -1,246 +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.
#
# This set has to keep pace with ``detect.DOC_EXTENSIONS``: anything classified
# as a document reaches the semantic pass, and anything the pass sees that is
# NOT listed here is silently cut at ``_FILE_CHAR_CAP`` by ``_read_files``. The
# two lists drifted as DOC_EXTENSIONS grew — .qmd, .skill, .html, .yaml and .yml
# were documents that never got sliced, so a 38k-character one reached the model
# as its first 20k with no warning and no partial marker (#2900).
# ``tests/test_oversized_document_slicing.py`` pins the relationship so a future
# addition to DOC_EXTENSIONS fails loudly instead of quietly losing content.
_SPLITTABLE_TEXT_SUFFIXES = frozenset({
".md", ".mdx", ".markdown", ".txt", ".rst",
".qmd", ".skill", ".html", ".yaml", ".yml",
})
# Document types whose BYTES are not what the model is shown. `llm._file_to_text`
# routes these through a converter, so a character range has to be taken over the
# converted text, never over the file. Kept separate from the set above because
# they are splittable for a different reason and via a different reader.
_CONVERTED_TEXT_SUFFIXES = frozenset({".pdf"})
def _pdf_text(path: Path) -> str:
"""Extracted text of a PDF — the same string `llm._file_to_text` builds.
Imported lazily from ``detect`` so this module keeps no import-time
dependency on the extraction stack (``llm`` imports *this* module, so the
reverse direction would be a cycle).
"""
from graphify.detect import extract_pdf_text
return extract_pdf_text(path)
# Slicing a PDF means extracting its text, and the slicing pass asks for the same
# file several times: once to measure it, then once per slice as the prompt is
# built. Memoised on (path, size, mtime_ns) so a corpus of papers is parsed once
# rather than once per slice, and so a file rewritten mid-run is re-read instead
# of served a stale body. Bounded: the entries are whole documents, and a large
# corpus should not pin all of them in memory.
_CONVERTED_TEXT_CACHE: "dict[tuple, str]" = {}
_CONVERTED_TEXT_CACHE_MAX = 64
def unit_source_text(path: Path) -> str:
"""The text a unit contributes to the prompt, whatever its container.
Plain-text files are read directly; converted types (PDF) go through their
converter. Both `expand_oversized_files` and `read_slice_text` use this, so
the offsets a slice carries always index the same string the model sees.
"""
if path.suffix.lower() not in _CONVERTED_TEXT_SUFFIXES:
return path.read_text(encoding="utf-8", errors="replace")
try:
st = path.stat()
key = (str(path), st.st_size, st.st_mtime_ns)
except OSError:
return _pdf_text(path)
hit = _CONVERTED_TEXT_CACHE.get(key)
if hit is not None:
return hit
text = _pdf_text(path)
if len(_CONVERTED_TEXT_CACHE) >= _CONVERTED_TEXT_CACHE_MAX:
_CONVERTED_TEXT_CACHE.clear()
_CONVERTED_TEXT_CACHE[key] = text
return text
# 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 document types that may be sliced.
Covers plain text read straight off disk and converted types (PDF) whose
text is produced by a converter. Both are sliceable because
:func:`unit_source_text` gives the slicing pass the same string the prompt
will carry; what disqualifies a type is having no text at all (an image) or
text the reader cannot address by character offset.
"""
suffix = path.suffix.lower()
return suffix in _SPLITTABLE_TEXT_SUFFIXES or suffix in _CONVERTED_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:
# The CONVERTED text for a PDF, so the boundaries below index the
# same string read_slice_text will later slice and the prompt will
# carry — not the container's bytes (#2906).
text = unit_source_text(f)
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.
Goes through :func:`unit_source_text`, so a PDF slice indexes the extracted
text rather than the container's bytes — the offsets `expand_oversized_files`
computed and the string the prompt carries are then the same string (#2906).
"""
return unit_source_text(fs.path)[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
# Index the SAME string the slice offsets were computed against and the
# prompt carries: for a PDF that is the extracted text via unit_source_text,
# not the raw container bytes. Reading the container here (the old behavior)
# searched for the newline cut in binary coordinates, so a compressed PDF
# slice could cut mid-line or past the text end (#2906). Any converter/read
# failure means we cannot split, so fall back to None (treated as atomic).
try:
text = unit_source_text(fs.path)
except Exception:
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
+12 -47
View File
@@ -16,34 +16,14 @@ 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": {}}
def _save_manifest(manifest: dict) -> None:
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
from graphify.paths import write_json_atomic
write_json_atomic(_GLOBAL_MANIFEST, manifest, indent=2)
_GLOBAL_MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
def _load_global_graph() -> nx.Graph:
@@ -66,8 +46,7 @@ def _save_global_graph(G: nx.Graph) -> None:
data = _jg.node_link_data(G, edges="links")
except TypeError:
data = _jg.node_link_data(G)
from graphify.paths import write_json_atomic
write_json_atomic(_GLOBAL_GRAPH, data, indent=2)
_GLOBAL_GRAPH.write_text(json.dumps(data, indent=2), encoding="utf-8")
def _file_hash(path: Path) -> str:
@@ -79,8 +58,7 @@ def _file_hash(path: Path) -> str:
def global_add(source_path: Path, repo_tag: str) -> dict:
"""Add or update a project graph in the global graph.
Returns a summary dict with keys: repo_tag, nodes_added, nodes_removed, skipped,
cross_repo_calls.
Returns a summary dict with keys: repo_tag, nodes_added, nodes_removed, skipped.
Skipped=True means the source graph hasn't changed since last add.
"""
from graphify.build import prefix_graph_for_global, prune_repo_from_graph
@@ -101,8 +79,7 @@ def global_add(source_path: Path, repo_tag: str) -> dict:
file=sys.stderr,
)
if existing.get("source_hash") == src_hash:
return {"repo_tag": repo_tag, "nodes_added": 0, "nodes_removed": 0, "skipped": True,
"cross_repo_calls": 0}
return {"repo_tag": repo_tag, "nodes_added": 0, "nodes_removed": 0, "skipped": True}
# Load source graph
from graphify.security import check_graph_file_size_cap
@@ -128,31 +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)
# A member call parked on a caller node (#3152) may be answered by a repo
# already in the global graph, or by this one for a repo added earlier. The
# pass recomputes its own output, so adding repos one at a time lands where a
# single merge-graphs of the same inputs would.
from graphify.cross_repo_calls import link_cross_repo_member_calls
cross_repo_calls = link_cross_repo_member_calls(G)
added = prefixed.number_of_nodes() - len(nodes_to_skip)
_save_global_graph(G)
manifest["repos"][repo_tag] = {
@@ -164,8 +130,7 @@ def global_add(source_path: Path, repo_tag: str) -> dict:
}
_save_manifest(manifest)
return {"repo_tag": repo_tag, "nodes_added": added, "nodes_removed": removed,
"skipped": False, "cross_repo_calls": cross_repo_calls}
return {"repo_tag": repo_tag, "nodes_added": added, "nodes_removed": removed, "skipped": False}
def global_remove(repo_tag: str) -> int:
+3 -17
View File
@@ -121,21 +121,8 @@ def _run_gws_export(file_id: str, mime_type: str, output: Path, resource_key: st
raise RuntimeError(f"gws export failed for {file_id}: {stderr}")
def _sidecar_path(path: Path, out_dir: Path, root: "Path | None" = None) -> Path:
# Hash the scan-root-relative, NFC-normalized path — not the absolute path.
# The absolute form salts the sidecar name with the checkout location, so the
# same shortcut in two clones/worktrees emits differently-named byte-identical
# sidecars, each ingested as a distinct source doc when graphify-out/ is
# committed (#2059; mirrors convert_office_file). NFC guards macOS NFD drift
# (#1226). The relative path still disambiguates same-stem files.
import unicodedata
if root is None:
root = out_dir.parent.parent
try:
key = path.resolve().relative_to(Path(root).resolve()).as_posix()
except (ValueError, OSError):
key = str(path.resolve())
name_hash = hashlib.sha256(unicodedata.normalize("NFC", key).encode()).hexdigest()[:8]
def _sidecar_path(path: Path, out_dir: Path) -> Path:
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
return out_dir / f"{path.stem}_{name_hash}.md"
@@ -165,7 +152,6 @@ def convert_google_workspace_file(
out_dir: Path,
*,
xlsx_to_markdown: Callable[[Path], str] | None = None,
root: "Path | None" = None,
) -> Path | None:
"""Export a Google Workspace shortcut to a Markdown sidecar.
@@ -178,7 +164,7 @@ def convert_google_workspace_file(
shortcut = read_google_shortcut(path)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = _sidecar_path(path, out_dir, root=root)
out_path = _sidecar_path(path, out_dir)
if ext == ".gdoc":
with tempfile.NamedTemporaryFile("w+b", suffix=".md", delete=False, dir=out_dir) as tmp:
+105 -602
View File
@@ -1,6 +1,6 @@
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
from __future__ import annotations
import os
import configparser
import re
import sys
from pathlib import Path
@@ -20,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
@@ -41,43 +32,20 @@ if [ -z "$GRAPHIFY_PYTHON" ]; then
if [ -f "$_GFY_PYTHON_FILE" ]; then
_FROM_FILE=$(cat "$_GFY_PYTHON_FILE" 2>/dev/null | tr -d '[:space:]')
case "$_FROM_FILE" in
*[!a-zA-Z0-9/_.@:\\\\-]*) _FROM_FILE="" ;; # allowlist (covers Windows paths)
*[!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. Gate on a
# leading '#!': a launcher can also be a binary trampoline with no
# shebang at all (uv tool installs on Windows), and its bytes must
# never reach the shebang parse (#2852).
case "$GRAPHIFY_BIN" in
*.exe) _GFY_HEAD="" ;;
*) _GFY_HEAD=$(head -c 256 "$GRAPHIFY_BIN" 2>/dev/null | tr -d '\\000') ;;
esac
case "$_GFY_HEAD" in
'#!'*) _SHEBANG=$(printf '%s\\n' "$_GFY_HEAD" | head -n 1 | sed 's/^#![[:space:]]*//') ;;
*) _SHEBANG="" ;;
*.exe) _SHEBANG="" ;;
*) _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//') ;;
esac
case "$_SHEBANG" in
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
@@ -86,49 +54,18 @@ if [ -z "$GRAPHIFY_PYTHON" ]; then
# Allowlist: only keep characters valid in a filesystem path to prevent
# injection if the shebang contains shell metacharacters.
case "$GRAPHIFY_PYTHON" in
*[!a-zA-Z0-9/_.@:\\\\-]*) GRAPHIFY_PYTHON="" ;;
*[!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
# Fourth probe: uv tool environments. `uv tool install` (the README's
# recommended method) puts graphify in an isolated venv that no ambient
# python can import, and on Windows its launcher on PATH is a binary
# trampoline with no shebang to parse — so the probes above can all miss a
# healthy install and the hook dies at the last-resort fallback (#2852).
# Scan the uv tool envs directly; UV_TOOL_DIR overrides the default
# location. A tool env is adopted only if its python passes the probe, so a
# co-installed tool without graphify never satisfies it.
#
# The snap roots matter because an install made from inside a snap-confined
# editor lands in that snap's private HOME, which the plain $HOME roots above
# never see once the hook runs from an ordinary shell. Revisions are globbed
# rather than pinned: snap rotates them on update, which is exactly what makes
# a pinned path unsafe (see _is_rotating_prefix).
if [ -z "$GRAPHIFY_PYTHON" ]; then
for _GFY_TOOLS in \
"${UV_TOOL_DIR:-}" \
"$HOME/.local/share/uv/tools" \
"$HOME/AppData/Roaming/uv/tools" \
"$HOME"/snap/*/current/.local/share/uv/tools \
"$HOME"/snap/*/[0-9]*/.local/share/uv/tools; do
[ -n "$_GFY_TOOLS" ] || continue
for _GFY_CAND in "$_GFY_TOOLS"/*/bin/python "$_GFY_TOOLS"/*/Scripts/python.exe; do
[ -x "$_GFY_CAND" ] || continue
if "$_GFY_CAND" -c "$_GFY_PROBE" 2>/dev/null; then
GRAPHIFY_PYTHON="$_GFY_CAND"
break 2
fi
done
done
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
@@ -142,7 +79,7 @@ fi
# double-quote, $, backtick or backslash characters: it is carried inside a
# shell double-quoted `-c "..."` argument (see _detached_launch).
_REBUILD_BODY_COMMIT = """\
import os, signal, sys, threading, multiprocessing
import os, signal, sys
from pathlib import Path
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
@@ -157,63 +94,17 @@ try:
from graphify.watch import _rebuild_code, _apply_resource_limits
_apply_resource_limits()
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
if _timeout > 0:
if hasattr(signal, 'SIGALRM'):
def _sigalrm_bail(*_a):
# Killing here, before the exception unwinds, matters: once
# TimeoutError starts propagating it passes straight through
# the ProcessPoolExecutor with-block's own __exit__, which
# calls shutdown(wait=True) and blocks until every worker
# exits -- forever, for a worker stuck the way #3341 was,
# since the alarm firing never actually stops it. Killing the
# workers first means shutdown has nothing left to wait for.
for _child in multiprocessing.active_children():
_child.kill()
raise TimeoutError(f'graphify rebuild exceeded {_timeout}s')
signal.signal(signal.SIGALRM, _sigalrm_bail)
signal.alarm(_timeout)
else:
def _bail():
print(f'[graphify hook] graphify rebuild exceeded {_timeout}s', flush=True)
for _child in multiprocessing.active_children():
_child.kill()
os._exit(1)
_watchdog = threading.Timer(_timeout, _bail)
_watchdog.daemon = True
_watchdog.start()
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
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-sig').strip()
_txt = _saved.read_text(encoding='utf-8').strip()
if _txt:
_candidate = Path(_txt)
try:
_cwd = Path.cwd().resolve()
_resolved = _candidate.resolve()
# Python 3.13 no longer raises on a symlink loop (resolve returns
# the path unresolved), so require a real directory: a loop or a
# dangling target is not a dir and correctly falls back.
_in_repo = (_resolved == _cwd or _cwd in _resolved.parents) and _resolved.is_dir()
except (OSError, RuntimeError):
_in_repo = False
if _in_repo:
_root = _candidate
else:
print(f'[graphify hook] ignoring out-of-repo .graphify_root: {_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)
@@ -225,70 +116,24 @@ except Exception as exc:
_REBUILD_BODY_CHECKOUT = """\
from graphify.watch import _rebuild_code, _apply_resource_limits
from pathlib import Path
import os, signal, sys, threading, multiprocessing
import os, signal, sys
try:
_apply_resource_limits()
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
if _timeout > 0:
if hasattr(signal, 'SIGALRM'):
def _sigalrm_bail(*_a):
# Killing here, before the exception unwinds, matters: once
# TimeoutError starts propagating it passes straight through
# the ProcessPoolExecutor with-block's own __exit__, which
# calls shutdown(wait=True) and blocks until every worker
# exits -- forever, for a worker stuck the way #3341 was,
# since the alarm firing never actually stops it. Killing the
# workers first means shutdown has nothing left to wait for.
for _child in multiprocessing.active_children():
_child.kill()
raise TimeoutError(f'graphify rebuild exceeded {_timeout}s')
signal.signal(signal.SIGALRM, _sigalrm_bail)
signal.alarm(_timeout)
else:
def _bail():
print(f'[graphify] graphify rebuild exceeded {_timeout}s', flush=True)
for _child in multiprocessing.active_children():
_child.kill()
os._exit(1)
_watchdog = threading.Timer(_timeout, _bail)
_watchdog.daemon = True
_watchdog.start()
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
signal.alarm(_timeout)
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
# post-checkout: branch switch can touch arbitrary files; full rebuild path
# (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-sig').strip()
_txt = _saved.read_text(encoding='utf-8').strip()
if _txt:
_candidate = Path(_txt)
try:
_cwd = Path.cwd().resolve()
_resolved = _candidate.resolve()
# Python 3.13 no longer raises on a symlink loop (resolve returns
# the path unresolved), so require a real directory: a loop or a
# dangling target is not a dir and correctly falls back.
_in_repo = (_resolved == _cwd or _cwd in _resolved.parents) and _resolved.is_dir()
except (OSError, RuntimeError):
_in_repo = False
if _in_repo:
_root = _candidate
else:
print(f'[graphify] ignoring out-of-repo .graphify_root: {_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)
@@ -305,15 +150,8 @@ except Exception as exc:
# requires Python, so we let Python do the detaching: a tiny outer process spawns
# the real rebuild fully detached and returns immediately, so the hook never
# blocks. POSIX uses start_new_session (the setsid equivalent); Windows uses
# CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP, breaking away from any job object
# when allowed. Do NOT 'simplify' CREATE_NO_WINDOW back into DETACHED_PROCESS:
# on Windows 11 with Windows Terminal as the default console host, a
# console-less python still gets a VISIBLE console allocated when its runtime
# touches the console API during startup (ctrl-handler installation), popping
# an empty Terminal window over whatever the user is doing - once per commit,
# for the whole rebuild. Reproduced via GetConsoleWindow(): DETACHED_PROCESS
# child reports a visible hwnd, CREATE_NO_WINDOW child reports none (3bac3df).
# This payload is carried inside a shell double-quoted -c argument,
# DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, breaking away from any job object
# when allowed. This payload is carried inside a shell double-quoted -c argument,
# so it deliberately uses only single-quoted Python strings (no ", $, ` or \\).
_LAUNCHER_TEMPLATE = """\
import os, subprocess, sys
@@ -329,7 +167,7 @@ except OSError:
_kw = dict(stdout=_out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, cwd=os.getcwd(), close_fds=True)
_cmd = [sys.executable, '-c', _src]
if os.name == 'nt':
_flags = 0x08000000 | 0x00000200 # CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP
_flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
try:
subprocess.Popen(_cmd, creationflags=_flags | 0x01000000, **_kw) # + CREATE_BREAKAWAY_FROM_JOB
except OSError:
@@ -352,56 +190,18 @@ 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
"""
# Both hook bodies run inside a subshell `( ... )`. The generated block is
# appended to whatever post-commit / post-checkout already exists, and other
# tools chain their own logic after it; every skip condition in the block is a
# bare `exit 0`, which in a flat script ends the WHOLE hook, silently dropping
# anything after graphify's end marker - on every root commit (HEAD~1 does
# not exist), every rebase/merge, every linked worktree, every
# GRAPHIFY_SKIP_HOOK=1 (#2986). Inside the subshell an `exit` ends only
# graphify's section; the detached rebuild launch is unaffected, and the
# hook's own exit status stays 0 as before.
_HOOK_SCRIPT = """\
# graphify-hook-start
# Auto-rebuilds the knowledge graph after each commit (code files only, no LLM needed).
# Installed by: graphify hook install
(
# Deterministic clustering: networkx louvain iterates string-keyed sets whose
# order is randomized per-process by PYTHONHASHSEED, so community assignments
# churn run-to-run. Pinning it makes graphify-out reproducible.
export PYTHONHASHSEED=0
__VIZ_LIMIT_EXPORT__
# 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
@@ -409,26 +209,13 @@ 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
fi
# Skip when only output-dir artifacts changed (avoids rebuild loop when graph
# outputs are tracked in git). The dir is whatever GRAPHIFY_OUT names, the same
# source the rebuild body reads (#1423): a literal graphify-out/ here let a
# commit touching only a renamed output dir's graph.json trigger a full rebuild.
_GFY_OUT="${GRAPHIFY_OUT:-graphify-out}"
_GFY_OUT="${_GFY_OUT%/}"
# The leading ( on each pattern is POSIX and keeps bash 3.2 (macOS /bin/sh)
# from mis-parsing the pattern's ) as the end of the $(...) substitution.
_NON_GRAPH=$(printf '%s\n' "$CHANGED" | while IFS= read -r _GFY_F; do
case "$_GFY_F" in
("$_GFY_OUT"/*) ;;
(*) printf '%s\n' "$_GFY_F" ;;
esac
done)
# Skip when only graphify-out/ artifacts changed (avoids rebuild loop when graph outputs are tracked in git)
_NON_GRAPH=$(echo "$CHANGED" | grep -v '^graphify-out/' || true)
if [ -z "$_NON_GRAPH" ]; then
exit 0
fi
@@ -444,8 +231,7 @@ _GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
export GRAPHIFY_REBUILD_LOG="$_GRAPHIFY_LOG"
echo "[graphify hook] launching background rebuild (log: $_GRAPHIFY_LOG)"
""" + _detached_launch(_REBUILD_BODY_COMMIT) + """)
# graphify-hook-end
""" + _detached_launch(_REBUILD_BODY_COMMIT) + """# graphify-hook-end
"""
@@ -453,19 +239,11 @@ _CHECKOUT_SCRIPT = """\
# graphify-checkout-hook-start
# Auto-rebuilds the knowledge graph (code only) when switching branches.
# Installed by: graphify hook install
(
# Deterministic clustering: networkx louvain iterates string-keyed sets whose
# order is randomized per-process by PYTHONHASHSEED, so community assignments
# churn run-to-run. Pinning it makes graphify-out reproducible.
export PYTHONHASHSEED=0
__VIZ_LIMIT_EXPORT__
# 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
@@ -476,76 +254,27 @@ if [ "$BRANCH_SWITCH" != "1" ]; then
exit 0
fi
# A no-op checkout (e.g. `git checkout -b` with no start point) reports a
# branch switch but leaves the tree unchanged ΓÇö nothing to rebuild (#2421).
[ "$PREV_HEAD" = "$NEW_HEAD" ] && exit 0
# Only run if the output dir exists (graph has been built before). Resolve it
# from GRAPHIFY_OUT like the rebuild body does (#1423): a literal graphify-out/
# here made the branch-switch rebuild a silent no-op for every renamed output dir.
_GFY_OUT="${GRAPHIFY_OUT:-graphify-out}"
if [ ! -d "${_GFY_OUT%/}" ]; then
# Only run if graphify-out/ exists (graph has been built before)
if [ ! -d "graphify-out" ]; then
exit 0
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"
echo "[graphify] Branch switched - launching background rebuild (log: $_GRAPHIFY_LOG)"
""" + _detached_launch(_REBUILD_BODY_CHECKOUT) + """)
# graphify-checkout-hook-end
""" + _detached_launch(_REBUILD_BODY_CHECKOUT) + """# graphify-checkout-hook-end
"""
def _load_graphifyrc(root: Path) -> dict[str, str | int]:
"""Load key/value options from <root>/.graphifyrc if present.
Supported options:
viz_node_limit: integer >= 0 (e.g. viz_node_limit=0)
"""
rc_path = root / ".graphifyrc"
if not rc_path.is_file():
return {}
cfg: dict[str, str | int] = {}
content = rc_path.read_text(encoding="utf-8")
for line_num, raw in enumerate(content.splitlines(), 1):
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
raise ValueError(f"Invalid line {line_num} in {rc_path}: {raw!r} (expected key=value)")
key, val = line.split("=", 1)
key = key.strip()
val = val.strip()
if key == "viz_node_limit":
try:
parsed_val = int(val)
if parsed_val < 0:
raise ValueError("must be a non-negative integer")
cfg["viz_node_limit"] = parsed_val
except ValueError as exc:
raise ValueError(
f"Invalid viz_node_limit in {rc_path} at line {line_num}: {val!r}. "
f"Must be a non-negative integer."
) from exc
return cfg
def _git_root(path: Path) -> Path | None:
"""Walk up to find .git directory."""
current = path.resolve()
@@ -555,39 +284,38 @@ 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).
Asks git itself via ``rev-parse --git-path hooks`` rather than parsing
``.git/config`` with configparser: git legally allows duplicate keys and
sections (VS Code writes such configs), which a strict configparser rejects
with DuplicateOptionError/DuplicateSectionError, so every hook command
printed a spurious "could not read core.hooksPath" warning (#1907). git
resolves core.hooksPath, includeIf, and linked worktrees (where .git is a
file, not a directory) correctly in one place. Genuinely corrupt configs
are still surfaced: git itself fails on them, and its stderr is printed.
"""
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
try:
cfg = configparser.RawConfigParser()
cfg.read(root / ".git" / "config", encoding="utf-8")
# configparser lowercases option names; git's hooksPath becomes hookspath
custom = cfg.get("core", "hookspath", fallback="").strip()
if custom:
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
# Validate the resolved path stays within the repository root
# to prevent supply-chain attacks via malicious core.hooksPath values
try:
p.resolve().relative_to(root.resolve())
except ValueError:
pass # Path escapes repo root; fall through to default .git/hooks
else:
p.mkdir(parents=True, exist_ok=True)
return p
except (configparser.Error, OSError) as exc:
# Narrow the exception (PR747-NEW-2): a bare `except Exception: pass`
# was hiding tampering signals (corrupt .git/config, permission flips
# by another tool). Surface them on stderr instead of silently
# falling through to the default hooks directory.
print(
f"[graphify hooks] could not read core.hooksPath from "
f"{root / '.git' / 'config'}: {exc}",
file=sys.stderr,
)
# In a linked worktree .git is a file not a directory, so constructing
# root/.git/hooks directly fails. Ask git for the real hooks path instead.
# NOTE: do NOT pass --path-format=absolute — added in git 2.31; older git
# echoes it back as a literal argument, contaminating stdout and causing a
# phantom directory to be created (#907). git -C <root> already returns an
@@ -599,25 +327,13 @@ def _hooks_dir(root: Path) -> Path:
["git", "-C", str(root), "rev-parse", "--git-path", "hooks"],
capture_output=True, text=True,
)
if res.returncode != 0:
# git failing here is a real signal (corrupt .git/config, tampering,
# permission flips by another tool). Surface git's own stderr rather
# than silently falling through to the default hooks directory.
err = (res.stderr or "").strip()
print(
f"[graphify hooks] git could not resolve the hooks path for "
f"{root}: {err or f'git exited with code {res.returncode}'}",
file=sys.stderr,
)
else:
raw = res.stdout.strip()
# A valid hooks path can never contain newlines or NUL. Their presence
# means git echoed an unrecognised flag back (old git behaviour).
if 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
raw = res.stdout.strip()
# 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")):
d = (root / raw).resolve()
d.mkdir(parents=True, exist_ok=True)
return d
except (OSError, FileNotFoundError):
pass
d = root / ".git" / "hooks"
@@ -625,29 +341,12 @@ def _hooks_dir(root: Path) -> Path:
return d
def _install_hook(
hooks_dir: Path,
name: str,
script: str,
marker: str,
marker_end: str = "",
) -> str:
"""Install a single git hook, appending if an existing hook is present, or updating
an existing graphify block in-place."""
def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
"""Install a single git hook, appending if an existing hook is present."""
hook_path = hooks_dir / name
if hook_path.exists():
content = hook_path.read_text(encoding="utf-8")
if marker in content:
if marker_end and marker_end in content:
start_idx = content.find(marker)
end_idx = content.find(marker_end)
if start_idx != -1 and end_idx != -1 and end_idx >= start_idx:
end_idx += len(marker_end)
new_content = content[:start_idx] + script.rstrip() + content[end_idx:]
if new_content == content:
return f"already installed at {hook_path}"
hook_path.write_text(new_content, encoding="utf-8", newline="\n")
return f"updated existing {name} hook at {hook_path}"
return f"already installed at {hook_path}"
hook_path.write_text(content.rstrip() + "\n\n" + script, encoding="utf-8", newline="\n")
return f"appended to existing {name} hook at {hook_path}"
@@ -677,177 +376,6 @@ def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) ->
return f"graphify removed from {name} at {hook_path} (other hook content preserved)"
def _pinned_python() -> str:
"""Return sys.executable if its path is shell-safe, else an empty string.
Applies the same allowlist used in _PYTHON_DETECT: rejects any character
that is not a valid plain filesystem path character, preventing $(...),
backtick, double-quote, semicolon, etc. from being injected into generated
shell scripts or the merge-driver command line. The allowlist includes ':'
and '\\' so Windows paths (C:\\...) are accepted, and a plain space so
Windows profile paths (C:\\Users\\First Last\\...) are too — a space cannot
start a substitution or a new command, and every consumer quotes the value:
the hook scripts embed it as '$_PINNED' (single-quoted, then referenced as
"$_PINNED") and _register_merge_driver double-quotes it (#2166). Before that
a space rejected the whole path, so hooks installed under any Windows user
whose profile name contains a space silently pinned nothing. An empty return
means callers must fall back to the `graphify` launcher on PATH — safe
degradation.
"""
if re.search(r"[^a-zA-Z0-9/_.@: \\-]", sys.executable):
return ""
if _is_rotating_prefix(sys.executable):
return ""
return sys.executable
# ``~/snap/<app>/<revision>/`` — snap swaps <revision> on every package update and
# prunes the old tree, so anything under it is a path with an expiry date.
_ROTATING_PREFIX_RE = re.compile(r"/snap/[^/]+/(\d+|current)/")
def _is_rotating_prefix(path: str) -> bool:
"""True if `path` lives under a directory the packaging system rotates.
A pin is only worth writing if it will still resolve tomorrow. An interpreter
inside a snap revision will not: the revision number changes on update and the
old tree is removed, which silently kills every hook pinned to it — observed
across 15 repositories at once when an editor snap moved past its revision.
Returning "" here is the documented safe degradation: the hook falls through to
its other probes, including the uv-tools scan, which searches snap-confined
homes too.
"""
return bool(_ROTATING_PREFIX_RE.search(path.replace("\\", "/")))
def _merge_attr_line() -> str:
"""The .gitattributes line assigning the graphify merge driver to graph.json.
The graph lives under the configured output directory (graphify.paths,
GRAPHIFY_OUT env override). gitattributes patterns are repo-relative, so an
absolute output-dir override cannot be expressed there — fall back to the
default name in that case.
"""
from graphify.paths import GRAPHIFY_OUT
out = GRAPHIFY_OUT
if not out or Path(out).is_absolute() or "\\" in out:
out = "graphify-out"
return f"{out.rstrip('/')}/graph.json merge=graphify"
def _has_merge_attr(content: str) -> bool:
"""True if a (non-comment) `<...>graph.json ... merge=graphify` line exists."""
for raw in content.splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
fields = line.split()
if fields and fields[0].endswith("graph.json") and "merge=graphify" in fields[1:]:
return True
return False
def _register_merge_driver(root: Path) -> str:
"""Register the graph.json union merge driver in git config + .gitattributes (#1902).
README and CHANGELOG 0.7.0 document `graphify merge-driver` as being set up
by `hook install`, but install never actually registered it. Writes go
through `git config` (never hand-edit .git/config — in a linked worktree the
effective config is not at root/.git/config). The interpreter is pinned the
same way the hook scripts pin it, so the driver works even when the graphify
launcher is not on PATH at merge time.
"""
import subprocess as _sp
pinned = _pinned_python()
if pinned:
# Double-quoted: the allowlist in _pinned_python() permits a space (Windows
# profile paths), and git runs this driver string through a shell, so an
# unquoted "C:\\Users\\First Last\\...\\python.exe" would split into two
# words and the driver would never run (#2166). The same allowlist keeps
# '$' and backticks out, so double quotes cannot introduce expansion.
driver = f'"{pinned}" -m graphify merge-driver %O %A %B'
else:
driver = "graphify merge-driver %O %A %B"
try:
for key, value in (
("merge.graphify.name", "graphify graph.json union merge"),
("merge.graphify.driver", driver),
):
_sp.run(
["git", "-C", str(root), "config", key, value],
check=True, capture_output=True, text=True,
)
except (OSError, _sp.CalledProcessError) as exc:
return f"not registered (git config failed: {exc})"
line = _merge_attr_line()
attrs = root / ".gitattributes"
if attrs.exists():
content = attrs.read_text(encoding="utf-8")
if _has_merge_attr(content):
return f"already registered ({line})"
# Never clobber other entries; preserve a trailing newline.
if content and not content.endswith("\n"):
content += "\n"
attrs.write_text(content + line + "\n", encoding="utf-8", newline="\n")
else:
attrs.write_text(line + "\n", encoding="utf-8", newline="\n")
return f"registered ({line})"
def _unregister_merge_driver(root: Path) -> str:
"""Remove the merge-driver git config keys and the .gitattributes line."""
import subprocess as _sp
for key in ("merge.graphify.name", "merge.graphify.driver"):
try:
# --unset exits nonzero if the key is absent; that is fine.
_sp.run(
["git", "-C", str(root), "config", "--unset", key],
capture_output=True, text=True,
)
except OSError:
pass
attrs = root / ".gitattributes"
if not attrs.exists():
return "not registered - nothing to remove."
content = attrs.read_text(encoding="utf-8")
kept = [
raw for raw in content.splitlines()
if not _has_merge_attr(raw)
]
if kept == content.splitlines():
return "gitattributes entry not found - nothing to remove."
if kept:
# Other entries survive; the file stays.
attrs.write_text("\n".join(kept) + "\n", encoding="utf-8", newline="\n")
return "removed from .gitattributes (other entries preserved)"
attrs.unlink()
return "removed (.gitattributes deleted - no other entries)"
def _merge_driver_status(root: Path) -> str:
"""Report whether the merge driver is registered (config + gitattributes)."""
import subprocess as _sp
try:
res = _sp.run(
["git", "-C", str(root), "config", "--get", "merge.graphify.driver"],
capture_output=True, text=True,
)
cfg_ok = res.returncode == 0 and bool(res.stdout.strip())
except OSError:
cfg_ok = False
attrs = root / ".gitattributes"
attr_ok = attrs.exists() and _has_merge_attr(attrs.read_text(encoding="utf-8"))
if cfg_ok and attr_ok:
return "registered"
if cfg_ok:
return "partially registered (git config set, .gitattributes line missing)"
if attr_ok:
return "partially registered (.gitattributes line set, git config missing)"
return "not registered"
def _user_hooks_dir(hooks_dir: Path) -> Path:
"""Return the user-editable hooks directory.
@@ -869,26 +397,33 @@ def install(path: Path = Path(".")) -> str:
hooks_dir = _user_hooks_dir(_hooks_dir(root))
cfg = _load_graphifyrc(root)
viz_limit = cfg.get("viz_node_limit")
if viz_limit is not None:
# Use the `:-` default form (like GRAPHIFY_MAX_WORKERS below) so an
# explicit `GRAPHIFY_VIZ_NODE_LIMIT=... git commit` still wins over the
# baked project default — persisting config must not clobber a per-run
# override.
viz_export = f'export GRAPHIFY_VIZ_NODE_LIMIT="${{GRAPHIFY_VIZ_NODE_LIMIT:-{viz_limit}}}"\n'
else:
viz_export = ""
# Pin the current interpreter so the hook works even when the graphify
# launcher is not on PATH at git-trigger time (uv tool / pipx isolation).
# sys.executable is the Python running this very install command, so it is
# always the correct isolated-venv interpreter. The placeholder is replaced
# in both scripts before writing; the allowlist in _PYTHON_DETECT strips any
# characters unsafe in a shell path, and import-verification catches a stale
# pinned path so it safely falls through to the dynamic detection.
# Apply the same allowlist used in _PYTHON_DETECT for all other probes.
# This rejects any character that is not a valid plain filesystem path
# character, preventing $(...), backtick, double-quote, semicolon, etc.
# from being injected into the generated shell scripts. The allowlist
# includes ':' and '\' so Windows paths (C:\...) are accepted.
import re as _re
_safe = sys.executable
if _re.search(r"[^a-zA-Z0-9/_.@:\\-]", _safe):
# Path contains characters outside the allowlist (spaces, quotes, etc.).
# Embed an empty string so the pinned probe is skipped and the hook
# falls through to the dynamic detection — safe degradation.
_safe = ""
pinned = _safe
hook = _HOOK_SCRIPT.replace("__PINNED_PYTHON__", pinned)
checkout = _CHECKOUT_SCRIPT.replace("__PINNED_PYTHON__", pinned)
pinned = _pinned_python()
hook = _HOOK_SCRIPT.replace("__PINNED_PYTHON__", pinned).replace("__VIZ_LIMIT_EXPORT__", viz_export)
checkout = _CHECKOUT_SCRIPT.replace("__PINNED_PYTHON__", pinned).replace("__VIZ_LIMIT_EXPORT__", viz_export)
commit_msg = _install_hook(hooks_dir, "post-commit", hook, _HOOK_MARKER)
checkout_msg = _install_hook(hooks_dir, "post-checkout", checkout, _CHECKOUT_MARKER)
commit_msg = _install_hook(hooks_dir, "post-commit", hook, _HOOK_MARKER, _HOOK_MARKER_END)
checkout_msg = _install_hook(hooks_dir, "post-checkout", checkout, _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
merge_msg = _register_merge_driver(root)
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}\nmerge driver: {merge_msg}"
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
def uninstall(path: Path = Path(".")) -> str:
@@ -900,9 +435,8 @@ def uninstall(path: Path = Path(".")) -> str:
hooks_dir = _user_hooks_dir(_hooks_dir(root))
commit_msg = _uninstall_hook(hooks_dir, "post-commit", _HOOK_MARKER, _HOOK_MARKER_END)
checkout_msg = _uninstall_hook(hooks_dir, "post-checkout", _CHECKOUT_MARKER, _CHECKOUT_MARKER_END)
merge_msg = _unregister_merge_driver(root)
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}\nmerge driver: {merge_msg}"
return f"post-commit: {commit_msg}\npost-checkout: {checkout_msg}"
def status(path: Path = Path(".")) -> str:
@@ -911,44 +445,13 @@ def status(path: Path = Path(".")) -> str:
if root is None:
return "Not in a git repository."
hooks_dir = _user_hooks_dir(_hooks_dir(root))
# status is a read-only diagnostic: a malformed .graphifyrc must not turn it
# into a traceback. Report the config problem and continue with no limit.
try:
cfg = _load_graphifyrc(root)
except ValueError as exc:
cfg = {}
print(f" warning: {exc}")
cfg_limit = cfg.get("viz_node_limit")
def _check(name: str, marker: str) -> str:
p = hooks_dir / name
if not p.exists():
return "not installed"
text = p.read_text(encoding="utf-8")
if marker not in text:
return "not installed (hook exists but graphify not found)"
if cfg_limit is not None:
# Baked as `"${GRAPHIFY_VIZ_NODE_LIMIT:-<n>}"` so a per-run override
# wins; match the default <n>, and still accept the older bare
# `"<n>"` form from hooks installed before that change.
m = re.search(
r'export GRAPHIFY_VIZ_NODE_LIMIT="(?:\$\{GRAPHIFY_VIZ_NODE_LIMIT:-(\d+)\}|(\d+))"',
text,
)
installed_limit = int(m.group(1) or m.group(2)) if m else None
if installed_limit != cfg_limit:
return (
f"installed (out of date: hook has limit "
f"{installed_limit if installed_limit is not None else 'unset'}, "
f".graphifyrc has {cfg_limit})"
)
return "installed"
return "installed" if marker in p.read_text(encoding="utf-8") else "not installed (hook exists but graphify not found)"
commit = _check("post-commit", _HOOK_MARKER)
checkout = _check("post-checkout", _CHECKOUT_MARKER)
merge = _merge_driver_status(root)
res = f"post-commit: {commit}\npost-checkout: {checkout}\nmerge driver: {merge}"
if cfg_limit is not None:
res += f"\nviz node limit: {cfg_limit}"
return res
return f"post-commit: {commit}\npost-checkout: {checkout}"
-93
View File
@@ -1,93 +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: iterate ``casefold`` then NFKC-normalize to a fixpoint (casefold can
*expand* a character into a base letter plus a combining mark — ``İ`` -> ``i`` +
U+0307 — and NFKC then recomposes what can be recomposed; because the two do not
commute and neither is a fixpoint of the other, a single pass is not
caseless-stable), then 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, then
strip leading/trailing underscores.
Casefolding runs BEFORE the non-word filter, not after. With it last, the
combining marks casefold introduces were never filtered: ``İslemYap`` produced
``i̇slemyap`` — an id containing U+0307, which is not a ``\\w`` character — and a
second pass collapsed it to ``i_slemyap``, so the function was not idempotent
and the builder's re-normalization disagreed with the extractor's ``make_id``
for any Turkish identifier (#2614).
Casefolding runs in a FIXPOINT LOOP, not once. A single ``NFKC(casefold(...))``
left ``normalize_id(s) != normalize_id(s.casefold())`` for some combining-mark
sequences (Greek ypogegrammeni U+0345 followed by a combining accent):
pre-casefolding turns U+0345 into ``ι``, which NFKC composes with the accent into
a precomposed char the single pass never reached. Iterating to a fixpoint —
casefold first, on the raw input — makes the result caseless-stable regardless of
how many times the caller has already casefolded.
"""
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.
Guarantees, all enforced by tests:
- Idempotent: ``normalize_id(normalize_id(s)) == normalize_id(s)``.
- The result contains only ``\w`` characters and ``_``.
- Caseless-stable: ``normalize_id(s) == normalize_id(s.casefold())``.
casefold and NFKC do not commute, and neither is a fixpoint of the other:
casefolding a char can expand it into a base letter plus a combining mark
(``İ`` -> ``i`` + U+0307), and NFKC can then recompose that mark with an
adjacent one into a different precomposed char. A single ``NFKC(casefold(...))``
pass therefore left ``normalize_id(s) != normalize_id(s.casefold())`` for some
combining-mark sequences (e.g. Greek ypogegrammeni U+0345 followed by a
combining accent): pre-casefolding turned U+0345 into ``ι`` which NFKC then
composed with the accent, reaching a form the single-pass recipe never saw.
So iterate ``casefold`` then ``NFKC`` to a fixpoint (casefold FIRST, on the
raw input, so a caller that pre-casefolds lands on the same fixpoint). The
loop is bounded — Unicode caseless folding converges in one or two steps —
with a hard cap as a termination guard. Only then apply the ``[^\w]+`` filter,
so every combining mark casefold introduced has been fully normalized before
it is filtered (#2614 and its combining-mark follow-on).
"""
cur = s
for _ in range(6):
nxt = unicodedata.normalize("NFKC", cur.casefold())
if nxt == cur:
break
cur = nxt
cur = re.sub(r"[^\w]+", "_", cur, flags=re.UNICODE)
cur = re.sub(r"_+", "_", cur)
return cur.strip("_")
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))
+2 -29
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import json
import re
import uuid
import urllib.error
import urllib.parse
from datetime import datetime, timezone
@@ -269,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,
@@ -278,33 +275,19 @@ 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)
now = datetime.now(timezone.utc)
slug = re.sub(r"[^\w]", "_", question.lower())[:50].strip("_")
# A second-granularity stamp plus a 50-char slug is not unique: two saves in
# the same second whose questions share a prefix resolve to one path, and the
# later write_text silently replaces the earlier one (#3301). The short uuid
# makes every save its own file; the query_ prefix and .md suffix are kept.
filename = f"query_{now.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}_{slug}.md"
filename = f"query_{now.strftime('%Y%m%d_%H%M%S')}_{slug}.md"
frontmatter_lines = [
"---",
@@ -313,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("---")
@@ -330,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]
-2375
View File
File diff suppressed because it is too large. Load diff
+273 -1921
View File
File diff suppressed because it is too large. Load diff
-311
View File
@@ -1,311 +0,0 @@
"""Deterministic package-manifest ingestion (#1377).
Package manifests (``apm.yml``, ``pyproject.toml``, ``Cargo.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",
"cargo.toml": "cargo",
"go.mod": "go",
"pom.xml": "maven",
}
_MAX_MANIFEST_BYTES = 2_000_000 # 2 MB cap — manifests are small; this rejects junk
_TOMLI_REQUIRED = (
"Package-manifest ingestion on Python < 3.11 needs tomli. "
"Install with: pip install 'tomli' "
"(or reinstall graphifyy, which declares tomli for python_version < '3.11')."
)
def _load_toml_module():
"""Return a tomllib-compatible module, or raise ImportError (#3283).
Returning ``None`` used to look identical to a virtual workspace root with
nothing to emit, so missing ``tomli`` on Python 3.10 silently dropped every
``Cargo.toml`` / ``pyproject.toml``. Raise instead: the caller
(``extract_package_manifest``) surfaces this as a visible per-manifest error
rather than dropping the file silently. In practice the runtime ``tomli``
dependency (python_version < '3.11') keeps this path unreachable for a
standard install.
"""
try:
import tomllib as _toml # type: ignore[import-not-found]
return _toml
except ImportError:
try:
import tomli as _toml # type: ignore[import-not-found,no-redef]
return _toml
except ImportError as exc:
raise ImportError(_TOMLI_REQUIRED) from exc
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:``/``version:`` plus a simple ``dependencies:`` block (list items or
a name map)."""
name = None
version = 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
# `version` is part of the manifest contract the YAML path already
# returns; dropping it here made a package node lose its version
# on every machine without PyYAML installed.
m = re.match(r'^version:\s*["\']?([^"\'\s#]+)', line)
if m:
version = 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": version, "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:
_toml = _load_toml_module()
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_cargo(text: str) -> dict | None:
"""Cargo.toml: name/version from ``[package]``, runtime deps from
``[dependencies]`` plus every ``[target.<cfg>.dependencies]`` table (mirrors
``_parse_pyproject``'s runtime-only scope; dev-/build-dependencies excluded)."""
_toml = _load_toml_module()
data = _toml.loads(text)
pkg = data.get("package", {}) if isinstance(data.get("package"), dict) else {}
name = pkg.get("name")
# A virtual workspace root (``[workspace]``, no ``[package]``) declares no
# package of its own — emit nothing rather than a fabricated node. ``name`` is
# never workspace-inheritable in Cargo, but guard on the type anyway.
if not isinstance(name, str) or not name:
return None
# ``version`` may be workspace-inherited (``version.workspace = true``), which
# parses to a table; keep only a concrete string version.
version = pkg.get("version")
if not isinstance(version, str):
version = None
# A dependency value is a bare version string or an inline table; either way
# _coerce_deps keys it by the dependency NAME (the table/map key).
deps = _coerce_deps(data.get("dependencies"))
# Platform-conditional deps live under ``[target.<cfg>.dependencies]``; fold
# them in so a crate whose deps are entirely cfg-gated still emits its edges.
targets = data.get("target")
if isinstance(targets, dict):
for cfg in targets.values():
if isinstance(cfg, dict):
deps += _coerce_deps(cfg.get("dependencies"))
return {"name": name, "version": version, "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,
"cargo": _parse_cargo,
"go": _parse_gomod,
"maven": _parse_pom,
}
-231
View File
@@ -1,231 +0,0 @@
"""Cross-file resolution of code-span mentions in Markdown documents.
``extract_markdown`` reports every inline code span that reads as a symbol
name (``Widget``, ``render()``, ``pkg.Widget``, ``src/mod.py::Widget::render``)
as a ``raw_calls`` entry tagged ``language: "markdown"`` instead of guessing a
target id: the symbol is defined in some other file, and only once every file
is extracted and the id-remap passes have run can the mention be matched to
the node that actually exists. Riding the ``raw_calls`` channel means those
passes rewrite the mention's ``caller_nid`` alongside every other raw call,
and the extraction cache round-trips it for free.
This resolver runs from the language-resolver registry (see
``resolver_registry``) with the merged corpus in hand and turns each mention
into a ``references`` edge from the heading (or page) that cites the symbol
to the code node that defines it:
* a path-qualified mention resolves against the cited file only. The file is
matched by its path relative to the document, then as a segment-aligned
suffix of a scanned file, and must be unique; the symbol chain is walked
through ``contains`` / ``method`` edges so ``mod.py::Widget::render`` is
the ``render`` owned by ``Widget``. The document names the file and the
symbol verbatim, so the edge is EXTRACTED;
* a bare mention resolves only when exactly one callable or type in the
corpus carries that label (case-sensitive; language built-ins excluded).
Only nodes the extractors marked ``_callable`` qualify, for the reason the
indirect-call pass gives (#1566): a by-name match must land on a real
function, method or class, never on a same-named data symbol such as a
JSON key. A dotted mention (``pkg.Widget``, ``Widget.render``) keeps its
qualifiers, and a candidate survives only when every qualifier is a label
on its ``contains`` / ``method`` owner chain or a segment (or stem) of its
source path: ``time.sleep`` never lands on a repo's own ``sleep``, and
``Widget.render`` picks the ``render`` that ``Widget`` owns. No other
tie-breaking: an ambiguous name is a guess, and a guess is not an edge.
The match is INFERRED (0.95, a named cross-file reference).
An explicit relative cite (``./`` or ``../``) resolves against the document's
directory only; it never falls through to the suffix rule, so a path that
escapes the corpus cannot land on an unrelated copy of the file elsewhere.
The shared cross-file call pass in ``extract`` skips ``markdown`` raw calls,
so a mention never surfaces as a ``calls`` edge.
"""
from __future__ import annotations
import os
import re
from typing import Any
from graphify.extractors.base import _LANGUAGE_BUILTIN_GLOBALS
MARKDOWN_MENTION_SUFFIXES = frozenset({".md", ".mdx", ".qmd", ".skill"})
_CONTAINMENT_RELATIONS = frozenset({"contains", "method"})
#: Leading ``./`` and ``../`` segments of a cited path, stripped as whole
#: segments (``lstrip("./")`` would eat the dot of ``.github/...``).
_RELATIVE_PREFIX_RE = re.compile(r"^(\.\.?/)+")
def _symbol_label(node: dict[str, Any]) -> str:
"""A node's label as a document would write it: no ``()``, no leading dot."""
return str(node.get("label", "")).strip("()").lstrip(".")
def _is_file_node(node: dict[str, Any]) -> bool:
label = str(node.get("label", ""))
source_file = str(node.get("source_file", ""))
return bool(source_file) and label == os.path.basename(source_file)
def _posix(path: str) -> str:
return path.replace("\\", "/")
def _match_cited_file(cited: str, doc_file: str, source_files: set[str]) -> str | None:
"""The scanned source file a ``path::Name`` mention names, or None.
Tries the path relative to the citing document first (``../src/mod.py``
from ``docs/guide.md``), then an exact match, then a unique
segment-aligned suffix (``src/mod.py`` naming ``/repo/src/mod.py``). A
cite that is explicitly relative (``./x`` or ``../x``) stops after the
first step: it names one location, and a suffix match elsewhere would be a
different file.
"""
cited_posix = _posix(cited)
doc_dir = os.path.dirname(doc_file)
relative = _posix(os.path.normpath(os.path.join(doc_dir, cited_posix)))
if relative in source_files:
return relative
if cited_posix.startswith(("./", "../")):
return None
if cited_posix in source_files:
return cited_posix
stripped = _RELATIVE_PREFIX_RE.sub("", cited_posix)
matches = [sf for sf in source_files
if sf == stripped or sf.endswith("/" + stripped)]
return matches[0] if len(matches) == 1 else None
def _evidence(node_id: str, nodes_by_id: dict[str, dict[str, Any]],
parents: dict[str, set[str]]) -> set[str]:
"""Labels a dotted mention may qualify ``node_id`` with.
The labels of every node on its ``contains`` / ``method`` owner chain
(``Widget`` for ``Widget.render``) plus each segment and stem of its
source path (``pkg`` and ``mod`` for ``pkg.mod.Widget``).
"""
evidence: set[str] = set()
frontier = {node_id}
seen: set[str] = set()
while frontier:
nid = frontier.pop()
if nid in seen:
continue
seen.add(nid)
owners = parents.get(nid, set())
for owner in owners:
node = nodes_by_id.get(owner)
if node is not None:
evidence.add(_symbol_label(node))
frontier |= owners
node = nodes_by_id.get(node_id, {})
for segment in _posix(str(node.get("source_file", ""))).split("/"):
if segment:
evidence.add(segment)
evidence.add(os.path.splitext(segment)[0])
return evidence
def _markdown_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", []) or []:
if isinstance(rc, dict) and rc.get("language") == "markdown":
calls.append(rc)
return calls
def resolve_markdown_mentions(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Turn ``language: "markdown"`` raw calls into ``references`` edges in place."""
mentions = _markdown_raw_calls(per_file)
if not mentions:
return
code_nodes = [
n for n in all_nodes
if n.get("id") and n.get("file_type") == "code" and not _is_file_node(n)
]
by_label: dict[str, list[str]] = {}
by_file: dict[str, dict[str, list[str]]] = {}
for n in code_nodes:
label = _symbol_label(n)
if not label:
continue
if n.get("_callable"):
by_label.setdefault(label, []).append(n["id"])
source_file = _posix(str(n.get("source_file", "")))
if source_file:
by_file.setdefault(source_file, {}).setdefault(label, []).append(n["id"])
source_files = set(by_file)
parents: dict[str, set[str]] = {}
for e in all_edges:
if e.get("relation") in _CONTAINMENT_RELATIONS:
parents.setdefault(str(e.get("target")), set()).add(str(e.get("source")))
nodes_by_id = {n["id"]: n for n in all_nodes if n.get("id")}
node_ids = set(nodes_by_id)
existing = {
(e.get("source"), e.get("target"))
for e in all_edges if e.get("relation") == "references"
}
def _resolve_chain(file_labels: dict[str, list[str]], names: list[str]) -> str | None:
candidates = list(file_labels.get(names[-1], []))
for depth, owner_name in enumerate(reversed(names[:-1]), start=1):
owners = set(file_labels.get(owner_name, []))
narrowed = []
for c in candidates:
chain = {c}
for _ in range(depth):
chain = {p for nid in chain for p in parents.get(nid, ())}
if chain & owners:
narrowed.append(c)
candidates = narrowed
return candidates[0] if len(candidates) == 1 else None
for rc in mentions:
caller = str(rc.get("caller_nid", ""))
callee = str(rc.get("callee", "")).strip()
if not caller or not callee or caller not in node_ids:
continue
names = list(rc.get("qualifiers") or []) + [callee]
cited = rc.get("path")
if cited:
source_file = _match_cited_file(
str(cited), _posix(str(rc.get("source_file", ""))), source_files
)
if source_file is None:
continue
target = _resolve_chain(by_file[source_file], names)
confidence, score = "EXTRACTED", 1.0
else:
if callee in _LANGUAGE_BUILTIN_GLOBALS:
continue
qualifiers = set(names[:-1])
candidates = [
c for c in by_label.get(callee, [])
if qualifiers <= _evidence(c, nodes_by_id, parents)
]
target = candidates[0] if len(candidates) == 1 else None
confidence, score = "INFERRED", 0.95
if target is None or target == caller or (caller, target) in existing:
continue
existing.add((caller, target))
all_edges.append({
"source": caller,
"target": target,
"relation": "references",
"context": rc.get("context", ""),
"confidence": confidence,
"confidence_score": score,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
Loaded 100 of 686 files, more files were not shown because too many files have changed in this diff. Show more