Compare commits

..
4 Commits
Author SHA1 Message Date
Safi 43baaf1950 Merge pull request #881 from cbeaulieu-gt/v7
Merging as-is — clean case study with no code risk.
2026-05-15 23:24:24 +01:00
Christopher Beaulieu 230a75c4f6 Merge pull request #1 from cbeaulieu-gt/evaluation/rsl-siege-manager
worked(case-study): add rsl-siege-manager (Python + TypeScript monorepo)
2026-05-15 13:26:22 -04:00
Christopher BeaulieuandClaude Opus 4.7 3d99603e8d refactor(eval): restructure as worked/ case study for upstream alignment
Restructures the rsl-siege-manager evaluation to match upstream's
worked/karpathy-repos/ convention before opening against safishamsi/graphify:

- Move evaluations/rsl-siege-manager/ -> worked/rsl-siege-manager/
- Flatten graphify-out-with-tests/ artifacts to the case directory root
  (matches karpathy-repos layout: README.md, review.md, GRAPH_REPORT.md,
  graph.html, graph.json, manifest.json at top level).
- Drop the codebase-only artifact set; keep only the tests-included run as
  the more realistic default (most users won't pre-configure .graphifyignore).
- Rename runbook.md -> README.md (corpus description + reproduction steps).
- Rename results.md -> review.md (matches karpathy-repos), and reframe from
  "do not adopt" verdict to neutral findings + suggested follow-ups.
- Drop evaluations/README.md fork-only index.
- Revert .gitignore evaluations/ exception block — no longer needed now that
  artifacts live at worked/rsl-siege-manager/ (no graphify-out/ in path).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 13:22:04 -04:00
Christopher BeaulieuandClaude Opus 4.7 5685984110 evaluation(rsl-siege-manager): capture dry-run results + verdict
Adds the rsl-siege-manager evaluation under a new `evaluations/` convention:

- `evaluations/README.md` — directory index for future evaluations.
- `evaluations/rsl-siege-manager/runbook.md` — methodology used (relocated
  from siege-web's `docs/experiments/graphify-dry-run.md`).
- `evaluations/rsl-siege-manager/results.md` — decision log with quoted
  findings and acid-test scoring. Verdict: do not adopt.
- `evaluations/rsl-siege-manager/graphify-out/` and `…-with-tests/` — raw
  artifacts (GRAPH_REPORT.md, graph.html, graph.json, manifest.json) so
  quoted findings stay auditable. AST cache excluded.

Also extends `.gitignore` with a scoped exception so the rule that hides
fresh `graphify-out/` from a developer's working checkout still applies,
while committed evaluation artifacts under `evaluations/` are preserved.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 11:08:27 -04:00
38 changed files with 344 additions and 6934 deletions

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
# Tell GitHub Linguist to ignore generated/example HTML files when calculating
# the repo's primary language. Without this, large graph.html artifacts in
# worked/ dominate the byte count and the repo shows as HTML instead of Python.
worked/**/*.html linguist-vendored=true
graphify-out/**/*.html linguist-vendored=true
*.html linguist-detectable=false
+2 -2
View File
@@ -2,9 +2,9 @@ name: CI
on:
push:
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
pull_request:
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
workflow_dispatch:
jobs:
+1
View File
@@ -21,6 +21,7 @@ skills/
docs/superpowers/
.vscode/
openspec/
uv.lock
# Local benchmark scripts — never commit
scripts/run_k2_*.py
scripts/llm.py
-57
View File
@@ -2,63 +2,6 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.8.7 (2026-05-16)
- Fix: query seed selection now uses IDF weighting — common terms like `error` or `handle` that match dozens of nodes are down-weighted so a rare identifier like `FooBarService` ranks first and BFS expands from the right node (#897)
- Fix: seed count is now dynamic — a dominant match (score gap >80% vs next candidate) gets one seed rather than always picking three, preventing noise nodes from consuming BFS slots alongside the target (#897)
- Fix: truncation message in `query_graph` now tells Claude what to do (call `get_node` or add a `context_filter`) rather than just saying "truncated" (#897)
- Fix: C++ class data members (`int x;`, `static const int MAX = 100;`) now extracted as nodes with `defines` edges from the parent class — previously the field_declaration branch was a no-op due to a wrong child type guard (#898)
- Fix: dedup Pass 1 now partitions same-label groups by source_file before merging — nodes with generic labels (`handle`, `init`, `run`) from different files no longer collapse into artificial god nodes; cross-file matches are routed to Pass 2 fuzzy (#895)
- Fix: C/C++ `#include "path/to/file.h"` edges now resolve the include path relative to the including file and use the full resolved path as the target node ID, matching what extraction creates for the included file — previously all include edges dangled with a basename-only ID (#899)
- Fix: `exact_merges` counter in dedup now reports only merges actually performed rather than counting all same-label nodes across files (#895)
## 0.8.6 (2026-05-16)
- Fix: cross-language INFERRED `calls`/`uses` edges (e.g. Python → TypeScript) are suppressed in Surprising Connections — label-matching across language boundaries in monorepos is resolver pollution, not structural insight; all structural bonuses zeroed for these edges
- Fix: code-to-doc INFERRED `calls`/`uses` edges suppressed in Surprising Connections — the LLM seeing a symbol name in a README and emitting a `calls` edge is documentation cross-reference noise, not a real architectural connection (#890)
- Fix: generic JSON key nodes (`name`, `id`, `type`, `start`, `end`, `key`, `value`, `data`, `items`, `title`, `description`, `version`, `properties`) filtered from god_nodes — their degree is positional (every sibling record in the same JSON file references them), not architectural (#890)
- Fix: Alembic migrations, Django migrations, and protobuf-generated files now have their module-level docstrings suppressed from rationale extraction — these are boilerplate headers, not design intent; function docstrings inside migration files are still captured
- Feat: `--follow-symlinks` is now auto-detected — if symlinked children are present in the target directory, follow-symlinks is enabled automatically without requiring an explicit flag (#887)
- Fix: install guidance now directs users to run `/graphify query` interactively rather than reading `GRAPH_REPORT.md` first; the report is a summary, not a starting point (#891)
## 0.8.5 (2026-05-15)
- Fix: `.graphifyignore` parent-exclusion rule now correctly blocks files under an excluded directory even when a `!` negation exists elsewhere in the file — previously any negation pattern disabled directory pruning entirely (#882)
- Fix: dedup no longer false-merges chip/model SKU variants like `ASR1603`/`ASR1605` or `M1`/`M1 Pro` — Jaro-Winkler prefix bonus is now gated by `_is_variant_pair` and `_short_label_blocked` guards; real typos on short labels still merge (#878)
- Docs: added `worked/rsl-siege-manager/` — case study on a real-world Python + TypeScript monorepo (FastAPI backend, React/Vite frontend, Discord bot); covers god node behaviour with tests included, cross-language INFERRED edges, community cohesion, and Alembic migration noise (#881)
## 0.8.4 (2026-05-15)
- Feat: Firebird SQL — trigger and stored procedure extraction via `CREATE TRIGGER` and regex fallback; FK detection via global regex covering `REFERENCES` and `FOREIGN KEY` clauses (#875)
- Fix: SQL extraction regex fallback now decodes source as UTF-8 instead of latin-1, preventing non-ASCII identifier hash mismatches (#875)
- Fix: `--update` deletion pruning now matches on full source file paths instead of basenames, preventing false node removal when different directories contain files with the same name (#876)
- Fix: `--update` now also prunes edges whose `source_file` attr points to deleted files, not just nodes (#876)
- Fix: community label keys from `graph.json` (stored as strings) are now coerced to int before lookup, fixing blank community names in GRAPH_REPORT.md and graph.html (#877)
## 0.8.3 (2026-05-15)
- Fix: Windows skill temp files (chunk JSONs, `.graphify_python`, `.graphify_root`) no longer pollute the project root — all written under `graphify-out/` (#831)
- Fix: `--update` with deletions-only no longer errors when `.graphify_extract.json` does not yet exist — creates an empty extraction file before merging (#876)
## 0.8.2 (2026-05-15)
- Fix: Python interpreter detection for `uv tool` and `pipx` installs on Windows — `graphify install` and all skill steps now find the correct executable (#831)
- Fix: antigravity Windows skill path resolution (#831)
- Fix: dot directories (e.g. `.github/`, `.vscode/`) are now indexed when explicitly included via `.graphifyignore` (#873)
- Fix: MCP server hot-reloads the graph when `graph.json` changes on disk (#874)
## 0.8.1 (2026-05-15)
- Feat: Bash extractor — `.sh` and `.bash` files now indexed via tree-sitter; extracts functions, cross-function calls, `source`/`.` imports resolved to real file paths, and `export`/`declare` variable declarations (#866)
- Feat: JSON extractor — `.json` files now indexed via tree-sitter; extracts key/value `contains` tree, `dependencies`/`devDependencies` blocks as `imports` edges, `extends` edges (tsconfig, eslintrc), and `$ref` references (#866)
- Feat: `.sh`, `.bash`, `.json` added to `CODE_EXTENSIONS` in `detect.py` so files are picked up during corpus scan (#866)
- Feat: Mermaid callflow HTML auto-regenerates on every graph rebuild when `*-callflow.html` exists in `graphify-out/` — works with `--watch` and `graphify hook install`
- Fix: `coverage/`, `lcov-report/`, `visual-tests/`, `visual-test/`, `__snapshots__/`, `snapshots/`, `storybook-static/`, `dist-protected/` added to `_SKIP_DIRS` — generated artefact dirs no longer appear in the corpus (#869, #870)
- Fix: `graphify hook install` now works in git linked worktrees — uses `git rev-parse --git-path hooks` instead of constructing `.git/hooks/` directly (#865)
- Fix: office sidecar files in `graphify-out/converted/` are now checked against `.graphifyignore` before being added to the file list (#861)
- Fix: `save_manifest()` accepts a `kind` parameter (`ast`, `semantic`, `both`) — incremental AST-only `graphify update` no longer overwrites `semantic_hash` entries, preventing spurious full re-extracts on the next run (#857)
- Fix: five paths in `skill-windows.md` Step B3 were missing the `graphify-out/` prefix, causing chunk files to be written to the wrong directory (#862)
## 0.7.19 (2026-05-14)
- Feat: `.astro` files now extracted as code — frontmatter static imports, dynamic imports, and `<script>` block imports all produce edges; tsconfig path aliases resolved (#850, PR #852)
+6 -6
View File
@@ -8,7 +8,7 @@
<p align="center">
<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://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v7" alt="CI"/></a>
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
<a href="https://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>
@@ -174,7 +174,7 @@ Run this once in your project after building a graph:
| Pi coding agent | `graphify pi 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. On platforms that support payload-bearing hooks (Claude Code, Gemini CLI), a hook fires automatically before search-style tool calls 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.
This writes a small config file that tells your assistant to read `GRAPH_REPORT.md` before answering questions about your codebase. On platforms that support hooks (Claude Code, Codex, Gemini CLI), a hook fires automatically before every file-read call — your assistant navigates by the graph instead of grepping through everything.
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`).
@@ -194,7 +194,7 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| Type | Extensions |
|------|-----------|
| Code (31 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json` |
| Code (29 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk` |
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (requires `pip install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `pip install graphifyy[google]`) |
@@ -229,7 +229,7 @@ You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into
/graphify . --cluster-only # rerun clustering without re-extracting
/graphify . --no-viz # skip the HTML, just the report + JSON
/graphify . --wiki # build a markdown wiki from the graph
graphify export callflow-html # Mermaid architecture/call-flow HTML (auto-regenerates on every git commit if hook is installed)
graphify export callflow-html # architecture/call-flow HTML from graphify-out/
/graphify query "what connects auth to the database?"
/graphify path "UserService" "DatabasePool"
@@ -513,7 +513,7 @@ Clone the repo and install in editable mode:
```bash
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v8 # active development branch
git checkout v7 # active development branch
# Create a virtual environment (Python 3.10+ required):
python3 -m venv .venv
@@ -542,7 +542,7 @@ pytest tests/ -q -k "python" # filter by name
### Git workflow
- Active development happens on the `v8` branch.
- Active development happens on the `v7` branch.
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
- Before opening a PR, run `pytest tests/ -q` and confirm it passes.
- Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py` for any new language extractor.
+54 -132
View File
@@ -62,7 +62,7 @@ _SETTINGS_HOOK = {
"case \"$CMD\" in "
r"*grep*|*rg\ *|*ripgrep*|*find\ *|*fd\ *|*ack\ *|*ag\ *) "
" [ -f graphify-out/graph.json ] && "
r""" echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: knowledge graph at graphify-out/. For focused questions, run `graphify query \"<question>\"` (scoped subgraph, usually much smaller than GRAPH_REPORT.md) instead of grepping raw files. Read GRAPH_REPORT.md only for broad architecture context."}}' """
r""" echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
" || true ;; "
"esac"
),
@@ -145,11 +145,6 @@ _PLATFORM_CONFIG: dict[str, dict] = {
"skill_dst": Path(".agents") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"antigravity-windows": {
"skill_file": "skill-windows.md",
"skill_dst": Path(".agents") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"windows": {
"skill_file": "skill-windows.md",
"skill_dst": Path(".claude") / "skills" / "graphify" / "SKILL.md",
@@ -163,51 +158,6 @@ _PLATFORM_CONFIG: dict[str, dict] = {
}
def _replace_or_append_section(content: str, marker: str, new_section: str) -> str:
"""Idempotently update or append a graphify-owned section in shared files.
If ``marker`` is not in ``content``, append ``new_section`` to the end
(with a blank-line separator if there's existing content).
If ``marker`` IS in ``content``, replace the existing section in place.
The section runs from the first line containing ``marker`` to the line
before the next H2 heading (``## `` at line start), or to EOF if no later
H2 exists. This lets older installs receive the updated copy without
users having to uninstall and reinstall — important for the issue #580
fix where existing report-first text would otherwise silently linger.
"""
if marker not in content:
if content.strip():
return content.rstrip() + "\n\n" + new_section.lstrip()
return new_section.lstrip()
lines = content.split("\n")
start = next((i for i, line in enumerate(lines) if marker in line), None)
if start is None:
return content.rstrip() + "\n\n" + new_section.lstrip()
end = len(lines)
for j in range(start + 1, len(lines)):
if lines[j].startswith("## "):
end = j
break
head = "\n".join(lines[:start]).rstrip()
tail = "\n".join(lines[end:]).lstrip()
section = new_section.strip()
parts: list[str] = []
if head:
parts.append(head)
parts.append(section)
if tail:
parts.append(tail)
out = "\n\n".join(parts)
if not out.endswith("\n"):
out += "\n"
return out
def install(platform: str = "claude") -> None:
if platform == "gemini":
gemini_install()
@@ -215,9 +165,6 @@ def install(platform: str = "claude") -> None:
if platform == "cursor":
_cursor_install(Path("."))
return
# On Windows, antigravity needs the PowerShell skill, not the bash one
if platform == "antigravity" and sys.platform == "win32":
platform = "antigravity-windows"
if platform not in _PLATFORM_CONFIG:
print(
f"error: unknown platform '{platform}'. Choose from: {', '.join(_PLATFORM_CONFIG)}, gemini, cursor",
@@ -292,9 +239,9 @@ _CLAUDE_MD_SECTION = """\
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
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.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- ALWAYS read graphify-out/GRAPH_REPORT.md before reading any source files, running grep/glob searches, or answering codebase questions. The graph is your primary map of the codebase.
- IF graphify-out/wiki/index.md EXISTS, navigate it instead of reading raw files
- For cross-module "how does X relate to Y" questions, prefer `graphify query "<question>"`, `graphify path "<A>" "<B>"`, or `graphify explain "<concept>"` over grep — these traverse the graph's EXTRACTED + INFERRED edges instead of scanning files
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
"""
@@ -310,9 +257,9 @@ This project has a knowledge graph at graphify-out/ with god nodes, community st
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.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- ALWAYS read graphify-out/GRAPH_REPORT.md before reading any source files, running grep/glob searches, or answering codebase questions. The graph is your primary map of the codebase.
- IF graphify-out/wiki/index.md EXISTS, navigate it instead of reading raw files
- For cross-module "how does X relate to Y" questions, prefer `graphify query "<question>"`, `graphify path "<A>" "<B>"`, or `graphify explain "<concept>"` over grep — these traverse the graph's EXTRACTED + INFERRED edges instead of scanning files
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
"""
@@ -324,9 +271,9 @@ _GEMINI_MD_SECTION = """\
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
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.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- ALWAYS read graphify-out/GRAPH_REPORT.md before reading any source files, running grep/glob searches, or answering codebase questions. The graph is your primary map of the codebase.
- IF graphify-out/wiki/index.md EXISTS, navigate it instead of reading raw files
- For cross-module "how does X relate to Y" questions, prefer `graphify query "<question>"`, `graphify path "<A>" "<B>"`, or `graphify explain "<concept>"` over grep — these traverse the graph's EXTRACTED + INFERRED edges instead of scanning files
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
"""
@@ -342,7 +289,7 @@ _GEMINI_HOOK = {
"import sys,pathlib,json;"
"e=pathlib.Path('graphify-out/graph.json').exists();"
"d={'decision':'allow'};"
"e and d.update({'additionalContext':'graphify: knowledge graph at graphify-out/. For focused questions, run `graphify query \"<question>\"` (scoped subgraph, usually much smaller than GRAPH_REPORT.md) instead of grepping raw files. Read GRAPH_REPORT.md only for broad architecture context.'});"
"e and d.update({'additionalContext':'graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files.'});"
"sys.stdout.write(json.dumps(d))"
'"'
),
@@ -369,20 +316,15 @@ def gemini_install(project_dir: Path | None = None) -> None:
if target.exists():
content = target.read_text(encoding="utf-8")
new_content = _replace_or_append_section(
content, _GEMINI_MD_MARKER, _GEMINI_MD_SECTION
)
if _GEMINI_MD_MARKER in content:
print("graphify already configured in GEMINI.md")
else:
target.write_text(content.rstrip() + "\n\n" + _GEMINI_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
else:
new_content = _GEMINI_MD_SECTION
if target.exists() and new_content == target.read_text(encoding="utf-8"):
print(f"graphify already configured in {target.resolve()} (no change)")
else:
target.write_text(new_content, encoding="utf-8")
target.write_text(_GEMINI_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
# Always re-install the Gemini hook so an older payload (e.g. pre-issue-#580
# wording) is replaced on upgrade.
_install_gemini_hook(project_dir or Path("."))
print()
print("Gemini CLI will now check the knowledge graph before answering")
@@ -462,18 +404,14 @@ _VSCODE_INSTRUCTIONS_SECTION = """\
## graphify
For any question about this repo's architecture, structure, components, or how to add/modify/find
code, your first action should be `graphify query "<question>"` when `graphify-out/graph.json`
exists. Use `graphify path "<A>" "<B>"` for relationship questions and `graphify explain "<concept>"`
for focused-concept questions. These return a scoped subgraph, usually much smaller than the full
report or raw grep output.
code, your **first tool call must be** to read `graphify-out/GRAPH_REPORT.md` (if it exists).
Triggers: "how do I…", "where is…", "what does … do", "add/modify a <component>",
"explain the architecture", or anything that depends on how files or classes relate.
If `graphify-out/wiki/index.md` exists, use it for broad navigation. Read `graphify-out/GRAPH_REPORT.md`
only for broad architecture review or when query/path/explain do not surface enough context. Only read
source files when (a) modifying/debugging specific code, (b) the graph lacks the needed detail, or
(c) the graph is missing or stale.
After reading the report (and `graphify-out/wiki/index.md` for deep questions), answer from the
graph. Only read source files when (a) modifying/debugging specific code, (b) the graph lacks
the needed detail, or (c) the graph is missing or stale.
Type `/graphify` in Copilot Chat to build or update the graph.
"""
@@ -494,14 +432,11 @@ def vscode_install(project_dir: Path | None = None) -> None:
instructions.parent.mkdir(parents=True, exist_ok=True)
if instructions.exists():
content = instructions.read_text(encoding="utf-8")
new_content = _replace_or_append_section(
content, _VSCODE_INSTRUCTIONS_MARKER, _VSCODE_INSTRUCTIONS_SECTION
)
if new_content == content:
if _VSCODE_INSTRUCTIONS_MARKER in content:
print(f" {instructions} -> already configured (no change)")
else:
instructions.write_text(new_content, encoding="utf-8")
print(f" {instructions} -> graphify section {'updated' if _VSCODE_INSTRUCTIONS_MARKER in content else 'added'}")
instructions.write_text(content.rstrip() + "\n\n" + _VSCODE_INSTRUCTIONS_SECTION, encoding="utf-8")
print(f" {instructions} -> graphify section added")
else:
instructions.write_text(_VSCODE_INSTRUCTIONS_SECTION, encoding="utf-8")
print(f" {instructions} -> created")
@@ -547,7 +482,7 @@ _ANTIGRAVITY_WORKFLOW_PATH = Path(".agents") / "workflows" / "graphify.md"
_ANTIGRAVITY_RULES = """\
---
trigger: always_on
description: Consult the graphify knowledge graph at graphify-out/ for codebase and architecture questions.
description: Always consult the graphify knowledge graph at graphify-out/ before answering codebase or architecture questions.
---
## graphify
@@ -555,9 +490,10 @@ description: Consult the graphify knowledge graph at graphify-out/ for codebase
This project has a graphify knowledge graph at graphify-out/.
Rules:
- For codebase or architecture questions, when `graphify-out/graph.json` exists, first run `graphify query "<question>"` (CLI) or `query_graph` (MCP). Use `graphify path "<A>" "<B>"` / `shortest_path` for relationships and `graphify explain "<concept>"` / `get_node` for focused concepts. These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output.
- 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
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context
- If the graphify MCP server is active, utilize tools like `query_graph`, `get_node`, and `shortest_path` for precise architecture navigation instead of falling back to `grep`
- If the MCP server is not active, the CLI equivalents are `graphify query "<question>"`, `graphify path "<A>" "<B>"`, and `graphify explain "<concept>"` - prefer these over grep for cross-module questions
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
"""
@@ -581,10 +517,9 @@ inclusion: always
---
graphify: A knowledge graph of this project lives in `graphify-out/`. \
For codebase, architecture, or dependency questions, when `graphify-out/graph.json` exists, \
first run `graphify query "<question>"` (or `graphify path "<A>" "<B>"` / `graphify explain "<concept>"`). \
These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output. \
Read `GRAPH_REPORT.md` only for broad architecture review or when those commands do not surface enough context.
If `graphify-out/GRAPH_REPORT.md` exists, read it before answering architecture questions, \
tracing dependencies, or searching files — it contains god nodes, community structure, \
and surprising connections the graph found. Navigate by graph structure instead of grepping raw files.
"""
_KIRO_STEERING_MARKER = "graphify: A knowledge graph of this project"
@@ -605,14 +540,11 @@ def _kiro_install(project_dir: Path) -> None:
steering_dir = project_dir / ".kiro" / "steering"
steering_dir.mkdir(parents=True, exist_ok=True)
steering_dst = steering_dir / "graphify.md"
if steering_dst.exists() and steering_dst.read_text(encoding="utf-8") == _KIRO_STEERING:
print(f" .kiro/steering/graphify.md -> already configured (no change)")
if steering_dst.exists() and _KIRO_STEERING_MARKER in steering_dst.read_text(encoding="utf-8"):
print(f" .kiro/steering/graphify.md -> already configured")
else:
# File is wholly graphify-owned. Overwrite on upgrade so older
# report-first wording does not silently linger (issue #580).
action = "updated" if steering_dst.exists() else "written"
steering_dst.write_text(_KIRO_STEERING, encoding="utf-8")
print(f" .kiro/steering/graphify.md -> always-on steering {action}")
print(f" .kiro/steering/graphify.md -> always-on steering written")
print()
print("Kiro will now read the knowledge graph before every conversation.")
@@ -664,7 +596,7 @@ def _antigravity_install(project_dir: Path) -> None:
rules_path.write_text(_ANTIGRAVITY_RULES, encoding="utf-8")
print(f"graphify rule updated at {rules_path.resolve()}")
else:
print(f"graphify rule already configured at {rules_path.resolve()} (no change)")
print(f"graphify rule already up to date at {rules_path.resolve()}")
else:
rules_path.write_text(_ANTIGRAVITY_RULES, encoding="utf-8")
print(f"graphify rule written to {rules_path.resolve()}")
@@ -678,7 +610,7 @@ def _antigravity_install(project_dir: Path) -> None:
wf_path.write_text(_ANTIGRAVITY_WORKFLOW, encoding="utf-8")
print(f"graphify workflow updated at {wf_path.resolve()}")
else:
print(f"graphify workflow already configured at {wf_path.resolve()} (no change)")
print(f"graphify workflow already up to date at {wf_path.resolve()}")
else:
wf_path.write_text(_ANTIGRAVITY_WORKFLOW, encoding="utf-8")
print(f"graphify workflow written to {wf_path.resolve()}")
@@ -734,9 +666,8 @@ alwaysApply: true
This project has a graphify knowledge graph at graphify-out/.
- For codebase or architecture questions, when `graphify-out/graph.json` exists, first run `graphify query "<question>"` (or `graphify path "<A>" "<B>"` / `graphify explain "<concept>"`). These return a scoped subgraph, usually much smaller than `GRAPH_REPORT.md` or raw grep output.
- 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
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
"""
@@ -745,14 +676,11 @@ def _cursor_install(project_dir: Path) -> None:
"""Write .cursor/rules/graphify.mdc with alwaysApply: true."""
rule_path = (project_dir or Path(".")) / _CURSOR_RULE_PATH
rule_path.parent.mkdir(parents=True, exist_ok=True)
if rule_path.exists() and rule_path.read_text(encoding="utf-8") == _CURSOR_RULE:
print(f"graphify rule at {rule_path} already configured (no change)")
if rule_path.exists():
print(f"graphify rule already exists at {rule_path} (no change)")
return
# File is wholly graphify-owned. Overwrite on upgrade so older
# report-first wording does not silently linger (issue #580).
action = "updated" if rule_path.exists() else "written"
rule_path.write_text(_CURSOR_RULE, encoding="utf-8")
print(f"graphify rule {action} at {rule_path.resolve()}")
print(f"graphify rule written to {rule_path.resolve()}")
print()
print("Cursor will now always include the knowledge graph context.")
print("Run /graphify . first to build the graph if you haven't already.")
@@ -786,7 +714,7 @@ export const GraphifyPlugin = async ({ directory }) => {
if (input.tool === "bash") {
output.args.command =
'echo "[graphify] knowledge graph at graphify-out/. For focused questions, run \\`graphify query \\"<question>\\"\\` (scoped subgraph, usually much smaller than GRAPH_REPORT.md) instead of grepping raw files. Read GRAPH_REPORT.md only for broad architecture context." && ' +
'echo "[graphify] Knowledge graph available. Read graphify-out/GRAPH_REPORT.md for god nodes and architecture context before searching files." && ' +
output.args.command;
reminded = true;
}
@@ -944,16 +872,13 @@ def _agents_install(project_dir: Path, platform: str) -> None:
if target.exists():
content = target.read_text(encoding="utf-8")
new_content = _replace_or_append_section(
content, _AGENTS_MD_MARKER, _AGENTS_MD_SECTION
)
if _AGENTS_MD_MARKER in content:
print(f"graphify already configured in AGENTS.md")
else:
target.write_text(content.rstrip() + "\n\n" + _AGENTS_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
else:
new_content = _AGENTS_MD_SECTION
if target.exists() and new_content == target.read_text(encoding="utf-8"):
print(f"graphify already configured in {target.resolve()} (no change)")
else:
target.write_text(new_content, encoding="utf-8")
target.write_text(_AGENTS_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
if platform == "codex":
@@ -1006,20 +931,17 @@ def claude_install(project_dir: Path | None = None) -> None:
if target.exists():
content = target.read_text(encoding="utf-8")
new_content = _replace_or_append_section(
content, _CLAUDE_MD_MARKER, _CLAUDE_MD_SECTION
)
if _CLAUDE_MD_MARKER in content:
print("graphify already configured in CLAUDE.md")
return
new_content = content.rstrip() + "\n\n" + _CLAUDE_MD_SECTION
else:
new_content = _CLAUDE_MD_SECTION
if target.exists() and new_content == target.read_text(encoding="utf-8"):
print(f"graphify already configured in {target.resolve()} (no change)")
else:
target.write_text(new_content, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
target.write_text(new_content, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
# Always re-install the Claude Code PreToolUse hook so an old hook
# payload (e.g. pre-issue-#580 wording) is replaced on upgrade.
# Also write Claude Code PreToolUse hook to .claude/settings.json
_install_claude_hook(project_dir or Path("."))
print()
+9 -38
View File
@@ -65,21 +65,6 @@ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
return False
_JSON_NOISE_LABELS: frozenset[str] = frozenset({
"start", "end", "name", "id", "type", "properties",
"value", "key", "data", "items", "title", "description", "version",
})
def _is_json_key_node(G: nx.Graph, node_id: str) -> bool:
attrs = G.nodes[node_id]
src = (attrs.get("source_file") or "").lower()
if not src.endswith(".json"):
return False
label = (attrs.get("label") or "").strip().lower()
return label in _JSON_NOISE_LABELS
def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
"""Return the top_n most-connected real entities - the core abstractions.
@@ -90,7 +75,7 @@ def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
sorted_nodes = sorted(degree.items(), key=lambda x: x[1], reverse=True)
result = []
for node_id, deg in sorted_nodes:
if _is_file_node(G, node_id) or _is_concept_node(G, node_id) or _is_json_key_node(G, node_id):
if _is_file_node(G, node_id) or _is_concept_node(G, node_id):
continue
result.append({
"id": node_id,
@@ -190,41 +175,30 @@ def _surprise_score(
relation = data.get("relation", "")
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
cat_u = _file_category(u_source)
cat_v = _file_category(v_source)
# Suppress all structural bonuses for INFERRED calls/uses that cross language
# boundaries or connect code to a doc file. Both cases are resolver pollution:
# label-matching fires across language families in monorepos, and code→doc
# "calls" edges are extraction artefacts, not real architecture.
# Excludes `semantically_similar_to` (genuine cross-boundary insight) and all
# AMBIGUOUS/EXTRACTED edges (not from the resolver path).
_suppress_structural = (
conf == "INFERRED"
and relation in ("calls", "uses")
and (_cross_language(u_source, v_source) or {cat_u, cat_v} == {"code", "doc"})
)
if _suppress_structural:
conf_bonus = 0
# Cross-language INFERRED calls are likely resolver pollution, not real surprises
if conf == "INFERRED" and relation == "calls" and _cross_language(u_source, v_source):
conf_bonus = 0 # downgrade: don't promote likely false positives
score += conf_bonus
if conf in ("AMBIGUOUS", "INFERRED"):
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
# 2. Cross file-type bonus - code↔paper or code↔image is non-obvious
if cat_u != cat_v and not _suppress_structural:
cat_u = _file_category(u_source)
cat_v = _file_category(v_source)
if cat_u != cat_v:
score += 2
reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
# 3. Cross-repo bonus - different top-level directory
if _top_level_dir(u_source) != _top_level_dir(v_source) and not _suppress_structural:
if _top_level_dir(u_source) != _top_level_dir(v_source):
score += 2
reasons.append("connects across different repos/directories")
# 4. Cross-community bonus - Leiden says these are structurally distant
cid_u = node_community.get(u)
cid_v = node_community.get(v)
if cid_u is not None and cid_v is not None and cid_u != cid_v and not _suppress_structural:
if cid_u is not None and cid_v is not None and cid_u != cid_v:
score += 1
reasons.append("bridges separate communities")
@@ -406,9 +380,6 @@ def suggest_questions(
Based on: AMBIGUOUS edges, bridge nodes, underexplored god nodes, isolated nodes.
Each question has a 'type', 'question', and 'why' field.
"""
if community_labels:
community_labels = {int(k) if isinstance(k, str) else k: v for k, v in community_labels.items()}
questions = []
node_community = _node_community_map(communities)
+4 -17
View File
@@ -295,12 +295,11 @@ def build_merge(
all_chunks = base + list(new_chunks)
G = build(all_chunks, directed=directed, dedup=dedup, dedup_llm_backend=dedup_llm_backend)
# Prune nodes and edges from deleted source files
# Prune nodes from deleted source files
if prune_sources:
prune_set = set(prune_sources)
to_remove = [
n for n, d in G.nodes(data=True)
if d.get("source_file") in prune_set
if d.get("source_file") in prune_sources
]
G.remove_nodes_from(to_remove)
n_files = len(prune_sources)
@@ -310,22 +309,10 @@ def build_merge(
f"[graphify] Pruned {n_nodes} node(s) from {n_files} deleted source file(s).",
file=sys.stderr,
)
edges_to_remove = [
(u, v) for u, v, d in G.edges(data=True)
if d.get("source_file") in prune_set
]
if edges_to_remove:
G.remove_edges_from(edges_to_remove)
print(
f"[graphify] Pruned {len(edges_to_remove)} edge(s) from deleted source file(s).",
file=sys.stderr,
)
if not n_nodes and not edges_to_remove:
else:
print(
f"[graphify] {n_files} source file(s) deleted since last run — "
f"no matching nodes or edges in graph, already clean.",
f"no matching nodes in graph, already clean.",
file=sys.stderr,
)
+8 -67
View File
@@ -46,45 +46,6 @@ def _make_minhash(text: str, num_perm: int = 128) -> MinHash:
return m
# Matches labels whose trailing token is a version/variant suffix:
# digits optionally followed by letters (chip SKUs: ASR1603, M1, Cortex-A55)
# or 2+ letters (codename revisions: cranelr vs cranel).
# Requires the stem to end in a letter so plain words don't accidentally match.
_VARIANT_SUFFIX = re.compile(r"^(.*[a-z])([0-9]+[a-z]*|[a-z]{2,})$")
def _is_variant_pair(a: str, b: str) -> bool:
"""True if a and b are sibling model/SKU variants (same stem, different suffix).
Only applied to short labels (< 12 chars); long labels go through JW normally.
"""
if a == b:
return False
if max(len(a), len(b)) >= 12:
return False
ma, mb = _VARIANT_SUFFIX.match(a), _VARIANT_SUFFIX.match(b)
if not (ma and mb):
return False
return ma.group(1) == mb.group(1) and ma.group(2) != mb.group(2)
def _short_label_blocked(a: str, b: str, jw_score: float) -> bool:
"""Block fuzzy merge for short labels unless it's a same-length single-char substitution.
Insertions/deletions on short strings (cranel/cranelr, M1/M1 Pro) produce
high Jaro-Winkler scores due to the prefix bonus but are almost never true
duplicates — they're abbreviations or variants.
"""
if max(len(a), len(b)) >= 12:
return False
from rapidfuzz.distance import DamerauLevenshtein
# Allow only same-length single-char substitutions (true typos like "Extractor"/"Extractar").
# Block length-differing pairs regardless of score.
if jw_score >= 97.0 and len(a) == len(b) and DamerauLevenshtein.distance(a, b) <= 1:
return False
return True
# ── union-find ────────────────────────────────────────────────────────────────
class _UF:
@@ -174,22 +135,13 @@ def deduplicate_entities(
norm_to_nodes[key].append(node)
uf = _UF()
exact_merges = 0
for key, group in norm_to_nodes.items():
if len(group) <= 1:
continue
# Partition by source_file — only merge within the same file in Pass 1.
# Cross-file matches fall through to Pass 2 fuzzy matching.
by_file: dict[str, list[dict]] = defaultdict(list)
for node in group:
sf = node.get("source_file") or ""
by_file[sf].append(node)
for file_group in by_file.values():
if len(file_group) > 1:
winner = _pick_winner(file_group)
for node in file_group:
uf.union(winner["id"], node["id"])
exact_merges += len(file_group) - 1
if len(group) > 1:
winner = _pick_winner(group)
for node in group:
uf.union(winner["id"], node["id"])
exact_merges = sum(len(g) - 1 for g in norm_to_nodes.values() if len(g) > 1)
# ── pass 2: MinHash/LSH + Jaro-Winkler (high-entropy nodes only) ─────────
candidates: list[dict] = []
@@ -233,15 +185,9 @@ def deduplicate_entities(
neighbor_norm = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
if _is_variant_pair(norm_label, neighbor_norm):
continue
if _short_label_blocked(norm_label, neighbor_norm, score):
continue
c1 = communities.get(node_id)
c2 = communities.get(neighbor_id)
if (c1 is not None and c2 is not None and c1 == c2
and min(len(norm_label), len(neighbor_norm)) >= 12):
if c1 is not None and c2 is not None and c1 == c2:
score += _COMMUNITY_BOOST
if score >= _MERGE_THRESHOLD:
@@ -351,14 +297,9 @@ def _llm_tiebreak(
continue
norm_j = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
if _is_variant_pair(norm_i, norm_j):
continue
if _short_label_blocked(norm_i, norm_j, score):
continue
c1 = communities.get(node["id"])
c2 = communities.get(neighbor["id"])
if (c1 is not None and c2 is not None and c1 == c2
and min(len(norm_i), len(norm_j)) >= 12):
if c1 is not None and c2 is not None and c1 == c2:
score += _COMMUNITY_BOOST
if low <= score < high:
ambiguous.append((node, neighbor, score))
+49 -90
View File
@@ -24,7 +24,7 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json'}
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
@@ -376,10 +376,6 @@ _SKIP_DIRS = {
"__snapshots__", "snapshots", # Jest/Vitest snapshot dirs
"storybook-static", # Storybook production build output
"dist-protected", # Protected dist variants (same noise as dist)
# Framework cache/build dirs — generated, never architecturally meaningful (#873)
".next", ".nuxt", ".turbo", ".angular",
".idea", ".cache", ".parcel-cache", ".svelte-kit", ".terraform", ".serverless",
".graphify", # graphify's own extraction cache — never index self-generated data
}
# Large generated files that are never useful to extract
@@ -481,76 +477,55 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
Uses gitignore last-match-wins semantics: all patterns are evaluated in
order; the final matching pattern determines the result. Negation patterns
(starting with !) un-ignore a previously ignored path.
Enforces gitignore's parent-exclusion rule: a ! pattern cannot re-include
a file whose ancestor directory is already excluded.
"""
if not patterns:
return False
def _eval(target: Path) -> bool:
"""Apply last-match-wins to a single target path."""
def _matches(rel: str, p: str) -> bool:
parts = rel.split("/")
if fnmatch.fnmatch(rel, p):
def _matches(rel: str, p: str) -> bool:
parts = rel.split("/")
if fnmatch.fnmatch(rel, p):
return True
if fnmatch.fnmatch(path.name, p):
return True
for i, part in enumerate(parts):
if fnmatch.fnmatch(part, p):
return True
if fnmatch.fnmatch(target.name, p):
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
return True
for i, part in enumerate(parts):
if fnmatch.fnmatch(part, p):
return True
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
return True
return False
return False
result = False
for anchor, pattern in patterns:
negated = pattern.startswith("!")
raw = pattern[1:] if negated else pattern
anchored = raw.startswith("/")
p = raw.strip("/")
if not p:
continue
result = False
for anchor, pattern in patterns:
negated = pattern.startswith("!")
raw = pattern[1:] if negated else pattern
anchored = raw.startswith("/")
p = raw.strip("/")
if not p:
continue
matched = False
if anchored:
matched = False
if anchored:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p)
except ValueError:
pass
else:
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
matched = _matches(rel, p)
except ValueError:
pass
if not matched and anchor != root:
try:
rel_anchor = str(target.relative_to(anchor)).replace(os.sep, "/")
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p)
except ValueError:
pass
else:
try:
rel = str(target.relative_to(root)).replace(os.sep, "/")
matched = _matches(rel, p)
except ValueError:
pass
if not matched and anchor != root:
try:
rel_anchor = str(target.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p)
except ValueError:
pass
if matched:
result = not negated # last match wins; ! flips to un-ignore
return result
# Gitignore parent-exclusion rule: a ! re-include cannot rescue a file
# whose ancestor directory is already excluded. Walk ancestors top-down;
# if any ancestor is excluded, the file is excluded regardless of later
# ! patterns targeting the file or a sub-path.
try:
rel_parts = path.relative_to(root).parts
except ValueError:
return _eval(path)
ancestor = root
for part in rel_parts[:-1]:
ancestor = ancestor / part
if _eval(ancestor):
return True
return _eval(path)
if matched:
result = not negated # last match wins; ! flips to un-ignore
return result
def _load_graphifyinclude(root: Path) -> list[tuple[Path, str]]:
@@ -662,29 +637,8 @@ def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Pa
return False
def _auto_follow_symlinks(root: Path) -> bool:
"""Auto-detect: ``True`` if ``root`` has any direct symlinked child.
Allows "fake working dir" patterns (e.g. a folder full of symlinks pointing
at scattered source dirs across the user's machine) to work transparently
without the caller having to know to pass ``follow_symlinks=True``.
Override is always possible by passing an explicit ``follow_symlinks=True``
or ``follow_symlinks=False`` to :func:`detect` / :func:`detect_incremental`.
"""
try:
for p in root.iterdir():
if p.is_symlink():
return True
except (OSError, PermissionError):
pass
return False
def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace: bool | None = None) -> dict:
def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool | None = None) -> dict:
root = root.resolve()
if follow_symlinks is None:
follow_symlinks = _auto_follow_symlinks(root)
google_workspace = google_workspace_enabled() if google_workspace is None else google_workspace
files: dict[FileType, list[str]] = {
FileType.CODE: [],
@@ -720,14 +674,15 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
continue
if not in_memory_tree:
# Prune noise dirs in-place so os.walk never descends into them.
# Dot dirs are allowed — users often want .github/, .claude/, etc.
# Framework caches (.next, .nuxt, …) are caught by _is_noise_dir.
# Hidden dirs are allowed through if they could contain an
# explicitly included path (.graphifyinclude allowlist).
# When negation patterns (!) exist, skip directory-level ignore
# pruning so negated files inside can still be reached.
has_negation = any(p.startswith("!") for _, p in ignore_patterns)
dirnames[:] = [
d for d in dirnames
if not _is_noise_dir(d)
if (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
and not _is_noise_dir(d)
and (has_negation or not _is_ignored(dp / d, root, ignore_patterns))
]
for fname in filenames:
@@ -744,6 +699,11 @@ def detect(root: Path, *, follow_symlinks: bool | None = None, google_workspace:
# For memory dir files, skip hidden/noise filtering
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
if not in_memory:
# Hidden files are already excluded via dir pruning above,
# but catch hidden files at the root level. A .graphifyinclude
# entry can opt a specific hidden file back in.
if p.name.startswith(".") and not _is_included(p, root, include_patterns):
continue
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
if str(p).startswith(str(converted_dir)):
continue
@@ -890,7 +850,7 @@ def detect_incremental(
root: Path,
manifest_path: str = _MANIFEST_PATH,
*,
follow_symlinks: bool | None = None,
follow_symlinks: bool = False,
google_workspace: bool | None = None,
kind: str = "semantic",
) -> dict:
@@ -914,8 +874,7 @@ def detect_incremental(
The ``follow_symlinks`` flag is forwarded to :func:`detect` so corpora that
rely on symlinked sub-trees (e.g. a ``state_of_truth/`` symlink pointing to a
directory outside the scan root) are scanned consistently between full and
incremental runs. ``None`` (default) means auto-detect: ``True`` when ``root``
contains at least one direct symlinked child, ``False`` otherwise.
incremental runs.
"""
full = detect(root, follow_symlinks=follow_symlinks, google_workspace=google_workspace)
manifest = load_manifest(manifest_path)
+23 -514
View File
@@ -537,41 +537,10 @@ def _import_java(node, source: bytes, file_nid: str, stem: str, edges: list, str
break
def _resolve_c_include_path(raw: str, str_path: str) -> "Path | None":
"""Resolve a quoted #include path to a real file on disk.
Searches relative to the including file's directory. Returns None for
system headers (<...>) or paths that don't exist on disk.
"""
if not raw:
return None
candidate = (Path(str_path).parent / raw).resolve()
if candidate.is_file():
return candidate
return None
def _import_c(node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str) -> None:
for child in node.children:
if child.type in ("string_literal", "system_lib_string", "string"):
raw = _read_text(child, source).strip('"<> ')
# Quoted includes: try to resolve to a real file so the target ID
# matches the node ID _extract_generic creates for that file.
if child.type != "system_lib_string":
resolved = _resolve_c_include_path(raw, str_path)
if resolved is not None:
tgt_nid = _make_id(str(resolved))
edges.append({
"source": file_nid,
"target": tgt_nid,
"relation": "imports",
"context": "import",
"confidence": "EXTRACTED",
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
"weight": 1.0,
})
break
module_name = raw.split("/")[-1].split(".")[0]
if module_name:
tgt_nid = _make_id(module_name)
@@ -703,8 +672,6 @@ def _get_cpp_func_name(node, source: bytes) -> str | None:
"""Recursively unwrap declarator to find the innermost identifier (C++)."""
if node.type == "identifier":
return _read_text(node, source)
if node.type in ("field_identifier", "destructor_name", "operator_name"):
return _read_text(node, source)
if node.type == "qualified_identifier":
name_node = node.child_by_field_name("name")
if name_node:
@@ -1492,23 +1459,6 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
"references", line, context="field")
return
if (config.ts_module == "tree_sitter_cpp"
and t == "field_declaration"
and parent_class_nid):
# Emit a node for each data member. Use children_by_field_name so we
# only visit declarator children, not the type node (which would give
# us the type name, not the field name). Handles int x, y; via
# multiple declarator fields and static const int MAX = 100; via the
# init_declarator → field_identifier recursion in _get_cpp_func_name.
for decl in node.children_by_field_name("declarator"):
name = _get_cpp_func_name(decl, source)
if name:
line = decl.start_point[0] + 1
field_nid = _make_id(parent_class_nid, name)
add_node(field_nid, name, line)
add_edge(parent_class_nid, field_nid, "defines", line, context="field")
return
# Function types
if t in config.function_types:
# Swift deinit/subscript have no name field — resolve before generic fallback
@@ -1916,27 +1866,6 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
_RATIONALE_PREFIXES = ("# NOTE:", "# IMPORTANT:", "# HACK:", "# WHY:", "# RATIONALE:", "# TODO:", "# FIXME:")
def _is_autogenerated_python(source: bytes) -> bool:
"""Return True if this Python file is auto-generated and its module docstring is noise.
Covers: Alembic/Flask-Migrate revisions, Django migrations, protobuf/gRPC/OpenAPI stubs.
Module docstrings in these files are change annotations or boilerplate, not rationale.
"""
head = source[:2048].decode("utf-8", errors="replace")
# Generic generated-file markers (protobuf, gRPC, OpenAPI codegen, etc.)
if any(m in head for m in ("DO NOT EDIT", "@generated", "Generated by the protocol buffer")):
return True
# Alembic / Flask-Migrate revision files
if (re.search(r"^revision\s*[:=]", head, re.MULTILINE)
and "def upgrade(" in head
and "down_revision" in head):
return True
# Django migrations
if "class Migration(migrations.Migration)" in head and "operations" in head:
return True
return False
def _extract_python_rationale(path: Path, result: dict) -> None:
"""Post-pass: extract docstrings and rationale comments from Python source.
Mutates result in-place by appending to result['nodes'] and result['edges'].
@@ -1995,13 +1924,10 @@ def _extract_python_rationale(path: Path, result: dict) -> None:
"weight": 1.0,
})
# Module-level docstring — skip for auto-generated files (Alembic, Django
# migrations, protobuf stubs, etc.) whose module docstrings are revision
# annotations, not architectural rationale.
if not _is_autogenerated_python(source):
ds = _get_docstring(root)
if ds:
_add_rationale(ds[0], ds[1], file_nid)
# Module-level docstring
ds = _get_docstring(root)
if ds:
_add_rationale(ds[0], ds[1], file_nid)
# Class and function docstrings
def walk_docstrings(node, parent_nid: str) -> None:
@@ -2755,51 +2681,20 @@ def extract_sql(path: Path) -> dict:
# Foreign key REFERENCES
for col in node.children:
if col.type == "column_definitions":
has_error = any(cd.type == "ERROR" for cd in col.children)
seen_refs: set[str] = set()
for cd in col.children:
if cd.type == "column_definition":
# Inline column-level REFERENCES
ref_name: str | None = None
found_ref = False
for cc in cd.children:
if cc.type == "keyword_references":
found_ref = True
elif found_ref and cc.type == "object_reference":
ref_name = _read(cc)
break
if ref_name:
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
_add_edge(nid, ref_nid, "references", line)
seen_refs.add(ref_name.lower())
elif cd.type == "constraints":
# Table-level FOREIGN KEY ... REFERENCES ... constraints
for constraint in cd.children:
if constraint.type != "constraint":
continue
ref_name = None
found_ref = False
for cc in constraint.children:
if cc.type == "keyword_references":
found_ref = True
elif found_ref and cc.type == "object_reference":
ref_name = _read(cc)
break
if ref_name:
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
_add_edge(nid, ref_nid, "references", line)
seen_refs.add(ref_name.lower())
if has_error:
# Dialect-specific syntax (e.g. Firebird COMPUTED BY) causes ERROR
# nodes that make the parser drop the trailing constraints block.
# Regex-scan the raw column_definitions text as fallback.
col_text = _read(col)
for rm in re.finditer(r"\bREFERENCES\s+([\w$]+)", col_text, re.IGNORECASE):
ref_name = rm.group(1)
if ref_name.lower() not in seen_refs:
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
_add_edge(nid, ref_nid, "references", line)
seen_refs.add(ref_name.lower())
if cd.type != "column_definition":
continue
ref_name: str | None = None
found_ref = False
for cc in cd.children:
if cc.type == "keyword_references":
found_ref = True
elif found_ref and cc.type == "object_reference":
ref_name = _read(cc)
break
if ref_name:
ref_nid = _make_id(stem, ref_name)
_add_edge(nid, ref_nid, "references", line)
elif t == "create_view":
name = _obj_name(node)
@@ -2851,64 +2746,6 @@ def extract_sql(path: Path) -> dict:
ref_nid = _make_id(stem, ref_name)
_add_edge(src_nid, ref_nid, "references", line)
elif t == "create_trigger":
trig_name: str | None = None
tbl_name: str | None = None
after_trigger = False
after_for = False
for c in node.children:
if c.type == "keyword_trigger":
after_trigger = True
elif after_trigger and not trig_name and c.type == "object_reference":
trig_name = _read(c)
elif c.type == "keyword_for":
after_for = True
elif after_for and not tbl_name and c.type == "object_reference":
tbl_name = _read(c)
if trig_name:
trig_nid = _make_id(stem, trig_name)
_add_node(trig_nid, trig_name, line)
if tbl_name:
tbl_nid = table_nids.get(tbl_name.lower()) or _make_id(stem, tbl_name)
_add_edge(trig_nid, tbl_nid, "triggers", line)
elif t == "fb_proc_or_trigger":
text = _read(node)
m = re.match(
r"CREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?"
r"(PROCEDURE|TRIGGER|FUNCTION)\s+([\w$]+)",
text, re.IGNORECASE,
)
if m:
obj_type = m.group(1).upper()
obj_name = m.group(2)
obj_nid = _make_id(stem, obj_name)
label = obj_name if obj_type == "TRIGGER" else f"{obj_name}()"
_add_node(obj_nid, label, line)
if obj_type == "TRIGGER":
fm = re.search(r"\bFOR\s+([\w$]+)", text, re.IGNORECASE)
if fm:
tbl = fm.group(1)
tbl_nid = table_nids.get(tbl.lower()) or _make_id(stem, tbl)
_add_edge(obj_nid, tbl_nid, "triggers", line)
_NON_TABLES = {
"select", "where", "set", "dual", "null", "true", "false",
"first", "skip", "rows", "next", "only", "lateral",
}
seen_tbls: set[str] = set()
for rm in re.finditer(r"\b(?:FROM|JOIN|INTO)\s+([\w$]+)", text, re.IGNORECASE):
tbl = rm.group(1)
if tbl.lower() not in _NON_TABLES and tbl.lower() not in seen_tbls:
seen_tbls.add(tbl.lower())
tbl_nid = table_nids.get(tbl.lower()) or _make_id(stem, tbl)
_add_edge(obj_nid, tbl_nid, "reads_from", line)
for rm in re.finditer(r"\bUPDATE\s+([\w$]+)", text, re.IGNORECASE):
tbl = rm.group(1)
if tbl.lower() not in _NON_TABLES and tbl.lower() not in seen_tbls:
seen_tbls.add(tbl.lower())
tbl_nid = table_nids.get(tbl.lower()) or _make_id(stem, tbl)
_add_edge(obj_nid, tbl_nid, "reads_from", line)
for child in node.children:
walk(child)
@@ -2930,29 +2767,6 @@ def extract_sql(path: Path) -> dict:
if stmt.type == "statement":
for child in stmt.children:
walk(child)
elif stmt.type in ("fb_proc_or_trigger", "set_term", "declare_external_function"):
walk(stmt)
# Global regex fallback: catch any REFERENCES missed due to ERROR nodes in the parse tree
# (e.g. Firebird COMPUTED BY columns push constraints out of the tree entirely).
# Snapshot after tree walk so we don't re-emit edges already captured above.
emitted = {(e["source"], e["target"]) for e in edges if e["relation"] == "references"}
src_text = source.decode("utf-8", errors="replace")
for m in re.finditer(r"CREATE\s+TABLE\s+([\w$]+)\s*\(", src_text, re.IGNORECASE):
tbl_name = m.group(1)
tbl_nid = table_nids.get(tbl_name.lower())
if tbl_nid is None:
continue
tbl_line = src_text[: m.start()].count("\n") + 1
tail = src_text[m.start():]
end = re.search(r"(?:^|\n)(?:CREATE|SET\s+TERM|ALTER)\s", tail[1:], re.IGNORECASE)
block = tail[: end.start() + 1] if end else tail
for rm in re.finditer(r"\bREFERENCES\s+([\w$]+)", block, re.IGNORECASE):
ref_name = rm.group(1)
ref_nid = table_nids.get(ref_name.lower()) or _make_id(stem, ref_name)
if (tbl_nid, ref_nid) not in emitted:
_add_edge(tbl_nid, ref_nid, "references", tbl_line)
emitted.add((tbl_nid, ref_nid))
return {"nodes": nodes, "edges": edges}
@@ -5765,310 +5579,6 @@ def _check_tree_sitter_version() -> None:
)
def extract_bash(path: Path) -> dict:
"""Extract functions, source imports, and cross-function calls from a .sh file."""
try:
import tree_sitter_bash as tsbash
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-bash not installed"}
try:
language = Language(tsbash.language())
parser = Parser(language)
source = path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
function_bodies: list[tuple[str, Any]] = []
defined_functions: set[str] = set()
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 = {"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)
_BASH_SKIP = frozenset({
"if", "then", "else", "elif", "fi", "for", "while", "until", "do",
"done", "case", "esac", "in", "return", "exit", "break", "continue",
"echo", "printf", "cd", "set", "local", "export", "readonly",
"declare", "unset", "shift", "read", "test", "[", "[[", ":", "true",
"false", "source", ".", "trap", "wait", "exec", "eval",
})
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 _read_text(child, source)
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 == "command":
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 = _read_text(cmd_name_node, source).strip()
if name and name not in _BASH_SKIP and name in defined_functions:
tgt = _make_id(stem, name)
key = (func_nid, tgt)
if tgt and key not in seen_calls:
seen_calls.add(key)
add_edge(func_nid, tgt, "calls",
child.start_point[0] + 1,
confidence="EXTRACTED", context="call")
walk_calls(child, func_nid, seen_calls)
def walk(node, parent_nid: str) -> None:
t = node.type
if t == "function_definition":
name = _bash_func_name(node)
if name:
fn_nid = _make_id(stem, name)
line = node.start_point[0] + 1
add_node(fn_nid, f"{name}()", line)
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))
return # don't recurse into function body during structural pass
if t == "command":
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 = _read_text(cmd_name_node, source).strip()
if cmd in ("source", "."):
# find the path argument (first word after command name)
args = [c for c in node.children
if c.type in ("word", "string", "concatenation")
and c != cmd_name_node]
if args:
raw = _read_text(args[0], source).strip().strip("'\"")
line = node.start_point[0] + 1
if raw.startswith((".", "/")):
resolved = (path.parent / raw).resolve()
# Only emit the edge if the target actually exists on
# disk — prevents graph pollution from crafted paths
# like `source ../../etc/passwd` that traverse outside
# the project tree (B-1).
if resolved.exists():
tgt_nid = _make_id(str(resolved))
add_edge(file_nid, tgt_nid, "imports_from", line,
context="import")
else:
tgt_nid = _make_id(raw)
if tgt_nid:
add_edge(file_nid, tgt_nid, "imports", line,
context="import")
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)
walk(root, file_nid)
# Second pass: cross-function calls
for fn_nid, body in function_bodies:
walk_calls(body, fn_nid, set())
return {"nodes": nodes, "edges": edges}
def extract_json(path: Path) -> dict:
"""Extract top-level keys, nested structure, and dependency edges from a .json file."""
_JSON_MAX_BYTES = 1_048_576 # 1 MiB — skip large fixture dumps / GeoJSON blobs
try:
import tree_sitter_json as tsjson
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-json not installed"}
try:
# Bounded read instead of stat()+read() to eliminate TOCTOU (J-1):
# read one byte beyond the limit so we can detect oversized files even
# if the file grows between stat and read.
with path.open("rb") as _f:
source = _f.read(_JSON_MAX_BYTES + 1)
if len(source) > _JSON_MAX_BYTES:
return {"nodes": [], "edges": [], "error": "json file too large to index"}
language = Language(tsjson.language())
parser = Parser(language)
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
# Keys whose string values become imports (package.json dep blocks)
_DEP_KEYS = frozenset({
"dependencies", "devDependencies", "peerDependencies",
"optionalDependencies", "bundleDependencies", "bundledDependencies",
})
def add_node(nid: str, label: str, line: int) -> 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,
context: str | None = None) -> None:
if not src or not tgt or src == tgt:
return
edge = {"source": src, "target": tgt, "relation": relation,
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": f"L{line}", "weight": 1.0}
if context:
edge["context"] = context
edges.append(edge)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def _key_text(pair_node) -> str | None:
"""Extract the string content of a pair's key."""
key_node = pair_node.child_by_field_name("key")
if key_node is None:
return None
if key_node.type == "string":
content = key_node.child_by_field_name("string_content")
if content:
return _read_text(content, source)
# fallback: strip surrounding quotes
raw = _read_text(key_node, source)
return raw.strip('"\'')
return _read_text(key_node, source)
def _val_node(pair_node):
return pair_node.child_by_field_name("value")
def walk_object(obj_node, parent_nid: str, parent_key: str | None,
depth: int, pair_count: list) -> None:
if depth > 6:
return
for child in obj_node.children:
if child.type != "pair":
continue
if pair_count[0] >= 500: # check per-pair so the cap is honoured exactly (J-3)
return
pair_count[0] += 1
key = _key_text(child)
if not key:
continue
key_nid = _make_id(stem, *(([parent_key] if parent_key else []) + [key]))
if not key_nid:
continue
line = child.start_point[0] + 1
add_node(key_nid, key, line)
add_edge(parent_nid, key_nid, "contains", line)
val = _val_node(child)
if val is None:
continue
if val.type == "object":
walk_object(val, key_nid, key, depth + 1, pair_count)
elif val.type == "array":
# For "extends" arrays (tsconfig, eslint): each string element.
# Prefix with "ref_" so external refs don't collide with real
# code/file node IDs that share the same collapsed _make_id (J-4).
for item in val.children:
if item.type == "string":
content = item.child_by_field_name("string_content")
ref = _read_text(content, source) if content else _read_text(item, source).strip('"\'')
if ref:
ref_nid = _make_id("ref", ref)
if ref_nid:
add_edge(key_nid, ref_nid, "extends", line, context="import")
elif val.type == "string":
content = val.child_by_field_name("string_content")
val_text = _read_text(content, source) if content else _read_text(val, source).strip('"\'')
if key == "extends" and val_text:
# Namespace external refs to avoid ID collision with file nodes (J-4)
ref_nid = _make_id("ref", val_text)
if ref_nid:
add_edge(file_nid, ref_nid, "extends", line, context="import")
elif key == "$ref" and val_text:
# Namespace $ref values to prevent edge hijacking into code nodes (J-4)
ref_nid = _make_id("ref", val_text)
if ref_nid:
add_edge(parent_nid, ref_nid, "references", line)
elif parent_key in _DEP_KEYS and val_text:
dep_nid = _make_id(key)
if dep_nid:
add_edge(key_nid, dep_nid, "imports", line, context="import")
# Entry: find root document → object
doc = root
if doc.type == "document" and doc.child_count > 0:
doc = doc.children[0]
if doc.type == "object":
walk_object(doc, file_nid, None, 0, [0])
return {"nodes": nodes, "edges": edges}
_DISPATCH: dict[str, Any] = {
".py": extract_python,
".js": extract_js,
@@ -6133,9 +5643,6 @@ _DISPATCH: dict[str, Any] = {
".dfm": extract_delphi_form,
".lfm": extract_lazarus_form,
".lpk": extract_lazarus_package,
".sh": extract_bash,
".bash": extract_bash,
".json": extract_json,
}
@@ -6538,7 +6045,7 @@ def collect_files(target: Path, *, follow_symlinks: bool = False, root: Path | N
if target.is_file():
return [target]
_EXTENSIONS = set(_DISPATCH.keys())
from graphify.detect import _load_graphifyignore, _is_ignored, _is_noise_dir
from graphify.detect import _load_graphifyignore, _is_ignored
ignore_root = root if root is not None else target
patterns = _load_graphifyignore(ignore_root)
@@ -6550,7 +6057,7 @@ def collect_files(target: Path, *, follow_symlinks: bool = False, root: Path | N
for ext in sorted(_EXTENSIONS):
results.extend(
p for p in target.rglob(f"*{ext}")
if not any(_is_noise_dir(part) for part in p.parts)
if not any(part.startswith(".") for part in p.parts)
and not _ignored(p)
)
return sorted(results)
@@ -6564,10 +6071,12 @@ def collect_files(target: Path, *, follow_symlinks: bool = False, root: Path | N
dirnames.clear()
continue
dp = Path(dirpath)
dirnames[:] = [d for d in dirnames if not _is_noise_dir(d)]
if any(part.startswith(".") for part in dp.parts):
dirnames.clear()
continue
for fname in filenames:
p = dp / fname
if p.suffix in _EXTENSIONS and not _ignored(p):
if p.suffix in _EXTENSIONS and not fname.startswith(".") and not _ignored(p):
results.append(p)
return sorted(results)
+1 -8
View File
@@ -28,10 +28,6 @@ def generate(
) -> str:
today = date.today().isoformat()
# JSON deserialization produces string keys; normalize to int so .get(cid) works.
if community_labels:
community_labels = {int(k) if isinstance(k, str) else k: v for k, v in community_labels.items()}
confidences = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
total = len(confidences) or 1
ext_pct = round(confidences.count("EXTRACTED") / total * 100)
@@ -164,10 +160,7 @@ def generate(
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)
]
thin_communities = {
cid: nodes for cid, nodes in communities.items()
+6 -101
View File
@@ -1,7 +1,6 @@
# MCP stdio server - exposes graph query tools to Claude and other agents
from __future__ import annotations
import json
import math
import sys
from pathlib import Path
import networkx as nx
@@ -56,76 +55,30 @@ _SUBSTRING_MATCH_BONUS = 1.0
_SOURCE_MATCH_BONUS = 0.5
def _compute_idf(G: nx.Graph, terms: list[str]) -> dict[str, float]:
"""IDF weights for query terms, cached in G.graph['_idf_cache'].
Common terms like 'error' or 'exception' that match hundreds of nodes get
low weights; rare identifiers like 'FooBarService' get high weights.
Cache is stored on the graph object itself so it auto-invalidates when
_maybe_reload() replaces G with a new object.
"""
cache: dict[str, float] = G.graph.setdefault("_idf_cache", {})
N = G.number_of_nodes() or 1
uncached = [t for t in terms if t not in cache]
if uncached:
df: dict[str, int] = {t: 0 for t in uncached}
for _, data in G.nodes(data=True):
norm_label = (
data.get("norm_label") or _strip_diacritics(data.get("label") or "")
).lower()
for t in uncached:
if t in norm_label:
df[t] += 1
for t in uncached:
cache[t] = math.log(1 + N / (1 + df[t]))
return {t: cache.get(t, math.log(1 + N)) for t in terms}
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
scored = []
norm_terms = [_strip_diacritics(t).lower() for t in terms]
idf = _compute_idf(G, norm_terms)
for nid, data in G.nodes(data=True):
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
bare_label = norm_label.rstrip("()")
source = (data.get("source_file") or "").lower()
score = 0.0
for t in norm_terms:
w = idf.get(t, 1.0)
# Three-tier precedence: exact > prefix > substring (take the
# strongest tier per term so a single term cannot double-count).
if t == norm_label or t == bare_label:
score += _EXACT_MATCH_BONUS * w
score += _EXACT_MATCH_BONUS
elif norm_label.startswith(t) or bare_label.startswith(t):
score += _PREFIX_MATCH_BONUS * w
score += _PREFIX_MATCH_BONUS
elif t in norm_label:
score += _SUBSTRING_MATCH_BONUS * w
score += _SUBSTRING_MATCH_BONUS
if t in source:
score += _SOURCE_MATCH_BONUS * w
score += _SOURCE_MATCH_BONUS
if score > 0:
scored.append((score, nid))
return sorted(scored, reverse=True)
def _pick_seeds(scored: list[tuple[float, str]], max_k: int = 3, gap_ratio: float = 0.2) -> list[str]:
"""Select BFS seed nodes, stopping when score drops too far below the top.
Prevents high-frequency noise terms (error, exception) from stealing seed
slots from a dominant identifier match. When FooBarService scores 1000 and
error nodes score 1.0, only FooBarService is seeded — the score gap is 99.9%
which is well above the 20% threshold that would allow additional seeds.
"""
if not scored:
return []
top_score = scored[0][0]
seeds = []
for score, nid in scored[:max_k]:
if seeds and score < top_score * gap_ratio:
break
seeds.append(nid)
return seeds
_CONTEXT_HINTS: tuple[tuple[str, tuple[str, ...]], ...] = (
("call", ("call", "calls", "called", "invoke", "invokes", "invoked")),
("import", ("import", "imports", "imported", "module", "modules")),
@@ -284,16 +237,7 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
lines.append(line)
output = "\n".join(lines)
if len(output) > char_budget:
cut_at = output[:char_budget].rfind("\n")
cut_at = cut_at if cut_at > 0 else char_budget
total_nodes = sum(1 for l in lines if l.startswith("NODE "))
shown_nodes = output[:cut_at].count("\nNODE ") + (1 if output.startswith("NODE ") else 0)
cut_count = total_nodes - shown_nodes
output = (
output[:cut_at]
+ f"\n... (truncated — {cut_count} more nodes cut by ~{token_budget}-token budget."
f" Narrow with context_filter=['call'] or use get_node for a specific symbol)"
)
output = output[:char_budget] + f"\n... (truncated to ~{token_budget} token budget)"
return output
@@ -308,7 +252,7 @@ def _query_graph_text(
) -> str:
terms = [t.lower() for t in question.split() if len(t) > 2]
scored = _score_nodes(G, terms)
start_nodes = _pick_seeds(scored)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
return "No matching nodes found."
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
@@ -380,8 +324,6 @@ def _filter_blank_stdin() -> None:
def serve(graph_path: str = "graphify-out/graph.json") -> None:
"""Start the MCP server. Requires pip install mcp."""
import threading
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
@@ -393,41 +335,6 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
G = _load_graph(graph_path)
communities = _communities_from_graph(G)
# Hot-reload state: mtime+size key lets us detect graph.json changes without
# polling. Initialised from the file stat at startup so the first tool call
# never triggers a redundant reload.
_reload_lock = threading.Lock()
try:
_s = Path(graph_path).stat()
_reload_state: dict = {"mtime_ns": _s.st_mtime_ns, "size": _s.st_size}
except FileNotFoundError:
_reload_state = {"mtime_ns": 0, "size": -1}
def _maybe_reload() -> None:
nonlocal G, communities
try:
s = Path(graph_path).stat()
key = (s.st_mtime_ns, s.st_size)
except FileNotFoundError:
return
if key == (_reload_state["mtime_ns"], _reload_state["size"]):
return
with _reload_lock:
try:
s = Path(graph_path).stat()
key = (s.st_mtime_ns, s.st_size)
except FileNotFoundError:
return
if key == (_reload_state["mtime_ns"], _reload_state["size"]):
return # another thread already reloaded
try:
new_G = _load_graph(graph_path)
except SystemExit:
return # keep serving stale graph on transient read error
G = new_G
communities = _communities_from_graph(new_G)
_reload_state["mtime_ns"], _reload_state["size"] = key
server = Server("graphify")
@server.list_tools()
@@ -689,7 +596,6 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
@server.read_resource()
async def read_resource(uri: AnyUrl) -> str:
_maybe_reload()
uri_str = str(uri)
if uri_str == "graphify://report":
report_path = Path(graph_path).parent / "GRAPH_REPORT.md"
@@ -741,7 +647,6 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
_maybe_reload()
handler = _handlers.get(name)
if not handler:
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
+2 -21
View File
@@ -716,14 +716,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -747,21 +743,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -716,14 +716,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -747,21 +743,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -775,14 +775,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -806,21 +802,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -793,14 +793,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -824,21 +820,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -772,14 +772,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -803,21 +799,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -715,14 +715,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -746,21 +742,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -825,14 +825,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -856,21 +852,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -715,14 +715,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -746,21 +742,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+2 -21
View File
@@ -750,14 +750,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -781,21 +777,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+154 -209
View File
@@ -63,59 +63,25 @@ Follow these steps in order. Do not skip steps.
### Step 1 - Ensure graphify is installed
```powershell
# Detect Python with graphify — uv/pipx-aware (fixes #831)
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
$GRAPHIFY_PYTHON = $null
function Find-GraphifyPython {
# 1. uv tool install — 'uv tool dir' is authoritative, respects UV_TOOL_DIR automatically
if (Get-Command uv -ErrorAction SilentlyContinue) {
$uvDir = (uv tool dir 2>$null).Trim()
if ($uvDir) {
$py = Join-Path $uvDir "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 2. pipx install — 'pipx environment' respects PIPX_HOME automatically
if (Get-Command pipx -ErrorAction SilentlyContinue) {
$venvs = (pipx environment --value PIPX_LOCAL_VENVS 2>$null).Trim()
if ($venvs) {
$py = Join-Path $venvs "graphifyy\Scripts\python.exe"
if (Test-Path $py) {
& $py -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) { return $py }
}
}
}
# 3. Active venv / conda / pip-into-current-env
$pyCmd = Get-Command python -ErrorAction SilentlyContinue
if ($pyCmd) {
& $pyCmd.Source -c "import graphify" 2>$null
if ($LASTEXITCODE -eq 0) {
return (& $pyCmd.Source -c "import sys; print(sys.executable)").Trim()
}
}
return $null
}
# Try to find the right Python (uv → pipx → active env)
$GRAPHIFY_PYTHON = Find-GraphifyPython
# Not found — install then re-detect
if (-not $GRAPHIFY_PYTHON) {
# Detect Python and install graphify if needed
@'
import graphify
'@ | Out-File -FilePath .graphify_step_1_ensure_graphify_is_installed_1.py -Encoding utf8
python .graphify_step_1_ensure_graphify_is_installed_1.py 2>$null
Remove-Item -ErrorAction SilentlyContinue .graphify_step_1_ensure_graphify_is_installed_1.py
if ($LASTEXITCODE -ne 0) {
if (Get-Command uv -ErrorAction SilentlyContinue) {
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
} else {
pip install graphifyy -q 2>&1 | Select-Object -Last 3
}
$GRAPHIFY_PYTHON = Find-GraphifyPython
}
# Save interpreter path — all subsequent steps read this
$GRAPHIFY_PYTHON | Out-File -FilePath graphify-out\.graphify_python -Encoding utf8 -NoNewline
# Write interpreter path for all subsequent steps
@'
import sys; open('.graphify_python', 'w', encoding='utf-8').write(sys.executable)
'@ | Out-File -FilePath .graphify_step_1_ensure_graphify_is_installed_2.py -Encoding utf8
python .graphify_step_1_ensure_graphify_is_installed_2.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_1_ensure_graphify_is_installed_2.py
```
If the import succeeds, print nothing and move straight to Step 2.
@@ -129,9 +95,9 @@ from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result, ensure_ascii=False))
'@ | Out-File -FilePath graphify-out\.graphify_step_2_detect_files_3.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_2_detect_files_3.py | Out-File -FilePath graphify-out\.graphify_detect.json -Encoding utf8
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_2_detect_files_3.py
'@ | Out-File -FilePath .graphify_step_2_detect_files_3.py -Encoding utf8
python .graphify_step_2_detect_files_3.py > .graphify_detect.json
Remove-Item -ErrorAction SilentlyContinue .graphify_step_2_detect_files_3.py
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
@@ -186,9 +152,9 @@ prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and p
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths, ensure_ascii=False))
'@ | Out-File -FilePath graphify-out\.graphify_step_transcribe.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_transcribe.py | Out-File -FilePath graphify-out\.graphify_transcripts.json -Encoding utf8
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_transcribe.py
'@ | Out-File -FilePath .graphify_step_transcribe.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) .graphify_step_transcribe.py | Out-File -FilePath graphify-out\.graphify_transcripts.json -Encoding utf8
Remove-Item -ErrorAction SilentlyContinue .graphify_step_transcribe.py
```
After transcription:
@@ -222,16 +188,16 @@ from pathlib import Path
def main():
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files)
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
print('No code files - skipping AST extraction')
@@ -242,9 +208,9 @@ def main():
# extraction working on Windows.
if __name__ == '__main__':
main()
'@ | Out-File -FilePath graphify-out\.graphify_step_ast.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_ast.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_ast.py
'@ | Out-File -FilePath .graphify_step_ast.py -Encoding utf8
python .graphify_step_ast.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_ast.py
```
#### Part B - Semantic extraction (parallel subagents)
@@ -254,7 +220,7 @@ Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_ast.py
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Load `total_words` and file counts from `.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
@@ -269,7 +235,7 @@ import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
@@ -278,9 +244,9 @@ if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
'@ | Out-File -FilePath graphify-out\.graphify_step_3_extract_entities_and_relations_5.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_3_extract_entities_and_relations_5.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_3_extract_entities_and_relations_5.py
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_5.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_5.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_5.py
```
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
@@ -374,8 +340,8 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```powershell
& (Get-Content graphify-out\.graphify_python) -c "
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
@@ -407,12 +373,12 @@ from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
'@ | Out-File -FilePath graphify-out\.graphify_step_3_extract_entities_and_relations_6.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_3_extract_entities_and_relations_6.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_3_extract_entities_and_relations_6.py
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_6.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_6.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_6.py
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
Merge cached + new results into `.graphify_semantic.json`:
```powershell
@'
import json
@@ -440,9 +406,9 @@ merged = {
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
'@ | Out-File -FilePath graphify-out\.graphify_step_3_extract_entities_and_relations_7.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_3_extract_entities_and_relations_7.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_3_extract_entities_and_relations_7.py
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_7.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_7.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_7.py
```
Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json`
@@ -453,8 +419,8 @@ Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue graphify-out\.gr
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding="utf-8"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding="utf-8"))
ast = json.loads(Path('.graphify_ast.json').read_text(encoding="utf-8"))
sem = json.loads(Path('.graphify_semantic.json').read_text(encoding="utf-8"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
@@ -473,13 +439,13 @@ merged = {
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
'@ | Out-File -FilePath graphify-out\.graphify_step_3_extract_entities_and_relations_8.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_3_extract_entities_and_relations_8.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_3_extract_entities_and_relations_8.py
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_8.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_8.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_8.py
```
### Step 4 - Build graph, cluster, analyze, generate outputs
@@ -495,8 +461,8 @@ from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = cluster(G)
@@ -519,15 +485,15 @@ analysis = {
'surprises': surprises,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
'@ | Out-File -FilePath graphify-out\.graphify_step_4_build_graph_cluster_analyze_ge_9.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_4_build_graph_cluster_analyze_ge_9.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_4_build_graph_cluster_analyze_ge_9.py
'@ | Out-File -FilePath .graphify_step_4_build_graph_cluster_analyze_ge_9.py -Encoding utf8
python .graphify_step_4_build_graph_cluster_analyze_ge_9.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_4_build_graph_cluster_analyze_ge_9.py
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
@@ -536,7 +502,7 @@ Replace INPUT_PATH with the actual path.
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
@@ -549,9 +515,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -566,11 +532,11 @@ questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
print('Report updated with community labels')
'@ | Out-File -FilePath graphify-out\.graphify_step_5_label_communities_10.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_5_label_communities_10.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_5_label_communities_10.py
'@ | Out-File -FilePath .graphify_step_5_label_communities_10.py -Encoding utf8
python .graphify_step_5_label_communities_10.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_5_label_communities_10.py
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
@@ -591,9 +557,9 @@ from graphify.build import build_from_json
from graphify.export import to_obsidian, to_canvas
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_labels.json').exists() else {}
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -612,9 +578,9 @@ print(f'Open {obsidian_dir}/ as a vault in Obsidian.')
print(' Graph view - nodes colored by community (set automatically)')
print(' graph.canvas - structured layout with communities as groups')
print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries')
'@ | Out-File -FilePath graphify-out\.graphify_step_6_generate_obsidian_vault_opt_in_11.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_6_generate_obsidian_vault_opt_in_11.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_6_generate_obsidian_vault_opt_in_11.py
'@ | Out-File -FilePath .graphify_step_6_generate_obsidian_vault_opt_in_11.py -Encoding utf8
python .graphify_step_6_generate_obsidian_vault_opt_in_11.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_6_generate_obsidian_vault_opt_in_11.py
```
Generate the HTML graph (always, unless `--no-viz`):
@@ -626,9 +592,9 @@ from graphify.build import build_from_json
from graphify.export import to_html
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_labels.json').exists() else {}
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -639,9 +605,9 @@ if G.number_of_nodes() > 5000:
else:
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
print('graph.html written - open in any browser, no server needed')
'@ | Out-File -FilePath graphify-out\.graphify_step_6_generate_obsidian_vault_opt_in_12.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_6_generate_obsidian_vault_opt_in_12.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_6_generate_obsidian_vault_opt_in_12.py
'@ | Out-File -FilePath .graphify_step_6_generate_obsidian_vault_opt_in_12.py -Encoding utf8
python .graphify_step_6_generate_obsidian_vault_opt_in_12.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_6_generate_obsidian_vault_opt_in_12.py
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
@@ -655,12 +621,12 @@ from graphify.build import build_from_json
from graphify.export import to_cypher
from pathlib import Path
G = build_from_json(json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8")))
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8")))
to_cypher(G, 'graphify-out/cypher.txt')
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
'@ | Out-File -FilePath graphify-out\.graphify_step_7_neo4j_export_only_if_neo4j_or__13.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_7_neo4j_export_only_if_neo4j_or__13.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_7_neo4j_export_only_if_neo4j_or__13.py
'@ | Out-File -FilePath .graphify_step_7_neo4j_export_only_if_neo4j_or__13.py -Encoding utf8
python .graphify_step_7_neo4j_export_only_if_neo4j_or__13.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7_neo4j_export_only_if_neo4j_or__13.py
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
@@ -673,16 +639,16 @@ from graphify.cluster import cluster
from graphify.export import push_to_neo4j
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
result = push_to_neo4j(G, uri='NEO4J_URI', user='NEO4J_USER', password='NEO4J_PASSWORD', communities=communities)
print(f'Pushed to Neo4j: {result["nodes"]} nodes, {result["edges"]} edges')
'@ | Out-File -FilePath graphify-out\.graphify_step_7_neo4j_export_only_if_neo4j_or__14.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_7_neo4j_export_only_if_neo4j_or__14.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_7_neo4j_export_only_if_neo4j_or__14.py
'@ | Out-File -FilePath .graphify_step_7_neo4j_export_only_if_neo4j_or__14.py -Encoding utf8
python .graphify_step_7_neo4j_export_only_if_neo4j_or__14.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7_neo4j_export_only_if_neo4j_or__14.py
```
Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
@@ -696,9 +662,9 @@ from graphify.build import build_from_json
from graphify.export import to_svg
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_labels.json').exists() else {}
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -706,9 +672,9 @@ labels = {int(k): v for k, v in labels_raw.items()}
to_svg(G, communities, 'graphify-out/graph.svg', community_labels=labels or None)
print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
'@ | Out-File -FilePath graphify-out\.graphify_step_7b_svg_export_only_if_svg_flag_15.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_7b_svg_export_only_if_svg_flag_15.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_7b_svg_export_only_if_svg_flag_15.py
'@ | Out-File -FilePath .graphify_step_7b_svg_export_only_if_svg_flag_15.py -Encoding utf8
python .graphify_step_7b_svg_export_only_if_svg_flag_15.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7b_svg_export_only_if_svg_flag_15.py
```
### Step 7c - GraphML export (only if --graphml flag)
@@ -720,23 +686,23 @@ from graphify.build import build_from_json
from graphify.export import to_graphml
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding="utf-8"))
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
to_graphml(G, communities, 'graphify-out/graph.graphml')
print('graph.graphml written - open in Gephi, yEd, or any GraphML tool')
'@ | Out-File -FilePath graphify-out\.graphify_step_7c_graphml_export_only_if_graphml_16.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_7c_graphml_export_only_if_graphml_16.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_7c_graphml_export_only_if_graphml_16.py
'@ | Out-File -FilePath .graphify_step_7c_graphml_export_only_if_graphml_16.py -Encoding utf8
python .graphify_step_7c_graphml_export_only_if_graphml_16.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7c_graphml_export_only_if_graphml_16.py
```
### Step 7d - MCP server (only if --mcp flag)
```powershell
& (Get-Content graphify-out\.graphify_python) -m graphify.serve graphify-out/graph.json
python -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
@@ -755,7 +721,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
```powershell
@'
@@ -763,12 +729,12 @@ import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
print_benchmark(result)
'@ | Out-File -FilePath graphify-out\.graphify_step_8_token_reduction_benchmark_only_17.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_8_token_reduction_benchmark_only_17.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_8_token_reduction_benchmark_only_17.py
'@ | Out-File -FilePath .graphify_step_8_token_reduction_benchmark_only_17.py -Encoding utf8
python .graphify_step_8_token_reduction_benchmark_only_17.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_8_token_reduction_benchmark_only_17.py
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
@@ -785,11 +751,11 @@ from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
save_manifest(detect['files'])
# Update cumulative cost tracker
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
extract = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
@@ -811,10 +777,10 @@ cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="u
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
'@ | Out-File -FilePath graphify-out\.graphify_step_9_save_manifest_update_cost_trac_18.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_9_save_manifest_update_cost_trac_18.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_9_save_manifest_update_cost_trac_18.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_detect.json, graphify-out\.graphify_extract.json, graphify-out\.graphify_ast.json, graphify-out\.graphify_semantic.json, graphify-out\.graphify_analysis.json, graphify-out\.graphify_labels.json
'@ | Out-File -FilePath .graphify_step_9_save_manifest_update_cost_trac_18.py -Encoding utf8
python .graphify_step_9_save_manifest_update_cost_trac_18.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_9_save_manifest_update_cost_trac_18.py
Remove-Item -ErrorAction SilentlyContinue .graphify_detect.json, .graphify_extract.json, .graphify_ast.json, .graphify_semantic.json, .graphify_analysis.json, .graphify_labels.json
Remove-Item -ErrorAction SilentlyContinue graphify-out/.needs_update
```
@@ -862,18 +828,14 @@ from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
Path('.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
'@ | Out-File -FilePath graphify-out\.graphify_step_for_update_incremental_re_extracti_19.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_update_incremental_re_extracti_19.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_update_incremental_re_extracti_19.py
print(f'{new_total} new/changed file(s) to re-extract.')
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_19.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_19.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_19.py
```
If new files exist, first check whether all changed files are code files:
@@ -883,38 +845,21 @@ If new files exist, first check whether all changed files are code files:
import json
from pathlib import Path
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
result = json.loads(open('.graphify_incremental.json', encoding='utf-8').read()) if Path('.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
print('code_only:', code_only)
'@ | Out-File -FilePath graphify-out\.graphify_step_for_update_incremental_re_extracti_20.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_update_incremental_re_extracti_20.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_update_incremental_re_extracti_20.py
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_20.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_20.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_20.py
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```powershell
if (-not (Test-Path graphify-out\.graphify_extract.json)) {
Write-Host '[graphify update] Only deletions -- creating empty extraction for merge.'
@'
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
'@ | Out-File -FilePath graphify-out\.graphify_step_empty_extract.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_empty_extract.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_empty_extract.py
}
```
Then:
```powershell
@@ -931,11 +876,11 @@ existing_data = json.loads(Path('graphify-out/graph.json').read_text(encoding="u
G_existing = json_graph.node_link_graph(existing_data, edges='links')
# Load new extraction
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
new_extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
G_new = build_from_json(new_extraction)
# Prune nodes from deleted files
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding="utf-8"))
incremental = json.loads(Path('.graphify_incremental.json').read_text(encoding="utf-8"))
deleted = set(incremental.get('deleted_files', []))
if deleted:
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
@@ -956,9 +901,9 @@ print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edge
from graphify.detect import save_manifest
save_manifest(incremental['files'])
print('[graphify update] Manifest saved.')
'@ | Out-File -FilePath graphify-out\.graphify_step_for_update_incremental_re_extracti_21.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_update_incremental_re_extracti_21.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_update_incremental_re_extracti_21.py
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_21.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_21.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_21.py
```
Then run Steps 4–8 on the merged graph as normal.
@@ -975,8 +920,8 @@ import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding="utf-8"))
old_data = json.loads(Path('.graphify_old.json').read_text(encoding="utf-8")) if Path('.graphify_old.json').exists() else None
new_extract = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
G_new = build_from_json(new_extract)
if old_data:
@@ -987,13 +932,13 @@ if old_data:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
'@ | Out-File -FilePath graphify-out\.graphify_step_for_update_incremental_re_extracti_22.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_update_incremental_re_extracti_22.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_update_incremental_re_extracti_22.py
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_22.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_22.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_22.py
```
Before the merge step, save the old graph: `Copy-Item graphify-out/graph.json graphify-out\.graphify_old.json`
Clean up after: `Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_old.json`
Before the merge step, save the old graph: `Copy-Item graphify-out/graph.json .graphify_old.json`
Clean up after: `Remove-Item -ErrorAction SilentlyContinue .graphify_old.json`
---
@@ -1035,11 +980,11 @@ analysis = {
'gods': gods,
'surprises': surprises,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Re-clustered: {len(communities)} communities')
'@ | Out-File -FilePath graphify-out\.graphify_step_for_cluster_only_23.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_cluster_only_23.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_cluster_only_23.py
'@ | Out-File -FilePath .graphify_step_for_cluster_only_23.py -Encoding utf8
python .graphify_step_for_cluster_only_23.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_cluster_only_23.py
```
Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).
@@ -1062,9 +1007,9 @@ from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
'@ | Out-File -FilePath graphify-out\.graphify_step_for_graphify_query_24.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_graphify_query_24.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_graphify_query_24.py
'@ | Out-File -FilePath .graphify_step_for_graphify_query_24.py -Encoding utf8
python .graphify_step_for_graphify_query_24.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_query_24.py
```
If it fails, stop and tell the user to run `/graphify <path>` first.
@@ -1160,9 +1105,9 @@ output = '\n'.join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
print(output)
'@ | Out-File -FilePath graphify-out\.graphify_step_for_graphify_query_25.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_graphify_query_25.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_graphify_query_25.py
'@ | Out-File -FilePath .graphify_step_for_graphify_query_25.py -Encoding utf8
python .graphify_step_for_graphify_query_25.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_query_25.py
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
@@ -1170,7 +1115,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
After writing the answer, save it back into the graph so it improves future queries:
```powershell
& (Get-Content graphify-out\.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
python -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
@@ -1188,9 +1133,9 @@ from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
'@ | Out-File -FilePath graphify-out\.graphify_step_for_graphify_path_26.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_graphify_path_26.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_graphify_path_26.py
'@ | Out-File -FilePath .graphify_step_for_graphify_path_26.py -Encoding utf8
python .graphify_step_for_graphify_path_26.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_path_26.py
```
If it fails, stop and tell the user to run `/graphify <path>` first.
@@ -1239,9 +1184,9 @@ except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
'@ | Out-File -FilePath graphify-out\.graphify_step_for_graphify_path_27.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_graphify_path_27.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_graphify_path_27.py
'@ | Out-File -FilePath .graphify_step_for_graphify_path_27.py -Encoding utf8
python .graphify_step_for_graphify_path_27.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_path_27.py
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
@@ -1249,7 +1194,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
After writing the explanation, save it back:
```powershell
& (Get-Content graphify-out\.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
python -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
---
@@ -1265,9 +1210,9 @@ from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
'@ | Out-File -FilePath graphify-out\.graphify_step_for_graphify_explain_28.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_graphify_explain_28.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_graphify_explain_28.py
'@ | Out-File -FilePath .graphify_step_for_graphify_explain_28.py -Encoding utf8
python .graphify_step_for_graphify_explain_28.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_explain_28.py
```
If it fails, stop and tell the user to run `/graphify <path>` first.
@@ -1309,9 +1254,9 @@ for neighbor in G.neighbors(nid):
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
'@ | Out-File -FilePath graphify-out\.graphify_step_for_graphify_explain_29.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_graphify_explain_29.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_graphify_explain_29.py
'@ | Out-File -FilePath .graphify_step_for_graphify_explain_29.py -Encoding utf8
python .graphify_step_for_graphify_explain_29.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_explain_29.py
```
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
@@ -1319,7 +1264,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
After writing the explanation, save it back:
```powershell
& (Get-Content graphify-out\.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
python -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```
---
@@ -1343,9 +1288,9 @@ except ValueError as e:
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
'@ | Out-File -FilePath graphify-out\.graphify_step_for_graphify_add_30.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) graphify-out\.graphify_step_for_graphify_add_30.py
Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_step_for_graphify_add_30.py
'@ | Out-File -FilePath .graphify_step_for_graphify_add_30.py -Encoding utf8
python .graphify_step_for_graphify_add_30.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_add_30.py
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
@@ -1364,7 +1309,7 @@ Supported URL types (auto-detected):
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```powershell
& (Get-Content graphify-out\.graphify_python) -m graphify.watch INPUT_PATH --debounce 3
python -m graphify.watch INPUT_PATH --debounce 3
```
Replace INPUT_PATH with the folder to watch. Behavior depends on what changed:
+2 -21
View File
@@ -769,14 +769,10 @@ result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
@@ -818,21 +814,6 @@ If `code_only` is True: print `[graphify update] Code-only changes detected - sk
If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
+1 -20
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.8.7"
version = "0.7.19"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
@@ -38,8 +38,6 @@ dependencies = [
"tree-sitter-julia",
"tree-sitter-verilog",
"tree-sitter-fortran",
"tree-sitter-bash",
"tree-sitter-json",
]
[project.urls]
@@ -80,22 +78,5 @@ include-package-data = false
[tool.setuptools.package-data]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-aider.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md", "skill-kiro.md", "skill-vscode.md", "skill-pi.md"]
[tool.pytest.ini_options]
testpaths = ["tests"]
norecursedirs = [
"graphify-benchmark", "graphify_eval", "graphify_test",
"worked", "llm-stack-corpus", "llm-stack-demo", "product-site",
"scripts", "ebook", ".github", "dist", "build",
]
[tool.bandit]
skips = ["B404"]
[dependency-groups]
dev = [
"build>=1.5.0",
"nuitka>=4.1",
"patchelf>=0.17.2.4 ; sys_platform != 'win32'",
"setuptools>=82.0.1",
"wheel>=0.47.0",
]
-16
View File
@@ -1,16 +0,0 @@
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"build": "tsc",
"test": "jest",
"start": "node dist/index.js"
},
"dependencies": {
"react": "^18.0.0",
"axios": "^1.6.0"
},
"devDependencies": {
"typescript": "^5.0.0"
}
}
-23
View File
@@ -1,23 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
source ./helpers.sh
export APP_ENV="production"
build() {
echo "Building..."
local out_dir="dist"
mkdir -p "$out_dir"
}
test_suite() {
echo "Running tests..."
build
}
deploy() {
build
test_suite
echo "Deploying to $APP_ENV"
}
-10
View File
@@ -1,10 +0,0 @@
{
"extends": "@tsconfig/strictest/tsconfig.json",
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"outDir": "dist",
"strict": true
},
"include": ["src"]
}
+1 -270
View File
@@ -4,7 +4,7 @@ import networkx as nx
from pathlib import Path
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.analyze import god_nodes, surprising_connections, _is_concept_node, graph_diff, _surprise_score, _file_category, _is_json_key_node
from graphify.analyze import god_nodes, surprising_connections, _is_concept_node, graph_diff, _surprise_score, _file_category
FIXTURES = Path(__file__).parent / "fixtures"
@@ -123,98 +123,6 @@ def test_surprising_connections_cross_type_scores_higher():
assert any("code" in r and "paper" in r for r in reasons_cross)
def _make_cross_lang_graph():
"""Helper: Python node in backend/, TypeScript node in frontend/, different communities."""
G = nx.Graph()
G.add_node("py_auth", label="AuthError", source_file="backend/auth.py", file_type="code")
G.add_node("ts_member", label="Member", source_file="frontend/types.ts", file_type="code")
G.add_node("py_a", label="ServiceA", source_file="backend/service.py", file_type="code")
G.add_node("py_b", label="ServiceB", source_file="backend/utils.py", file_type="code")
return G
def test_cross_language_inferred_calls_suppressed():
"""Cross-language INFERRED calls edge should score lower than same-language EXTRACTED."""
G = _make_cross_lang_graph()
G.add_edge("py_auth", "ts_member", relation="calls", confidence="INFERRED",
weight=0.8, source_file="backend/auth.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="backend/service.py")
nc = {"py_auth": 0, "ts_member": 1, "py_a": 0, "py_b": 0}
score_cross, _ = _surprise_score(G, "py_auth", "ts_member",
G.edges["py_auth", "ts_member"], nc,
"backend/auth.py", "frontend/types.ts")
score_same, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"backend/service.py", "backend/utils.py")
assert score_cross <= score_same
def test_cross_language_inferred_uses_suppressed():
"""Cross-language INFERRED uses edge (the exact rsl-siege-manager false positive) should be suppressed."""
G = _make_cross_lang_graph()
G.add_edge("py_auth", "ts_member", relation="uses", confidence="INFERRED",
weight=0.8, source_file="backend/auth.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="backend/service.py")
nc = {"py_auth": 0, "ts_member": 1, "py_a": 0, "py_b": 0}
score_cross, _ = _surprise_score(G, "py_auth", "ts_member",
G.edges["py_auth", "ts_member"], nc,
"backend/auth.py", "frontend/types.ts")
score_same, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"backend/service.py", "backend/utils.py")
assert score_cross <= score_same
def test_cross_language_semantically_similar_not_suppressed():
"""`semantically_similar_to` across languages is a genuine insight — must not be suppressed."""
G = _make_cross_lang_graph()
G.add_edge("py_auth", "ts_member", relation="semantically_similar_to",
confidence="INFERRED", weight=0.85, source_file="backend/auth.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="backend/service.py")
nc = {"py_auth": 0, "ts_member": 1, "py_a": 0, "py_b": 0}
score_sem, _ = _surprise_score(G, "py_auth", "ts_member",
G.edges["py_auth", "ts_member"], nc,
"backend/auth.py", "frontend/types.ts")
score_same, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"backend/service.py", "backend/utils.py")
assert score_sem > score_same
def test_same_language_inferred_calls_not_suppressed():
"""INFERRED calls within the same language family must not be affected."""
G = nx.Graph()
G.add_node("py_a", label="ModuleA", source_file="src/a.py", file_type="code")
G.add_node("py_b", label="ModuleB", source_file="src/b.py", file_type="code")
G.add_node("py_c", label="ModuleC", source_file="src/c.py", file_type="code")
G.add_node("py_d", label="ModuleD", source_file="src/d.py", file_type="code")
G.add_edge("py_a", "py_b", relation="calls", confidence="INFERRED",
weight=0.8, source_file="src/a.py")
G.add_edge("py_c", "py_d", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="src/c.py")
nc = {"py_a": 0, "py_b": 1, "py_c": 0, "py_d": 1}
score_inf, _ = _surprise_score(G, "py_a", "py_b", G.edges["py_a", "py_b"], nc,
"src/a.py", "src/b.py")
score_ext, _ = _surprise_score(G, "py_c", "py_d", G.edges["py_c", "py_d"], nc,
"src/c.py", "src/d.py")
assert score_inf > score_ext
def test_cross_language_extracted_calls_not_suppressed():
"""EXTRACTED cross-language edges are real structural facts — must not be penalised."""
G = _make_cross_lang_graph()
G.add_edge("py_auth", "ts_member", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="backend/auth.py")
nc = {"py_auth": 0, "ts_member": 1}
score, _ = _surprise_score(G, "py_auth", "ts_member",
G.edges["py_auth", "ts_member"], nc,
"backend/auth.py", "frontend/types.ts")
assert score >= 1
def test_surprising_connections_have_why_field():
G = make_graph()
communities = cluster(G)
@@ -322,180 +230,3 @@ def test_graph_diff_empty_diff():
assert diff["new_edges"] == []
assert diff["removed_edges"] == []
assert diff["summary"] == "no changes"
# --- code↔doc INFERRED suppression tests ---
def _make_code_doc_graph():
G = nx.Graph()
G.add_node("py_fn", label="ProcessData", source_file="src/processor.py", file_type="code")
G.add_node("md_doc", label="README Section", source_file="docs/readme.md", file_type="document")
G.add_node("py_a", label="ServiceA", source_file="src/service.py", file_type="code")
G.add_node("py_b", label="ServiceB", source_file="src/utils.py", file_type="code")
return G
def test_code_doc_inferred_calls_suppressed():
"""Code→doc INFERRED calls edge should score lower than same-language EXTRACTED."""
G = _make_code_doc_graph()
G.add_edge("py_fn", "md_doc", relation="calls", confidence="INFERRED",
weight=0.8, source_file="src/processor.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="src/service.py")
nc = {"py_fn": 0, "md_doc": 1, "py_a": 0, "py_b": 0}
score_noise, _ = _surprise_score(G, "py_fn", "md_doc",
G.edges["py_fn", "md_doc"], nc,
"src/processor.py", "docs/readme.md")
score_real, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"src/service.py", "src/utils.py")
assert score_noise <= score_real
def test_code_doc_inferred_uses_suppressed():
"""Code→doc INFERRED uses edge should score lower than same-language EXTRACTED."""
G = _make_code_doc_graph()
G.add_edge("py_fn", "md_doc", relation="uses", confidence="INFERRED",
weight=0.8, source_file="src/processor.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="src/service.py")
nc = {"py_fn": 0, "md_doc": 1, "py_a": 0, "py_b": 0}
score_noise, _ = _surprise_score(G, "py_fn", "md_doc",
G.edges["py_fn", "md_doc"], nc,
"src/processor.py", "docs/readme.md")
score_real, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"src/service.py", "src/utils.py")
assert score_noise <= score_real
def test_code_doc_extracted_calls_not_suppressed():
"""EXTRACTED code↔doc edges are real facts — must not be penalised."""
G = _make_code_doc_graph()
G.add_edge("py_fn", "md_doc", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="src/processor.py")
nc = {"py_fn": 0, "md_doc": 1}
score, _ = _surprise_score(G, "py_fn", "md_doc",
G.edges["py_fn", "md_doc"], nc,
"src/processor.py", "docs/readme.md")
assert score >= 1
def test_code_doc_inferred_semantically_similar_not_suppressed():
"""`semantically_similar_to` across code↔doc is explicit LLM insight — must not be suppressed."""
G = _make_code_doc_graph()
G.add_edge("py_fn", "md_doc", relation="semantically_similar_to",
confidence="INFERRED", weight=0.85, source_file="src/processor.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="src/service.py")
nc = {"py_fn": 0, "md_doc": 1, "py_a": 0, "py_b": 0}
score_sem, _ = _surprise_score(G, "py_fn", "md_doc",
G.edges["py_fn", "md_doc"], nc,
"src/processor.py", "docs/readme.md")
score_same, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"src/service.py", "src/utils.py")
assert score_sem > score_same
def test_code_unknown_extension_inferred_calls_suppressed():
"""_file_category falls back to 'doc' for unknown extensions, so INFERRED
calls/uses to unknown-extension files are suppressed the same as code↔doc."""
assert _file_category("vendor/random.xyz") == "doc"
G = nx.Graph()
G.add_node("py_fn", label="Handler", source_file="src/handler.py", file_type="code")
G.add_node("unk", label="Handler", source_file="vendor/unknown.xyz", file_type="document")
G.add_node("py_a", label="A", source_file="src/a.py", file_type="code")
G.add_node("py_b", label="B", source_file="src/b.py", file_type="code")
G.add_edge("py_fn", "unk", relation="calls", confidence="INFERRED",
weight=0.8, source_file="src/handler.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="src/a.py")
nc = {"py_fn": 0, "unk": 1, "py_a": 0, "py_b": 0}
score_unk, _ = _surprise_score(G, "py_fn", "unk",
G.edges["py_fn", "unk"], nc,
"src/handler.py", "vendor/unknown.xyz")
score_same, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"src/a.py", "src/b.py")
assert score_unk <= score_same
def test_code_paper_inferred_calls_not_suppressed():
"""Code↔paper INFERRED calls should still surface — it is a meaningful link."""
G = nx.Graph()
G.add_node("py_model", label="Transformer", source_file="src/model.py", file_type="code")
G.add_node("pdf_paper", label="Attention Is All You Need", source_file="papers/vaswani.pdf",
file_type="paper")
G.add_node("py_a", label="ServiceA", source_file="src/service.py", file_type="code")
G.add_node("py_b", label="ServiceB", source_file="src/utils.py", file_type="code")
G.add_edge("py_model", "pdf_paper", relation="calls", confidence="INFERRED",
weight=0.8, source_file="src/model.py")
G.add_edge("py_a", "py_b", relation="calls", confidence="EXTRACTED",
weight=1.0, source_file="src/service.py")
nc = {"py_model": 0, "pdf_paper": 1, "py_a": 0, "py_b": 1}
score_cross, _ = _surprise_score(G, "py_model", "pdf_paper",
G.edges["py_model", "pdf_paper"], nc,
"src/model.py", "papers/vaswani.pdf")
score_same, _ = _surprise_score(G, "py_a", "py_b",
G.edges["py_a", "py_b"], nc,
"src/service.py", "src/utils.py")
assert score_cross > score_same
# --- JSON key node filtering tests ---
def test_is_json_key_node_noise_label():
G = nx.Graph()
G.add_node("j1", label="name", source_file="schema.json")
assert _is_json_key_node(G, "j1") is True
def test_is_json_key_node_non_json_file():
G = nx.Graph()
G.add_node("n1", label="name", source_file="model.py")
assert _is_json_key_node(G, "n1") is False
def test_is_json_key_node_real_label():
G = nx.Graph()
G.add_node("j2", label="UserProfile", source_file="schema.json")
assert _is_json_key_node(G, "j2") is False
def test_god_nodes_excludes_json_noise():
"""god_nodes must not return generic JSON key nodes like 'name' or 'id'."""
G = nx.Graph()
# Add many edges to a real node
G.add_node("real", label="AuthService", source_file="src/auth.py")
# Add a noisy JSON key node with high degree
G.add_node("json_name", label="name", source_file="schema.json")
for i in range(8):
n = f"peer{i}"
G.add_node(n, label=f"Peer{i}", source_file=f"src/peer{i}.py")
G.add_edge("json_name", n)
G.add_edge("real", n)
result = god_nodes(G, top_n=10)
labels = [r["label"] for r in result]
assert "name" not in labels
assert "AuthService" in labels
def test_god_nodes_filter_is_case_insensitive():
"""JSON-key filter must match regardless of label casing."""
G = nx.Graph()
G.add_node("real", label="RealAbstraction", source_file="libs/real.py")
for i in range(3):
G.add_node(f"peer{i}", label=f"P{i}", source_file=f"src/p{i}.py")
G.add_edge("real", f"peer{i}")
for variant in ("Start", "START", "Name", "ID"):
nid = f"json_{variant.lower()}"
G.add_node(nid, label=variant, source_file="testhelpers/data.json")
for i in range(15):
t = f"{nid}_t{i}"
G.add_node(t, label=f"X{i}", source_file="testhelpers/data.json")
G.add_edge(t, nid)
result = god_nodes(G, top_n=10)
labels = [r["label"] for r in result]
for variant in ("Start", "START", "Name", "ID"):
assert variant not in labels, f"`{variant}` should be filtered as JSON-key noise"
-42
View File
@@ -135,45 +135,3 @@ def test_build_calls_dedup():
}
G = build([chunk1, chunk2])
assert G.number_of_nodes() == 1
# --- #878: fuzzy dedup false merges on short/variant labels ---
def test_dedup_does_not_merge_numeric_variants(tmp_path):
"""Chip SKU variants (ASR1603 vs ASR1605) must not be merged (#878)."""
nodes = _make_nodes("ASR1603", "ASR1605")
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2, "ASR1603 and ASR1605 are distinct chip models, not duplicates"
def test_dedup_does_not_merge_short_insertion_variants(tmp_path):
"""Short labels differing by an insertion (cranel vs cranelr) must not merge (#878)."""
nodes = _make_nodes("cranel", "cranelr")
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2, "cranel and cranelr are distinct, not a typo"
def test_dedup_does_not_merge_model_with_suffix(tmp_path):
"""M1 vs M1 Pro must not merge (#878)."""
nodes = _make_nodes("M1", "M1 Pro")
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2, "M1 and M1 Pro are distinct Apple chip variants"
def test_dedup_still_merges_real_typos():
"""Genuine same-length single-char typos should still merge (#878 non-regression)."""
from graphify.dedup import _is_variant_pair, _short_label_blocked
from rapidfuzz.distance import JaroWinkler
a, b = "graphextractor", "graphextractar"
score = JaroWinkler.normalized_similarity(a, b) * 100
assert not _is_variant_pair(a, b), "not a variant pair"
assert not _short_label_blocked(a, b, score), "long-enough label, should not be blocked"
def test_variant_pair_helper():
"""_is_variant_pair correctly identifies chip-model variant pairs (#878)."""
from graphify.dedup import _is_variant_pair
assert _is_variant_pair("asr1603", "asr1605")
assert _is_variant_pair("cortex a55", "cortex a55x")
assert not _is_variant_pair("graphextractor", "graphextracter")
assert not _is_variant_pair("foo", "foo")
+3 -137
View File
@@ -47,17 +47,11 @@ def test_detect_warns_small_corpus():
assert result["needs_graph"] is False
assert result["warning"] is not None
def test_detect_skips_noise_dot_dirs():
"""Noise dot dirs (.next, .nuxt, .graphify cache, …) are skipped (#873).
Non-noise dot dirs (.github, .claude, …) are now allowed through."""
def test_detect_skips_dotfiles():
result = detect(FIXTURES)
for files in result["files"].values():
for f in files:
# graphify's own cache is always skipped
assert "/.graphify/" not in f
# well-known framework caches are always skipped
for noise in ("/.next/", "/.nuxt/", "/.turbo/", "/.angular/"):
assert noise not in f
assert "/." not in f
def test_classify_md_paper_by_signals(tmp_path):
@@ -226,47 +220,6 @@ def test_detect_handles_circular_symlinks(tmp_path):
assert any("main.py" in f for f in result["files"]["code"])
def test_detect_auto_detects_direct_symlink_child(tmp_path):
"""When ``root`` has a direct symlinked child, default (None) follows symlinks
so the user does not have to know to pass follow_symlinks=True for "fake
working dir" patterns (folder of symlinks pointing at scattered sources)."""
real_dir = tmp_path / "real_lib"
real_dir.mkdir()
(real_dir / "util.py").write_text("x = 1")
(tmp_path / "linked_lib").symlink_to(real_dir)
# Default (no kwarg): auto-detect → follows because of linked_lib symlink
result = detect(tmp_path)
assert any("linked_lib" in f for f in result["files"]["code"])
def test_detect_default_does_not_follow_when_no_symlinks(tmp_path):
"""When ``root`` has no direct symlinks, the auto-detect default stays False
(legacy behaviour preserved for ordinary scans)."""
(tmp_path / "main.py").write_text("x = 1")
sub = tmp_path / "sub"
sub.mkdir()
(sub / "other.py").write_text("y = 2")
# Smoke: no symlinks anywhere → auto-detect returns False, scan succeeds
result = detect(tmp_path)
assert any("main.py" in f for f in result["files"]["code"])
assert any("other.py" in f for f in result["files"]["code"])
def test_detect_explicit_false_overrides_auto_detect(tmp_path):
"""An explicit follow_symlinks=False overrides the auto-detect, even when
root contains symlinks. Lets callers opt out of the new behaviour."""
real_dir = tmp_path / "real_lib"
real_dir.mkdir()
(real_dir / "util.py").write_text("x = 1")
(tmp_path / "linked_lib").symlink_to(real_dir)
# Explicit False overrides auto-detect; symlink contents must NOT appear.
result = detect(tmp_path, follow_symlinks=False)
assert not any("linked_lib" in f for f in result["files"]["code"])
def test_detect_incremental_propagates_follow_symlinks(tmp_path, monkeypatch):
"""detect_incremental must forward follow_symlinks so symlinked sub-trees
appear in incremental scans the same way they appear in full scans."""
@@ -277,11 +230,7 @@ def test_detect_incremental_propagates_follow_symlinks(tmp_path, monkeypatch):
(real_dir / "note.md").write_text("# real note\n\nsome content")
(tmp_path / "linked_corpus").symlink_to(real_dir)
# Store manifest inside graphify-out/ so it is pruned by _SKIP_DIRS
# and doesn't get re-detected as a code file now that .json is indexed.
manifest_dir = tmp_path / "graphify-out"
manifest_dir.mkdir()
manifest_path = str(manifest_dir / "manifest.json")
manifest_path = str(tmp_path / "manifest.json")
# Without following symlinks, the symlinked dir contents are invisible.
no_link = detect_incremental(tmp_path, manifest_path, follow_symlinks=False)
@@ -418,86 +367,3 @@ def test_detect_skips_storybook_static_dir(tmp_path):
all_files = [f for files in result["files"].values() for f in files]
assert not any("storybook-static" in f for f in all_files)
assert any("Button.tsx" in f for f in all_files)
# --- #873: dot dirs allowed, framework caches blocked ---
def test_detect_allows_github_dir(tmp_path):
"""Files inside .github/ (workflows etc.) are now indexed (#873)."""
gh = tmp_path / ".github" / "workflows"
gh.mkdir(parents=True)
(gh / "ci.yml").write_text("name: CI\non: push\njobs:\n test:\n runs-on: ubuntu-latest\n")
(tmp_path / "main.py").write_text("def run(): pass")
result = detect(tmp_path)
all_files = [f for files in result["files"].values() for f in files]
assert any(".github" in f for f in all_files), "expected .github/workflows/ci.yml to be detected"
def test_detect_skips_next_cache(tmp_path):
""".next/ (Next.js build cache) must be excluded even after dot-dir fix (#873)."""
next_dir = tmp_path / ".next" / "cache"
next_dir.mkdir(parents=True)
(next_dir / "build.js").write_text("(function(){var s=1;})()")
pages = tmp_path / "pages"
pages.mkdir()
(pages / "index.tsx").write_text("export default function Home() { return <div/> }")
result = detect(tmp_path)
all_files = [f for files in result["files"].values() for f in files]
assert not any(".next" in f for f in all_files)
assert any("index.tsx" in f for f in all_files)
def test_detect_skips_graphify_own_cache(tmp_path):
""".graphify/ (extraction cache) must never be re-indexed as source (#873)."""
cache = tmp_path / ".graphify" / "cache"
cache.mkdir(parents=True)
(cache / "abc123.json").write_text('{"nodes": [], "edges": []}')
(tmp_path / "app.py").write_text("def go(): pass")
result = detect(tmp_path)
all_files = [f for files in result["files"].values() for f in files]
assert not any(".graphify" in f for f in all_files)
assert any("app.py" in f for f in all_files)
# --- #882: gitignore parent-exclusion rule for ! re-includes ---
def test_negation_cannot_rescue_file_under_excluded_dir(tmp_path):
"""A ! re-include cannot un-ignore a file whose parent dir is excluded (#882)."""
from graphify.detect import _is_ignored, _load_graphifyignore
android = tmp_path / "android" / "app" / "src"
android.mkdir(parents=True)
victim = android / "Main.kt"
victim.write_text("fun main() {}")
(tmp_path / ".graphifyignore").write_text("android/\n!src/\n")
patterns = _load_graphifyignore(tmp_path)
assert _is_ignored(victim, tmp_path, patterns), (
"android/app/src/Main.kt must remain ignored even with !src/ because "
"the parent android/ is excluded"
)
def test_negation_works_when_no_ancestor_excluded(tmp_path):
"""A ! re-include must still un-ignore a file when no ancestor is excluded (#882)."""
from graphify.detect import _is_ignored, _load_graphifyignore
src = tmp_path / "src"
src.mkdir()
keep = src / "keep.py"
keep.write_text("x = 1")
(tmp_path / ".graphifyignore").write_text("*.py\n!src/keep.py\n")
patterns = _load_graphifyignore(tmp_path)
assert not _is_ignored(keep, tmp_path, patterns), (
"src/keep.py should be un-ignored by !src/keep.py since src/ itself is not excluded"
)
def test_negation_ancestor_itself_reincluded(tmp_path):
"""If the ancestor dir itself is re-included, its children should not be blocked (#882)."""
from graphify.detect import _is_ignored, _load_graphifyignore
vendor = tmp_path / "vendor" / "lib"
vendor.mkdir(parents=True)
f = vendor / "utils.py"
f.write_text("x = 1")
(tmp_path / ".graphifyignore").write_text("vendor/\n!vendor/\n")
patterns = _load_graphifyignore(tmp_path)
# vendor/ is excluded then re-included; ancestor eval returns False so file is evaluated on its own
assert not _is_ignored(f, tmp_path, patterns)
+1 -168
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from graphify.extract import extract_python, extract, collect_files, _make_id, extract_bash, extract_json, _DISPATCH
from graphify.extract import extract_python, extract, collect_files, _make_id
FIXTURES = Path(__file__).parent / "fixtures"
@@ -425,170 +425,3 @@ def test_extract_parallel_returns_false_on_broken_pool(tmp_path, monkeypatch, ca
out = capsys.readouterr().out
assert "BrokenProcessPool" in out, "user-facing warning must mention the failure"
assert "__main__" in out, "warning must hint at the Windows __main__ guard idiom"
# ---------------------------------------------------------------------------
# Bash extractor tests (#866)
# ---------------------------------------------------------------------------
def test_dispatch_includes_sh_and_json():
assert ".sh" in _DISPATCH
assert ".bash" in _DISPATCH
assert ".json" in _DISPATCH
def test_extract_bash_finds_functions():
result = extract_bash(FIXTURES / "sample.sh")
assert "error" not in result
labels = {n["label"] for n in result["nodes"]}
assert "build()" in labels
assert "test_suite()" in labels
assert "deploy()" in labels
def test_extract_bash_emits_defines_edges():
result = extract_bash(FIXTURES / "sample.sh")
relations = {e["relation"] for e in result["edges"]}
assert "defines" in relations
def test_extract_bash_emits_calls_edges():
result = extract_bash(FIXTURES / "sample.sh")
calls = [(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "calls"]
# deploy() calls build() and test_suite(); test_suite() calls build()
assert any("deploy" in s and "build" in t for s, t in calls)
assert any("deploy" in s and "test_suite" in t for s, t in calls)
assert any("test_suite" in s and "build" in t for s, t in calls)
def test_extract_bash_calls_have_extracted_confidence():
result = extract_bash(FIXTURES / "sample.sh")
for e in result["edges"]:
if e["relation"] == "calls":
assert e["confidence"] == "EXTRACTED"
assert e.get("context") == "call"
def test_extract_bash_emits_source_imports_from(tmp_path):
helpers = tmp_path / "helpers.sh"
helpers.write_text("# helper\n")
script = tmp_path / "deploy.sh"
script.write_text(f"#!/bin/bash\nsource ./helpers.sh\nfoo() {{ echo hi; }}\n")
result = extract_bash(script)
import_edges = [e for e in result["edges"] if e["relation"] == "imports_from"]
assert len(import_edges) >= 1
assert import_edges[0].get("context") == "import"
def test_extract_bash_no_self_loops():
result = extract_bash(FIXTURES / "sample.sh")
for e in result["edges"]:
assert e["source"] != e["target"], f"Self-loop: {e}"
def test_extract_bash_no_dangling_edges():
result = extract_bash(FIXTURES / "sample.sh")
node_ids = {n["id"] for n in result["nodes"]}
for e in result["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e['source']}"
# targets may reference external files (imports_from) — only check non-import edges
if e["relation"] not in ("imports_from", "imports"):
assert e["target"] in node_ids, f"Dangling target: {e['target']}"
def test_extract_bash_skip_builtins_in_calls():
result = extract_bash(FIXTURES / "sample.sh")
builtins = {"echo", "cd", "set", "export", "local", "mkdir", "if", "then"}
call_targets = {e["target"] for e in result["edges"] if e["relation"] == "calls"}
for b in builtins:
assert not any(b in t for t in call_targets), f"Builtin '{b}' appeared as calls target"
def test_extract_bash_missing_grammar_returns_error():
"""extract_bash returns error dict when tree-sitter-bash not installed (mocked)."""
import unittest.mock as mock
import builtins
real_import = builtins.__import__
def patched(name, *args, **kwargs):
if name == "tree_sitter_bash":
raise ImportError("mocked")
return real_import(name, *args, **kwargs)
with mock.patch("builtins.__import__", side_effect=patched):
result = extract_bash(FIXTURES / "sample.sh")
assert "error" in result
assert result["nodes"] == []
# ---------------------------------------------------------------------------
# JSON extractor tests (#866)
# ---------------------------------------------------------------------------
def test_extract_json_top_level_keys():
result = extract_json(FIXTURES / "sample.json")
assert "error" not in result
labels = {n["label"] for n in result["nodes"]}
assert "name" in labels
assert "version" in labels
assert "scripts" in labels
assert "dependencies" in labels
def test_extract_json_nested_contains():
result = extract_json(FIXTURES / "sample.json")
contains = [(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "contains"]
assert any("scripts" in s and "build" in t for s, t in contains)
assert any("scripts" in s and "test" in t for s, t in contains)
assert any("dependencies" in s and "react" in t for s, t in contains)
def test_extract_json_dependencies_become_imports():
result = extract_json(FIXTURES / "sample.json")
import_edges = [e for e in result["edges"] if e["relation"] == "imports"]
targets = {e["target"] for e in import_edges}
assert any("react" in t for t in targets)
assert any("axios" in t for t in targets)
assert any("typescript" in t for t in targets)
def test_extract_json_extends_resolved():
result = extract_json(FIXTURES / "sample_tsconfig.json")
extends_edges = [e for e in result["edges"] if e["relation"] == "extends"]
assert len(extends_edges) >= 1
assert extends_edges[0].get("context") == "import"
def test_extract_json_large_file_skipped(tmp_path):
big = tmp_path / "big.json"
# Write a JSON file just over 1 MiB
big.write_bytes(b'{"x": "' + b"a" * (1_048_576) + b'"}')
result = extract_json(big)
assert "error" in result
assert result["nodes"] == []
def test_extract_json_handles_invalid_json(tmp_path):
bad = tmp_path / "broken.json"
bad.write_text("{this is not: valid json!!!")
result = extract_json(bad)
# Should not crash — returns empty or error result
assert isinstance(result, dict)
assert "nodes" in result
def test_extract_json_no_self_loops():
result = extract_json(FIXTURES / "sample.json")
for e in result["edges"]:
assert e["source"] != e["target"], f"Self-loop: {e}"
def test_extract_bash_via_dispatch():
from graphify.extract import _get_extractor
assert _get_extractor(Path("foo.sh")) is extract_bash
assert _get_extractor(Path("foo.bash")) is extract_bash
def test_extract_json_via_dispatch():
from graphify.extract import _get_extractor
assert _get_extractor(Path("foo.json")) is extract_json
-117
View File
@@ -1,117 +0,0 @@
"""Regression tests for install-time instruction strings.
These strings live in graphify/__main__.py and are written into project-local
files (CLAUDE.md, AGENTS.md, GEMINI.md, .cursor/rules/, .kiro/steering/, etc.)
or into in-process hook payloads. Earlier versions of graphify told every
assistant to "ALWAYS read graphify-out/GRAPH_REPORT.md before answering" —
which silently increased per-question token usage in Claude Code sessions
(issue #580). This file locks in the query-first policy so a future revert
or partial change is caught by CI.
"""
from __future__ import annotations
import json
from graphify.__main__ import (
_SETTINGS_HOOK,
_CLAUDE_MD_SECTION,
_AGENTS_MD_SECTION,
_GEMINI_MD_SECTION,
_GEMINI_HOOK,
_VSCODE_INSTRUCTIONS_SECTION,
_ANTIGRAVITY_RULES,
_KIRO_STEERING,
_CURSOR_RULE,
_OPENCODE_PLUGIN_JS,
)
# All install-surface text rendered as plain strings, in one place.
# Hook constants are dicts/JSON; serialize them so we can do substring checks
# against the actual payload text the assistant will receive.
_INSTALL_TEXTS: dict[str, str] = {
"_SETTINGS_HOOK": json.dumps(_SETTINGS_HOOK),
"_CLAUDE_MD_SECTION": _CLAUDE_MD_SECTION,
"_AGENTS_MD_SECTION": _AGENTS_MD_SECTION,
"_GEMINI_MD_SECTION": _GEMINI_MD_SECTION,
"_GEMINI_HOOK": json.dumps(_GEMINI_HOOK),
"_VSCODE_INSTRUCTIONS_SECTION": _VSCODE_INSTRUCTIONS_SECTION,
"_ANTIGRAVITY_RULES": _ANTIGRAVITY_RULES,
"_KIRO_STEERING": _KIRO_STEERING,
"_CURSOR_RULE": _CURSOR_RULE,
"_OPENCODE_PLUGIN_JS": _OPENCODE_PLUGIN_JS,
}
def test_every_install_surface_recommends_graphify_query():
"""All ten install surfaces must point the assistant at `graphify query`
as the first action for codebase questions. This is the load-bearing
fix for issue #580 — the alternative (reading GRAPH_REPORT.md) costs
~10x more tokens per question and made the project worse-than-baseline
in real Claude Code sessions."""
missing: list[str] = []
for name, text in _INSTALL_TEXTS.items():
if "graphify query" not in text:
missing.append(name)
assert not missing, (
f"these install surfaces no longer mention `graphify query`: {missing}. "
f"If you removed it intentionally, consider whether issue #580 is back."
)
def test_no_install_surface_demands_reading_the_full_report_first():
"""The pre-fix instructions told assistants to read GRAPH_REPORT.md as
their first action for codebase questions. The new policy demotes the
report to a fallback; any phrasing that puts reading the report BEFORE
other actions for codebase questions is a regression of issue #580.
Uses regex patterns instead of literal strings so a future revert that
rephrases ("MUST read", "Always consult", "first task is to open ...")
is also caught. Note: bare 'ALWAYS' is NOT banned because
``alwaysApply: true`` (Cursor) and ``trigger: always_on`` (Antigravity)
are legitimate platform metadata, not the bug.
"""
import re
banned = [
# "read ... GRAPH_REPORT.md ... before"
re.compile(r"read[^.\n]{0,80}GRAPH_REPORT\.md[^.\n]{0,80}before", re.IGNORECASE),
# "first tool call ... GRAPH_REPORT" (VS Code variant)
re.compile(r"first\s+tool\s+call[^.\n]{0,80}GRAPH_REPORT", re.IGNORECASE),
# "ALWAYS read ... GRAPH_REPORT" (catches the literal old text and minor variants)
re.compile(r"always\s+read[^.\n]{0,80}GRAPH_REPORT", re.IGNORECASE),
]
hits: list[tuple[str, str]] = []
for name, text in _INSTALL_TEXTS.items():
for pattern in banned:
m = pattern.search(text)
if m:
hits.append((name, m.group(0)))
assert not hits, (
f"banned report-first phrasing reappeared: {hits}. "
f"This regresses issue #580."
)
def test_report_is_still_referenced_as_fallback():
"""The fix demotes GRAPH_REPORT.md, it doesn't delete the reference.
Most install surfaces should still mention the report as the deep-dive
artifact so users know it exists for broad architecture review.
(Hook payloads may or may not name the report; check the MD sections
explicitly — those are the rule lists assistants follow.)"""
md_section_texts = {
"_CLAUDE_MD_SECTION": _CLAUDE_MD_SECTION,
"_AGENTS_MD_SECTION": _AGENTS_MD_SECTION,
"_GEMINI_MD_SECTION": _GEMINI_MD_SECTION,
"_VSCODE_INSTRUCTIONS_SECTION": _VSCODE_INSTRUCTIONS_SECTION,
"_ANTIGRAVITY_RULES": _ANTIGRAVITY_RULES,
"_KIRO_STEERING": _KIRO_STEERING,
"_CURSOR_RULE": _CURSOR_RULE,
}
missing: list[str] = []
for name, text in md_section_texts.items():
if "GRAPH_REPORT.md" not in text:
missing.append(name)
assert not missing, (
f"these install sections no longer mention GRAPH_REPORT.md at all: {missing}. "
f"The fix should demote the report, not delete the reference — users need to know "
f"it's available for broad-architecture queries."
)
-233
View File
@@ -1,233 +0,0 @@
"""Installer-level regression tests for upgrade-in-place behavior (issue #580).
Pre-fix, the installers wrote a "## graphify" section with report-first
instructions and skipped writing if the marker was already present. So users
who installed graphify and then upgraded to the fixed package still had the
old report-first text on disk — the bug stayed live for them.
These tests seed each platform's instruction file with the old report-first
section, run the installer, and assert that the on-disk file now contains
the new query-first wording and does not contain the old report-first text.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
import graphify.__main__ as mainmod
# A representative slice of the pre-fix text. Each platform's old install
# wrote a variant of "ALWAYS read graphify-out/GRAPH_REPORT.md before ...".
_OLD_CLAUDE_SECTION = """\
## graphify
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
Rules:
- ALWAYS read graphify-out/GRAPH_REPORT.md before reading any source files, running grep/glob searches, or answering codebase questions. The graph is your primary map of the codebase.
- IF graphify-out/wiki/index.md EXISTS, navigate it instead of reading raw files
- For cross-module "how does X relate to Y" questions, prefer `graphify query "<question>"`, `graphify path "<A>" "<B>"`, or `graphify explain "<concept>"` over grep — these traverse the graph's EXTRACTED + INFERRED edges instead of scanning files
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
"""
_OLD_AGENTS_SECTION = _OLD_CLAUDE_SECTION # identical pre-fix shape
_OLD_GEMINI_SECTION = _OLD_CLAUDE_SECTION
_OLD_VSCODE_SECTION = """\
## graphify
For any question about this repo's architecture, structure, components, or how to add/modify/find
code, your **first tool call must be** to read `graphify-out/GRAPH_REPORT.md` (if it exists).
Triggers: "how do I…", "where is…", "what does … do", "add/modify a <component>".
"""
_OLD_CURSOR_RULE = """\
---
description: graphify knowledge graph context
alwaysApply: true
---
This project has a graphify knowledge graph at graphify-out/.
- 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
"""
_OLD_KIRO_STEERING = """\
---
inclusion: always
---
graphify: A knowledge graph of this project lives in `graphify-out/`. \
If `graphify-out/GRAPH_REPORT.md` exists, read it before answering architecture questions, \
tracing dependencies, or searching files — it contains god nodes, community structure, \
and surprising connections the graph found.
"""
_OLD_HOOK_PAYLOAD_SNIPPET = "Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files"
def _assert_no_report_first(text: str, ctx: str) -> None:
assert "ALWAYS read graphify-out/GRAPH_REPORT.md" not in text, (
f"{ctx}: old 'ALWAYS read' phrasing survived upgrade"
)
assert "first tool call must be" not in text, (
f"{ctx}: old VS Code 'first tool call must be' phrasing survived upgrade"
)
def _assert_query_first(text: str, ctx: str) -> None:
assert "graphify query" in text, (
f"{ctx}: new 'graphify query' guidance missing after upgrade"
)
def test_claude_install_upgrades_stale_section(tmp_path, monkeypatch):
"""A pre-fix CLAUDE.md gets the new section in place when the user runs
`graphify claude install` again after upgrading to a fixed package."""
monkeypatch.chdir(tmp_path)
claude_md = tmp_path / "CLAUDE.md"
claude_md.write_text("# My Project\n\nSome description.\n\n" + _OLD_CLAUDE_SECTION, encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
mainmod.claude_install(tmp_path)
after = claude_md.read_text(encoding="utf-8")
_assert_no_report_first(after, "CLAUDE.md")
_assert_query_first(after, "CLAUDE.md")
# Pre-existing non-graphify content must be preserved
assert "# My Project" in after
assert "Some description." in after
def test_claude_install_upgrades_stale_hook_payload(tmp_path, monkeypatch):
"""The Claude install must also rewrite a stale .claude/settings.json hook
payload on upgrade. Pre-fix, the install returned early when CLAUDE.md was
already configured, leaving the old hook in place."""
monkeypatch.chdir(tmp_path)
claude_md = tmp_path / "CLAUDE.md"
claude_md.write_text(_OLD_CLAUDE_SECTION, encoding="utf-8")
settings = tmp_path / ".claude" / "settings.json"
settings.parent.mkdir(parents=True, exist_ok=True)
stale_settings = {
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": (
"case x in *) "
+ _OLD_HOOK_PAYLOAD_SNIPPET
+ " esac"
),
}
],
}
]
}
}
settings.write_text(json.dumps(stale_settings), encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
mainmod.claude_install(tmp_path)
new_settings_text = settings.read_text(encoding="utf-8")
assert _OLD_HOOK_PAYLOAD_SNIPPET not in new_settings_text, (
"stale hook payload survived upgrade"
)
assert "graphify query" in new_settings_text, (
"new hook payload should route to `graphify query`"
)
def test_agents_install_upgrades_stale_section(tmp_path, monkeypatch):
"""Same upgrade behavior for AGENTS.md (Codex / OpenCode / Aider / Trae)."""
monkeypatch.chdir(tmp_path)
agents_md = tmp_path / "AGENTS.md"
agents_md.write_text("# Project agents\n\n" + _OLD_AGENTS_SECTION, encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
mainmod._agents_install(tmp_path, platform="codex")
after = agents_md.read_text(encoding="utf-8")
_assert_no_report_first(after, "AGENTS.md")
_assert_query_first(after, "AGENTS.md")
assert "# Project agents" in after
def test_gemini_install_upgrades_stale_section(tmp_path, monkeypatch):
"""Same upgrade behavior for GEMINI.md."""
monkeypatch.chdir(tmp_path)
gemini_md = tmp_path / "GEMINI.md"
gemini_md.write_text(_OLD_GEMINI_SECTION, encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
mainmod.gemini_install(tmp_path)
after = gemini_md.read_text(encoding="utf-8")
_assert_no_report_first(after, "GEMINI.md")
_assert_query_first(after, "GEMINI.md")
def test_vscode_install_upgrades_stale_section(tmp_path, monkeypatch):
"""Same upgrade behavior for .github/copilot-instructions.md (VS Code)."""
monkeypatch.chdir(tmp_path)
instructions = tmp_path / ".github" / "copilot-instructions.md"
instructions.parent.mkdir(parents=True, exist_ok=True)
instructions.write_text(_OLD_VSCODE_SECTION, encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
mainmod.vscode_install(tmp_path)
after = instructions.read_text(encoding="utf-8")
_assert_no_report_first(after, "copilot-instructions.md")
_assert_query_first(after, "copilot-instructions.md")
def test_cursor_install_upgrades_stale_rule(tmp_path, monkeypatch):
"""Same upgrade behavior for .cursor/rules/graphify.mdc.
The Cursor rule file is wholly graphify-owned; overwrite on upgrade."""
monkeypatch.chdir(tmp_path)
rule_path = tmp_path / ".cursor" / "rules" / "graphify.mdc"
rule_path.parent.mkdir(parents=True, exist_ok=True)
rule_path.write_text(_OLD_CURSOR_RULE, encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
mainmod._cursor_install(tmp_path)
after = rule_path.read_text(encoding="utf-8")
assert "read graphify-out/GRAPH_REPORT.md for god nodes and community structure" not in after
_assert_query_first(after, ".cursor/rules/graphify.mdc")
# YAML frontmatter must be preserved
assert "alwaysApply: true" in after
def test_kiro_install_upgrades_stale_steering(tmp_path, monkeypatch):
"""Same upgrade behavior for .kiro/steering/graphify.md (wholly owned)."""
monkeypatch.chdir(tmp_path)
steering = tmp_path / ".kiro" / "steering" / "graphify.md"
steering.parent.mkdir(parents=True, exist_ok=True)
steering.write_text(_OLD_KIRO_STEERING, encoding="utf-8")
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
# Kiro install copies a skill file too; provide a minimal stand-in
skill_src = Path(mainmod.__file__).parent / "skill-kiro.md"
if not skill_src.exists():
pytest.skip("skill-kiro.md not present in this checkout")
mainmod._kiro_install(tmp_path)
after = steering.read_text(encoding="utf-8")
assert "read it before answering architecture questions" not in after
_assert_query_first(after, ".kiro/steering/graphify.md")
assert "inclusion: always" in after # frontmatter preserved
-85
View File
@@ -87,88 +87,3 @@ def test_rationale_confidence_is_extracted(tmp_path):
result = extract_python(path)
rationale_edges = [e for e in result["edges"] if e.get("relation") == "rationale_for"]
assert all(e.get("confidence") == "EXTRACTED" for e in rationale_edges)
def test_alembic_module_docstring_suppressed(tmp_path):
path = _write_py(tmp_path, '''
"""initial schema
Revision ID: 0001abcd
Revises:
Create Date: 2023-01-01 00:00:00
"""
revision = "0001abcd"
down_revision = None
branch_labels = None
def upgrade():
pass
def downgrade():
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert not any("Revision ID" in n["label"] for n in rationale)
def test_alembic_function_docstrings_still_extracted(tmp_path):
"""Function docstrings inside upgrade/downgrade should still be captured."""
path = _write_py(tmp_path, '''
"""Revision ID: 0002 Revises: 0001"""
revision = "0002"
down_revision = "0001"
def upgrade():
"""Add users table because auth was added in this release."""
pass
def downgrade():
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
# module docstring suppressed
assert not any("Revision ID" in n["label"] for n in rationale)
# function docstring still captured
assert any("auth" in n["label"] for n in rationale)
def test_non_migration_revision_var_not_suppressed(tmp_path):
"""A file with a `revision` variable but no Alembic markers keeps its docstring."""
path = _write_py(tmp_path, '''
"""This module tracks document revisions because we need audit history."""
revision = 42
def get_revision(): pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert any("audit history" in n["label"] for n in rationale)
def test_django_migration_module_docstring_suppressed(tmp_path):
path = _write_py(tmp_path, '''
"""Add post_priority_config table."""
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("myapp", "0001_initial")]
operations = []
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert not any("post_priority" in n["label"] for n in rationale)
def test_generated_file_module_docstring_suppressed(tmp_path):
path = _write_py(tmp_path, '''
"""Generated by the protocol buffer compiler. DO NOT EDIT!"""
from google.protobuf import descriptor as _descriptor
class UserMessage:
pass
''')
result = extract_python(path)
rationale = [n for n in result["nodes"] if n.get("file_type") == "rationale"]
assert not any("protocol buffer" in n["label"].lower() for n in rationale)
-170
View File
@@ -7,8 +7,6 @@ from networkx.readwrite import json_graph
from graphify.serve import (
_communities_from_graph,
_score_nodes,
_compute_idf,
_pick_seeds,
_bfs,
_dfs,
_filter_graph_by_context,
@@ -198,171 +196,3 @@ def test_load_graph_missing_file(tmp_path):
graphify_dir.mkdir()
with pytest.raises(SystemExit):
_load_graph(str(graphify_dir / "nonexistent.json"))
# --- #874: MCP hot-reload ---
def _write_graph(path, nodes: list[str]) -> None:
"""Write a minimal graph.json with the given node IDs."""
G = nx.DiGraph()
for n in nodes:
G.add_node(n, label=n, community=0)
data = json_graph.node_link_data(G, edges="links")
path.write_text(json.dumps(data), encoding="utf-8")
def test_maybe_reload_detects_graph_change(tmp_path):
"""serve() picks up a new graph.json written after startup (#874)."""
import time
from unittest.mock import patch
out = tmp_path / "graphify-out"
out.mkdir()
graph_path = out / "graph.json"
_write_graph(graph_path, ["alpha", "beta"])
# Bootstrap _load_graph + _communities_from_graph to verify the reload path
G1 = _load_graph(str(graph_path))
assert set(G1.nodes()) == {"alpha", "beta"}
# Simulate file changing (bump mtime by touching)
time.sleep(0.01)
_write_graph(graph_path, ["alpha", "beta", "gamma"])
G2 = _load_graph(str(graph_path))
assert "gamma" in G2.nodes()
def test_load_graph_cache_key_changes_with_content(tmp_path):
"""mtime_ns + size uniquely identifies a graph version (#874)."""
import time
out = tmp_path / "graphify-out"
out.mkdir()
graph_path = out / "graph.json"
_write_graph(graph_path, ["a"])
s1 = graph_path.stat()
key1 = (s1.st_mtime_ns, s1.st_size)
time.sleep(0.01)
_write_graph(graph_path, ["a", "b"])
s2 = graph_path.stat()
key2 = (s2.st_mtime_ns, s2.st_size)
assert key1 != key2, "stat key must change when file content changes"
# --- IDF weighting tests (#897) ---
def _make_noisy_graph() -> nx.Graph:
"""20 error-handler nodes + 1 rare identifier: FooBarService."""
G = nx.Graph()
for i in range(20):
G.add_node(f"err{i}", label=f"error_handler_{i}", source_file=f"err{i}.py", community=0)
if i > 0:
G.add_edge(f"err{i-1}", f"err{i}", relation="calls", confidence="EXTRACTED")
G.add_node("fbs", label="FooBarService", source_file="service.py", community=1)
G.add_node("fbs_dep", label="ServiceClient", source_file="client.py", community=1)
G.add_edge("fbs", "fbs_dep", relation="uses", confidence="EXTRACTED")
return G
def test_idf_downweights_common_terms():
"""'error' matches 20 nodes, 'foobarservice' matches 1 — IDF should make
FooBarService rank first despite error's higher raw frequency."""
G = _make_noisy_graph()
scored = _score_nodes(G, ["foobarservice", "error"])
assert scored, "should have results"
assert scored[0][1] == "fbs", (
f"FooBarService should rank first, got {scored[0][1]}"
)
def test_idf_cached_on_graph():
"""IDF results are stored in G.graph so repeated queries don't recompute."""
G = _make_graph()
_score_nodes(G, ["extract"])
assert "_idf_cache" in G.graph
assert "extract" in G.graph["_idf_cache"]
def test_idf_new_graph_starts_fresh():
"""Two separate graph instances must not share an IDF cache."""
G1 = _make_graph()
G2 = _make_graph()
_score_nodes(G1, ["extract"])
assert "_idf_cache" not in G2.graph
def test_idf_rare_term_gets_high_weight():
"""A term matching only 1 of N nodes should get IDF > 1."""
import math
G = _make_graph() # 5 nodes
idf = _compute_idf(G, ["extract"])
# extract matches only n1: IDF = log(1 + 5/2) ≈ 1.25
assert idf["extract"] > 1.0
def test_idf_common_term_gets_low_weight():
"""A term matching most nodes should get IDF < 1."""
import math
G = nx.Graph()
# 'handle' in every node label
for i in range(20):
G.add_node(f"n{i}", label=f"handle_{i}", source_file=f"f{i}.py")
idf = _compute_idf(G, ["handle"])
assert idf["handle"] < 1.0
# --- _pick_seeds tests (#897) ---
def test_pick_seeds_dominant_identifier_gives_one_seed():
"""FooBarService at 1000 vs error nodes at 1.0 → only 1 seed chosen."""
scored = [(1000.0, "fbs"), (1.0, "err1"), (0.9, "err2")]
seeds = _pick_seeds(scored)
assert seeds == ["fbs"]
def test_pick_seeds_close_scores_keeps_multiple():
"""When all scores are within 20% of the top, keep up to 3 seeds."""
scored = [(10.0, "a"), (9.0, "b"), (8.5, "c")]
seeds = _pick_seeds(scored)
assert len(seeds) == 3
def test_pick_seeds_empty():
assert _pick_seeds([]) == []
def test_pick_seeds_single():
assert _pick_seeds([(5.0, "x")]) == ["x"]
def test_pick_seeds_respects_max_k():
"""Never return more than max_k seeds even when all scores are close."""
scored = [(10.0, f"n{i}") for i in range(10)]
seeds = _pick_seeds(scored, max_k=3)
assert len(seeds) == 3
# --- actionable truncation hint (#897) ---
def test_subgraph_to_text_truncation_hint_is_actionable():
"""Truncation message must tell Claude what to do, not just say truncated."""
G = _make_graph()
text = _subgraph_to_text(G, {"n1", "n2", "n3", "n4"}, [("n1", "n2")], token_budget=1)
assert "truncated" in text
assert "get_node" in text or "context_filter" in text
# --- integration: identifier + noise query seeds from identifier (#897) ---
def test_query_seeds_from_identifier_not_noise():
"""'FooBarService error handling' should expand from FooBarService,
not from error-handler nodes, so ServiceClient appears in results."""
G = _make_noisy_graph()
text = _query_graph_text(G, "FooBarService error handling", mode="bfs", depth=2)
assert "FooBarService" in text
assert "ServiceClient" in text
+1 -3
View File
@@ -47,9 +47,7 @@ def test_watched_extensions_includes_images():
assert ".jpg" in _WATCHED_EXTENSIONS
def test_watched_extensions_excludes_noise():
# .json is now indexed (bash/JSON extractors added in #866)
assert ".json" in _WATCHED_EXTENSIONS
assert ".sh" in _WATCHED_EXTENSIONS
assert ".json" not in _WATCHED_EXTENSIONS
assert ".pyc" not in _WATCHED_EXTENSIONS
assert ".log" not in _WATCHED_EXTENSIONS
Generated
-4183
View File
File diff suppressed because it is too large. Load diff