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
774 changed files with 19644 additions and 162049 deletions

No files matched your search

-21
View File
@@ -1,21 +0,0 @@
# Code owners for graphify.
#
# Owners are automatically requested for review on pull requests that touch
# matching paths. This file is advisory review routing; it does not by itself
# block merges unless "Require review from Code Owners" is enabled in branch
# protection.
#
# See: https://docs.github.com/articles/about-code-owners
# Default owner for everything in the repo.
* @safishamsi
# Skill generation is roundtrip-sensitive (monolith sanctioned diffs); flag it.
/tools/skillgen/ @safishamsi
/graphify/skill*.md @safishamsi
/graphify/skills/ @safishamsi
# Release, security, and CI configuration.
/.github/workflows/ @safishamsi
/SECURITY.md @safishamsi
/RELEASING.md @safishamsi
-34
View File
@@ -1,34 +0,0 @@
labels: []
body:
- type: markdown
attributes:
value: |
Thanks for asking. Before posting, please check the
[docs](https://docs.graphify.com) and search existing
[discussions](https://github.com/Graphify-Labs/graphify/discussions)
and [issues](https://github.com/Graphify-Labs/graphify/issues) — your
question may already be answered. For real-time help, join the
[Discord](https://discord.gg/XDnKVpzdXB). If you have found a bug, please
open an issue instead so it can be tracked.
- type: textarea
id: question
attributes:
label: What are you trying to do?
description: Describe the goal and the question, not only the error.
validations:
required: true
- type: textarea
id: tried
attributes:
label: What have you tried?
description: Commands you ran, docs you read, and what happened.
validations:
required: false
- type: input
id: version
attributes:
label: graphify version and environment
description: Output of `graphify --version`, plus your OS and Python version.
placeholder: "graphify 0.9.70, macOS 15, Python 3.12"
validations:
required: false
-98
View File
@@ -1,98 +0,0 @@
name: Bug report
description: Report incorrect behavior, a crash, or a regression.
title: "[Bug]: "
labels:
- bug
body:
- type: markdown
attributes:
value: |
Please search existing issues first. Include the smallest reproducible example you can.
- type: checkboxes
id: checks
attributes:
label: Pre-flight checks
options:
- label: I have checked the Troubleshooting section in the README
required: true
- type: textarea
id: description
attributes:
label: What happened?
description: Describe the actual behavior and the behavior you expected.
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Steps to reproduce
description: Include commands, input files, and the smallest useful example.
render: shell
validations:
required: true
- type: textarea
id: output
attributes:
label: Error output or graph output
description: Paste the relevant traceback, diagnostic, or incorrect result.
render: text
validations:
required: true
- type: input
id: version
attributes:
label: Graphify version
placeholder: "e.g. 0.9.68"
- type: dropdown
id: os
attributes:
label: Operating System
options:
- macOS
- Linux
- Windows
- WSL
validations:
required: true
- type: dropdown
id: python
attributes:
label: Python Version
options:
- 3.10
- 3.11
- 3.12
- 3.13
validations:
required: true
- type: dropdown
id: install_method
attributes:
label: Installation Method
options:
- uv tool install (recommended)
- pipx
- pip
- built from source (git clone)
validations:
required: true
- type: textarea
id: environment
attributes:
label: Additional Environment Details
description: List any provider environment variables set (e.g., OPENAI_API_KEY) and whether a clean checkout reproduced the issue.
- type: textarea
id: additional
attributes:
label: Additional context
description: Add related files, screenshots, or links if they help explain the issue.
-14
View File
@@ -1,14 +0,0 @@
blank_issues_enabled: true
contact_links:
- name: Security policy
url: https://github.com/Graphify-Labs/graphify/security/policy
about: Please report vulnerabilities privately using the security policy.
- name: Discord community
url: https://discord.gg/XDnKVpzdXB
about: Join the Discord to ask questions and discuss ideas in real time.
- name: 📖 Documentation
url: https://docs.graphify.com
about: Check the docs (guides, command reference, integrations) before opening an issue.
- name: 🤝 Contributing guide
url: https://github.com/Graphify-Labs/graphify/blob/v8/CONTRIBUTING.md
about: Read the development and contribution guidelines before opening a pull request.
@@ -1,73 +0,0 @@
name: Feature request
description: Suggest an improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
body:
- type: markdown
attributes:
value: |
Please search existing issues first and describe the user problem before proposing an implementation.
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do that Graphify cannot do today?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the expected behavior, command, API, or workflow.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: What other approaches or workarounds did you consider?
- type: dropdown
id: area
attributes:
label: Area
options:
- Extraction or language support
- Graph building or querying
- CLI or installation
- Skills or assistant integrations
- Documentation
- Performance
- Security
- Developer experience or CI
validations:
required: true
- type: dropdown
id: pr
attributes:
label: Are you willing to submit a PR?
options:
- Yes, I can work on this
- Yes, but I will need guidance
- No, I just wanted to request it
validations:
required: true
- type: textarea
id: compatibility
attributes:
label: Compatibility / behavior impact
description: Does this affect node/edge IDs, cache semantics, graph.json schema, generated skills, MCP output, or incremental updates?
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional context
description: Add examples, links, or sample input where useful.
-39
View File
@@ -1,39 +0,0 @@
## What does this PR do?
<!-- Describe the problem and the change. Link the relevant issue when one exists. -->
## Type of change
- [ ] Bug fix
- [ ] New feature
- [ ] Documentation
- [ ] Tests or CI
- [ ] Refactor
- [ ] Security fix
## Verification & Invariants
<!-- What invariant does this code protect? How do you prove your change doesn't break it? What generated or persisted state could your change invalidate? -->
- [ ] **Read** the [CONTRIBUTING.md](../CONTRIBUTING.md) guide.
- [ ] **Reproduced** the issue and identified the invariant.
- [ ] Made the **smallest fix** necessary.
- [ ] Added a **regression test** (if bug fix) or isolated boundary test.
- [ ] Kept the PR description **synchronized** with the final implementation.
- [ ] Documented any **limitations / unsupported cases** explicitly.
## How was this tested?
<!-- List the commands you actually ran. Mention environment isolation if touching provider paths. -->
```text
```
## Graphify-specific checklist
- [ ] I updated generated skill artifacts (`uv run python -m tools.skillgen --bless`) when changing their source fragments.
- [ ] I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
- [ ] I reviewed changes for security implications (no unsafe interpolation into shell/Python).
- [ ] I confirmed no API keys or local-only graph data are included.
- [ ] (If applicable) I disclosed AI authorship in my commit messages.
+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
-56
View File
@@ -1,56 +0,0 @@
name: Welcome and invite to Discord
# Posts a friendly comment when someone opens an issue or a pull request,
# pointing them to Discord (real-time) and GitHub Discussions (longer-form).
# pull_request_target is used so the token can comment on PRs from forks;
# the job only posts a comment and never checks out or runs PR code, so this
# is safe.
on:
issues:
types: [opened]
pull_request_target:
types: [opened]
permissions:
issues: write
pull-requests: write
jobs:
welcome:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const isPR = context.eventName === 'pull_request_target';
const payload = isPR ? context.payload.pull_request : context.payload.issue;
const author = payload.user.login;
const number = payload.number;
// Don't comment on bot-opened issues/PRs (dependabot, etc.).
if (author.endsWith('[bot]')) {
return;
}
const discord = 'https://discord.gg/XDnKVpzdXB';
const discussions = 'https://github.com/Graphify-Labs/graphify/discussions';
const body = isPR
? `Thanks for the pull request, @${author}. A maintainer will review it soon.\n\n`
+ `Want to talk it through while it is in review? Come join us on our [Discord server](${discord}). `
+ `For longer-form discussion there is also [GitHub Discussions](${discussions}).\n\n`
+ `A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, `
+ `and that the change keeps extraction deterministic.`
: `Thanks for opening this issue, @${author}. A maintainer will take a look soon.\n\n`
+ `If you would like to discuss it in real time, come say hi on our [Discord server](${discord}). `
+ `For longer-form questions and ideas there is also [GitHub Discussions](${discussions}).\n\n`
+ `To help us triage, please make sure the report includes what you expected, what actually happened, `
+ `and the steps (and a small sample) to reproduce it.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: number,
body,
});
-3
View File
@@ -37,6 +37,3 @@ scripts/llm.py
scripts/benchmark_kimi*.json
scripts/benchmark_kimi*.py
paper/
# macOS Finder metadata
.DS_Store
+1 -1
View File
@@ -3,6 +3,6 @@
This project has a graphify knowledge graph at graphify-out/.
Rules:
- When working on Graphify itself, use the repository's existing Graphify guidance. For codebase questions, prefer scoped graph queries where available; use the report for broad orientation. Do not use the graph as evidence when the task concerns the graph's correctness itself.
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
+22 -45
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. While designed to minimize shared state, some stages (like extractors) rely on ambient module-level state around the active scan root. 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`.
@@ -87,22 +70,16 @@ All external input passes through `graphify/security.py` before use:
- URLs → `validate_url()` (http/https only) + `_NoFileRedirectHandler` (blocks file:// redirects)
- Fetched content → `safe_fetch()` / `safe_fetch_text()` (size cap, timeout)
- Graph file paths → `validate_graph_path()` (must resolve inside `graphify-out/`)
- Node labels → `sanitize_label()` (strips control chars, caps 256 chars)
- Node labels → `sanitize_label()` (strips control chars, caps 256 chars, HTML-escapes)
See `SECURITY.md` for the full threat model.
## Testing
`analyze.suggest_questions()` interleaves candidates across question types before
applying its result limit (seven by default). This keeps ambiguous relationships
from hiding bridge, inferred-relationship, isolation, and low-cohesion signals.
The existing candidate order within each type is preserved; if the limit is smaller
than the number of available types, their generation order determines priority.
One test file per module under `tests/`. Run with:
```bash
pytest tests/ -q
```
The test suite is designed to avoid network access and uncontrolled filesystem effects; most tests are isolated with temporary directories and environment fixtures.
All tests are pure unit tests - no network calls, no file system side effects outside `tmp_path`.
-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>
```
+1 -1229
View File
File diff suppressed because it is too large. Load diff
-73
View File
@@ -1,73 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, including the GitHub repository, Discord server, and any other channels managed by Graphify Labs. It also applies when an individual is officially representing the community in public spaces.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the project maintainers at safi@graphify.com, or by directly messaging a Community Leader on the [Graphify Discord server](https://discord.gg/XDnKVpzdXB).
All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html).
-151
View File
@@ -1,151 +0,0 @@
# Contributing to Graphify
Graphify is a graph-building system whose correctness depends on preserving provenance, deterministic extraction, and safe incremental updates. A contribution is not complete because the new code works on the happy path; it is complete when the relevant invariant is explicit, tested, and preserved across rebuilds.
## Before You Start
- Read [ARCHITECTURE.md](ARCHITECTURE.md)
- Read [SECURITY.md](SECURITY.md) when relevant
- Understand `v8` is the active development branch
- Use `graphify-out/GRAPH_REPORT.md` for repository orientation
## What We Value
1. **Preserve correctness, not merely successful execution**. A failed, partial, smaller, or differently keyed extraction must not overwrite valid persisted state or poison incremental caches.
2. **Preserve provenance; incidental richness is not evidence**. A real source-backed record must not lose to a richer sourceless stub. A location without a corresponding source file is not sufficient provenance.
3. **Keep deterministic extraction deterministic**. AST extraction, symbol identity, traversal order, merge behavior, and other structural passes must not depend on filesystem ordering, ambient environment state, network calls, or nondeterministic model output.
4. **Keep inference visibly separate from extracted fact**. Never turn uncertainty into false certainty just because a richer result looks better. Preserve the distinction between extracted fact, inference, and ambiguity.
5. **Prefer fail-closed behavior over guessed relationships**.
6. **Treat persistent graph/cache state as data that can be corrupted**.
7. **Make bug fixes prove the old failure with a regression test**. Demonstrate the old failure, not merely exercise the new code.
8. **Keep PRs narrow and reviewable**. Small, auditable diffs beat clever broad fixes.
9. **Document heuristic boundaries and unsupported cases**.
10. **Never hand-edit generated artifacts**. Edit the source fragment, run the generator, and run the corresponding verification checks.
11. **Do not let ambient environment state affect tests**. Tests must be deterministic with respect to the contributor's shell environment.
12. **Treat paths, source text, model output, URLs, and generated commands as untrusted**. Never construct shell commands or Python source by interpolating free text.
13. **Check cross-platform behavior when touching filesystem/process/install logic**. A change is not considered cross-platform-safe merely because it passes on Linux.
14. **Update documentation when behavior or invariants change**. Documentation is part of the behavior contract.
15. **Use Graphify itself to understand Graphify**, except when the graph is the thing being debugged.
## Repository Architecture
- **Pipeline**: `detect()` → `extract()` → `build()` → `cluster()` → `analyze()` → `report.generate()` → `export.to_*()`
- **Where extractors live**: `graphify/extractors/`
- **Generated skills vs source fragments**: Skill files in `graphify/` are generated from fragments in `tools/skillgen/`.
- **What is generated and what is authoritative**: `tools/skillgen/fragments/` is authoritative.
## Development Setup
```bash
# Fork and clone the repository
git clone https://github.com/<your-username>/graphify.git
cd graphify
git remote add upstream https://github.com/Graphify-Labs/graphify.git
git fetch upstream
git checkout -b my-feature-branch upstream/v8 # Always branch off upstream v8, never commit directly to v8
# Set up the environment
uv sync
uv run pre-commit install
# Run the test suite to confirm your setup
uv run pytest tests/ -q
# Run linters and type checkers before pushing
uv run ruff check .
uv run pyright
```
- **Python versions**: 3.10+
- **uv**: We use `uv` for dependency management.
## Working on the Codebase
- **Use graphify itself**: Before making non-trivial architectural changes, use `graphify query ...` to navigate the codebase rather than blind grepping. Do not use the graph as evidence when the task concerns the graph's own correctness.
- **Update graph after code changes**: `graphify update .`
- **Root/path invariants**: Paths resolve relative to the calling module or scan root.
- **Cache considerations**: Be aware of relative/absolute path caching across rebuilds.
- **Generated skill files**: Regenerate with `uv run python -m tools.skillgen --bless`. Never hand-edit the generated files directly.
- **Corpus boundaries**: Do not create a second interpretation of the corpus boundary. Reuse the existing detection/ignore semantics whenever another pass walks project files (e.g. `.graphifyignore`).
- **Cross-platform**: Windows portability is a first-class contribution concern. Path separators, symlinks, absolute/relative paths, hash seeds, and shell interpolation must work correctly on Windows.
## Making a Change
1. Find or create an issue
2. Reproduce
3. Identify invariant
4. Make smallest fix
5. Add regression test
6. Run targeted tests
7. Run full suite (`uv run pytest tests`)
8. Run lint/type checks (`uv run ruff check .`, `uv run pyright`)
9. Regenerate artifacts if you touched their sources (`uv run python -m tools.skillgen --bless`).
## Tests
- **pytest**: The primary test runner.
- **Fixture conventions**: New language extractors need fixtures under `tests/fixtures/` and tests in `tests/test_languages.py`.
- **Environment isolation**: Tests must not accidentally depend on the contributor's ambient environment. When writing backend/provider tests, explicitly isolate or clear environment variables (e.g., `OPENAI_API_KEY`, `OLLAMA_HOST`).
- **Deterministic tests**: Ensure tests don't rely on ambient state or ordering.
- **Regression-test expectations**: Test must fail on pre-fix and pass on post-fix.
## Language Extractors
- **Extractor module**: Defines logic for each language AST.
- **Dispatch table**: Registers the parser and language.
- **Tree-sitter dependency**: Use ASTs where possible.
- **Fixture**: Ensure comprehensive test cases in `tests/fixtures/`.
- **Cross-file resolution considerations**: Resolution stays local to AST paths.
## Generated Skills and Monoliths
- Source fragments are authoritative.
- Run skillgen (`uv run python -m tools.skillgen --bless`).
- Never casually edit generated artifacts.
- Sanctioned round-trip changes only.
- Preserve multiset checks.
## Data Integrity Rules
- **Zero-node guard**: Must run before writes.
- **Shrink guard**: Must not persist smaller corrupt graphs. (Note: forced writes can bypass this).
- `to_json` before report side effects.
- **Cache consistency**: Must be maintained across absolute/relative paths. (e.g., The Windows absolute-path issue taught us that earlier side effects that persist bad absolute-path entries into the semantic cache are still data loss, even if the final graph write passes the shrink guard).
- **Provenance**: Must be preserved.
- **Cross-file edges**: Must be preserved during incremental updates, even if node count is unchanged.
## Security
- Review [SECURITY.md](SECURITY.md).
- Any change touching generated skill instructions, shell commands, subprocesses, URL ingestion, path handling, prompts, or serialization must be reviewed as a security-sensitive change.
- Never interpolate untrusted content into shell/Python.
## Commit Messages
Use a conventional-commit prefix (e.g., `fix:`, `feat:`, `docs:`, `fix(extract):`) and make the subject describe the change. Explain why in the body when the change is non-trivial. Reference the relevant issue/PR.
- **AI Authorship Disclosure**: If an AI coding assistant materially contributed to the implementation, disclose it in the commit metadata according to the repository's authorship convention (e.g., `Co-Authored-By: Claude <noreply@anthropic.com>`). Do not attribute code to a model that did not contribute.
## Pull Requests
- One concern per PR.
- No unrelated changes.
- Describe problem / implementation / verification.
- List commands actually run.
- Document limitations / unsupported cases.
- Keep description synchronized with final implementation.
- Rebase/resolve conflicts before requesting final review.
## Issue Reports
### Bugs
Include exact version/commit, environment, minimal reproduction, expected vs actual, logs, graph/cache artifacts where relevant, and whether a clean checkout reproduced it.
### Feature Requests
Focus on the problem first, proposed behavior, alternatives, and compatibility considerations.
## Review Expectations
- Correctness, regression coverage, scope, determinism, provenance, security, and documentation.
## Release / Generated Artifacts
- **What gets regenerated**: Skill files via skillgen, HTML exports.
- **What should not be committed**: Local cache (`.graphify_cached.json`), generated node artifacts outside of the expected outputs.
## Getting Help
- **Discord**: Join the [Graphify Discord](https://discord.gg/XDnKVpzdXB) for questions and discussion.
- **Issues**: Search [existing issues](https://github.com/Graphify-Labs/graphify/issues) before opening a new one.
- **Discussions**: Use GitHub issues for bugs and feature requests, Discord for open-ended questions.
## Further Reading
- [README.md](README.md)
- [ARCHITECTURE.md](ARCHITECTURE.md)
- [SECURITY.md](SECURITY.md)
- [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)
- [RELEASING.md](RELEASING.md) (maintainers)
+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.
+108 -328
View File
@@ -1,65 +1,37 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" 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://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-blue" alt="License: Apache-2.0"/></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://docs.graphify.com"><img src="https://img.shields.io/badge/Docs-docs.graphify.com-0b7285?style=flat&logo=readthedocs&logoColor=white" alt="Docs"/></a>
<a href="https://smithery.ai/servers/graphify/graphify"><img src="https://img.shields.io/badge/Smithery-MCP%20server-5c4ee5?style=flat&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmZiI+PHBhdGggZD0iTTEyIDJMMiA3djEwbDEwIDUgMTAtNVY3eiIvPjwvc3ZnPg==" alt="Smithery"/></a>
<a href="https://discord.gg/XDnKVpzdXB"><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>Try the graphify platform free for 14 days: <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/
@@ -68,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
@@ -163,12 +79,10 @@ curl -LsSf https://astral.sh/uv/install.sh | sh
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
The official source repository is [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
**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:
@@ -201,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 |
|----------|----------------|
@@ -233,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 |
|---|---|---|
@@ -259,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]"` |
@@ -272,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
@@ -306,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.
@@ -345,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 .vh .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` |
@@ -361,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
@@ -413,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
@@ -430,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
@@ -450,45 +321,21 @@ dist/
## Team setup
For users building a team graph, the `graphify-out/` directory is gitignored by default. If your team wants to share a graph, you should **explicitly force-add only the queryable products** so your teammates can consume them:
`graphify-out/` is meant to be committed to git so everyone on the team starts with a map.
*(Note: If you are contributing to the Graphify repository itself, do not commit your local `graphify-out/` at all unless it's a specific test fixture).*
**Recommended git commands to share a graph (you only need to force-add once; git will track future changes normally):**
```bash
git add -f graphify-out/graph.json
git add -f graphify-out/GRAPH_REPORT.md
# git add -f graphify-out/wiki/ # optional: if using the wiki export
# git add -f graphify-out/obsidian/ # optional: if using the Obsidian export
**Recommended `.gitignore` additions:**
```
graphify-out/cost.json # local only
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
```
> `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.
The remaining `graphify-out/` files stay machine-local and should **not** be force-added: `.graphify_root` and `.graphify_python` (absolute paths to this machine's scan root and interpreter), `.graphify_analysis.json`, the AST cache under `graphify-out/cache/`, and the `needs_update` flag. A teammate who pulls the shared `graph.json` can query it immediately; running `graphify update` re-anchors the committed `manifest.json` and rebuilds only what changed on their machine.
### 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.
---
@@ -501,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
@@ -513,19 +359,6 @@ python -m graphify.serve graphify-out/graph.json --transport http --host 0.0.0.0
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`, `list_prs`, `get_pr_impact`, `triage_prs`.
### One-click install (VS Code · Smithery)
Prefer not to edit MCP config by hand? Register the graphify MCP server in one step. Run `/graphify` first so a `graphify-out/graph.json` exists in the workspace; the server reads it on launch.
[![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_graphify_MCP-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=graphify&config=%7B%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22--from%22%2C%22graphifyy%5Bmcp%5D%22%2C%22graphify-mcp%22%5D%7D)
The button adds a `graphify` server that launches with `uvx --from "graphifyy[mcp]" graphify-mcp` (no API key, no prior install). Or install via [Smithery](https://smithery.ai/servers/graphify/graphify) for Claude, Cursor, VS Code, and other clients:
```bash
# pick your client (claude, cursor, vscode, windsurf, ...)
npx -y @smithery/cli install graphify/graphify --client claude
```
### Shared HTTP server
`--transport stdio` (the default) spawns one local server per developer. `--transport http` serves the same tools over the MCP Streamable HTTP transport, so a single shared process can serve the graph for the whole team — clients point their IDE MCP config at `http://<host>:8080/mcp` instead of running graphify locally.
@@ -563,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`) |
@@ -582,59 +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_NO_AUTO_REFRESH` | Set to `1` to stop the CLI from refreshing installed skills that are older than the package after an upgrade | optional — refresh is on by default |
| `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.
@@ -642,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
@@ -657,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
@@ -675,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
@@ -689,18 +479,10 @@ ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
**Skill version mismatch warning in your IDE**
Your installed graphify version is different from the skill file. After an upgrade, the first `graphify` command refreshes every installed skill that is older than the package, on all platforms at once, and keeps a locally edited `SKILL.md` as `SKILL.md.bak`. Set `GRAPHIFY_NO_AUTO_REFRESH=1` to turn this off. A skill it can't refresh safely keeps the warning: one newer than the package, or a directory that two installers share (for example Copilot and `graphify vscode install`). Reinstall that platform by hand:
Your installed graphify version is different from the skill file. Update:
```bash
uv tool upgrade graphifyy
graphify install --platform <name> # 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/
graphify install # overwrites the skill file
```
---
@@ -711,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
@@ -737,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
@@ -782,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)
@@ -797,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
@@ -806,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
@@ -826,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
@@ -850,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.
@@ -866,49 +626,69 @@ graphify label ./my-project --backend=openai --model gpt-4o # force a specific
## Learn more
- [docs.graphify.com](https://docs.graphify.com) — full documentation: guides, command reference, and integrations
- [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/enterprise) 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)
---
## Contributing
<details>
<summary>Contributing</summary>
Contributions are welcome. See **[CONTRIBUTING.md](CONTRIBUTING.md)** for the development setup, the test and CI-parity commands, the git workflow, and what makes a strong contribution (worked examples and extraction bug reports are the most useful). Architecture and how to add a language: [ARCHITECTURE.md](ARCHITECTURE.md).
### Development setup
New here? Say hi on [Discord](https://discord.gg/XDnKVpzdXB) or in [GitHub Discussions](https://github.com/Graphify-Labs/graphify/discussions).
The project uses [uv](https://docs.astral.sh/uv/) for dev workflow. Install it once, then:
---
```bash
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v8 # active development branch
## Contributors
# Create the project venv and install graphify + all extras + the dev group
# (pytest). uv installs the dev dependency group by default; pass --no-dev to
# skip it.
uv sync --all-extras
```
<a href="https://github.com/Graphify-Labs/graphify/graphs/contributors">
<img src="https://contrib.rocks/image?repo=Graphify-Labs/graphify" alt="graphify contributors" />
</a>
Verify the editable install:
```bash
uv run graphify --version
uv run python -c "import graphify; print(graphify.__file__)"
```
Made with [contrib.rocks](https://contrib.rocks).
### Running tests
---
```bash
uv run pytest tests/ -q # run the full suite
uv run pytest tests/test_extract.py -q # one module
uv run pytest tests/ -q -k "python" # filter by name
```
## Community and links
> 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.
<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/XDnKVpzdXB"><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>
### Git workflow
- Active development happens on the `v8` branch.
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
- Before opening a PR, run `uv run pytest tests/ -q` and confirm it passes.
- Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py` for any new language extractor.
### What to contribute
**Worked examples** are the most useful contribution. Run `/graphify` on a real corpus, save the output to `worked/{slug}/`, write an honest `review.md` covering what the graph got right and wrong, and open a PR.
**Extraction bugs** — open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or wrong.
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
</details>
-49
View File
@@ -1,49 +0,0 @@
# Releasing graphify
Maintainer-facing release process. Contributors do not need this; see
[CONTRIBUTING.md](CONTRIBUTING.md) for how to propose changes.
graphify publishes to PyPI (package name `graphifyy`) automatically through
GitHub trusted publishing. There is no manual `twine` upload and no API token to
manage.
## Steps
1. **Bump the version.** Edit `version` in `pyproject.toml`.
2. **Update the changelog.** Add a dated section for the new version at the top of
`CHANGELOG.md`, crediting each landed PR and its author.
3. **Refresh the lock.** Run `uv lock` so `uv.lock` records the new version (and
any dependency changes).
4. **Test on both supported interpreters.** Run the full suite on Python 3.10 and
3.13:
```bash
uv run pytest
# and against a 3.13 environment, e.g.
uv run --python 3.13 pytest
```
5. **Commit and push `v8`.** Commit the version, changelog, and lock together,
then `git push origin v8`.
6. **Cut the GitHub release.** Tag the release off `v8`:
```bash
gh release create vX.Y.Z --repo Graphify-Labs/graphify --target v8 \
--title "vX.Y.Z" --notes-file <notes>
```
Publishing the release fires `publish.yml` on the `release-published` event,
which builds the wheel/sdist and uploads to PyPI via trusted publishing. Do
**not** run `twine` or pass a token.
7. **Verify the install** once PyPI has the new version (the JSON API updates
before the install index; use `--refresh`):
```bash
uvx --refresh --from graphifyy==X.Y.Z graphify --version
```
## Version numbering
Keep public versions contiguous. If a number was bumped locally but never
published to PyPI, reuse that number for the next release rather than leaving a
gap.
## Supported versions
Security fixes target only the latest released `0.9.x`. See
[SECURITY.md](SECURITY.md).
+7 -8
View File
@@ -4,8 +4,8 @@
| Version | Supported |
|---------|-----------|
| Latest 0.9.x | Yes |
| < 0.9 | No |
| 0.3.x | Yes |
| < 0.3 | No |
## Reporting a Vulnerability
@@ -18,11 +18,11 @@ Report security issues via GitHub's private vulnerability reporting, or email th
- Potential impact
- Suggested fix (if any)
We will acknowledge receipt as soon as possible and work with you to release a coordinated fix.
We will acknowledge receipt within 48 hours and aim to release a fix within 7 days for critical issues.
## Security Model
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. Its network boundaries are: AST/code extraction is local and deterministic; semantic extraction may send content to a configured model/backend; `ingest` uses explicit outbound fetch; HTTP MCP is an opt-in network listener.
graphify is a **local development tool**. It runs as a Claude Code skill and optionally as a local MCP stdio server. It makes no network calls during graph analysis - only during `ingest` (explicit URL fetch by the user).
### Threat Surface
@@ -32,17 +32,16 @@ graphify is a **local development tool**. It runs as a Claude Code skill and opt
| Oversized downloads | `safe_fetch()` streams responses and aborts at 50 MB. `safe_fetch_text()` aborts at 10 MB. |
| Non-2xx HTTP responses | `safe_fetch()` raises `HTTPError` on non-2xx status codes - error pages are not silently treated as content. |
| 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 and caps at 256 chars. (Note: HTML escaping happens separately in the HTML exporter, not in `sanitize_label()`). |
| 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 parameterized to avoid unchecked traversal where appropriate. |
| Symlink traversal | `os.walk(..., followlinks=False)` is explicit throughout `detect.py`. |
| Corrupted graph.json | `_load_graph()` in `serve.py` wraps `json.JSONDecodeError` and prints a clear recovery message instead of crashing. |
### 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
-32
View File
@@ -1,32 +0,0 @@
# Getting help with graphify
Thanks for using graphify. Here is where to go, depending on what you need.
## Questions, ideas, and usage help
- **Docs:** [docs.graphify.com](https://docs.graphify.com) — guides, command reference, and integrations. Start here.
- **GitHub Discussions:** [Discussions](https://github.com/Graphify-Labs/graphify/discussions) for longer-form questions, ideas, and show-and-tell.
- **Discord:** [discord.gg/XDnKVpzdXB](https://discord.gg/XDnKVpzdXB) for real-time chat with the community and maintainers.
Please search the docs and existing discussions/issues before posting — your question may already be answered.
## Bug reports
Open a [bug report](https://github.com/Graphify-Labs/graphify/issues/new/choose). To help us reproduce it quickly, include:
- what you expected and what actually happened,
- the smallest input that reproduces it (a sample file or repo helps a lot),
- the relevant cache entry from `graphify-out/cache/` for an extraction bug,
- your OS, Python version, and `graphify --version`.
## Feature requests
Open a [feature request](https://github.com/Graphify-Labs/graphify/issues/new/choose) describing the problem you are trying to solve, not only the solution you have in mind.
## Security vulnerabilities
Do **not** open a public issue. Report privately via the [security policy](https://github.com/Graphify-Labs/graphify/security/policy). See [SECURITY.md](SECURITY.md).
## Contributing
Want to help? See [CONTRIBUTING.md](CONTRIBUTING.md). Worked examples and extraction bug reports are the most useful contributions.
-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: 6.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 634 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 931 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?
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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">
@@ -79,7 +79,7 @@ pip install graphifyy && graphify install
<div dir="rtl">
> **الحزمة الرسمية:** اسم حزمة PyPI هو `graphifyy` (تثبيت بـ `pip install graphifyy`). الحزم الأخرى المسماة `graphify*` على PyPI ليست تابعة لهذا المشروع. المستودع الرسمي الوحيد هو [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **الحزمة الرسمية:** اسم حزمة PyPI هو `graphifyy` (تثبيت بـ `pip install graphifyy`). الحزم الأخرى المسماة `graphify*` على PyPI ليست تابعة لهذا المشروع. المستودع الرسمي الوحيد هو [safishamsi/graphify](https://github.com/safishamsi/graphify).
### دعم المنصات
@@ -174,4 +174,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. استخراج دلال
</div>
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Oficiální balíček:** Balíček PyPI se jmenuje `graphifyy`. Jediné oficiální úložiště je [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Oficiální balíček:** Balíček PyPI se jmenuje `graphifyy`. Jediné oficiální úložiště je [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Použití
@@ -74,4 +74,4 @@ Kódové soubory jsou zpracovávány lokálně prostřednictvím tree-sitter AST
[**Penpax**](https://safishamsi.github.io/penpax.ai) je enterprise vrstva nad graphify. **Bezplatná zkušební verze brzy.** [Přidejte se na čekací listinu →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Officiel pakke:** PyPI-pakken hedder `graphifyy`. Det eneste officielle lager er [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Officiel pakke:** PyPI-pakken hedder `graphifyy`. Det eneste officielle lager er [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Brug
@@ -74,4 +74,4 @@ Kodefiler behandles lokalt via tree-sitter AST. Videoer transskriberes lokalt me
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oven på graphify. **Gratis prøveperiode kommer snart.** [Tilmeld dig ventelisten →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Offizielles Paket:** Das PyPI-Paket heißt `graphifyy` (installieren mit `pip install graphifyy`). Andere Pakete mit Namen `graphify*` auf PyPI sind nicht mit diesem Projekt verbunden. Das einzige offizielle Repository ist [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify). CLI und Skill-Befehl heißen weiterhin `graphify`.
> **Offizielles Paket:** Das PyPI-Paket heißt `graphifyy` (installieren mit `pip install graphifyy`). Andere Pakete mit Namen `graphify*` auf PyPI sind nicht mit diesem Projekt verbunden. Das einzige offizielle Repository ist [safishamsi/graphify](https://github.com/safishamsi/graphify). CLI und Skill-Befehl heißen weiterhin `graphify`.
> **`graphify: command not found`?** Verwende `uv tool install graphifyy` (empfohlen) oder `pipx install graphifyy` — beide platzieren die CLI an einem verwalteten Ort, der automatisch im PATH ist. Mit einfachem `pip` musst du möglicherweise `~/.local/bin` (Linux) oder `~/Library/Python/3.x/bin` (Mac) zum PATH hinzufügen, oder `python -m graphify` verwenden.
@@ -177,4 +177,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantische Extraktion v
## Star-Verlauf
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Επίσημο πακέτο:** Το πακέτο PyPI ονομάζεται `graphifyy`. Το μοναδικό επίσημο αποθετήριο είναι το [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Επίσημο πακέτο:** Το πακέτο PyPI ονομάζεται `graphifyy`. Το μοναδικό επίσημο αποθετήριο είναι το [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Χρήση
@@ -74,4 +74,4 @@ graphify update ./src
Το [**Penpax**](https://safishamsi.github.io/penpax.ai) είναι το εταιρικό επίπεδο πάνω από το graphify. **Δωρεάν δοκιμή σύντομα.** [Εγγραφείτε στη λίστα αναμονής →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Paquete oficial:** El paquete PyPI se llama `graphifyy` (instalar con `pip install graphifyy`). Otros paquetes llamados `graphify*` en PyPI no están afiliados con este proyecto. El único repositorio oficial es [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Paquete oficial:** El paquete PyPI se llama `graphifyy` (instalar con `pip install graphifyy`). Otros paquetes llamados `graphify*` en PyPI no están afiliados con este proyecto. El único repositorio oficial es [safishamsi/graphify](https://github.com/safishamsi/graphify).
### Soporte de plataformas
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extracción semántica v
## Historial de estrellas
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
-572
View File
@@ -1,572 +0,0 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" 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/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/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/Graphify-Labs/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>
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Virallinen paketti:** PyPI-paketti on nimeltään `graphifyy`. Ainoa virallinen repositorio on [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Virallinen paketti:** PyPI-paketti on nimeltään `graphifyy`. Ainoa virallinen repositorio on [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Käyttö
@@ -74,4 +74,4 @@ Kooditiedostot käsitellään paikallisesti tree-sitter AST:n kautta. Videot lit
[**Penpax**](https://safishamsi.github.io/penpax.ai) on graphifyn päälle rakennettu yritystaso. **Ilmainen kokeilujakso tulossa pian.** [Liity odotuslistalle →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Opisyal na package:** Ang PyPI package ay pinangalanang `graphifyy`. Ang tanging opisyal na repository ay [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Opisyal na package:** Ang PyPI package ay pinangalanang `graphifyy`. Ang tanging opisyal na repository ay [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Paggamit
@@ -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=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Package officiel :** Le package PyPI s'appelle `graphifyy` (installer avec `pip install graphifyy`). Les autres packages nommés `graphify*` sur PyPI ne sont pas affiliés à ce projet. Le seul dépôt officiel est [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Package officiel :** Le package PyPI s'appelle `graphifyy` (installer avec `pip install graphifyy`). Les autres packages nommés `graphify*` sur PyPI ne sont pas affiliés à ce projet. Le seul dépôt officiel est [safishamsi/graphify](https://github.com/safishamsi/graphify).
### Support des plateformes
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extraction sémantique v
## Historique des étoiles
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
-849
View File
@@ -1,849 +0,0 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" 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/XDnKVpzdXB"><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/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/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/#Graphify-Labs/graphify&Date">
<img src="https://api.star-history.com/svg?repos=Graphify-Labs/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/Graphify-Labs/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>
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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` टाइप करें — यह आपकी फ़ाइलें पढ़ता है, एक नॉलेज ग्राफ बनाता है, और आपको वह संरचना वापस देता है जो आप नहीं जानते थे कि मौजूद है। कोडबेस को तेज़ी से समझें। आर्किटेक्चरल निर्णयों के पीछे का "क्यों" खोजें।
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **आधिकारिक पैकेज:** PyPI पैकेज का नाम `graphifyy` है (`pip install graphifyy` से इंस्टॉल करें)। PyPI पर `graphify*` नाम वाले अन्य पैकेज इस प्रोजेक्ट से संबद्ध नहीं हैं। एकमात्र आधिकारिक रिपॉजिटरी [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify) है।
> **आधिकारिक पैकेज:** PyPI पैकेज का नाम `graphifyy` है (`pip install graphifyy` से इंस्टॉल करें)। PyPI पर `graphify*` नाम वाले अन्य पैकेज इस प्रोजेक्ट से संबद्ध नहीं हैं। एकमात्र आधिकारिक रिपॉजिटरी [safishamsi/graphify](https://github.com/safishamsi/graphify) है।
### प्लेटफॉर्म समर्थन
@@ -140,4 +140,4 @@ graphify दस्तावेज़ों, papers और छवियों क
## Star इतिहास
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Hivatalos csomag:** A PyPI-csomag neve `graphifyy`. Az egyetlen hivatalos tároló a [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Hivatalos csomag:** A PyPI-csomag neve `graphifyy`. Az egyetlen hivatalos tároló a [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Használat
@@ -74,4 +74,4 @@ A kódfájlokat helyben dolgozza fel tree-sitter AST-n keresztül. A videókat h
A [**Penpax**](https://safishamsi.github.io/penpax.ai) a graphify feletti vállalati réteg. **Ingyenes próbaverzió hamarosan.** [Csatlakozzon a várólistához →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Paket resmi:** Paket PyPI bernama `graphifyy`. Satu-satunya repositori resmi adalah [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Paket resmi:** Paket PyPI bernama `graphifyy`. Satu-satunya repositori resmi adalah [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Penggunaan
@@ -74,4 +74,4 @@ File kode diproses secara lokal melalui tree-sitter AST. Video ditranskrip secar
[**Penpax**](https://safishamsi.github.io/penpax.ai) adalah lapisan enterprise di atas graphify. **Uji coba gratis segera hadir.** [Bergabunglah dengan daftar tunggu →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Pacchetto ufficiale:** Il pacchetto PyPI si chiama `graphifyy`. L'unico repository ufficiale è [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Pacchetto ufficiale:** Il pacchetto PyPI si chiama `graphifyy`. L'unico repository ufficiale è [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Utilizzo
@@ -75,4 +75,4 @@ I file di codice vengono elaborati localmente via tree-sitter AST. I video vengo
[**Penpax**](https://safishamsi.github.io/penpax.ai) è il livello enterprise su graphify. **Prova gratuita in arrivo.** [Unisciti alla lista d'attesa →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+20 -6
View File
@@ -1,12 +1,8 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8)](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
@@ -105,6 +101,24 @@ Codex ユーザーは並列抽出のために `~/.codex/config.toml` の `[featu
こう考えてください:常時有効のフックはアシスタントに地図を与え、`/graphify` コマンドはその地図を正確にナビゲートさせます。
<details>
<summary>手動インストール(curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
`~/.claude/CLAUDE.md` に追加します:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 使い方
```
@@ -210,7 +224,7 @@ NetworkX + Leiden(graspologic) + tree-sitter + vis.js。意味的抽出は C
## スター履歴
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
<details>
<summary>コントリビューション</summary>
+20 -6
View File
@@ -1,12 +1,8 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8)](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
@@ -141,6 +137,24 @@ python -m graphify.serve graphify-out/graph.json
이를 통해 어시스턴트가 `query_graph`, `get_node`, `get_neighbors`, `shortest_path` 같은 반복 쿼리에 구조화된 그래프 접근을 할 수 있습니다.
<details>
<summary>수동 설치 (curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
`~/.claude/CLAUDE.md`에 추가:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 사용법
```
@@ -254,7 +268,7 @@ graphify는 그래프 레이어입니다. 그 위에 [Penpax](https://safishamsi
## 스타 히스토리
[![Star History Chart](https://starchart.cc/Graphify-Labs/graphify.svg)](https://starchart.cc/Graphify-Labs/graphify)
[![Star History Chart](https://starchart.cc/safishamsi/graphify.svg)](https://starchart.cc/safishamsi/graphify)
<details>
<summary>기여하기</summary>
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Officieel pakket:** Het PyPI-pakket heet `graphifyy`. De enige officiële repository is [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Officieel pakket:** Het PyPI-pakket heet `graphifyy`. De enige officiële repository is [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Gebruik
@@ -74,4 +74,4 @@ Codebestanden worden lokaal verwerkt via tree-sitter AST. Video's lokaal getrans
[**Penpax**](https://safishamsi.github.io/penpax.ai) is de enterprise-laag boven op graphify. **Gratis proefversie binnenkort.** [Meld je aan voor de wachtlijst →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Offisiell pakke:** PyPI-pakken heter `graphifyy`. Det eneste offisielle depotet er [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Offisiell pakke:** PyPI-pakken heter `graphifyy`. Det eneste offisielle depotet er [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Bruk
@@ -74,4 +74,4 @@ Kodefiler behandles lokalt via tree-sitter AST. Videoer transkriberes lokalt med
[**Penpax**](https://safishamsi.github.io/penpax.ai) er enterprise-laget oppå graphify. **Gratis prøveperiode kommer snart.** [Bli med på ventelisten →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Oficjalny pakiet:** Pakiet PyPI nazywa się `graphifyy`. Jedyne oficjalne repozytorium to [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Oficjalny pakiet:** Pakiet PyPI nazywa się `graphifyy`. Jedyne oficjalne repozytorium to [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Użycie
@@ -75,4 +75,4 @@ Pliki kodu są przetwarzane lokalnie przez tree-sitter AST. Wideo transkrybowane
[**Penpax**](https://safishamsi.github.io/penpax.ai) to warstwa enterprise nad graphify. **Bezpłatna wersja próbna wkrótce.** [Dołącz do listy oczekujących →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Pacote oficial:** O pacote PyPI chama-se `graphifyy` (instalar com `pip install graphifyy`). Outros pacotes chamados `graphify*` no PyPI não são afiliados a este projeto. O único repositório oficial é [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Pacote oficial:** O pacote PyPI chama-se `graphifyy` (instalar com `pip install graphifyy`). Outros pacotes chamados `graphify*` no PyPI não são afiliados a este projeto. O único repositório oficial é [safishamsi/graphify](https://github.com/safishamsi/graphify).
### Suporte a plataformas
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Extração semântica vi
## Histórico de estrelas
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Pachet oficial:** Pachetul PyPI se numește `graphifyy`. Singurul depozit oficial este [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Pachet oficial:** Pachetul PyPI se numește `graphifyy`. Singurul depozit oficial este [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Utilizare
@@ -74,4 +74,4 @@ Fișierele de cod sunt procesate local prin tree-sitter AST. Videoclipurile sunt
[**Penpax**](https://safishamsi.github.io/penpax.ai) este stratul enterprise peste graphify. **Perioadă de probă gratuită în curând.** [Alăturați-vă listei de așteptare →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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 — он прочитает ваши файлы, построит граф знаний и вернёт вам структуру, о существовании которой вы не подозревали. Понимайте кодовую базу быстрее. Находите «почему» за архитектурными решениями.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Официальный пакет:** Пакет PyPI называется `graphifyy` (установить через `pip install graphifyy`). Другие пакеты с именем `graphify*` на PyPI не связаны с этим проектом. Единственный официальный репозиторий — [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Официальный пакет:** Пакет PyPI называется `graphifyy` (установить через `pip install graphifyy`). Другие пакеты с именем `graphify*` на PyPI не связаны с этим проектом. Единственный официальный репозиторий — [safishamsi/graphify](https://github.com/safishamsi/graphify).
### Поддержка платформ
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Семантическо
## История звёзд
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Officiellt paket:** PyPI-paketet heter `graphifyy`. Det enda officiella förrådet är [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Officiellt paket:** PyPI-paketet heter `graphifyy`. Det enda officiella förrådet är [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Användning
@@ -74,4 +74,4 @@ Kodfiler behandlas lokalt via tree-sitter AST. Videor transkriberas lokalt med f
[**Penpax**](https://safishamsi.github.io/penpax.ai) är enterprise-lagret ovanpå graphify. **Gratis provperiod kommer snart.** [Gå med i väntelistan →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **แพ็กเกจอย่างเป็นทางการ:** แพ็กเกจ PyPI ชื่อ `graphifyy` repository อย่างเป็นทางการเดียวคือ [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify)
> **แพ็กเกจอย่างเป็นทางการ:** แพ็กเกจ PyPI ชื่อ `graphifyy` repository อย่างเป็นทางการเดียวคือ [safishamsi/graphify](https://github.com/safishamsi/graphify)
## การใช้งาน
@@ -74,4 +74,4 @@ graphify update ./src
[**Penpax**](https://safishamsi.github.io/penpax.ai) คือชั้น enterprise เหนือ graphify **ทดลองใช้ฟรีเร็วๆ นี้** [เข้าร่วมรายชื่อรอ →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Resmi paket:** PyPI paketi `graphifyy` olarak adlandırılır. Tek resmi depo [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify)'dir.
> **Resmi paket:** PyPI paketi `graphifyy` olarak adlandırılır. Tek resmi depo [safishamsi/graphify](https://github.com/safishamsi/graphify)'dir.
## Kullanım
@@ -74,4 +74,4 @@ Kod dosyaları tree-sitter AST aracılığıyla yerel olarak işlenir. Videolar
[**Penpax**](https://safishamsi.github.io/penpax.ai), graphify üzerindeki kurumsal katmandır. **Ücretsiz deneme yakında.** [Bekleme listesine katılın →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+9 -15
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" 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">
@@ -9,17 +9,17 @@
<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/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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://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>
<p align="center">
<a href="https://star-history.com/#Graphify-Labs/graphify&Date">
<img src="https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date" alt="Star History Chart" width="370"/>
<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>
@@ -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)
---
@@ -545,7 +539,7 @@ graphify cluster-only ./my-project --exclude-hubs 99 # виключи
Клонуйте репо і встановіть у редагованому режимі:
```bash
git clone https://github.com/Graphify-Labs/graphify.git
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v8 # гілка активної розробки
+5 -5
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,11 +7,11 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://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.
@@ -65,7 +65,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Rasmiy paket:** PyPI dagi paket nomi `graphifyy` (`pip install graphifyy` orqali o'rnatiladi). PyPI dagi boshqa `graphify*` nomli paketlar bu loyiha bilan bog'liq emas. Yagona rasmiy repozitoriy — [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Rasmiy paket:** PyPI dagi paket nomi `graphifyy` (`pip install graphifyy` orqali o'rnatiladi). PyPI dagi boshqa `graphify*` nomli paketlar bu loyiha bilan bog'liq emas. Yagona rasmiy repozitoriy — [safishamsi/graphify](https://github.com/safishamsi/graphify).
### Platforma qo'llab-quvvatlash
@@ -167,4 +167,4 @@ NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantik chiqarish Claud
## Yulduzlar tarixi
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **Gói chính thức:** Gói PyPI có tên là `graphifyy`. Kho lưu trữ chính thức duy nhất là [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify).
> **Gói chính thức:** Gói PyPI có tên là `graphifyy`. Kho lưu trữ chính thức duy nhất là [safishamsi/graphify](https://github.com/safishamsi/graphify).
## Sử dụng
@@ -74,4 +74,4 @@ Các tệp code được xử lý cục bộ qua tree-sitter AST. Video được
[**Penpax**](https://safishamsi.github.io/penpax.ai) là lớp doanh nghiệp trên graphify. **Dùng thử miễn phí sắp ra mắt.** [Tham gia danh sách chờ →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
+19 -5
View File
@@ -1,12 +1,8 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
</p>
# graphify
🇺🇸 [English](../../README.md) | 🇨🇳 [简体中文](README.zh-CN.md) | 🇯🇵 [日本語](README.ja-JP.md) | 🇰🇷 [한국어](README.ko-KR.md) | 🇩🇪 [Deutsch](README.de-DE.md) | 🇫🇷 [Français](README.fr-FR.md) | 🇪🇸 [Español](README.es-ES.md) | 🇮🇳 [हिन्दी](README.hi-IN.md) | 🇧🇷 [Português](README.pt-BR.md) | 🇷🇺 [Русский](README.ru-RU.md) | 🇸🇦 [العربية](README.ar-SA.md) | 🇮🇹 [Italiano](README.it-IT.md) | 🇵🇱 [Polski](README.pl-PL.md) | 🇳🇱 [Nederlands](README.nl-NL.md) | 🇹🇷 [Türkçe](README.tr-TR.md) | 🇺🇦 [Українська](README.uk-UA.md) | 🇻🇳 [Tiếng Việt](README.vi-VN.md) | 🇮🇩 [Bahasa Indonesia](README.id-ID.md) | 🇸🇪 [Svenska](README.sv-SE.md) | 🇬🇷 [Ελληνικά](README.el-GR.md) | 🇷🇴 [Română](README.ro-RO.md) | 🇨🇿 [Čeština](README.cs-CZ.md) | 🇫🇮 [Suomi](README.fi-FI.md) | 🇩🇰 [Dansk](README.da-DK.md) | 🇳🇴 [Norsk](README.no-NO.md) | 🇭🇺 [Magyar](README.hu-HU.md) | 🇹🇭 [ภาษาไทย](README.th-TH.md) | 🇺🇿 [Oʻzbekcha](README.uz-UZ.md) | 🇹🇼 [繁體中文](README.zh-TW.md)
[![CI](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8)](https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml)
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
**一个面向 AI 编码助手的技能。** 在 Claude Code、CodeBuddy、Codex、OpenCode、OpenClaw、Factory Droid 或 Trae 中输入 `/graphify`,它会读取你的文件、构建知识图谱,并把原本不明显的结构关系还给你。更快理解代码库,找到架构决策背后的"为什么"。
@@ -101,6 +97,24 @@ Codex 用户还需要在 `~/.codex/config.toml` 的 `[features]` 下打开 `mult
可以这样理解:常驻 hook 是先给助手一张地图,`/graphify` 这几个命令则是让它沿着地图精确导航。
<details>
<summary>手动安装(curl)</summary>
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v3/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
```
把下面内容加到 `~/.claude/CLAUDE.md`:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
```
</details>
## 用法
```
+4 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://graphify.com"><img src="https://raw.githubusercontent.com/Graphify-Labs/graphify/v8/docs/graphify-logo.png" width="480" height="252" alt="Graphify"/></a>
<img src="https://raw.githubusercontent.com/safishamsi/graphify/v4/docs/logo-text.svg" width="260" height="64" alt="Graphify"/>
</p>
<p align="center">
@@ -7,7 +7,7 @@
</p>
<p align="center">
<a href="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml"><img src="https://github.com/Graphify-Labs/graphify/actions/workflows/ci.yml/badge.svg?branch=v8" alt="CI"/></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=v4" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -49,7 +49,7 @@ pipx install graphifyy && graphify install
pip install graphifyy && graphify install
```
> **官方套件:** PyPI 套件名稱為 `graphifyy`。唯一的官方儲存庫是 [Graphify-Labs/graphify](https://github.com/Graphify-Labs/graphify)。
> **官方套件:** PyPI 套件名稱為 `graphifyy`。唯一的官方儲存庫是 [safishamsi/graphify](https://github.com/safishamsi/graphify)。
## 使用方式
@@ -74,4 +74,4 @@ graphify update ./src
[**Penpax**](https://safishamsi.github.io/penpax.ai) 是 graphify 之上的企業層。**免費試用即將推出。** [加入等待名單 →](https://safishamsi.github.io/penpax.ai)
[![Star History Chart](https://api.star-history.com/svg?repos=Graphify-Labs/graphify&type=Date)](https://star-history.com/#Graphify-Labs/graphify&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
-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
+4170 -556
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.
+14 -89
View File
@@ -13,37 +13,21 @@ _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", ".vb")},
**{e: "dotnet" for e in (".cs",)},
**{e: "php" for e in (".php",)},
**{e: "r" for e in (".r",)},
**{e: "cobol" for e in (".cbl", ".cob", ".cobol", ".cpy")},
**{e: "solidity" for e in (".sol",)},
**{e: "erlang" for e in (".erl", ".hrl", ".escript")},
}
@@ -75,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("()"):
@@ -109,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:
@@ -214,19 +182,8 @@ def _file_category(path: str) -> str:
def _top_level_dir(path: str) -> str:
"""Return the first path component - used to detect cross-repo edges.
A path with no "/" is a file at the scan root, so its top-level directory
is the root itself ("."), not the filename: otherwise every pair of
root-level files would look like it crosses repos/directories. "." keeps
root files distinct from an absolute path outside the root, whose first
component is "". Backslashes and a leading "./" are normalised first,
since a graph.json loaded without build_from_json can still carry them.
"""
path = path.replace("\\", "/")
while path.startswith("./"):
path = path[2:]
return path.split("/")[0] if "/" in path else "."
"""Return the first path component - used to detect cross-repo edges."""
return path.split("/")[0] if "/" in path else path
def _surprise_score(
@@ -274,12 +231,8 @@ def _surprise_score(
score += 2
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
# 3. Cross-repo bonus - different top-level directory. merge-graphs /
# global add keep source_file repo-relative and tag nodes with `repo`, so
# the repo is part of the key (absent on a single-repo graph).
top_u = (G.nodes[u].get("repo"), _top_level_dir(u_source))
top_v = (G.nodes[v].get("repo"), _top_level_dir(v_source))
if top_u != top_v and not _suppress_structural:
# 3. Cross-repo bonus - different top-level directory
if _top_level_dir(u_source) != _top_level_dir(v_source) and not _suppress_structural:
score += 2
reasons.append("connects across different repos/directories")
@@ -468,9 +421,6 @@ def suggest_questions(
Generate questions the graph is uniquely positioned to answer.
Based on: AMBIGUOUS edges, bridge nodes, underexplored god nodes, isolated nodes.
Each question has a 'type', 'question', and 'why' field.
Interleave question types before applying top_n so an abundant early type
cannot crowd out later signals. Preserve the existing order within each type
and category generation order when the limit is smaller than the type count.
"""
if community_labels:
community_labels = {int(k) if isinstance(k, str) else k: v for k, v in community_labels.items()}
@@ -549,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]]
@@ -586,16 +533,7 @@ def suggest_questions(
),
}]
from itertools import zip_longest
by_type: dict[str, list[dict]] = {}
for question in questions:
by_type.setdefault(question["type"], []).append(question)
diversified = [
question for row in zip_longest(*by_type.values())
for question in row if question is not None
]
return diversified[:top_n]
return questions[:top_n]
def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
@@ -720,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
@@ -758,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
+123 -2135
View File
File diff suppressed because it is too large. Load diff
+115 -1521
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)}
-166
View File
@@ -1,166 +0,0 @@
"""Cargo manifest introspection for workspace-internal crate dependencies."""
from __future__ import annotations
import os
from pathlib import Path
from typing import Any
_CONFIDENCE_EXTRACTED = "EXTRACTED"
_MAX_DISCOVERY_DEPTH = 2
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 _discover_root_manifest(root: Path) -> Path | None:
"""Find a Cargo.toml under *root* when none sits directly at the root.
A bounded-depth search rather than an unbounded walk: a Tauri app's
crate lives in src-tauri/, a polyglot repo's in rust/ or crates/, but
going arbitrarily deep risks matching a vendored or example manifest
nested well inside an unrelated dependency (#3678). Reuses the same
noise-directory pruning the AST scanner already applies (venvs, caches,
node_modules, build output) so those never get searched into. A
genuinely ambiguous layout with more than one candidate at the same
depth is resolved by sorted path order rather than guessed at; the
caller is free to point --cargo at a subdirectory directly for a repo
where that is not the right answer.
"""
from graphify.detect import _is_noise_dir
found: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
current = Path(dirpath)
depth = len(current.relative_to(root).parts)
if depth > 0 and "Cargo.toml" in filenames:
found.append(current / "Cargo.toml")
if depth >= _MAX_DISCOVERY_DEPTH:
dirnames[:] = []
continue
dirnames[:] = [d for d in dirnames if not _is_noise_dir(d, current)]
if not found:
return None
return sorted(found)[0]
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"
if not root_manifest.is_file():
discovered = _discover_root_manifest(root_path)
if discovered is not None:
root_manifest = discovered
root_data = _load_toml(root_manifest)
workspace = root_data.get("workspace")
workspace_dependencies = workspace.get("dependencies", {}) if isinstance(workspace, dict) else {}
if not isinstance(workspace_dependencies, dict):
workspace_dependencies = {}
# Workspace members are resolved relative to the manifest's OWN
# directory, not necessarily root_path (#3678: the manifest can live in
# a discovered subdirectory, e.g. src-tauri/).
manifests = _member_manifest_paths(root_manifest.parent, 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()):
inherited = isinstance(spec, dict) and "workspace" in spec
if inherited:
if spec["workspace"] is not True:
continue
spec = workspace_dependencies.get(dep_key)
if not isinstance(spec, dict) or not isinstance(spec.get("path"), str):
continue
# 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
if inherited:
# Shared paths are relative to the workspace root, not the member.
# A matching name alone cannot prove a registry/git dep is local.
inherited_manifest = (root_path / spec["path"] / "Cargo.toml").resolve()
if inherited_manifest != target[1].resolve():
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}
-5019
View File
File diff suppressed because it is too large. Load diff
+7 -188
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,
@@ -247,9 +101,8 @@ def cluster(
<1.0 = fewer larger communities. Default 1.0.
exclude_hubs_percentile: if set (0-100), nodes whose degree exceeds this
percentile are excluded from partitioning and reattached to their
majority-vote neighbour community afterwards. Nodes whose only
neighbours are excluded hubs follow them, by the same vote. Useful for
staging/utility super-hubs that inflate god-node rankings (#919).
majority-vote neighbour community afterwards. Useful for staging/utility
super-hubs that inflate god-node rankings (#919).
"""
if G.number_of_nodes() == 0:
return {}
@@ -273,21 +126,6 @@ def cluster(
excluded = hub_nodes
isolates = [n for n in G.nodes() if G.degree(n) == 0 and n not in excluded]
connected_nodes = [n for n in G.nodes() if G.degree(n) > 0 and n not in excluded]
# A node whose only neighbours are excluded hubs is isolated in the
# partitioned subgraph purely because of the exclusion. Hold it out of the
# partition and place it with its hub(s) below, instead of letting it come
# back as a singleton cut off from the only node it connects to.
stranded: list[str] = []
if hub_nodes:
# A self-loop is not a neighbour: judge a node by its other neighbours.
stranded = [
n for n in connected_nodes
if (nbs := [nb for nb in G.neighbors(n) if nb != n])
and all(nb in hub_nodes for nb in nbs)
]
if stranded:
_stranded = set(stranded)
connected_nodes = [n for n in connected_nodes if n not in _stranded]
connected = G.subgraph(connected_nodes)
raw: dict[int, list[str]] = {}
@@ -319,18 +157,6 @@ def cluster(
raw[next_cid] = [hub]
node_community[hub] = next_cid
next_cid += 1
# Every neighbour of a stranded node is a hub, and every hub is placed
# by now, so the same majority vote always has a winner.
for node in sorted(stranded, key=str):
votes = {}
for nb in G.neighbors(node):
if nb == node:
continue
cid = node_community[nb]
votes[cid] = votes.get(cid, 0) + 1
best = min(votes, key=lambda c: (-votes[c], c))
raw[best].append(node)
node_community[node] = best
# Split oversized communities
max_size = max(_MIN_SPLIT_SIZE, int(G.number_of_nodes() * _MAX_COMMUNITY_FRACTION))
@@ -386,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.85,
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.85,
source_file=str(merged.nodes[left].get("source_file") or ""),
weight=1.0,
_src=left,
_tgt=right,
)
added += 1
return added
-39
View File
@@ -1,39 +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.
The mechanism — single-implementer, single-owner, per-method `dispatches_to`
edges at INFERRED — lives in `graphify.interface_dispatch` so that another
language can add a gate rather than a copy; this module fixes the C# gate.
Both ends of a pair must be declared in a `.cs` file: `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.
"""
from __future__ import annotations
from graphify.interface_dispatch import ( # noqa: F401 (re-exported for callers)
DISPATCH_RELATION,
method_label as _method_label,
resolve_interface_dispatch,
)
_CSHARP_SUFFIXES = (".cs",)
def resolve_csharp_interface_dispatch(
per_file: list[dict],
all_nodes: list[dict],
all_edges: list[dict],
) -> None:
"""Link each single-implementer C# interface method to its implementation."""
resolve_interface_dispatch(per_file, all_nodes, all_edges, suffixes=_CSHARP_SUFFIXES)
+44 -878
View File
File diff suppressed because it is too large. Load diff
+270 -1726
View File
File diff suppressed because it is too large. Load diff
+3 -35
View File
@@ -161,26 +161,13 @@ def diagnose_extraction(
max_examples: int = 5,
extract_path: str | Path | None = None,
) -> dict[str, Any]:
"""Summarize graph-integrity risks for one JSON graph/extraction dict.
Missing ``ref_*`` targets are expected external references produced for
dependencies outside the scanned corpus. They are counted separately from
actionable internal dangling endpoints.
"""
"""Summarize same-endpoint edge-collapse risk for one JSON graph/extraction dict."""
from graphify.build import build_from_json
node_ids = _node_ids(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()
@@ -189,7 +176,6 @@ def diagnose_extraction(
non_object_edges = 0
missing_endpoint_edges = 0
dangling_endpoint_edges = 0
external_reference_edges = 0
self_loop_edges = 0
valid_candidate_edges = 0
@@ -203,15 +189,7 @@ def diagnose_extraction(
missing_endpoint_edges += 1
continue
if source not in node_ids or target not in node_ids:
# Two intentionally-distinct populations of "external": a `ref_`
# target here is a JSON/config out-of-corpus reference ($ref /
# extends / references), whereas import-family externals are minted
# as declared `external=True` stub nodes at build time (#2873) and
# therefore never reach this branch. Don't try to unify them.
if source in node_ids and target.startswith("ref_"):
external_reference_edges += 1
else:
dangling_endpoint_edges += 1
dangling_endpoint_edges += 1
continue
if source == target:
self_loop_edges += 1
@@ -261,12 +239,10 @@ 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,
"dangling_endpoint_edges": dangling_endpoint_edges,
"external_reference_edges": external_reference_edges,
"self_loop_edges": self_loop_edges,
"valid_candidate_edges": valid_candidate_edges,
"exact_duplicate_edges": _count_extra(exact_counts),
@@ -298,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
@@ -368,12 +338,10 @@ 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']}",
f"dangling_endpoint_edges: {summary['dangling_endpoint_edges']}",
f"external_reference_edges: {summary.get('external_reference_edges', 0)}",
f"self_loop_edges: {summary['self_loop_edges']}",
f"exact_duplicate_edges: {summary['exact_duplicate_edges']}",
f"directed_unique_endpoint_pairs: {summary['directed_unique_endpoint_pairs']}",
+652 -634
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",
]
-210
View File
@@ -1,210 +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 _distinct_node_labels(G: nx.Graph) -> list[str]:
"""Distinct Cypher labels the node-upsert loop will write, sorted.
The label is derived exactly as the push loops derive it, so the indexes
created up front cover every label the MERGE statements will match against.
"""
labels = set()
for _, data in G.nodes(data=True):
label = data.get("file_type", "Entity").capitalize()
labels.add(re.sub(r"[^A-Za-z0-9_]", "", label) or "Entity")
return sorted(labels)
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:
# Index (label, id) before any upsert, for the same reason as the
# FalkorDB path: MERGE matches on (label, id), so an unindexed match
# pattern scans the whole label and the push degrades to O(n^2)
# (#3804). IF NOT EXISTS keeps this idempotent across re-pushes.
for label in _distinct_node_labels(G):
try:
session.run(f"CREATE INDEX IF NOT EXISTS FOR (n:{label}) ON (n.id)")
except Exception:
pass
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
# Index (label, id) before any upsert. The MERGE below matches on
# (label, id), so with no index FalkorDB scans every existing node carrying
# that label to decide whether the node is new: each upsert costs
# O(nodes with that label) and the whole push degrades to O(n^2) (#3804).
# Measured on a 167k-node / 209k-edge graph, adding these indexes first
# restored the throughput the push started at. FalkorDB's CREATE INDEX has
# no IF NOT EXISTS, so a re-run against an already-indexed graph raises —
# tolerate that rather than failing an otherwise valid push.
for label in _distinct_node_labels(G):
try:
graph.query(f"CREATE INDEX FOR (n:{label}) ON (n.id)")
except Exception:
pass
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}
-663
View File
@@ -1,663 +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, i) => ({{
id: n.id, label: n.label, color: n.color, size: n.size,
font: n.font, title: n.title,
// Fermat/golden-angle spiral seed positions (#3699): spreading nodes out
// before physics runs keeps avoidOverlap from computing near-zero-distance
// repulsion that blows the BarnesHut recursion into a stack overflow on large
// graphs. `i` is the map index — physics still settles small graphs identically.
x: 30 * Math.sqrt(i) * Math.cos(i * 2.4),
y: 30 * Math.sqrt(i) * Math.sin(i * 2.4),
community: n.community, community_name: n.community_name,
source_file: n.source_file, file_type: n.file_type, degree: n.degree,
member_count: n.member_count,
}})));
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('');
const isMetaNode = !n.file_type && !n.source_file;
let html = `<div class="field"><b>${{esc(n.label)}}</b></div>`;
if (!isMetaNode) {{
html += `<div class="field">Type: ${{esc(n.file_type || 'unknown')}}</div>`;
}}
html += `<div class="field">Community: ${{esc(n.community_name || '')}}</div>`;
if (!isMetaNode) {{
html += `<div class="field">Source: ${{esc(n.source_file || '-')}}</div>`;
}} else if (n.member_count !== undefined && n.member_count !== null) {{
html += `<div class="field">Members: ${{esc(n.member_count)}}</div>`;
}}
html += `<div class="field">Degree: ${{n.degree}}</div>`;
if (neighborIds.length) {{
html += `<div class="field" style="margin-top:8px;color:#aaa;font-size:11px">Neighbors (${{neighborIds.length}})</div><div id="neighbors-list">${{neighborItems}}</div>`;
}}
document.getElementById('info-content').innerHTML = html;
}}
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"},
# Tooltip `title` is a STRING, which vis-network renders via
# Popup.setText -> `frame.innerText = t` (verified in the pinned
# 9.1.6 bundle: the only non-Element branch is innerText, and the
# bundle has zero `innerHTML = <var>` sinks). So raw special chars
# are shown literally and must NOT be html-escaped here or the user
# sees `&amp;`/`&lt;` in the tooltip (#3664/#3686). This is the
# #1838 stored-XSS boundary: never pass an HTMLElement as `title`,
# and do not change the vis-network pin below without re-checking
# Popup rendering (the test_export version-pin guard enforces this).
"title": 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,
}
if member_counts:
node["member_count"] = member_counts.get(cid, len(communities.get(cid, [])))
# 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"] = f"{label}\n{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": sanitize_label(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
+9518 -7103
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`.
-76
View File
@@ -1,76 +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.cobol import extract_cobol
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.erlang import extract_erlang
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.r import extract_r
from graphify.extractors.razor import extract_razor
from graphify.extractors.rust import extract_rust
from graphify.extractors.sln import extract_sln
from graphify.extractors.solidity import extract_solidity
from graphify.extractors.sql import extract_sql
from graphify.extractors.terraform import extract_terraform
from graphify.extractors.verilog import extract_verilog
from graphify.extractors.vbnet import extract_vbnet
from graphify.extractors.zig import extract_zig
LANGUAGE_EXTRACTORS: dict[str, Callable[[Path], dict]] = {
"apex": extract_apex,
"bash": extract_bash,
"blade": extract_blade,
"cobol": extract_cobol,
"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,
"erlang": extract_erlang,
"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,
"r": extract_r,
"razor": extract_razor,
"rust": extract_rust,
"sln": extract_sln,
"solidity": extract_solidity,
"sql": extract_sql,
"terraform": extract_terraform,
"verilog": extract_verilog,
"vbnet": extract_vbnet,
"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")
-627
View File
@@ -1,627 +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"})
# Non-shell interpreters a pipeline orchestrator commonly hands a script
# path to (#3802): `python3 scripts/stage_one.py`, `node build.js`. A
# script run this way is most of what an orchestrator does, and none of
# it produced an edge before — the orchestrator looked disconnected from
# every stage it runs.
_SCRIPT_INVOKERS = frozenset({"python", "python3", "python2", "node", "nodejs", "ruby", "perl"})
_INVOKABLE_SCRIPT_EXTENSIONS = (".py", ".js", ".mjs", ".cjs", ".rb", ".pl", ".sh")
# 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))
# python3 scripts/stage_one.py / node build.js / "$PYTHON"
# scripts/stage_two.py (#3802): a script run through a
# non-shell interpreter, or through a bare variable standing
# in for one, is still a real dependency on that file -
# independent of the .sh-specific runner/direct-invocation
# handling above, so this never interferes with it.
is_known_interpreter = (
cmd is not None and cmd in _SCRIPT_INVOKERS
and cmd not in defined_functions
)
cmd_word = text(cmd_name_node).strip()
if cmd_word[0:1] in {"'", '"'} and cmd_word[-1:] == cmd_word[0]:
cmd_word = cmd_word[1:-1]
# A bare variable standing in for an interpreter (`$PYTHON x.py`)
# has no path separator; `"$DIR/run.sh" x.py` runs run.sh with
# x.py as its ARGUMENT, so the `/` guard keeps us from minting a
# spurious invokes edge to the argument on top of the real
# `calls` edge the .sh runner path already emits.
is_interpreter_variable = (
cmd is None and cmd_word.startswith("$")
and "$(" not in cmd_word and "/" not in cmd_word
)
if (is_known_interpreter or is_interpreter_variable) and args:
invoked_raw = literal(args[0])
if invoked_raw and invoked_raw.endswith(_INVOKABLE_SCRIPT_EXTENSIONS):
resolved = (path.parent / invoked_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
tgt_nid = _make_id(str(target_path))
if resolved.suffix == ".sh":
tgt_nid += "__entry"
add_edge(caller_nid, tgt_nid, "invokes",
node.start_point[0] + 1,
confidence="INFERRED", 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}
-67
View File
@@ -1,67 +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 @extends, @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 = []
# @extends('layouts.app') — template inheritance: this view renders inside
# the named parent layout. It is the primary structural relationship in a
# Blade view (most page templates extend a layout), so dropping it left the
# child disconnected from its layout in the graph.
for m in re.finditer(r"@extends\(['\"]([^'\"]+)['\"]", 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": "extends",
"confidence": "EXTRACTED", "confidence_score": 1.0,
"source_file": str(path), "source_location": None, "weight": 1.0})
# @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}
-297
View File
@@ -1,297 +0,0 @@
"""Deterministic extraction for fixed- and free-format COBOL source."""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
from graphify.extractors.base import _make_id
_NAME = r"[A-Z0-9][A-Z0-9-]*"
_PROGRAM = re.compile(rf"\bPROGRAM-ID\s*\.\s*({_NAME})", re.IGNORECASE)
_PARAGRAPH = re.compile(
rf"^({_NAME})(?:\s+(SECTION))?\s*\.\s*$", re.IGNORECASE
)
_PERFORM = re.compile(
rf"\bPERFORM\s+({_NAME})(?:\s+(?:THRU|THROUGH)\s+({_NAME}))?\b",
re.IGNORECASE,
)
_COPY = re.compile(
rf"\bCOPY\s+(?:'([^']+)'|\"([^\"]+)\"|({_NAME}(?:\.[A-Z0-9-]+)?))",
re.IGNORECASE,
)
_CALL = re.compile(r"\bCALL\s+(['\"])([A-Z0-9-]+)\1", re.IGNORECASE)
_DATA_ITEM = re.compile(
rf"^\s*(?:0[1-9]|[1-4][0-9]|66|77|88)\s+({_NAME})\b", re.IGNORECASE
)
_NOT_PARAGRAPHS = frozenset({
"IDENTIFICATION", "ENVIRONMENT", "DATA", "PROCEDURE", "FILE",
"WORKING-STORAGE", "LOCAL-STORAGE", "LINKAGE", "CONFIGURATION",
"INPUT-OUTPUT", "STOP", "EXIT", "GOBACK", "CONTINUE", "DISPLAY", "MOVE",
"COMPUTE", "ADD", "SUBTRACT", "MULTIPLY", "DIVIDE", "PERFORM", "COPY",
"CALL", "IF", "ELSE", "END-IF", "END-PERFORM", "END-EXEC",
})
_PERFORM_MODIFIERS = frozenset({
"UNTIL", "VARYING", "TIMES", "WITH", "TEST", "FOREVER",
})
def _code_lines(source: str) -> list[tuple[int, str]]:
"""Return logical COBOL lines with fixed-format continuations joined."""
physical = source.splitlines()
forced_free = bool(
re.search(r">>\s*SOURCE\s+FORMAT\s+(?:IS\s+)?FREE", source, re.IGNORECASE)
)
# A fixed-format line is a 6-column sequence area followed by the indicator
# in column 7. The sequence area is blank on some files but carries a
# sequence NUMBER on legacy mainframe source (the historical norm), so match
# both: six spaces, or six digits, followed by a valid indicator (space =
# code, `*`/`/` = comment, `-` = continuation, `D` = debug). Requiring six
# blank columns misclassified every sequence-numbered file as free-format,
# which then kept the sequence number in the code and dropped every paragraph
# (its `^NAME.$` anchor no longer matched) and PERFORM edge.
fixed_markers = sum(
bool(re.match(r"^(?: {6}|\d{6})[ *\-/dD]", line))
for line in physical if line.strip()
)
nonempty = sum(bool(line.strip()) for line in physical)
free = forced_free or fixed_markers < max(1, nonempty // 2)
logical: list[tuple[int, str]] = []
for number, line in enumerate(physical, 1):
if free:
code = line.split("*>", 1)[0].rstrip()
if not code.strip() or code.lstrip().startswith(">>"):
continue
logical.append((number, code))
continue
if len(line) < 7:
continue
indicator = line[6]
if indicator in "*/":
continue
code = line[7:72].split("*>", 1)[0].rstrip()
if not code.strip():
continue
if indicator == "-" and logical:
prior_number, prior = logical[-1]
joiner = "" if prior.rstrip().endswith("-") else " "
logical[-1] = (prior_number, prior.rstrip() + joiner + code.lstrip())
else:
logical.append((number, code))
return logical
def _mask_strings(code: str) -> str:
return re.sub(r"'[^']*'|\"[^\"]*\"", lambda match: " " * len(match.group()), code)
def _starts_inside_string(code: str, offset: int) -> bool:
"""Whether *offset* lies inside a COBOL quoted literal."""
for match in re.finditer(r"'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"", code):
if match.start() <= offset < match.end():
return True
return False
def extract_cobol(path: Path) -> dict:
try:
source = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return {"nodes": [], "edges": [], "error": str(exc)}
source_file = str(path)
file_id = _make_id(source_file)
nodes: list[dict[str, Any]] = []
edges: list[dict[str, Any]] = []
raw_calls: list[dict[str, Any]] = []
seen_ids: set[str] = set()
seen_edges: set[tuple[str, str, str]] = set()
def add_node(
nid: str,
label: str,
line: int,
*,
kind: str,
source_backed: bool = True,
callable_node: bool = False,
) -> str:
if nid not in seen_ids:
seen_ids.add(nid)
item: dict[str, Any] = {
"id": nid,
"label": label,
"file_type": "code",
"source_location": f"L{line}",
"metadata": {"language": "cobol", "kind": kind},
}
if source_backed:
item["source_file"] = source_file
if callable_node:
item["_callable"] = True
nodes.append(item)
return nid
def add_edge(
source_id: str,
target_id: str,
relation: str,
line: int,
*,
target_file: str | None = None,
) -> None:
key = (source_id, target_id, relation)
if not source_id or not target_id or source_id == target_id or key in seen_edges:
return
seen_edges.add(key)
edge: dict[str, Any] = {
"source": source_id,
"target": target_id,
"relation": relation,
"confidence": "EXTRACTED",
"source_file": source_file,
"source_location": f"L{line}",
"weight": 1.0,
}
if target_file:
edge["target_file"] = target_file
edges.append(edge)
add_node(file_id, path.name, 1, kind="file")
code_lines = _code_lines(source)
current_program = file_id
current_scope = file_id
in_procedure = False
in_exec = False
paragraphs: dict[tuple[str, str], str] = {}
pending_performs: list[tuple[str, str, str, int]] = []
for line, code in code_lines:
upper = code.upper().strip()
if in_exec:
if "END-EXEC" in upper:
in_exec = False
continue
if re.search(r"\bEXEC\s+(?:SQL|CICS)\b", upper):
if "END-EXEC" not in upper:
in_exec = True
continue
program_match = _PROGRAM.search(upper)
if program_match:
name = program_match.group(1).upper()
current_program = add_node(
_make_id(file_id, "program", name.casefold()),
name,
line,
kind="program",
callable_node=True,
)
add_edge(file_id, current_program, "contains", line)
current_scope = current_program
in_procedure = False
continue
copy_match = _COPY.search(code)
if copy_match:
written = next(group for group in copy_match.groups() if group)
copy_name = written.rstrip(".")
copy_path = Path(copy_name)
if not copy_path.suffix:
copy_path = copy_path.with_suffix(".cpy")
target = path.parent / copy_path
reference_id = add_node(
_make_id(current_program, "copybook", copy_name.casefold()),
Path(copy_name).stem.upper(),
line,
kind="copybook_reference",
)
add_edge(current_program, reference_id, "contains", line)
add_edge(
current_program,
_make_id(str(target)),
"imports_from",
line,
target_file=str(target),
)
if "PROCEDURE DIVISION" in upper:
in_procedure = True
current_scope = current_program
continue
if not in_procedure:
item = _DATA_ITEM.match(upper)
if item:
name = item.group(1).upper()
if name != "FILLER":
item_id = add_node(
_make_id(current_program, "data", name.casefold()),
name,
line,
kind="data_item",
)
add_edge(current_program, item_id, "contains", line)
continue
paragraph = _PARAGRAPH.match(upper)
if paragraph and paragraph.group(1) not in _NOT_PARAGRAPHS:
name = paragraph.group(1).upper()
key = (current_program, name.casefold())
paragraph_id = paragraphs.get(key)
if paragraph_id is None:
paragraph_id = add_node(
_make_id(current_program, "paragraph", name.casefold()),
name,
line,
kind="section" if paragraph.group(2) else "paragraph",
callable_node=True,
)
paragraphs[key] = paragraph_id
add_edge(current_program, paragraph_id, "contains", line)
current_scope = paragraph_id
continue
masked = _mask_strings(upper)
for match in _PERFORM.finditer(masked):
# `PERFORM A THRU Z` runs the range A..Z, so both endpoints are
# performed — link both. Only the entry paragraph was captured
# before, leaving the range-end with no inbound edge ("what performs
# Z?" answered nothing even though this paragraph does). Intermediate
# paragraphs in the range are not individually linked (that needs
# source ordering); the two endpoints are the reliable, common signal.
for group in (match.group(1), match.group(2)):
if group is None:
continue
name = group.upper()
if name not in _PERFORM_MODIFIERS:
pending_performs.append((current_scope, current_program, name, line))
for match in _CALL.finditer(upper):
if _starts_inside_string(upper, match.start()):
continue
callee = match.group(2).upper()
raw_calls.append({
"caller_nid": current_scope,
"callee": callee,
"language": "cobol",
"source_file": source_file,
"source_location": f"L{line}",
})
for caller_id, program_id, name, line in pending_performs:
target_id = paragraphs.get((program_id, name.casefold()))
if target_id is not None:
add_edge(caller_id, target_id, "calls", line)
clean_edges = [
edge for edge in edges
if edge["source"] in seen_ids
and (edge["target"] in seen_ids or edge["relation"] == "imports_from")
]
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
-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}
-474
View File
@@ -1,474 +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],
all_edges: list[dict] | None = None,
) -> dict[tuple[str, str], str]:
"""Return deterministic ``(namespace, name) -> node_id`` C# type definitions."""
non_type_ids: set[str] = set()
if all_edges is not None:
for edge in all_edges:
rel = edge.get("relation")
if rel in ("case_of", "defines", "method"):
tgt = edge.get("_tgt") or edge.get("target")
if isinstance(tgt, str):
non_type_ids.add(tgt)
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
if all_edges is not None and nid in non_type_ids:
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, all_edges)
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, all_edges)
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
]
-589
View File
@@ -1,589 +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
part_of_line = None
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
part_of_line = _line_at(part_of_match.start(1))
except Exception:
pass
# Every scanned file keeps its own file node. For a part file the symbols
# still belong to the library (file_nid above); the part's node is linked
# from the library and to its symbols at the end of extraction.
own_nid = _make_id(str(path))
nodes = [{"id": own_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
# A directive may carry configurable URIs that pick a platform-specific
# library: `export 'x_stub.dart' if (dart.library.io) 'x_io.dart';`. The
# default URI keeps its plain edge; every `if (...)` alternative is emitted
# too, tagged context="conditional_uri", because the real implementation
# usually lives there. A string literal inside the condition itself
# (`if (dart.library.io == 'true')`) is part of the test, not a URI.
quoted = r"""(?:'[^']*'|"[^"]*")"""
condition = rf"""if\s*\(\s*[\w.]+\s*(?:==\s*{quoted}\s*)?\)\s*"""
branch_re = re.compile(rf"""{condition}(['"])(?P<uri>[^'"]+)\1""")
for kind, relation in (("import", "imports"), ("export", "exports")):
directive_re = re.compile(
rf"""^\s*{kind}\s+(['"])(?P<uri>[^'"]+)\1(?P<branches>(?:\s*{condition}{quoted})*)""",
re.MULTILINE,
)
for m in directive_re.finditer(src_clean):
uris: list[tuple[str, int, str | None]] = [(m.group("uri"), m.start("uri"), None)]
for bm in branch_re.finditer(m.group("branches")):
uris.append((bm.group("uri"), m.start("branches") + bm.start("uri"), "conditional_uri"))
for pkg, offset, context in uris:
tgt_nid = _make_id(pkg)
add_node(tgt_nid, pkg, source_file=None)
add_edge(file_nid, tgt_nid, relation, context=context, line=_line_at(offset))
# 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)))
if is_part:
# The library includes this part; the part physically contains the
# declarations the library defines from it. Ids stay in the library's
# namespace, so the library is not split in two.
part_edges = [{**e, "source": own_nid, "relation": "contains"}
for e in edges
if e["source"] == file_nid and e["relation"] == "defines"]
add_edge(file_nid, own_nid, "includes", line=part_of_line)
edges.extend(part_edges)
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}
-345
View File
@@ -1,345 +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)
# Elixir scopes `import`/`use` to the module body it appears in and to the
# modules nested in it, so targets are recorded per enclosing module (None
# is the file's top level), along with each module's and function's parent.
call_scope: dict[str | None, list[str]] = {}
enclosing: dict[str, str | None] = {}
_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 _get_defimpl_target(node) -> str | None:
"""The `for:` target module of a `defimpl Proto, for: Type` argument
list. The grammar holds it in a trailing `keywords` node as a `pair`
whose keyword is `for:` and whose value is an `alias`."""
for child in node.children:
if child.type != "keywords":
continue
for pair in child.children:
if pair.type != "pair":
continue
kw = None
val = None
for sub in pair.children:
if sub.type == "keyword":
kw = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
elif sub.type == "alias":
val = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
if kw and kw.rstrip(": ").strip() == "for" and val:
return val
return None
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)
enclosing[module_nid] = parent_module_nid
if do_block_node:
for child in do_block_node.children:
walk(child, parent_module_nid=module_nid)
return
if keyword == "defprotocol":
# A protocol is a module-like named container. Without this branch
# the `defprotocol` call fell through to the generic recursion with
# parent_module_nid=None, so the protocol node was never minted and
# its callbacks (`def size(data)`) were attached to the FILE instead
# of the protocol.
proto_name = _get_alias_text(arguments_node) if arguments_node else None
if not proto_name:
return
proto_nid = _make_id(stem, proto_name)
add_node(proto_nid, proto_name, line,
**({"_elixir_module": True} if parent_module_nid is None else {}))
add_edge(parent_module_nid or file_nid, proto_nid, "contains", line)
enclosing[proto_nid] = parent_module_nid
if do_block_node:
for child in do_block_node.children:
walk(child, parent_module_nid=proto_nid)
return
if keyword == "defimpl":
# `defimpl Proto, for: Type do ... end`. Same orphaning bug as
# defprotocol: the implementation's functions leaked onto the file.
proto_name = _get_alias_text(arguments_node) if arguments_node else None
if not proto_name:
return
target = _get_defimpl_target(arguments_node)
impl_nid = _make_id(stem, "defimpl", proto_name, target or "")
label = f"{proto_name} (for {target})" if target else proto_name
add_node(impl_nid, label, line)
add_edge(parent_module_nid or file_nid, impl_nid, "contains", line)
enclosing[impl_nid] = parent_module_nid
# Link the implementation to the protocol it satisfies. A same-file
# protocol resolves directly; a cross-file target is filtered out by
# the dangling-edge guard below rather than left hanging.
add_edge(impl_nid, _make_id(stem, proto_name), "implements", line)
if do_block_node:
for child in do_block_node.children:
walk(child, parent_module_nid=impl_nid)
return
# `defmacro`/`defmacrop` (macros) and `defguard`/`defguardp` (guard
# macros) define named, invocable members with the exact same head shape
# as `def`/`defp` — a `call` head, optionally wrapped in a `when`
# binary_operator. They were not in this branch, so they fell through to
# the generic recursion and were dropped entirely: the member was never a
# node and a call to it (e.g. a macro invoked elsewhere) had nothing to
# resolve to. Handle them identically to def/defp; they are already in the
# call-pass _SKIP_KEYWORDS so their own keyword is never mistaken for a call.
if keyword in ("def", "defp", "defmacro", "defmacrop",
"defguard", "defguardp"):
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)
enclosing[func_nid] = parent_module_nid
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")
# Only import/use bring functions into scope for unqualified
# calls; alias/require do not.
if keyword in ("import", "use"):
call_scope.setdefault(parent_module_nid, []).append(module_name)
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 _call_scope_for(caller_nid: str) -> list[str]:
"""import/use targets visible to a call inside ``caller_nid``: its own
module's, each enclosing module's, then the file's top-level ones."""
scope: list[str] = []
seen: set[str] = set() # a module nested in a same-named one shares its nid
container = enclosing.get(caller_nid)
while container is not None and container not in seen:
seen.add(container)
scope.extend(call_scope.get(container, ()))
container = enclosing.get(container)
scope.extend(call_scope.get(None, ()))
return scope
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}",
"elixir_call_scope": _call_scope_for(caller_nid),
})
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
Loaded 100 of 774 files, more files were not shown because too many files have changed in this diff. Show more