Compare commits

...
52 Commits
Author SHA1 Message Date
SafiandClaude Sonnet 4.6 441ac9fc38 bump to 0.7.8: update README extensions table and changelog for PR merges
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 12:28:02 +01:00
Safi 25c1ea9212 Merge PR #735: Add Gemini and OpenAI semantic extraction backends (preserve Ollama priority) 2026-05-06 12:13:39 +01:00
Safi 0010d38337 Merge PR #717: fix(extract): TS bare-path / .svelte.ts / .svelte.js / multi-dot import resolution 2026-05-06 12:06:27 +01:00
Safi 06df2066a8 Merge PR #732: feat: add Groovy and Spock support 2026-05-06 12:04:51 +01:00
Safi 12a706b595 Merge PR #711: feat(extract): add Markdown structural extraction + sync collect_files extensions with _DISPATCH 2026-05-06 12:02:43 +01:00
Safi 189cdd92c9 Merge PR #747: fix: sanitize subprocess call in hooks.py (replace git subprocess with configparser + path validation) 2026-05-06 12:00:18 +01:00
Safi 519564b742 Merge PR #745: add .luau extension support (Roblox Luau) 2026-05-06 11:59:40 +01:00
Safi 660b605e18 Merge PR #736: fix(detect): forward follow_symlinks from detect_incremental to detect 2026-05-06 11:58:59 +01:00
SafiandClaude Sonnet 4.6 e22a189df1 fix cluster-only label persistence, wiki data-loss guard, ollama error message (#744 #746 #750)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 11:56:04 +01:00
orbisai0security 6fa2ba2318 fix: V-003 security vulnerability
Automated security fix generated by Orbis Security AI
2026-05-06 06:51:11 +00:00
daleardiandClaude Opus 4.7 3457b9cd80 add .luau extension support (Roblox Luau)
Add `.luau` to CODE_EXTENSIONS and route it through extract_lua
(tree-sitter-lua). Roblox first-party code uses .luau; without this,
graphify silently skipped 379/479 files on a real Roblox codebase
and the resulting graph was dominated by vendored .lua dependencies.

tree-sitter-lua doesn't parse Luau type annotations, but it
successfully extracts function declarations and call edges from
Luau source — verified on a 379-file Roblox codebase (1265 nodes,
1471 edges, 236 communities).

A dedicated tree-sitter-luau grammar would be a richer long-term
fix; this is the minimal change to make Luau projects work today.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 23:56:51 -04:00
SafiandClaude Sonnet 4.6 48888a7c26 add Ollama backend and cross-project global graph (#729)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 18:36:59 +01:00
Safi 69d2cc84e2 fix merge-graphs to accept both edges and links key in graph.json (#738) 2026-05-05 17:14:12 +01:00
Safi 21e096fd88 update README with --graph for cluster-only and GRAPHIFY_MAX_OUTPUT_TOKENS 2026-05-05 16:04:59 +01:00
Safi 2415576ab0 bump version to 0.7.6 2026-05-05 16:02:09 +01:00
SafiandClaude Sonnet 4.6 005a36608a fix 7 bugs: cluster-only --graph, _is_sensitive boundaries, max_tokens 16384, prune message clarity, svelte stub source_file, svelte static imports, manifest on full rebuild + pi skill YAML fix
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-05 16:00:08 +01:00
Daniel Graham cc63a1711b Make Gemini extraction model configurable
The initial Gemini backend defaulted to 2.5 Flash, but large semantic extraction chunks can benefit from newer models and more output headroom. Move the default to Gemini 3 Flash Preview, add CLI and environment model overrides, and increase the Gemini completion budget while keeping low reasoning effort for cost control.

Constraint: Google exposes Gemini through an OpenAI-compatible chat-completions endpoint

Rejected: Hardcode Gemini 3.1 Pro as the default | higher cost for routine repository indexing

Confidence: medium

Scope-risk: narrow

Directive: Keep --model and GRAPHIFY_GEMINI_MODEL working before changing Gemini defaults again

Tested: uv run --directory vendor/graphify pytest tests/test_llm_backends.py tests/test_chunking.py -q

Not-tested: Live Gemini 3 extraction on the full cloud-edge repo before this commit
2026-05-05 10:11:12 -04:00
Alpha Nury 64585cf889 fix(detect): forward follow_symlinks from detect_incremental to detect
`detect_incremental(root)` always called `detect(root)` without forwarding
the `follow_symlinks` kwarg. As a result, corpora that include symlinked
sub-trees pointing to directories outside the scan root (e.g. a
`state_of_truth/` symlink pointing at `~/.hermes/state_of_truth/`) were
visible to a full `detect()` run with `follow_symlinks=True` but invisible
to any subsequent `--update` run. The incremental scan would then either
report no changes (silently dropping legitimate new files) or repeatedly
re-extract a phantom subset, depending on what was reachable without
crossing symlinks.

Add a keyword-only `follow_symlinks` parameter to `detect_incremental()`
and forward it. Default stays `False` for backwards compatibility — only
callers that already opt in to symlink following on `detect()` pick up
the new behaviour for incremental runs too.

Test: a corpus with a symlinked directory is invisible with
`follow_symlinks=False`, fully indexed with `follow_symlinks=True`, and
correctly reports zero new files on a second incremental scan after the
manifest is saved.
2026-05-05 15:25:08 +02:00
Daniel Graham a9cb692961 Prefer accessible semantic extraction backends
Gemini is often the cheaper available quota for low-stakes semantic graph extraction, while OpenAI is a useful fallback. Extend the direct extraction backend registry, CLI validation, docs, and tests so headless extraction can use GEMINI_API_KEY, GOOGLE_API_KEY, or OPENAI_API_KEY without changing the existing Claude and Kimi paths.

Constraint: Gemini supports OpenAI-compatible chat completions at the Google generative-language endpoint

Rejected: Native google-genai integration | higher dependency and response-shape churn for the same chat-completions path

Confidence: medium

Scope-risk: moderate

Directive: Keep backend detection explicit and test every accepted API-key environment variable before adding new providers

Tested: uv run --directory vendor/graphify pytest tests/test_llm_backends.py tests/test_chunking.py -q

Not-tested: Live Gemini/OpenAI API calls; no GEMINI_API_KEY or OPENAI_API_KEY present in this environment
2026-05-05 08:59:37 -04:00
Mikołaj Cekut 9a8346d39a chore: remove version pin from tree-sitter-groovy dependency 2026-05-05 12:23:46 +02:00
Mikołaj Cekut 6aecfcf0fe chore: replace pl.allegro with com.nicklastrange in Groovy fixtures 2026-05-05 12:22:38 +02:00
Mikołaj Cekut dc69020a47 feat: add Groovy and Spock support
- Register .groovy and .gradle in CODE_EXTENSIONS, _DISPATCH, and collect_files
- Add _GROOVY_CONFIG (reuses Java import handler)
- Add regex-based _extract_spock_fallback for Spock spec files where
  tree-sitter-groovy wraps the body in ERROR nodes due to def-string methods
- _is_spock_file detects via regex scan (def "...") instead of node-label
  heuristic, avoiding false negatives on classes whose name differs from stem
- Fallback retains only file node + import edges from tree-sitter pass to
  prevent orphaned constructor/method nodes
- Add tree-sitter-groovy>=0.1.2 dependency
- Add 11 tests covering plain Groovy and Spock paths, including apostrophe
  in feature method names
2026-05-05 12:15:15 +02:00
Christian Winther b68ec63494 fix(extract): apply resolver fixups to JS/TS dynamic_import handler
Third call site that re-implemented the same .js→.ts rewrite in
isolation. Previously only handled the explicit .js→.ts case; bare
paths, multi-dot helper files, and alias-resolved dynamic imports
all dropped silently.

Now uses _resolve_js_module_path on both branches (relative and
alias) — same shape as the static-import and Svelte regex paths.

Real-world impact: TS files using `await import('./foo')` patterns
for code splitting (e.g. lazy-loading a profanity check) now produce
edges to the resolved target.
2026-05-05 00:07:50 +02:00
Christian Winther 0dfc26e57f fix: prefer file matches over directory matches in resolver
When both a file (foo.ts) and a directory (foo/) exist at the same path,
both TypeScript and Vite prefer the file. The previous ordering checked
directory first and fell through unchanged when the directory had no
index, silently dropping every import like 'from ./auth' when an
auth/ subdirectory existed alongside auth.ts.
2026-05-04 23:44:32 +02:00
Christian Winther 5f5b59309c test(extract): cover .svelte.js + hybrid TS/JS Svelte 5 rune files
The generalized resolver already handles .svelte.js because the append
loop iterates _JS_RESOLVE_EXTS = (.ts, .tsx, .svelte, .js, .jsx, .mjs).
Adds three explicit tests to pin the behaviour and document the priority
choice:

  - test_resolve_svelte_to_svelte_js_for_javascript_rune_files
      JS-only Svelte 5 project: .svelte → .svelte.js works the same
      way as .svelte.ts in TS projects. No special-casing needed —
      the generalized append loop covers both.

  - test_resolve_svelte_prefers_svelte_ts_over_svelte_js
      Hybrid case (both files exist, e.g. .svelte.ts source plus
      .svelte.js build artifact): .ts wins. Documents the deliberate
      source-first priority — graphify is a source-code tool, not a
      runtime resolver, so we differ from Vite's default JS-first order.

  - test_resolve_real_svelte_file_wins_over_svelte_ts_sibling
      Existence check short-circuits before any extension append, so a
      real .svelte file always wins over a .svelte.ts sibling.
2026-05-04 22:47:29 +02:00
Christian Winther 49c3b50b5f fix(extract): generalize resolver to multi-dot filenames + rename
Two changes that landed together because they share the same code path:

1. Generalize the bare-path append to handle multi-dot filenames

   The previous resolver only appended extensions when path.suffix == ""
   (truly bare paths). Real codebases use a lot of multi-dot patterns:

     foo.shared.ts        ← imported as './foo.shared'
     foo.config.ts        ← imported as './foo.config'
     foo.compile.ts       ← imported as './foo.compile'
     foo.integration.ts   ← imported as './foo.integration' (test helper)
     foo.triggers.ts      ← imported as './foo.triggers'  (test helper)
     foo.svelte.ts        ← imported as './foo.svelte'    (Svelte 5 rune)
     foo.d.ts             ← imported as './foo.d'         (ambient types)

   For all of these, .suffix is the meaningful middle segment (.shared,
   .config, .integration, etc.) — not in the .js/.jsx/.svelte handled
   list, so the resolver fell through and the import dropped to a phantom.

   The fix unifies the bare-path and .svelte→.svelte.ts cases into a
   single rule: append each candidate extension to the FULL filename, not
   to the stripped stem. This subsumes:

     bare path:           foo           → foo.ts
     Svelte rune file:    foo.svelte    → foo.svelte.ts
     multi-dot helper:    foo.shared    → foo.shared.ts
     ambient declaration: foo.d         → foo.d.ts

   No behaviour change for paths that DO exist (.is_file() short-circuit)
   or for the .js→.ts / .jsx→.tsx convention (handled before the append
   loop so we don't accidentally match foo.js → foo.js.ts when foo.ts
   is the real file).

2. Rename _resolve_with_extensions → _resolve_js_module_path

   The function is JS/TS/Svelte-specific (Vite resolver order, mirrors the
   convention used by _import_js, _JS_CONFIG, _TS_CONFIG). The original
   name suggested it was a generic path utility. Renamed to make scope
   explicit and align with the existing _import_js / _JS_CONFIG naming
   pattern. Constants renamed to match: _JS_RESOLVE_EXTS, _JS_INDEX_FILES.

Tests
-----
4 new tests in tests/test_import_extension_resolution.py:

  - test_resolve_multi_dot_helper_file: foo.shared → foo.shared.ts
  - test_resolve_multi_dot_with_explicit_extension_still_works:
    foo.shared.ts (explicit) still wins
  - test_resolve_ambient_d_ts_via_bare_path: foo.d → foo.d.ts
  - test_end_to_end_multi_dot_import_resolves: tree-sitter pipeline
    sanity check via extract_js

Existing 28 tests updated for the rename. 32/32 pass; 7 pre-existing
unrelated failures elsewhere in the suite.

Validation
----------
On a 1,873-file SvelteKit codebase, applying both rules over the v0.7.5
baseline:

  baseline:                 12,096 edges
  with the resolver fix:    20,151 edges  (+8,055 = +67%)

The +2,652 over the previous version of this branch is attributable
entirely to multi-dot filename recovery, primarily test helper imports
('*.integration.ts', '*.triggers.ts'), domain-shared modules
('*.shared.ts'), and config files.
2026-05-04 22:41:50 +02:00
Christian Winther 0267cd789f test(extract): exhaustive coverage for extension resolution edge cases
Adds 8 tests covering import shapes that came up during real-codebase
validation against a 1,873-file SvelteKit project:

  - test_type_only_import_with_bare_path_resolves
      `import type { X } from './foo'` — type-only imports must go
      through the same resolver. Common pattern in TS codebases.

  - test_named_imports_emit_symbol_edges_after_resolution
      `import { foo, bar } from './module'` — verifies the per-symbol
      `imports` edges (file → module.foo, file → module.bar) target the
      correct stem after resolution. The symbol target_stem comes from
      _file_stem(resolved), so resolution must happen first.

  - test_alias_directory_import_resolves_to_index_ts
      `from '$lib/queue'` — alias + directory composes correctly.

  - test_resolve_does_not_match_partial_directory_name
      Regression guard: `from './foo'` where only `foo-extra.ts` exists
      must NOT accidentally resolve to it.

  - test_resolve_directory_without_index_returns_unchanged
      A directory with no index.* must fall through, not pick a random
      .ts inside.

  - test_resolve_handles_subpath_into_directory_with_index
      `./foo/sub` where `./foo/sub/index.ts` exists.

  - test_resolve_does_not_treat_dotfile_as_extension
      Path('.env-types.ts').suffix is '.ts' (correct), but worth pinning.

  - test_resolve_chain_alias_and_extension_compose
      Two-layer resolution: alias → bare path → .svelte.ts. Verifies
      the full chain works end-to-end for the Svelte 5 rune-file case.

Also expanded test_named_imports_emit_symbol_edges_after_resolution to
catch a subtle regression class: per-symbol import edges (line 319-340
in _import_js) build their target id from _file_stem(resolved). If
resolution fails or returns the wrong path, the symbol edges silently
target a different stem and downstream "where is X used?" queries miss
real callers.
2026-05-04 22:33:29 +02:00
Christian Winther 2b1efe8f08 fix(extract): TS bare-path / .svelte.ts / index.ts import resolution
_import_js previously only rewrote .js→.ts and .jsx→.tsx, leaving every
other common TypeScript / SvelteKit / Vite import shape unresolved. The
resulting node id wouldn't match the target file's own _make_id, so
build_from_json dropped the edge as external.

Three missed shapes:

  1. Bare paths (no extension) — TS convention:
     `import { foo } from './foo'`            → real file is foo.ts
  2. .svelte → .svelte.ts (Svelte 5 rune-only files):
     `import { x } from './x.svelte'`         → real file is x.svelte.ts
  3. Directory imports / barrel index files:
     `import { x } from './queue'`            → real file is queue/index.ts

Fix
---
New helper _resolve_with_extensions(p: Path) -> Path mirrors Vite/TS
resolver order:

  1. exact path (file)
  2. .js→.ts, .jsx→.tsx (existing TS-ESM convention)
  3. bare path → .ts/.tsx/.svelte/.js/.jsx/.mjs
  4. bare path → directory's index.{ts,tsx,js,jsx}
  5. .svelte → .svelte.ts (Svelte 5 rune file)

Falls back to the original path on no match — preserves pre-fix behaviour
for genuinely external modules (build_from_json drops them as phantoms).

Wired into _import_js (relative + alias branches) and extract_svelte's
regex pass for dynamic_import so static and dynamic imports both benefit.

Subtle: uses .is_file() / .is_dir() rather than .exists(). When the
import is a directory, .exists() returns True and would short-circuit
before the index.ts lookup ever ran.

Tests
-----
20 new tests in tests/test_import_extension_resolution.py:

  Resolver unit tests (12):
    - existing path returned unchanged
    - bare path → .ts / .tsx / .svelte
    - .ts wins over .svelte for ambiguous bare paths (Vite order)
    - directory → index.ts
    - directory prefers index.ts over index.js
    - .svelte → .svelte.ts (Svelte 5 rune file)
    - .js → .ts (TS ESM convention)
    - .jsx → .tsx
    - real .js stays .js when .ts doesn't exist
    - unresolvable returns input unchanged

  End-to-end (8):
    - bare-path import resolves in TS file
    - directory import resolves to index.ts
    - .svelte import resolves to .svelte.ts rune file
    - explicit .ts/.svelte imports still work (regression guard)
    - external module specifiers unchanged
    - alias + bare path resolves
    - dynamic_import bare path resolves
2026-05-04 22:26:48 +02:00
Safi ee85bbfbfd fix antigravity install paths .agents → .agent 2026-05-04 19:00:35 +01:00
Safi 5b33e6d2e6 remove dedup architecture diagram 2026-05-04 18:51:59 +01:00
SafiandClaude Sonnet 4.6 579e1cc744 wire --dedup-llm through build pipeline and fix fresh-extract dedup bypass
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 18:51:14 +01:00
Safi 913feca6a6 CI: add v5-v7 branches, workflow_dispatch trigger, sql extra 2026-05-04 18:27:33 +01:00
Safi 4f08e23807 Update README: add graphify extract to command reference, fix CI badge branch 2026-05-04 18:26:17 +01:00
Safi b3c99ec0ed Fix hook rebuild losing community labels; fix gemini platform install (#705, #706) 2026-05-04 18:20:16 +01:00
Safi 682d124618 bump version to 0.7.5 2026-05-04 18:07:48 +01:00
Safi 239000d2c9 Add incremental updates to graphify extract: semantic cache + build_merge + manifest 2026-05-04 18:07:02 +01:00
Safi ec413d5233 Wire deduplicate_entities into build() and build_merge() 2026-05-04 18:02:38 +01:00
Safi 34380434c4 Add graphify/dedup.py: entropy gate + MinHash/LSH + Jaro-Winkler entity deduplication 2026-05-04 18:01:11 +01:00
Safi b26467a8eb Add datasketch and rapidfuzz as base dependencies 2026-05-04 17:51:46 +01:00
Safi b5e7cf3f55 Add implementation plan: incremental updates + entity deduplication 2026-05-04 16:30:36 +01:00
Safi 5ee4b01406 Add design spec: incremental updates + entity deduplication 2026-05-04 16:25:58 +01:00
imfarhanm cddf9cf9bf docs: add fork install instructions and feature comparison to README 2026-05-04 20:04:23 +05:30
imfarhanm 09b33b795b fix: include .md/.mdx document files in graphify update rebuild path 2026-05-04 20:01:20 +05:30
Farhan M 68081c1c89 feat(extract): add Markdown structural extraction + sync collect_files extensions
1. NEW: extract_markdown() — structurally indexes .md/.mdx files into the
   knowledge graph. Headings become nodes, code blocks become nodes with
   language tags, and nesting produces 'contains' edges. Zero new deps
   (pure regex/line-by-line parsing, no tree-sitter needed).

2. FIX: collect_files() _EXTENSIONS was hardcoded and missing 18 extensions
   that _DISPATCH already supported (.jsx, .mjs, .ex, .exs, .jl, .vue,
   .svelte, .dart, .v, .sv, .sql, .f, .F, .f90, etc). Now uses
   set(_DISPATCH.keys()) to stay automatically in sync.

3. Added deploy_guide.md test fixture and 6 new test cases.
4. Updated test_collect_files_from_dir to use dynamic extension set.
2026-05-04 19:08:50 +05:30
Safi 6c3ccdc77b Fix #703: unify community counts in GRAPH_REPORT.md header and body 2026-05-04 13:59:27 +01:00
Safi 26a5a35200 bump version to 0.7.4 2026-05-04 12:40:43 +01:00
SafiandClaude Opus 4.7 741ac3655b Fix #700 #701: JSONC tsconfig parsing + Svelte dynamic import edge IDs
#700: _read_tsconfig_aliases() now handles // comments, /* */ block comments,
and trailing commas via a regex-based _strip_jsonc() helper. Tries plain
json.loads first, falls back to stripped parse, warns to stderr on failure
instead of silently returning {}.

#701 Bug A: removed startswith('.') filter from Svelte regex fallback so
aliased imports ($lib/, $partials/, @/) are no longer skipped.
#701 Bug B: fixed synthetic node IDs — source uses _make_id(str(path)),
target uses _make_id(str(normpath(parent/raw))) matching _extract_generic
and _import_js conventions so build_from_json no longer drops every edge.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 12:39:07 +01:00
Safi c1a7e250b6 bump version to 0.7.3 2026-05-04 11:46:39 +01:00
Safi c121fc4e42 README: clarify semantic extraction uses IDE model via skill, or Anthropic/Kimi for headless extract 2026-05-04 11:42:58 +01:00
Safi 6e84b42320 Clarify README: semantic extraction supports Anthropic and Kimi only (not OpenAI) 2026-05-04 11:41:40 +01:00
SafiandClaude Opus 4.7 d40e27463d Add graphify extract subcommand for headless semantic extraction (#698)
Enables docs-only corpora to run full LLM extraction in CI without Claude Code.
Handles code-only, docs-only, and mixed corpora; --no-cluster for raw dumps.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 11:31:54 +01:00
SafiandClaude Sonnet 4.6 b6ffdbb8dd v0.7.2: Fortran support + export CLI subcommands + skill.md size reduction
- Add Fortran support (26th language): .f/.F/.f90/.F90/.f95/.F95/.f03/.F03/.f08/.F08
  via tree-sitter-fortran; capital-F files preprocessed with cpp -w -P
- Add graphify export {html,obsidian,wiki,svg,graphml,neo4j} CLI subcommands
- Add graphify query/path/explain CLI subcommands
- Reduce skill.md from 63KB to 47KB by replacing Python heredocs with CLI calls
- Extend to_html() with node_limit param for auto-aggregation on large graphs
- Add integration tests for all export/query/path/explain subcommands

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-04 11:17:06 +01:00
37 changed files with 5434 additions and 545 deletions

No files matched your search

+4 -3
View File
@@ -2,9 +2,10 @@ name: CI
on:
push:
branches: ["v1", "v2", "v3", "v4", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
pull_request:
branches: ["v1", "v2", "v3", "v4", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "main"]
workflow_dispatch:
jobs:
test:
@@ -23,7 +24,7 @@ jobs:
- name: Install dependencies
run: |
pip install -e ".[mcp,pdf,watch]"
pip install -e ".[mcp,pdf,watch,sql]"
pip install pytest
- name: Run tests
+79
View File
@@ -2,6 +2,85 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.7.8 (2026-05-06)
- Feat: Gemini and OpenAI backends -- `graphify extract ./docs --backend gemini` (GEMINI_API_KEY / GOOGLE_API_KEY) or `--backend openai` (OPENAI_API_KEY); `[gemini]` and `[openai]` extras added (#735)
- Feat: Groovy and Spock support -- `.groovy` and `.gradle` extracted via tree-sitter-groovy; Spock spec files (`def "feature"()` syntax) handled via regex fallback (#732)
- Feat: Luau support -- `.luau` (Roblox Luau) added to code extraction using the Lua tree-sitter parser (#745)
- Feat: Markdown structural extraction -- headings, fenced code blocks, and nesting hierarchy extracted as graph nodes from `.md` and `.mdx` files with zero new dependencies (#711)
- Fix: `collect_files()` extension set now auto-syncs with `_DISPATCH` -- previously 18 extensions (`.sql`, `.vue`, `.svelte`, `.jsx`, `.ex`, `.jl`, etc.) were silently skipped in skill-mode extraction (#711)
- Fix: `detect_incremental` now forwards `follow_symlinks` to `detect()` -- symlinked subtrees no longer vanish on `--update` runs (#736)
- Fix: TS bare-path / `.svelte.ts` / `.svelte.js` / `index.ts` directory / multi-dot imports now resolve correctly -- previously these produced phantom edges dropped at merge time (#717, #716)
- Fix: `cluster-only` now loads and saves `.graphify_labels.json` -- human-readable community labels survive re-clustering instead of resetting to "Community N" (#744)
- Fix: `graphify export wiki` now fails fast with exit 1 if `.graphify_analysis.json` is missing -- prevents silent deletion of existing wiki articles (#746)
- Fix: `to_wiki()` now raises before the cleanup loop when `communities` is empty -- second safety layer against wiki data loss (#746)
- Fix: Ollama import error message now says "Ollama" not "Kimi" and points to `pip install openai`; `[ollama]` extras group added (#750)
- Security: hooks.py path execution now validates scripts are within the repo root -- closes supply-chain attack vector where a malicious commit could redirect hook execution (#747)
## 0.7.7 (2026-05-05)
- Feat: Ollama backend for headless extraction -- `graphify extract ./docs --backend ollama`; auto-detected when `OLLAMA_BASE_URL` is set; defaults to `qwen2.5-coder:7b`; zero cost ($0.00); sentinel API key handles OpenAI client auth requirement (#729)
- Feat: Cross-project global graph at `~/.graphify/global.json` -- `graphify global add/remove/list/path` to register multiple project graphs with `<repo>::<id>` prefixed node IDs, preventing silent collisions; hash-based skip avoids re-ingesting unchanged graphs (#729)
- Feat: `graphify extract --global --as <tag>` flag -- after building a project graph, auto-registers it into the global graph in one step (#729)
- Feat: `merge-graphs` now prefix-relabels each input graph before composing, preventing silent node ID collisions when two projects share entity names (#729)
- Fix: `deduplicate_entities` raises `ValueError` if called with nodes spanning multiple repos (cross-project dedup disabled by design -- per-project graphs are deduplicated in isolation) (#729)
- Fix: `detect_incremental()` now accepts and forwards `follow_symlinks` to `detect()`. Without this, `--update` runs silently miss any files reached through a symlinked sub-tree (e.g. `state_of_truth/` symlinking to a directory outside the corpus root), even when the original full run had detected them. Previously the flag was on `detect()` and `collect_files()` only. (#736)
## 0.7.6 (2026-05-05)
- Fix: `cluster-only` now accepts `--graph <path>` to specify a non-default graph.json location; positional path and flags can appear in any order (#724)
- Fix: `_is_sensitive()` no longer drops legitimate source files — word boundaries on the keyword pattern prevent false positives like `tokenizer.py`, `password_verification.py`, `SecretManager.java` (#718)
- Fix: `graphify extract --backend claude/kimi` raises default `max_tokens` from 8192 → 16384, eliminating the truncation-then-recursive-split cascade on dense doc corpora; respects `GRAPHIFY_MAX_OUTPUT_TOKENS` env var (#730)
- Fix: `--update` prune message now clearly distinguishes "N nodes pruned from M deleted files" from "M deletions detected but graph already clean — no drift" (#539)
- Fix: `extract_svelte()` stub nodes now carry the resolved import path as `source_file` instead of the importer's path, preventing metadata corruption after merge (#712)
- Fix: `extract_svelte()` now catches static `import X from './foo.svelte'` via a dedicated regex pass over `<script>` block content — previously tree-sitter's JS parser silently dropped all static imports in `.svelte` files (#713)
- Fix: `graphify extract` (full rebuild path) now saves `manifest.json` on every successful run, not only on `--update`; prevents stale-manifest drift on subsequent incremental runs (#538)
- Fix: `graphify antigravity install` now writes to `.agent/` (no trailing s) matching Antigravity's actual config paths (#704)
- Fix: Pi skill YAML frontmatter description simplified to avoid "nested mappings" parse error on Pi startup (#737)
- Fix: `--dedup-llm` flag now correctly threads LLM backend through to `deduplicate_entities` in both fresh and incremental extract paths; fresh extract path now also runs dedup (previously called `build_from_json` directly, bypassing dedup entirely)
## 0.7.5 (2026-05-04)
- Feat: `graphify extract` now runs incrementally - auto-detects prior `manifest.json` and re-extracts only changed/new files; semantic results cached by content hash so unchanged docs cost zero LLM tokens on repeat runs (#698)
- Feat: Entity deduplication pipeline runs on every build - entropy gate + MinHash/LSH blocking + Jaro-Winkler verification + same-community boost collapses near-duplicate entities (typos, spacing, plurals) before clustering
- Feat: `--dedup-llm` flag for `graphify extract` - optional LLM tiebreaker for ambiguous entity pairs (~$0.01 for 10k-node graphs), off by default
- Fix: `graphify hook install` rebuild now preserves human-readable community labels from `.graphify_labels.json` instead of resetting to generic "Community N" names on every commit (#705)
- Fix: `graphify install --platform gemini` now works correctly (#706)
- Deps: `datasketch` and `rapidfuzz` added as base dependencies
## 0.7.4 (2026-05-04)
- Fix: `_read_tsconfig_aliases()` now parses JSONC — handles `//` line comments, `/* */` block comments, and trailing commas that every TypeScript framework starter generates; warns to stderr on parse failure instead of silently returning `{}` (#700)
- Fix: `extract_svelte()` regex fallback now captures aliased dynamic imports (`$lib/...`, `$partials/...`, `@/...`) and uses correct `_make_id(str(path))` scheme so edges survive into `graph.json` instead of being dropped as phantom nodes (#701)
## 0.7.3 (2026-05-04)
- Feat: `graphify extract <path>` — headless full-pipeline extraction for CI; runs AST extraction on code files and semantic LLM extraction on docs/papers/images without Claude Code in the loop; supports `--backend kimi|claude`, `--out DIR`, `--no-cluster`; auto-detects backend from `MOONSHOT_API_KEY` / `ANTHROPIC_API_KEY`; docs-only corpora (issue #698) work cleanly
- Fix: export/query/path/explain CLI subcommands added in 0.7.2 now ship with integration tests
- Fix: skill.md reduced from 63KB to 47KB by replacing Python heredocs with CLI calls (#696)
## 0.7.2 (2026-05-04)
- Feat: Fortran support - extracts modules, subroutines, functions, programs, `use` imports, and `call` edges from `.f`, `.F`, `.f90`, `.F90`, `.f95`, `.F95`, `.f03`, `.F03`, `.f08`, `.F08` files; names are lowercased for case-insensitive matching (#694)
## 0.7.1 (2026-05-04)
- Fix: Obsidian export - community labels with `.`, `&`, `(`, `)` now produce valid Obsidian tags; only `[a-zA-Z0-9_\-/]` characters survive, preventing broken Dataview queries (#690)
- Fix: `_load_tsconfig_aliases()` now follows tsconfig `extends` chains - SvelteKit, Nuxt, and NestJS path aliases defined in extended configs are no longer silently dropped (#691)
- Fix: `.svelte` files now get a regex pass over the template layer after JS AST extraction - `{#await import('./X.svelte')}` markup-level dynamic imports are captured as edges (#692)
- Fix: recursion limit raised to 10,000 at extract entry points (main process + each worker) with a `_safe_extract` wrapper that skips pathological files with a clear warning instead of crashing the whole run (#695)
## 0.7.0 (2026-05-03)
Multi-dev busy-repo support: four gaps that caused merge conflicts, stale graphs, and silent cache misses in team workflows.
- Feat: `graphify hook install` now also configures a git merge driver for `graphify-out/graph.json` — union-merges two graph.json files so git never produces conflict markers in the knowledge graph; writes `.gitattributes` and registers `graphify merge-driver` in `.git/config`
- Feat: `graphify merge-driver <base> <current> <other>` subcommand — takes two graph.json variants and writes their node/edge union back to `<current>`; always exits 0 so merge never blocks
- Feat: Leiden community detection now seeded (`seed=42` when supported) for deterministic community IDs across parallel rebuilds — reduces JSON diff churn in multi-dev repos
- Feat: `graph.json` now embeds `built_at_commit` (git HEAD) at write time; `GRAPH_REPORT.md` surfaces the commit hash and a freshness check hint
- Fix: `file_hash` is now content-only (path removed from hash) — renamed files reuse their cache entry instead of re-extracting; cached `source_file` fields are updated to the new path on load
- Fix: watch mode mixed-batch handling — commits with both code and non-code files now rebuild code immediately AND write `needs_update` flag; previously code changes were silently dropped in mixed batches
## 0.6.9 (2026-05-03)
- Fix: `source_file` path separators normalized to forward slashes at graph ingestion — same physical file emitted with backslashes (Windows AST extractor) and forward slashes (semantic subagents) now merges into one node instead of splitting into two disconnected components (#683)
+19 -4
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=v4" 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://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
@@ -124,7 +124,7 @@ Uninstall with the matching command (e.g. `graphify claude uninstall`).
| Type | Extensions |
|------|-----------|
| Code (25 languages) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .jl .vue .svelte .sql` |
| Code (28 languages) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .jl .vue .svelte .groovy .gradle .sql .f .F .f90 .F90 .f95 .F95 .f03 .F03 .f08 .F08` |
| Docs | `.md .mdx .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (requires `pip install graphifyy[office]`) |
| PDFs | `.pdf` |
@@ -192,7 +192,7 @@ graphify-out/cost.json # local only
**Workflow:**
1. One person runs `/graphify .` and commits `graphify-out/`.
2. Everyone pulls — their assistant reads the graph immediately.
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost).
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost). This also sets up a git merge driver so `graph.json` is never left with conflict markers — two devs committing in parallel get their graphs union-merged automatically.
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
---
@@ -221,7 +221,7 @@ The MCP server gives your assistant structured access: `query_graph`, `get_node`
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine.
- **Video / audio** — transcribed locally with faster-whisper. Nothing leaves your machine.
- **Docs, PDFs, images** — sent to your AI assistant's model API (Anthropic, OpenAI, etc.) using your own API key.
- **Docs, PDFs, images** — sent to your AI assistant for semantic extraction (via the `/graphify` skill, using whatever model your IDE session runs). Headless `graphify extract` requires `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), or a running Ollama instance (`OLLAMA_BASE_URL`). The `--dedup-llm` flag uses the same key.
- No telemetry, no usage tracking, no analytics.
---
@@ -273,12 +273,27 @@ graphify hermes install / uninstall
graphify kiro install / uninstall
graphify antigravity install / uninstall
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, or ollama
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL)
graphify extract ./docs --no-cluster # raw extraction only, skip clustering
graphify extract ./docs --dedup-llm # LLM tiebreaker for ambiguous entity pairs (uses same API key)
graphify extract ./docs --global --as myrepo # extract and register into the cross-project global graph
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # raise output cap for dense corpora
graphify global add graphify-out/graph.json myrepo # register a project graph into ~/.graphify/global.json
graphify global remove myrepo # remove a project from the global graph
graphify global list # show all registered repos + node/edge counts
graphify global path # print path to the global graph file
graphify clone https://github.com/karpathy/nanoGPT
graphify merge-graphs a.json b.json --out merged.json
graphify watch ./src
graphify check-update ./src
graphify update ./src
graphify cluster-only ./my-project
graphify cluster-only ./my-project --graph path/to/graph.json # custom graph location
```
---
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,133 @@
# Design: Incremental Updates + Entity Deduplication
**Date:** 2026-05-04
**Issues:** #698 (incremental updates), entity deduplication (no issue, proactive)
**Branch:** v7
---
## Problem
1. `graphify extract` rebuilds the full graph from scratch every run — re-sends all files to the LLM regardless of what changed. For a 1000-file Markdown corpus updated daily this is expensive.
2. LLM extraction is chunk-by-chunk — the same real-world concept can get different labels across chunks (`AuthManager`, `AuthenticationManager`, `auth_mgr`). No semantic dedup exists beyond exact string normalization.
---
## Pipeline (every `graphify extract` run)
```
detect (full or incremental, auto-detected)
↓
AST extract (code files, AST cache-aware)
↓
Semantic LLM extract (doc/paper/image files, semantic cache-aware)
↓
build_merge (merge into existing graph, prune deleted nodes)
↓
deduplicate_entities (normalize → entropy gate → MinHash/LSH → Jaro-Winkler → community boost → optional LLM)
↓
cluster (full graph, always re-run)
↓
score_all + god_nodes + surprising_connections
↓
write graph.json + .graphify_analysis.json + manifest.json
```
---
## Feature 1: Incremental Updates
### Auto-detection
If `graphify-out/manifest.json` + `graphify-out/graph.json` both exist → incremental mode. No flag needed. First run is always full.
### Incremental mode changes
- `detect_incremental(target)` instead of `detect(target)` — returns `new_files`, `unchanged_files`, `deleted_files`
- Only `new_files` go through AST + LLM extraction
- `build_merge(new_chunks, prune_sources=deleted_files)` instead of `build_from_json` — merges into existing graph, prunes nodes from deleted files
- `manifest.json` written only on successful completion (crash mid-run does not corrupt next run's diff)
### Semantic cache (both full and incremental mode)
- Before LLM call: `check_semantic_cache(files)` splits into `(cached_results, uncached_files)`
- Only `uncached_files` sent to `extract_corpus_parallel`
- After LLM call: `save_semantic_cache(fresh_results)` — keyed by content hash
- On file rename: `source_file` updated to new path in cached result (same pattern as existing AST cache)
### Output summary
```
[graphify extract] incremental: 20 changed, 980 cached, 2 deleted
[graphify extract] graph: 4,821 nodes, 12,304 edges, 43 communities
[graphify extract] tokens: 18,432 in / 6,201 out, est. cost: $0.08
```
### Files changed
- `graphify/__main__.py` — `elif cmd == "extract":` block only (~5 targeted changes)
---
## Feature 2: Entity Deduplication
### New module: `graphify/dedup.py`
Single responsibility. Called from `build.py` after graph construction. Returns deduplicated `(nodes, edges)`.
### Pipeline
**Step 1 — Exact normalization**
Wire up the dormant `deduplicate_by_label` in `build.py`. Catches case/punctuation variants across files. Free win, already written.
**Step 2 — Entropy gate**
Skip fuzzy matching on labels with < 2.5 bits/char entropy. Short ambiguous names (`"AI"`, `"DB"`, `"x"`) are too risky to auto-merge. Only high-entropy labels proceed to steps 3-4.
**Step 3 — MinHash + LSH blocking** (`datasketch`)
3-gram shingles, 128 permutations, threshold 0.7. Generates candidate pairs in O(n) instead of O(n²). Sub-second at 10k nodes.
**Step 4 — Jaro-Winkler verification** (`rapidfuzz`)
Each candidate pair verified at ≥ 0.92. Catches typos, plurals, spacing variants. Pairs below threshold discarded.
**Step 5 — Same-community boost**
Pairs where both nodes share a Leiden community ID get +0.05 score bonus. Graphify-specific advantage — community structure is a strong signal that GraphRAG/LightRAG don't exploit.
**Step 6 — Union-find merge**
Confirmed pairs fed into union-find → connected components → each component merged into one node. Edges rewired to survivor. Self-loops dropped. Prefer shorter non-chunk-suffixed IDs as survivor.
**Step 7 — Optional LLM tiebreaker** (`--dedup-llm` flag)
Ambiguous pairs (score 0.75–0.85) batched in groups of 30, one LLM call per batch. ~$0.01 total for 10k nodes. Off by default.
### Integration point
Dedup runs after `build_merge` / `build_from_json`, before `cluster`. Order matters: cleaner graph → better community detection.
```python
# in build.py
G = build_merge(...) # or build_from_json
G = deduplicate_entities(G) # new step
communities = cluster(G) # unchanged
```
### New dependencies
- `datasketch` — always required (added to `[project.dependencies]`)
- `rapidfuzz` — always required (added to `[project.dependencies]`)
- No `sentence-transformers` / PyTorch dependency
### Files changed
- `graphify/dedup.py` — new module, full pipeline
- `graphify/build.py` — call `deduplicate_entities` after graph construction; wire dormant `deduplicate_by_label`
- `graphify/__main__.py` — add `--dedup-llm` flag parsing in extract block
- `pyproject.toml` — add `datasketch`, `rapidfuzz` to base dependencies
---
## Testing
- Unit tests for each dedup step in isolation (`tests/test_dedup.py`)
- Integration test: two chunks with overlapping entity labels → single merged node in output graph
- Incremental test: run extract twice, assert second run makes zero LLM calls for unchanged files
- Rename test: rename a file, assert cache hit and `source_file` updated correctly
- Delete test: delete a file, assert its nodes are pruned from graph
---
## Non-goals
- `--dedup embed` (MiniLM cosine) — explicitly excluded, no PyTorch dependency
- Incremental support for `graphify update` (AST-only) — already handled by existing AST cache
- Dedup across different graph.json files (merge two graphs) — separate feature
+660 -18
View File
@@ -135,7 +135,7 @@ _PLATFORM_CONFIG: dict[str, dict] = {
},
"antigravity": {
"skill_file": "skill.md",
"skill_dst": Path(".agents") / "skills" / "graphify" / "SKILL.md",
"skill_dst": Path.home() / ".agent" / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"windows": {
@@ -447,8 +447,8 @@ def vscode_uninstall(project_dir: Path | None = None) -> None:
print(f" {instructions} -> deleted (was empty after removal)")
_ANTIGRAVITY_RULES_PATH = Path(".agents") / "rules" / "graphify.md"
_ANTIGRAVITY_WORKFLOW_PATH = Path(".agents") / "workflows" / "graphify.md"
_ANTIGRAVITY_RULES_PATH = Path(".agent") / "rules" / "graphify.md"
_ANTIGRAVITY_WORKFLOW_PATH = Path(".agent") / "workflows" / "graphify.md"
_ANTIGRAVITY_RULES = """\
## graphify
@@ -471,7 +471,7 @@ description: Turn any folder of files into a navigable knowledge graph
# Workflow: graphify
Follow the graphify skill installed at ~/.agents/skills/graphify/SKILL.md to run the full pipeline.
Follow the graphify skill installed at ~/.agent/skills/graphify/SKILL.md to run the full pipeline.
If no path argument is given, use `.` (current directory).
"""
@@ -1060,6 +1060,7 @@ def main() -> None:
print(" explain \"X\" plain-language explanation of a node and its neighbors")
print(" --graph <path> path to graph.json (default graphify-out/graph.json)")
print(" clone <github-url> clone a GitHub repo locally and print its path for /graphify")
print(" merge-driver <base> <current> <other> git merge driver: union-merge two graph.json files (set up via hook install)")
print(" merge-graphs <g1> <g2> merge two or more graph.json files into one cross-repo graph")
print(" --out <path> output path (default: graphify-out/merged-graph.json)")
print(" --branch <branch> checkout a specific branch (default: repo default)")
@@ -1074,6 +1075,7 @@ def main() -> None:
print(" (also: GRAPHIFY_FORCE=1 env var; use after refactors that delete code)")
print(" cluster-only <path> rerun clustering on an existing graph.json and regenerate report")
print(" --no-viz skip graph.html generation (useful for >5000 node graphs / CI)")
print(" --graph <path> path to graph.json (default <path>/graphify-out/graph.json)")
print(" query \"<question>\" BFS traversal of graph.json for a question")
print(" --dfs use depth-first instead of breadth-first")
print(" --context C explicit edge-context filter (repeatable)")
@@ -1093,6 +1095,18 @@ def main() -> None:
print(" --max-children N cap children per node (default 200)")
print(" --top-k-edges N per-symbol outbound edges in inspector (default 12)")
print(" --label NAME project label in header")
print(" extract <path> headless full extraction (AST + semantic LLM) for CI/scripts")
print(" --backend B gemini|kimi|claude|openai|ollama (default: whichever API key is set)")
print(" --model M override backend default model")
print(" --out DIR output dir (default: <path>); writes <DIR>/graphify-out/")
print(" --no-cluster skip clustering, write raw extraction only")
print(" --global also merge the resulting graph into the global graph")
print(" --as <tag> repo tag for --global (default: target directory name)")
print(" global add <graph.json> add/update a project graph in the global graph (~/.graphify/global-graph.json)")
print(" --as <tag> repo tag (default: parent directory name)")
print(" global remove <tag> remove a repo's nodes from the global graph")
print(" global list list repos in the global graph")
print(" global path print path to the global graph file")
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
print(" hook uninstall remove git hooks")
@@ -1121,8 +1135,8 @@ def main() -> None:
print(" trae uninstall remove graphify section from AGENTS.md")
print(" trae-cn install write graphify section to AGENTS.md (Trae CN)")
print(" trae-cn uninstall remove graphify section from AGENTS.md")
print(" antigravity install write .agents/rules + .agents/workflows + skill (Google Antigravity)")
print(" antigravity uninstall remove .agents/rules, .agents/workflows, and skill")
print(" antigravity install write .agent/rules + .agent/workflows + skill (Google Antigravity)")
print(" antigravity uninstall remove .agent/rules, .agent/workflows, and skill")
print(" hermes install write skill to ~/.hermes/skills/graphify/ (Hermes)")
print(" hermes uninstall remove skill from ~/.hermes/skills/graphify/")
print(" kiro install write skill to .kiro/skills/graphify/ + steering file (Kiro IDE/CLI)")
@@ -1489,11 +1503,30 @@ def main() -> None:
sys.exit(1)
elif cmd == "cluster-only":
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
# Mirror the tree/export arg-parsing pattern: walk argv so flags and
# the optional positional path can appear in any order (#724).
no_viz = "--no-viz" in sys.argv
_min_cs_arg = next((a for a in sys.argv if a.startswith("--min-community-size=")), None)
min_community_size = int(_min_cs_arg.split("=")[1]) if _min_cs_arg else 3
graph_json = watch_path / "graphify-out" / "graph.json"
args = sys.argv[2:]
watch_path: Path | None = None
graph_override: Path | None = None
i_arg = 0
while i_arg < len(args):
a = args[i_arg]
if a == "--graph" and i_arg + 1 < len(args):
graph_override = Path(args[i_arg + 1]); i_arg += 2
elif a == "--no-viz" or a.startswith("--min-community-size="):
i_arg += 1
elif a.startswith("--"):
i_arg += 1
elif watch_path is None:
watch_path = Path(a); i_arg += 1
else:
i_arg += 1
if watch_path is None:
watch_path = Path(".")
graph_json = graph_override if graph_override is not None else watch_path / "graphify-out" / "graph.json"
if not graph_json.exists():
print(f"error: no graph found at {graph_json} — run /graphify first", file=sys.stderr)
sys.exit(1)
@@ -1513,16 +1546,26 @@ def main() -> None:
cohesion = score_all(G, communities)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: f"Community {cid}" for cid in communities}
out = watch_path / "graphify-out"
labels_path = out / ".graphify_labels.json"
if labels_path.exists():
try:
labels = {int(k): v for k, v in json.loads(labels_path.read_text(encoding="utf-8")).items()}
except Exception:
labels = {cid: f"Community {cid}" for cid in communities}
else:
labels = {cid: f"Community {cid}" for cid in communities}
questions = suggest_questions(G, communities, labels)
tokens = {"input": 0, "output": 0}
from graphify.export import _git_head as _gh
_commit = _gh()
report = generate(G, communities, cohesion, labels, gods, surprises,
{"warning": "cluster-only mode — file stats not available"},
tokens, str(watch_path), suggested_questions=questions,
min_community_size=min_community_size)
out = watch_path / "graphify-out"
min_community_size=min_community_size, built_at_commit=_commit)
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
to_json(G, communities, str(out / "graph.json"))
labels_path.write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
# Mirror watch.py pattern: gate to_html so core outputs (graph.json +
# GRAPH_REPORT.md) always land. Honor --no-viz explicitly; otherwise
@@ -1566,8 +1609,13 @@ def main() -> None:
ok = _rebuild_code(watch_path, force=force)
if ok:
print("Code graph updated. For doc/paper/image changes run /graphify --update in your AI assistant.")
if not os.environ.get("MOONSHOT_API_KEY") and not os.environ.get("GRAPHIFY_NO_TIPS"):
print("Tip: set MOONSHOT_API_KEY to use Kimi K2.6 for semantic extraction — 3x cheaper, richer graphs. pip install 'graphifyy[kimi]'")
if not (
os.environ.get("GEMINI_API_KEY")
or os.environ.get("GOOGLE_API_KEY")
or os.environ.get("MOONSHOT_API_KEY")
or os.environ.get("GRAPHIFY_NO_TIPS")
):
print("Tip: set GEMINI_API_KEY or GOOGLE_API_KEY to use Gemini for semantic extraction.")
else:
print("Nothing to update or rebuild failed — check output above.", file=sys.stderr)
sys.exit(1)
@@ -1640,6 +1688,37 @@ def main() -> None:
print(f"open with: xdg-open {out} (or file://{out.resolve()})")
sys.exit(0)
elif cmd == "merge-driver":
# git merge driver for graph.json — takes (base, current, other) and writes
# the union of current+other nodes/edges back to current. Always exits 0
# so git never marks graph.json as conflicted.
# Usage: graphify merge-driver %O %A %B (set in .git/config merge driver)
if len(sys.argv) < 5:
print("Usage: graphify merge-driver <base> <current> <other>", file=sys.stderr)
sys.exit(1)
_base_path, _current_path, _other_path = sys.argv[2], sys.argv[3], sys.argv[4]
import networkx as _nx
from networkx.readwrite import json_graph as _jg
def _load_graph(p: str):
data = json.loads(Path(p).read_text(encoding="utf-8"))
try:
return _jg.node_link_graph(data, edges="links"), data
except TypeError:
return _jg.node_link_graph(data), data
try:
G_cur, _ = _load_graph(_current_path)
G_oth, _ = _load_graph(_other_path)
except Exception as exc:
print(f"[graphify merge-driver] error loading graphs: {exc}", file=sys.stderr)
sys.exit(0) # exit 0 so git doesn't block the merge
merged = _nx.compose(G_cur, G_oth)
try:
out_data = _jg.node_link_data(merged, edges="links")
except TypeError:
out_data = _jg.node_link_data(merged)
Path(_current_path).write_text(json.dumps(out_data, indent=2), encoding="utf-8")
sys.exit(0)
elif cmd == "merge-graphs":
# graphify merge-graphs graph1.json graph2.json ... --out merged.json
args = sys.argv[2:]
@@ -1656,22 +1735,27 @@ def main() -> None:
sys.exit(1)
import networkx as _nx
from networkx.readwrite import json_graph as _jg
from graphify.build import prefix_graph_for_global as _prefix
graphs = []
for gp in graph_paths:
if not gp.exists():
print(f"error: not found: {gp}", file=sys.stderr)
sys.exit(1)
data = json.loads(gp.read_text(encoding="utf-8"))
# Normalize edges/links key before loading — graphify writes "links"
# via node_link_data but older runs may have used "edges" (#738).
if "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
try:
G = _jg.node_link_graph(data, edges="links")
except TypeError:
G = _jg.node_link_graph(data)
# Tag every node with which repo it came from
repo_tag = gp.parent.parent.name # graphify-out/../ → repo dir name
for node in G.nodes:
G.nodes[node].setdefault("repo", repo_tag)
graphs.append(G)
merged = _nx.compose_all(graphs)
merged = _nx.Graph()
for G, gp in zip(graphs, graph_paths):
repo_tag = gp.parent.parent.name # graphify-out/../ → repo dir name
prefixed = _prefix(G, repo_tag)
merged = _nx.compose(merged, prefixed)
try:
out_data = _jg.node_link_data(merged, edges="links")
except TypeError:
@@ -1700,6 +1784,147 @@ def main() -> None:
local_path = _clone_repo(url, branch=branch, out_dir=out_dir)
print(local_path)
elif cmd == "export":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd not in ("html", "obsidian", "wiki", "svg", "graphml", "neo4j"):
print("Usage: graphify export <format>", file=sys.stderr)
print(" html [--graph PATH] [--labels PATH] [--node-limit N] [--no-viz]", file=sys.stderr)
print(" obsidian [--graph PATH] [--labels PATH] [--dir PATH]", file=sys.stderr)
print(" wiki [--graph PATH] [--labels PATH]", file=sys.stderr)
print(" svg [--graph PATH] [--labels PATH]", file=sys.stderr)
print(" graphml [--graph PATH]", file=sys.stderr)
print(" neo4j [--graph PATH] [--push URI] [--user U] [--password P]", file=sys.stderr)
sys.exit(1)
# Parse shared args
args = sys.argv[3:]
graph_path = Path(_GRAPHIFY_OUT) / "graph.json"
labels_path = Path(_GRAPHIFY_OUT) / ".graphify_labels.json"
analysis_path = Path(_GRAPHIFY_OUT) / ".graphify_analysis.json"
node_limit = 5000
no_viz = False
obsidian_dir = Path(_GRAPHIFY_OUT) / "obsidian"
neo4j_uri: str | None = None
neo4j_user = "neo4j"
neo4j_password: str | None = None
i = 0
while i < len(args):
a = args[i]
if a == "--graph" and i + 1 < len(args):
graph_path = Path(args[i + 1]); i += 2
elif a == "--labels" and i + 1 < len(args):
labels_path = Path(args[i + 1]); i += 2
elif a == "--node-limit" and i + 1 < len(args):
node_limit = int(args[i + 1]); i += 2
elif a == "--no-viz":
no_viz = True; i += 1
elif a == "--dir" and i + 1 < len(args):
obsidian_dir = Path(args[i + 1]); i += 2
elif a == "--push" and i + 1 < len(args):
neo4j_uri = args[i + 1]; i += 2
elif a == "--user" and i + 1 < len(args):
neo4j_user = args[i + 1]; i += 2
elif a == "--password" and i + 1 < len(args):
neo4j_password = args[i + 1]; i += 2
else:
i += 1
if not graph_path.exists():
print(f"error: graph not found: {graph_path}. Run /graphify <path> first.", file=sys.stderr)
sys.exit(1)
from networkx.readwrite import json_graph as _jg
from graphify.build import build_from_json as _bfj
_raw = json.loads(graph_path.read_text(encoding="utf-8"))
try:
G = _jg.node_link_graph(_raw, edges="links")
except TypeError:
G = _jg.node_link_graph(_raw)
# Load optional analysis/labels
communities: dict[int, list[str]] = {}
if analysis_path.exists():
_an = json.loads(analysis_path.read_text(encoding="utf-8"))
communities = {int(k): v for k, v in _an.get("communities", {}).items()}
cohesion: dict[int, float] = {int(k): v for k, v in _an.get("cohesion", {}).items()}
gods_data = _an.get("gods", [])
else:
cohesion = {}
gods_data = []
labels: dict[int, str] = {}
if labels_path.exists():
labels = {int(k): v for k, v in json.loads(labels_path.read_text(encoding="utf-8")).items()}
out_dir = graph_path.parent
if subcmd == "html":
from graphify.export import to_html as _to_html
if no_viz:
html_target = out_dir / "graph.html"
if html_target.exists():
html_target.unlink()
print("--no-viz: skipped graph.html")
else:
_to_html(G, communities, str(out_dir / "graph.html"),
community_labels=labels or None, node_limit=node_limit)
if G.number_of_nodes() <= node_limit:
print(f"graph.html written - open in any browser, no server needed")
elif subcmd == "obsidian":
from graphify.export import to_obsidian as _to_obsidian, to_canvas as _to_canvas
n = _to_obsidian(G, communities, str(obsidian_dir),
community_labels=labels or None, cohesion=cohesion or None)
print(f"Obsidian vault: {n} notes in {obsidian_dir}/")
_to_canvas(G, communities, str(obsidian_dir / "graph.canvas"),
community_labels=labels or None)
print(f"Canvas: {obsidian_dir}/graph.canvas")
print(f"Open {obsidian_dir}/ as a vault in Obsidian.")
elif subcmd == "wiki":
from graphify.wiki import to_wiki as _to_wiki
from graphify.analyze import god_nodes as _god_nodes
if not communities:
print(
"error: .graphify_analysis.json is missing or empty — refusing to export wiki to prevent data loss.\n"
"Run `graphify extract .` (or `graphify cluster-only .`) to regenerate community data first.",
file=sys.stderr,
)
sys.exit(1)
if not gods_data:
gods_data = _god_nodes(G)
n = _to_wiki(G, communities, str(out_dir / "wiki"),
community_labels=labels or None, cohesion=cohesion or None,
god_nodes_data=gods_data)
print(f"Wiki: {n} articles written to {out_dir}/wiki/")
print(f" {out_dir}/wiki/index.md -> agent entry point")
elif subcmd == "svg":
from graphify.export import to_svg as _to_svg
_to_svg(G, communities, str(out_dir / "graph.svg"),
community_labels=labels or None)
print(f"graph.svg written - embeds in Obsidian, Notion, GitHub READMEs")
elif subcmd == "graphml":
from graphify.export import to_graphml as _to_graphml
_to_graphml(G, communities, str(out_dir / "graph.graphml"))
print(f"graph.graphml written - open in Gephi, yEd, or any GraphML tool")
elif subcmd == "neo4j":
if neo4j_uri:
from graphify.export import push_to_neo4j as _push
if neo4j_password is None:
print("error: --password required for --push", file=sys.stderr)
sys.exit(1)
result = _push(G, uri=neo4j_uri, user=neo4j_user,
password=neo4j_password, communities=communities)
print(f"Pushed to Neo4j: {result['nodes']} nodes, {result['edges']} edges")
else:
from graphify.export import to_cypher as _to_cypher
_to_cypher(G, str(out_dir / "cypher.txt"))
print(f"cypher.txt written - import with: cypher-shell < {out_dir}/cypher.txt")
elif cmd == "benchmark":
from graphify.benchmark import run_benchmark, print_benchmark
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
@@ -1714,6 +1939,423 @@ def main() -> None:
pass
result = run_benchmark(graph_path, corpus_words=corpus_words)
print_benchmark(result)
elif cmd == "global":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
from graphify.global_graph import (
global_add as _global_add,
global_remove as _global_remove,
global_list as _global_list,
global_path as _global_path,
)
if subcmd == "add":
# graphify global add <graph.json> [--as <tag>]
args = sys.argv[3:]
source = None
tag = None
i = 0
while i < len(args):
if args[i] == "--as" and i + 1 < len(args):
tag = args[i + 1]; i += 2
elif not source:
source = Path(args[i]); i += 1
else:
i += 1
if not source:
print("Usage: graphify global add <graph.json> [--as <repo-tag>]", file=sys.stderr)
sys.exit(1)
tag = tag or source.parent.parent.name
try:
result = _global_add(source, tag)
if result["skipped"]:
print(f"'{tag}' unchanged since last add — global graph not modified.")
else:
print(f"Added '{tag}' to global graph: +{result['nodes_added']} nodes, "
f"-{result['nodes_removed']} pruned. Global: {_global_path()}")
except Exception as exc:
print(f"error: {exc}", file=sys.stderr); sys.exit(1)
elif subcmd == "remove":
tag = sys.argv[3] if len(sys.argv) > 3 else ""
if not tag:
print("Usage: graphify global remove <repo-tag>", file=sys.stderr); sys.exit(1)
try:
removed = _global_remove(tag)
print(f"Removed '{tag}' from global graph ({removed} nodes pruned).")
except KeyError as exc:
print(f"error: {exc}", file=sys.stderr); sys.exit(1)
elif subcmd == "list":
repos = _global_list()
if not repos:
print("Global graph is empty. Use 'graphify global add' to add a project.")
else:
print(f"Global graph: {_global_path()}")
for tag, info in repos.items():
print(f" {tag}: {info.get('node_count', '?')} nodes, added {info.get('added_at', '?')[:10]}")
elif subcmd == "path":
print(_global_path())
else:
print("Usage: graphify global [add|remove|list|path]", file=sys.stderr); sys.exit(1)
elif cmd == "extract":
# Headless full-pipeline extraction for CI / scripts (#698).
# Runs detect -> AST extraction on code -> semantic LLM extraction on
# docs/papers/images -> merge -> build -> cluster -> write outputs.
# Unlike the skill.md path (which runs through Claude Code subagents),
# this calls extract_corpus_parallel directly using whichever backend
# has an API key set.
if len(sys.argv) < 3:
print(
"Usage: graphify extract <path> [--backend gemini|kimi|claude|openai] "
"[--out DIR] [--no-cluster]",
file=sys.stderr,
)
sys.exit(1)
target = Path(sys.argv[2]).resolve()
if not target.exists():
print(f"error: path not found: {target}", file=sys.stderr)
sys.exit(1)
backend: str | None = None
model: str | None = None
out_dir: Path | None = None
no_cluster = False
dedup_llm = False
global_merge = False
global_repo_tag: str | None = None
args = sys.argv[3:]
i = 0
while i < len(args):
a = args[i]
if a == "--backend" and i + 1 < len(args):
backend = args[i + 1]; i += 2
elif a.startswith("--backend="):
backend = a.split("=", 1)[1]; i += 1
elif a == "--model" and i + 1 < len(args):
model = args[i + 1]; i += 2
elif a.startswith("--model="):
model = a.split("=", 1)[1]; i += 1
elif a == "--out" and i + 1 < len(args):
out_dir = Path(args[i + 1]); i += 2
elif a.startswith("--out="):
out_dir = Path(a.split("=", 1)[1]); i += 1
elif a == "--no-cluster":
no_cluster = True; i += 1
elif a == "--dedup-llm":
dedup_llm = True; i += 1
elif a == "--global":
global_merge = True; i += 1
elif a == "--as" and i + 1 < len(args):
global_repo_tag = args[i + 1]; i += 2
else:
i += 1
# Backend resolution. If user did not pass --backend, sniff env.
# If backend was explicitly requested, validate its key is present
# and surface a clear error early — don't let extract_corpus_parallel
# raise mid-run after we've spent time on AST extraction.
from graphify.llm import (
BACKENDS as _BACKENDS,
detect_backend as _detect_backend,
estimate_cost as _estimate_cost,
extract_corpus_parallel as _extract_corpus_parallel,
_format_backend_env_keys,
_get_backend_api_key,
)
if backend is None:
backend = _detect_backend()
if backend is None:
print(
"error: no LLM API key found. Set GEMINI_API_KEY or GOOGLE_API_KEY "
"(gemini), MOONSHOT_API_KEY (kimi), ANTHROPIC_API_KEY (claude), "
"or OPENAI_API_KEY (openai), or pass --backend.",
file=sys.stderr,
)
sys.exit(1)
if backend not in _BACKENDS:
print(
f"error: unknown backend '{backend}'. "
f"Available: {', '.join(sorted(_BACKENDS))}",
file=sys.stderr,
)
sys.exit(1)
if not _get_backend_api_key(backend):
print(
f"error: backend '{backend}' requires {_format_backend_env_keys(backend)} to be set.",
file=sys.stderr,
)
sys.exit(1)
# Resolve output dir. The user-facing contract is "<out>/graphify-out/"
# so a fresh checkout writes graphify-out/ at the project root, matching
# the skill.md pipeline.
out_root = (out_dir.resolve() if out_dir else target)
graphify_out = out_root / "graphify-out"
graphify_out.mkdir(parents=True, exist_ok=True)
from graphify.detect import (
detect as _detect,
detect_incremental as _detect_incremental,
save_manifest as _save_manifest,
)
manifest_path = graphify_out / "manifest.json"
existing_graph_path = graphify_out / "graph.json"
incremental_mode = manifest_path.exists() and existing_graph_path.exists()
if incremental_mode:
print(f"[graphify extract] incremental scan of {target}")
detection = _detect_incremental(target, manifest_path=str(manifest_path))
else:
print(f"[graphify extract] scanning {target}")
detection = _detect(target)
files_by_type = detection.get("files", {})
if incremental_mode:
new_by_type = detection.get("new_files", {})
code_files = [Path(p) for p in new_by_type.get("code", [])]
doc_files = [Path(p) for p in new_by_type.get("document", [])]
paper_files = [Path(p) for p in new_by_type.get("paper", [])]
image_files = [Path(p) for p in new_by_type.get("image", [])]
deleted_files = list(detection.get("deleted_files", []))
unchanged_total = sum(len(v) for v in detection.get("unchanged_files", {}).values())
else:
code_files = [Path(p) for p in files_by_type.get("code", [])]
doc_files = [Path(p) for p in files_by_type.get("document", [])]
paper_files = [Path(p) for p in files_by_type.get("paper", [])]
image_files = [Path(p) for p in files_by_type.get("image", [])]
deleted_files = []
unchanged_total = 0
semantic_files = doc_files + paper_files + image_files
if incremental_mode:
print(
f"[graphify extract] {len(code_files)} code, {len(doc_files)} docs, "
f"{len(paper_files)} papers, {len(image_files)} images changed; "
f"{unchanged_total} unchanged; {len(deleted_files)} deleted"
)
else:
print(
f"[graphify extract] found {len(code_files)} code, "
f"{len(doc_files)} docs, {len(paper_files)} papers, "
f"{len(image_files)} images"
)
# AST extraction on code files. Empty code list (docs-only corpus) is
# the issue #698 case — skip cleanly instead of crashing inside extract().
ast_result: dict = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
if code_files:
from graphify.extract import extract as _ast_extract
print(f"[graphify extract] AST extraction on {len(code_files)} code files...")
try:
ast_result = _ast_extract(code_files, cache_root=target)
except Exception as exc:
print(f"[graphify extract] AST extraction failed: {exc}", file=sys.stderr)
ast_result = {"nodes": [], "edges": [], "input_tokens": 0, "output_tokens": 0}
# Semantic extraction on docs/papers/images. Check cache first.
from graphify.cache import (
check_semantic_cache as _check_semantic_cache,
save_semantic_cache as _save_semantic_cache,
)
sem_result: dict = {
"nodes": [], "edges": [], "hyperedges": [],
"input_tokens": 0, "output_tokens": 0,
}
sem_cache_hits = 0
sem_cache_misses = 0
if semantic_files:
sem_paths_str = [str(p) for p in semantic_files]
cached_nodes, cached_edges, cached_hyperedges, uncached_paths = (
_check_semantic_cache(sem_paths_str, root=target)
)
sem_cache_hits = len(semantic_files) - len(uncached_paths)
sem_cache_misses = len(uncached_paths)
sem_result["nodes"].extend(cached_nodes)
sem_result["edges"].extend(cached_edges)
sem_result["hyperedges"].extend(cached_hyperedges)
if sem_cache_hits:
print(f"[graphify extract] semantic cache: {sem_cache_hits} hit / {sem_cache_misses} miss")
if uncached_paths:
print(f"[graphify extract] semantic extraction on {len(uncached_paths)} files via {backend}...")
try:
fresh = _extract_corpus_parallel(
[Path(p) for p in uncached_paths],
backend=backend,
model=model,
root=target,
)
except ImportError as exc:
print(f"error: {exc}", file=sys.stderr)
sys.exit(1)
except Exception as exc:
print(
f"[graphify extract] semantic extraction failed: {exc}",
file=sys.stderr,
)
fresh = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
try:
_save_semantic_cache(
fresh.get("nodes", []),
fresh.get("edges", []),
fresh.get("hyperedges", []),
root=target,
)
except Exception as exc:
print(f"[graphify extract] warning: could not write semantic cache: {exc}", file=sys.stderr)
sem_result["nodes"].extend(fresh.get("nodes", []))
sem_result["edges"].extend(fresh.get("edges", []))
sem_result["hyperedges"].extend(fresh.get("hyperedges", []))
sem_result["input_tokens"] += fresh.get("input_tokens", 0)
sem_result["output_tokens"] += fresh.get("output_tokens", 0)
# Merge AST + semantic. Order matters for deduplication: passing AST
# first means semantic node attributes win on collision (richer labels
# for symbols also referenced in docs). Hyperedges only come from the
# semantic side.
merged: dict = {
"nodes": list(ast_result.get("nodes", [])) + list(sem_result.get("nodes", [])),
"edges": list(ast_result.get("edges", [])) + list(sem_result.get("edges", [])),
"hyperedges": list(sem_result.get("hyperedges", [])),
"input_tokens": ast_result.get("input_tokens", 0) + sem_result.get("input_tokens", 0),
"output_tokens": ast_result.get("output_tokens", 0) + sem_result.get("output_tokens", 0),
}
graph_json_path = graphify_out / "graph.json"
analysis_path = graphify_out / ".graphify_analysis.json"
if no_cluster:
# --no-cluster: dump the raw merged extraction as graph.json.
# No NetworkX, no community detection, no analysis sidecar.
graph_json_path.write_text(
json.dumps(merged, indent=2), encoding="utf-8"
)
cost = _estimate_cost(
backend, merged["input_tokens"], merged["output_tokens"]
)
print(
f"[graphify extract] wrote {graph_json_path} — "
f"{len(merged['nodes'])} nodes, {len(merged['edges'])} edges "
f"(no clustering)"
)
if merged["input_tokens"] or merged["output_tokens"]:
print(
f"[graphify extract] tokens: "
f"{merged['input_tokens']:,} in / "
f"{merged['output_tokens']:,} out, "
f"est. cost: ${cost:.4f}"
)
try:
_save_manifest(files_by_type, manifest_path=str(manifest_path))
except Exception as exc:
print(f"[graphify extract] warning: could not write manifest: {exc}", file=sys.stderr)
if global_merge:
from graphify.global_graph import global_add as _global_add
_tag = global_repo_tag or target.name
try:
result = _global_add(graphify_out / "graph.json", _tag)
if result["skipped"]:
print(f"[graphify global] '{_tag}' unchanged since last add — skipped.")
else:
print(f"[graphify global] '{_tag}' merged into global graph "
f"(+{result['nodes_added']} nodes, -{result['nodes_removed']} pruned).")
except Exception as exc:
print(f"[graphify global] warning: failed to merge into global graph: {exc}", file=sys.stderr)
sys.exit(0)
# Build graph + cluster + score + write.
from graphify.build import (
build as _build,
build_from_json as _build_from_json,
build_merge as _build_merge,
)
from graphify.cluster import cluster as _cluster, score_all as _score_all
from graphify.export import to_json as _to_json
from graphify.analyze import god_nodes as _god_nodes, surprising_connections as _surprising
dedup_backend = backend if dedup_llm else None
if incremental_mode:
G = _build_merge(
[merged],
graph_path=existing_graph_path,
prune_sources=deleted_files or None,
dedup=True,
dedup_llm_backend=dedup_backend,
)
else:
G = _build([merged], dedup=True, dedup_llm_backend=dedup_backend)
if G.number_of_nodes() == 0:
print(
"[graphify extract] graph is empty — extraction produced no nodes. "
"Possible causes: all files skipped, binary-only corpus, or LLM "
"returned no edges.",
file=sys.stderr,
)
sys.exit(1)
communities = _cluster(G)
cohesion = _score_all(G, communities)
try:
gods = _god_nodes(G)
except Exception:
gods = []
try:
surprises = _surprising(G, communities)
except Exception:
surprises = []
_to_json(G, communities, str(graph_json_path), force=True)
if global_merge:
from graphify.global_graph import global_add as _global_add
_tag = global_repo_tag or target.name
try:
result = _global_add(graphify_out / "graph.json", _tag)
if result["skipped"]:
print(f"[graphify global] '{_tag}' unchanged since last add — skipped.")
else:
print(f"[graphify global] '{_tag}' merged into global graph "
f"(+{result['nodes_added']} nodes, -{result['nodes_removed']} pruned).")
except Exception as exc:
print(f"[graphify global] warning: failed to merge into global graph: {exc}", file=sys.stderr)
analysis = {
"communities": {str(k): v for k, v in communities.items()},
"cohesion": {str(k): v for k, v in cohesion.items()},
"gods": gods,
"surprises": surprises,
"tokens": {
"input": merged["input_tokens"],
"output": merged["output_tokens"],
},
}
analysis_path.write_text(json.dumps(analysis, indent=2), encoding="utf-8")
try:
_save_manifest(files_by_type, manifest_path=str(manifest_path))
except Exception as exc:
print(f"[graphify extract] warning: could not write manifest: {exc}", file=sys.stderr)
cost = _estimate_cost(backend, merged["input_tokens"], merged["output_tokens"])
print(
f"[graphify extract] wrote {graph_json_path}: "
f"{G.number_of_nodes()} nodes, {G.number_of_edges()} edges, "
f"{len(communities)} communities"
)
print(f"[graphify extract] wrote {analysis_path}")
if incremental_mode:
print(
f"[graphify extract] incremental summary: "
f"{sem_cache_hits + unchanged_total} files cached/unchanged, "
f"{len(code_files) + sem_cache_misses} re-extracted, "
f"{len(deleted_files)} deleted"
)
elif sem_cache_hits:
print(f"[graphify extract] semantic cache: {sem_cache_hits} cached, {sem_cache_misses} re-extracted")
if merged["input_tokens"] or merged["output_tokens"]:
print(
f"[graphify extract] tokens: "
f"{merged['input_tokens']:,} in / "
f"{merged['output_tokens']:,} out, "
f"est. cost (~{backend}): ${cost:.4f}"
)
else:
print(f"error: unknown command '{cmd}'", file=sys.stderr)
print("Run 'graphify --help' for usage.", file=sys.stderr)
+57 -5
View File
@@ -116,17 +116,27 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
return G
def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
def build(
extractions: list[dict],
*,
directed: bool = False,
dedup: bool = True,
dedup_llm_backend: str | None = None,
) -> nx.Graph:
"""Merge multiple extraction results into one graph.
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
dedup=True (default) runs entity deduplication before building the graph.
dedup_llm_backend: if set (e.g. "gemini", "claude", or "kimi"), uses LLM to resolve
ambiguous pairs in the 75–92 Jaro-Winkler score zone.
Extractions are merged in order. For nodes with the same ID, the last
extraction's attributes win (NetworkX add_node overwrites). Pass AST
results before semantic results so semantic labels take precedence, or
reverse the order if you prefer AST source_location precision to win.
"""
from graphify.dedup import deduplicate_entities
combined: dict = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
for ext in extractions:
combined["nodes"].extend(ext.get("nodes", []))
@@ -134,6 +144,11 @@ def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
combined["hyperedges"].extend(ext.get("hyperedges", []))
combined["input_tokens"] += ext.get("input_tokens", 0)
combined["output_tokens"] += ext.get("output_tokens", 0)
if dedup and combined["nodes"]:
combined["nodes"], combined["edges"] = deduplicate_entities(
combined["nodes"], combined["edges"], communities={},
dedup_llm_backend=dedup_llm_backend,
)
return build_from_json(combined, directed=directed)
@@ -194,6 +209,8 @@ def build_merge(
prune_sources: list[str] | None = None,
*,
directed: bool = False,
dedup: bool = True,
dedup_llm_backend: str | None = None,
) -> nx.Graph:
"""Load existing graph.json, merge new chunks into it, and save back.
@@ -219,7 +236,7 @@ def build_merge(
base = []
all_chunks = base + list(new_chunks)
G = build(all_chunks, directed=directed)
G = build(all_chunks, directed=directed, dedup=dedup, dedup_llm_backend=dedup_llm_backend)
# Prune nodes from deleted source files
if prune_sources:
@@ -228,11 +245,23 @@ def build_merge(
if d.get("source_file") in prune_sources
]
G.remove_nodes_from(to_remove)
if to_remove:
print(f"[graphify] Pruned {len(to_remove)} node(s) from deleted sources.", file=sys.stderr)
n_files = len(prune_sources)
n_nodes = len(to_remove)
if n_nodes:
print(
f"[graphify] Pruned {n_nodes} node(s) from {n_files} deleted source file(s).",
file=sys.stderr,
)
else:
print(
f"[graphify] {n_files} source file(s) deleted since last run — "
f"no matching nodes in graph, already clean.",
file=sys.stderr,
)
# Safety check: refuse to shrink the graph silently (#479)
if graph_path.exists():
# Skip when dedup or prune_sources is active — shrinkage is intentional there.
if graph_path.exists() and not dedup and not prune_sources:
existing_n = len(existing_nodes)
new_n = G.number_of_nodes()
if new_n < existing_n:
@@ -242,3 +271,26 @@ def build_merge(
)
return G
def prefix_graph_for_global(G: nx.Graph, repo_tag: str) -> nx.Graph:
"""Return a copy of G with all node IDs prefixed with repo_tag::.
Labels are preserved unchanged (for display). A 'local_id' attribute
is added to each node so the original ID can be recovered. Edges are
rewritten to match the new prefixed IDs. The 'repo' attribute is set
on every node.
"""
relabel = {n: f"{repo_tag}::{n}" for n in G.nodes}
H = nx.relabel_nodes(G, relabel, copy=True)
for node, data in H.nodes(data=True):
data["repo"] = repo_tag
data.setdefault("local_id", node.split("::", 1)[1])
return H
def prune_repo_from_graph(G: nx.Graph, repo_tag: str) -> int:
"""Remove all nodes tagged with repo_tag from G in-place. Returns count removed."""
to_remove = [n for n, d in G.nodes(data=True) if d.get("repo") == repo_tag]
G.remove_nodes_from(to_remove)
return len(to_remove)
+336
View File
@@ -0,0 +1,336 @@
"""Entity deduplication pipeline for graphify knowledge graphs.
Pipeline: exact normalization → entropy gate → MinHash/LSH blocking →
Jaro-Winkler verification → same-community boost → union-find merge.
"""
from __future__ import annotations
import math
import re
from collections import defaultdict
from datasketch import MinHash, MinHashLSH
from rapidfuzz.distance import JaroWinkler
# ── helpers ───────────────────────────────────────────────────────────────────
def _norm(label: str) -> str:
"""Lowercase + collapse non-alphanumeric runs to space."""
return re.sub(r"[^a-z0-9]+", " ", label.lower()).strip()
def _entropy(label: str) -> float:
"""Shannon entropy in bits/char of the normalised label."""
s = _norm(label)
if not s:
return 0.0
freq: dict[str, int] = defaultdict(int)
for ch in s:
freq[ch] += 1
n = len(s)
return -sum((c / n) * math.log2(c / n) for c in freq.values())
def _shingles(text: str, k: int = 3) -> set[str]:
"""Return k-gram character shingles of text."""
if len(text) < k:
return {text}
return {text[i : i + k] for i in range(len(text) - k + 1)}
def _make_minhash(text: str, num_perm: int = 128) -> MinHash:
# Strip spaces so "graph extractor" and "graphextractor" share shingles
m = MinHash(num_perm=num_perm)
for shingle in _shingles(text.replace(" ", "")):
m.update(shingle.encode("utf-8"))
return m
# ── union-find ────────────────────────────────────────────────────────────────
class _UF:
def __init__(self) -> None:
self._parent: dict[str, str] = {}
def find(self, x: str) -> str:
self._parent.setdefault(x, x)
while self._parent[x] != x:
self._parent[x] = self._parent[self._parent[x]]
x = self._parent[x]
return x
def union(self, x: str, y: str) -> None:
self._parent.setdefault(x, x)
self._parent.setdefault(y, y)
rx, ry = self.find(x), self.find(y)
if rx != ry:
self._parent[ry] = rx
def components(self) -> dict[str, list[str]]:
groups: dict[str, list[str]] = defaultdict(list)
for x in self._parent:
groups[self.find(x)].append(x)
return dict(groups)
# ── constants ─────────────────────────────────────────────────────────────────
_ENTROPY_THRESHOLD = 2.5
_LSH_THRESHOLD = 0.7
_MERGE_THRESHOLD = 92.0 # rapidfuzz normalized_similarity * 100
_COMMUNITY_BOOST = 5.0 # score bonus when both nodes share community
_NUM_PERM = 128
_CHUNK_SUFFIX = re.compile(r"_c\d+$")
# ── main entry point ──────────────────────────────────────────────────────────
def deduplicate_entities(
nodes: list[dict],
edges: list[dict],
*,
communities: dict[str, int],
dedup_llm_backend: str | None = None,
) -> tuple[list[dict], list[dict]]:
"""Deduplicate near-identical entities in a knowledge graph.
Args:
nodes: list of node dicts with at minimum {"id": str, "label": str}
edges: list of edge dicts with {"source": str, "target": str, ...}
communities: mapping of node_id -> community_id (from cluster())
dedup_llm_backend: if set, use LLM to resolve ambiguous pairs
Returns:
(deduped_nodes, deduped_edges) with edges rewired to survivors
"""
# Guard: cross-project dedup is not supported — nodes from different repos
# share label names by coincidence and must never be merged by string similarity.
# If you need to dedup a global graph, run deduplicate_entities per-repo first.
repos_seen = {n.get("repo") for n in nodes if n.get("repo")}
if len(repos_seen) > 1:
raise ValueError(
f"deduplicate_entities: nodes span multiple repos {sorted(repos_seen)!r}. "
f"Cross-project dedup is disabled — run dedup per-repo before merging."
)
if len(nodes) <= 1:
return nodes, edges
# Pre-deduplicate: keep first occurrence of each id
seen_ids: dict[str, dict] = {}
for node in nodes:
nid = node.get("id", "")
if nid and nid not in seen_ids:
seen_ids[nid] = node
unique_nodes = list(seen_ids.values())
if len(unique_nodes) <= 1:
return unique_nodes, edges
# ── pass 1: exact normalization ───────────────────────────────────────────
norm_to_nodes: dict[str, list[dict]] = defaultdict(list)
for node in unique_nodes:
key = _norm(node.get("label", node.get("id", "")))
if key:
norm_to_nodes[key].append(node)
uf = _UF()
for key, group in norm_to_nodes.items():
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] = []
seen_norms: set[str] = set()
for node in unique_nodes:
key = _norm(node.get("label", node.get("id", "")))
if key and key not in seen_norms:
seen_norms.add(key)
if _entropy(node.get("label", "")) >= _ENTROPY_THRESHOLD:
candidates.append(node)
fuzzy_merges = 0
if len(candidates) >= 2:
lsh = MinHashLSH(threshold=_LSH_THRESHOLD, num_perm=_NUM_PERM)
minhashes: dict[str, MinHash] = {}
for node in candidates:
norm_label = _norm(node.get("label", node.get("id", "")))
m = _make_minhash(norm_label)
minhashes[node["id"]] = m
try:
lsh.insert(node["id"], m)
except ValueError:
pass # duplicate key in LSH — already inserted
for node in candidates:
node_id = node["id"]
norm_label = _norm(node.get("label", node.get("id", "")))
neighbors = lsh.query(minhashes[node_id])
for neighbor_id in neighbors:
if neighbor_id == node_id:
continue
if uf.find(node_id) == uf.find(neighbor_id):
continue
neighbor = next((n for n in candidates if n["id"] == neighbor_id), None)
if neighbor is None:
continue
neighbor_norm = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_label, neighbor_norm) * 100
c1 = communities.get(node_id)
c2 = communities.get(neighbor_id)
if c1 is not None and c2 is not None and c1 == c2:
score += _COMMUNITY_BOOST
if score >= _MERGE_THRESHOLD:
all_group = norm_to_nodes.get(norm_label, [node]) + \
norm_to_nodes.get(neighbor_norm, [neighbor])
winner = _pick_winner(all_group)
uf.union(winner["id"], node_id)
uf.union(winner["id"], neighbor_id)
fuzzy_merges += 1
# ── pass 3: LLM tiebreaker for ambiguous pairs (opt-in) ──────────────────
if dedup_llm_backend is not None:
_llm_tiebreak(candidates, uf, communities, backend=dedup_llm_backend)
# ── build remap table from union-find components ──────────────────────────
components = uf.components()
remap: dict[str, str] = {}
for root, members in components.items():
if len(members) == 1:
continue
group_nodes = [n for n in unique_nodes if n["id"] in members]
winner = _pick_winner(group_nodes) if group_nodes else {"id": root}
winner_id = winner["id"]
for member in members:
if member != winner_id:
remap[member] = winner_id
# ── apply remap ───────────────────────────────────────────────────────────
if not remap:
return unique_nodes, edges
total = len(remap)
msg = f"[graphify] Deduplicated {total} node(s)"
if exact_merges:
msg += f" ({exact_merges} exact"
if fuzzy_merges:
msg += f", {fuzzy_merges} fuzzy"
msg += ")"
print(msg + ".", flush=True)
deduped_nodes = [n for n in unique_nodes if n["id"] not in remap]
deduped_edges = []
for edge in edges:
e = dict(edge)
e["source"] = remap.get(e["source"], e["source"])
e["target"] = remap.get(e["target"], e["target"])
if e["source"] != e["target"]:
deduped_edges.append(e)
return deduped_nodes, deduped_edges
def _pick_winner(nodes: list[dict]) -> dict:
"""Pick the canonical survivor: prefer no chunk suffix, then shorter ID."""
if not nodes:
raise ValueError("Cannot pick winner from empty list")
def _score(n: dict) -> tuple[int, int]:
has_suffix = bool(_CHUNK_SUFFIX.search(n["id"]))
return (1 if has_suffix else 0, len(n["id"]))
return min(nodes, key=_score)
def _llm_tiebreak(
candidates: list[dict],
uf: _UF,
communities: dict[str, int],
*,
backend: str,
batch_size: int = 30,
low: float = 75.0,
high: float = 92.0,
) -> None:
"""Batch-resolve ambiguous pairs (score in [low, high)) via LLM."""
try:
from graphify.llm import BACKENDS, _format_backend_env_keys, _get_backend_api_key
if backend not in BACKENDS:
print(f"[graphify] --dedup-llm: unknown backend {backend!r}, skipping LLM tiebreaker.", flush=True)
return
if not _get_backend_api_key(backend):
env_keys = _format_backend_env_keys(backend)
print(f"[graphify] --dedup-llm: {env_keys} not set, skipping LLM tiebreaker.", flush=True)
return
except ImportError:
return
ambiguous: list[tuple[dict, dict, float]] = []
for i, node in enumerate(candidates):
norm_i = _norm(node.get("label", node.get("id", "")))
for j in range(i + 1, len(candidates)):
neighbor = candidates[j]
if uf.find(node["id"]) == uf.find(neighbor["id"]):
continue
norm_j = _norm(neighbor.get("label", neighbor.get("id", "")))
score = JaroWinkler.normalized_similarity(norm_i, norm_j) * 100
c1 = communities.get(node["id"])
c2 = communities.get(neighbor["id"])
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))
if not ambiguous:
return
try:
from graphify.llm import _call_llm
except ImportError:
return
for batch_start in range(0, len(ambiguous), batch_size):
batch = ambiguous[batch_start : batch_start + batch_size]
pairs_text = "\n".join(
f"{i+1}. \"{a['label']}\" vs \"{b['label']}\""
for i, (a, b, _) in enumerate(batch)
)
prompt = (
"For each pair below, answer only 'yes' or 'no': are they the same real-world concept?\n\n"
f"{pairs_text}\n\n"
"Reply with one line per pair: '1. yes', '2. no', etc."
)
try:
response = _call_llm(prompt, backend=backend, max_tokens=200)
lines = response.strip().splitlines()
for line in lines:
line = line.strip()
if not line:
continue
parts = line.split(".", 1)
if len(parts) != 2:
continue
try:
idx = int(parts[0].strip()) - 1
except ValueError:
continue
if 0 <= idx < len(batch):
answer = parts[1].strip().lower()
if answer.startswith("yes"):
a, b, _ = batch[idx]
winner = _pick_winner([a, b])
uf.union(winner["id"], a["id"])
uf.union(winner["id"], b["id"])
except Exception as exc:
print(f"[graphify] --dedup-llm batch failed: {exc}", flush=True)
+14 -4
View File
@@ -18,7 +18,7 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv', '.sql', '.r'}
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08'}
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
@@ -33,7 +33,7 @@ FILE_COUNT_UPPER = 200 # files - above this, warn about token cost
_SENSITIVE_PATTERNS = [
re.compile(r'(^|[\\/])\.(env|envrc)(\.|$)', re.IGNORECASE),
re.compile(r'\.(pem|key|p12|pfx|cert|crt|der|p8)$', re.IGNORECASE),
re.compile(r'(credential|secret|passwd|password|token|private_key)', re.IGNORECASE),
re.compile(r'\b(credential|secret|passwd|password|token|private_key)s?\b', re.IGNORECASE),
re.compile(r'(id_rsa|id_dsa|id_ecdsa|id_ed25519)(\.pub)?$'),
re.compile(r'(\.netrc|\.pgpass|\.htpasswd)$', re.IGNORECASE),
re.compile(r'(aws_credentials|gcloud_credentials|service.account)', re.IGNORECASE),
@@ -771,7 +771,12 @@ def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PA
Path(manifest_path).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
def detect_incremental(
root: Path,
manifest_path: str = _MANIFEST_PATH,
*,
follow_symlinks: bool = False,
) -> dict:
"""Like detect(), but returns only new or modified files since the last run.
Fast path: mtime unchanged → unchanged (free, no hash).
@@ -779,8 +784,13 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
treat as unchanged. Different hash = actually changed, re-extract.
Backwards compatible with legacy manifests storing plain float mtime values.
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.
"""
full = detect(root)
full = detect(root, follow_symlinks=follow_symlinks)
manifest = load_manifest(manifest_path)
if not manifest:
+57 -4
View File
@@ -11,6 +11,15 @@ from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.analyze import _node_community_map
def _obsidian_tag(name: str) -> str:
"""Sanitize a community name for use as an Obsidian tag.
Obsidian tags only allow alphanumerics, hyphens, underscores, and slashes.
Spaces become underscores; everything else is stripped.
"""
return re.sub(r"[^a-zA-Z0-9_\-/]", "", name.replace(" ", "_"))
def _strip_diacritics(text: str) -> str:
import unicodedata
nfkd = unicodedata.normalize("NFKD", text)
@@ -340,7 +349,17 @@ def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
G.graph["hyperedges"] = existing
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False) -> bool:
def _git_head() -> str | None:
"""Return the current git HEAD commit hash, or None if not in a git repo."""
import subprocess as _sp
try:
r = _sp.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=3)
return r.stdout.strip() if r.returncode == 0 else None
except Exception:
return None
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None) -> bool:
# Safety check: refuse to silently shrink an existing graph (#479)
existing_path = Path(output_path)
if not force and existing_path.exists():
@@ -383,6 +402,9 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
link["source"] = true_src
link["target"] = true_tgt
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
commit = built_at_commit if built_at_commit is not None else _git_head()
if commit:
data["built_at_commit"] = commit
with open(output_path, "w", encoding="utf-8") as f: # nosec
json.dump(data, f, indent=2)
return True
@@ -436,6 +458,7 @@ def to_html(
output_path: str,
community_labels: dict[int, str] | None = None,
member_counts: dict[int, int] | None = None,
node_limit: int | None = None,
) -> None:
"""Generate an interactive vis.js HTML visualization of the graph.
@@ -445,9 +468,39 @@ def to_html(
If member_counts is provided (aggregated community view), node sizes are
based on community member counts rather than graph degree.
If node_limit is set and the graph exceeds it, automatically builds an
aggregated community-level meta-graph instead of raising ValueError.
"""
limit = _viz_node_limit()
limit = node_limit if node_limit is not None else _viz_node_limit()
if G.number_of_nodes() > limit:
if node_limit is not None:
# Build aggregated community meta-graph
from collections import Counter as _Counter
import networkx as _nx
print(f"Graph has {G.number_of_nodes()} nodes (above {limit} limit). Building aggregated community view...")
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
meta = _nx.Graph()
for cid, members in communities.items():
meta.add_node(str(cid), label=(community_labels or {}).get(cid, f"Community {cid}"))
edge_counts = _Counter()
for u, v in G.edges():
cu, cv = node_to_community.get(u), node_to_community.get(v)
if cu is not None and cv is not None and cu != cv:
edge_counts[(min(cu, cv), max(cu, cv))] += 1
for (cu, cv), w in edge_counts.items():
meta.add_edge(str(cu), str(cv), weight=w,
relation=f"{w} cross-community edges", confidence="AGGREGATED")
if meta.number_of_nodes() <= 1:
print("Single community - aggregated view not useful. Skipping graph.html.")
return
meta_communities = {cid: [str(cid)] for cid in communities}
mc = {cid: len(members) for cid, members in communities.items()}
to_html(meta, meta_communities, output_path,
community_labels=community_labels, member_counts=mc)
print(f"graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)")
print("Tip: run with --obsidian for full node-level detail.")
return
raise ValueError(
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
@@ -639,7 +692,7 @@ def to_obsidian(
ftype_tag = _FTYPE_TAG.get(ftype, f"graphify/{ftype}" if ftype else "graphify/document")
dom_conf = _dominant_confidence(node_id)
conf_tag = f"graphify/{dom_conf}"
comm_tag = f"community/{community_name.replace(' ', '_')}"
comm_tag = f"community/{_obsidian_tag(community_name)}"
node_tags = [ftype_tag, conf_tag, comm_tag]
lines: list[str] = []
@@ -751,7 +804,7 @@ def to_obsidian(
lines.append("")
# Dataview live query (improvement 2)
comm_tag_name = community_name.replace(" ", "_")
comm_tag_name = _obsidian_tag(community_name)
lines.append("## Live Query (requires Dataview plugin)")
lines.append("")
lines.append("```dataview")
+767 -33
View File
@@ -10,6 +10,24 @@ from pathlib import Path
from typing import Callable, Any
from .cache import load_cached, save_cached
_RECURSION_LIMIT = 10_000
def _raise_recursion_limit() -> None:
if sys.getrecursionlimit() < _RECURSION_LIMIT:
sys.setrecursionlimit(_RECURSION_LIMIT)
def _safe_extract(extractor: Callable, path: Path) -> dict:
try:
return extractor(path)
except RecursionError:
print(f" warning: skipped {path} (recursion limit exceeded)", file=sys.stderr, flush=True)
return {"nodes": [], "edges": [], "error": "recursion_limit_exceeded"}
except Exception as e:
print(f" warning: skipped {path} ({type(e).__name__}: {e})", file=sys.stderr, flush=True)
return {"nodes": [], "edges": [], "error": f"{type(e).__name__}: {e}"}
def _make_id(*parts: str) -> str:
"""Build a stable node ID from one or more name parts."""
@@ -30,9 +48,85 @@ def _file_stem(path: Path) -> str:
_TSCONFIG_ALIAS_CACHE: dict[str, dict[str, str]] = {}
def _strip_jsonc(text: str) -> str:
"""Strip // line comments, /* */ block comments, and trailing commas from JSONC.
Preserves string contents (including // and /* inside strings) by skipping over
quoted spans first. Required for tsconfig.json files generated by SvelteKit,
NestJS, Vite, T3, Astro, etc., which use JSONC by default (#700).
"""
# Remove block and line comments while leaving string literals untouched.
pattern = re.compile(
r'"(?:\\.|[^"\\])*"' # double-quoted string (with escapes)
r"|/\*.*?\*/" # /* block comment */
r"|//[^\n]*", # // line comment
re.DOTALL,
)
def _replace(match: re.Match) -> str:
token = match.group(0)
if token.startswith('"'):
return token
return ""
stripped = pattern.sub(_replace, text)
# Remove trailing commas before } or ] (allowing whitespace between).
stripped = re.sub(r",(\s*[}\]])", r"\1", stripped)
return stripped
def _read_tsconfig_aliases(tsconfig: Path, base_dir: Path, seen: set) -> dict[str, str]:
"""Recursively read path aliases from a tsconfig, following extends chains.
Child config paths override parent. Circular extends are detected via seen set.
npm package configs (e.g. @tsconfig/svelte) are skipped since they're not on disk.
Handles JSONC (comments + trailing commas) which is the default tsconfig format
for SvelteKit, NestJS, Vite, T3, Astro, etc. (#700).
"""
if str(tsconfig) in seen:
return {}
seen.add(str(tsconfig))
try:
raw = tsconfig.read_text(encoding="utf-8")
except Exception as e:
print(f" warning: could not read {tsconfig} ({type(e).__name__}: {e})", file=sys.stderr, flush=True)
return {}
try:
data = json.loads(raw)
except json.JSONDecodeError:
try:
data = json.loads(_strip_jsonc(raw))
except json.JSONDecodeError as e:
print(f" warning: failed to parse {tsconfig} as JSON/JSONC ({e.msg} at line {e.lineno} col {e.colno})", file=sys.stderr, flush=True)
return {}
except Exception as e:
print(f" warning: failed to parse {tsconfig} ({type(e).__name__}: {e})", file=sys.stderr, flush=True)
return {}
aliases: dict[str, str] = {}
extends = data.get("extends")
if extends and not extends.startswith("@"):
extended_path = (base_dir / extends).resolve()
if not extended_path.suffix:
extended_path = extended_path.with_suffix(".json")
if extended_path.exists():
aliases.update(_read_tsconfig_aliases(extended_path, extended_path.parent, seen))
paths = data.get("compilerOptions", {}).get("paths", {})
for alias, targets in paths.items():
if not targets:
continue
alias_prefix = alias.rstrip("/*")
target_base = targets[0].rstrip("/*")
aliases[alias_prefix] = str(base_dir / target_base)
return aliases
def _load_tsconfig_aliases(start_dir: Path) -> dict[str, str]:
"""Walk up from start_dir to find tsconfig.json and return compilerOptions.paths aliases.
Follows extends chains so SvelteKit/Nuxt/NestJS inherited aliases are included.
Returns a dict mapping alias prefix (e.g. "@/") to resolved base dir (e.g. "src/").
Result is cached by tsconfig path string.
"""
@@ -42,20 +136,7 @@ def _load_tsconfig_aliases(start_dir: Path) -> dict[str, str]:
if tsconfig.exists():
key = str(tsconfig)
if key not in _TSCONFIG_ALIAS_CACHE:
try:
data = json.loads(tsconfig.read_text(encoding="utf-8"))
paths = data.get("compilerOptions", {}).get("paths", {})
aliases: dict[str, str] = {}
for alias, targets in paths.items():
if not targets:
continue
# Strip trailing /* from alias and target
alias_prefix = alias.rstrip("/*")
target_base = targets[0].rstrip("/*")
aliases[alias_prefix] = str(candidate / target_base)
_TSCONFIG_ALIAS_CACHE[key] = aliases
except Exception:
_TSCONFIG_ALIAS_CACHE[key] = {}
_TSCONFIG_ALIAS_CACHE[key] = _read_tsconfig_aliases(tsconfig, candidate, seen=set())
return _TSCONFIG_ALIAS_CACHE[key]
return {}
@@ -107,6 +188,75 @@ class LanguageConfig:
# ── Generic helpers ───────────────────────────────────────────────────────────
# Vite / TypeScript resolver extensions. Used by _resolve_js_module_path()
# to map import specifiers onto real files on disk, so the resulting node
# id matches the one _extract_generic creates for the target file.
_JS_RESOLVE_EXTS = (".ts", ".tsx", ".svelte", ".js", ".jsx", ".mjs")
_JS_INDEX_FILES = ("index.ts", "index.tsx", "index.js", "index.jsx")
def _resolve_js_module_path(p: Path) -> Path:
"""Resolve a JS/TS-style import specifier path to an actual file on disk.
TypeScript / SvelteKit / Vite let you write imports without a file
extension and auto-resolve via a fixed extension order. The pre-existing
.js→.ts and .jsx→.tsx rewrites only covered the TS-ESM-via-.js convention;
every other shape produced a phantom node id and the edge was lost in
build_from_json.
Order, mirroring Vite's resolver:
1. exact path, when it's a real file on disk
2. directory → try index.{ts,tsx,js,jsx}
3. .js → .ts (TS ESM convention; written as .js, file is .ts)
.jsx → .tsx
4. append .ts/.tsx/.svelte/.js/.jsx/.mjs to the FULL filename — not
a suffix-swap. This handles, in one rule:
- bare paths: foo → foo.ts
- Svelte 5 rune files: foo.svelte → foo.svelte.ts
- multi-dot helper files: foo.shared → foo.shared.ts
- config files: foo.config → foo.config.ts
- test helper files: foo.spec → foo.spec.ts
5. directory variant: try ./<name>/index.{ts,tsx,js,jsx}
Falls back to the original path on no match — preserves pre-fix behaviour
for genuinely external modules (the edge gets dropped as external by
build_from_json).
"""
if p.is_file():
return p
# TS ESM convention: import path written with .js but the real file is .ts.
# Apply BEFORE the generic append loop so we don't accidentally match
# foo.js → foo.js.ts when the real file is foo.ts.
if p.suffix == ".js":
c = p.with_suffix(".ts")
if c.is_file():
return c
if p.suffix == ".jsx":
c = p.with_suffix(".tsx")
if c.is_file():
return c
# Try appending extensions to the FULL filename BEFORE checking for a
# directory import. Both TypeScript and Vite resolvers prefer a file
# match over a directory match — projects routinely have a `foo.ts`
# file living alongside a `foo/` directory of sub-modules (e.g.
# `auth.ts` next to `auth/`). If we checked the directory first, those
# file imports would silently lose to a directory with no `index.*`.
for ext in _JS_RESOLVE_EXTS:
c = p.parent / (p.name + ext)
if c.is_file():
return c
# Directory imports: try ./<name>/index.{ts,tsx,js,jsx}. Reached only
# after every file-extension candidate has been ruled out, matching the
# resolver fallback chain.
if p.is_dir():
for idx in _JS_INDEX_FILES:
c = p / idx
if c.is_file():
return c
return p
def _read_text(node, source: bytes) -> str:
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
@@ -194,11 +344,9 @@ def _import_js(node, source: bytes, file_nid: str, stem: str, edges: list, str_p
# Relative import - resolve to full path so IDs match file node IDs
# normpath removes ".." segments so the ID matches the target file's own node ID
resolved = Path(os.path.normpath(Path(str_path).parent / raw))
# TypeScript ESM: imports written as .js but actual file is .ts/.tsx
if resolved.suffix == ".js":
resolved = resolved.with_suffix(".ts")
elif resolved.suffix == ".jsx":
resolved = resolved.with_suffix(".tsx")
# TS / SvelteKit resolver: try .ts/.tsx/.svelte/.svelte.ts/index.{ts,…}
# so bare-path and Svelte-5-rune imports land on the right node id (#716)
resolved = _resolve_js_module_path(resolved)
tgt_nid = _make_id(str(resolved))
resolved_path = resolved
else:
@@ -211,6 +359,9 @@ def _import_js(node, source: bytes, file_nid: str, stem: str, edges: list, str_p
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
break
if resolved_alias is not None:
# Same resolver fixups as the relative branch — alias targets
# are equally likely to be bare paths / .svelte.ts / index.ts (#716)
resolved_alias = _resolve_js_module_path(resolved_alias)
tgt_nid = _make_id(str(resolved_alias))
resolved_path = resolved_alias
else:
@@ -302,10 +453,11 @@ def _dynamic_import_js(node, source: bytes, caller_nid: str, str_path: str, edge
# Resolve path using the same logic as static imports
if raw.startswith("."):
resolved = Path(os.path.normpath(Path(str_path).parent / raw))
if resolved.suffix == ".js":
resolved = resolved.with_suffix(".ts")
elif resolved.suffix == ".jsx":
resolved = resolved.with_suffix(".tsx")
# Same TS/SvelteKit resolver fixups static imports use, so
# `await import('./foo')` (bare path), `import('./bar.shared')`
# (multi-dot helper), and Svelte 5 rune-file dynamic imports
# all land on real file nodes.
resolved = _resolve_js_module_path(resolved)
tgt_nid = _make_id(str(resolved))
else:
aliases = _load_tsconfig_aliases(Path(str_path).parent)
@@ -316,6 +468,7 @@ def _dynamic_import_js(node, source: bytes, caller_nid: str, str_path: str, edge
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
break
if resolved_alias is not None:
resolved_alias = _resolve_js_module_path(resolved_alias)
tgt_nid = _make_id(str(resolved_alias))
else:
module_name = raw.split("/")[-1]
@@ -645,6 +798,18 @@ _JAVA_CONFIG = LanguageConfig(
import_handler=_import_java,
)
_GROOVY_CONFIG = LanguageConfig(
ts_module="tree_sitter_groovy",
class_types=frozenset({"class_declaration", "interface_declaration"}),
function_types=frozenset({"method_declaration", "constructor_declaration"}),
import_types=frozenset({"import_declaration"}),
call_types=frozenset({"method_invocation"}),
call_function_field="name",
call_accessor_node_types=frozenset(),
function_boundary_types=frozenset({"method_declaration", "constructor_declaration"}),
import_handler=_import_java,
)
_C_CONFIG = LanguageConfig(
ts_module="tree_sitter_c",
class_types=frozenset(),
@@ -1656,11 +1821,262 @@ def extract_js(path: Path) -> dict:
return _extract_generic(path, config)
def extract_svelte(path: Path) -> dict:
"""Extract imports from .svelte files: script-block via JS AST + template regex fallback.
Tree-sitter only sees the <script> block. Svelte template syntax like
{#await import('./X.svelte')} lives in the markup layer and is invisible
to the JS parser, so a regex pass covers those dynamic imports.
"""
result = _extract_generic(path, _JS_CONFIG)
try:
import re as _re
src = path.read_text(encoding="utf-8", errors="replace")
existing_ids = {n["id"] for n in result.get("nodes", [])}
# Source file node ID must match the one _extract_generic creates:
# _make_id(str(path)) - single arg, no stem prefix. Otherwise the source
# endpoint is a phantom node and build_from_json drops the edge (#701).
file_node_id = _make_id(str(path))
aliases = _load_tsconfig_aliases(path.parent)
for m in _re.finditer(r"""import\(\s*['"]([^'"]+)['"]\s*\)""", src):
raw = m.group(1)
if not raw:
continue
if raw.startswith("."):
# Relative import - resolve to full path so IDs match file node IDs.
resolved = Path(os.path.normpath(path.parent / raw))
# Apply same TS/Svelte resolver fixups as static imports so dynamic
# imports of bare paths and .svelte.ts rune files land on real
# file nodes instead of phantom ids (#716).
resolved = _resolve_js_module_path(resolved)
node_id = _make_id(str(resolved))
stub_source_file = str(resolved)
else:
# Check tsconfig.json path aliases (e.g. "$lib/" -> "src/lib/", "@/" -> "src/")
# before treating as external. Mirrors _import_js logic so SvelteKit alias
# imports resolve to the same file node IDs the extractor creates (#701).
resolved_alias = None
for alias_prefix, alias_base in aliases.items():
if raw == alias_prefix or raw.startswith(alias_prefix + "/"):
rest = raw[len(alias_prefix):].lstrip("/")
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
break
if resolved_alias is not None:
resolved_alias = _resolve_js_module_path(resolved_alias)
node_id = _make_id(str(resolved_alias))
stub_source_file = str(resolved_alias)
else:
# Bare/scoped import (node_modules) - use last segment;
# build_from_json drops as external if no matching node exists.
module_name = raw.split("/")[-1]
if not module_name:
continue
node_id = _make_id(module_name)
stub_source_file = raw
if node_id in existing_ids:
# Edge target already a real node - just add the edge, don't add a node.
result.setdefault("edges", []).append({
"source": file_node_id, "target": node_id,
"relation": "dynamic_import", "confidence": "EXTRACTED",
"source_file": str(path),
})
continue
result.setdefault("nodes", []).append({
"id": node_id, "label": raw,
"file_type": "code", "source_file": stub_source_file,
"confidence": "EXTRACTED",
})
result.setdefault("edges", []).append({
"source": file_node_id, "target": node_id,
"relation": "dynamic_import", "confidence": "EXTRACTED",
"source_file": str(path),
})
existing_ids.add(node_id)
# Static imports inside <script> blocks. The JS tree-sitter parser fed
# the full .svelte file produces a top-level ERROR node (HTML markup
# is not valid JS), so import_statement nodes are never reached and
# static imports are silently dropped (#713). Regex over each script
# body recovers them.
script_re = _re.compile(
r"<script\b[^>]*>([\s\S]*?)</script\s*>", _re.IGNORECASE
)
static_import_re = _re.compile(
r"""import\s+(?:[^'"`;]+?\s+from\s+)?['"]([^'"]+)['"]"""
)
for script_match in script_re.finditer(src):
script_body = script_match.group(1)
for m in static_import_re.finditer(script_body):
raw = m.group(1)
if not raw:
continue
if raw.startswith("."):
resolved = Path(os.path.normpath(path.parent / raw))
if resolved.suffix == ".js":
resolved = resolved.with_suffix(".ts")
elif resolved.suffix == ".jsx":
resolved = resolved.with_suffix(".tsx")
node_id = _make_id(str(resolved))
stub_source_file = str(resolved)
else:
resolved_alias = None
for alias_prefix, alias_base in aliases.items():
if raw == alias_prefix or raw.startswith(alias_prefix + "/"):
rest = raw[len(alias_prefix):].lstrip("/")
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
break
if resolved_alias is not None:
node_id = _make_id(str(resolved_alias))
stub_source_file = str(resolved_alias)
else:
module_name = raw.split("/")[-1]
if not module_name:
continue
node_id = _make_id(module_name)
stub_source_file = raw
if node_id in existing_ids:
result.setdefault("edges", []).append({
"source": file_node_id, "target": node_id,
"relation": "imports_from", "confidence": "EXTRACTED",
"source_file": str(path),
})
continue
result.setdefault("nodes", []).append({
"id": node_id, "label": raw,
"file_type": "code", "source_file": stub_source_file,
"confidence": "EXTRACTED",
})
result.setdefault("edges", []).append({
"source": file_node_id, "target": node_id,
"relation": "imports_from", "confidence": "EXTRACTED",
"source_file": str(path),
})
existing_ids.add(node_id)
except Exception:
pass
return result
def extract_java(path: Path) -> dict:
"""Extract classes, interfaces, methods, constructors, and imports from a .java file."""
return _extract_generic(path, _JAVA_CONFIG)
def _is_spock_file(path: Path, ts_result: dict) -> bool:
"""Return True when the file contains Spock-style ``def "feature"()`` methods
that tree-sitter-groovy cannot parse, detected by checking the raw source."""
import re as _re
_SPOCK_FEATURE_RE = _re.compile(r"""^\s*def\s+[\"']""", _re.MULTILINE)
try:
return bool(_SPOCK_FEATURE_RE.search(path.read_text(errors="replace")))
except OSError:
return False
def _extract_spock_fallback(path: Path, ts_result: dict) -> dict:
"""Regex-based fallback for Spock spec files where tree-sitter-groovy cannot parse
``def "feature name"()`` methods. Merges import edges from the tree-sitter pass
(which survive reliably) with class and feature-method nodes extracted via regex.
"""
import re as _re
source = path.read_text(errors="replace")
str_path = str(path)
stem = _file_stem(path)
# Only keep the file node from the tree-sitter pass (guaranteed present and
# correctly IDed) plus all import edges. All other ts nodes are discarded to
# avoid orphaned method/constructor nodes whose parent edges were dropped.
file_node = next((n for n in ts_result.get("nodes", []) if n.get("label") == path.name), None)
nodes: list[dict] = [file_node] if file_node else []
edges: list[dict] = [e for e in ts_result.get("edges", []) if e.get("context") == "import"]
seen_ids: set[str] = {n["id"] for n in nodes}
def _add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": label,
"file_type": "code",
"source_file": str_path,
"source_location": f"L{line}",
})
def _add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED") -> None:
edges.append({
"source": src,
"target": tgt,
"relation": relation,
"confidence": confidence,
"source_file": str_path,
"source_location": f"L{line}",
"weight": 1.0,
})
lines_text = source.splitlines()
# Extract class declarations
class_re = _re.compile(r"^\s*(?:[\w@]+\s+)*class\s+(\w+)")
# Extract Spock feature methods: def "..." () or def '...' ()
# Two separate capture groups per quote style so apostrophes inside
# double-quoted names (e.g. "shouldn't") are captured correctly.
feature_re = _re.compile(r"""^\s*def\s+(?:\"([^\"]+)\"|'([^']+)')\s*\(""")
# Extract plain def methods (non-string names) as well
plain_method_re = _re.compile(r"""^\s*def\s+(\w+)\s*\(""")
current_class_nid: str | None = None
file_nid = _make_id(str_path)
# Ensure the file node exists (tree-sitter pass may have emitted it)
if file_nid not in seen_ids:
_add_node(file_nid, path.name, 1)
for lineno, line_text in enumerate(lines_text, start=1):
cm = class_re.match(line_text)
if cm:
class_name = cm.group(1)
class_nid = _make_id(stem, class_name)
_add_node(class_nid, class_name, lineno)
_add_edge(file_nid, class_nid, "contains", lineno)
current_class_nid = class_nid
continue
if current_class_nid is None:
continue
fm = feature_re.match(line_text)
if fm:
method_name = fm.group(1) or fm.group(2)
method_label = f'"{method_name}"'
method_nid = _make_id(current_class_nid, method_name)
_add_node(method_nid, method_label, lineno)
_add_edge(current_class_nid, method_nid, "method", lineno)
continue
pm = plain_method_re.match(line_text)
if pm:
method_name = pm.group(1)
if method_name not in ("if", "while", "for", "switch", "catch"):
method_label = f".{method_name}()"
method_nid = _make_id(current_class_nid, method_name)
_add_node(method_nid, method_label, lineno)
_add_edge(current_class_nid, method_nid, "method", lineno)
return {"nodes": nodes, "edges": edges}
def extract_groovy(path: Path) -> dict:
"""Extract classes, methods, constructors, and imports from a .groovy/.gradle file.
Falls back to a regex-based Spock extractor when tree-sitter-groovy cannot parse
``def "feature name"()`` methods (common in Spock specification classes).
"""
result = _extract_generic(path, _GROOVY_CONFIG)
if _is_spock_file(path, result):
result = _extract_spock_fallback(path, result)
return result
def extract_c(path: Path) -> dict:
"""Extract functions and includes from a .c/.h file."""
return _extract_generic(path, _C_CONFIG)
@@ -2257,6 +2673,203 @@ def extract_julia(path: Path) -> dict:
return {"nodes": nodes, "edges": edges}
_FORTRAN_CPP_EXTS = {".F", ".F90", ".F95", ".F03", ".F08"}
def _cpp_preprocess(path: Path) -> bytes:
"""Run cpp -w -P on a capital-F Fortran file and return preprocessed bytes.
Falls back to raw file bytes if cpp is not available. Capital-F extensions
conventionally require C preprocessor expansion (#ifdef MPI, #define REAL8, etc.)
before parsing.
"""
import shutil
import subprocess
if not shutil.which("cpp"):
return path.read_bytes()
try:
result = subprocess.run(
["cpp", "-w", "-P", str(path)],
capture_output=True,
timeout=30,
)
if result.returncode == 0 and result.stdout:
return result.stdout
except Exception:
pass
return path.read_bytes()
def extract_fortran(path: Path) -> dict:
"""Extract programs, modules, subroutines, functions, use statements, and calls from Fortran files.
Capital-F extensions (.F, .F90, etc.) are run through the C preprocessor before
parsing so #ifdef/#define macros are resolved.
"""
try:
import tree_sitter_fortran as tsfortran
from tree_sitter import Language, Parser
except ImportError:
return {"nodes": [], "edges": [], "error": "tree-sitter-fortran not installed"}
try:
language = Language(tsfortran.language())
parser = Parser(language)
source = _cpp_preprocess(path) if path.suffix in _FORTRAN_CPP_EXTS else path.read_bytes()
tree = parser.parse(source)
root = tree.root_node
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
scope_bodies: list[tuple[str, object]] = []
def add_node(nid: str, label: str, line: int) -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({
"id": nid,
"label": label,
"file_type": "code",
"source_file": str_path,
"source_location": f"L{line}",
})
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0,
context: str | None = None) -> None:
edge = {
"source": src,
"target": tgt,
"relation": relation,
"confidence": confidence,
"source_file": str_path,
"source_location": f"L{line}",
"weight": weight,
}
if context:
edge["context"] = context
edges.append(edge)
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
def _fortran_name(stmt_node) -> str | None:
"""Extract name from a *_statement node. Fortran is case-insensitive; lowercase."""
for child in stmt_node.children:
if child.type in ("name", "identifier"):
return _read_text(child, source).lower()
return None
def walk_calls(node, scope_nid: str) -> None:
if node is None:
return
t = node.type
if t in ("subroutine", "function", "module", "program", "internal_procedures"):
return
# call FOO(args) — tree-sitter-fortran uses subroutine_call
if t == "subroutine_call":
name_node = next((c for c in node.children if c.type == "identifier"), None)
if name_node:
callee = _read_text(name_node, source).lower()
target_nid = _make_id(stem, callee)
add_edge(scope_nid, target_nid, "calls", node.start_point[0] + 1,
confidence="EXTRACTED", context="call")
for child in node.children:
walk_calls(child, scope_nid)
def walk(node, scope_nid: str) -> None:
t = node.type
if t == "program":
stmt = next((c for c in node.children if c.type == "program_statement"), None)
name = _fortran_name(stmt) if stmt else None
if name:
nid = _make_id(stem, name)
line = node.start_point[0] + 1
add_node(nid, name, line)
add_edge(file_nid, nid, "defines", line)
scope_bodies.append((nid, node))
for child in node.children:
walk(child, nid)
return
if t == "module":
stmt = next((c for c in node.children if c.type == "module_statement"), None)
name = _fortran_name(stmt) if stmt else None
if name:
nid = _make_id(stem, name)
line = node.start_point[0] + 1
add_node(nid, name, line)
add_edge(file_nid, nid, "defines", line)
for child in node.children:
walk(child, nid)
return
# subroutines/functions inside a module live under internal_procedures
if t == "internal_procedures":
for child in node.children:
walk(child, scope_nid)
return
if t == "subroutine":
stmt = next((c for c in node.children if c.type == "subroutine_statement"), None)
name = _fortran_name(stmt) if stmt else None
if name:
nid = _make_id(stem, name)
line = node.start_point[0] + 1
add_node(nid, f"{name}()", line)
add_edge(scope_nid, nid, "defines", line)
scope_bodies.append((nid, node))
for child in node.children:
walk(child, nid)
return
if t == "function":
stmt = next((c for c in node.children if c.type == "function_statement"), None)
name = _fortran_name(stmt) if stmt else None
if name:
nid = _make_id(stem, name)
line = node.start_point[0] + 1
add_node(nid, f"{name}()", line)
add_edge(scope_nid, nid, "defines", line)
scope_bodies.append((nid, node))
for child in node.children:
walk(child, nid)
return
if t == "use_statement":
line = node.start_point[0] + 1
# tree-sitter-fortran uses module_name node for the used module
name_node = next((c for c in node.children if c.type in ("module_name", "name", "identifier")), None)
if name_node:
mod_name = _read_text(name_node, source).lower()
imp_nid = _make_id(mod_name)
add_node(imp_nid, mod_name, line)
add_edge(scope_nid, imp_nid, "imports", line, context="use")
return
for child in node.children:
walk(child, scope_nid)
walk(root, file_nid)
_stmt_headers = {
"subroutine_statement", "function_statement",
"program_statement", "module_statement",
}
for scope_nid, body_node in scope_bodies:
for child in body_node.children:
if child.type not in _stmt_headers:
walk_calls(child, scope_nid)
return {"nodes": nodes, "edges": edges}
# ── Go extractor (custom walk) ────────────────────────────────────────────────
def extract_go(path: Path) -> dict:
@@ -3629,6 +4242,116 @@ def extract_elixir(path: Path) -> dict:
return {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls, "input_tokens": 0, "output_tokens": 0}
def extract_markdown(path: Path) -> dict:
"""Extract structural nodes and edges from a Markdown file.
Produces nodes for:
- The file itself
- Each heading (# / ## / ### etc.)
- Each fenced code block (``` ... ```)
Produces edges for:
- file --contains--> heading
- parent heading --contains--> child heading (nesting by level)
- heading --contains--> code block
- heading --references--> other node (when backtick `Name` matches a known pattern)
No tree-sitter dependency — pure line-by-line parsing.
"""
try:
source = path.read_text(encoding="utf-8", errors="replace")
except Exception as e:
return {"nodes": [], "edges": [], "error": str(e)}
stem = _file_stem(path)
str_path = str(path)
nodes: list[dict] = []
edges: list[dict] = []
seen_ids: set[str] = set()
def add_node(nid: str, label: str, line: int, file_type: str = "document") -> None:
if nid not in seen_ids:
seen_ids.add(nid)
nodes.append({"id": nid, "label": label, "file_type": file_type,
"source_file": str_path, "source_location": f"L{line}"})
def add_edge(src: str, tgt: str, relation: str, line: int,
confidence: str = "EXTRACTED", weight: float = 1.0) -> None:
edges.append({"source": src, "target": tgt, "relation": relation,
"confidence": confidence, "source_file": str_path,
"source_location": f"L{line}", "weight": weight})
file_nid = _make_id(str(path))
add_node(file_nid, path.name, 1)
# Track heading stack for nesting: [(level, nid), ...]
heading_stack: list[tuple[int, str]] = []
in_code_block = False
code_block_lang: str | None = None
code_block_start: int = 0
code_block_lines: list[str] = []
code_block_count = 0
lines = source.splitlines()
for line_num_0, line_text in enumerate(lines):
line_num = line_num_0 + 1
# Toggle fenced code blocks
stripped = line_text.strip()
if stripped.startswith("```"):
if not in_code_block:
in_code_block = True
code_block_lang = stripped[3:].strip().split()[0] if len(stripped) > 3 else None
code_block_start = line_num
code_block_lines = []
continue
else:
# End of code block — create a node
in_code_block = False
code_block_count += 1
snippet = "\n".join(code_block_lines[:3]) # first 3 lines as preview
label = f"code:{code_block_lang}" if code_block_lang else f"code:block{code_block_count}"
if snippet:
# Use first meaningful line as label hint
first_line = code_block_lines[0].strip()[:60] if code_block_lines else ""
if first_line:
label = f"{label} ({first_line})"
cb_nid = _make_id(stem, f"codeblock_{code_block_count}")
add_node(cb_nid, label, code_block_start)
# Attach to nearest heading or file
parent = heading_stack[-1][1] if heading_stack else file_nid
add_edge(parent, cb_nid, "contains", code_block_start)
continue
if in_code_block:
code_block_lines.append(line_text)
continue
# Detect headings: # Heading, ## Heading, etc.
heading_match = re.match(r'^(#{1,6})\s+(.+)', line_text)
if heading_match:
level = len(heading_match.group(1))
title = heading_match.group(2).strip()
h_nid = _make_id(stem, title)
# Avoid duplicate heading IDs by appending line number
if h_nid in seen_ids:
h_nid = _make_id(stem, title, str(line_num))
add_node(h_nid, title, line_num)
# Pop headings at same or deeper level
while heading_stack and heading_stack[-1][0] >= level:
heading_stack.pop()
# Connect to parent heading or file
parent = heading_stack[-1][1] if heading_stack else file_nid
add_edge(parent, h_nid, "contains", line_num)
heading_stack.append((level, h_nid))
continue
return {"nodes": nodes, "edges": edges, "input_tokens": 0, "output_tokens": 0}
# ── Main extract and collect_files ────────────────────────────────────────────
@@ -3660,6 +4383,8 @@ _DISPATCH: dict[str, Any] = {
".go": extract_go,
".rs": extract_rust,
".java": extract_java,
".groovy": extract_groovy,
".gradle": extract_groovy,
".c": extract_c,
".h": extract_c,
".cpp": extract_cpp,
@@ -3674,6 +4399,7 @@ _DISPATCH: dict[str, Any] = {
".php": extract_php,
".swift": extract_swift,
".lua": extract_lua,
".luau": extract_lua,
".toc": extract_lua,
".zig": extract_zig,
".ps1": extract_powershell,
@@ -3682,12 +4408,24 @@ _DISPATCH: dict[str, Any] = {
".m": extract_objc,
".mm": extract_objc,
".jl": extract_julia,
".f": extract_fortran,
".F": extract_fortran,
".f90": extract_fortran,
".F90": extract_fortran,
".f95": extract_fortran,
".F95": extract_fortran,
".f03": extract_fortran,
".F03": extract_fortran,
".f08": extract_fortran,
".F08": extract_fortran,
".vue": extract_js,
".svelte": extract_js,
".svelte": extract_svelte,
".dart": extract_dart,
".v": extract_verilog,
".sv": extract_verilog,
".sql": extract_sql,
".md": extract_markdown,
".mdx": extract_markdown,
}
@@ -3713,6 +4451,7 @@ def _extract_single_file(args: tuple) -> tuple[int, dict]:
idx, path_str, cache_root_str = args
path = Path(path_str)
cache_root = Path(cache_root_str)
_raise_recursion_limit()
# Check cache first (avoid re-extraction)
cached = load_cached(path, cache_root)
@@ -3723,7 +4462,7 @@ def _extract_single_file(args: tuple) -> tuple[int, dict]:
if extractor is None:
return idx, {"nodes": [], "edges": []}
result = extractor(path)
result = _safe_extract(extractor, path)
if "error" not in result:
save_cached(path, result, cache_root)
return idx, result
@@ -3793,7 +4532,7 @@ def _extract_sequential(
if extractor is None:
per_file[idx] = {"nodes": [], "edges": []}
continue
result = extractor(path)
result = _safe_extract(extractor, path)
if "error" not in result:
save_cached(path, result, effective_root)
per_file[idx] = result
@@ -3828,6 +4567,7 @@ def extract(
max_workers: max subprocess count. Defaults to min(cpu_count, 8).
"""
_check_tree_sitter_version()
_raise_recursion_limit()
# Infer a common root for cache keys (use first diverging segment, not sum of all matches)
try:
@@ -4002,13 +4742,7 @@ def extract(
def collect_files(target: Path, *, follow_symlinks: bool = False, root: Path | None = None) -> list[Path]:
if target.is_file():
return [target]
_EXTENSIONS = {
".py", ".js", ".ts", ".tsx", ".go", ".rs",
".java", ".c", ".h", ".cpp", ".cc", ".cxx", ".hpp",
".rb", ".cs", ".kt", ".kts", ".scala", ".php", ".swift",
".lua", ".toc", ".zig", ".ps1",
".m", ".mm",
}
_EXTENSIONS = set(_DISPATCH.keys())
from graphify.detect import _load_graphifyignore, _is_ignored
ignore_root = root if root is not None else target
patterns = _load_graphifyignore(ignore_root)
+155
View File
@@ -0,0 +1,155 @@
from __future__ import annotations
import json
import hashlib
import sys
from datetime import datetime, timezone
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph as _jg
_GLOBAL_DIR = Path.home() / ".graphify"
_GLOBAL_GRAPH = _GLOBAL_DIR / "global-graph.json"
_GLOBAL_MANIFEST = _GLOBAL_DIR / "global-manifest.json"
def _load_manifest() -> dict:
if _GLOBAL_MANIFEST.exists():
try:
return json.loads(_GLOBAL_MANIFEST.read_text(encoding="utf-8"))
except Exception:
pass
return {"version": 1, "repos": {}}
def _save_manifest(manifest: dict) -> None:
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
_GLOBAL_MANIFEST.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
def _load_global_graph() -> nx.Graph:
if _GLOBAL_GRAPH.exists():
data = json.loads(_GLOBAL_GRAPH.read_text(encoding="utf-8"))
if "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
try:
return _jg.node_link_graph(data, edges="links")
except TypeError:
return _jg.node_link_graph(data)
return nx.Graph()
def _save_global_graph(G: nx.Graph) -> None:
_GLOBAL_DIR.mkdir(parents=True, exist_ok=True)
try:
data = _jg.node_link_data(G, edges="links")
except TypeError:
data = _jg.node_link_data(G)
_GLOBAL_GRAPH.write_text(json.dumps(data, indent=2), encoding="utf-8")
def _file_hash(path: Path) -> str:
h = hashlib.sha256()
h.update(path.read_bytes())
return h.hexdigest()[:16]
def global_add(source_path: Path, repo_tag: str) -> dict:
"""Add or update a project graph in the global graph.
Returns a summary dict with keys: repo_tag, nodes_added, nodes_removed, skipped.
Skipped=True means the source graph hasn't changed since last add.
"""
from graphify.build import prefix_graph_for_global, prune_repo_from_graph
if not source_path.exists():
raise FileNotFoundError(f"graph not found: {source_path}")
manifest = _load_manifest()
src_hash = _file_hash(source_path)
existing = manifest["repos"].get(repo_tag, {})
existing_path = existing.get("source_path", "")
if existing_path and existing_path != str(source_path.resolve()):
print(
f"[graphify global] warning: repo tag '{repo_tag}' previously pointed to "
f"{existing_path!r}, now updating to {str(source_path.resolve())!r}. "
f"Use --as <tag> to give it a different name.",
file=sys.stderr,
)
if existing.get("source_hash") == src_hash:
return {"repo_tag": repo_tag, "nodes_added": 0, "nodes_removed": 0, "skipped": True}
# Load source graph
data = json.loads(source_path.read_text(encoding="utf-8"))
if "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
try:
src_G = _jg.node_link_graph(data, edges="links")
except TypeError:
src_G = _jg.node_link_graph(data)
# Prefix IDs for cross-project isolation
prefixed = prefix_graph_for_global(src_G, repo_tag)
# Load global graph and prune stale nodes for this repo
G = _load_global_graph()
removed = prune_repo_from_graph(G, repo_tag)
# Merge external-library nodes (no source_file) by label to avoid duplication
external_labels = {
d.get("label", ""): n
for n, d in G.nodes(data=True)
if not d.get("source_file") and d.get("label")
}
nodes_to_skip = set()
for node, data in prefixed.nodes(data=True):
if not data.get("source_file") and data.get("label") in external_labels:
nodes_to_skip.add(node)
# Compose: add prefixed nodes (except deduplicated externals) into global graph
for node, data in prefixed.nodes(data=True):
if node not in nodes_to_skip:
G.add_node(node, **data)
for u, v, data in prefixed.edges(data=True):
if u not in nodes_to_skip and v not in nodes_to_skip:
G.add_edge(u, v, **data)
added = prefixed.number_of_nodes() - len(nodes_to_skip)
_save_global_graph(G)
manifest["repos"][repo_tag] = {
"added_at": datetime.now(timezone.utc).isoformat(),
"source_path": str(source_path.resolve()),
"node_count": added,
"edge_count": prefixed.number_of_edges(),
"source_hash": src_hash,
}
_save_manifest(manifest)
return {"repo_tag": repo_tag, "nodes_added": added, "nodes_removed": removed, "skipped": False}
def global_remove(repo_tag: str) -> int:
"""Remove all nodes for repo_tag from the global graph. Returns count removed."""
from graphify.build import prune_repo_from_graph
manifest = _load_manifest()
if repo_tag not in manifest["repos"]:
raise KeyError(f"repo '{repo_tag}' not in global graph")
G = _load_global_graph()
removed = prune_repo_from_graph(G, repo_tag)
_save_global_graph(G)
del manifest["repos"][repo_tag]
_save_manifest(manifest)
return removed
def global_list() -> dict:
"""Return the manifest repos dict."""
return _load_manifest().get("repos", {})
def global_path() -> Path:
return _GLOBAL_GRAPH
+17 -12
View File
@@ -1,7 +1,7 @@
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
from __future__ import annotations
import configparser
import re
import subprocess
from pathlib import Path
_HOOK_MARKER = "# graphify-hook-start"
@@ -151,19 +151,24 @@ def _git_root(path: Path) -> Path | None:
def _hooks_dir(root: Path) -> Path:
"""Return the git hooks directory, respecting core.hooksPath if set (e.g. Husky)."""
try:
result = subprocess.run(
["git", "-C", str(root), "config", "core.hooksPath"],
capture_output=True, text=True,
)
if result.returncode == 0:
custom = result.stdout.strip()
if custom:
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
cfg = configparser.RawConfigParser()
cfg.read(root / ".git" / "config", encoding="utf-8")
# configparser lowercases option names; git's hooksPath becomes hookspath
custom = cfg.get("core", "hookspath", fallback="").strip()
if custom:
p = Path(custom).expanduser()
if not p.is_absolute():
p = root / p
# Validate the resolved path stays within the repository root
# to prevent supply-chain attacks via malicious core.hooksPath values
try:
p.resolve().relative_to(root.resolve())
except ValueError:
pass # Path escapes repo root; fall through to default .git/hooks
else:
p.mkdir(parents=True, exist_ok=True)
return p
except (OSError, FileNotFoundError):
except Exception:
pass
d = root / ".git" / "hooks"
d.mkdir(exist_ok=True)
+125 -17
View File
@@ -1,5 +1,6 @@
# Direct LLM backend for semantic extraction — supports Claude and Kimi K2.6.
# Used by `graphify . --backend kimi` and the benchmark scripts.
# Direct LLM backend for semantic extraction — supports Claude, Kimi K2.6,
# Gemini, and OpenAI.
# Used by `graphify extract . --backend gemini` and the benchmark scripts.
# The default graphify pipeline uses Claude Code subagents via skill.md;
# this module provides a direct API path for non-Claude-Code environments.
from __future__ import annotations
@@ -50,6 +51,7 @@ BACKENDS: dict[str, dict] = {
"env_key": "ANTHROPIC_API_KEY",
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
"temperature": 0,
"max_tokens": 16384,
},
"kimi": {
"base_url": "https://api.moonshot.ai/v1",
@@ -57,9 +59,49 @@ BACKENDS: dict[str, dict] = {
"env_key": "MOONSHOT_API_KEY",
"pricing": {"input": 0.74, "output": 4.66}, # USD per 1M tokens
"temperature": None, # kimi-k2.6 enforces its own fixed temperature; sending any value raises 400
"max_tokens": 16384,
},
"ollama": {
"base_url": os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434/v1"),
"default_model": os.environ.get("OLLAMA_MODEL", "qwen2.5-coder:7b"),
"env_key": "OLLAMA_API_KEY",
"pricing": {"input": 0.0, "output": 0.0},
"temperature": 0,
"max_tokens": 16384,
},
"gemini": {
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai/",
"default_model": "gemini-3-flash-preview",
"env_keys": ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
"model_env_key": "GRAPHIFY_GEMINI_MODEL",
"pricing": {"input": 0.50, "output": 3.00}, # USD per 1M tokens
"temperature": 0,
"reasoning_effort": "low",
"max_completion_tokens": 16384,
},
"openai": {
"base_url": "https://api.openai.com/v1",
"default_model": "gpt-4.1-mini",
"env_key": "OPENAI_API_KEY",
"model_env_key": "GRAPHIFY_OPENAI_MODEL",
"pricing": {"input": 0.40, "output": 1.60}, # USD per 1M tokens
"temperature": 0,
},
}
def _resolve_max_tokens(default: int) -> int:
"""Honour GRAPHIFY_MAX_OUTPUT_TOKENS env var override, else use backend default."""
raw = os.environ.get("GRAPHIFY_MAX_OUTPUT_TOKENS", "").strip()
if raw:
try:
v = int(raw)
if v > 0:
return v
except ValueError:
pass
return default
_EXTRACTION_SYSTEM = """\
You are a graphify semantic extraction agent. Extract a knowledge graph fragment from the files provided.
Output ONLY valid JSON — no explanation, no markdown fences, no preamble.
@@ -107,20 +149,59 @@ def _parse_llm_json(raw: str) -> dict:
return {"nodes": [], "edges": [], "hyperedges": []}
def _backend_env_keys(backend: str) -> list[str]:
"""Return accepted API-key environment variables for a backend."""
cfg = BACKENDS[backend]
keys = cfg.get("env_keys")
if keys:
return list(keys)
return [cfg["env_key"]]
def _get_backend_api_key(backend: str) -> str:
"""Return the first configured API key for backend, or an empty string."""
for env_key in _backend_env_keys(backend):
value = os.environ.get(env_key)
if value:
return value
return ""
def _format_backend_env_keys(backend: str) -> str:
"""Return user-facing accepted API-key variable names."""
return " or ".join(_backend_env_keys(backend))
def _default_model_for_backend(backend: str) -> str:
"""Return configured model override or backend default model."""
cfg = BACKENDS[backend]
model_env_key = cfg.get("model_env_key")
if model_env_key:
model = os.environ.get(model_env_key)
if model:
return model
return cfg["default_model"]
def _call_openai_compat(
base_url: str,
api_key: str,
model: str,
user_message: str,
temperature: float | None = 0,
reasoning_effort: str | None = None,
max_completion_tokens: int = 8192,
*,
backend: str = "",
) -> dict:
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
try:
from openai import OpenAI
except ImportError as exc:
pkg_hint = "graphifyy[kimi]" if backend == "kimi" else "openai"
raise ImportError(
"Kimi/OpenAI-compatible extraction requires the openai package. "
"Run: pip install openai"
"Gemini/Kimi/Ollama/OpenAI-compatible extraction requires the openai package. "
f"Run: pip install {pkg_hint}"
) from exc
client = OpenAI(api_key=api_key, base_url=base_url)
@@ -130,10 +211,12 @@ def _call_openai_compat(
{"role": "system", "content": _EXTRACTION_SYSTEM},
{"role": "user", "content": user_message},
],
"max_completion_tokens": 8192,
"max_completion_tokens": max_completion_tokens,
}
if temperature is not None:
kwargs["temperature"] = temperature
if reasoning_effort is not None:
kwargs["reasoning_effort"] = reasoning_effort
# Kimi-k2.6 is a reasoning model — disable thinking so content isn't empty
if "moonshot" in base_url:
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
@@ -146,10 +229,18 @@ def _call_openai_compat(
# mid-generation. The JSON we got back is truncated; callers should
# treat this as a signal to retry with smaller input.
result["finish_reason"] = resp.choices[0].finish_reason
output_tokens = result["output_tokens"]
if output_tokens < 50 and backend == "ollama":
print(
"[graphify] warning: ollama returned very few tokens — the model may be "
"too small or not following the JSON instruction format. "
"Try a larger model with --model (e.g. --model qwen2.5-coder:14b).",
file=sys.stderr,
)
return result
def _call_claude(api_key: str, model: str, user_message: str) -> dict:
def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int = 8192) -> dict:
"""Call Anthropic Claude directly (not via OpenAI compat layer)."""
try:
import anthropic
@@ -162,7 +253,7 @@ def _call_claude(api_key: str, model: str, user_message: str) -> dict:
client = anthropic.Anthropic(api_key=api_key)
resp = client.messages.create(
model=model,
max_tokens=8192,
max_tokens=max_tokens,
system=_EXTRACTION_SYSTEM,
messages=[{"role": "user", "content": user_message}],
)
@@ -193,19 +284,31 @@ def extract_files_direct(
raise ValueError(f"Unknown backend {backend!r}. Available: {sorted(BACKENDS)}")
cfg = BACKENDS[backend]
key = api_key or os.environ.get(cfg["env_key"], "")
key = api_key or _get_backend_api_key(backend)
if not key and backend == "ollama":
key = "ollama" # Ollama ignores auth but openai client requires non-empty
if not key:
raise ValueError(
f"No API key for backend '{backend}'. "
f"Set {cfg['env_key']} or pass api_key=."
f"Set {_format_backend_env_keys(backend)} or pass api_key=."
)
mdl = model or cfg["default_model"]
mdl = model or _default_model_for_backend(backend)
user_msg = _read_files(files, root)
max_out = _resolve_max_tokens(cfg.get("max_tokens", 8192))
if backend == "claude":
return _call_claude(key, mdl, user_msg)
return _call_claude(key, mdl, user_msg, max_tokens=max_out)
else:
return _call_openai_compat(cfg["base_url"], key, mdl, user_msg, temperature=cfg.get("temperature", 0))
return _call_openai_compat(
cfg["base_url"],
key,
mdl,
user_msg,
temperature=cfg.get("temperature", 0),
reasoning_effort=cfg.get("reasoning_effort"),
max_completion_tokens=cfg.get("max_completion_tokens", max_out),
backend=backend,
)
def _estimate_file_tokens(path: Path) -> int:
@@ -468,11 +571,16 @@ def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
def detect_backend() -> str | None:
"""Return the name of whichever backend has an API key set, or None.
Kimi is checked first (opt-in). Falls back to Claude if ANTHROPIC_API_KEY is set.
Priority: gemini → kimi → ollama (opt-in via OLLAMA_BASE_URL) → claude → openai.
Ollama is opt-in via env var — never auto-probed without OLLAMA_BASE_URL set.
Claude is the default for the skill.md subagent pipeline and is never forced here.
"""
if os.environ.get("MOONSHOT_API_KEY"):
return "kimi"
if os.environ.get("ANTHROPIC_API_KEY"):
return "claude"
for backend in ("gemini", "kimi"):
if _get_backend_api_key(backend):
return backend
if os.environ.get("OLLAMA_BASE_URL"):
return "ollama"
for backend in ("claude", "openai"):
if _get_backend_api_key(backend):
return backend
return None
+18 -6
View File
@@ -24,6 +24,7 @@ def generate(
root: str,
suggested_questions: list[dict] | None = None,
min_community_size: int = 3,
built_at_commit: str | None = None,
) -> str:
today = date.today().isoformat()
@@ -53,16 +54,31 @@ def generate(
from .analyze import _is_file_node as _ifn
non_empty = {cid: nodes for cid, nodes in communities.items()
if any(not _ifn(G, n) for n in nodes)}
thin_count_summary = sum(
1 for nodes in communities.values()
if 0 < sum(1 for n in nodes if not _ifn(G, n)) < min_community_size
)
shown_count = len(communities) - thin_count_summary
lines += [
"",
"## Summary",
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(non_empty)} communities detected",
f"- {G.number_of_nodes()} nodes · {G.number_of_edges()} edges · {len(communities)} communities"
+ (f" ({shown_count} shown, {thin_count_summary} thin omitted)" if thin_count_summary else ""),
f"- Extraction: {ext_pct}% EXTRACTED · {inf_pct}% INFERRED · {amb_pct}% AMBIGUOUS"
+ (f" · INFERRED: {len(inf_edges)} edges (avg confidence: {inf_avg})" if inf_avg is not None else ""),
f"- Token cost: {token_cost.get('input', 0):,} input · {token_cost.get('output', 0):,} output",
]
if built_at_commit:
lines += [
"",
"## Graph Freshness",
f"- Built from commit: `{built_at_commit[:8]}`",
"- Run `git rev-parse HEAD` and compare to check if the graph is stale.",
"- Run `graphify update .` after code changes (no API cost).",
]
# Community hub navigation - links to _COMMUNITY_*.md files in the Obsidian vault.
# Without these, GRAPH_REPORT.md is a dead-end and the vault splits into disconnected components.
if non_empty:
@@ -109,11 +125,7 @@ def generate(
conf_tag = f"{conf} {cscore:.2f}" if cscore is not None else conf
lines.append(f"- **{h.get('label', h.get('id', ''))}** — {node_labels} [{conf_tag}]")
thin_count = sum(
1 for nodes in communities.values()
if 0 < sum(1 for n in nodes if not _ifn(G, n)) < min_community_size
)
lines += ["", f"## Communities ({len(communities)} total, {thin_count} thin omitted)"]
lines += ["", f"## Communities ({len(communities)} total, {thin_count_summary} thin omitted)"]
for cid, nodes in communities.items():
label = community_labels.get(cid, f"Community {cid}")
score = cohesion_scores.get(cid, 0.0)
+4 -1
View File
@@ -843,7 +843,10 @@ deleted = set(incremental.get('deleted_files', []))
if deleted:
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
G_existing.remove_nodes_from(to_remove)
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
if to_remove:
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s).')
else:
print(f'{len(deleted)} file(s) deleted since last run — no ghost nodes in graph, already clean.')
# Merge: new nodes/edges into existing graph
G_existing.update(G_new)
+1 -1
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: Turn any folder of files (code, docs, papers, images, video) into a queryable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md. Use when asked to analyze a codebase, understand architecture, map dependencies, or build a knowledge graph.
description: any input (code, docs, papers, images, video) → knowledge graph → clustered communities → HTML + JSON + GRAPH_REPORT.md
---
# /graphify
+25 -422
View File
@@ -43,18 +43,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
## What graphify is for
graphify is built around Andrej Karpathy's /raw folder workflow: drop anything into a folder - papers, tweets, screenshots, code, notes - and get a structured knowledge graph that shows you what you didn't know was connected.
Three things it does that Claude alone cannot:
1. **Persistent graph** - relationships are stored in `graphify-out/graph.json` and survive across sessions. Ask questions weeks later without re-reading everything.
2. **Honest audit trail** - every edge is tagged EXTRACTED, INFERRED, or AMBIGUOUS. You know what was found vs invented.
3. **Cross-document surprise** - community detection finds connections between concepts in different files that you would never think to ask about directly.
Use it for:
- A codebase you're new to (understand architecture before touching anything)
- A reading list (papers + tweets + notes → one navigable graph)
- A research corpus (citation graph + concept graph in one)
- Your personal /raw folder (drop everything in, let it grow, query it)
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
## What You Must Do When Invoked
@@ -202,10 +191,10 @@ After transcription:
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
**Before dispatching subagents:** check whether `MOONSHOT_API_KEY` is set. If it is NOT set, print this one-liner to the user:
> Tip: set `MOONSHOT_API_KEY` to use Kimi K2.6 for semantic extraction — 3x cheaper, richer graphs (`pip install 'graphifyy[kimi]'`).
**Before dispatching subagents:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
Print it once, then continue. If `MOONSHOT_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="kimi")` for semantic extraction instead of dispatching Claude subagents.
Print it once, then continue. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching Claude subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
@@ -566,84 +555,18 @@ Replace INPUT_PATH with the actual path.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, use that path as the vault directory. Otherwise default to `graphify-out/obsidian`.
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
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())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
obsidian_dir = 'OBSIDIAN_DIR' # replace with --obsidian-dir value, or 'graphify-out/obsidian' if not given
n = to_obsidian(G, communities, obsidian_dir, community_labels=labels or None, cohesion=cohesion)
print(f'Obsidian vault: {n} notes in {obsidian_dir}/')
to_canvas(G, communities, f'{obsidian_dir}/graph.canvas', community_labels=labels or None)
print(f'Canvas: {obsidian_dir}/graph.canvas - open in Obsidian for structured community layout')
print()
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')
"
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
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())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
NODE_LIMIT = 5000
if G.number_of_nodes() > NODE_LIMIT:
from collections import Counter
print(f'Graph has {G.number_of_nodes()} nodes (above {NODE_LIMIT} limit). Building aggregated community view...')
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
import networkx as nx_meta
meta = nx_meta.Graph()
for cid, members in communities.items():
meta.add_node(str(cid), label=labels.get(cid, f'Community {cid}'))
edge_counts = Counter()
for u, v in G.edges():
cu, cv = node_to_community.get(u), node_to_community.get(v)
if cu is not None and cv is not None and cu != cv:
edge_counts[(min(cu, cv), max(cu, cv))] += 1
for (cu, cv), w in edge_counts.items():
meta.add_edge(str(cu), str(cv), weight=w, relation=f'{w} cross-community edges', confidence='AGGREGATED')
if meta.number_of_nodes() > 1:
meta_communities = {cid: [str(cid)] for cid in communities}
member_counts = {cid: len(members) for cid, members in communities.items()}
to_html(meta, meta_communities, 'graphify-out/graph.html', community_labels=labels or None, member_counts=member_counts)
print(f'graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)')
print('Tip: run with --obsidian for full node-level detail.')
else:
print('Single community — aggregated view not useful. Skipping graph.html.')
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')
"
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Step 6b - Wiki (only if --wiki flag)
@@ -653,27 +576,7 @@ else:
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.build import build_from_json
from graphify.wiki import to_wiki
from graphify.analyze import god_nodes
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
labels = {int(k): v for k, v in labels_raw.items()}
gods = god_nodes(G)
n = to_wiki(G, communities, 'graphify-out/wiki', community_labels=labels or None, cohesion=cohesion, god_nodes_data=gods)
print(f'Wiki: {n} articles written to graphify-out/wiki/')
print(' graphify-out/wiki/index.md -> agent entry point')
"
graphify export wiki
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
@@ -681,80 +584,27 @@ print(' graphify-out/wiki/index.md -> agent entry point')
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
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()))
to_cypher(G, 'graphify-out/cypher.txt')
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
"
graphify export neo4j
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
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())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
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')
"
graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD
```
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.
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7b - SVG export (only if --svg flag)
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
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())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
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')
"
graphify export svg
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
$(cat graphify-out/.graphify_python) -c "
import json
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())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
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')
"
graphify export graphml
```
### Step 7d - MCP server (only if --mcp flag)
@@ -782,15 +632,7 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
$(cat graphify-out/.graphify_python) -c "
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())
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
print_benchmark(result)
"
graphify benchmark
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
@@ -916,7 +758,7 @@ import json
from pathlib import Path
result = json.loads(open('graphify-out/.graphify_incremental.json').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
@@ -1019,45 +861,10 @@ Clean up after: `rm -f graphify-out/.graphify_old.json`
## For --cluster-only
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
Skip Steps 1–3. Re-run clustering on the existing graph:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
from graphify.report import generate
from graphify.export import to_json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output': 0}
communities = cluster(G)
cohesion = score_all(G, communities)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.')
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
to_json(G, communities, 'graphify-out/graph.json')
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
print(f'Re-clustered: {len(communities)} communities')
"
graphify cluster-only .
```
Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).
@@ -1073,113 +880,12 @@ Two traversal modes - choose based on the question:
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
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)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
Load `graphify-out/graph.json`, then:
1. Find the 1-3 nodes whose label best matches key terms in the question.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
mode = 'MODE' # 'bfs' or 'dfs'
terms = [t.lower() for t in question.split() if len(t) > 3]
# Find best-matching start nodes
scored = []
for nid, ndata in G.nodes(data=True):
label = ndata.get('label', '').lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
scored.sort(reverse=True)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
print('No matching nodes found for query terms:', terms)
sys.exit(0)
subgraph_nodes = set()
subgraph_edges = []
if mode == 'dfs':
# DFS: follow one path as deep as possible before backtracking.
# Depth-limited to 6 to avoid traversing the whole graph.
visited = set()
stack = [(n, 0) for n in reversed(start_nodes)]
while stack:
node, depth = stack.pop()
if node in visited or depth > 6:
continue
visited.add(node)
subgraph_nodes.add(node)
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, depth + 1))
subgraph_edges.append((node, neighbor))
else:
# BFS: explore all neighbors layer by layer up to depth 3.
frontier = set(start_nodes)
subgraph_nodes = set(start_nodes)
for _ in range(3):
next_frontier = set()
for n in frontier:
for neighbor in G.neighbors(n):
if neighbor not in subgraph_nodes:
next_frontier.add(neighbor)
subgraph_edges.append((n, neighbor))
subgraph_nodes.update(next_frontier)
frontier = next_frontier
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
token_budget = BUDGET # default 2000
char_budget = token_budget * 4
# Score each node by term overlap for ranked output
def relevance(nid):
label = G.nodes[nid].get('label', '').lower()
return sum(1 for t in terms if t in label)
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
for nid in ranked_nodes:
d = G.nodes[nid]
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
d = G.edges[u, v]
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{d.get(\"relation\",\"\")} [{d.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
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)
"
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
```
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.
Replace `QUESTION` with the user's actual question. Answer using **only** what the graph output contains. Quote `source_location` when citing a specific fact. If the graph lacks enough information, say so - do not hallucinate edges.
After writing the answer, save it back into the graph so it improves future queries:
@@ -1195,66 +901,11 @@ Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOUR
Find the shortest path between two named concepts in the graph.
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
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)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
b_term = 'NODE_B'
def find_node(term):
term = term.lower()
scored = sorted(
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
return scored[0][1] if scored and scored[0][0] > 0 else None
src = find_node(a_term)
tgt = find_node(b_term)
if not src or not tgt:
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
sys.exit(0)
try:
path = nx.shortest_path(G, src, tgt)
print(f'Shortest path ({len(path)-1} hops):')
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
edge = G.edges[nid, path[i+1]]
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
else:
print(f' {label}')
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}')
"
graphify path "NODE_A" "NODE_B"
```
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.
Replace `NODE_A` and `NODE_B` with the actual concept names. Then explain the path in plain language - what each hop means, why it's significant.
After writing the explanation, save it back:
@@ -1268,56 +919,8 @@ $(cat graphify-out/.graphify_python) -m graphify save-result --question "Path fr
Give a plain-language explanation of a single node - everything connected to it.
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
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)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
term_lower = term.lower()
# Find best matching node
scored = sorted(
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
if not scored or scored[0][0] == 0:
print(f'No node matching {term!r}')
sys.exit(0)
nid = scored[0][1]
data_n = G.nodes[nid]
print(f'NODE: {data_n.get(\"label\", nid)}')
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
"
graphify explain "NODE_NAME"
```
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.
+36 -6
View File
@@ -9,6 +9,16 @@ from pathlib import Path
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
def _git_head() -> str | None:
"""Return current git HEAD commit hash, or None outside a repo."""
import subprocess as _sp
try:
r = _sp.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=3)
return r.stdout.strip() if r.returncode == 0 else None
except Exception:
return None
from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
_WATCHED_EXTENSIONS = CODE_EXTENSIONS | DOC_EXTENSIONS | PAPER_EXTENSIONS | IMAGE_EXTENSIONS
@@ -60,10 +70,18 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False, force: boo
detected = detect(watch_path, follow_symlinks=follow_symlinks)
code_files = [Path(f) for f in detected['files']['code']]
# Include document files that have AST extractors (e.g. .md, .mdx)
from graphify.extract import _get_extractor
for doc_file in detected['files'].get('document', []):
p = Path(doc_file)
if _get_extractor(p) is not None:
code_files.append(p)
if not code_files:
print("[graphify watch] No code files found - nothing to rebuild.")
return False
commit = _git_head()
result = extract(code_files, cache_root=watch_root)
# Preserve semantic nodes/edges from a previous full run.
@@ -106,13 +124,22 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False, force: boo
cohesion = score_all(G, communities)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: "Community " + str(cid) for cid in communities}
labels_file = out / ".graphify_labels.json"
try:
raw = json.loads(labels_file.read_text(encoding="utf-8")) if labels_file.exists() else {}
labels = {int(k): v for k, v in raw.items() if int(k) in communities}
except Exception:
raw = {}
labels = {}
for cid in communities:
if cid not in labels:
labels[cid] = "Community " + str(cid)
questions = suggest_questions(G, communities, labels)
out.mkdir(exist_ok=True)
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
json_written = to_json(G, communities, str(out / "graph.json"), force=force)
json_written = to_json(G, communities, str(out / "graph.json"), force=force, built_at_commit=commit)
if not json_written:
return False
@@ -123,7 +150,8 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False, force: boo
pass
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
{"input": 0, "output": 0}, report_root, suggested_questions=questions)
{"input": 0, "output": 0}, report_root, suggested_questions=questions,
built_at_commit=commit)
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
@@ -241,10 +269,12 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
batch = list(changed)
changed.clear()
print(f"\n[graphify watch] {len(batch)} file(s) changed")
if _has_non_code(batch):
_notify_only(watch_path)
else:
has_non_code = _has_non_code(batch)
has_code = any(p.suffix.lower() in _CODE_EXTENSIONS for p in batch)
if has_code:
_rebuild_code(watch_path)
if has_non_code:
_notify_only(watch_path)
except KeyboardInterrupt:
print("\n[graphify watch] Stopped.")
finally:
+6
View File
@@ -196,6 +196,12 @@ def to_wiki(
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
if not communities:
raise ValueError(
"communities dict is empty — refusing to clear wiki/. "
"Run `graphify extract .` or `graphify cluster-only .` first."
)
# Clear stale .md files from previous runs to prevent orphan accumulation.
# Community labels are LLM-generated (per skill.md Step 5) and non-deterministic
# across runs — the same conceptual community may be named differently each time
+11 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.6.9"
version = "0.7.8"
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" }
@@ -12,6 +12,8 @@ keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "a
requires-python = ">=3.10"
dependencies = [
"networkx",
"datasketch",
"rapidfuzz",
"tree-sitter>=0.23.0",
"tree-sitter-python",
"tree-sitter-javascript",
@@ -19,6 +21,7 @@ dependencies = [
"tree-sitter-go",
"tree-sitter-rust",
"tree-sitter-java",
"tree-sitter-groovy",
"tree-sitter-c",
"tree-sitter-cpp",
"tree-sitter-ruby",
@@ -34,6 +37,7 @@ dependencies = [
"tree-sitter-objc",
"tree-sitter-julia",
"tree-sitter-verilog",
"tree-sitter-fortran",
]
[project.urls]
@@ -51,6 +55,9 @@ leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
video = ["faster-whisper", "yt-dlp"]
kimi = ["openai", "tiktoken"]
ollama = ["openai"]
gemini = ["openai", "tiktoken"]
openai = ["openai", "tiktoken"]
sql = ["tree-sitter-sql"]
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai", "tiktoken", "tree-sitter-sql"]
@@ -68,3 +75,6 @@ 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.bandit]
skips = ["B404"]
+33
View File
@@ -0,0 +1,33 @@
# Deploy Guide
How to deploy the QuranicWords backend.
## Prerequisites
- Docker installed
- SSH access to VPS
## Full Deploy
Run this one-liner on your VPS:
```bash
cd /opt/QuranicWords && git pull origin main && docker compose build --no-cache api
```
### Database Migration
If you changed the Prisma schema:
```sql
ALTER TABLE users ADD COLUMN points INT DEFAULT 0;
```
## Rollback
Use `git revert` to undo bad deploys.
```python
def rollback(version):
subprocess.run(["git", "checkout", version])
```
+17
View File
@@ -0,0 +1,17 @@
#define NDIM 3
module shapes
#ifdef MPI
use mpi
#endif
implicit none
contains
subroutine compute_volume(side, vol)
real, intent(in) :: side
real, intent(out) :: vol
vol = side ** NDIM
end subroutine compute_volume
end module shapes
+39
View File
@@ -0,0 +1,39 @@
module geometry
use constants
implicit none
real, parameter :: PI = 3.14159
contains
subroutine circle_area(radius, area)
real, intent(in) :: radius
real, intent(out) :: area
area = PI * radius * radius
end subroutine circle_area
function distance(x1, y1, x2, y2) result(d)
real, intent(in) :: x1, y1, x2, y2
real :: d
d = sqrt((x2 - x1)**2 + (y2 - y1)**2)
end function distance
subroutine print_area(radius)
real, intent(in) :: radius
real :: area
call circle_area(radius, area)
print *, "Area =", area
end subroutine print_area
end module geometry
program main
use geometry
implicit none
real :: r, a
r = 5.0
call circle_area(r, a)
print *, "Circle area:", a
end program main
+21
View File
@@ -0,0 +1,21 @@
package com.nicklastrange.example
import com.nicklastrange.Processor
import com.nicklastrange.util.Helper
class SampleService {
Processor processor
SampleService(Processor processor) {
this.processor = processor
}
String process(String input) {
def result = processor.transform(input)
return Helper.clean(result)
}
private void reset() {
processor.reset()
}
}
+35
View File
@@ -0,0 +1,35 @@
-- Luau sample (Roblox): typed Lua superset.
-- tree-sitter-lua doesn't parse the type annotations, but extracts
-- function declarations and call edges fine.
local Server = {}
Server.__index = Server
type ServerConfig = {
port: number,
name: string?,
}
function Server.new(config: ServerConfig): Server
local self = setmetatable({}, Server)
self.port = config.port
self.name = config.name or "default"
return self
end
function Server:start(): ()
print(string.format("listening on :%d", self.port))
end
function Server:stop(): ()
print("stopped")
end
local function main()
local s = Server.new({ port = 8080 })
s:start()
end
main()
return Server
+42
View File
@@ -0,0 +1,42 @@
package com.nicklastrange.example
import spock.lang.Specification
class SampleSpec extends Specification {
def setup() {
// common setup
}
def "should process valid input"() {
given:
def input = "hello"
when:
def result = input.toUpperCase()
then:
result == "HELLO"
}
def "should not change value when it's already correct"() {
given:
def value = "HELLO"
when:
def result = value.toUpperCase()
then:
result == value
}
def "should handle #input and return #expected"() {
expect:
input.toUpperCase() == expected
where:
input | expected
"hello" | "HELLO"
"world" | "WORLD"
}
}
+199
View File
@@ -0,0 +1,199 @@
"""Integration tests for graphify export subcommands and CLI commands.
Each test builds a minimal graph in a temp dir, runs the CLI command as a subprocess,
and asserts the expected output file exists and is non-empty / valid.
"""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
import pytest
PYTHON = sys.executable
FIXTURES = Path(__file__).parent / "fixtures"
def _run(args: list[str], cwd: Path) -> subprocess.CompletedProcess:
return subprocess.run(
[PYTHON, "-m", "graphify"] + args,
cwd=cwd,
capture_output=True,
text=True,
)
def _make_graph(tmp_path: Path) -> Path:
"""Build a minimal graph.json + analysis/labels files in tmp_path/graphify-out/."""
out = tmp_path / "graphify-out"
out.mkdir()
extraction = json.loads((FIXTURES / "extraction.json").read_text())
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
from graphify.export import to_json
G = build_from_json(extraction)
communities = cluster(G)
cohesion = score_all(G, communities)
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: f"Community {cid}" for cid in communities}
to_json(G, communities, str(out / "graph.json"))
analysis = {
"communities": {str(k): v for k, v in communities.items()},
"cohesion": {str(k): v for k, v in cohesion.items()},
"gods": gods,
"surprises": surprises,
}
(out / ".graphify_analysis.json").write_text(json.dumps(analysis))
(out / ".graphify_labels.json").write_text(
json.dumps({str(k): v for k, v in labels.items()})
)
return out
# ── graphify export html ─────────────────────────────────────────────────────
def test_export_html_creates_file(tmp_path):
_make_graph(tmp_path)
r = _run(["export", "html"], tmp_path)
assert r.returncode == 0, r.stderr
html = tmp_path / "graphify-out" / "graph.html"
assert html.exists()
assert html.stat().st_size > 0
def test_export_html_no_viz_removes_file(tmp_path):
out = _make_graph(tmp_path)
(out / "graph.html").write_text("<html/>")
r = _run(["export", "html", "--no-viz"], tmp_path)
assert r.returncode == 0, r.stderr
assert not (out / "graph.html").exists()
def test_export_html_error_without_graph(tmp_path):
r = _run(["export", "html"], tmp_path)
assert r.returncode != 0
# ── graphify export obsidian ─────────────────────────────────────────────────
def test_export_obsidian_creates_vault(tmp_path):
_make_graph(tmp_path)
r = _run(["export", "obsidian"], tmp_path)
assert r.returncode == 0, r.stderr
vault = tmp_path / "graphify-out" / "obsidian"
assert vault.exists()
md_files = list(vault.glob("*.md"))
assert len(md_files) > 0
def test_export_obsidian_custom_dir(tmp_path):
_make_graph(tmp_path)
custom = tmp_path / "my-vault"
r = _run(["export", "obsidian", "--dir", str(custom)], tmp_path)
assert r.returncode == 0, r.stderr
assert custom.exists()
assert len(list(custom.glob("*.md"))) > 0
# ── graphify export wiki ─────────────────────────────────────────────────────
def test_export_wiki_creates_articles(tmp_path):
_make_graph(tmp_path)
r = _run(["export", "wiki"], tmp_path)
assert r.returncode == 0, r.stderr
wiki = tmp_path / "graphify-out" / "wiki"
assert wiki.exists()
assert (wiki / "index.md").exists()
# ── graphify export graphml ──────────────────────────────────────────────────
def test_export_graphml_creates_file(tmp_path):
_make_graph(tmp_path)
r = _run(["export", "graphml"], tmp_path)
assert r.returncode == 0, r.stderr
gml = tmp_path / "graphify-out" / "graph.graphml"
assert gml.exists()
assert gml.stat().st_size > 0
content = gml.read_text()
assert "<graphml" in content
# ── graphify export neo4j (cypher) ───────────────────────────────────────────
def test_export_neo4j_creates_cypher(tmp_path):
_make_graph(tmp_path)
r = _run(["export", "neo4j"], tmp_path)
assert r.returncode == 0, r.stderr
cypher = tmp_path / "graphify-out" / "cypher.txt"
assert cypher.exists()
assert cypher.stat().st_size > 0
content = cypher.read_text()
assert "MERGE" in content or "CREATE" in content
# ── graphify query ───────────────────────────────────────────────────────────
def test_query_returns_output(tmp_path):
_make_graph(tmp_path)
r = _run(["query", "test"], tmp_path)
assert r.returncode == 0, r.stderr
assert len(r.stdout) > 0
def test_query_dfs_flag(tmp_path):
_make_graph(tmp_path)
r = _run(["query", "test", "--dfs"], tmp_path)
assert r.returncode == 0, r.stderr
def test_query_budget_flag(tmp_path):
_make_graph(tmp_path)
r = _run(["query", "test", "--budget", "500"], tmp_path)
assert r.returncode == 0, r.stderr
def test_query_missing_graph_fails(tmp_path):
r = _run(["query", "anything"], tmp_path)
assert r.returncode != 0
# ── graphify path ────────────────────────────────────────────────────────────
def test_path_runs_without_error(tmp_path):
_make_graph(tmp_path)
r = _run(["path", "Transformer", "LayerNorm"], tmp_path)
# May find or not find a path — either is valid, should not crash
assert r.returncode == 0, r.stderr
def test_path_missing_graph_fails(tmp_path):
r = _run(["path", "a", "b"], tmp_path)
assert r.returncode != 0
# ── graphify explain ─────────────────────────────────────────────────────────
def test_explain_runs_without_error(tmp_path):
_make_graph(tmp_path)
r = _run(["explain", "test"], tmp_path)
assert r.returncode == 0, r.stderr
def test_explain_missing_graph_fails(tmp_path):
r = _run(["explain", "anything"], tmp_path)
assert r.returncode != 0
# ── graphify export unknown format ───────────────────────────────────────────
def test_export_unknown_format_fails(tmp_path):
r = _run(["export", "pdf"], tmp_path)
assert r.returncode != 0
+137
View File
@@ -0,0 +1,137 @@
"""Tests for graphify/dedup.py entity deduplication pipeline."""
from __future__ import annotations
import pytest
from graphify.dedup import deduplicate_entities, _entropy, _shingles
# ── entropy gate ─────────────────────────────────────────────────────────────
def test_entropy_short_label_low():
assert _entropy("AI") < 2.5
def test_entropy_normal_label_high():
assert _entropy("AuthenticationManager") >= 2.5
def test_entropy_empty_string():
assert _entropy("") == 0.0
# ── shingles ─────────────────────────────────────────────────────────────────
def test_shingles_produces_trigrams():
s = _shingles("hello")
assert "hel" in s
assert "ell" in s
assert "llo" in s
def test_shingles_short_string():
# strings shorter than 3 chars return single shingle of the string itself
assert _shingles("ab") == {"ab"}
# ── full pipeline ─────────────────────────────────────────────────────────────
def _make_nodes(*labels):
return [{"id": label.lower().replace(" ", "_"), "label": label, "source_file": "test.md"} for label in labels]
def _make_edges(src, tgt, relation="relates_to"):
return [{"source": src, "target": tgt, "relation": relation}]
def test_exact_duplicates_merged():
nodes = _make_nodes("UserService", "userservice", "User Service")
edges = []
result_nodes, result_edges = deduplicate_entities(nodes, edges, communities={})
# All three are the same concept — only one survives
assert len(result_nodes) == 1
def test_typo_merged():
# "GraphExtractor" vs "Graph Extractor" — Jaro-Winkler >= 0.92
nodes = _make_nodes("GraphExtractor", "Graph Extractor")
edges = []
result_nodes, _ = deduplicate_entities(nodes, edges, communities={})
assert len(result_nodes) == 1
def test_unrelated_not_merged():
nodes = _make_nodes("UserService", "OrderService")
edges = []
result_nodes, _ = deduplicate_entities(nodes, edges, communities={})
assert len(result_nodes) == 2
def test_short_low_entropy_not_merged():
# "AI" and "ML" are low-entropy — entropy gate skips them
nodes = _make_nodes("AI", "ML")
edges = []
result_nodes, _ = deduplicate_entities(nodes, edges, communities={})
assert len(result_nodes) == 2
def test_edges_rewired_after_merge():
nodes = _make_nodes("GraphExtractor", "Graph Extractor", "Parser")
# edge from loser to Parser should be rewired to winner
edges = [{"source": "graph_extractor", "target": "parser", "relation": "uses"}]
result_nodes, result_edges = deduplicate_entities(nodes, edges, communities={})
assert len(result_nodes) == 2 # merged + Parser
# edge should still exist (rewired to winner)
assert len(result_edges) == 1
def test_self_loops_dropped_after_merge():
# If both endpoints of an edge get merged into same node, drop the edge
nodes = _make_nodes("GraphExtractor", "Graph Extractor")
edges = [{"source": "graphextractor", "target": "graph_extractor", "relation": "same"}]
_, result_edges = deduplicate_entities(nodes, edges, communities={})
assert result_edges == []
def test_community_boost_aids_merge():
# Two nodes in same community with score in 0.75-0.85 zone get boosted
nodes = _make_nodes("AuthManager", "Auth Manager")
edges = []
# Same community → boost → merge
communities = {"authmanager": 1, "auth_manager": 1}
result_with, _ = deduplicate_entities(nodes, edges, communities=communities)
# Different community → no boost
communities_diff = {"authmanager": 1, "auth_manager": 2}
result_without, _ = deduplicate_entities(nodes, edges, communities=communities_diff)
assert len(result_with) <= len(result_without)
def test_empty_inputs():
result_nodes, result_edges = deduplicate_entities([], [], communities={})
assert result_nodes == []
assert result_edges == []
def test_single_node_no_crash():
nodes = _make_nodes("UserService")
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 1
def test_dedup_llm_flag_accepted():
"""deduplicate_entities accepts dedup_llm_backend without crashing when no ambiguous pairs exist."""
nodes = _make_nodes("UserService", "OrderService")
edges = []
result_nodes, _ = deduplicate_entities(nodes, edges, communities={}, dedup_llm_backend=None)
assert len(result_nodes) == 2
# ── build integration ─────────────────────────────────────────────────────────
def test_build_calls_dedup():
"""build() should deduplicate near-identical nodes across extractions."""
from graphify.build import build
chunk1 = {
"nodes": [{"id": "graphextractor", "label": "GraphExtractor", "source_file": "a.py"}],
"edges": [],
}
chunk2 = {
"nodes": [{"id": "graph_extractor", "label": "Graph Extractor", "source_file": "b.py"}],
"edges": [],
}
G = build([chunk1, chunk2])
assert G.number_of_nodes() == 1
+28 -1
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from graphify.detect import classify_file, count_words, detect, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
from graphify.detect import classify_file, count_words, detect, detect_incremental, save_manifest, FileType, _looks_like_paper, _is_ignored, _load_graphifyignore
FIXTURES = Path(__file__).parent / "fixtures"
@@ -220,6 +220,33 @@ def test_detect_handles_circular_symlinks(tmp_path):
assert any("main.py" 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."""
monkeypatch.chdir(tmp_path)
real_dir = tmp_path / "real_corpus"
real_dir.mkdir()
(real_dir / "note.md").write_text("# real note\n\nsome content")
(tmp_path / "linked_corpus").symlink_to(real_dir)
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)
assert not any("linked_corpus" in f for f in no_link["files"]["document"])
# With follow_symlinks=True, the symlinked dir contents appear and are new.
yes_link = detect_incremental(tmp_path, manifest_path, follow_symlinks=True)
assert any("linked_corpus" in f for f in yes_link["files"]["document"])
assert yes_link["new_total"] >= 2 # real + linked
# After saving manifest, a second incremental scan should see no changes.
save_manifest(yes_link["files"], manifest_path)
second = detect_incremental(tmp_path, manifest_path, follow_symlinks=True)
assert second["new_total"] == 0
def test_classify_video_extensions():
"""Video and audio file extensions should classify as VIDEO."""
from graphify.detect import FileType
+2 -5
View File
@@ -57,12 +57,9 @@ def test_extract_merges_multiple_files():
def test_collect_files_from_dir():
from graphify.extract import _DISPATCH
files = collect_files(FIXTURES)
supported = {".py", ".js", ".ts", ".tsx", ".go", ".rs",
".java", ".c", ".cpp", ".cc", ".cxx", ".rb",
".cs", ".kt", ".kts", ".scala", ".php", ".h", ".hpp",
".swift", ".lua", ".toc", ".zig", ".ps1", ".ex", ".exs",
".m", ".mm"}
supported = set(_DISPATCH.keys())
assert all(f.suffix in supported for f in files)
assert len(files) > 0
+279
View File
@@ -0,0 +1,279 @@
"""Tests for the global graph infrastructure (graphify/global_graph.py),
prefix/prune helpers in graphify/build.py, and the cross-repo guard in
graphify/dedup.py."""
from __future__ import annotations
import json
import pytest
import networkx as nx
from unittest.mock import patch
# ── helpers ──────────────────────────────────────────────────────────────────
def _make_graph(nodes, edges=None):
"""Build a simple nx.Graph from node dicts."""
G = nx.Graph()
for n in nodes:
nid = n["id"]
G.add_node(nid, **{k: v for k, v in n.items() if k != "id"})
for e in (edges or []):
G.add_edge(
e["source"],
e["target"],
**{k: v for k, v in e.items() if k not in ("source", "target")},
)
return G
def _graph_to_json(G, path):
from networkx.readwrite import json_graph as jg
try:
data = jg.node_link_data(G, edges="links")
except TypeError:
data = jg.node_link_data(G)
path.write_text(json.dumps(data), encoding="utf-8")
# ── build.py helpers ──────────────────────────────────────────────────────────
def test_prefix_graph_preserves_label():
from graphify.build import prefix_graph_for_global
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
H = prefix_graph_for_global(G, "repoA")
assert "repoA::userservice" in H.nodes
assert "userservice" not in H.nodes
assert H.nodes["repoA::userservice"]["label"] == "UserService"
def test_prefix_graph_sets_repo_and_local_id():
from graphify.build import prefix_graph_for_global
G = _make_graph([{"id": "userservice", "label": "UserService"}])
H = prefix_graph_for_global(G, "repoA")
data = H.nodes["repoA::userservice"]
assert data["repo"] == "repoA"
assert data["local_id"] == "userservice"
def test_prefix_graph_rewrites_edges():
from graphify.build import prefix_graph_for_global
G = _make_graph(
[{"id": "a", "label": "A"}, {"id": "b", "label": "B"}],
[{"source": "a", "target": "b"}],
)
H = prefix_graph_for_global(G, "repo1")
assert H.has_edge("repo1::a", "repo1::b")
assert not H.has_edge("a", "b")
def test_prune_repo_removes_correct_nodes():
from graphify.build import prune_repo_from_graph
G = nx.Graph()
G.add_node("repoA::userservice", repo="repoA", label="UserService")
G.add_node("repoB::userservice", repo="repoB", label="UserService")
G.add_node("repoA::auth", repo="repoA", label="Auth")
removed = prune_repo_from_graph(G, "repoA")
assert removed == 2
assert "repoB::userservice" in G.nodes
assert "repoA::userservice" not in G.nodes
assert "repoA::auth" not in G.nodes
def test_prune_repo_returns_zero_if_not_present():
from graphify.build import prune_repo_from_graph
G = nx.Graph()
G.add_node("repoA::x", repo="repoA")
removed = prune_repo_from_graph(G, "repoB")
assert removed == 0
assert G.number_of_nodes() == 1
# ── global_graph.py ───────────────────────────────────────────────────────────
def test_global_add_creates_global_graph(tmp_path):
src_graph = tmp_path / "graph.json"
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
_graph_to_json(G, src_graph)
global_dir = tmp_path / ".graphify"
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
from graphify.global_graph import global_add
result = global_add(src_graph, "repoA")
assert result["skipped"] is False
assert result["nodes_added"] > 0
manifest_path = global_dir / "global-manifest.json"
assert manifest_path.exists()
manifest = json.loads(manifest_path.read_text())
assert "repoA" in manifest["repos"]
def test_global_add_skip_on_unchanged_hash(tmp_path):
src_graph = tmp_path / "graph.json"
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
_graph_to_json(G, src_graph)
global_dir = tmp_path / ".graphify"
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
from graphify.global_graph import global_add
global_add(src_graph, "repoA")
result2 = global_add(src_graph, "repoA")
assert result2["skipped"] is True
def test_global_add_two_repos_no_collision(tmp_path):
g1 = tmp_path / "graph1.json"
g2 = tmp_path / "graph2.json"
G1 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
G2 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
_graph_to_json(G1, g1)
_graph_to_json(G2, g2)
global_dir = tmp_path / ".graphify"
global_graph_path = global_dir / "global-graph.json"
global_manifest_path = global_dir / "global-manifest.json"
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
patch("graphify.global_graph._GLOBAL_GRAPH", global_graph_path), \
patch("graphify.global_graph._GLOBAL_MANIFEST", global_manifest_path):
from graphify.global_graph import global_add, _load_global_graph
global_add(g1, "repoA")
global_add(g2, "repoB")
G = _load_global_graph()
assert "repoA::userservice" in G.nodes
assert "repoB::userservice" in G.nodes
assert G.number_of_nodes() == 2 # no silent merge
def test_global_remove(tmp_path):
src_graph = tmp_path / "graph.json"
G = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
_graph_to_json(G, src_graph)
global_dir = tmp_path / ".graphify"
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
from graphify.global_graph import global_add, global_remove
global_add(src_graph, "repoA")
removed = global_remove("repoA")
assert removed > 0
# manifest should no longer list repoA - need to re-patch for list call
global_dir2 = global_dir # same dir
with patch("graphify.global_graph._GLOBAL_DIR", global_dir2), \
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir2 / "global-graph.json"), \
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir2 / "global-manifest.json"):
from graphify.global_graph import global_list
repos = global_list()
assert "repoA" not in repos
def test_global_remove_unknown_tag_raises(tmp_path):
global_dir = tmp_path / ".graphify"
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
from graphify.global_graph import global_remove
with pytest.raises(KeyError):
global_remove("nonexistent")
def test_global_add_collision_warning(tmp_path, capsys):
g1 = tmp_path / "graph1.json"
g2 = tmp_path / "graph2.json"
G = _make_graph([{"id": "x", "label": "X", "source_file": "x.py"}])
_graph_to_json(G, g1)
_graph_to_json(G, g2)
global_dir = tmp_path / ".graphify"
with patch("graphify.global_graph._GLOBAL_DIR", global_dir), \
patch("graphify.global_graph._GLOBAL_GRAPH", global_dir / "global-graph.json"), \
patch("graphify.global_graph._GLOBAL_MANIFEST", global_dir / "global-manifest.json"):
from graphify.global_graph import global_add
global_add(g1, "myrepo")
global_add(g2, "myrepo") # different source path, same tag
captured = capsys.readouterr()
assert "warning" in captured.err.lower() or "warning" in captured.out.lower()
# ── dedup guard ───────────────────────────────────────────────────────────────
def test_dedup_raises_on_cross_repo_nodes():
from graphify.dedup import deduplicate_entities
nodes = [
{"id": "repoA::userservice", "label": "UserService", "repo": "repoA"},
{"id": "repoB::userservice", "label": "UserService", "repo": "repoB"},
]
with pytest.raises(ValueError, match="multiple repos"):
deduplicate_entities(nodes, [], communities={})
def test_dedup_ok_with_single_repo():
from graphify.dedup import deduplicate_entities
nodes = [
{"id": "repoA::userservice", "label": "UserService", "repo": "repoA"},
{"id": "repoA::auth", "label": "Auth", "repo": "repoA"},
]
result_nodes, result_edges = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2 # no false merge
def test_dedup_ok_with_no_repo_attr():
from graphify.dedup import deduplicate_entities
nodes = [
{"id": "userservice", "label": "UserService"},
{"id": "auth", "label": "Auth"},
]
result_nodes, result_edges = deduplicate_entities(nodes, [], communities={})
assert len(result_nodes) == 2
# ── merge-graphs prefix ───────────────────────────────────────────────────────
def test_merge_graphs_prefixes_ids(tmp_path):
"""merge-graphs should prefix node IDs with repo name to avoid silent collision."""
from graphify.build import prefix_graph_for_global
from networkx.readwrite import json_graph as jg
# Two graphs with same node ID
G1 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
G2 = _make_graph([{"id": "userservice", "label": "UserService", "source_file": "src/user.py"}])
repo1 = tmp_path / "repo1" / "graphify-out"
repo2 = tmp_path / "repo2" / "graphify-out"
repo1.mkdir(parents=True)
repo2.mkdir(parents=True)
g1_path = repo1 / "graph.json"
g2_path = repo2 / "graph.json"
_graph_to_json(G1, g1_path)
_graph_to_json(G2, g2_path)
# Simulate what merge-graphs now does (prefix before compose)
graphs = []
graph_paths = [g1_path, g2_path]
for gp in graph_paths:
data = json.loads(gp.read_text())
if "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
try:
G = jg.node_link_graph(data, edges="links")
except TypeError:
G = jg.node_link_graph(data)
repo_tag = gp.parent.parent.name
graphs.append(prefix_graph_for_global(G, repo_tag))
merged = nx.Graph()
for G in graphs:
merged = nx.compose(merged, G)
assert "repo1::userservice" in merged.nodes
assert "repo2::userservice" in merged.nodes
assert merged.number_of_nodes() == 2 # no silent collapse
+529
View File
@@ -0,0 +1,529 @@
"""Tests for #716 — TypeScript bare-path imports, Svelte 5 rune file imports
(`from './foo.svelte'` for a `.svelte.ts` file), and directory/index.ts
imports must resolve to the actual file's node id, not a phantom.
Before #716, `_import_js` only rewrote `.js → .ts` and `.jsx → .tsx`. Every
other shape (bare path, `.svelte → .svelte.ts`, `./foo` directory imports)
produced an id like `..._foo` while the real file's node id was `..._foo_ts`,
so `build_from_json` dropped the edge as external.
"""
from pathlib import Path
from graphify.extract import (
_make_id,
_resolve_js_module_path,
extract_js,
extract_svelte,
)
def _write(path: Path, body: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
return path
def _import_targets(result: dict) -> set[str]:
return {str(e.get("target") or "") for e in result["edges"]
if e.get("relation") in ("imports", "imports_from")}
# ── _resolve_js_module_path unit tests ──────────────────────────────────────
def test_resolve_returns_existing_path_unchanged(tmp_path):
p = _write(tmp_path / "foo.ts", "export const x = 1")
assert _resolve_js_module_path(p) == p
def test_resolve_bare_path_to_ts(tmp_path):
target = _write(tmp_path / "foo.ts", "export const x = 1")
bare = tmp_path / "foo"
assert _resolve_js_module_path(bare) == target
def test_resolve_bare_path_to_tsx(tmp_path):
target = _write(tmp_path / "Component.tsx", "export const x = 1")
bare = tmp_path / "Component"
assert _resolve_js_module_path(bare) == target
def test_resolve_bare_path_to_svelte(tmp_path):
target = _write(tmp_path / "Card.svelte", "<div></div>")
bare = tmp_path / "Card"
assert _resolve_js_module_path(bare) == target
def test_resolve_prefers_ts_over_svelte_when_both_exist(tmp_path):
"""Vite resolver order: .ts wins over .svelte for ambiguous bare paths."""
ts_target = _write(tmp_path / "foo.ts", "export const x = 1")
_write(tmp_path / "foo.svelte", "<div></div>")
bare = tmp_path / "foo"
assert _resolve_js_module_path(bare) == ts_target
def test_resolve_file_wins_over_sibling_directory(tmp_path):
"""Real-world repro: a project has both `auth.ts` (file) and `auth/`
(directory of sub-modules) at the same path. Both TypeScript and Vite
prefer the file match. If the resolver checks the directory first and
falls back on a missing index, every `from './auth'` import silently
drops because the directory has no index.{ts,…}."""
file_target = _write(tmp_path / "auth.ts", "export const x = 1")
sibling_dir = tmp_path / "auth"
sibling_dir.mkdir()
_write(sibling_dir / "helpers.ts", "export const y = 2")
bare = tmp_path / "auth"
assert _resolve_js_module_path(bare) == file_target
def test_resolve_directory_to_index_ts(tmp_path):
pkg = tmp_path / "queue"
target = _write(pkg / "index.ts", "export const x = 1")
assert _resolve_js_module_path(pkg) == target
def test_resolve_directory_prefers_index_ts_over_index_js(tmp_path):
pkg = tmp_path / "queue"
target = _write(pkg / "index.ts", "export const x = 1")
_write(pkg / "index.js", "module.exports = {}")
assert _resolve_js_module_path(pkg) == target
def test_resolve_svelte_to_svelte_ts_for_rune_files(tmp_path):
"""Svelte 5: `from './foo.svelte'` may actually point at `foo.svelte.ts`
(a rune-only TypeScript file with no .svelte file). The resolver must
APPEND .ts to the full filename, not swap suffixes."""
target = _write(tmp_path / "is-mobile.svelte.ts",
"export const isMobile = () => true")
written_as = tmp_path / "is-mobile.svelte"
resolved = _resolve_js_module_path(written_as)
assert resolved == target, (
f"Expected resolution to is-mobile.svelte.ts; got {resolved}"
)
def test_resolve_svelte_to_svelte_js_for_javascript_rune_files(tmp_path):
"""JS variant of the rune file pattern: a `.svelte.js` file (used in
JavaScript-only Svelte 5 projects, no TypeScript). `from './foo.svelte'`
must resolve to `foo.svelte.js` when no `.ts` variant exists.
Same code path as the .svelte.ts case — the generalized resolver tries
every extension in priority order, so JS-only and TS-only projects
both work without special-casing."""
target = _write(tmp_path / "store.svelte.js",
"export const count = $state(0)")
written_as = tmp_path / "store.svelte"
resolved = _resolve_js_module_path(written_as)
assert resolved == target
def test_resolve_svelte_prefers_svelte_ts_over_svelte_js(tmp_path):
"""When both `.svelte.ts` and `.svelte.js` exist (hybrid project mid-
migration, or a build artifact alongside the source), `.ts` wins —
matching the resolver's stated TypeScript-first priority order.
Note: Vite's default `resolve.extensions` puts `.js` before `.ts`, but
in practice TypeScript codebases that emit `.svelte.js` build artifacts
expect tooling to read the `.svelte.ts` source. graphify is a source-
code tool, not a runtime resolver, so source-first ordering is correct
for our use case."""
ts_target = _write(tmp_path / "store.svelte.ts",
"export const count = $state(0)")
_write(tmp_path / "store.svelte.js",
"export const count = 0 // build artifact")
written_as = tmp_path / "store.svelte"
resolved = _resolve_js_module_path(written_as)
assert resolved == ts_target
def test_resolve_real_svelte_file_wins_over_svelte_ts_sibling(tmp_path):
"""If `foo.svelte` IS a real markup file, importing `./foo.svelte`
must resolve to that — not get hijacked to a sibling `foo.svelte.ts`
rune file. The existence-check short-circuits before any append."""
real = _write(tmp_path / "Card.svelte", "<div>card markup</div>")
_write(tmp_path / "Card.svelte.ts",
"export const helpers = {} // rune sibling, not the import target")
resolved = _resolve_js_module_path(real)
assert resolved == real
def test_resolve_js_to_ts_when_real_file_is_ts(tmp_path):
"""TS ESM convention: imports written as .js but the actual file is .ts."""
target = _write(tmp_path / "foo.ts", "export const x = 1")
written_as = tmp_path / "foo.js"
assert _resolve_js_module_path(written_as) == target
def test_resolve_jsx_to_tsx_when_real_file_is_tsx(tmp_path):
target = _write(tmp_path / "Component.tsx", "export const x = 1")
written_as = tmp_path / "Component.jsx"
assert _resolve_js_module_path(written_as) == target
def test_resolve_returns_unchanged_when_nothing_matches(tmp_path):
"""External / truly missing paths fall back to the input — preserves
pre-#716 behavior of becoming an external phantom edge."""
nothing = tmp_path / "does_not_exist"
assert _resolve_js_module_path(nothing) == nothing
def test_resolve_real_js_stays_js_when_ts_does_not_exist(tmp_path):
"""If `.js` exists and `.ts` does not, keep the `.js` rewrite from
triggering — return the existing file."""
target = _write(tmp_path / "foo.js", "module.exports = 1")
assert _resolve_js_module_path(target) == target
# ── End-to-end: bare-path imports in pure TS files ───────────────────────────
def test_bare_path_import_resolves_in_ts_file(tmp_path):
"""The #716 reproducer: TS file imports a sibling without an extension."""
target = _write(tmp_path / "type-helpers.ts",
"export type GetNestedType<T> = T")
importer = _write(tmp_path / "page.ts",
"import type { GetNestedType } from './type-helpers'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Bare-path .ts import must resolve to target node id; "
f"expected {expected}; got {_import_targets(result)}"
)
def test_directory_import_resolves_to_index_ts(tmp_path):
"""`from './queue'` must resolve to `./queue/index.ts`."""
target = _write(tmp_path / "queue" / "index.ts",
"export const enqueue = () => {}")
importer = _write(tmp_path / "page.ts",
"import { enqueue } from './queue'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Directory import must resolve to ./queue/index.ts; "
f"expected {expected}; got {_import_targets(result)}"
)
# ── End-to-end: .svelte → .svelte.ts (Svelte 5 rune files) ───────────────────
def test_dot_svelte_import_resolves_to_dot_svelte_ts(tmp_path):
"""Svelte 5 rune file: import written as .svelte, real file is .svelte.ts."""
target = _write(tmp_path / "is-mobile.svelte.ts",
"export const isMobile = () => true")
importer = _write(tmp_path / "page.ts",
"import { isMobile } from './is-mobile.svelte'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f".svelte → .svelte.ts resolution failed; "
f"expected {expected}; got {_import_targets(result)}"
)
# ── Regression guards: existing behavior preserved ───────────────────────────
def test_explicit_ts_import_still_works(tmp_path):
"""The most common case — import with explicit .ts extension — must
continue to work after the resolver change."""
target = _write(tmp_path / "foo.ts", "export const x = 1")
importer = _write(tmp_path / "page.ts",
"import { x } from './foo.ts'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Explicit .ts imports must still resolve; "
f"expected {expected}; got {_import_targets(result)}"
)
def test_explicit_svelte_import_still_works(tmp_path):
"""Real .svelte file imports must still resolve when the .svelte file
exists (i.e. don't accidentally redirect to a non-existent .svelte.ts)."""
target = _write(tmp_path / "Card.svelte", "<div></div>")
importer = _write(tmp_path / "page.ts",
"import Card from './Card.svelte'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Existing .svelte imports must resolve to the .svelte node, "
f"not get redirected; expected {expected}; "
f"got {_import_targets(result)}"
)
def test_external_module_unchanged(tmp_path):
"""Bare module specifiers (no leading dot, no alias match) must still
fall through to the external/last-segment path — don't accidentally
treat 'lodash' as a relative path."""
importer = _write(tmp_path / "page.ts",
"import _ from 'lodash-es'\n")
result = extract_js(importer)
targets = _import_targets(result)
# The target should be the bare module name, not a resolved file path
assert "lodash_es" in targets or any("lodash" in t for t in targets), (
f"External module specifier should still produce an external "
f"reference; got {targets}"
)
# ── End-to-end: alias-resolved imports go through the same resolver ─────────
def test_alias_import_with_bare_path_resolves(tmp_path):
"""`$lib/foo` (alias + bare path) — both layers must work together."""
src = tmp_path / "src"
target = _write(src / "lib" / "type-helpers.ts",
"export type X = string")
_write(tmp_path / "tsconfig.json",
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
'"$lib/*":["./src/lib/*"]}}}')
importer_dir = src / "routes"
importer = _write(importer_dir / "page.ts",
"import type { X } from '$lib/type-helpers'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Alias + bare-path resolution failed; "
f"expected {expected}; got {_import_targets(result)}"
)
# ── Edge cases — exhaustiveness ──────────────────────────────────────────────
def test_type_only_import_with_bare_path_resolves(tmp_path):
"""`import type { X } from './foo'` — type-only imports must go through
the same resolution path as regular imports. Common in TS codebases
that separate types into their own module."""
target = _write(tmp_path / "type-helpers.ts",
"export type GetNestedType<T> = T")
importer = _write(tmp_path / "page.ts",
"import type { GetNestedType } from './type-helpers'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Type-only import with bare path failed to resolve; "
f"expected {expected}; got {_import_targets(result)}"
)
def test_named_imports_emit_symbol_edges_after_resolution(tmp_path):
"""`import { foo, bar } from './module'` should emit per-symbol `imports`
edges to `module.foo` and `module.bar`, not just the file-level
`imports_from`. The symbol-edge target_stem comes from _file_stem(resolved),
which depends on resolution succeeding first."""
_write(tmp_path / "utils.ts", "export const foo = 1\nexport const bar = 2")
importer = _write(tmp_path / "page.ts",
"import { foo, bar } from './utils'\n")
result = extract_js(importer)
sym_edges = [e for e in result["edges"] if e.get("relation") == "imports"]
targets = {str(e.get("target") or "") for e in sym_edges}
# Target ids look like "<dir>_utils_foo" — substring-match the symbol names
assert any("_foo" in t for t in targets), (
f"Per-symbol `imports` edge for `foo` missing; got {targets}"
)
assert any("_bar" in t for t in targets), (
f"Per-symbol `imports` edge for `bar` missing; got {targets}"
)
def test_alias_directory_import_resolves_to_index_ts(tmp_path):
"""`from '$lib/queue'` where queue/ is a directory under src/lib/."""
src = tmp_path / "src"
target = _write(src / "lib" / "queue" / "index.ts",
"export const enqueue = () => {}")
_write(tmp_path / "tsconfig.json",
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
'"$lib/*":["./src/lib/*"]}}}')
importer = _write(src / "routes" / "page.ts",
"import { enqueue } from '$lib/queue'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Alias + directory resolution failed; "
f"expected {expected}; got {_import_targets(result)}"
)
def test_resolve_does_not_match_partial_directory_name(tmp_path):
"""Regression guard: `from './foo'` where './foo' doesn't exist but
'./foo-extra.ts' does must NOT accidentally resolve to the latter.
`.with_suffix(".ts")` on 'foo' produces 'foo.ts' — not 'foo-extra.ts',
but worth pinning down."""
_write(tmp_path / "foo-extra.ts", "export const x = 1")
bare = tmp_path / "foo"
resolved = _resolve_js_module_path(bare)
# Not a real file → nothing matches → returns input unchanged
assert resolved == bare, (
f"Partial-name match must not happen; got {resolved}"
)
def test_resolve_directory_without_index_returns_unchanged(tmp_path):
"""A directory with no index file should fall through to the
\"return as-is\" path, not pick a non-index file from inside."""
pkg = tmp_path / "pkg"
_write(pkg / "not-index.ts", "export const x = 1")
resolved = _resolve_js_module_path(pkg)
assert resolved == pkg, (
f"Directory without index.* must return unchanged; got {resolved}"
)
def test_resolve_handles_subpath_into_directory_with_index(tmp_path):
"""`./foo/sub` where ./foo/sub/index.ts exists — nested subpath.
Common pattern for sub-modules inside a package."""
target = _write(tmp_path / "foo" / "sub" / "index.ts",
"export const x = 1")
sub = tmp_path / "foo" / "sub"
assert _resolve_js_module_path(sub) == target
def test_resolve_does_not_treat_dotfile_as_extension(tmp_path):
"""Edge case: `.eslintrc` and similar dotfiles. Path('.eslintrc').suffix
returns '' on Python 3.x for files starting with `.`. Make sure we
don't accidentally treat a real file as bare and try to append .ts."""
target = _write(tmp_path / ".env-types.ts",
"export const x = 1")
# Path('.env-types.ts').suffix is '.ts' — not a problem
assert _resolve_js_module_path(target) == target
def test_resolve_multi_dot_helper_file(tmp_path):
"""Common patterns: foo.shared.ts, foo.config.ts, foo.compile.ts,
foo.integration.ts, foo.triggers.ts. Imports written as
`from './foo.shared'` (preserving the meaningful suffix) must resolve
to foo.shared.ts.
Before this rule, .suffix was '.shared' so neither the bare-path branch
nor the .js/.jsx branches matched, and the import dropped to a phantom."""
target = _write(tmp_path / "tag-action.shared.ts",
"export const apply = () => {}")
written_as = tmp_path / "tag-action.shared"
assert _resolve_js_module_path(written_as) == target
def test_resolve_multi_dot_with_explicit_extension_still_works(tmp_path):
"""Sanity: `from './foo.shared.ts'` (explicit) still wins over implicit."""
target = _write(tmp_path / "foo.shared.ts", "export const x = 1")
assert _resolve_js_module_path(target) == target
def test_resolve_ambient_d_ts_via_bare_path(tmp_path):
"""Ambient TS declaration files (foo.d.ts) — bare import `./foo.d`
should resolve to `./foo.d.ts` because `name + '.ts'` gives `foo.d.ts`."""
target = _write(tmp_path / "ambient.d.ts", "declare const X: string")
written_as = tmp_path / "ambient.d"
assert _resolve_js_module_path(written_as) == target
def test_end_to_end_multi_dot_import_resolves(tmp_path):
"""End-to-end sanity for the multi-dot pattern via the import handler."""
target = _write(tmp_path / "tag-action.shared.ts",
"export const apply = () => {}")
importer = _write(tmp_path / "page.ts",
"import { apply } from './tag-action.shared'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Multi-dot import failed end-to-end; "
f"expected {expected}; got {_import_targets(result)}"
)
def test_resolve_chain_alias_and_extension_compose(tmp_path):
"""Alias → bare path → .svelte.ts. Two layers of resolution must
compose correctly: tsconfig alias maps `$lib/...` to a real dir,
then extension resolution finds the actual file."""
src = tmp_path / "src"
target = _write(src / "lib" / "hooks" / "is-mobile.svelte.ts",
"export const isMobile = () => true")
_write(tmp_path / "tsconfig.json",
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
'"$lib/*":["./src/lib/*"]}}}')
importer = _write(src / "routes" / "page.ts",
"import { isMobile } from '$lib/hooks/is-mobile.svelte'\n")
result = extract_js(importer)
expected = _make_id(str(target))
assert expected in _import_targets(result), (
f"Alias + .svelte→.svelte.ts chain failed to compose; "
f"expected {expected}; got {_import_targets(result)}"
)
# ── End-to-end: dynamic_import in .svelte regex pass uses resolver ──────────
def test_ts_dynamic_import_bare_path_resolves(tmp_path):
"""Real-world repro: a TS file uses `await import('./foo')` (no extension)
to lazy-load a sibling module. The dynamic-import handler in JS/TS files
has its own copy of the resolution logic — distinct from the static-import
handler and from the Svelte regex pass — and was missing the bare-path
extension append, silently dropping every such edge."""
target = _write(tmp_path / "profanity.ts",
"export const hasProfanity = (s: string) => false")
importer = _write(tmp_path / "auth-validators.ts", """\
export async function validate(name: string) {
const { hasProfanity } = await import('./profanity')
return hasProfanity(name)
}
""")
result = extract_js(importer)
expected = _make_id(str(target))
targets = {str(e.get("target") or "") for e in result["edges"]
if e.get("relation") in ("imports", "imports_from")}
assert expected in targets, (
f"Bare-path TS dynamic import failed to resolve; "
f"expected {expected}; got {targets}"
)
def test_ts_dynamic_import_alias_with_bare_path_resolves(tmp_path):
"""The other branch of the dynamic-import handler — alias resolution —
also needs the same fixups. `import('$lib/foo')` should resolve to
`$lib/foo.ts` after both alias substitution and extension append."""
src = tmp_path / "src"
target = _write(src / "lib" / "lazy-module.ts", "export const x = 1")
_write(tmp_path / "tsconfig.json",
'{"compilerOptions":{"paths":{"$lib":["./src/lib"],'
'"$lib/*":["./src/lib/*"]}}}')
importer = _write(src / "routes" / "page.ts", """\
export async function load() {
const m = await import('$lib/lazy-module')
return m.x
}
""")
result = extract_js(importer)
expected = _make_id(str(target))
targets = {str(e.get("target") or "") for e in result["edges"]
if e.get("relation") in ("imports", "imports_from")}
assert expected in targets, (
f"Alias + bare-path dynamic import failed to resolve; "
f"expected {expected}; got {targets}"
)
def test_dynamic_import_bare_path_resolves(tmp_path):
"""The regex pass for `import('...')` in .svelte files must also use
the new resolver — otherwise dynamic imports of bare paths still
produce phantom edges."""
target = _write(tmp_path / "Heavy.svelte.ts",
"export const heavy = () => 1")
importer = _write(tmp_path / "page.svelte", """\
<script>
const lazy = () => import('./Heavy.svelte')
</script>
""")
result = extract_svelte(importer)
dyn_targets = {str(e.get("target") or "") for e in result["edges"]
if e.get("relation") == "dynamic_import"}
expected = _make_id(str(target))
assert expected in dyn_targets, (
f"dynamic_import of .svelte that's actually .svelte.ts must "
f"resolve through the new resolver; "
f"expected {expected}; got {dyn_targets}"
)
+57
View File
@@ -0,0 +1,57 @@
"""Integration tests for incremental graphify extract behavior."""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
import pytest
PYTHON = sys.executable
def _run(args: list[str], cwd: Path) -> subprocess.CompletedProcess:
return subprocess.run(
[PYTHON, "-m", "graphify"] + args,
cwd=cwd,
capture_output=True,
text=True,
)
def _make_docs_corpus(tmp_path: Path) -> Path:
docs = tmp_path / "docs"
docs.mkdir()
(docs / "intro.md").write_text("# Introduction\nThis doc introduces the system.")
(docs / "api.md").write_text("# API Reference\nThe API has endpoints.")
return docs
def test_manifest_written_after_extract(tmp_path):
"""After a full extract run, manifest.json must exist (or run fails before writing it)."""
docs = _make_docs_corpus(tmp_path)
r = _run(["extract", str(docs)], tmp_path)
# Should fail with no API key — but NOT with a path error
assert "no LLM API key" in r.stderr or r.returncode != 0
# manifest should NOT exist (run failed before writing)
manifest = docs / "graphify-out" / "manifest.json"
assert not manifest.exists()
def test_incremental_mode_detected_via_manifest(tmp_path):
"""If manifest.json + graph.json exist, incremental mode message is shown."""
docs = _make_docs_corpus(tmp_path)
out = docs / "graphify-out"
out.mkdir()
(out / "graph.json").write_text(json.dumps({"nodes": [], "links": []}))
(out / "manifest.json").write_text(json.dumps({"document": [str(docs / "intro.md")]}))
r = _run(["extract", str(docs)], tmp_path)
combined = r.stdout + r.stderr
assert "incremental" in combined.lower() or r.returncode != 0
def test_no_incremental_without_manifest(tmp_path):
"""Without manifest.json, full scan message is shown (not incremental)."""
docs = _make_docs_corpus(tmp_path)
r = _run(["extract", str(docs)], tmp_path)
assert "incremental" not in r.stdout
+182 -2
View File
@@ -1,11 +1,12 @@
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia, JS/TS."""
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia, Fortran, JS/TS."""
from __future__ import annotations
from pathlib import Path
import pytest
from graphify.extract import (
extract_java, extract_c, extract_cpp, extract_ruby,
extract_csharp, extract_kotlin, extract_scala, extract_php,
extract_swift, extract_go, extract_julia, extract_js,
extract_swift, extract_go, extract_julia, extract_js, extract_fortran,
extract_groovy,
)
FIXTURES = Path(__file__).parent / "fixtures"
@@ -721,6 +722,75 @@ def test_julia_no_dangling_edges():
assert e["source"] in node_ids, f"Dangling source: {e}"
# ── Fortran extractor ────────────────────────────────────────────────────────
def test_fortran_finds_module():
r = extract_fortran(FIXTURES / "sample.f90")
assert "error" not in r
labels = [n["label"] for n in r["nodes"]]
assert "geometry" in labels
def test_fortran_finds_subroutines():
r = extract_fortran(FIXTURES / "sample.f90")
labels = [n["label"] for n in r["nodes"]]
assert any("circle_area" in l for l in labels)
assert any("print_area" in l for l in labels)
def test_fortran_finds_function():
r = extract_fortran(FIXTURES / "sample.f90")
labels = [n["label"] for n in r["nodes"]]
assert any("distance" in l for l in labels)
def test_fortran_finds_program():
r = extract_fortran(FIXTURES / "sample.f90")
labels = [n["label"] for n in r["nodes"]]
assert "main" in labels
def test_fortran_finds_use_imports():
r = extract_fortran(FIXTURES / "sample.f90")
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert len(import_edges) >= 2
def test_fortran_use_edges_have_use_context():
r = extract_fortran(FIXTURES / "sample.f90")
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert all(e.get("context") == "use" for e in import_edges)
def test_fortran_finds_calls():
r = extract_fortran(FIXTURES / "sample.f90")
call_edges = [e for e in r["edges"] if e["relation"] == "calls"]
assert len(call_edges) >= 1
def test_fortran_case_insensitive_names():
r = extract_fortran(FIXTURES / "sample.f90")
labels = [n["label"] for n in r["nodes"]]
assert all(l == l.lower() or "(" in l for l in labels if l.endswith(("()", "")) and not "." in l)
assert "geometry" in labels
assert "main" in labels
def test_fortran_no_dangling_edges():
r = extract_fortran(FIXTURES / "sample.f90")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e}"
def test_fortran_capital_F_parses_preprocessed():
r = extract_fortran(FIXTURES / "sample.F90")
assert "error" not in r
labels = [n["label"] for n in r["nodes"]]
assert "shapes" in labels
assert any("compute_volume" in l for l in labels)
# ── TypeScript dynamic imports ───────────────────────────────────────────────
def test_ts_dynamic_import_no_error():
@@ -784,3 +854,113 @@ def test_ts_static_template_literal_resolved():
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
assert any("statichelper" in t.lower() for t in targets), \
f"Static template literal import not resolved: {targets}"
# ── Markdown ─────────────────────────────────────────────────────────────────
from graphify.extract import extract_markdown
def test_markdown_no_error():
r = extract_markdown(FIXTURES / "deploy_guide.md")
assert "error" not in r
def test_markdown_finds_headings():
r = extract_markdown(FIXTURES / "deploy_guide.md")
labels = _labels(r)
assert any("Deploy Guide" in l for l in labels)
assert any("Prerequisites" in l for l in labels)
assert any("Full Deploy" in l for l in labels)
assert any("Rollback" in l for l in labels)
def test_markdown_finds_nested_heading():
"""### Database Migration is nested under ## Full Deploy."""
r = extract_markdown(FIXTURES / "deploy_guide.md")
labels = _labels(r)
assert any("Database Migration" in l for l in labels)
def test_markdown_finds_code_blocks():
r = extract_markdown(FIXTURES / "deploy_guide.md")
labels = _labels(r)
assert any("code:bash" in l for l in labels)
assert any("code:sql" in l for l in labels)
assert any("code:python" in l for l in labels)
def test_markdown_contains_edges():
"""Headings and code blocks should be connected via 'contains' edges."""
r = extract_markdown(FIXTURES / "deploy_guide.md")
assert "contains" in _relations(r)
contains_edges = [e for e in r["edges"] if e["relation"] == "contains"]
assert len(contains_edges) >= 5 # file->h1, h1->h2s, h2->h3, h2->codeblocks
def test_markdown_no_dangling_edges():
r = extract_markdown(FIXTURES / "deploy_guide.md")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e}"
# ── Groovy ───────────────────────────────────────────────────────────────────
def test_groovy_no_error():
r = extract_groovy(FIXTURES / "sample.groovy")
assert "error" not in r
def test_groovy_finds_class():
r = extract_groovy(FIXTURES / "sample.groovy")
assert any("SampleService" in l for l in _labels(r))
def test_groovy_finds_methods():
r = extract_groovy(FIXTURES / "sample.groovy")
labels = _labels(r)
assert any("process" in l for l in labels)
assert any("reset" in l for l in labels)
def test_groovy_finds_imports():
r = extract_groovy(FIXTURES / "sample.groovy")
assert "imports" in _relations(r)
def test_groovy_import_edges_have_import_context():
r = extract_groovy(FIXTURES / "sample.groovy")
import_edges = _edges_with_relation(r, "imports", "imports_from")
assert import_edges
assert all(e.get("context") == "import" for e in import_edges)
def test_groovy_no_dangling_edges():
r = extract_groovy(FIXTURES / "sample.groovy")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids
def test_groovy_spock_finds_class():
r = extract_groovy(FIXTURES / "sample_spock.groovy")
assert any("SampleSpec" in l for l in _labels(r))
def test_groovy_spock_finds_feature_methods():
r = extract_groovy(FIXTURES / "sample_spock.groovy")
feature_labels = [l for l in _labels(r) if l.startswith('"')]
assert len(feature_labels) >= 2
def test_groovy_spock_finds_method_with_apostrophe():
r = extract_groovy(FIXTURES / "sample_spock.groovy")
assert any("it's" in l for l in _labels(r))
def test_groovy_spock_preserves_import_edges():
r = extract_groovy(FIXTURES / "sample_spock.groovy")
assert "imports" in _relations(r)
def test_groovy_spock_no_dangling_edges():
r = extract_groovy(FIXTURES / "sample_spock.groovy")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids
+97
View File
@@ -0,0 +1,97 @@
"""Tests for direct semantic-extraction backend selection."""
from pathlib import Path
from unittest.mock import patch
import pytest
from graphify import llm
def _clear_backend_env(monkeypatch):
for env_key in (
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"MOONSHOT_API_KEY",
"ANTHROPIC_API_KEY",
"OPENAI_API_KEY",
):
monkeypatch.delenv(env_key, raising=False)
def test_gemini_accepts_gemini_api_key(monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GEMINI_API_KEY", "gemini-key")
assert llm.detect_backend() == "gemini"
assert llm._get_backend_api_key("gemini") == "gemini-key"
def test_gemini_accepts_google_api_key(monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
assert llm.detect_backend() == "gemini"
assert llm._get_backend_api_key("gemini") == "google-key"
def test_backend_detection_prefers_gemini(monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("OPENAI_API_KEY", "openai-key")
monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-key")
monkeypatch.setenv("MOONSHOT_API_KEY", "moonshot-key")
monkeypatch.setenv("GEMINI_API_KEY", "gemini-key")
assert llm.detect_backend() == "gemini"
def test_openai_backend_detected(monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("OPENAI_API_KEY", "openai-key")
assert llm.detect_backend() == "openai"
assert llm._get_backend_api_key("openai") == "openai-key"
def test_extract_files_direct_routes_gemini_through_openai_compat(tmp_path, monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
source = tmp_path / "note.md"
source.write_text("# Architecture\n\nThe runner emits a snapshot.\n")
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
with patch("graphify.llm._call_openai_compat", return_value=result) as call:
assert llm.extract_files_direct([source], backend="gemini", root=tmp_path) is result
assert call.call_args.args[:4] == (
"https://generativelanguage.googleapis.com/v1beta/openai/",
"google-key",
"gemini-3-flash-preview",
"=== note.md ===\n# Architecture\n\nThe runner emits a snapshot.\n",
)
assert call.call_args.kwargs["temperature"] == 0
assert call.call_args.kwargs["reasoning_effort"] == "low"
assert call.call_args.kwargs["max_completion_tokens"] == 16384
def test_gemini_model_can_be_overridden_by_env(tmp_path, monkeypatch):
_clear_backend_env(monkeypatch)
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
monkeypatch.setenv("GRAPHIFY_GEMINI_MODEL", "gemini-3.1-pro-preview")
source = tmp_path / "note.md"
source.write_text("# Architecture\n")
result = {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 1, "output_tokens": 1}
with patch("graphify.llm._call_openai_compat", return_value=result) as call:
llm.extract_files_direct([source], backend="gemini", root=tmp_path)
assert call.call_args.args[2] == "gemini-3.1-pro-preview"
def test_missing_gemini_key_names_both_supported_env_vars(monkeypatch):
_clear_backend_env(monkeypatch)
with pytest.raises(ValueError) as exc:
llm.extract_files_direct([Path("missing.md")], backend="gemini")
assert "GEMINI_API_KEY or GOOGLE_API_KEY" in str(exc.value)
+70
View File
@@ -0,0 +1,70 @@
"""Tests for the Ollama backend additions in graphify/llm.py."""
from __future__ import annotations
from graphify.llm import detect_backend, BACKENDS
def test_ollama_in_backends():
assert "ollama" in BACKENDS
assert BACKENDS["ollama"]["pricing"]["input"] == 0.0
assert BACKENDS["ollama"]["pricing"]["output"] == 0.0
assert "max_tokens" in BACKENDS["ollama"]
def test_detect_backend_ollama(monkeypatch):
monkeypatch.delenv("MOONSHOT_API_KEY", raising=False)
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
assert detect_backend() == "ollama"
def test_detect_backend_kimi_beats_ollama(monkeypatch):
monkeypatch.setenv("MOONSHOT_API_KEY", "test-key")
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
assert detect_backend() == "kimi"
def test_detect_backend_ollama_beats_claude(monkeypatch):
monkeypatch.delenv("MOONSHOT_API_KEY", raising=False)
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test")
assert detect_backend() == "ollama"
def test_detect_backend_none_without_envvars(monkeypatch):
monkeypatch.delenv("MOONSHOT_API_KEY", raising=False)
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
assert detect_backend() is None
def test_ollama_api_key_sentinel(monkeypatch):
"""extract_files_direct with backend=ollama and no OLLAMA_API_KEY should use sentinel 'ollama' not raise."""
monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
from unittest.mock import patch
from pathlib import Path
import tempfile
fake_result = {
"nodes": [],
"edges": [],
"hyperedges": [],
"input_tokens": 0,
"output_tokens": 10,
"finish_reason": "stop",
}
with patch("graphify.llm._call_openai_compat", return_value=fake_result) as mock_call:
from graphify.llm import extract_files_direct
with tempfile.NamedTemporaryFile(suffix=".py", mode="w", delete=False) as f:
f.write("x = 1\n")
tmp = Path(f.name)
try:
extract_files_direct([tmp], backend="ollama", root=tmp.parent)
# Should have called _call_openai_compat with api_key="ollama"
assert mock_call.called
call_kwargs = mock_call.call_args
api_key_used = call_kwargs.args[1] if call_kwargs.args else call_kwargs.kwargs.get("api_key", "")
assert api_key_used == "ollama"
finally:
tmp.unlink(missing_ok=True)