Compare commits

...
114 Commits
Author SHA1 Message Date
SafiandClaude Sonnet 4.6 ab32098063 bump version to 0.7.16
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 14:44:23 +01:00
SafiandClaude Sonnet 4.6 994b17be46 fix #832 #831 #828 #826 #827: encoding, uv fallback, path scoring, cache, OpenCode trigger
- skill.md + skill-windows.md: add encoding="utf-8" to all read_text()/write_text()
  calls and ensure_ascii=False to json.dumps — bare calls defaulted to system
  codepage on Chinese-locale Windows, mojibaking non-ASCII content (#832)
- skill.md + skill-windows.md: prefer uv tool install --upgrade graphifyy over
  pip in the Step 1 install fallback — pip installs to the wrong env when
  graphify was installed via uv tool (#831)
- serve.py + __main__.py: replace flat substring scoring in _score_nodes with
  three-tier precedence (exact 1000 / prefix 100 / substring 1); _find_node
  returns results ordered exact→prefix→substring; both path CLI and MCP now
  emit a clear error when src and tgt resolve to the same node (#828)
- cache.py: normalize path key via .as_posix().lower() in file_hash so Windows
  junction/case variants hash identically; mirror abs-path normalization from
  save_semantic_cache into check_semantic_cache so relative source_file paths
  resolve the same way on both sides (#826)
- __main__.py: add /graphify skill trigger line to _AGENTS_MD_SECTION — affects
  all 7 AGENTS.md platforms (OpenCode, Codex, Aider, Trae, Hermes, Claw, Droid)
  so typing /graphify actually invokes the skill tool (#827)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 12:11:03 +01:00
SafiandClaude Sonnet 4.6 094d8ba731 fix #821 #818 #820: universal help guard, --version flag, Ollama num_ctx fallback
- Universal -h/--help/-? guard after cmd dispatch: any help flag anywhere in
  argv stops execution and prints "Run 'graphify --help'" instead of triggering
  the subcommand — cursor/kiro/gemini install --help no longer silently installs;
  benchmark --help no longer crashes with FileNotFoundError (#821)
- --version / -v / version subcommand: print graphify {__version__} and exit (#818)
- GRAPHIFY_OLLAMA_NUM_CTX=<invalid> now falls through to auto-derived num_ctx
  instead of hardcoding 131072 (the cap that causes OOM on constrained VRAM);
  pinned num_ctx < estimated input now triggers an explicit truncation warning
  with a suggested --token-budget correction (#820)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:18:48 +01:00
SafiandClaude Sonnet 4.6 dd465afd2c bump version to 0.7.14
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 18:49:16 +01:00
SafiandClaude Sonnet 4.6 95e2c5eb32 fix #811 #803 #801 #808: Unicode IDs, dedup edge keys, direction flip, chunk paths
- extract/_make_id + build/_normalize_id: use NFKC normalization and casefold
  so composed/decomposed Unicode forms produce the same ID; collapse consecutive
  underscores; both functions are now byte-for-byte equivalent (#811)
- dedup: use explicit key-presence check instead of `or` for source/from
  fallback; pop stale from/to keys so they don't leak into graph.json attrs (#803)
- skill --update: use build_merge() to avoid NetworkX round-trip direction flip;
  fix dict merge ordering so explicit source/target win; pull hyperedges from
  G.graph (merged) not new_extraction only (#801)
- skill subagents: inject absolute CHUNK_PATH so Write tool doesn't lose chunk
  files to undefined cwd (#808)
- __main__: skip skill version check during hook-check (runs on every editor
  tool use, must be silent); move warning to stderr

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 18:46:12 +01:00
Safi 4cec58e072 document GRAPHIFY_OLLAMA_NUM_CTX and GRAPHIFY_OLLAMA_KEEP_ALIVE env vars 2026-05-09 23:48:27 +01:00
Safi 9caaa17f7f bump version to 0.7.13 2026-05-09 23:45:43 +01:00
Safi 8c4c67f3ad fix Ollama num_ctx: derive from actual chunk size instead of hardcoding 131072 (#798) 2026-05-09 23:42:44 +01:00
Safi 5ead190891 wire callflow HTML into watch/hook rebuild: regenerates automatically if file exists 2026-05-09 23:29:43 +01:00
Porun db66b8727b feat: add callflow HTML export with Mermaid architecture diagrams 2026-05-09 23:26:01 +01:00
Safi 8c00287e84 fix Ollama context saturation: set num_ctx=131072, keep_alive=30m, serial by default (#798) 2026-05-09 22:51:36 +01:00
SafiandClaude Sonnet 4.6 e926079c0a bump version to 0.7.12, update README with new languages and extract flags
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 21:41:44 +01:00
SafiandClaude Sonnet 4.6 23f598f3a0 fix MultiGraph crash, hollow LLM response retry, and skill --help (#796, #795, #792)
#796: add edge_data()/edge_datas() helpers in build.py that tolerate
MultiGraph/MultiDiGraph; replace all G.edges[u,v] 2-tuple call sites in
__main__.py, serve.py, wiki.py, export.py, analyze.py, benchmark.py;
fix same pattern in 10 skill file inline heredocs

#795: all 12 skill files now short-circuit on /graphify --help or -h
and print the Usage block without running any pipeline steps

#792 (hollow response): add _response_is_hollow() predicate in llm.py;
when Ollama (or any backend) returns empty/null/whitespace content or a
parsed result with no nodes/edges, rewrite finish_reason="length" so
_extract_with_adaptive_retry bisects the chunk instead of silently
dropping it; applied to _call_openai_compat, _call_claude, _call_bedrock

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 21:17:25 +01:00
SafiandClaude Sonnet 4.6 dc50979a68 fix hook OOM, lift worker cap, fix antigravity .agents path and frontmatter
#791: per-repo fcntl flock in _rebuild_code prevents concurrent hook rebuilds
from exhausting memory; changed_paths wired through so only modified files are
re-extracted; stale nodes evicted on deletion; SIGALRM watchdog with
GRAPHIFY_REBUILD_TIMEOUT; Darwin-aware RLIMIT_DATA memory cap

#792: remove hard 8-worker cap (GRAPHIFY_MAX_WORKERS env var); add
--max-workers, --token-budget, --max-concurrency, --api-timeout CLI flags
to graphify extract; fix ollama API key gate for loopback URLs; explicit
timeout on OpenAI client (GRAPHIFY_API_TIMEOUT, default 600s); per-chunk
progress prints during extraction

#453 + #785: rename .agent -> .agents throughout antigravity install/uninstall;
add trigger:always_on YAML frontmatter to _ANTIGRAVITY_RULES so Antigravity
recognises the rules file

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 16:57:05 +01:00
SafiandClaude Sonnet 4.6 8e6483511d add Pascal regex fallback - extraction works without tree-sitter-pascal
tree-sitter-pascal is not on PyPI so extract_pascal() fell back to an
empty error result for all users. _extract_pascal_regex() now handles
unit/program/library headers, uses clauses, class/interface declarations
with inheritance, forward method decls, qualified impl headers, balanced
begin/end body extraction, and intra-file calls edges. All 15 previously
skipped pascal_required tests now run unconditionally and pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 15:52:17 +01:00
32bf8b4a37 feat(extract): add Pascal/Delphi and Lazarus IDE support (#781)
* feat(extract): add Pascal/Delphi language support

Adds full AST extraction for Pascal and Delphi source files using
tree-sitter-pascal (https://github.com/Isopod/tree-sitter-pascal).

Supported file extensions: .pas, .pp, .dpr, .dpk, .inc

Extracted nodes:
- File node (the .pas file itself)
- unit / program / library declarations
- class, interface, and helper type declarations
- procedure and function implementations

Extracted edges:
- file --contains--> module
- module --imports--> dependency (via uses clause, resolved to path-based IDs)
- class --inherits--> base class / interface
- class/module --contains/method--> procedure or function
- procedure --calls--> procedure (in-file call resolution)

Key design: uses clause targets are resolved to path-based node IDs by
scanning all Pascal files under the project root (_pascal_project_root +
_pascal_resolve_unit helpers). This avoids dangling import edges that
result from resolving bare unit names like "SysUtils" to IDs that never
match any file node.

Bare procedure calls (e.g. `Reset;` without parentheses) are detected
by inspecting statement nodes whose sole named child is an identifier,
in addition to the standard exprCall nodes used for calls with arguments.

Requires: pip install tree-sitter-pascal
(https://github.com/Isopod/tree-sitter-pascal)
If not installed, extract_pascal returns {"nodes":[], "edges":[], "error": ...}
so the rest of the pipeline is unaffected.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(extract): add Lazarus .lfm and .lpk file support

Adds two new extractors for Lazarus IDE-specific file formats:

extract_lazarus_form() — .lfm (Lazarus Form files)
  .lfm files are text-based UI component trees. The extractor parses
  `object Name: TClassName ... end` blocks to build a containment graph
  of form components, and captures `OnXxx = HandlerName` event bindings
  as `references` edges (context: "event") linking each component to
  its handler procedure.

extract_lazarus_package() — .lpk (Lazarus Package files)
  .lpk files are XML package definitions. The extractor reads the
  package name, required package dependencies (→ imports edges), and
  listed unit files (→ contains edges). Unit names are resolved to
  path-based node IDs via _pascal_resolve_unit so they connect to the
  same nodes produced by extract_pascal on .pas files.

Both extensions added to CODE_EXTENSIONS in detect.py and to _DISPATCH.
13 new tests in test_pascal.py cover both extractors.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(pascal): fix dangling inherits-edge targets and capture all base classes

The declType/typeref handler built inherits edge targets with
_make_id(_read(child)) — just the bare class name. But class nodes
use _make_id(stem, type_name), so targets never matched, making the
entire class hierarchy invisible in the graph.

Add _pascal_class_stem_cache and _pascal_resolve_class(): strips the
conventional T/I prefix, locates the defining file by stem lookup
(same cache mechanism as _pascal_resolve_unit), and returns the
correct _make_id(file_stem, class_name) ID. RTL/unresolvable bases
(e.g. TObject) fall back to _make_id(bare_name) with an explicit
stub node, following the same pattern as the Python extractor.

Also remove the `break` that stopped after the first typeref, so
all parents are captured (e.g. class(TBase, IInterface)).

Extend test_pascal_no_dangling_edges to also assert that within-file
edge targets (contains, method, inherits, calls) resolve to real nodes.

* feat(extract): add Delphi .dfm form file support

Adds extract_delphi_form() for Delphi Form files (.dfm), which use the
same `object Name: TClassName ... end` text syntax as Lazarus .lfm files.

Binary .dfm files (FF 0A magic header) are skipped gracefully with an
informative error message so the pipeline is unaffected.  Text .dfm files
are parsed identically to .lfm: component containment (`contains` edges)
and event handler references (`references`, context "event").

Adds .dfm to _DISPATCH and CODE_EXTENSIONS.
10 new tests in test_pascal.py, including a regression test for the
binary-format detection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add .lpr extension and fix removesuffix in Pascal extractor

Address review feedback from @safishamsi:
- Add .lpr (Lazarus program file, identical syntax to .dpr) to _DISPATCH
  in extract.py and CODE_EXTENSIONS in detect.py so Lazarus project entry
  points are indexed. Completes the promised Lazarus IDE support.
- Replace rstrip("()") with removesuffix("()") in the call-resolution
  dict comprehension for precise suffix removal (rstrip strips individual
  characters, not the literal string "()").
- Add .lpr assertions to test_pascal_dispatch_registered and
  test_pascal_detect_extensions_registered.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Simeon Bodurov <simeon.bodurov@speedy.bg>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 14:44:58 +01:00
SafiandClaude Sonnet 4.6 adf96da283 bump version to 0.7.11
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 13:10:42 +01:00
nauman73andNauman Hameed e5f263ba98 fix(windows): unblock pipeline on Windows consoles + missing __main__ guards (#788)
Three independent Windows compatibility fixes shipped together because they
all surface during the same first /graphify run on Windows.

graphify/benchmark.py
  print_benchmark() unconditionally printed U+2500 (box-drawing) and U+2192
  (rightwards arrow), which UnicodeEncodeError'd on stdouts that can't encode
  them — most notably the legacy Windows console at cp1252. New _safe()
  helper falls back to ASCII when the active stdout encoding can't carry the
  glyph; _hr() uses it. Two regression tests cover both paths and prove
  print_benchmark survives a cp1252-strict stream.

graphify/extract.py
  ProcessPoolExecutor on Windows uses spawn, so worker subprocesses
  re-import the calling __main__. When the caller is `python -c "..."` or a
  script without an `if __name__ == "__main__":` guard, the workers
  recursively spawn themselves and the pool dies. The user-visible failure
  was a 290-line traceback ending in BrokenProcessPool, hiding the actual
  cause. _extract_parallel now catches BrokenProcessPool, prints a one-line
  warning that names the __main__-guard idiom, and returns False so the
  public extract() routes to the existing _extract_sequential fallback. Two
  tests cover the parallel-returns-False contract and the sequential
  fallback wiring.

graphify/skill-windows.md
  Every `python -c "..."` block (30 in total) is replaced with a
  Write+run+delete pattern using PowerShell's literal here-string @'...'@.
  The old form was a quote-escaping minefield: any double-quote inside the
  Python source had to be backslash-escaped for the shell, and PowerShell's
  parser ate them inconsistently — failing on f-strings like
  `f'AST: {len(result["nodes"])} nodes'`. The new form passes Python source
  to disk literally, so what the model writes is what Python sees. The AST
  step's script template now includes an explicit `if __name__ == "__main__":`
  guard so multi-core extraction works even before the runtime fallback above
  kicks in. All 31 resulting heredoc blocks parse cleanly under
  `ast.parse`.

Co-authored-by: Nauman Hameed <Nauman.Hameed@enghouse.com>
2026-05-09 12:59:38 +01:00
tmaeder f88567b114 Recover from context-window-exceeded API errors in adaptive retry (#789)
Adaptive retry only recovered from `finish_reason="length"` (output
truncation). It did not handle the other shape of overflow: the API
rejecting the prompt outright with a 400 because the input plus
`max_completion_tokens` doesn't fit in the model's context window.

This shows up immediately on local OpenAI-compatible servers (LM
Studio, llama.cpp, vLLM) where the default context is small (4K-32K)
and a 60K-token chunk packed for cloud Kimi/Claude blows past it.
Without retry the whole chunk fails with no output, even though the
two halves would each fit cleanly.

Catch a heuristic set of context-overflow exception messages,
classify them as the same kind of recoverable failure as
`finish_reason="length"`, and split-recurse on the same path. Single-
file overflow returns an empty fragment so the rest of the corpus
keeps running. Unrelated errors (rate limit, auth, etc.) still
propagate.

Tested with qwen3.5-9b on LM Studio (32K ctx) against a 215-file
corpus where chunks 4-12 of 12 previously failed; with this change
the overflowing chunks self-heal by splitting in half.
2026-05-09 12:59:35 +01:00
SafiandClaude Sonnet 4.6 0c29b2cb88 fix reversed call edges after --update and missing SKILL.md on install (#760, #725)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 22:00:57 +01:00
SafiandClaude Sonnet 4.6 c8dcd03b08 document graphify uninstall command in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 20:40:07 +01:00
SafiandClaude Sonnet 4.6 480eaea2a8 add graphify uninstall command - removes all platforms in one shot
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 20:38:08 +01:00
zuyeyang 5d0392524a fix(extract): add ALTER TABLE FK extraction + schema-qualified name support for SQL (#779)
The SQL parser (`extract_sql`) previously only extracted foreign key
relationships defined inline within CREATE TABLE column definitions.
FK constraints added via ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY
... REFERENCES were silently ignored.

Additionally, `_obj_name()` only read the first identifier child of
object_reference nodes, so schema-qualified names like `Sales.Customer`
were truncated to just `Sales`.

Changes:
- Add `alter_table` handler to `walk()` that extracts FK edges from
  ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY ... REFERENCES
- Fix `_obj_name()` to read the full object_reference text, preserving
  schema-qualified names (e.g. `Sales.Customer`)
- Fix inline FK resolution in create_table and _walk_from_refs to use
  full object_reference text instead of first identifier only
2026-05-08 20:31:25 +01:00
SafiandClaude Sonnet 4.6 ef1050b0e4 bump version to 0.7.10
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 20:17:02 +01:00
Chris S ca1b774dd9 Harden Google Workspace gws exports (#772) 2026-05-07 20:07:57 +01:00
Arjun Pramanik e16ea149aa refactor(__main__): strengthen agent instructions sections with forceful graph-first directives (#775)
Rewrote _CLAUDE_MD_SECTION, _AGENTS_MD_SECTION, and _GEMINI_MD_SECTION to use forceful ALWAYS/NEVER directives instead of soft suggestions.
Agents must now consult the knowledge graph before file operations.

Context:
- Updated AGENTS.md template injected via _agents_install()
- Updated CLAUDE.md template injected via claude install
- Updated GEMINI.md template injected via gemini_install()
2026-05-07 20:07:53 +01:00
Arjun Pramanik a15cb36dfc fix(skills): rewrite YAML descriptions from pipeline-only to trigger-oriented (#774)
10 skill-*.md files had descriptions that only described what graphify does (input->pipeline->output), not when agents should use it. This meant skills never loaded proactively on codebase questions.

Changed to hybrid descriptions that retain the pipeline summary but add trigger conditions: 'Use when user asks any question about a codebase, project content, architecture, or file relationships'.
2026-05-07 20:07:49 +01:00
SerkanGeziciandSerkan Gezici 8489b26d06 fix(extract): use language_tsx for .tsx files to enable JSX-aware parsing (#766)
tree-sitter-typescript ships two grammars:
- language_typescript: pure TypeScript, no JSX support
- language_tsx:        JSX-aware variant for .tsx files

Currently both .ts and .tsx are parsed with language_typescript, which
treats JSX syntax as parse errors. Every function declaration, arrow
function, and call_expression nested inside a JSX tree is silently
dropped from the extracted graph.

Repro on a representative React+TypeScript codebase (a 13-file Tauri app):
parsing each .tsx with language_typescript produces ~276 ERROR nodes per
file. Only declarations that happen to live before the first JSX block
survive.

Fix: add _TSX_CONFIG that mirrors _TS_CONFIG but selects language_tsx,
and route .tsx files to it in extract_js().

Effect on the same repo (graphify update --force):
  Nodes:        303 → 618  (+104%)
  Edges:        482 → 779  (+62%)
  Communities:   28 → 45   (+61%)
  Parse errors  276 → 0    per .tsx file

Tests added:
- tsx fixture with helpers + JSX-returning component
- helpers and component are captured
- JSX expression calls ({fmtDate(now)}) resolve to call edges
- wiring check: .tsx uses language_tsx, .ts uses language_typescript

Note: this fixes the parsing layer. Calls inside deeply nested arrow
function callbacks (e.g. items.map(x => <T>{f(x)}</T>)) are still
missed by the call extraction logic — separate enhancement.

Co-authored-by: Serkan Gezici <serkan@quadroaipilot.com>
2026-05-07 20:07:36 +01:00
Safi 3e1c257dde add X link to README badges 2026-05-07 18:26:08 +01:00
Safi 853f4baad4 add PowerShell usage note to README 2026-05-07 16:37:35 +01:00
Safi 0656ec62a4 security hardening: F-002/F-005/F-007/F-008/F-009/F-010/F-016/F-031/F-035/F-038/PR747-NEW-2 2026-05-07 16:32:26 +01:00
Safi cf46be439a document AWS Bedrock backend in README privacy section and command reference 2026-05-07 14:51:41 +01:00
Safi aa2bd138b7 fix edges/links key mismatch in query, path, explain, and MCP loader (#768) 2026-05-07 14:48:51 +01:00
Safi 7c6c5242dc shrink star history chart width to 370px in README 2026-05-07 13:58:40 +01:00
Safi c8da4a7082 add Kimi Code CLI platform support (graphify install --platform kimi) 2026-05-07 13:16:15 +01:00
Safi 13947c3a05 add MCP resources: report, stats, god-nodes, surprises, audit, questions 2026-05-07 13:13:54 +01:00
SafiandClaude Sonnet 4.6 96c1d04889 bump version to 0.7.9, update README and CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 12:09:46 +01:00
SafiandClaude Sonnet 4.6 3529d46fd2 add PR numbers to 0.7.9 CHANGELOG entries
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 11:19:12 +01:00
Safi fe76612d90 Merge PR #708: TypeScript interface/enum/type-alias/const/new_expression extraction 2026-05-07 11:07:24 +01:00
Safi 30860b61fb changelog: 0.7.9 -- add .qmd Quarto support entry 2026-05-07 11:05:24 +01:00
Safi 62bcf754d3 Merge PR #761: add .qmd (Quarto) file extension support 2026-05-07 11:03:57 +01:00
Safi b1ea93586b add .qmd to to_obsidian_canvas safe_name regex 2026-05-07 11:03:42 +01:00
Safi 9bc79ef6e3 trim noisy scalar const types from js_extra_walk, collapse docstring 2026-05-07 11:02:15 +01:00
Safi 2d44788931 add .qmd to to_obsidian_canvas safe_name regex 2026-05-07 11:02:11 +01:00
SafiandClaude Sonnet 4.6 027fd7a1c1 remove spurious base_url from bedrock BACKENDS entry
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:53:53 +01:00
Safi 61e27fb1a5 add AWS Bedrock backend via boto3 Converse API 2026-05-07 10:51:45 +01:00
SafiandClaude Sonnet 4.6 669bc32e0d Merge PR #752: Google Workspace shortcut export (.gdoc/.gsheet/.gslides)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:42:23 +01:00
SafiandClaude Sonnet 4.6 6f15e5b102 pseudonymize Google account email with SHA256 hash in sidecar frontmatter
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:39:26 +01:00
SafiandClaude Sonnet 4.6 9bbd14a7dd Merge PR #753: CommonJS require() imports as EXTRACTED edges
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:28:44 +01:00
Safi 09e69745bc Merge PR #759: Positional install platform names 2026-05-07 10:25:56 +01:00
Safi c986e28a70 Merge PR #758: Fix GRAPHIFY_OUT for query/path/explain 2026-05-07 10:25:50 +01:00
Safi 78a16c3733 Merge PR #672: Silence file_type None warning 2026-05-07 10:25:40 +01:00
Safi 935312c227 Merge PR #671: tree-sitter version mismatch hint 2026-05-07 10:25:35 +01:00
shym 1026695da7 feat: add .qmd file extension support
Adds support for Quarto markdown (.qmd) files by:
- Adding '.qmd' to document file extensions in detection
- Updating export logic to handle .qmd in filename sanitization
- Adding .qmd extractor dispatch using the existing markdown extractor
- Updating watch comments to include .qmd files
2026-05-07 11:13:14 +09:00
Chris Stephens 68804f7f70 Handle positional install platforms 2026-05-06 17:10:45 -04:00
Chris Stephens 81bc2f9298 Fix GRAPHIFY_OUT defaults for graph query commands 2026-05-06 17:04:57 -04:00
Mani Saint-Victor, MD 2dd6ee6a9c fix: promote cross-file call edges to EXTRACTED when import evidence exists
The cross-file call resolver in `extract()` unconditionally marked every
resolved call edge as INFERRED with confidence_score 0.8 — even when the
caller's file had an explicit `imports` (symbol) or `imports_from`
(module) edge to the callee. The new CJS require handler made this gap
visible: imports were correctly EXTRACTED but the call edges that those
imports backed remained INFERRED, so downstream consumers couldn't tell
high-evidence calls apart from name-match guesses.

This pass runs after the file-id remap (line 4736), so we relativize
node `source_file` paths before computing file_nids — otherwise the
caller's computed file_nid (absolute-path-derived) wouldn't match the
imports_from edge source (already remapped to relative form).

Promotion rule:
  - Symbol-level `imports` edge from caller's file -> callee node id
    => EXTRACTED, confidence_score 1.0
  - Module-level `imports_from` edge from caller's file -> callee's file
    => EXTRACTED, confidence_score 1.0
  - Otherwise => INFERRED, confidence_score 0.8 (existing behavior)

Validated on a 92-file CJS orchestrator: 5 previously-INFERRED edges
from runExecute() now resolve to EXTRACTED, and 88% of cross-file calls
in the corpus (104 of 118) promote, leaving INFERRED only for genuine
heuristic guesses with no import backing.

Adds two tests:
  - test_cross_file_call_promoted_to_extracted_with_import_evidence
  - test_cross_file_call_remains_inferred_without_import_evidence
2026-05-06 13:13:30 -04:00
Chris Stephens f704972b3e Add optional Google Workspace shortcut export 2026-05-06 11:37:11 -04:00
Mani Saint-Victor, MD c902ae952b fix: extract CommonJS require() imports as EXTRACTED edges
The JS/TS extractor only handled ES `import` statements; CommonJS
`require()` calls produced no import edges. Downstream, the call-graph
pass could not resolve which symbols belonged to which file, so every
cross-file call in CJS Node.js codebases was downgraded to INFERRED
even when the binding was a top-of-file destructured require.

Adds three patterns to `_js_extra_walk` via a new `_require_imports_js`
helper:

  const { foo, bar: alias } = require('./mod')   -> imports_from + per-symbol imports
  const mod = require('./mod')                   -> imports_from
  const x = require('./mod').y                   -> imports_from + symbol edge for y

Refactors path-resolution out of `_import_js` into
`_resolve_js_import_target` so ES imports and CJS requires share the
relative / tsconfig-alias / bare-module logic.

Tested in a 92-file CJS Node.js orchestrator codebase: confirmed all
five previously INFERRED `runExecute -> {loadFoundation,
validateDispatchConfig, fetchSymphonyIssues, listSymphonyWorktrees,
workspacePathForIssue}` edges resolve to real top-of-file destructured
requires, so downstream calls would now be EXTRACTED instead of
INFERRED.
2026-05-06 09:41:56 -04:00
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
ibrahimyuecel eca3277fb9 feat(ts): extract interface, enum, type_alias, const literal, new_expression
Bring TypeScript AST extraction to parity with Java and C# by adding the
declaration types upstream graphify currently skips:

- interface_declaration (parity with Java/C# class_types)
- enum_declaration + members
- type_alias_declaration
- module-level const literals (object/array/string/call/new/template/number)
  via _js_extra_walk extension
- new_expression as call type for both _JS_CONFIG and _TS_CONFIG

Tested against tests/fixtures/typescript_advanced.ts: 8 expected node
types extracted (IUserRepository, UserStatus, UserId, USER_REPOSITORY,
DEFAULT_ROLES, USER_CONFIG, UserService, UserModule).

Validated on a 3,800-file TypeScript monorepo (NestJS + Next.js): yields
~1,885 interfaces, ~147 enums, ~405 type aliases, ~2,236 const literal
nodes, and ~1,935 instantiates edges that were previously invisible.
2026-05-04 20:46:36 +03: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
azizur100389 f87d0649c5 fix: silence "invalid file_type 'None'" warning on legacy graphs (#660)
Users running `graphify update .` against a graph that contains nodes
preserved from older graphify versions see the warning:

  [graphify] Extraction warning (31 issues): Node 1661 (id='telepathy_app')
  has invalid file_type 'None' - must be one of [...]

The cause: `_rebuild_code` in watch.py preserves nodes from the existing
graph.json that aren't in the new AST output. Some of those nodes
(stubs, semantic concepts created before file_type was always
populated) have file_type=null in the on-disk JSON, which becomes
Python None on load. The validator in validate.py:33 then flags every
such node.

Add a normalization step in `build_from_json` next to the existing
`source` -> `source_file` legacy canonicalization: if a node's
file_type is None or empty, default it to "concept" before validation.
This silences the false positive while keeping the validator strict for
genuinely invalid values like "weird_type".
2026-05-03 00:46:46 +01:00
azizur100389 189847eb47 fix: surface tree-sitter version-mismatch hint instead of bare TypeError
When a user has an older tree-sitter installed against a newer language
binding (or vice versa), Language() raises TypeError with messages like
"missing 1 required positional argument: 'name'". The previous catch-all
Exception handler stored that bare message in the per-file error field,
giving users no actionable signal.

Add a dedicated TypeError branch in _extract_generic() that returns a
clearer error with the upgrade command:

  tree-sitter version mismatch for tree_sitter_python: ... .
  Try: pip install --upgrade tree-sitter tree-sitter-languages

Behavior is unchanged for all non-version-mismatch errors - the broader
Exception handler still runs as before.
2026-05-03 00:27:10 +01:00
72 changed files with 12831 additions and 1029 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
+1
View File
@@ -21,6 +21,7 @@ Each stage is a single function in its own module. They communicate through plai
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
| `callflow_html.py` | `write_callflow_html(...)` | graphify-out files → Mermaid architecture/call-flow HTML |
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
| `security.py` | validation helpers | URL / path / label → validated or raises |
+152
View File
@@ -2,6 +2,158 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.7.16 (2026-05-12)
- Fix: all `read_text()`/`write_text()` calls in `skill.md` and `skill-windows.md` now specify `encoding="utf-8"` — bare calls defaulted to the system codepage on Chinese-locale Windows, silently mojibaking node labels and Markdown content on `--update` (#832)
- Fix: `json.dumps` in skill pipeline now uses `ensure_ascii=False` so Chinese/CJK characters are stored as-is rather than `\uXXXX` escaped (#832)
- Fix: Step 1 install fallback in skill now prefers `uv tool install --upgrade graphifyy` over `pip` when uv is on PATH — pip was installing to the wrong environment when graphify was originally installed via `uv tool` (#831)
- Fix: `_score_nodes` in `serve.py` now uses three-tier precedence (exact 1000 / prefix 100 / substring 1) instead of flat substring scoring — `graphify path "Foo" "FooBar"` no longer returns 0 hops when both labels substring-match the same node (#828)
- Fix: `graphify path` and MCP `_tool_shortest_path` now emit a clear error when source and target resolve to the same node, instead of silently returning 0 hops (#828)
- Fix: `file_hash` in `cache.py` now normalises path keys via `.as_posix().lower()` — Windows junction/case variants of the same file now hash identically, fixing `save_semantic_cache` always reporting "Cached 0 files" on subsequent `--update` runs (#826)
- Fix: `check_semantic_cache` now applies the same absolute-path normalization as `save_semantic_cache` so relative `source_file` paths resolve consistently on both sides (#826)
- Fix: `_AGENTS_MD_SECTION` now includes the `/graphify` skill trigger instruction — all 7 AGENTS.md platforms (OpenCode, Codex, Aider, Trae, Hermes, OpenClaw, Factory Droid) now correctly invoke the skill tool when the user types `/graphify` (#827)
## 0.7.15 (2026-05-11)
- Fix: `-h`/`--help`/`-?` in any position now stops execution — previously `graphify cursor install --help` silently installed into Cursor; `graphify benchmark --help` crashed with FileNotFoundError (#821)
- Fix: `--version`, `-v`, and `graphify version` now print the installed version and exit (#818)
- Fix: `GRAPHIFY_OLLAMA_NUM_CTX=<invalid>` no longer falls back to hardcoded 131072 (which exhausted VRAM) — it now falls through to the auto-derived value and prints a warning (#820)
- Fix: when `GRAPHIFY_OLLAMA_NUM_CTX` is set smaller than the estimated chunk size, graphify now warns explicitly that Ollama will silently truncate the prompt and suggests a corrected `--token-budget` (#820)
## 0.7.14 (2026-05-11)
- Fix: `_make_id` and `_normalize_id` now apply NFKC Unicode normalization before ID generation -- composed/decomposed forms of the same character (e.g. `é` typed vs pasted from a PDF) now produce the same node ID; switched from `.lower()` to `.casefold()` for correct Turkish/German/Greek case folding; both functions are now byte-for-byte equivalent (#811)
- Fix: non-ASCII identifiers (CJK, Cyrillic, Arabic, accented Latin) are no longer collapsed to a bare file stem -- `[^\w]+` with `re.UNICODE` replaces the old `[^a-zA-Z0-9]+` so Unicode word chars are preserved as part of the ID (#811)
- Fix: dedup edge remap uses explicit key-presence check instead of `or` so empty-string `source` is not silently swapped for `from`; stale `from`/`to` keys are now popped before the edge is emitted so they can't leak into `graph.json` edge attributes (#803)
- Fix: `--update` merge now calls `build_merge()` directly instead of an inline NetworkX round-trip that re-introduced the direction-flip bug from #760; dict merge ordering fixed so explicit `source`/`target` always win over stale attrs; hyperedges pulled from `G.graph` (merged) rather than just the new extraction (#801)
- Fix: subagent chunk files are now written to an absolute path (`CHUNK_PATH` injected at dispatch time from `graphify-out/.graphify_root`) so the Write tool doesn't lose chunks to an undefined working directory (#808)
- Fix: skill version mismatch warning is now suppressed during `hook-check` (runs on every editor tool use and must be silent) and routed to stderr for all other commands
## 0.7.13 (2026-05-09)
- Fix: Ollama `num_ctx` now derived from actual chunk size instead of hardcoded 131072 -- over-allocating 128k KV-cache slots for small chunks exhausted VRAM by chunk 4 on large models; formula is `min(input_tokens + output_cap + 2000, 131072)` so `--token-budget 8192` gets ~26k instead of 131072 (#798)
- Fix: hollow-response warning now mentions VRAM pressure and `GRAPHIFY_OLLAMA_NUM_CTX` / `GRAPHIFY_OLLAMA_KEEP_ALIVE` env vars as tuning knobs (#798)
- Feat: `graphify export callflow-html` -- generates a self-contained Mermaid architecture/call-flow HTML page from `graphify-out/graph.json`, grouped by community with interactive zoom/pan diagrams, call detail tables, and graph report highlights (#797)
- Feat: callflow HTML auto-regenerates on every `--watch` rebuild and post-commit hook if the file already exists -- opt-in by existence, zero config (#800)
## 0.7.12 (2026-05-09)
- Fix: `graphify explain` and `graphify path` no longer crash on `MultiGraph` inputs -- new `edge_data()`/`edge_datas()` helpers in `build.py` handle both simple and multi-graphs; all 8 production call sites and 30 skill-file inline heredocs updated (#796)
- Fix: hollow Ollama responses (0 tokens / empty string) now trigger adaptive retry bisection instead of silently dropping the chunk -- `_response_is_hollow()` detects empty/null/whitespace content and parsed results with no nodes/edges, then rewrites `finish_reason="length"` to route into the existing bisection path (#792)
- Fix: post-commit hook no longer spawns unbounded parallel rebuilds -- per-repo `fcntl.flock` non-blocking lock in `_rebuild_code`; `changed_paths` wired from hook through to AST extractor; stale nodes evicted on deletion; `GRAPHIFY_REBUILD_TIMEOUT` watchdog; Darwin-aware memory cap (#791)
- Fix: Antigravity install now writes to `.agents/` (plural) -- corrected in platform config, paths, workflow body, and help text (#453)
- Fix: Antigravity rules file now includes `trigger: always_on` YAML frontmatter so Antigravity recognises it (#785)
- Feat: `graphify extract` gains `--max-workers`, `--token-budget`, `--max-concurrency`, `--api-timeout` flags; hard 8-worker AST cap removed; explicit HTTP timeout on OpenAI client (default 600s, `GRAPHIFY_API_TIMEOUT`); ollama API key gate skipped for loopback URLs (#792)
- Feat: Pascal/Delphi extraction now works without `tree-sitter-pascal` -- regex fallback covers unit/program/library headers, uses clauses, class/interface inheritance, method declarations, and intra-file calls (#781)
- Feat: `/graphify --help` now prints the Usage block and stops without running pipeline steps (all 12 skill files) (#795)
## 0.7.11 (2026-05-09)
- Fix: context-window-exceeded API errors now trigger automatic retry with bisected file chunks -- exponential bisection up to 6 levels deep; covers `"context_length_exceeded"`, `"maximum context length"`, and `"too_large"` across OpenAI-compat backends (#789)
- Fix: Windows pipeline unblocked -- `print_benchmark()` falls back to ASCII box-drawing on cp1252 consoles; `ProcessPoolExecutor` `BrokenProcessPool` caught and falls back to sequential extraction when caller lacks `if __name__ == "__main__":` guard; Windows skill file (`skill-windows.md`) rewrites all `python -c "..."` blocks as PowerShell heredocs to fix quote-escaping failures (#788)
- Fix: reversed `calls` edges after `--update` -- `build_merge()` now reads the saved JSON directly instead of round-tripping through NetworkX `node_link_graph()`, which was silently reversing edge direction on reload (#760)
- Fix: atomic SKILL.md install -- temp-file + `os.replace()` pattern prevents half-installed empty skill directories that looked valid but contained no file; version-stamp guard and warning added for missing installs (#725)
- Feat: `graphify uninstall` top-level command -- removes graphify skill files from all platforms in one shot; `--purge` flag also deletes `graphify-out/`
- Feat: SQL `ALTER TABLE` FK extraction -- `ADD CONSTRAINT ... FOREIGN KEY` and `ADD FOREIGN KEY` DDL statements now emit `references` edges; schema-qualified table names (`schema.table`) correctly resolved (#779)
## 0.7.10 (2026-05-07)
- Fix: `.tsx` files now use `language_tsx` grammar for JSX-aware parsing -- previously `language_typescript` was used, silently dropping all JSX-specific nodes (#766)
- Fix: `edges` key in saved graph JSON now normalised to `links` before loading -- prevents `KeyError: 'links'` on graphs written by older NetworkX versions in `query`, `path`, `explain`, and serve (#768)
- Fix: Google Workspace `gws export` drops unsupported `resourceKey` query param -- Drive API requires it as an HTTP header; sending it as a query param was a silent no-op (#772)
- Security: eleven hardening fixes -- Cypher escape strips C0 control chars and `\n`/`\r`; YAML frontmatter escapes U+2028, U+2029, tabs, and C0; MCP `sanitize_label` applied to all LLM-derived fields; C preprocessor blocked from `#include` exfiltration via `-nostdinc -I /dev/null`; merge-driver 50 MB file size cap and 100k node cap; `detect_backend()` places Ollama last so paid API keys take precedence over ambient `OLLAMA_BASE_URL`; Neo4j `--password` reads from `NEO4J_PASSWORD` env var by default; hooks exception handling narrowed to `(configparser.Error, OSError)`
- Refactor: skill YAML descriptions rewritten to be trigger-oriented (#774)
- Refactor: generated `CLAUDE.md` / `AGENTS.md` / `GEMINI.md` templates strengthened with `ALWAYS`/`NEVER`/`IF ... EXISTS` graph-first directives (#775)
## 0.7.9 (2026-05-07)
- Feat: TypeScript extraction parity -- interface, enum, type alias, and module-level const nodes extracted; new_expression emits calls edges; parity with Java/C# class_types (#708)
- Feat: Quarto (`.qmd`) file support -- routed through existing Markdown extractor; Quarto executable code blocks (` ```{python} `) extracted as code nodes (#761)
- Feat: optional Google Workspace shortcut export for headless extraction -- `graphify extract ./docs --google-workspace` converts `.gdoc`, `.gsheet`, and `.gslides` files into Markdown sidecars with the `gws` CLI before semantic extraction; account email pseudonymized via SHA256 hash; `[google]` extra adds Sheets table rendering support (#752)
- Fix: Google Workspace exports now run `gws` from the sidecar output directory with a relative `-o` path, matching `gws` path validation and avoiding failures when extracting a corpus outside the current working directory.
- Feat: AWS Bedrock backend -- `graphify extract ./docs --backend bedrock`; credentials via standard AWS provider chain (AWS_PROFILE, AWS_REGION, IAM roles, SSO); model via GRAPHIFY_BEDROCK_MODEL (default anthropic.claude-3-5-sonnet-20241022-v2:0); `[bedrock]` extra adds boto3 (#757)
## 0.7.8 (2026-05-06)
- Fix: CommonJS `require()` imports now extracted from JS/TS -- `const { foo } = require('./mod')`, `const m = require('./mod')`, and `const x = require('./mod').y` all emit EXTRACTED `imports_from` (and per-symbol `imports`) edges. Previously CJS-only Node.js codebases produced AST graphs missing every import edge, which downgraded all cross-file calls to INFERRED.
- Fix: cross-file `calls` edges are now promoted from INFERRED to EXTRACTED when the caller's file has an explicit `imports` or `imports_from` edge to the callee. Previously every cross-file call was unconditionally INFERRED, even when a top-of-file `import` / `require` proved the binding. On a 92-file CJS Node.js corpus this promoted 88% of cross-file calls (104 of 118) to EXTRACTED.
- 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)
+70 -9
View File
@@ -8,22 +8,23 @@
<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://clickpy.clickhouse.com/dashboard/graphifyy"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsql-clickhouse.clickhouse.com%2F%3Fquery%3DSELECT%2520concat%2528toString%2528round%2528sum%2528count%2529%2F1000%2529%2529%2C%2520%2527k%2527%2529%2520AS%2520c%2520FROM%2520pypi.pypi_downloads%2520WHERE%2520project%253D%2527graphifyy%2527%2520FORMAT%2520JSON%26user%3Ddemo&query=%24.data%5B0%5D.c&label=downloads&color=blue" alt="Downloads"/></a>
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
</p>
<p align="center">
<a href="https://star-history.com/#safishamsi/graphify&Date">
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="600"/>
<img src="https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date" alt="Star History Chart" width="370"/>
</a>
</p>
Type `/graphify` in your AI coding assistant and it maps your entire project — code, docs, PDFs, images, videos — into a knowledge graph you can query instead of grepping through files.
Works in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, and Google Antigravity.
Works in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, and Google Antigravity.
```
/graphify .
@@ -38,6 +39,12 @@ graphify-out/
└── graph.json the full graph — query it anytime without re-reading your files
```
For a readable architecture page with Mermaid call-flow diagrams, run:
```bash
graphify export callflow-html
```
---
## Install
@@ -52,6 +59,8 @@ uv tool install graphifyy && graphify install
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell and will cause a "not recognized" error.
> **`graphify: command not found`?** Use `uv tool install graphifyy` or `pipx install graphifyy` — both put the CLI on PATH automatically. With plain `pip`, add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify`.
### Pick your platform
@@ -71,6 +80,7 @@ uv tool install graphifyy && graphify install
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Hermes | `graphify install --platform hermes` |
| Kimi Code | `graphify install --platform kimi` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify install --platform pi` |
| Cursor | `graphify cursor install` |
@@ -100,13 +110,14 @@ Run this once in your project after building a graph:
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
| Hermes | `graphify hermes install` |
| Kimi Code | `graphify install --platform kimi` |
| Kiro IDE/CLI | `graphify kiro install` |
| Pi coding agent | `graphify pi install` |
| Google Antigravity | `graphify antigravity install` |
This writes a small config file that tells your assistant to read `GRAPH_REPORT.md` before answering questions about your codebase. On platforms that support hooks (Claude Code, Codex, Gemini CLI), a hook fires automatically before every file-read call — your assistant navigates by the graph instead of grepping through everything.
Uninstall with the matching command (e.g. `graphify claude uninstall`).
To remove graphify from all platforms at once: `graphify uninstall` (add `--purge` to also delete `graphify-out/`). Or use the per-platform command (e.g. `graphify claude uninstall`).
---
@@ -124,9 +135,10 @@ 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` |
| Docs | `.md .mdx .html .txt .rst .yaml .yml` |
| Code (29 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk` |
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (requires `pip install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `pip install graphifyy[google]`) |
| PDFs | `.pdf` |
| Images | `.png .jpg .webp .gif` |
| Video / Audio | `.mp4 .mov .mp3 .wav` and more (requires `pip install graphifyy[video]`) |
@@ -134,6 +146,20 @@ Uninstall with the matching command (e.g. `graphify claude uninstall`).
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
Google Drive for desktop `.gdoc`, `.gsheet`, and `.gslides` files are shortcut
pointers, not document content. To include native Google Docs, Sheets, and Slides
in a headless extraction, install and authenticate the
[`gws` CLI](https://github.com/googleworkspace/cli), then run:
```bash
pip install "graphifyy[google]" # needed for Google Sheets table rendering
gws auth login -s drive
graphify extract ./docs --google-workspace
```
You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into
`graphify-out/converted/` as Markdown sidecars, then extracts those files.
---
## Common commands
@@ -144,6 +170,7 @@ Code is extracted locally with no API calls (AST via tree-sitter). Everything el
/graphify . --cluster-only # rerun clustering without re-extracting
/graphify . --no-viz # skip the HTML, just the report + JSON
/graphify . --wiki # build a markdown wiki from the graph
graphify export callflow-html # architecture/call-flow HTML from graphify-out/
/graphify query "what connects auth to the database?"
/graphify path "UserService" "DatabasePool"
@@ -192,7 +219,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.
---
@@ -206,6 +233,9 @@ graphify query "what connects DigestAuth to Response?" --graph graphify-out/grap
# expose the graph as an MCP server (for repeated tool-call access)
python -m graphify.serve graphify-out/graph.json
# register with Kimi Code:
kimi mcp add --transport stdio graphify -- python -m graphify.serve graphify-out/graph.json
```
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`.
@@ -221,7 +251,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), a running Ollama instance (`OLLAMA_BASE_URL`), or AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM). The `--dedup-llm` flag uses the same key.
- No telemetry, no usage tracking, no analytics.
---
@@ -254,6 +284,9 @@ The MCP server gives your assistant structured access: `query_graph`, `get_node`
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
graphify uninstall # remove from all platforms in one shot
graphify uninstall --purge # also delete graphify-out/
graphify hook install # post-commit + post-checkout hooks
graphify hook uninstall
graphify hook status
@@ -273,12 +306,40 @@ 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, ollama, or bedrock
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL) - no API key needed for loopback
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # override KV-cache window (auto-sized by default)
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # unload model after each chunk (saves VRAM on small GPUs)
graphify extract ./docs --backend bedrock # AWS Bedrock via IAM - no API key, uses AWS credential chain
graphify extract ./docs --max-workers 16 # AST parallelism (also GRAPHIFY_MAX_WORKERS)
graphify extract ./docs --token-budget 30000 # smaller semantic chunks for local/small models
graphify extract ./docs --max-concurrency 2 # fewer parallel LLM calls (useful for local inference)
graphify extract ./docs --api-timeout 900 # longer HTTP timeout for slow local models (default 600s)
graphify extract ./docs --google-workspace # export .gdoc/.gsheet/.gslides via gws before extraction
graphify extract ./docs --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 export callflow-html # graphify-out/<project>-callflow.html
graphify export callflow-html --max-sections 8 # cap generated architecture sections
graphify export callflow-html --output docs/arch.html
graphify export callflow-html ./some-repo/graphify-out
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
```
---
+6
View File
@@ -13,6 +13,12 @@ Video and audio files are transcribed with faster-whisper. To focus the transcri
**Pass 3 — Docs, papers, images (Claude subagents, costs tokens)**
Claude runs in parallel over markdown, PDFs, images, and transcripts. Each subagent reads a batch of files and outputs a JSON fragment: nodes, edges, and any group relationships. The fragments are merged into a single graph.
Before Pass 3, optional converters turn supported pointer/binary formats into
Markdown sidecars under `graphify-out/converted/`. Office files (`.docx`,
`.xlsx`) use the `[office]` extra. Google Workspace shortcuts (`.gdoc`,
`.gsheet`, `.gslides`) are opt-in with `--google-workspace` or
`GRAPHIFY_GOOGLE_WORKSPACE=1` and require an authenticated `gws` CLI.
---
## How community detection works
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
+1056 -45
View File
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -3,6 +3,8 @@ from __future__ import annotations
from pathlib import Path
import networkx as nx
from graphify.build import edge_data
# Language families — extensions sharing a runtime can legitimately call each other
_LANG_FAMILY: dict[str, str] = {
**{e: "python" for e in (".py", ".pyw")},
@@ -301,7 +303,7 @@ def _cross_community_surprises(
top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
result = []
for (u, v), score in top_edges:
data = G.edges[u, v]
data = edge_data(G, u, v)
result.append({
"source": G.nodes[u].get("label", u),
"target": G.nodes[v].get("label", v),
+26 -3
View File
@@ -1,14 +1,36 @@
"""Token-reduction benchmark - measures how much context graphify saves vs naive full-corpus approach."""
from __future__ import annotations
import json
import sys
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.build import edge_data
_CHARS_PER_TOKEN = 4 # standard approximation
def _safe(unicode_char: str, ascii_fallback: str) -> str:
"""Return unicode_char if stdout can encode it, else ascii_fallback.
Windows consoles often default to cp1252 which cannot encode box-drawing
or arrow glyphs; printing them raises UnicodeEncodeError mid-output.
"""
encoding = getattr(sys.stdout, "encoding", None) or ""
try:
unicode_char.encode(encoding)
return unicode_char
except (UnicodeEncodeError, LookupError):
return ascii_fallback
def _hr(width: int = 50) -> str:
"""Horizontal rule that survives non-UTF-8 stdout (e.g. Windows cp1252 console)."""
return _safe("─", "-") * width
def _estimate_tokens(text: str) -> int:
return max(1, len(text) // _CHARS_PER_TOKEN)
@@ -46,7 +68,7 @@ def _query_subgraph_tokens(G: nx.Graph, question: str, depth: int = 3) -> int:
lines.append(f"NODE {d.get('label', nid)} src={d.get('source_file', '')} loc={d.get('source_location', '')}")
for u, v in edges_seen:
if u in visited and v in visited:
d = G.edges[u, v]
d = edge_data(G, u, v)
lines.append(f"EDGE {G.nodes[u].get('label', u)} --{d.get('relation', '')}--> {G.nodes[v].get('label', v)}")
return _estimate_tokens("\n".join(lines))
@@ -118,8 +140,9 @@ def print_benchmark(result: dict) -> None:
return
print(f"\ngraphify token reduction benchmark")
print(f"{'─' * 50}")
print(f" Corpus: {result['corpus_words']:,} words → ~{result['corpus_tokens']:,} tokens (naive)")
print(_hr(50))
arrow = _safe("→", "->")
print(f" Corpus: {result['corpus_words']:,} words {arrow} ~{result['corpus_tokens']:,} tokens (naive)")
print(f" Graph: {result['nodes']:,} nodes, {result['edges']:,} edges")
print(f" Avg query cost: ~{result['avg_query_tokens']:,} tokens")
print(f" Reduction: {result['reduction_ratio']}x fewer tokens per query")
+108 -22
View File
@@ -24,19 +24,24 @@ from __future__ import annotations
import json
import re
import sys
import unicodedata
from pathlib import Path
import networkx as nx
from .validate import validate_extraction
def _normalize_id(s: str) -> str:
"""Normalize an ID string the same way extract._make_id does.
r"""Normalize an ID string the same way extract._make_id does.
Used to reconcile edge endpoints when the LLM generates IDs with slightly
different punctuation or casing than the AST extractor.
different punctuation or casing than the AST extractor. Must stay in sync
with extract._make_id — NFKC normalization, \w with re.UNICODE, underscore
collapse, and casefold must all match (#811).
"""
cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", s)
return cleaned.strip("_").lower()
s = unicodedata.normalize("NFKC", s)
cleaned = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
cleaned = re.sub(r"_+", "_", cleaned)
return cleaned.strip("_").casefold()
def _norm_source_file(p: str | None) -> str | None:
@@ -45,6 +50,27 @@ def _norm_source_file(p: str | None) -> str | None:
return p.replace("\\", "/") if p else p
def edge_data(G: nx.Graph, u: str, v: str) -> dict:
"""Return one edge attribute dict for (u, v), tolerating MultiGraph.
For MultiGraph/MultiDiGraph there can be multiple parallel edges;
this returns the first one (sufficient for callers that only need
relation/confidence for rendering). Fixes #796.
"""
raw = G[u][v]
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
return next(iter(raw.values()), {})
return raw
def edge_datas(G: nx.Graph, u: str, v: str) -> list[dict]:
"""Return every edge attribute dict for (u, v); always a list."""
raw = G[u][v]
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
return list(raw.values())
return [raw]
def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
"""Build a NetworkX graph from an extraction dict.
@@ -57,7 +83,9 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
# Canonicalize legacy node/edge schema before validation.
for node in extraction.get("nodes", []):
if isinstance(node, dict) and "source" in node and "source_file" not in node:
if not isinstance(node, dict):
continue
if "source" in node and "source_file" not in node:
# Count edges that reference this node so the warning is actionable (#479)
node_id = node.get("id", "?")
affected_edges = sum(
@@ -71,6 +99,12 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
file=sys.stderr,
)
node["source_file"] = node.pop("source")
# Default missing/None file_type to "concept" so legacy graph.json
# entries (and stub nodes preserved by `_rebuild_code` from older
# graphify versions that didn't always populate file_type) don't
# trigger spurious "invalid file_type 'None'" validator warnings (#660).
if node.get("file_type") in (None, ""):
node["file_type"] = "concept"
errors = validate_extraction(extraction)
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
@@ -116,17 +150,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 +178,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,32 +243,34 @@ 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.
Never replaces — only grows (or prunes deleted-file nodes via prune_sources).
Never replaces - only grows (or prunes deleted-file nodes via prune_sources).
Safe to call repeatedly: existing nodes and edges are preserved.
"""
from networkx.readwrite import json_graph as _jg
graph_path = Path(graph_path)
if graph_path.exists():
# Read JSON directly instead of going through node_link_graph().
# The latter rebuilds an undirected nx.Graph and then enumerating
# edges() yields endpoints based on node insertion order, which
# silently flips directional edges (e.g. `calls`) when the callee
# was inserted before the caller. The _src/_tgt direction-preserving
# attrs are popped before saving in export.py, so going through the
# NetworkX round-trip loses direction permanently (#760).
data = json.loads(graph_path.read_text(encoding="utf-8"))
try:
existing_G = _jg.node_link_graph(data, edges="links")
except TypeError:
existing_G = _jg.node_link_graph(data)
# Reconstruct as a plain extraction dict so build() can merge it
existing_nodes = [{"id": n, **existing_G.nodes[n]} for n in existing_G.nodes]
existing_edges = [
{"source": u, "target": v, **d} for u, v, d in existing_G.edges(data=True)
]
links_key = "links" if "links" in data else "edges"
existing_nodes = list(data.get("nodes", []))
existing_edges = list(data.get(links_key, []))
base = [{"nodes": existing_nodes, "edges": existing_edges}]
else:
existing_nodes = []
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 +279,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 +305,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)
+6 -3
View File
@@ -55,9 +55,9 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
h.update(b"\x00")
try:
rel = p.resolve().relative_to(Path(root).resolve())
h.update(str(rel).encode())
h.update(rel.as_posix().lower().encode())
except ValueError:
h.update(str(p.resolve()).encode())
h.update(p.resolve().as_posix().lower().encode())
return h.hexdigest()
@@ -190,7 +190,10 @@ def check_semantic_cache(
uncached: list[str] = []
for fpath in files:
result = load_cached(Path(fpath), root, kind="semantic")
p = Path(fpath)
if not p.is_absolute():
p = Path(root) / p
result = load_cached(p, root, kind="semantic")
if result is not None:
cached_nodes.extend(result.get("nodes", []))
cached_edges.extend(result.get("edges", []))
File diff suppressed because it is too large. Load diff
+355
View File
@@ -0,0 +1,355 @@
"""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)
# Tolerate "from"/"to" keys from LLM backends that don't follow the
# schema exactly — build_from_json normalises later but dedup runs
# first so bracket access would KeyError here (#803).
# Use explicit key presence check (not `or`) so empty-string src/tgt
# aren't silently replaced by the fallback key.
src = e["source"] if "source" in e else e.get("from")
tgt = e["target"] if "target" in e else e.get("to")
if src is None or tgt is None:
continue
e["source"] = remap.get(src, src)
e["target"] = remap.get(tgt, tgt)
# Remove legacy keys so they don't leak into edge attrs in graph.json.
e.pop("from", None)
e.pop("to", None)
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 as exc:
# F-038: previously this silent fallback hid the fact that `_call_llm`
# didn't exist in `graphify.llm` at all, so `--dedup-llm` was a no-op.
# Surface the import failure so future regressions are visible.
print(
f"[graphify] --dedup-llm: cannot import _call_llm ({exc}); skipping LLM tiebreaker.",
flush=True,
)
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)
+51 -7
View File
@@ -7,6 +7,12 @@ import re
from enum import Enum
from pathlib import Path
from graphify.google_workspace import (
GOOGLE_WORKSPACE_EXTENSIONS,
convert_google_workspace_file,
google_workspace_enabled,
)
class FileType(str, Enum):
CODE = "code"
@@ -18,8 +24,8 @@ 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'}
DOC_EXTENSIONS = {'.md', '.mdx', '.txt', '.rst', '.html', '.yaml', '.yml'}
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', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
@@ -33,7 +39,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),
@@ -130,6 +136,8 @@ def classify_file(path: Path) -> FileType | None:
return FileType.DOCUMENT
if ext in OFFICE_EXTENSIONS:
return FileType.DOCUMENT
if ext in GOOGLE_WORKSPACE_EXTENSIONS:
return FileType.DOCUMENT
if ext in VIDEO_EXTENSIONS:
return FileType.VIDEO
return None
@@ -239,7 +247,12 @@ def xlsx_extract_structure(path: Path) -> dict:
except Exception:
return {"nodes": [], "edges": []}
stem = _re.sub(r"[^a-z0-9]", "_", path.stem.lower())
# F-035: typo fix — was `_re.sub` (NameError, but unreachable because the
# whole xlsx codepath is currently behind a feature flag / not yet wired
# into the dispatcher). Before re-enabling this path, re-audit it for
# zip/XML bombs (openpyxl is built on top of zipfile and lxml-style XML
# parsing — a malicious .xlsx can blow up memory at load_workbook time).
stem = re.sub(r"[^a-z0-9]", "_", path.stem.lower())
str_path = str(path)
file_nid = _nid(str_path)
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "document",
@@ -618,8 +631,9 @@ def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Pa
return False
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool | None = None) -> dict:
root = root.resolve()
google_workspace = google_workspace_enabled() if google_workspace is None else google_workspace
files: dict[FileType, list[str]] = {
FileType.CODE: [],
FileType.DOCUMENT: [],
@@ -694,6 +708,25 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
continue
ftype = classify_file(p)
if ftype:
if p.suffix.lower() in GOOGLE_WORKSPACE_EXTENSIONS:
if not google_workspace:
skipped_sensitive.append(
str(p)
+ " [Google Workspace shortcut skipped - pass --google-workspace "
"or set GRAPHIFY_GOOGLE_WORKSPACE=1]"
)
continue
try:
md_path = convert_google_workspace_file(p, converted_dir, xlsx_to_markdown=xlsx_to_markdown)
except Exception as exc:
skipped_sensitive.append(str(p) + f" [Google Workspace export failed: {exc}]")
continue
if md_path:
files[ftype].append(str(md_path))
total_words += count_words(md_path)
else:
skipped_sensitive.append(str(p) + " [Google Workspace export produced no readable text]")
continue
# Office files: convert to markdown sidecar so subagents can read them
if p.suffix.lower() in OFFICE_EXTENSIONS:
md_path = convert_office_file(p, converted_dir)
@@ -771,7 +804,13 @@ 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,
google_workspace: bool | None = None,
) -> dict:
"""Like detect(), but returns only new or modified files since the last run.
Fast path: mtime unchanged → unchanged (free, no hash).
@@ -779,8 +818,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, google_workspace=google_workspace)
manifest = load_manifest(manifest_path)
if not manifest:
+158 -19
View File
@@ -10,6 +10,16 @@ import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.analyze import _node_community_map
from graphify.build import edge_data
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
@@ -17,6 +27,44 @@ def _strip_diacritics(text: str) -> str:
return "".join(c for c in nfkd if not unicodedata.combining(c))
def _yaml_str(s: str) -> str:
"""Escape a value for safe embedding in a YAML double-quoted scalar (F-009).
See `graphify.ingest._yaml_str` for the full rationale; duplicated here to
avoid pulling the URL-fetching `ingest` module into export's dependency
graph. Handles backslash, double-quote, all line breaks (\\n, \\r,
U+2028, U+2029), tab, NUL, and other C0/DEL control characters that
would otherwise let a hostile `source_file` / `community` / etc. break
out of the YAML scalar and inject sibling keys.
"""
if s is None:
return ""
out: list[str] = []
for ch in str(s):
cp = ord(ch)
if ch == "\\":
out.append("\\\\")
elif ch == '"':
out.append('\\"')
elif ch == "\n":
out.append("\\n")
elif ch == "\r":
out.append("\\r")
elif ch == "\t":
out.append("\\t")
elif ch == "\0":
out.append("\\0")
elif cp == 0x2028:
out.append("\\L")
elif cp == 0x2029:
out.append("\\P")
elif cp < 0x20 or cp == 0x7F:
out.append(f"\\x{cp:02x}")
else:
out.append(ch)
return "".join(out)
COMMUNITY_COLORS = [
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
"#EDC948", "#B07AA1", "#FF9DA7", "#9C755F", "#BAB0AC",
@@ -340,7 +388,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 +441,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
@@ -404,8 +465,48 @@ def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:
def _cypher_escape(s: str) -> str:
"""Escape a string for safe embedding in a Cypher single-quoted literal."""
return s.replace("\\", "\\\\").replace("'", "\\'")
"""Escape a string for safe embedding in a Cypher single-quoted literal.
Handles all characters that could prematurely terminate the literal or
inject control sequences:
- `\\` and `'` (literal terminators)
- newlines/CRs (would break the per-line statement framing)
- NUL/control bytes (defensive — Neo4j errors on raw NULs)
Also strips any leading/trailing whitespace that would let an attacker
break the `;`-terminated statement boundary used by `cypher-shell`.
Closing `}` and `)` are NOT special inside a single-quoted Cypher string,
so escaping the quote and backslash correctly is sufficient (a `}` inside
a properly-closed `'...'` literal is just a character) — but we previously
missed `\\n` / `\\r` which DO let a payload break out of the statement
line and inject a fresh MATCH/DELETE on the following line. See F-008.
"""
# First normalise: drop NUL and other C0 control chars except tab.
s = "".join(ch for ch in s if ch >= " " or ch == "\t")
return (
s.replace("\\", "\\\\")
.replace("'", "\\'")
.replace("\n", "\\n")
.replace("\r", "\\r")
)
# Restrict identifier-position values (labels and relationship types are NOT
# quoted in Cypher and so cannot be safely escaped — they must be allowlisted).
_CYPHER_IDENT_RE = re.compile(r"[^A-Za-z0-9_]")
def _cypher_label(raw: str, fallback: str) -> str:
"""Sanitise a value used in identifier position (node label / rel type).
Cypher does not provide a way to escape `:Foo` label syntax, so we must
strip everything except `[A-Za-z0-9_]` and require the result to start
with a letter; otherwise we fall back to a safe constant.
"""
cleaned = _CYPHER_IDENT_RE.sub("", raw or "")
if not cleaned or not cleaned[0].isalpha():
return fallback
return cleaned
def to_cypher(G: nx.Graph, output_path: str) -> None:
@@ -413,12 +514,17 @@ def to_cypher(G: nx.Graph, output_path: str) -> None:
for node_id, data in G.nodes(data=True):
label = _cypher_escape(data.get("label", node_id))
node_id_esc = _cypher_escape(node_id)
_ft = re.sub(r"[^A-Za-z0-9_]", "", data.get("file_type", "unknown").capitalize())
ftype = (_ft if _ft and _ft[0].isalpha() else "Entity")
ftype = _cypher_label(
(data.get("file_type", "unknown") or "unknown").capitalize(),
"Entity",
)
lines.append(f"MERGE (n:{ftype} {{id: '{node_id_esc}', label: '{label}'}});")
lines.append("")
for u, v, data in G.edges(data=True):
rel = re.sub(r"[^A-Za-z0-9_]", "_", data.get("relation", "RELATES_TO").upper())
rel = _cypher_label(
(data.get("relation", "RELATES_TO") or "RELATES_TO").upper(),
"RELATES_TO",
)
conf = _cypher_escape(data.get("confidence", "EXTRACTED"))
u_esc = _cypher_escape(u)
v_esc = _cypher_escape(v)
@@ -436,6 +542,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 +552,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, "
@@ -593,7 +730,7 @@ def to_obsidian(
def safe_name(label: str) -> str:
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
# Strip trailing .md/.mdx/.markdown so "CLAUDE.md" doesn't become "CLAUDE.md.md"
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"\.(md|mdx|qmd|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
node_filename: dict[str, str] = {}
@@ -639,20 +776,22 @@ 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] = []
# YAML frontmatter - readable in Obsidian's properties panel
# YAML frontmatter - readable in Obsidian's properties panel.
# All scalars pass through _yaml_str so a hostile source_file or
# community label cannot break out and inject sibling keys (F-009).
lines += [
"---",
f'source_file: "{data.get("source_file", "")}"',
f'type: "{ftype}"',
f'community: "{community_name}"',
f'source_file: "{_yaml_str(data.get("source_file", ""))}"',
f'type: "{_yaml_str(ftype)}"',
f'community: "{_yaml_str(community_name)}"',
]
if data.get("source_location"):
lines.append(f'location: "{data["source_location"]}"')
lines.append(f'location: "{_yaml_str(str(data["source_location"]))}"')
# Add tags list to frontmatter
lines.append("tags:")
for tag in node_tags:
@@ -664,10 +803,10 @@ def to_obsidian(
if neighbors:
lines.append("## Connections")
for neighbor in sorted(neighbors, key=lambda n: G.nodes[n].get("label", n)):
edge_data = G.edges[node_id, neighbor]
edata = edge_data(G, node_id, neighbor)
neighbor_label = node_filename[neighbor]
relation = edge_data.get("relation", "")
confidence = edge_data.get("confidence", "EXTRACTED")
relation = edata.get("relation", "")
confidence = edata.get("confidence", "EXTRACTED")
lines.append(f"- [[{neighbor_label}]] - `{relation}` [{confidence}]")
lines.append("")
@@ -751,7 +890,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")
@@ -831,7 +970,7 @@ def to_canvas(
def safe_name(label: str) -> str:
cleaned = re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip()
cleaned = re.sub(r"\.(md|mdx|markdown)$", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"\.(md|mdx|qmd|markdown)$", "", cleaned, flags=re.IGNORECASE)
return cleaned or "unnamed"
# Build node_filenames if not provided (same dedup logic as to_obsidian)
+2018 -119
View File
File diff suppressed because it is too large. Load diff
+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
+223
View File
@@ -0,0 +1,223 @@
"""Optional Google Workspace shortcut export support.
Google Drive for desktop stores native Docs, Sheets, and Slides as small JSON
shortcut files (.gdoc, .gsheet, .gslides). Those files are pointers, not the
document content. This module exports them to Markdown sidecars via the
googleworkspace CLI (`gws`) so Graphify can extract their actual contents.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
import urllib.parse
from pathlib import Path
from typing import Callable, Any
GOOGLE_WORKSPACE_EXTENSIONS = {".gdoc", ".gsheet", ".gslides"}
def google_workspace_enabled(value: str | None = None) -> bool:
"""Return True when Google Workspace shortcut export is enabled."""
raw = value if value is not None else os.environ.get("GRAPHIFY_GOOGLE_WORKSPACE", "")
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _safe_yaml_str(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
def _extract_file_id_from_url(url: str) -> str | None:
"""Extract a Drive file ID from common Google Docs/Drive URL shapes."""
if not url:
return None
parsed = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(parsed.query)
if query.get("id"):
return query["id"][0]
match = re.search(r"/(?:document|spreadsheets|presentation|file)/d/([^/?#]+)", parsed.path)
if match:
return match.group(1)
return None
def _extract_resource_key(url: str, data: dict[str, Any]) -> str | None:
for key in ("resource_key", "resourceKey"):
value = data.get(key)
if value:
return str(value)
if not url:
return None
parsed = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(parsed.query)
if query.get("resourcekey"):
return query["resourcekey"][0]
return None
def read_google_shortcut(path: Path) -> dict[str, str | None]:
"""Read a .gdoc/.gsheet/.gslides shortcut and return export metadata."""
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
raise RuntimeError(f"could not read Google Workspace shortcut {path}: {exc}") from exc
url = str(data.get("url") or "")
file_id = (
data.get("doc_id")
or data.get("file_id")
or data.get("fileId")
or data.get("id")
or _extract_file_id_from_url(url)
)
if not file_id:
resource_id = str(data.get("resource_id") or "")
if ":" in resource_id:
file_id = resource_id.split(":", 1)[1]
if not file_id:
raise RuntimeError(f"Google Workspace shortcut {path} does not include a Drive file ID")
return {
"file_id": str(file_id),
"url": url or None,
"resource_key": _extract_resource_key(url, data),
"account": str(data.get("email")) if data.get("email") else None,
}
def _run_gws_export(file_id: str, mime_type: str, output: Path, resource_key: str | None = None) -> None:
exe = shutil.which("gws")
if not exe:
raise RuntimeError(
"gws is required for Google Workspace export. Install it from "
"https://github.com/googleworkspace/cli and run `gws auth login -s drive`."
)
params: dict[str, str] = {"fileId": file_id, "mimeType": mime_type}
# Drive resource keys are sent via X-Goog-Drive-Resource-Keys. The current
# gws export command has no custom-header flag, so do not pass resourceKey
# as an unsupported query parameter.
_ = resource_key
output = output.resolve()
output.parent.mkdir(parents=True, exist_ok=True)
timeout = int(os.environ.get("GRAPHIFY_GOOGLE_WORKSPACE_TIMEOUT", "120"))
result = subprocess.run(
[exe, "drive", "files", "export", "--params", json.dumps(params), "-o", output.name],
capture_output=True,
cwd=output.parent,
text=True,
timeout=timeout,
)
if result.returncode != 0:
stderr = (result.stderr or result.stdout or "").strip()
if len(stderr) > 1200:
stderr = stderr[:1200] + "..."
raise RuntimeError(f"gws export failed for {file_id}: {stderr}")
def _sidecar_path(path: Path, out_dir: Path) -> Path:
name_hash = hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:8]
return out_dir / f"{path.stem}_{name_hash}.md"
def _with_frontmatter(path: Path, shortcut: dict[str, str | None], body: str, exported_mime_type: str) -> str:
source_url = shortcut.get("url") or ""
account = shortcut.get("account") or ""
account_line = ""
if account:
account_hash = hashlib.sha256(account.encode()).hexdigest()[:12]
account_line = f'google_account_hash: "{account_hash}"\n'
return (
"---\n"
f'source_file: "{_safe_yaml_str(str(path))}"\n'
'source_type: "google_workspace"\n'
f'google_file_id: "{_safe_yaml_str(shortcut["file_id"] or "")}"\n'
f'google_export_mime_type: "{_safe_yaml_str(exported_mime_type)}"\n'
f'source_url: "{_safe_yaml_str(source_url)}"\n'
f"{account_line}"
"---\n\n"
f"<!-- converted from Google Workspace shortcut: {path.name} -->\n\n"
f"{body.strip()}\n"
)
def convert_google_workspace_file(
path: Path,
out_dir: Path,
*,
xlsx_to_markdown: Callable[[Path], str] | None = None,
) -> Path | None:
"""Export a Google Workspace shortcut to a Markdown sidecar.
Returns the converted Markdown path, or None when conversion is unsupported
or produced no readable content.
"""
ext = path.suffix.lower()
if ext not in GOOGLE_WORKSPACE_EXTENSIONS:
return None
shortcut = read_google_shortcut(path)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = _sidecar_path(path, out_dir)
if ext == ".gdoc":
with tempfile.NamedTemporaryFile("w+b", suffix=".md", delete=False, dir=out_dir) as tmp:
tmp_path = Path(tmp.name)
try:
_run_gws_export(shortcut["file_id"] or "", "text/markdown", tmp_path, shortcut.get("resource_key"))
body = tmp_path.read_text(encoding="utf-8", errors="replace")
finally:
tmp_path.unlink(missing_ok=True)
if not body.strip():
return None
out_path.write_text(_with_frontmatter(path, shortcut, body, "text/markdown"), encoding="utf-8")
return out_path
if ext == ".gslides":
with tempfile.NamedTemporaryFile("w+b", suffix=".txt", delete=False, dir=out_dir) as tmp:
tmp_path = Path(tmp.name)
try:
_run_gws_export(shortcut["file_id"] or "", "text/plain", tmp_path, shortcut.get("resource_key"))
body = tmp_path.read_text(encoding="utf-8", errors="replace")
finally:
tmp_path.unlink(missing_ok=True)
if not body.strip():
return None
out_path.write_text(_with_frontmatter(path, shortcut, body, "text/plain"), encoding="utf-8")
return out_path
if ext == ".gsheet":
if xlsx_to_markdown is None:
raise RuntimeError("Google Sheets export requires the office extra: pip install graphifyy[office,google]")
with tempfile.NamedTemporaryFile("w+b", suffix=".xlsx", delete=False, dir=out_dir) as tmp:
tmp_path = Path(tmp.name)
try:
_run_gws_export(
shortcut["file_id"] or "",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
tmp_path,
shortcut.get("resource_key"),
)
body = xlsx_to_markdown(tmp_path)
finally:
tmp_path.unlink(missing_ok=True)
if not body.strip():
return None
out_path.write_text(
_with_frontmatter(
path,
shortcut,
body,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
),
encoding="utf-8",
)
return out_path
return None
+52 -20
View File
@@ -1,7 +1,8 @@
# git hook integration - install/uninstall graphify post-commit and post-checkout hooks
from __future__ import annotations
import configparser
import re
import subprocess
import sys
from pathlib import Path
_HOOK_MARKER = "# graphify-hook-start"
@@ -68,7 +69,7 @@ _GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
echo "[graphify hook] launching background rebuild (log: $_GRAPHIFY_LOG)"
nohup $GRAPHIFY_PYTHON -c "
import os, sys
import os, signal, sys
from pathlib import Path
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
@@ -80,10 +81,17 @@ if not changed:
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
try:
import os as _os
from graphify.watch import _rebuild_code
_force = _os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
_rebuild_code(Path('.'), force=_force)
from graphify.watch import _rebuild_code, _apply_resource_limits
_apply_resource_limits()
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
signal.alarm(_timeout)
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
_rebuild_code(Path('.'), changed_paths=changed, force=_force)
except TimeoutError as exc:
print(f'[graphify hook] {exc}')
sys.exit(1)
except Exception as exc:
print(f'[graphify hook] Rebuild failed: {exc}')
sys.exit(1)
@@ -124,12 +132,23 @@ _GRAPHIFY_LOG="${HOME}/.cache/graphify-rebuild.log"
mkdir -p "$(dirname "$_GRAPHIFY_LOG")"
echo "[graphify] Branch switched - launching background rebuild (log: $_GRAPHIFY_LOG)"
nohup $GRAPHIFY_PYTHON -c "
from graphify.watch import _rebuild_code
from graphify.watch import _rebuild_code, _apply_resource_limits
from pathlib import Path
import os, sys
import os, signal, sys
try:
_apply_resource_limits()
_timeout = int(os.environ.get('GRAPHIFY_REBUILD_TIMEOUT', '600'))
if _timeout > 0 and hasattr(signal, 'SIGALRM'):
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(TimeoutError(f'graphify rebuild exceeded {_timeout}s')))
signal.alarm(_timeout)
_force = os.environ.get('GRAPHIFY_FORCE', '').lower() in ('1', 'true', 'yes')
# post-checkout: branch switch can touch arbitrary files; full rebuild path
# (no changed_paths) is correct here. The flock inside _rebuild_code still
# prevents pile-ups when commit + checkout fire back-to-back.
_rebuild_code(Path('.'), force=_force)
except TimeoutError as exc:
print(f'[graphify] {exc}')
sys.exit(1)
except Exception as exc:
print(f'[graphify] Rebuild failed: {exc}')
sys.exit(1)
@@ -151,20 +170,33 @@ 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):
pass
except (configparser.Error, OSError) as exc:
# Narrow the exception (PR747-NEW-2): a bare `except Exception: pass`
# was hiding tampering signals (corrupt .git/config, permission flips
# by another tool). Surface them on stderr instead of silently
# falling through to the default hooks directory.
print(
f"[graphify hooks] could not read core.hooksPath from "
f"{root / '.git' / 'config'}: {exc}",
file=sys.stderr,
)
d = root / ".git" / "hooks"
d.mkdir(exist_ok=True)
return d
+39 -2
View File
@@ -11,8 +11,45 @@ from graphify.security import safe_fetch, safe_fetch_text, validate_url
def _yaml_str(s: str) -> str:
"""Escape a string for embedding in a YAML double-quoted scalar."""
return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
"""Escape a string for embedding in a YAML double-quoted scalar.
Handles every YAML 1.1/1.2 line-break and control character that could
let a hostile value (e.g. a fetched page title) break out of the quoted
scalar and inject sibling YAML keys (F-009 / F-019). The previous
implementation missed `\\t`, `\\0`, the unicode line-separator U+2028 and
paragraph-separator U+2029 — all of which YAML treats as line breaks.
We intentionally do not depend on PyYAML (not in pyproject deps) and
instead emit safely-escaped double-quoted scalars by hand: the YAML
double-quoted form recognises `\\\\`, `\\"`, `\\n`, `\\r`, `\\t`, `\\0`,
`\\L` (U+2028), `\\P` (U+2029), and `\\xNN`/`\\uNNNN` numeric escapes.
"""
if s is None:
return ""
out: list[str] = []
for ch in str(s):
cp = ord(ch)
if ch == "\\":
out.append("\\\\")
elif ch == '"':
out.append('\\"')
elif ch == "\n":
out.append("\\n")
elif ch == "\r":
out.append("\\r")
elif ch == "\t":
out.append("\\t")
elif ch == "\0":
out.append("\\0")
elif cp == 0x2028:
out.append("\\L")
elif cp == 0x2029:
out.append("\\P")
elif cp < 0x20 or cp == 0x7F:
out.append(f"\\x{cp:02x}")
else:
out.append(ch)
return "".join(out)
def _safe_filename(url: str, suffix: str) -> str:
+532 -35
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,56 @@ 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,
},
"bedrock": {
"default_model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"model_env_key": "GRAPHIFY_BEDROCK_MODEL",
"pricing": {"input": 3.0, "output": 15.0}, # USD per 1M tokens
"temperature": 0,
"max_tokens": 16384,
},
}
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.
@@ -93,8 +142,22 @@ def _read_files(paths: list[Path], root: Path) -> str:
return "\n\n".join(parts)
_LLM_JSON_MAX_BYTES = 10 * 1024 * 1024 # 10 MB hard cap before json.loads (F-016)
def _parse_llm_json(raw: str) -> dict:
"""Strip optional markdown fences and parse JSON. Returns empty fragment on failure."""
"""Strip optional markdown fences and parse JSON. Returns empty fragment on failure.
Caps the input at `_LLM_JSON_MAX_BYTES` so a hostile or runaway model
response cannot exhaust memory inside `json.loads` (F-016).
"""
if len(raw) > _LLM_JSON_MAX_BYTES:
print(
f"[graphify] LLM response exceeds {_LLM_JSON_MAX_BYTES} bytes "
f"({len(raw)} bytes); refusing to parse and dropping chunk.",
file=sys.stderr,
)
return {"nodes": [], "edges": [], "hyperedges": []}
if raw.startswith("```"):
raw = raw.split("```", 2)[1]
if raw.startswith("json"):
@@ -107,38 +170,162 @@ def _parse_llm_json(raw: str) -> dict:
return {"nodes": [], "edges": [], "hyperedges": []}
def _response_is_hollow(raw_content: str | None, parsed: dict) -> bool:
"""Detect a successful HTTP response that yielded no usable extraction.
A local model under load (most often Ollama) can return HTTP 200 with an
empty / null `message.content`, with whitespace, or with a half-generated
JSON prefix that fails to parse. All of these collapse to a "successful"
call producing zero nodes and zero edges. Without this check the chunk
is silently dropped from the corpus because no exception is raised and
`finish_reason` is `"stop"` rather than `"length"`. By flagging the
result as hollow, callers can re-route it through the same bisection
path used for context-window overflow and `finish_reason="length"`.
"""
if raw_content is None or not raw_content.strip():
return True
nodes = parsed.get("nodes")
edges = parsed.get("edges")
hyperedges = parsed.get("hyperedges")
return not nodes and not edges and not 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)
env_key = cfg.get("env_key")
if env_key:
return [env_key]
return []
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."""
keys = _backend_env_keys(backend)
return " or ".join(keys) if keys else "AWS_PROFILE or AWS_REGION"
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)
# Local backends (ollama, llama.cpp, vLLM) routinely take >60s for a
# single chunk on a large model — far longer than the openai SDK's
# default. Honour GRAPHIFY_API_TIMEOUT (seconds) for explicit override;
# default to 600s, which is long enough for a 31B model on a 16k chunk
# but still bounds runaway connections (issue #792 addendum).
timeout_raw = os.environ.get("GRAPHIFY_API_TIMEOUT", "").strip()
timeout_s: float = 600.0
if timeout_raw:
try:
v = float(timeout_raw)
if v > 0:
timeout_s = v
except ValueError:
pass
client = OpenAI(api_key=api_key, base_url=base_url, timeout=timeout_s)
kwargs: dict = {
"model": model,
"messages": [
{"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"}}
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
# than that — the symptom is hollow 200 OK responses after the first few
# chunks (#798). We derive num_ctx from the actual prompt size so we don't
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
# hollow-200 symptom — just from a different direction (#798 follow-up).
# Formula: actual input tokens + output cap + system prompt headroom.
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
if backend == "ollama":
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
# Auto-derive num_ctx from actual chunk size regardless — used as the
# fallback and for the mismatch check below.
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
auto_num_ctx = max(auto_num_ctx, 8192)
if num_ctx_raw:
try:
num_ctx = int(num_ctx_raw)
except ValueError:
# Bad env var: fall through to auto-derivation (not 131072 —
# hardcoding the cap is what causes OOM on constrained VRAM).
print(
f"[graphify] GRAPHIFY_OLLAMA_NUM_CTX={num_ctx_raw!r} is not a valid integer; "
f"using auto-derived value ({auto_num_ctx}).",
file=sys.stderr,
)
num_ctx = auto_num_ctx
else:
# Warn when the pinned value is smaller than the estimated input —
# Ollama silently truncates the prompt and returns empty responses.
if num_ctx < estimated_input:
print(
f"[graphify] warning: GRAPHIFY_OLLAMA_NUM_CTX={num_ctx} is smaller than "
f"the estimated chunk input (~{estimated_input} tokens). Ollama will "
f"silently truncate the prompt and return empty responses. "
f"Try --token-budget {max(1024, num_ctx // 3)} or increase NUM_CTX.",
file=sys.stderr,
)
else:
# Estimate input tokens: user_message chars / 4 (standard BPE
# heuristic) + 400 for the system prompt, then add output headroom.
num_ctx = auto_num_ctx
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
kwargs["extra_body"] = {"options": {"num_ctx": num_ctx}, "keep_alive": keep_alive}
resp = client.chat.completions.create(**kwargs)
result = _parse_llm_json(resp.choices[0].message.content or "{}")
raw_content = resp.choices[0].message.content
result = _parse_llm_json(raw_content or "{}")
result["input_tokens"] = resp.usage.prompt_tokens if resp.usage else 0
result["output_tokens"] = resp.usage.completion_tokens if resp.usage else 0
result["model"] = model
@@ -146,10 +333,35 @@ 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
# An overwhelmed local model (typically Ollama) can return HTTP 200 with
# empty / null content or unparseable half-generated JSON. The call looks
# successful, `finish_reason` is `"stop"`, and the chunk would be silently
# dropped from the corpus. Re-label as `"length"` so the adaptive retry
# layer bisects the chunk — same recovery as a true truncation.
if _response_is_hollow(raw_content, result) and result["finish_reason"] != "length":
print(
f"[graphify] {backend or 'backend'} returned a hollow response "
f"(content={'empty' if not (raw_content or '').strip() else 'no nodes/edges'}, "
f"output_tokens={result['output_tokens']}); "
"treating as truncation so adaptive retry can bisect the chunk.",
file=sys.stderr,
)
result["finish_reason"] = "length"
output_tokens = result["output_tokens"]
if output_tokens < 50 and backend == "ollama":
print(
"[graphify] warning: ollama returned very few tokens — likely causes: "
"(1) VRAM pressure: check `nvidia-smi` and reduce chunk size with "
"--token-budget (e.g. --token-budget 4096) or set "
"GRAPHIFY_OLLAMA_NUM_CTX to a smaller value; "
"(2) model too small for JSON instruction following — "
"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,11 +374,12 @@ 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}],
)
result = _parse_llm_json(resp.content[0].text if resp.content else "{}")
raw_content = resp.content[0].text if resp.content else None
result = _parse_llm_json(raw_content or "{}")
result["input_tokens"] = resp.usage.input_tokens if resp.usage else 0
result["output_tokens"] = resp.usage.output_tokens if resp.usage else 0
result["model"] = model
@@ -174,6 +387,57 @@ def _call_claude(api_key: str, model: str, user_message: str) -> dict:
# vocabulary so the adaptive-retry layer doesn't have to know which
# backend produced the result.
result["finish_reason"] = "length" if resp.stop_reason == "max_tokens" else "stop"
if _response_is_hollow(raw_content, result) and result["finish_reason"] != "length":
print(
"[graphify] claude returned a hollow response; treating as "
"truncation so adaptive retry can bisect the chunk.",
file=sys.stderr,
)
result["finish_reason"] = "length"
return result
def _call_bedrock(model: str, user_message: str, max_tokens: int = 8192) -> dict:
"""Call AWS Bedrock via boto3 Converse API using the standard AWS credential chain."""
try:
import boto3
import botocore.exceptions
except ImportError as exc:
raise ImportError(
"AWS Bedrock extraction requires boto3. Run: pip install graphifyy[bedrock]"
) from exc
region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or "us-east-1"
profile = os.environ.get("AWS_PROFILE")
session = boto3.Session(profile_name=profile, region_name=region)
client = session.client("bedrock-runtime")
try:
resp = client.converse(
modelId=model,
system=[{"text": _EXTRACTION_SYSTEM}],
messages=[{"role": "user", "content": [{"text": user_message}]}],
inferenceConfig={"maxTokens": max_tokens, "temperature": 0},
)
except botocore.exceptions.ClientError as exc:
code = exc.response["Error"]["Code"]
msg = exc.response["Error"]["Message"]
raise RuntimeError(f"Bedrock API error ({code}): {msg}") from exc
text = resp.get("output", {}).get("message", {}).get("content", [{}])[0].get("text", "{}")
result = _parse_llm_json(text)
usage = resp.get("usage", {})
result["input_tokens"] = usage.get("inputTokens", 0)
result["output_tokens"] = usage.get("outputTokens", 0)
result["model"] = model
result["finish_reason"] = "length" if resp.get("stopReason") == "max_tokens" else "stop"
if _response_is_hollow(text, result) and result["finish_reason"] != "length":
print(
"[graphify] bedrock returned a hollow response; treating as "
"truncation so adaptive retry can bisect the chunk.",
file=sys.stderr,
)
result["finish_reason"] = "length"
return result
@@ -193,19 +457,43 @@ 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"], "")
if not key:
key = api_key or _get_backend_api_key(backend)
if not key and backend == "ollama":
# Ollama ignores auth but the OpenAI client library requires a non-empty
# string. Use a placeholder and surface a visible warning so this never
# silently routes traffic without the user realising — see F-029.
ollama_url = os.environ.get("OLLAMA_BASE_URL", cfg.get("base_url", ""))
_validate_ollama_base_url(ollama_url)
print(
"[graphify] WARNING: ollama backend selected with no OLLAMA_API_KEY set; "
f"sending corpus to {ollama_url}. Set OLLAMA_API_KEY (any non-empty value) "
"to suppress this warning.",
file=sys.stderr,
)
key = "ollama"
if not key and backend != "bedrock":
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)
else:
return _call_openai_compat(cfg["base_url"], key, mdl, user_msg, temperature=cfg.get("temperature", 0))
return _call_claude(key, mdl, user_msg, max_tokens=max_out)
if backend == "bedrock":
return _call_bedrock(mdl, user_msg, max_tokens=max_out)
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:
@@ -272,6 +560,35 @@ def _pack_chunks_by_tokens(
return chunks
_CONTEXT_EXCEEDED_MARKERS = (
"context size",
"context length",
"context_length",
"context window",
"n_keep",
"exceeds the available",
"n_ctx",
"maximum context",
"too many tokens",
"prompt is too long",
"context_length_exceeded",
)
def _looks_like_context_exceeded(exc: BaseException) -> bool:
"""Heuristically classify an exception as a context-window overflow.
Different backends raise different exception types and messages for the
same underlying problem ("the prompt + max_completion_tokens did not fit
in the model's context window"). We match on substrings of the stringified
exception so the retry layer can recover without depending on a specific
SDK class. False positives are cheap (we'll re-extract on halves and
likely recover); false negatives are expensive (chunk fails entirely).
"""
msg = str(exc).lower()
return any(marker in msg for marker in _CONTEXT_EXCEEDED_MARKERS)
def _extract_with_adaptive_retry(
chunk: list[Path],
backend: str,
@@ -281,26 +598,79 @@ def _extract_with_adaptive_retry(
max_depth: int,
_depth: int = 0,
) -> dict:
"""Extract a chunk; if the response is truncated (`finish_reason="length"`),
"""Extract a chunk; if the response is truncated (`finish_reason="length"`)
or the API rejects the prompt as too large for the model's context window,
split the chunk in half and recurse.
The signal driving the retry is the API's own `finish_reason` — `"length"`
means the model hit `max_completion_tokens` mid-output. The truncated JSON
has nothing useful in it (parse fails partway through a string or array),
so we discard it and re-extract on smaller inputs that produce shorter
outputs.
Three signals drive the retry, all funnelled through the same code:
- `finish_reason == "length"` — the model accepted the input but ran out of
`max_completion_tokens` mid-output. The truncated JSON is unparseable, so
we discard it and re-extract on smaller inputs that produce shorter
outputs.
- context-window-exceeded API errors — the model rejected the input
outright (HTTP 400 from LM Studio, llama.cpp, vLLM, OpenAI, etc.).
Without a retry the whole chunk would fail with no output. Splitting in
half is the same recovery as for the `length` case and works for the
same reason.
- hollow successful responses — the model returned HTTP 200 with empty,
null, or unparseable content (typical of a local Ollama under load).
`_call_openai_compat` re-labels these as `finish_reason="length"` so they
take the same recovery path; without that the chunk would be silently
dropped from the corpus.
Recursion is capped at `max_depth` to bound worst-case cost. A chunk of N
files can split into up to 2**max_depth pieces — at depth=3 that's 8x. If
still truncated at the cap, we surface the (likely empty) result with a
still failing at the cap, we surface the (likely empty) result with a
warning rather than infinite-loop.
A single-file chunk that truncates is unrecoverable here — we can't make
A single-file chunk that overflows is unrecoverable here — we can't make
one file smaller than itself, so we return what we got and warn.
"""
result = extract_files_direct(
chunk, backend=backend, api_key=api_key, model=model, root=root
)
try:
result = extract_files_direct(
chunk, backend=backend, api_key=api_key, model=model, root=root
)
except Exception as exc: # noqa: BLE001 — re-raise unless it's a known context overflow
if not _looks_like_context_exceeded(exc):
raise
if len(chunk) <= 1:
print(
f"[graphify] single-file chunk {chunk[0]} exceeds model context "
f"and cannot be split further: {exc}",
file=sys.stderr,
)
return {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0, "model": model, "finish_reason": "stop"}
if _depth >= max_depth:
print(
f"[graphify] chunk of {len(chunk)} still overflows context at "
f"recursion depth {_depth} (max {max_depth}) — dropping",
file=sys.stderr,
)
return {"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0, "model": model, "finish_reason": "stop"}
print(
f"[graphify] chunk of {len(chunk)} exceeded context at depth "
f"{_depth} ({type(exc).__name__}); splitting in half and retrying",
file=sys.stderr,
)
mid = len(chunk) // 2
left = _extract_with_adaptive_retry(
chunk[:mid], backend, api_key, model, root, max_depth, _depth + 1
)
right = _extract_with_adaptive_retry(
chunk[mid:], backend, api_key, model, root, max_depth, _depth + 1
)
return {
"nodes": left.get("nodes", []) + right.get("nodes", []),
"edges": left.get("edges", []) + right.get("edges", []),
"hyperedges": left.get("hyperedges", []) + right.get("hyperedges", []),
"input_tokens": left.get("input_tokens", 0) + right.get("input_tokens", 0),
"output_tokens": left.get("output_tokens", 0) + right.get("output_tokens", 0),
"model": model,
"finish_reason": "stop",
}
if result.get("finish_reason") != "length":
return result
@@ -419,6 +789,11 @@ def extract_corpus_parallel(
except Exception as exc: # noqa: BLE001 — caller-facing surface, log + continue
return idx, None, exc
# Ollama serves one request at a time per loaded model on a single GPU.
# Four concurrent 60k-token requests cause VRAM pressure and hollow
# responses after 3-4 chunks (#798). Force serial unless the user opts in.
if backend == "ollama" and os.environ.get("GRAPHIFY_OLLAMA_PARALLEL", "").strip() != "1":
max_concurrency = 1
workers = max(1, min(max_concurrency, total))
if workers == 1:
# Avoid thread pool overhead for single-worker runs (and keep
@@ -457,6 +832,83 @@ def _merge_into(merged: dict, result: dict) -> None:
merged["output_tokens"] += result.get("output_tokens", 0)
def _call_llm(prompt: str, *, backend: str, max_tokens: int = 200) -> str:
"""Send a plain-text prompt to `backend` and return the model's text reply.
Used by lightweight callers (e.g. `graphify.dedup` LLM tiebreaker) that
don't need the full extraction prompt or JSON-shaped output. Mirrors the
backend dispatch logic of `extract_files_direct` but skips the
`_EXTRACTION_SYSTEM` prompt and JSON parsing.
Previously `graphify.dedup` imported a `_call_llm` symbol that did not
exist in this module, so the LLM tiebreaker silently no-op'd on
`ImportError` (F-038). Adding the function here re-enables it.
"""
if backend not in BACKENDS:
raise ValueError(f"Unknown backend {backend!r}")
cfg = BACKENDS[backend]
key = _get_backend_api_key(backend)
if not key and backend == "ollama":
ollama_url = os.environ.get("OLLAMA_BASE_URL", cfg.get("base_url", ""))
_validate_ollama_base_url(ollama_url)
key = "ollama"
if not key and backend != "bedrock":
raise ValueError(
f"No API key for backend '{backend}'. Set {_format_backend_env_keys(backend)}."
)
mdl = _default_model_for_backend(backend)
if backend == "claude":
try:
import anthropic
except ImportError as exc:
raise ImportError("anthropic package required for claude backend") from exc
client = anthropic.Anthropic(api_key=key)
resp = client.messages.create(
model=mdl,
max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}],
)
return resp.content[0].text if resp.content else ""
if backend == "bedrock":
try:
import boto3
except ImportError as exc:
raise ImportError("boto3 required for bedrock backend") from exc
region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or "us-east-1"
profile = os.environ.get("AWS_PROFILE")
session = boto3.Session(profile_name=profile, region_name=region)
client = session.client("bedrock-runtime")
resp = client.converse(
modelId=mdl,
messages=[{"role": "user", "content": [{"text": prompt}]}],
inferenceConfig={"maxTokens": max_tokens, "temperature": 0},
)
return resp.get("output", {}).get("message", {}).get("content", [{}])[0].get("text", "")
# OpenAI-compatible (kimi, openai, gemini, ollama)
try:
from openai import OpenAI
except ImportError as exc:
raise ImportError("openai package required for this backend") from exc
client = OpenAI(api_key=key, base_url=cfg["base_url"])
kwargs: dict = {
"model": mdl,
"messages": [{"role": "user", "content": prompt}],
"max_completion_tokens": max_tokens,
}
temperature = cfg.get("temperature", 0)
if temperature is not None:
kwargs["temperature"] = temperature
if cfg.get("reasoning_effort"):
kwargs["reasoning_effort"] = cfg["reasoning_effort"]
if "moonshot" in cfg["base_url"]:
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
resp = client.chat.completions.create(**kwargs)
return resp.choices[0].message.content or ""
def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
"""Estimate USD cost for a given token count using published pricing."""
if backend not in BACKENDS:
@@ -465,14 +917,59 @@ def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
def _validate_ollama_base_url(url: str) -> None:
"""Warn (do not raise) if OLLAMA_BASE_URL looks unsafe.
Sending an entire corpus to a non-loopback http:// endpoint silently leaks
proprietary code; we surface a visible stderr warning instead of failing
closed (some users genuinely run Ollama on a LAN host they trust).
"""
try:
from urllib.parse import urlparse
parsed = urlparse(url)
except Exception:
print(
f"[graphify] WARNING: OLLAMA_BASE_URL={url!r} is not a parseable URL.",
file=sys.stderr,
)
return
if parsed.scheme not in ("http", "https"):
print(
f"[graphify] WARNING: OLLAMA_BASE_URL has unexpected scheme {parsed.scheme!r}; "
"expected http or https.",
file=sys.stderr,
)
return
host = (parsed.hostname or "").lower()
is_loopback = host in ("localhost", "127.0.0.1", "::1") or host.startswith("127.")
if not is_loopback:
scheme_note = " (UNENCRYPTED)" if parsed.scheme == "http" else ""
print(
f"[graphify] WARNING: OLLAMA_BASE_URL points to non-loopback host {host!r}{scheme_note}. "
"Your full corpus will be sent to that endpoint. "
"Set OLLAMA_BASE_URL=http://localhost:11434/v1 to keep extraction local.",
file=sys.stderr,
)
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.
Claude is the default for the skill.md subagent pipeline and is never forced here.
Priority: gemini → kimi → claude → openai → bedrock → ollama (last, opt-in).
Ollama is intentionally checked LAST so a paid API key (Anthropic/OpenAI/etc.)
is never silently shadowed by an incidental OLLAMA_BASE_URL in the environment
— see security finding F-002/F-029. Setting OLLAMA_BASE_URL alongside a paid
key now keeps you on the paid backend; remove the paid key (or pass
--backend ollama explicitly) to route to the local model.
"""
if os.environ.get("MOONSHOT_API_KEY"):
return "kimi"
if os.environ.get("ANTHROPIC_API_KEY"):
return "claude"
for backend in ("gemini", "kimi", "claude", "openai"):
if _get_backend_api_key(backend):
return backend
if os.environ.get("AWS_PROFILE") or os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION"):
return "bedrock"
ollama_url = os.environ.get("OLLAMA_BASE_URL")
if ollama_url:
_validate_ollama_base_url(ollama_url)
return "ollama"
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)
+5 -2
View File
@@ -19,6 +19,9 @@ _MAX_TEXT_BYTES = 10_485_760 # 10 MB hard cap for HTML / text
# AWS metadata, link-local, and common cloud metadata endpoints
_BLOCKED_HOSTS = {"metadata.google.internal", "metadata.google.com"}
# RFC 6598 Shared Address Space (CGN) -- is_private misses this on Python <3.11
_CGN_NETWORK = ipaddress.ip_network("100.64.0.0/10")
# ---------------------------------------------------------------------------
# URL validation
@@ -54,7 +57,7 @@ def validate_url(url: str) -> str:
for info in infos:
addr = info[4][0]
ip = ipaddress.ip_address(addr)
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local or ip in _CGN_NETWORK:
raise ValueError(
f"Blocked private/internal IP {addr} (resolved from '{hostname}'). "
f"Got: {url!r}"
@@ -85,7 +88,7 @@ def _ssrf_guarded_socket():
ip = ipaddress.ip_address(addr)
except ValueError:
continue
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local or ip in _CGN_NETWORK:
raise OSError(
f"SSRF blocked: IP {addr} resolved from '{host}' is private/reserved"
)
+162 -23
View File
@@ -6,6 +6,7 @@ from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import sanitize_label
from graphify.build import edge_data
def _load_graph(graph_path: str) -> nx.Graph:
@@ -17,6 +18,8 @@ def _load_graph(graph_path: str) -> nx.Graph:
raise FileNotFoundError(f"Graph file not found: {resolved}")
safe = resolved
data = json.loads(safe.read_text(encoding="utf-8"))
if "links" not in data and "edges" in data:
data = dict(data, links=data["edges"])
try:
return json_graph.node_link_graph(data, edges="links")
except TypeError:
@@ -45,7 +48,10 @@ def _strip_diacritics(text: str) -> str:
return "".join(c for c in nfkd if not unicodedata.combining(c))
_EXACT_MATCH_BONUS = 100.0
_EXACT_MATCH_BONUS = 1000.0
_PREFIX_MATCH_BONUS = 100.0
_SUBSTRING_MATCH_BONUS = 1.0
_SOURCE_MATCH_BONUS = 0.5
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
@@ -53,11 +59,20 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
norm_terms = [_strip_diacritics(t).lower() for t in terms]
for nid, data in G.nodes(data=True):
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
bare_label = norm_label.rstrip("()")
source = (data.get("source_file") or "").lower()
score = sum(1 for t in norm_terms if t in norm_label) + sum(0.5 for t in norm_terms if t in source)
# Exact match: single term equals the full label (strip trailing () for functions)
if any(t == norm_label or t == norm_label.rstrip("()") for t in norm_terms):
score += _EXACT_MATCH_BONUS
score = 0.0
for t in norm_terms:
# Three-tier precedence: exact > prefix > substring (take the
# strongest tier per term so a single term cannot double-count).
if t == norm_label or t == bare_label:
score += _EXACT_MATCH_BONUS
elif norm_label.startswith(t) or bare_label.startswith(t):
score += _PREFIX_MATCH_BONUS
elif t in norm_label:
score += _SUBSTRING_MATCH_BONUS
if t in source:
score += _SOURCE_MATCH_BONUS
if score > 0:
scored.append((score, nid))
return sorted(scored, reverse=True)
@@ -170,17 +185,28 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
sorted(nodes - seed_set, key=lambda n: G.degree(n), reverse=True)
for nid in ordered:
d = G.nodes[nid]
line = f"NODE {sanitize_label(d.get('label', nid))} [src={d.get('source_file', '')} loc={d.get('source_location', '')} community={d.get('community', '')}]"
# Every LLM-derived field passes through sanitize_label before being
# concatenated into MCP tool output (F-010): an attacker who controls a
# corpus document can otherwise inject ANSI escapes, fake graphify-out
# log lines, or prompt-injection markup into the model's context via
# source_file / source_location / community.
line = (
f"NODE {sanitize_label(d.get('label', nid))} "
f"[src={sanitize_label(str(d.get('source_file', '')))} "
f"loc={sanitize_label(str(d.get('source_location', '')))} "
f"community={sanitize_label(str(d.get('community', '')))}]"
)
lines.append(line)
for u, v in edges:
if u in nodes and v in nodes:
raw = G[u][v]
d = next(iter(raw.values()), {}) if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)) else raw
context = d.get("context")
context_suffix = f" context={context}" if context else ""
context_suffix = f" context={sanitize_label(str(context))}" if context else ""
line = (
f"EDGE {sanitize_label(G.nodes[u].get('label', u))} "
f"--{d.get('relation', '')} [{d.get('confidence', '')}{context_suffix}]--> "
f"--{sanitize_label(str(d.get('relation', '')))} "
f"[{sanitize_label(str(d.get('confidence', '')))}{context_suffix}]--> "
f"{sanitize_label(G.nodes[v].get('label', v))}"
)
lines.append(line)
@@ -219,11 +245,26 @@ def _query_graph_text(
def _find_node(G: nx.Graph, label: str) -> list[str]:
"""Return node IDs whose label or ID matches the search term (diacritic-insensitive)."""
"""Return node IDs whose label or ID matches the search term (diacritic-insensitive).
Results are ordered by three-tier precedence: exact match, then prefix match,
then substring match. Node-ID exact matches are grouped with label exact matches.
"""
term = _strip_diacritics(label).lower()
return [nid for nid, d in G.nodes(data=True)
if term in (d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower())
or term == nid.lower()]
exact: list[str] = []
prefix: list[str] = []
substring: list[str] = []
for nid, d in G.nodes(data=True):
norm_label = d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower()
bare_label = norm_label.rstrip("()")
nid_lower = nid.lower()
if term == norm_label or term == bare_label or term == nid_lower:
exact.append(nid)
elif norm_label.startswith(term) or bare_label.startswith(term) or nid_lower.startswith(term):
prefix.append(nid)
elif term in norm_label:
substring.append(nid)
return exact + prefix + substring
def _filter_blank_stdin() -> None:
@@ -262,6 +303,7 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
from mcp.types import AnyUrl
except ImportError as e:
raise ImportError("mcp not installed. Run: pip install mcp") from e
@@ -370,12 +412,13 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
if not matches:
return f"No node matching '{label}' found."
nid, d = matches[0]
# Sanitise every LLM-derived field before concatenation (F-010).
return "\n".join([
f"Node: {d.get('label', nid)}",
f" ID: {nid}",
f" Source: {d.get('source_file', '')} {d.get('source_location', '')}",
f" Type: {d.get('file_type', '')}",
f" Community: {d.get('community', '')}",
f"Node: {sanitize_label(d.get('label', nid))}",
f" ID: {sanitize_label(nid)}",
f" Source: {sanitize_label(str(d.get('source_file', '')))} {sanitize_label(str(d.get('source_location', '')))}",
f" Type: {sanitize_label(str(d.get('file_type', '')))}",
f" Community: {sanitize_label(str(d.get('community', '')))}",
f" Degree: {G.degree(nid)}",
])
@@ -386,13 +429,16 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
if not matches:
return f"No node matching '{label}' found."
nid = matches[0]
lines = [f"Neighbors of {G.nodes[nid].get('label', nid)}:"]
lines = [f"Neighbors of {sanitize_label(G.nodes[nid].get('label', nid))}:"]
for neighbor in G.neighbors(nid):
d = G.edges[nid, neighbor]
d = edge_data(G, nid, neighbor)
rel = d.get("relation", "")
if rel_filter and rel_filter not in rel.lower():
continue
lines.append(f" --> {G.nodes[neighbor].get('label', neighbor)} [{rel}] [{d.get('confidence', '')}]")
lines.append(
f" --> {sanitize_label(G.nodes[neighbor].get('label', neighbor))} "
f"[{sanitize_label(str(rel))}] [{sanitize_label(str(d.get('confidence', '')))}]"
)
return "\n".join(lines)
def _tool_get_community(arguments: dict) -> str:
@@ -403,7 +449,11 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
lines = [f"Community {cid} ({len(nodes)} nodes):"]
for n in nodes:
d = G.nodes[n]
lines.append(f" {d.get('label', n)} [{d.get('source_file', '')}]")
# Sanitise label and source_file (F-010).
lines.append(
f" {sanitize_label(d.get('label', n))} "
f"[{sanitize_label(str(d.get('source_file', '')))}]"
)
return "\n".join(lines)
def _tool_god_nodes(arguments: dict) -> str:
@@ -433,6 +483,23 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
if not tgt_scored:
return f"No node matching target '{arguments['target']}' found."
src_nid, tgt_nid = src_scored[0][1], tgt_scored[0][1]
# Ambiguity guard: when both queries resolve to the same node, the
# shortest path is trivially zero hops, which is almost never what the
# caller wanted (see bug #828).
if src_nid == tgt_nid:
return (
f"'{arguments['source']}' and '{arguments['target']}' both resolved to "
f"the same node '{src_nid}'. Use a more specific label or the exact node ID."
)
warnings: list[str] = []
for name, scored in (("source", src_scored), ("target", tgt_scored)):
if len(scored) >= 2:
top, runner = scored[0][0], scored[1][0]
if top > 0 and (top - runner) / top < 0.10:
warnings.append(
f"warning: {name} match was ambiguous "
f"(top score {top:g}, runner-up {runner:g})"
)
max_hops = int(arguments.get("max_hops", 8))
try:
path_nodes = nx.shortest_path(G, src_nid, tgt_nid)
@@ -444,14 +511,15 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
segments = []
for i in range(len(path_nodes) - 1):
u, v = path_nodes[i], path_nodes[i + 1]
edata = G.edges[u, v]
edata = edge_data(G, u, v)
rel = edata.get("relation", "")
conf = edata.get("confidence", "")
conf_str = f" [{conf}]" if conf else ""
if i == 0:
segments.append(G.nodes[u].get("label", u))
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
return f"Shortest path ({hops} hops):\n " + " ".join(segments)
prefix = ("\n".join(warnings) + "\n") if warnings else ""
return prefix + f"Shortest path ({hops} hops):\n " + " ".join(segments)
_handlers = {
"query_graph": _tool_query_graph,
@@ -463,6 +531,77 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
"shortest_path": _tool_shortest_path,
}
def _load_community_labels() -> dict[int, str]:
labels_path = Path(graph_path).parent / ".graphify_labels.json"
if labels_path.exists():
try:
return {int(k): v for k, v in json.loads(labels_path.read_text(encoding="utf-8")).items()}
except Exception:
pass
return {cid: f"Community {cid}" for cid in communities}
@server.list_resources()
async def list_resources() -> list[types.Resource]:
return [
types.Resource(uri=AnyUrl("graphify://report"), name="Graph Report", description="Full GRAPH_REPORT.md", mimeType="text/markdown"),
types.Resource(uri=AnyUrl("graphify://stats"), name="Graph Stats", description="Node/edge/community counts and confidence breakdown", mimeType="text/plain"),
types.Resource(uri=AnyUrl("graphify://god-nodes"), name="God Nodes", description="Top 10 most-connected nodes", mimeType="text/plain"),
types.Resource(uri=AnyUrl("graphify://surprises"), name="Surprising Connections", description="Cross-community surprising connections", mimeType="text/plain"),
types.Resource(uri=AnyUrl("graphify://audit"), name="Confidence Audit", description="EXTRACTED/INFERRED/AMBIGUOUS edge breakdown", mimeType="text/plain"),
types.Resource(uri=AnyUrl("graphify://questions"), name="Suggested Questions", description="Suggested questions for this codebase", mimeType="text/plain"),
]
@server.read_resource()
async def read_resource(uri: AnyUrl) -> str:
uri_str = str(uri)
if uri_str == "graphify://report":
report_path = Path(graph_path).parent / "GRAPH_REPORT.md"
if report_path.exists():
return report_path.read_text(encoding="utf-8")
return "GRAPH_REPORT.md not found. Run graphify extract first."
if uri_str == "graphify://stats":
return _tool_graph_stats({})
if uri_str == "graphify://god-nodes":
return _tool_god_nodes({"top_n": 10})
if uri_str == "graphify://surprises":
try:
from graphify.analyze import surprising_connections
surprises = surprising_connections(G, communities, top_n=10)
if not surprises:
return "No surprising connections found."
lines = ["Surprising cross-community connections:"]
for s in surprises:
lines.append(f" {s.get('source', '')} <-> {s.get('target', '')} [{s.get('relation', '')}]")
return "\n".join(lines)
except Exception as exc:
return f"Could not compute surprising connections: {exc}"
if uri_str == "graphify://audit":
confs = [d.get("confidence", "EXTRACTED") for _, _, d in G.edges(data=True)]
total = len(confs) or 1
return (
f"Total edges: {total}\n"
f"EXTRACTED: {confs.count('EXTRACTED')} ({round(confs.count('EXTRACTED')/total*100)}%)\n"
f"INFERRED: {confs.count('INFERRED')} ({round(confs.count('INFERRED')/total*100)}%)\n"
f"AMBIGUOUS: {confs.count('AMBIGUOUS')} ({round(confs.count('AMBIGUOUS')/total*100)}%)\n"
)
if uri_str == "graphify://questions":
try:
from graphify.analyze import suggest_questions
community_labels = _load_community_labels()
questions = suggest_questions(G, communities, community_labels, top_n=10)
if not questions:
return "No suggested questions available."
lines = ["Suggested questions:"]
for q in questions:
if isinstance(q, dict):
lines.append(f" - {q.get('question', '')}")
else:
lines.append(f" - {q}")
return "\n".join(lines)
except Exception as exc:
return f"Could not generate questions: {exc}"
raise ValueError(f"Unknown resource: {uri_str}")
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
handler = _handlers.get(name)
+6 -4
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -51,6 +51,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -952,7 +954,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1024,7 +1026,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1094,7 +1096,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+6 -4
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -51,6 +51,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -952,7 +954,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1024,7 +1026,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1094,7 +1096,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+6 -4
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -51,6 +51,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -1011,7 +1013,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1083,7 +1085,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1153,7 +1155,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+10 -5
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -53,6 +53,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -843,7 +845,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)
@@ -1037,7 +1042,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1109,7 +1114,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1179,7 +1184,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+6 -4
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -51,6 +51,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -1008,7 +1010,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1080,7 +1082,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1150,7 +1152,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+5 -3
View File
@@ -50,6 +50,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -951,7 +953,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1023,7 +1025,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1093,7 +1095,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+6 -4
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -51,6 +51,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -1061,7 +1063,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1133,7 +1135,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1203,7 +1205,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+6 -4
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. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
---
# /graphify
@@ -50,6 +50,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -951,7 +953,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1023,7 +1025,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1093,7 +1095,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+6 -4
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -51,6 +51,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -976,7 +978,7 @@ for nid in ranked_nodes:
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]
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
@@ -1048,7 +1050,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1117,7 +1119,7 @@ print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
edge = G.edges[nid, neighbor]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
+3 -1
View File
@@ -1,6 +1,6 @@
---
name: graphify
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -21,6 +21,8 @@ Turn any folder of files into a navigable knowledge graph with community detecti
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
+229 -145
View File
@@ -1,6 +1,6 @@
---
name: graphify-windows
description: any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report
description: "any input (code, docs, papers, images) → knowledge graph → clustered communities → HTML + JSON + audit report. Use when user asks any question about a codebase, project content, architecture, or file relationships — especially if graphify-out/ exists. Provides persistent graph with god nodes, community detection, and BFS/DFS query tools."
trigger: /graphify
---
@@ -54,6 +54,8 @@ Use it for:
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
@@ -62,10 +64,24 @@ Follow these steps in order. Do not skip steps.
```powershell
# Detect Python and install graphify if needed
python -c "import graphify" 2>$null
if ($LASTEXITCODE -ne 0) { pip install graphifyy -q 2>&1 | Select-Object -Last 3 }
@'
import graphify
'@ | Out-File -FilePath .graphify_step_1_ensure_graphify_is_installed_1.py -Encoding utf8
python .graphify_step_1_ensure_graphify_is_installed_1.py 2>$null
Remove-Item -ErrorAction SilentlyContinue .graphify_step_1_ensure_graphify_is_installed_1.py
if ($LASTEXITCODE -ne 0) {
if (Get-Command uv -ErrorAction SilentlyContinue) {
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
} else {
pip install graphifyy -q 2>&1 | Select-Object -Last 3
}
}
# Write interpreter path for all subsequent steps
python -c "import sys; open('.graphify_python', 'w').write(sys.executable)"
@'
import sys; open('.graphify_python', 'w', encoding='utf-8').write(sys.executable)
'@ | Out-File -FilePath .graphify_step_1_ensure_graphify_is_installed_2.py -Encoding utf8
python .graphify_step_1_ensure_graphify_is_installed_2.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_1_ensure_graphify_is_installed_2.py
```
If the import succeeds, print nothing and move straight to Step 2.
@@ -73,13 +89,15 @@ If the import succeeds, print nothing and move straight to Step 2.
### Step 2 - Detect files
```powershell
python -c "
@'
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result))
" > .graphify_detect.json
print(json.dumps(result, ensure_ascii=False))
'@ | Out-File -FilePath .graphify_step_2_detect_files_3.py -Encoding utf8
python .graphify_step_2_detect_files_3.py > .graphify_detect.json
Remove-Item -ErrorAction SilentlyContinue .graphify_step_2_detect_files_3.py
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
@@ -123,18 +141,20 @@ Set it as `$env:GRAPHIFY_WHISPER_PROMPT` before running the transcription comman
**Step 2 - Transcribe (PowerShell):**
```powershell
& (Get-Content graphify-out\.graphify_python) -c "
@'
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" | Out-File -FilePath graphify-out\.graphify_transcripts.json -Encoding utf8
print(json.dumps(transcript_paths, ensure_ascii=False))
'@ | Out-File -FilePath .graphify_step_transcribe.py -Encoding utf8
& (Get-Content graphify-out\.graphify_python) .graphify_step_transcribe.py | Out-File -FilePath graphify-out\.graphify_transcripts.json -Encoding utf8
Remove-Item -ErrorAction SilentlyContinue .graphify_step_transcribe.py
```
After transcription:
@@ -160,25 +180,37 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
For any code files detected, run AST extraction in parallel with Part B subagents:
```powershell
python -c "
import sys, json
@'
import json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('.graphify_detect.json').read_text())
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files)
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
print('No code files - skipping AST extraction')
"
def main():
code_files = []
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files)
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
else:
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
print('No code files - skipping AST extraction')
# Windows-spawn ProcessPoolExecutor (used inside extract()) re-imports this
# script in each worker; without an `if __name__ == "__main__":` guard the
# pool would recursively spawn itself. graphify v0.7.11+ falls back to
# sequential extraction if the pool dies, but the guard keeps multi-core
# extraction working on Windows.
if __name__ == '__main__':
main()
'@ | Out-File -FilePath .graphify_step_ast.py -Encoding utf8
python .graphify_step_ast.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_ast.py
```
#### Part B - Semantic extraction (parallel subagents)
@@ -198,21 +230,23 @@ Before dispatching subagents, print a timing estimate:
Before dispatching any subagents, check which files already have cached extraction results:
```powershell
python -c "
@'
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('.graphify_detect.json').read_text())
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
Path('.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_5.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_5.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_5.py
```
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
@@ -315,7 +349,7 @@ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
total_in, total_out = 0, 0
for c in chunks:
d = json.loads(Path(c).read_text())
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
@@ -324,32 +358,34 @@ for c in chunks:
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
'input_tokens': total_in, 'output_tokens': total_out,
}, indent=2))
}, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```powershell
python -c "
@'
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_6.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_6.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_6.py
```
Merge cached + new results into `.graphify_semantic.json`:
```powershell
python -c "
@'
import json
from pathlib import Path
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
cached = json.loads(Path('.graphify_cached.json').read_text(encoding="utf-8")) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
@@ -368,21 +404,23 @@ merged = {
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_7.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_7.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_7.py
```
Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue .graphify_cached.json, .graphify_uncached.txt, .graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```powershell
python -c "
@'
import sys, json
from pathlib import Path
ast = json.loads(Path('.graphify_ast.json').read_text())
sem = json.loads(Path('.graphify_semantic.json').read_text())
ast = json.loads(Path('.graphify_ast.json').read_text(encoding="utf-8"))
sem = json.loads(Path('.graphify_semantic.json').read_text(encoding="utf-8"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
@@ -401,18 +439,20 @@ merged = {
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
"
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_8.py -Encoding utf8
python .graphify_step_3_extract_entities_and_relations_8.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_8.py
```
### Step 4 - Build graph, cluster, analyze, generate outputs
```powershell
New-Item -ItemType Directory -Force -Path graphify-out | Out-Null
python -c "
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
@@ -421,8 +461,8 @@ from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = cluster(G)
@@ -435,7 +475,7 @@ labels = {cid: 'Community ' + str(cid) for cid in communities}
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
to_json(G, communities, 'graphify-out/graph.json')
analysis = {
@@ -445,13 +485,15 @@ analysis = {
'surprises': surprises,
'questions': questions,
}
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
"
'@ | Out-File -FilePath .graphify_step_4_build_graph_cluster_analyze_ge_9.py -Encoding utf8
python .graphify_step_4_build_graph_cluster_analyze_ge_9.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_4_build_graph_cluster_analyze_ge_9.py
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
@@ -465,7 +507,7 @@ Read `.graphify_analysis.json`. For each community key, look at its node labels
Then regenerate the report and save the labels for the visualizer:
```powershell
python -c "
@'
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
@@ -473,9 +515,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('.graphify_extract.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -489,10 +531,12 @@ labels = LABELS_DICT
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
print('Report updated with community labels')
"
'@ | Out-File -FilePath .graphify_step_5_label_communities_10.py -Encoding utf8
python .graphify_step_5_label_communities_10.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_5_label_communities_10.py
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
@@ -507,15 +551,15 @@ If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, use that path as the vault directory. Otherwise default to `graphify-out/obsidian`.
```powershell
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_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -534,21 +578,23 @@ print(f'Open {obsidian_dir}/ as a vault in Obsidian.')
print(' Graph view - nodes colored by community (set automatically)')
print(' graph.canvas - structured layout with communities as groups')
print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries')
"
'@ | Out-File -FilePath .graphify_step_6_generate_obsidian_vault_opt_in_11.py -Encoding utf8
python .graphify_step_6_generate_obsidian_vault_opt_in_11.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_6_generate_obsidian_vault_opt_in_11.py
```
Generate the HTML graph (always, unless `--no-viz`):
```powershell
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_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -559,7 +605,9 @@ if G.number_of_nodes() > 5000:
else:
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
print('graph.html written - open in any browser, no server needed')
"
'@ | Out-File -FilePath .graphify_step_6_generate_obsidian_vault_opt_in_12.py -Encoding utf8
python .graphify_step_6_generate_obsidian_vault_opt_in_12.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_6_generate_obsidian_vault_opt_in_12.py
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
@@ -567,36 +615,40 @@ else:
**If `--neo4j`** - generate a Cypher file for manual import:
```powershell
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_extract.json').read_text()))
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8")))
to_cypher(G, 'graphify-out/cypher.txt')
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
"
'@ | Out-File -FilePath .graphify_step_7_neo4j_export_only_if_neo4j_or__13.py -Encoding utf8
python .graphify_step_7_neo4j_export_only_if_neo4j_or__13.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7_neo4j_export_only_if_neo4j_or__13.py
```
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
```powershell
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_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
result = push_to_neo4j(G, uri='NEO4J_URI', user='NEO4J_USER', password='NEO4J_PASSWORD', communities=communities)
print(f'Pushed to Neo4j: {result[\"nodes\"]} nodes, {result[\"edges\"]} edges')
"
print(f'Pushed to Neo4j: {result["nodes"]} nodes, {result["edges"]} edges')
'@ | Out-File -FilePath .graphify_step_7_neo4j_export_only_if_neo4j_or__14.py -Encoding utf8
python .graphify_step_7_neo4j_export_only_if_neo4j_or__14.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7_neo4j_export_only_if_neo4j_or__14.py
```
Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.
@@ -604,15 +656,15 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
### Step 7b - SVG export (only if --svg flag)
```powershell
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_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -620,27 +672,31 @@ labels = {int(k): v for k, v in labels_raw.items()}
to_svg(G, communities, 'graphify-out/graph.svg', community_labels=labels or None)
print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
"
'@ | Out-File -FilePath .graphify_step_7b_svg_export_only_if_svg_flag_15.py -Encoding utf8
python .graphify_step_7b_svg_export_only_if_svg_flag_15.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7b_svg_export_only_if_svg_flag_15.py
```
### Step 7c - GraphML export (only if --graphml flag)
```powershell
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_extract.json').read_text())
analysis = json.loads(Path('.graphify_analysis.json').read_text())
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
to_graphml(G, communities, 'graphify-out/graph.graphml')
print('graph.graphml written - open in Gephi, yEd, or any GraphML tool')
"
'@ | Out-File -FilePath .graphify_step_7c_graphml_export_only_if_graphml_16.py -Encoding utf8
python .graphify_step_7c_graphml_export_only_if_graphml_16.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_7c_graphml_export_only_if_graphml_16.py
```
### Step 7d - MCP server (only if --mcp flag)
@@ -668,15 +724,17 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
```powershell
python -c "
@'
import json
from graphify.benchmark import run_benchmark, print_benchmark
from pathlib import Path
detection = json.loads(Path('.graphify_detect.json').read_text())
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
print_benchmark(result)
"
'@ | Out-File -FilePath .graphify_step_8_token_reduction_benchmark_only_17.py -Encoding utf8
python .graphify_step_8_token_reduction_benchmark_only_17.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_8_token_reduction_benchmark_only_17.py
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
@@ -686,24 +744,24 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
### Step 9 - Save manifest, update cost tracker, clean up, and report
```powershell
python -c "
@'
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('.graphify_detect.json').read_text())
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
save_manifest(detect['files'])
# Update cumulative cost tracker
extract = json.loads(Path('.graphify_extract.json').read_text())
extract = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text())
cost = json.loads(cost_path.read_text(encoding="utf-8"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
@@ -715,11 +773,13 @@ cost['runs'].append({
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2))
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
'@ | Out-File -FilePath .graphify_step_9_save_manifest_update_cost_trac_18.py -Encoding utf8
python .graphify_step_9_save_manifest_update_cost_trac_18.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_9_save_manifest_update_cost_trac_18.py
Remove-Item -ErrorAction SilentlyContinue .graphify_detect.json, .graphify_extract.json, .graphify_ast.json, .graphify_semantic.json, .graphify_analysis.json, .graphify_labels.json
Remove-Item -ErrorAction SilentlyContinue graphify-out/.needs_update
```
@@ -760,36 +820,40 @@ The graph is the map. Your job after the pipeline is to be the guide.
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```powershell
python -c "
@'
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('.graphify_incremental.json').write_text(json.dumps(result))
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
print(f'{new_total} new/changed file(s) to re-extract.')
"
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_19.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_19.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_19.py
```
If new files exist, first check whether all changed files are code files:
```powershell
python -c "
@'
import json
from pathlib import Path
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
result = json.loads(open('.graphify_incremental.json', encoding='utf-8').read()) if Path('.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
print('code_only:', code_only)
"
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_20.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_20.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_20.py
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.
@@ -799,7 +863,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
Then:
```powershell
python -c "
@'
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
@@ -808,15 +872,15 @@ import networkx as nx
from pathlib import Path
# Load existing graph
existing_data = json.loads(Path('graphify-out/graph.json').read_text())
existing_data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
G_existing = json_graph.node_link_graph(existing_data, edges='links')
# Load new extraction
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
new_extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
G_new = build_from_json(new_extraction)
# Prune nodes from deleted files
incremental = json.loads(Path('.graphify_incremental.json').read_text())
incremental = json.loads(Path('.graphify_incremental.json').read_text(encoding="utf-8"))
deleted = set(incremental.get('deleted_files', []))
if deleted:
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
@@ -837,7 +901,9 @@ print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edge
from graphify.detect import save_manifest
save_manifest(incremental['files'])
print('[graphify update] Manifest saved.')
"
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_21.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_21.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_21.py
```
Then run Steps 4–8 on the merged graph as normal.
@@ -845,7 +911,7 @@ Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```powershell
python -c "
@'
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
@@ -854,8 +920,8 @@ import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
new_extract = json.loads(Path('.graphify_extract.json').read_text())
old_data = json.loads(Path('.graphify_old.json').read_text(encoding="utf-8")) if Path('.graphify_old.json').exists() else None
new_extract = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
G_new = build_from_json(new_extract)
if old_data:
@@ -866,7 +932,9 @@ if old_data:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
"
'@ | Out-File -FilePath .graphify_step_for_update_incremental_re_extracti_22.py -Encoding utf8
python .graphify_step_for_update_incremental_re_extracti_22.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_update_incremental_re_extracti_22.py
```
Before the merge step, save the old graph: `Copy-Item graphify-out/graph.json .graphify_old.json`
@@ -879,7 +947,7 @@ Clean up after: `Remove-Item -ErrorAction SilentlyContinue .graphify_old.json`
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
```powershell
python -c "
@'
import sys, json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections
@@ -889,7 +957,7 @@ from networkx.readwrite import json_graph
import networkx as nx
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text())
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
G = json_graph.node_link_graph(data, edges='links')
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
@@ -903,7 +971,7 @@ 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)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
to_json(G, communities, 'graphify-out/graph.json')
analysis = {
@@ -912,9 +980,11 @@ analysis = {
'gods': gods,
'surprises': surprises,
}
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Re-clustered: {len(communities)} communities')
"
'@ | Out-File -FilePath .graphify_step_for_cluster_only_23.py -Encoding utf8
python .graphify_step_for_cluster_only_23.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_cluster_only_23.py
```
Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).
@@ -932,12 +1002,14 @@ Two traversal modes - choose based on the question:
First check the graph exists:
```powershell
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)
"
'@ | Out-File -FilePath .graphify_step_for_graphify_query_24.py -Encoding utf8
python .graphify_step_for_graphify_query_24.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_query_24.py
```
If it fails, stop and tell the user to run `/graphify <path>` first.
@@ -950,13 +1022,13 @@ Load `graphify-out/graph.json`, then:
5. If the graph lacks enough information, say so - do not hallucinate edges.
```powershell
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())
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
@@ -1020,20 +1092,22 @@ def relevance(nid):
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']
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\",\"\")}]')
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)}')
_raw = G[u][v]; d = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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)
"
'@ | Out-File -FilePath .graphify_step_for_graphify_query_25.py -Encoding utf8
python .graphify_step_for_graphify_query_25.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_query_25.py
```
Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above.
@@ -1054,23 +1128,25 @@ Find the shortest path between two named concepts in the graph.
First check the graph exists:
```powershell
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)
"
'@ | Out-File -FilePath .graphify_step_for_graphify_path_26.py -Encoding utf8
python .graphify_step_for_graphify_path_26.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_path_26.py
```
If it fails, stop and tell the user to run `/graphify <path>` first.
```powershell
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())
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
@@ -1098,7 +1174,7 @@ try:
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]]
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
@@ -1108,7 +1184,9 @@ except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
"
'@ | Out-File -FilePath .graphify_step_for_graphify_path_27.py -Encoding utf8
python .graphify_step_for_graphify_path_27.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_path_27.py
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
@@ -1127,23 +1205,25 @@ Give a plain-language explanation of a single node - everything connected to it.
First check the graph exists:
```powershell
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)
"
'@ | Out-File -FilePath .graphify_step_for_graphify_explain_28.py -Encoding utf8
python .graphify_step_for_graphify_explain_28.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_explain_28.py
```
If it fails, stop and tell the user to run `/graphify <path>` first.
```powershell
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())
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
@@ -1161,20 +1241,22 @@ if not scored or scored[0][0] == 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'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]
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
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})')
"
'@ | Out-File -FilePath .graphify_step_for_graphify_explain_29.py -Encoding utf8
python .graphify_step_for_graphify_explain_29.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_explain_29.py
```
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
@@ -1192,7 +1274,7 @@ python -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER"
Fetch a URL and add it to the corpus, then update the graph.
```powershell
python -c "
@'
import sys
from graphify.ingest import ingest
from pathlib import Path
@@ -1206,7 +1288,9 @@ except ValueError as e:
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
"
'@ | Out-File -FilePath .graphify_step_for_graphify_add_30.py -Encoding utf8
python .graphify_step_for_graphify_add_30.py
Remove-Item -ErrorAction SilentlyContinue .graphify_step_for_graphify_add_30.py
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
+119 -500
View File
@@ -43,24 +43,15 @@ 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
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
If no path was given, use `.` (current directory). Do not ask the user for a path.
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL — run Step 0 before anything else, then continue with the resolved local path.
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
Follow these steps in order. Do not skip steps.
@@ -108,10 +99,19 @@ if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
fi
# 3. Fall back to python3
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
if command -v uv >/dev/null 2>&1; then
uv tool install --upgrade graphifyy -q 2>&1 | tail -3
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
else
"$PYTHON" -m pip install graphifyy -q 2>/dev/null \
|| "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
fi
fi
# Write interpreter path for all subsequent steps (persists across invocations)
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
# Save scan root so `graphify update` (no args) knows where to look next time
echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root
```
@@ -128,7 +128,7 @@ import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result))
print(json.dumps(result, ensure_ascii=False))
" > graphify-out/.graphify_detect.json
```
@@ -179,12 +179,12 @@ import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
print(json.dumps(transcript_paths, ensure_ascii=False))
" > graphify-out/.graphify_transcripts.json
```
@@ -202,10 +202,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.**
@@ -223,16 +223,16 @@ from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files, cache_root=Path('.'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
print('No code files - skipping AST extraction')
"
```
@@ -259,14 +259,14 @@ import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached))
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding=\"utf-8\")
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding=\"utf-8\")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
@@ -291,7 +291,15 @@ Concrete example for 3 chunks:
```
All three in one message. Not three separate messages.
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE):
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
```bash
PROJECT_ROOT=$(cat graphify-out/.graphify_root)
# Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json"
```
Subagent prompt template:
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
@@ -351,8 +359,11 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Output exactly this JSON (no other text):
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
```
**Step B3 - Collect, cache, and merge**
@@ -375,7 +386,7 @@ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
total_in, total_out = 0, 0
for c in chunks:
d = json.loads(Path(c).read_text())
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
@@ -384,7 +395,7 @@ for c in chunks:
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
'input_tokens': total_in, 'output_tokens': total_out,
}, indent=2))
}, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
@@ -396,7 +407,7 @@ import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
@@ -408,8 +419,8 @@ $(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
@@ -428,7 +439,7 @@ merged = {
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
@@ -441,8 +452,8 @@ $(cat graphify-out/.graphify_python) -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text())
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
@@ -461,7 +472,7 @@ merged = {
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
@@ -483,8 +494,8 @@ from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
communities = cluster(G)
@@ -497,7 +508,7 @@ labels = {cid: 'Community ' + str(cid) for cid in communities}
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
to_json(G, communities, 'graphify-out/graph.json')
analysis = {
@@ -507,7 +518,7 @@ analysis = {
'surprises': surprises,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
@@ -535,9 +546,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
from graphify.report import generate
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
G = build_from_json(extraction)
communities = {int(k): v for k, v in analysis['communities'].items()}
@@ -551,8 +562,8 @@ labels = LABELS_DICT
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
print('Report updated with community labels')
"
```
@@ -566,84 +577,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 +598,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 +606,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 +654,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.
@@ -807,17 +671,17 @@ from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
save_manifest(detect['files'])
# Update cumulative cost tracker
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text())
cost = json.loads(cost_path.read_text(encoding=\"utf-8\"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
@@ -829,7 +693,7 @@ cost['runs'].append({
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2))
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
@@ -883,7 +747,7 @@ if [ ! -f graphify-out/.graphify_python ]; then
PYTHON="python3"
fi
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
fi
```
@@ -899,8 +763,8 @@ from pathlib import Path
result = detect_incremental(Path('INPUT_PATH'))
new_total = result.get('new_total', 0)
print(json.dumps(result, indent=2))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
print(json.dumps(result, indent=2, ensure_ascii=False))
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
if new_total == 0:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
@@ -915,8 +779,8 @@ $(cat graphify-out/.graphify_python) -c "
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'}
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').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','.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)
@@ -932,55 +796,49 @@ Then:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.export import to_json
from networkx.readwrite import json_graph
import networkx as nx
import json
from pathlib import Path
from graphify.build import build_merge
from graphify.detect import save_manifest
# Load existing graph
existing_data = json.loads(Path('graphify-out/graph.json').read_text())
G_existing = json_graph.node_link_graph(existing_data, edges='links')
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
deleted = list(incremental.get('deleted_files', []))
# Load new extraction
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
G_new = build_from_json(new_extraction)
# Prune nodes from deleted files
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text())
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)
if to_remove:
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
else:
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
# Merge: new nodes/edges into existing graph
G_existing.update(G_new)
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=deleted or None,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
merged_out = {
'nodes': [{'id': n, **d} for n, d in G_existing.nodes(data=True)],
'edges': [{'source': u, 'target': v, **d} for u, v, d in G_existing.edges(data=True)],
'hyperedges': new_extraction.get('hyperedges', []),
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
'edges': [
# Explicit source/target last so they win over any stale attrs in d.
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
for u, v, d in G.edges(data=True)
],
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
# and new_extraction (build_merge combines them). Falling back to
# new_extraction only would silently drop prior-run hyperedges (#801).
'hyperedges': list(G.graph.get('hyperedges', [])),
'input_tokens': new_extraction.get('input_tokens', 0),
'output_tokens': new_extraction.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out))
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
# Save manifest with the CURRENT full file list so the next --update
# diffs against today's filesystem state, not the prior --update's
# baseline. Without this, deleted files get reported as ghosts again
# on every subsequent --update until a full rebuild runs.
from graphify.detect import save_manifest
# Save manifest so next --update diffs against today's state, not the
# prior run's baseline (prevents ghost-node reports on subsequent updates).
save_manifest(incremental['files'])
print('[graphify update] Manifest saved.')
"
"
```
Then run Steps 4–8 on the merged graph as normal.
@@ -997,8 +855,8 @@ import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text()) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
G_new = build_from_json(new_extract)
if old_data:
@@ -1019,45 +877,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 +896,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 +917,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 +935,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.
+206 -12
View File
@@ -1,5 +1,6 @@
# monitor a folder and auto-trigger --update when files change
from __future__ import annotations
import contextlib
import json
import os
import sys
@@ -9,6 +10,84 @@ from pathlib import Path
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
@contextlib.contextmanager
def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
"""Per-repo advisory lock around a rebuild.
Yields True if acquired, False if another rebuild is already running and
``blocking`` is False. Uses fcntl.flock so the lock is released
automatically if the process is killed (no stale-lock cleanup needed).
Falls back to a no-op yield(True) on platforms without fcntl (Windows).
"""
try:
import fcntl
except ImportError:
yield True
return
out_dir.mkdir(parents=True, exist_ok=True)
lock_path = out_dir / ".rebuild.lock"
fh = open(lock_path, "a", encoding="utf-8")
try:
flags = fcntl.LOCK_EX if blocking else (fcntl.LOCK_EX | fcntl.LOCK_NB)
try:
fcntl.flock(fh.fileno(), flags)
except BlockingIOError:
yield False
return
try:
fh.write(str(os.getpid()))
fh.flush()
except OSError:
pass
yield True
finally:
try:
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
except OSError:
pass
fh.close()
def _apply_resource_limits() -> None:
"""Best-effort nice + memory cap. Called from inline hook scripts.
GRAPHIFY_REBUILD_MEMORY_LIMIT_MB caps RSS-ish memory. Uses RLIMIT_DATA on
macOS (RLIMIT_AS is unreliable under Apple's libmalloc) and RLIMIT_AS on
Linux. Silently skips if the platform doesn't support it.
"""
try:
os.nice(10)
except (OSError, AttributeError):
pass
mb = os.environ.get("GRAPHIFY_REBUILD_MEMORY_LIMIT_MB", "").strip()
if not mb:
return
try:
limit = int(mb) * 1024 * 1024
except ValueError:
return
try:
import resource
which = resource.RLIMIT_DATA if sys.platform == "darwin" else resource.RLIMIT_AS
soft, hard = resource.getrlimit(which)
new_hard = hard if hard != resource.RLIM_INFINITY and hard < limit else limit
resource.setrlimit(which, (limit, new_hard))
except (ImportError, ValueError, OSError):
pass
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
@@ -36,20 +115,55 @@ def _relativize_source_files(payload: dict, root: Path) -> None:
continue
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False, force: bool = False) -> bool:
def _rebuild_code(
watch_path: Path,
*,
changed_paths: list[Path] | None = None,
follow_symlinks: bool = False,
force: bool = False,
acquire_lock: bool = True,
block_on_lock: bool = False,
) -> bool:
"""Re-run AST extraction + build + cluster + report for code files. No LLM needed.
When ``force`` is True the node-count safety check in ``to_json`` is bypassed
so the rebuilt graph overwrites graph.json even if it has fewer nodes.
Use this after refactors that legitimately delete code.
Returns True on success, False on error.
When ``changed_paths`` is provided, only those files are re-extracted; nodes
for unchanged files are preserved from the existing graph. Deleted paths
in ``changed_paths`` (paths that no longer exist on disk) are dropped from
the preserved set. When ``changed_paths`` is None the full code corpus is
re-extracted (used by the watcher and post-checkout hook).
``acquire_lock`` (default True) takes a non-blocking per-repo flock around
the rebuild so concurrent post-commit hooks across multiple repos do not
pile up. Returns False with a log line if the lock is held. Pass
``block_on_lock=True`` to wait instead of skip (used by the interactive
``graphify update`` CLI).
Returns True on success, False on error or skipped-due-to-lock.
"""
out = watch_path / _GRAPHIFY_OUT
if acquire_lock:
with _rebuild_lock(out, blocking=block_on_lock) as got:
if not got:
print("[graphify watch] Rebuild already in progress for "
f"{watch_path.resolve()} - skipping.")
return False
return _rebuild_code(
watch_path,
changed_paths=changed_paths,
follow_symlinks=follow_symlinks,
force=force,
acquire_lock=False,
)
watch_root = watch_path.resolve()
project_root = Path.cwd().resolve() if not watch_path.is_absolute() else watch_root
report_root = _report_root_label(watch_path)
try:
from graphify.extract import extract
from graphify.extract import extract, _get_extractor
from graphify.detect import detect
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
@@ -60,24 +174,73 @@ 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, .qmd)
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
result = extract(code_files, cache_root=watch_root)
# Incremental path: when the caller passed an explicit change list,
# extract only changed-and-still-existing files. Deleted paths are
# tracked separately so their stale nodes can be evicted below.
deleted_paths: set[str] = set()
if changed_paths is not None:
code_set = {p.resolve() for p in code_files}
wanted: list[Path] = []
for raw in changed_paths:
cand = (watch_root / raw).resolve() if not raw.is_absolute() else raw.resolve()
if cand.exists() and cand in code_set:
wanted.append(cand)
else:
# File was deleted, renamed away, or filtered out by detect
# (e.g. .gitignore, vendored). Either way, evict any
# preserved nodes that still claim this source path.
try:
deleted_paths.add(str(cand.relative_to(project_root)))
except ValueError:
deleted_paths.add(str(cand))
if not wanted and not deleted_paths:
print("[graphify watch] No tracked code files in change set - skipping rebuild.")
return True
extract_targets = wanted
else:
extract_targets = code_files
commit = _git_head()
result = extract(extract_targets, cache_root=watch_root) if extract_targets else {
"nodes": [], "edges": [], "hyperedges": [],
"input_tokens": 0, "output_tokens": 0,
}
# Preserve semantic nodes/edges from a previous full run.
# AST-only rebuild replaces nodes for changed files; everything else is kept.
# Filter by node ID membership in the new AST output, not by file_type —
# INFERRED/AMBIGUOUS nodes extracted from code files also carry file_type="code"
# and would be wrongly dropped by a file_type-based filter.
out = watch_path / _GRAPHIFY_OUT
# When the caller supplied changed_paths, also evict preserved nodes whose
# source_file matches a path that was changed (re-extracted) or deleted —
# otherwise the old nodes for those files would survive forever.
existing_graph = out / "graph.json"
if existing_graph.exists():
try:
existing = json.loads(existing_graph.read_text(encoding="utf-8"))
new_ast_ids = {n["id"] for n in result["nodes"]}
preserved_nodes = [n for n in existing.get("nodes", []) if n["id"] not in new_ast_ids]
evict_sources: set[str] = set(deleted_paths)
if changed_paths is not None:
for p in extract_targets:
try:
evict_sources.add(str(p.relative_to(project_root)))
except ValueError:
evict_sources.add(str(p))
preserved_nodes = [
n for n in existing.get("nodes", [])
if n["id"] not in new_ast_ids
and (not evict_sources or n.get("source_file") not in evict_sources)
]
all_ids = new_ast_ids | {n["id"] for n in preserved_nodes}
preserved_edges = [
e for e in existing.get("links", existing.get("edges", []))
@@ -106,13 +269,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 +295,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).
@@ -138,6 +311,23 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False, force: boo
if stale.exists():
stale.unlink()
# Regenerate callflow HTML if the user previously generated one —
# opt-in by existence so users who never ran callflow-html aren't affected.
callflow_files = list(out.glob("*-callflow.html"))
if callflow_files:
try:
from graphify.callflow_html import write_callflow_html
for cf in callflow_files:
write_callflow_html(
graph=out / "graph.json",
report=out / "GRAPH_REPORT.md",
labels=out / ".graphify_labels.json",
output=cf,
verbose=False,
)
except Exception as cf_err:
print(f"[graphify watch] callflow HTML update skipped: {cf_err}")
# clear stale needs_update flag if present
flag = out / "needs_update"
if flag.exists():
@@ -146,6 +336,8 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False, force: boo
print(f"[graphify watch] Rebuilt: {G.number_of_nodes()} nodes, "
f"{G.number_of_edges()} edges, {len(communities)} communities")
products = "graph.json" + (", graph.html" if html_written else "") + " and GRAPH_REPORT.md"
if callflow_files:
products += f", {len(callflow_files)} callflow HTML"
print(f"[graphify watch] {products} updated in {out}")
return True
@@ -241,10 +433,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:
+10 -2
View File
@@ -5,6 +5,8 @@ from collections import Counter
from pathlib import Path
import networkx as nx
from graphify.build import edge_data
def _safe_filename(name: str) -> str:
"""Make a label safe for use as a filename across platforms.
@@ -48,7 +50,7 @@ def _community_article(
conf_counts: Counter = Counter()
for nid in nodes:
for neighbor in G.neighbors(nid):
ed = G.edges[nid, neighbor]
ed = edge_data(G, nid, neighbor)
conf_counts[ed.get("confidence", "EXTRACTED")] += 1
total_edges = sum(conf_counts.values()) or 1
@@ -118,7 +120,7 @@ def _god_node_article(G: nx.Graph, nid: str, labels: dict[int, str]) -> str:
by_relation: dict[str, list[str]] = {}
for neighbor in sorted(G.neighbors(nid), key=lambda n: G.degree(n), reverse=True):
nd = G.nodes[neighbor]
ed = G.edges[nid, neighbor]
ed = edge_data(G, nid, neighbor)
rel = ed.get("relation", "related")
neighbor_label = nd.get("label", neighbor)
conf = ed.get("confidence", "")
@@ -196,6 +198,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
+14 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.6.9"
version = "0.7.16"
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]
@@ -49,10 +53,15 @@ watch = ["watchdog"]
svg = ["matplotlib"]
leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
google = ["openpyxl"]
video = ["faster-whisper", "yt-dlp"]
kimi = ["openai", "tiktoken"]
ollama = ["openai"]
bedrock = ["boto3"]
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"]
all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai", "tiktoken", "boto3", "tree-sitter-sql"]
[project.scripts]
graphify = "graphify.__main__:main"
@@ -68,3 +77,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"]
+12
View File
@@ -0,0 +1,12 @@
const { loadFoundation, validateConfig } = require('./foundation');
const utils = require('./utils');
const helper = require('./helpers').helperFn;
function runDispatch() {
const cfg = loadFoundation({});
validateConfig(cfg);
utils.log('go');
helper();
}
module.exports = { runDispatch };
+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
+28
View File
@@ -0,0 +1,28 @@
object MainForm: TMainForm
Left = 100
Top = 100
Width = 640
Height = 480
Caption = 'Sample Form'
OnCreate = FormCreate
OnDestroy = FormDestroy
object Panel1: TPanel
Align = alTop
Height = 40
object ButtonOK: TButton
Caption = 'OK'
OnClick = ButtonOKClick
end
object ButtonCancel: TButton
Caption = 'Cancel'
OnClick = ButtonCancelClick
end
end
object Memo1: TMemo
Align = alClient
OnChange = Memo1Change
end
object StatusBar1: TStatusBar
Align = alBottom
end
end
+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()
}
}
+30
View File
@@ -0,0 +1,30 @@
object SampleForm: TSampleForm
Left = 100
Top = 100
Caption = 'Sample Form'
ClientHeight = 300
ClientWidth = 400
object PanelMain: TPanel
Left = 0
Top = 0
Width = 400
Height = 260
object ButtonOK: TButton
Left = 160
Top = 220
Width = 75
Height = 25
Caption = 'OK'
OnClick = ButtonOKClick
end
object LabelTitle: TLabel
Left = 10
Top = 10
Caption = 'Title'
end
end
object TimerRefresh: TTimer
Interval = 1000
OnTimer = TimerRefreshTimer
end
end
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<Package Version="5">
<Name Value="SamplePackage"/>
<Description Value="A sample Lazarus package"/>
<Files Count="2">
<Item1>
<Filename Value="sample.pas"/>
<UnitName Value="sample"/>
</Item1>
<Item2>
<Filename Value="sampleutils.pas"/>
<UnitName Value="sampleutils"/>
</Item2>
</Files>
<RequiredPkgs Count="2">
<Item1>
<PackageName Value="FCL"/>
</Item1>
<Item2>
<PackageName Value="LCL"/>
</Item2>
</RequiredPkgs>
</Package>
</CONFIG>
+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
+71
View File
@@ -0,0 +1,71 @@
unit SampleUnit;
interface
uses
SysUtils, Classes;
type
IProcessor = interface
procedure Process;
function GetCount: Integer;
end;
TBaseProcessor = class(TObject)
public
procedure Initialize; virtual;
function GetCount: Integer; virtual;
end;
TDataProcessor = class(TBaseProcessor, IProcessor)
private
FCount: Integer;
public
constructor Create;
procedure Initialize; override;
procedure Process;
function GetCount: Integer; override;
procedure Reset;
end;
implementation
procedure TBaseProcessor.Initialize;
begin
{ base init }
end;
function TBaseProcessor.GetCount: Integer;
begin
Result := 0;
end;
constructor TDataProcessor.Create;
begin
inherited;
FCount := 0;
end;
procedure TDataProcessor.Initialize;
begin
inherited Initialize;
FCount := 0;
end;
procedure TDataProcessor.Process;
begin
Inc(FCount);
Reset;
end;
function TDataProcessor.GetCount: Integer;
begin
Result := FCount;
end;
procedure TDataProcessor.Reset;
begin
FCount := 0;
end;
end.
+18
View File
@@ -0,0 +1,18 @@
function fmtDate(d: Date): string {
return d.toISOString();
}
function fmtCount(n: number): string {
return `${n} items`;
}
export function App() {
const now = new Date();
return (
<div className="app">
<h1>Header</h1>
<span>{fmtDate(now)}</span>
<span>{fmtCount(42)}</span>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INT,
total NUMERIC
);
ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id);
+11
View File
@@ -0,0 +1,11 @@
CREATE TABLE Sales.Customer (
CustomerID SERIAL PRIMARY KEY,
Name TEXT NOT NULL
);
CREATE TABLE Sales.SalesOrder (
OrderID SERIAL PRIMARY KEY,
CustomerID INT REFERENCES Sales.Customer(CustomerID)
);
ALTER TABLE Sales.SalesOrder ADD CONSTRAINT fk_cust FOREIGN KEY (CustomerID) REFERENCES Sales.Customer(CustomerID);
+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"
}
}
+69
View File
@@ -0,0 +1,69 @@
// Test fixture for upstream PR — exercises every new extraction path.
//
// Expected nodes after this PR:
// - IUserRepository (interface)
// - UserStatus (enum) + Active, Inactive (members)
// - UserId (type_alias)
// - USER_REPOSITORY (const, value=call_expression)
// - DEFAULT_ROLES (const, value=array)
// - USER_CONFIG (const, value=object)
// - UserService (class — already extracted by current code)
// - UserModule (class — already extracted)
//
// Expected edges after this PR:
// - UserService.create() --instantiates--> User
// - UserService.bulkCreate() --instantiates--> Array
// - UserModule --provides--> UserService
// - UserModule --provides--> USER_REPOSITORY (via { provide, useClass } detection — optional)
// - UserModule --exports--> UserService
import { Module, Injectable } from '@nestjs/common';
import type { User } from './user.entity';
export interface IUserRepository {
findById(id: string): Promise<User | null>;
save(user: User): Promise<void>;
}
export enum UserStatus {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
Suspended = 'SUSPENDED',
}
export type UserId = string;
export const USER_REPOSITORY = Symbol('USER_REPOSITORY');
export const DEFAULT_ROLES = ['admin', 'editor', 'user'] as const;
export const USER_CONFIG = {
maxRetries: 3,
timeoutMs: 5000,
features: {
twoFactor: true,
sso: false,
},
};
@Injectable()
export class UserService {
constructor(private repo: IUserRepository) {}
create(name: string): User {
return new User(name);
}
bulkCreate(names: string[]): User[] {
return names.map((n) => new User(n));
}
}
@Module({
providers: [
UserService,
{ provide: USER_REPOSITORY, useClass: PrismaUserRepository },
],
exports: [UserService],
})
export class UserModule {}
+47 -1
View File
@@ -5,7 +5,7 @@ import pytest
import networkx as nx
from networkx.readwrite import json_graph
from graphify.benchmark import run_benchmark, print_benchmark, _query_subgraph_tokens, _SAMPLE_QUESTIONS
from graphify.benchmark import run_benchmark, print_benchmark, _query_subgraph_tokens, _SAMPLE_QUESTIONS, _safe, _hr
def _make_graph() -> nx.Graph:
@@ -117,3 +117,49 @@ def test_print_benchmark_error_message(capsys):
print_benchmark({"error": "test error message"})
out = capsys.readouterr().out
assert "test error message" in out
# --- cp1252 / Windows-console encoding compatibility (regression for #?) ---
# print_benchmark previously crashed on Windows consoles (cp1252) because it
# unconditionally printed U+2500 and U+2192. _safe() falls back to ASCII when
# stdout cannot encode the glyph.
def test_safe_returns_unicode_when_encodable():
import io, sys
real_stdout = sys.stdout
try:
sys.stdout = io.TextIOWrapper(io.BytesIO(), encoding="utf-8")
assert _safe("→", "->") == "→"
assert _hr(5) == "─" * 5
finally:
sys.stdout = real_stdout
def test_safe_falls_back_when_unencodable():
import io, sys
real_stdout = sys.stdout
try:
sys.stdout = io.TextIOWrapper(io.BytesIO(), encoding="cp1252")
assert _safe("→", "->") == "->"
assert _hr(5) == "-" * 5
finally:
sys.stdout = real_stdout
def test_print_benchmark_survives_cp1252_stdout(tmp_path, monkeypatch, capsys):
"""Regression: U+2500 / U+2192 used to crash with UnicodeEncodeError on cp1252."""
import io, sys
G = _make_graph()
graph_file = tmp_path / "graph.json"
_write_graph(G, graph_file)
result = run_benchmark(str(graph_file), corpus_words=5_000)
# Replace stdout with a strict cp1252 stream — same behaviour as the
# legacy Windows console that surfaced this bug.
cp1252_stdout = io.TextIOWrapper(io.BytesIO(), encoding="cp1252", errors="strict")
monkeypatch.setattr(sys, "stdout", cp1252_stdout)
print_benchmark(result) # must not raise UnicodeEncodeError
cp1252_stdout.flush()
written = cp1252_stdout.buffer.getvalue().decode("cp1252")
assert "reduction" in written.lower()
# ASCII fallbacks must be present, fancy glyphs must not.
assert "─" not in written
assert "→" not in written
+207 -1
View File
@@ -1,6 +1,8 @@
import json
from pathlib import Path
from graphify.build import build_from_json, build
import networkx as nx
from networkx.readwrite import json_graph
from graphify.build import build_from_json, build, build_merge, edge_data, edge_datas
FIXTURES = Path(__file__).parent / "fixtures"
@@ -75,3 +77,207 @@ def test_build_merges_multiple_extractions():
G = build([ext1, ext2])
assert G.number_of_nodes() == 2
assert G.number_of_edges() == 1
def test_none_file_type_defaults_to_concept(capsys):
"""Legacy nodes with file_type=None (e.g. preserved from older graph.json
by `_rebuild_code`) must not trigger 'invalid file_type None' warnings (#660)."""
ext = {
"nodes": [
{"id": "n1", "label": "Stub", "file_type": None, "source_file": "a.py"},
{"id": "n2", "label": "Real", "file_type": "code", "source_file": "b.py"},
],
"edges": [],
"input_tokens": 0,
"output_tokens": 0,
}
G = build_from_json(ext)
err = capsys.readouterr().err
assert "invalid file_type" not in err
# The legacy node still exists in the graph and has been canonicalized
assert G.nodes["n1"]["file_type"] == "concept"
assert G.nodes["n2"]["file_type"] == "code"
def test_missing_file_type_defaults_to_concept(capsys):
"""Nodes missing file_type entirely should also be canonicalized to 'concept'."""
ext = {
"nodes": [
{"id": "n1", "label": "Bare", "source_file": "a.py"},
],
"edges": [],
"input_tokens": 0,
"output_tokens": 0,
}
G = build_from_json(ext)
err = capsys.readouterr().err
assert "invalid file_type" not in err
assert "missing required field 'file_type'" not in err
assert G.nodes["n1"]["file_type"] == "concept"
def test_real_invalid_file_type_still_warns(capsys):
"""Truly invalid file_type values (not None, not empty) must still warn."""
ext = {
"nodes": [
{"id": "n1", "label": "Bad", "file_type": "weird_type", "source_file": "a.py"},
],
"edges": [],
"input_tokens": 0,
"output_tokens": 0,
}
build_from_json(ext)
err = capsys.readouterr().err
assert "invalid file_type" in err
assert "weird_type" in err
def test_build_merge_preserves_call_edge_direction(tmp_path):
"""Regression for #760.
When the callee is defined before the caller in source, NetworkX's
undirected Graph stores edges in node-insertion order. Going through
node_link_graph() + edges() during build_merge previously flipped the
`calls` edge so that on the next save source/target were swapped.
build_merge must read the saved JSON's source/target verbatim instead
of round-tripping through NetworkX.
"""
from graphify.extract import extract_js
from graphify.export import to_json
# Callee `b` is defined before caller `a` so node insertion order
# is b, a. An undirected Graph then yields the edge as (b, a) on
# iteration, which is the wrong direction for `calls` (a calls b).
src = "function b() {}\nfunction a() { b(); }\n"
src_file = tmp_path / "x.js"
src_file.write_text(src)
extraction = extract_js(src_file)
assert "error" not in extraction
# Locate the `calls` edge in the raw extraction so we know the truth.
call_edges = [e for e in extraction["edges"] if e["relation"] == "calls"]
assert len(call_edges) == 1, "expected exactly one calls edge from the snippet"
truth_src = call_edges[0]["source"]
truth_tgt = call_edges[0]["target"]
nodes_by_id = {n["id"]: n for n in extraction["nodes"]}
assert nodes_by_id[truth_src]["label"].startswith("a")
assert nodes_by_id[truth_tgt]["label"].startswith("b")
# First build + save.
G1 = build([extraction], dedup=False)
graph_path = tmp_path / "graph.json"
communities: dict = {}
assert to_json(G1, communities, str(graph_path), force=True)
# Verify direction is correct in the freshly written JSON.
saved = json.loads(graph_path.read_text())
saved_calls = [e for e in saved.get("links", saved.get("edges", []))
if e.get("relation") == "calls"]
assert len(saved_calls) == 1
assert saved_calls[0]["source"] == truth_src
assert saved_calls[0]["target"] == truth_tgt
# Now simulate `--update` with no new chunks — load + re-save.
G2 = build_merge([], graph_path, dedup=False)
assert to_json(G2, communities, str(graph_path), force=True)
# The calls edge must still go a -> b, not b -> a.
reloaded = json.loads(graph_path.read_text())
reloaded_calls = [e for e in reloaded.get("links", reloaded.get("edges", []))
if e.get("relation") == "calls"]
assert len(reloaded_calls) == 1
assert reloaded_calls[0]["source"] == truth_src, (
f"calls edge source flipped after build_merge round-trip: "
f"expected {truth_src} (a), got {reloaded_calls[0]['source']}"
)
assert reloaded_calls[0]["target"] == truth_tgt, (
f"calls edge target flipped after build_merge round-trip: "
f"expected {truth_tgt} (b), got {reloaded_calls[0]['target']}"
)
# Regression tests for #796 — edge_data / edge_datas helpers must tolerate
# MultiGraph and MultiDiGraph, which networkx's node_link_graph() produces
# whenever the loaded JSON has multigraph: true. Plain G.edges[u, v] crashes
# on those with `ValueError: not enough values to unpack (expected 3, got 2)`.
def test_edge_data_simple_graph():
G = nx.Graph()
G.add_edge("a", "b", relation="calls", confidence="EXTRACTED")
d = edge_data(G, "a", "b")
assert isinstance(d, dict)
assert d["relation"] == "calls"
assert d["confidence"] == "EXTRACTED"
def test_edge_datas_simple_graph_returns_singleton_list():
G = nx.Graph()
G.add_edge("a", "b", relation="calls", confidence="EXTRACTED")
ds = edge_datas(G, "a", "b")
assert isinstance(ds, list)
assert len(ds) == 1
assert ds[0]["relation"] == "calls"
def test_edge_data_multigraph_with_parallel_edges():
G = nx.MultiGraph()
G.add_edge("a", "b", relation="calls", confidence="EXTRACTED")
G.add_edge("a", "b", relation="references", confidence="INFERRED")
d = edge_data(G, "a", "b")
assert isinstance(d, dict)
# First parallel edge wins; should be one of the two attribute dicts above.
assert d.get("relation") in ("calls", "references")
def test_edge_datas_multigraph_returns_all_parallel_edges():
G = nx.MultiGraph()
G.add_edge("a", "b", relation="calls", confidence="EXTRACTED")
G.add_edge("a", "b", relation="references", confidence="INFERRED")
ds = edge_datas(G, "a", "b")
assert isinstance(ds, list)
assert len(ds) == 2
relations = {e.get("relation") for e in ds}
assert relations == {"calls", "references"}
def test_edge_data_multidigraph():
G = nx.MultiDiGraph()
G.add_edge("a", "b", relation="calls")
G.add_edge("a", "b", relation="imports")
d = edge_data(G, "a", "b")
assert isinstance(d, dict)
assert d.get("relation") in ("calls", "imports")
ds = edge_datas(G, "a", "b")
assert len(ds) == 2
def test_edge_data_node_link_multigraph_roundtrip():
"""A node_link JSON with multigraph: true must load as MultiGraph and the
helpers must operate on it without raising the 3-tuple unpack ValueError."""
data = {
"directed": False,
"multigraph": True,
"graph": {},
"nodes": [
{"id": "a", "label": "A"},
{"id": "b", "label": "B"},
],
"links": [
{"source": "a", "target": "b", "relation": "calls", "confidence": "EXTRACTED"},
{"source": "a", "target": "b", "relation": "references", "confidence": "INFERRED"},
],
}
try:
G = json_graph.node_link_graph(data, edges="links")
except TypeError:
G = json_graph.node_link_graph(data)
assert isinstance(G, nx.MultiGraph)
# Plain G.edges[u, v] would raise here; the helper must not.
d = edge_data(G, "a", "b")
assert isinstance(d, dict)
assert d.get("relation") in ("calls", "references")
ds = edge_datas(G, "a", "b")
assert len(ds) == 2
+170
View File
@@ -0,0 +1,170 @@
import json
import subprocess
import sys
from pathlib import Path
from graphify.callflow_html import derive_sections_from_communities, write_callflow_html
def _make_graphify_out(tmp_path: Path) -> Path:
out = tmp_path / "graphify-out"
out.mkdir()
graph = {
"directed": False,
"multigraph": False,
"graph": {},
"nodes": [
{"id": "api", "label": "ApiClient", "source_file": "src/api.py", "file_type": "code", "community": 0},
{"id": "run", "label": "run()", "source_file": "src/main.py", "file_type": "code", "community": 0},
{"id": "export", "label": "write_html()", "source_file": "src/export.py", "file_type": "code", "community": 1},
{"id": "evil", "label": "<script>alert(1)</script>", "source_file": "src/evil.py", "file_type": "code", "community": 1},
],
"links": [
{"source": "run", "target": "api", "relation": "calls", "confidence": "EXTRACTED", "confidence_score": 1.0},
{"source": "api", "target": "export", "relation": "uses", "confidence": "EXTRACTED", "confidence_score": 1.0},
{"source": "export", "target": "evil", "relation": "calls", "confidence": "EXTRACTED", "confidence_score": 1.0},
],
"hyperedges": [],
"built_at_commit": "abcdef123456",
}
(out / "graph.json").write_text(json.dumps(graph), encoding="utf-8")
(out / ".graphify_labels.json").write_text(
json.dumps({"0": "Runtime", "1": "Export"}),
encoding="utf-8",
)
(out / "GRAPH_REPORT.md").write_text(
"\n".join(
[
"# Graph Report - sample",
"",
"## Summary",
"- 3 nodes · 2 edges · 1 communities detected",
"",
"## God Nodes (most connected - your core abstractions)",
"1. `Transformer` - 2 edges",
]
),
encoding="utf-8",
)
return out
def test_write_callflow_html_creates_file_and_uses_report(tmp_path):
out = _make_graphify_out(tmp_path)
html_path = write_callflow_html(
tmp_path,
output="graphify-out/callflow.html",
max_sections=4,
)
assert html_path == out / "callflow.html"
content = html_path.read_text(encoding="utf-8")
assert "mermaid" in content
assert "Graph Report Highlights" in content
assert "Transformer" in content
assert "ApiClient" in content
assert "&lt;script&gt;alert(1)&lt;/script&gt;" in content
assert "<script>alert(1)</script>" not in content
def test_export_callflow_html_cli_creates_file(tmp_path):
_make_graphify_out(tmp_path)
result = subprocess.run(
[
sys.executable,
"-m",
"graphify",
"export",
"callflow-html",
"--output",
"graphify-out/from-cli.html",
"--max-sections",
"4",
],
cwd=tmp_path,
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
html_path = tmp_path / "graphify-out" / "from-cli.html"
assert html_path.exists()
assert "callflow HTML written" in result.stdout
def test_export_callflow_html_cli_accepts_positional_graph_path(tmp_path):
_make_graphify_out(tmp_path)
external_out = tmp_path / "GitNexus" / "graphify-out"
external_out.mkdir(parents=True)
graph = {
"directed": False,
"multigraph": False,
"graph": {},
"nodes": [
{"id": "external", "label": "ExternalOnly", "source_file": "src/external.py", "file_type": "code", "community": 0},
{"id": "writer", "label": "write_external()", "source_file": "src/writer.py", "file_type": "code", "community": 1},
],
"links": [
{"source": "external", "target": "writer", "relation": "calls", "confidence": "EXTRACTED", "confidence_score": 1.0},
],
"hyperedges": [],
}
(external_out / "graph.json").write_text(json.dumps(graph), encoding="utf-8")
(external_out / ".graphify_labels.json").write_text(json.dumps({"0": "External Runtime", "1": "External Export"}), encoding="utf-8")
(external_out / "GRAPH_REPORT.md").write_text(
"\n".join(
[
"# Graph Report - external",
"",
"## Summary",
"- 2 nodes · 1 edges · 2 communities detected",
"",
"## God Nodes (most connected - your core abstractions)",
"1. `ExternalGod` - 1 edges",
]
),
encoding="utf-8",
)
result = subprocess.run(
[
sys.executable,
"-m",
"graphify",
"export",
"callflow-html",
str(external_out / "graph.json"),
"--output",
"positional.html",
"--max-sections",
"4",
],
cwd=tmp_path,
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
html = (tmp_path / "positional.html").read_text(encoding="utf-8")
assert "ExternalOnly" in html
assert "ExternalGod" in html
assert "ApiClient" not in html
assert "Transformer" not in html
def test_derive_sections_groups_by_architecture_keywords():
nodes = [
{"id": "extract_py", "label": "extract_python", "source_file": "graphify/extract.py", "community": 0},
{"id": "extract_js", "label": "extract_js", "source_file": "graphify/extract.py", "community": 0},
{"id": "to_html", "label": "to_html", "source_file": "graphify/export.py", "community": 1},
{"id": "test_html", "label": "test_export_html", "source_file": "tests/test_export.py", "community": 2},
]
sections = derive_sections_from_communities(nodes, {}, "en", 6)
ids = {section["id"] for section in sections}
assert "extract-pipeline" in ids
assert "outputs-docs" in ids
assert "tests-fixtures" in ids
+238
View File
@@ -0,0 +1,238 @@
"""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 os
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, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
return subprocess.run(
[PYTHON, "-m", "graphify"] + args,
cwd=cwd,
capture_output=True,
text=True,
env=env,
)
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
def test_query_uses_graphify_out_env(tmp_path):
out = _make_graph(tmp_path)
custom_out = tmp_path / "custom-graph"
out.rename(custom_out)
env = os.environ.copy()
env["GRAPHIFY_OUT"] = custom_out.name
r = _run(["query", "test"], tmp_path, env=env)
assert r.returncode == 0, r.stderr
assert len(r.stdout) > 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
def test_path_uses_graphify_out_env(tmp_path):
out = _make_graph(tmp_path)
custom_out = tmp_path / "custom-graph"
out.rename(custom_out)
env = os.environ.copy()
env["GRAPHIFY_OUT"] = custom_out.name
r = _run(["path", "Transformer", "LayerNorm"], tmp_path, env=env)
assert r.returncode == 0, r.stderr
# ── 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
def test_explain_uses_graphify_out_env(tmp_path):
out = _make_graph(tmp_path)
custom_out = tmp_path / "custom-graph"
out.rename(custom_out)
env = os.environ.copy()
env["GRAPHIFY_OUT"] = custom_out.name
r = _run(["explain", "test"], tmp_path, env=env)
assert r.returncode == 0, r.stderr
# ── 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
+62 -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
@@ -231,6 +258,40 @@ def test_classify_video_extensions():
assert classify_file(Path("audio.m4a")) == FileType.VIDEO
def test_classify_google_workspace_shortcuts():
assert classify_file(Path("notes.gdoc")) == FileType.DOCUMENT
assert classify_file(Path("budget.gsheet")) == FileType.DOCUMENT
assert classify_file(Path("deck.gslides")) == FileType.DOCUMENT
def test_detect_skips_google_workspace_shortcuts_by_default(tmp_path):
(tmp_path / "notes.gdoc").write_text('{"doc_id":"doc-1"}', encoding="utf-8")
result = detect(tmp_path)
assert not result["files"]["document"]
assert any("Google Workspace shortcut skipped" in item for item in result["skipped_sensitive"])
def test_detect_converts_google_workspace_shortcuts_when_enabled(tmp_path, monkeypatch):
shortcut = tmp_path / "notes.gdoc"
shortcut.write_text('{"doc_id":"doc-1"}', encoding="utf-8")
def fake_convert(path, out_dir, *, xlsx_to_markdown=None):
out_dir.mkdir(parents=True, exist_ok=True)
out = out_dir / "notes_converted.md"
out.write_text("# Notes\n\nA converted Google Doc.", encoding="utf-8")
return out
monkeypatch.setattr("graphify.detect.convert_google_workspace_file", fake_convert)
result = detect(tmp_path, google_workspace=True)
assert len(result["files"]["document"]) == 1
assert result["files"]["document"][0].endswith("notes_converted.md")
assert result["total_words"] > 0
def test_detect_includes_video_key(tmp_path):
"""detect() result always includes a 'video' key even with no video files."""
(tmp_path / "main.py").write_text("x = 1")
+233 -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
@@ -197,3 +194,234 @@ def test_cross_file_calls_skip_ambiguous_duplicate_labels(tmp_path):
nodes[e["source"]]["label"] == "run()" and nodes[e["target"]]["label"] == "log()"
for e in calls
)
def test_extract_generic_surfaces_tree_sitter_version_mismatch_hint(monkeypatch):
"""When Language() raises TypeError (e.g. old tree-sitter binding meets a
new tree-sitter API), the error message should point users at the upgrade
path instead of leaving a bare 'missing 1 required positional argument'.
"""
import sys
import types
from graphify.extract import _extract_generic, LanguageConfig
# Build a fake tree_sitter module whose Language() raises TypeError -
# this is exactly what users see when an older tree-sitter is paired
# with a newer language binding.
fake_ts = types.ModuleType("tree_sitter")
def _raise(*args, **kwargs):
raise TypeError("missing 1 required positional argument: 'name'")
fake_ts.Language = _raise
fake_ts.Parser = None
monkeypatch.setitem(sys.modules, "tree_sitter", fake_ts)
# Stub the language module so import_module returns something with .language
fake_lang_mod = types.ModuleType("fake_ts_lang")
fake_lang_mod.language = lambda: object()
monkeypatch.setitem(sys.modules, "fake_ts_lang", fake_lang_mod)
config = LanguageConfig(ts_module="fake_ts_lang", ts_language_fn="language")
result = _extract_generic(Path("dummy.txt"), config)
assert "error" in result
assert "tree-sitter version mismatch" in result["error"]
assert "pip install --upgrade" in result["error"]
def test_extract_js_destructured_require_imports_from():
"""`const { foo } = require('./mod')` must emit imports_from to the resolved module path."""
from graphify.extract import extract_js
result = extract_js(FIXTURES / "cjs_require.js")
imports_from = [e for e in result["edges"] if e["relation"] == "imports_from"]
targets = [e["target"] for e in imports_from]
# Must resolve relative require() targets to file ids so they connect across the corpus
assert any("foundation" in t for t in targets), f"No foundation import_from: {targets}"
assert any("utils" in t for t in targets), f"No utils import_from: {targets}"
assert any("helpers" in t for t in targets), f"No helpers import_from: {targets}"
for e in imports_from:
assert e["confidence"] == "EXTRACTED"
def test_extract_js_destructured_require_named_symbols():
"""Destructured CJS requires must emit symbol-level `imports` edges per binder."""
from graphify.extract import extract_js, _make_id, _file_stem
result = extract_js(FIXTURES / "cjs_require.js")
sym_targets = [e["target"] for e in result["edges"] if e["relation"] == "imports"]
foundation_stem = _file_stem(FIXTURES / "foundation.js")
assert _make_id(foundation_stem, "loadFoundation") in sym_targets
assert _make_id(foundation_stem, "validateConfig") in sym_targets
def test_extract_js_member_require_emits_property_symbol():
"""`const x = require('./m').y` must emit symbol edge for `y`."""
from graphify.extract import extract_js, _make_id, _file_stem
result = extract_js(FIXTURES / "cjs_require.js")
sym_targets = [e["target"] for e in result["edges"] if e["relation"] == "imports"]
helpers_stem = _file_stem(FIXTURES / "helpers.js")
assert _make_id(helpers_stem, "helperFn") in sym_targets
def test_extract_js_arrow_function_still_extracted():
"""Regression: arrow functions in lexical_declaration must still produce nodes."""
from graphify.extract import extract_js
arrow_fixture = FIXTURES / "_arrow_only.js"
arrow_fixture.write_text("const greet = () => console.log('hi');\n")
try:
result = extract_js(arrow_fixture)
labels = [n["label"] for n in result["nodes"]]
assert "greet()" in labels
finally:
arrow_fixture.unlink()
def test_cross_file_call_promoted_to_extracted_with_import_evidence(tmp_path):
"""A cross-file `calls` edge must be EXTRACTED when the caller's file has
an `imports` or `imports_from` edge linking it to the callee."""
caller = tmp_path / "caller.js"
callee = tmp_path / "lib.js"
caller.write_text(
"const { doWork } = require('./lib');\n"
"function run() { doWork(); }\n"
)
callee.write_text(
"function doWork() { return 1; }\n"
"module.exports = { doWork };\n"
)
result = extract([caller, callee], cache_root=tmp_path)
nodes = {n["id"]: n for n in result["nodes"]}
call_edges = [
e for e in result["edges"]
if e["relation"] == "calls"
and nodes[e["source"]]["label"] == "run()"
and nodes[e["target"]]["label"] == "doWork()"
]
assert len(call_edges) == 1
assert call_edges[0]["confidence"] == "EXTRACTED"
assert call_edges[0]["confidence_score"] == 1.0
def test_cross_file_call_remains_inferred_without_import_evidence(tmp_path):
"""A cross-file `calls` edge must stay INFERRED when there is no import
edge — name collision alone is insufficient evidence."""
caller = tmp_path / "caller.js"
callee = tmp_path / "lib.js"
# Caller does NOT require lib — same-name function happens to exist elsewhere
caller.write_text("function run() { doUnique(); }\n")
callee.write_text(
"function doUnique() { return 1; }\n"
"module.exports = { doUnique };\n"
)
result = extract([caller, callee], cache_root=tmp_path)
nodes = {n["id"]: n for n in result["nodes"]}
call_edges = [
e for e in result["edges"]
if e["relation"] == "calls"
and nodes[e["source"]]["label"] == "run()"
and nodes[e["target"]]["label"] == "doUnique()"
]
assert len(call_edges) == 1
assert call_edges[0]["confidence"] == "INFERRED"
# ── TSX (JSX-aware) parsing ──────────────────────────────────────────────────
# .tsx files require tree-sitter-typescript's `language_tsx`, not the plain
# `language_typescript` grammar. Parsing JSX with the wrong grammar produces
# silent ERROR nodes and drops every function/call inside JSX trees.
def test_extract_tsx_finds_helpers_and_component():
"""Functions defined alongside a JSX-returning component must be captured."""
from graphify.extract import extract_js
result = extract_js(FIXTURES / "sample.tsx")
labels = [n["label"] for n in result["nodes"]]
assert any("fmtDate" in l for l in labels), f"fmtDate missing from {labels}"
assert any("fmtCount" in l for l in labels), f"fmtCount missing from {labels}"
assert any("App" in l for l in labels), f"App missing from {labels}"
def test_extract_tsx_jsx_expression_calls_resolve():
"""Calls inside JSX expressions like `{fmtDate(now)}` must yield call edges.
Regression guard for the TSX language fix: with `language_typescript`,
JSX is parsed as ERROR nodes and these call_expressions disappear.
"""
from graphify.extract import extract_js
result = extract_js(FIXTURES / "sample.tsx")
nodes_by_id = {n["id"]: n for n in result["nodes"]}
call_targets = {
nodes_by_id[e["target"]]["label"]
for e in result["edges"]
if e["relation"] == "calls" and e["target"] in nodes_by_id
}
assert "fmtDate()" in call_targets, (
f"JSX expression call to fmtDate() not captured. Targets: {call_targets}"
)
assert "fmtCount()" in call_targets, (
f"JSX expression call to fmtCount() not captured. Targets: {call_targets}"
)
def test_extract_tsx_uses_tsx_grammar():
"""Wiring check: the .tsx config must use tree-sitter's `language_tsx`."""
from graphify.extract import _TSX_CONFIG, _TS_CONFIG
assert _TSX_CONFIG.ts_language_fn == "language_tsx"
assert _TS_CONFIG.ts_language_fn == "language_typescript"
# --- Windows-spawn ProcessPool fallback (regression for #?) ---
# When the caller has no `if __name__ == "__main__":` guard, ProcessPoolExecutor
# on Windows raises BrokenProcessPool before any work completes. extract() must
# detect this, warn, and fall back to sequential extraction rather than
# propagating a 290-line traceback.
def test_extract_falls_back_to_sequential_when_parallel_returns_false(tmp_path, monkeypatch):
"""extract() must run sequential when _extract_parallel signals failure (returns False)."""
from graphify import extract as extract_mod
files = [FIXTURES / "sample.py"] * 25 # >= _PARALLEL_THRESHOLD triggers parallel branch
cache_root = tmp_path / "cache"
cache_root.mkdir()
calls = {"parallel": 0, "sequential": 0}
real_sequential = extract_mod._extract_sequential
def fake_parallel(uncached_work, per_file, effective_root, max_workers, total_files):
calls["parallel"] += 1
return False # simulate the post-fix BrokenProcessPool branch
def wrapped_sequential(*args, **kwargs):
calls["sequential"] += 1
return real_sequential(*args, **kwargs)
monkeypatch.setattr(extract_mod, "_extract_parallel", fake_parallel)
monkeypatch.setattr(extract_mod, "_extract_sequential", wrapped_sequential)
result = extract_mod.extract(files, cache_root=cache_root)
assert calls["parallel"] == 1, "parallel path should have been attempted once"
assert calls["sequential"] == 1, "sequential fallback should have run exactly once"
assert result["nodes"], "extract should still produce nodes after fallback"
def test_extract_parallel_returns_false_on_broken_pool(tmp_path, monkeypatch, capsys):
"""_extract_parallel must catch BrokenProcessPool internally and return False."""
from concurrent.futures.process import BrokenProcessPool
import concurrent.futures
from graphify import extract as extract_mod
class FakePool:
def __init__(self, *a, **kw): pass
def __enter__(self): return self
def __exit__(self, *a): return False
def submit(self, *a, **kw):
raise BrokenProcessPool("simulated spawn failure")
monkeypatch.setattr(
concurrent.futures, "ProcessPoolExecutor", lambda *a, **kw: FakePool()
)
uncached = [(0, FIXTURES / "sample.py")]
per_file: list = [None]
ok = extract_mod._extract_parallel(uncached, per_file, tmp_path, 2, 1)
assert ok is False, "function should report failure via return value, not raise"
out = capsys.readouterr().out
assert "BrokenProcessPool" in out, "user-facing warning must mention the failure"
assert "__main__" in out, "warning must hint at the Windows __main__ guard idiom"
+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
+129
View File
@@ -0,0 +1,129 @@
from pathlib import Path
import json
import graphify.google_workspace as gw
def test_read_google_shortcut_doc_id(tmp_path):
shortcut = tmp_path / "Planning.gdoc"
shortcut.write_text(
'{"url":"https://docs.google.com/document/d/doc-123/edit","doc_id":"doc-123","email":"me@example.com"}',
encoding="utf-8",
)
metadata = gw.read_google_shortcut(shortcut)
assert metadata["file_id"] == "doc-123"
assert metadata["account"] == "me@example.com"
def test_read_google_shortcut_extracts_id_from_url(tmp_path):
shortcut = tmp_path / "Budget.gsheet"
shortcut.write_text(
'{"url":"https://docs.google.com/spreadsheets/d/sheet-456/edit?resourcekey=key-1"}',
encoding="utf-8",
)
metadata = gw.read_google_shortcut(shortcut)
assert metadata["file_id"] == "sheet-456"
assert metadata["resource_key"] == "key-1"
def test_convert_gdoc_to_markdown_sidecar(tmp_path, monkeypatch):
shortcut = tmp_path / "Planning.gdoc"
shortcut.write_text(
'{"url":"https://docs.google.com/document/d/doc-123/edit","doc_id":"doc-123"}',
encoding="utf-8",
)
def fake_export(file_id, mime_type, output, resource_key=None):
assert file_id == "doc-123"
assert mime_type == "text/markdown"
output.write_text("# Planning\n\nExported doc text.", encoding="utf-8")
monkeypatch.setattr(gw, "_run_gws_export", fake_export)
out = gw.convert_google_workspace_file(shortcut, tmp_path / "converted")
assert out is not None
assert out.suffix == ".md"
content = out.read_text(encoding="utf-8")
assert 'source_type: "google_workspace"' in content
assert "# Planning" in content
def test_convert_gsheet_uses_xlsx_markdown_callback(tmp_path, monkeypatch):
shortcut = tmp_path / "Budget.gsheet"
shortcut.write_text('{"doc_id":"sheet-456"}', encoding="utf-8")
def fake_export(file_id, mime_type, output, resource_key=None):
assert file_id == "sheet-456"
assert mime_type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
output.write_bytes(b"xlsx")
monkeypatch.setattr(gw, "_run_gws_export", fake_export)
out = gw.convert_google_workspace_file(
shortcut,
tmp_path / "converted",
xlsx_to_markdown=lambda path: "## Sheet: Main\n\n| A |\n| --- |\n| 1 |",
)
assert out is not None
assert "## Sheet: Main" in out.read_text(encoding="utf-8")
def test_run_gws_export_uses_output_directory_as_cwd(tmp_path, monkeypatch):
output = tmp_path / "converted" / "doc.md"
calls = []
class Result:
returncode = 0
stdout = ""
stderr = ""
def fake_run(cmd, **kwargs):
calls.append((cmd, kwargs))
return Result()
monkeypatch.setattr(gw.shutil, "which", lambda name: "/usr/local/bin/gws")
monkeypatch.setattr(gw.subprocess, "run", fake_run)
gw._run_gws_export("doc-123", "text/markdown", output)
assert output.parent.exists()
cmd, kwargs = calls[0]
assert kwargs["cwd"] == output.parent.resolve()
assert cmd[:4] == ["/usr/local/bin/gws", "drive", "files", "export"]
assert cmd[-2:] == ["-o", "doc.md"]
def test_run_gws_export_does_not_send_resource_key_as_query_param(tmp_path, monkeypatch):
output = tmp_path / "converted" / "doc.md"
calls = []
class Result:
returncode = 0
stdout = ""
stderr = ""
def fake_run(cmd, **kwargs):
calls.append(cmd)
return Result()
monkeypatch.setattr(gw.shutil, "which", lambda name: "/usr/local/bin/gws")
monkeypatch.setattr(gw.subprocess, "run", fake_run)
gw._run_gws_export("doc-123", "text/markdown", output, resource_key="rk-1")
params = json.loads(calls[0][calls[0].index("--params") + 1])
assert params == {"fileId": "doc-123", "mimeType": "text/markdown"}
def test_google_workspace_enabled_env(monkeypatch):
monkeypatch.setenv("GRAPHIFY_GOOGLE_WORKSPACE", "yes")
assert gw.google_workspace_enabled()
monkeypatch.setenv("GRAPHIFY_GOOGLE_WORKSPACE", "0")
assert not gw.google_workspace_enabled()
+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
+32 -2
View File
@@ -1,5 +1,7 @@
"""Tests for graphify install --platform routing."""
import os
from pathlib import Path
import sys
from unittest.mock import patch
import pytest
@@ -18,8 +20,13 @@ PLATFORMS = {
def _install(tmp_path, platform):
from graphify.__main__ import install
with patch("graphify.__main__.Path.home", return_value=tmp_path):
install(platform=platform)
old_cwd = Path.cwd()
try:
os.chdir(tmp_path)
with patch("graphify.__main__.Path.home", return_value=tmp_path):
install(platform=platform)
finally:
os.chdir(old_cwd)
def test_install_default_claude(tmp_path):
@@ -37,6 +44,29 @@ def test_install_opencode(tmp_path):
assert (tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_positional_platform_opencode(tmp_path, monkeypatch):
from graphify.__main__ import main
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(sys, "argv", ["graphify", "install", "opencode"])
with patch("graphify.__main__.Path.home", return_value=tmp_path):
main()
assert (tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md").exists()
assert not (tmp_path / ".claude" / "skills" / "graphify" / "SKILL.md").exists()
def test_install_help_does_not_install_default(tmp_path, monkeypatch, capsys):
from graphify.__main__ import main
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(sys, "argv", ["graphify", "install", "opencode", "--help"])
with patch("graphify.__main__.Path.home", return_value=tmp_path):
main()
out = capsys.readouterr().out
assert "Usage: graphify install" in out
assert "opencode" in out
assert not (tmp_path / ".claude").exists()
assert not (tmp_path / ".config").exists()
def test_install_claw(tmp_path):
_install(tmp_path, "claw")
assert (tmp_path / ".openclaw" / "skills" / "graphify" / "SKILL.md").exists()
+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
+515
View File
@@ -0,0 +1,515 @@
"""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)
# ---------------------------------------------------------------------------
# Adaptive retry: context-window overflow recovery
# ---------------------------------------------------------------------------
def _ok(nodes=None, edges=None, model="m"):
return {
"nodes": nodes or [],
"edges": edges or [],
"hyperedges": [],
"input_tokens": 1,
"output_tokens": 1,
"model": model,
"finish_reason": "stop",
}
def test_looks_like_context_exceeded_matches_common_messages():
msgs = [
"Error code: 400 - {'error': 'Context size has been exceeded.'}",
"n_keep: 22374 >= n_ctx: 4096",
"context_length_exceeded: This model's maximum context length is 8192 tokens",
"exceeds the available context size",
"The prompt is too long for this model.",
]
for m in msgs:
assert llm._looks_like_context_exceeded(RuntimeError(m)), m
def test_looks_like_context_exceeded_ignores_unrelated_errors():
for m in ["timeout", "rate limit", "401 unauthorized", "connection refused"]:
assert not llm._looks_like_context_exceeded(RuntimeError(m)), m
def test_adaptive_retry_splits_on_context_exceeded(tmp_path):
files = [tmp_path / f"f{i}.md" for i in range(4)]
for f in files:
f.write_text("hello")
calls = {"n": 0}
def fake_extract(chunk, *_, **__):
calls["n"] += 1
# First call (whole chunk) fails with context overflow; recursive
# halves succeed. This is the same shape LM Studio / vLLM / OpenAI
# produce when a chunk overflows the model's context window.
if len(chunk) == 4:
raise RuntimeError("Error 400: Context size has been exceeded.")
return _ok(nodes=[{"id": f.stem} for f in chunk])
with patch("graphify.llm.extract_files_direct", side_effect=fake_extract):
result = llm._extract_with_adaptive_retry(
files, backend="kimi", api_key="k", model="m", root=tmp_path, max_depth=3
)
assert len(result["nodes"]) == 4
assert calls["n"] == 3 # 1 failure + 2 halves
def test_adaptive_retry_gives_up_on_single_file_overflow(tmp_path):
f = tmp_path / "huge.md"
f.write_text("x")
def fake_extract(*_, **__):
raise RuntimeError("context_length_exceeded")
with patch("graphify.llm.extract_files_direct", side_effect=fake_extract):
result = llm._extract_with_adaptive_retry(
[f], backend="kimi", api_key="k", model="m", root=tmp_path, max_depth=3
)
# Single-file overflow returns an empty fragment instead of raising — the
# caller can keep going on the rest of the corpus.
assert result["nodes"] == []
assert result["edges"] == []
assert result["finish_reason"] == "stop"
def test_adaptive_retry_re_raises_unrelated_errors(tmp_path):
f = tmp_path / "f.md"
f.write_text("x")
def fake_extract(*_, **__):
raise RuntimeError("rate limit hit")
with patch("graphify.llm.extract_files_direct", side_effect=fake_extract):
with pytest.raises(RuntimeError, match="rate limit"):
llm._extract_with_adaptive_retry(
[f], backend="kimi", api_key="k", model="m", root=tmp_path, max_depth=3
)
# ---------------------------------------------------------------------------
# Hollow-response detection: empty / null / unparseable content from a
# successful HTTP call must route into the same bisection path as a true
# `finish_reason="length"` truncation, not be silently dropped.
# ---------------------------------------------------------------------------
def test_response_is_hollow_flags_empty_string():
assert llm._response_is_hollow("", {"nodes": [], "edges": [], "hyperedges": []})
def test_response_is_hollow_flags_none_content():
assert llm._response_is_hollow(None, {"nodes": [], "edges": [], "hyperedges": []})
def test_response_is_hollow_flags_whitespace_only():
assert llm._response_is_hollow(" \n\t ", {"nodes": [], "edges": [], "hyperedges": []})
def test_response_is_hollow_flags_parsed_but_no_nodes_or_edges():
# Content was non-empty (e.g. model said `{"sorry": "I cannot"}` or returned
# `{}` literally) but the parsed result has nothing usable.
assert llm._response_is_hollow('{"sorry": "I cannot"}', {})
assert llm._response_is_hollow("{}", {"nodes": [], "edges": [], "hyperedges": []})
def test_response_is_hollow_accepts_real_extraction():
parsed = {"nodes": [{"id": "x"}], "edges": [], "hyperedges": []}
assert not llm._response_is_hollow('{"nodes":[{"id":"x"}]}', parsed)
parsed = {"nodes": [], "edges": [{"source": "a", "target": "b"}], "hyperedges": []}
assert not llm._response_is_hollow('{"edges":[...]}', parsed)
def _fake_openai_response(content, *, finish_reason="stop", prompt_tokens=100, completion_tokens=0):
"""Build a minimal stand-in for an `openai` SDK ChatCompletion response."""
class _Usage:
def __init__(self):
self.prompt_tokens = prompt_tokens
self.completion_tokens = completion_tokens
class _Message:
def __init__(self):
self.content = content
class _Choice:
def __init__(self):
self.message = _Message()
self.finish_reason = finish_reason
class _Resp:
def __init__(self):
self.choices = [_Choice()]
self.usage = _Usage()
return _Resp()
def _install_fake_openai(monkeypatch, fake_resp):
"""Inject a stub `openai` module so `_call_openai_compat` can run without
the real SDK installed. The function does `from openai import OpenAI`
inside its body, so we satisfy that lookup via `sys.modules`."""
import sys
import types
class _FakeOpenAI:
def __init__(self, *_, **__):
self.chat = self
self.completions = self
def create(self, **__):
return fake_resp
fake_module = types.ModuleType("openai")
fake_module.OpenAI = _FakeOpenAI
monkeypatch.setitem(sys.modules, "openai", fake_module)
def test_call_openai_compat_relabels_empty_content_as_length(monkeypatch):
# Simulates an overwhelmed Ollama: HTTP 200, empty content, finish_reason
# "stop", zero completion tokens. Pre-fix this would silently return an
# empty fragment and the chunk would be dropped. Post-fix `finish_reason`
# is rewritten to "length" so the adaptive retry layer bisects.
fake_resp = _fake_openai_response("", finish_reason="stop", completion_tokens=0)
_install_fake_openai(monkeypatch, fake_resp)
result = llm._call_openai_compat(
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
"user msg", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert result["finish_reason"] == "length", (
"empty content from a 'successful' call must be re-labelled so the "
"adaptive retry layer treats it as a truncation and bisects the chunk"
)
def test_call_openai_compat_relabels_none_content_as_length(monkeypatch):
fake_resp = _fake_openai_response(None, finish_reason="stop")
_install_fake_openai(monkeypatch, fake_resp)
result = llm._call_openai_compat(
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert result["finish_reason"] == "length"
def test_call_openai_compat_relabels_unparseable_json_as_length(monkeypatch):
# A half-generated response: `{"nodes": [{"id":` parses to {} (empty
# fragment) via _parse_llm_json's JSONDecodeError fallback. That is also
# hollow and must trigger bisection.
fake_resp = _fake_openai_response('{"nodes": [{"id":', finish_reason="stop", completion_tokens=20)
_install_fake_openai(monkeypatch, fake_resp)
result = llm._call_openai_compat(
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert result["finish_reason"] == "length"
def test_call_openai_compat_preserves_real_finish_reason(monkeypatch):
# A genuine extraction with real nodes must NOT be re-labelled.
fake_resp = _fake_openai_response(
'{"nodes":[{"id":"a"}],"edges":[],"hyperedges":[]}',
finish_reason="stop",
completion_tokens=200,
)
_install_fake_openai(monkeypatch, fake_resp)
result = llm._call_openai_compat(
"http://localhost:11434/v1", "k", "m",
"u", temperature=0, max_completion_tokens=8192, backend="kimi",
)
assert result["finish_reason"] == "stop"
assert result["nodes"] == [{"id": "a"}]
# ---------------------------------------------------------------------------
# Ollama context-window fix (#798): num_ctx + keep_alive in extra_body,
# serial execution by default.
# ---------------------------------------------------------------------------
def _install_capturing_openai(monkeypatch):
"""Like _install_fake_openai but records kwargs passed to create()."""
import sys
import types
captured = {}
class _FakeOpenAI:
def __init__(self, *_, **__):
self.chat = self
self.completions = self
def create(self, **kwargs):
captured.update(kwargs)
return _fake_openai_response(
'{"nodes":[{"id":"x"}],"edges":[],"hyperedges":[]}',
finish_reason="stop",
completion_tokens=100,
)
fake_module = types.ModuleType("openai")
fake_module.OpenAI = _FakeOpenAI
monkeypatch.setitem(sys.modules, "openai", fake_module)
return captured
def test_ollama_extra_body_sets_num_ctx_and_keep_alive(monkeypatch):
captured = _install_capturing_openai(monkeypatch)
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
llm._call_openai_compat(
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
"user msg", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert "extra_body" in captured, "extra_body must be sent to Ollama"
eb = captured["extra_body"]
# num_ctx is now dynamic: derived from message size, not hardcoded 131072
assert "num_ctx" in eb.get("options", {}), "num_ctx must be present"
assert eb["options"]["num_ctx"] >= 8192, "num_ctx must be at least the floor value"
assert eb.get("keep_alive") == "30m", "default keep_alive must be 30m"
def test_ollama_num_ctx_scales_with_small_token_budget(monkeypatch):
# Regression for #798 follow-up: with --token-budget 8192, the old hardcoded
# 131072 forced Ollama to allocate 128k KV-cache slots on a 31B model, causing
# VRAM exhaustion by chunk 4. num_ctx must now reflect actual chunk size.
captured = _install_capturing_openai(monkeypatch)
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
# Simulate an 8k-token chunk: ~32k chars of content
small_chunk_msg = "x" * 32_000
llm._call_openai_compat(
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
small_chunk_msg, temperature=0, max_completion_tokens=16384, backend="ollama",
)
num_ctx = captured["extra_body"]["options"]["num_ctx"]
# Should be far less than 131072 for an 8k input — VRAM-friendly
assert num_ctx < 131072, (
f"num_ctx={num_ctx} is too large for a small chunk; "
"this wastes VRAM and causes OOM on large models (#798)"
)
# But still large enough to fit input + output
assert num_ctx >= 8192, "num_ctx must cover at least the output cap"
def test_ollama_num_ctx_env_override(monkeypatch):
captured = _install_capturing_openai(monkeypatch)
monkeypatch.setenv("GRAPHIFY_OLLAMA_NUM_CTX", "65536")
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
llm._call_openai_compat(
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert captured["extra_body"]["options"]["num_ctx"] == 65536
def test_non_ollama_backend_gets_no_num_ctx_extra_body(monkeypatch):
captured = _install_capturing_openai(monkeypatch)
llm._call_openai_compat(
"https://api.openai.com/v1", "sk-test", "gpt-4.1-mini",
"u", temperature=0, max_completion_tokens=8192, backend="openai",
)
eb = captured.get("extra_body")
assert eb is None or "options" not in eb, "non-ollama backends must not get num_ctx injection"
def test_extract_corpus_parallel_ollama_runs_serially(tmp_path, monkeypatch):
# With 3 chunks and backend=ollama, ThreadPoolExecutor must NOT be used
# (workers=1 takes the sequential path). We verify by ensuring all chunks
# are processed and no pool is spun up.
files = [tmp_path / f"f{i}.md" for i in range(6)]
for f in files:
f.write_text("hello")
call_order = []
def fake_extract(chunk, *_, **__):
call_order.append(len(chunk))
return _ok(nodes=[{"id": f.stem} for f in chunk])
monkeypatch.delenv("GRAPHIFY_OLLAMA_PARALLEL", raising=False)
with patch("graphify.llm.extract_files_direct", side_effect=fake_extract):
with patch("graphify.llm.ThreadPoolExecutor") as mock_pool:
result = llm.extract_corpus_parallel(
files, backend="ollama", api_key="ollama", model="qwen2.5-coder:7b",
root=tmp_path, token_budget=None, chunk_size=2, max_concurrency=4,
)
mock_pool.assert_not_called()
assert len(result["nodes"]) == 6
def test_extract_corpus_parallel_ollama_parallel_env_restores_concurrency(tmp_path, monkeypatch):
files = [tmp_path / f"f{i}.md" for i in range(4)]
for f in files:
f.write_text("hello")
monkeypatch.setenv("GRAPHIFY_OLLAMA_PARALLEL", "1")
with patch("graphify.llm.extract_files_direct", return_value=_ok()):
with patch("graphify.llm.ThreadPoolExecutor") as mock_pool:
mock_pool.return_value.__enter__ = lambda s: s
mock_pool.return_value.__exit__ = lambda s, *a: False
mock_pool.return_value.submit = lambda fn, *a, **kw: type(
"F", (), {"result": lambda self: fn(*a, **kw)}
)()
try:
llm.extract_corpus_parallel(
files, backend="ollama", api_key="ollama", model="m",
root=tmp_path, token_budget=None, chunk_size=2, max_concurrency=4,
)
except Exception:
pass # mock scaffolding may not be complete; we only care about the call
mock_pool.assert_called()
def test_adaptive_retry_bisects_on_hollow_ollama_response(tmp_path):
# End-to-end: an overwhelmed Ollama returns hollow on the full 4-file
# chunk; halves succeed. The bug being fixed is that pre-fix this
# produces zero nodes (chunk silently dropped). Post-fix the hollow
# response is relabelled `finish_reason="length"` and the existing
# bisection path recovers the full 4 nodes.
files = [tmp_path / f"f{i}.md" for i in range(4)]
for f in files:
f.write_text("hello")
calls = {"n": 0}
def fake_extract(chunk, *_, **__):
calls["n"] += 1
if len(chunk) == 4:
# Hollow response: looks successful, finish_reason already
# rewritten to "length" by _call_openai_compat.
return {
"nodes": [], "edges": [], "hyperedges": [],
"input_tokens": 100, "output_tokens": 0,
"model": "m", "finish_reason": "length",
}
return _ok(nodes=[{"id": f.stem} for f in chunk])
with patch("graphify.llm.extract_files_direct", side_effect=fake_extract):
result = llm._extract_with_adaptive_retry(
files, backend="ollama", api_key="ollama", model="qwen2.5-coder:7b",
root=tmp_path, max_depth=3,
)
assert len(result["nodes"]) == 4, (
"bisection should recover all 4 nodes from the two halves after the "
"full chunk came back hollow"
)
assert calls["n"] == 3 # 1 hollow + 2 successful halves
+27
View File
@@ -252,3 +252,30 @@ def test_sql_no_dangling_edges():
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"dangling source: {e['source']}"
def test_sql_alter_table_fk_edge():
"""ALTER TABLE ... FOREIGN KEY ... REFERENCES produces a references edge."""
r = extract_sql(FIXTURES / "sample_alter_fk.sql")
fk_edges = [e for e in r["edges"] if e["relation"] == "references"]
assert len(fk_edges) >= 1
node_ids = {n["id"] for n in r["nodes"]}
for e in fk_edges:
assert e["source"] in node_ids, f"dangling source: {e['source']}"
assert e["target"] in node_ids, f"dangling target: {e['target']}"
def test_sql_schema_qualified_names():
"""Schema-qualified table names (Schema.Table) are preserved."""
r = extract_sql(FIXTURES / "sample_schema_qualified.sql")
labels = [n["label"] for n in r["nodes"]]
assert any("Sales.Customer" in l for l in labels)
assert any("Sales.SalesOrder" in l for l in labels)
def test_sql_schema_qualified_alter_fk():
"""ALTER TABLE with schema-qualified names produces correct edges."""
r = extract_sql(FIXTURES / "sample_schema_qualified.sql")
fk_edges = [e for e in r["edges"] if e["relation"] == "references"]
assert len(fk_edges) >= 1
node_ids = {n["id"] for n in r["nodes"]}
for e in fk_edges:
assert e["source"] in node_ids, f"dangling source: {e['source']}"
assert e["target"] in node_ids, f"dangling target: {e['target']}"
+74
View File
@@ -0,0 +1,74 @@
"""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_claude_beats_ollama(monkeypatch):
# ANTHROPIC_API_KEY (paid, intentional) should win over OLLAMA_BASE_URL
# (env-driven, easy to set accidentally) -- security fix F-002/F-029.
monkeypatch.delenv("MOONSHOT_API_KEY", raising=False)
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434/v1")
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test")
assert detect_backend() == "claude"
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)
+322
View File
@@ -0,0 +1,322 @@
"""Tests for the Pascal/Delphi extractor."""
from __future__ import annotations
from pathlib import Path
FIXTURES = Path(__file__).parent / "fixtures"
def _labels(r):
return [n["label"] for n in r["nodes"]]
def _relations(r):
return {e["relation"] for e in r["edges"]}
def _edges_with_relation(r, *relations):
return [e for e in r["edges"] if e["relation"] in relations]
def test_pascal_no_error():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
assert "error" not in r
def test_pascal_finds_unit():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
assert any("SampleUnit" in l for l in _labels(r))
def test_pascal_finds_classes():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
labels = _labels(r)
assert any("TBaseProcessor" in l for l in labels)
assert any("TDataProcessor" in l for l in labels)
def test_pascal_finds_interface():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
assert any("IProcessor" in l for l in _labels(r))
def test_pascal_finds_methods():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
labels = _labels(r)
assert any("Process" in l for l in labels)
assert any("Initialize" in l for l in labels)
assert any("GetCount" in l for l in labels)
assert any("Reset" in l for l in labels)
def test_pascal_finds_imports():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
assert "imports" in _relations(r)
def test_pascal_import_edges_have_import_context():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
import_edges = _edges_with_relation(r, "imports")
assert import_edges
assert all(e.get("context") == "import" for e in import_edges)
def test_pascal_finds_inherits():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
assert "inherits" in _relations(r)
def test_pascal_inherits_from_base():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
found = any(
"TDataProcessor" in node_by_id.get(e["source"], "")
for e in inherits
)
assert found, "TDataProcessor should have at least one inherits edge"
def test_pascal_finds_calls():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
assert "calls" in _relations(r)
def test_pascal_call_edges_have_call_context():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_pascal_all_edges_extracted():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
structural = {"contains", "method", "inherits", "imports"}
for e in r["edges"]:
if e["relation"] in structural:
assert e["confidence"] == "EXTRACTED", f"Expected EXTRACTED: {e}"
def test_pascal_no_dangling_edges():
from graphify.extract import extract_pascal
r = extract_pascal(FIXTURES / "sample.pas")
node_ids = {n["id"] for n in r["nodes"]}
# imports edges are cross-file by design; only check within-file edge targets
within_file_relations = {"contains", "method", "inherits", "calls"}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e}"
if e["relation"] in within_file_relations:
assert e["target"] in node_ids, f"Dangling target: {e}"
def test_pascal_dispatch_registered():
from graphify.extract import _DISPATCH
assert ".pas" in _DISPATCH
assert ".pp" in _DISPATCH
assert ".dpr" in _DISPATCH
assert ".dpk" in _DISPATCH
assert ".lpr" in _DISPATCH
assert ".inc" in _DISPATCH
assert ".lfm" in _DISPATCH
assert ".lpk" in _DISPATCH
def test_pascal_detect_extensions_registered():
from graphify.detect import CODE_EXTENSIONS
assert ".pas" in CODE_EXTENSIONS
assert ".pp" in CODE_EXTENSIONS
assert ".dpr" in CODE_EXTENSIONS
assert ".lpr" in CODE_EXTENSIONS
assert ".lfm" in CODE_EXTENSIONS
assert ".lpk" in CODE_EXTENSIONS
# ── Lazarus Form (.lfm) ───────────────────────────────────────────────────────
def test_lfm_no_error():
from graphify.extract import extract_lazarus_form
r = extract_lazarus_form(FIXTURES / "sample.lfm")
assert "error" not in r
def test_lfm_finds_root_form_class():
from graphify.extract import extract_lazarus_form
r = extract_lazarus_form(FIXTURES / "sample.lfm")
assert any("TSampleForm" in l for l in _labels(r))
def test_lfm_finds_component_classes():
from graphify.extract import extract_lazarus_form
r = extract_lazarus_form(FIXTURES / "sample.lfm")
labels = _labels(r)
assert any("TPanel" in l for l in labels)
assert any("TButton" in l for l in labels)
assert any("TLabel" in l for l in labels)
assert any("TTimer" in l for l in labels)
def test_lfm_finds_event_handlers():
from graphify.extract import extract_lazarus_form
r = extract_lazarus_form(FIXTURES / "sample.lfm")
labels = _labels(r)
assert any("ButtonOKClick" in l for l in labels)
assert any("TimerRefreshTimer" in l for l in labels)
def test_lfm_event_edges_have_event_context():
from graphify.extract import extract_lazarus_form
r = extract_lazarus_form(FIXTURES / "sample.lfm")
ref_edges = [e for e in r["edges"] if e["relation"] == "references"]
assert ref_edges
assert all(e.get("context") == "event" for e in ref_edges)
def test_lfm_contains_edges_form_hierarchy():
from graphify.extract import extract_lazarus_form
r = extract_lazarus_form(FIXTURES / "sample.lfm")
assert "contains" in _relations(r)
def test_lfm_no_dangling_edges():
from graphify.extract import extract_lazarus_form
r = extract_lazarus_form(FIXTURES / "sample.lfm")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e}"
# ── Lazarus Package (.lpk) ───────────────────────────────────────────────────
def test_lpk_no_error():
from graphify.extract import extract_lazarus_package
r = extract_lazarus_package(FIXTURES / "sample.lpk")
assert "error" not in r
def test_lpk_finds_package_name():
from graphify.extract import extract_lazarus_package
r = extract_lazarus_package(FIXTURES / "sample.lpk")
assert any("SamplePackage" in l for l in _labels(r))
def test_lpk_finds_required_packages():
from graphify.extract import extract_lazarus_package
r = extract_lazarus_package(FIXTURES / "sample.lpk")
labels = _labels(r)
assert any("FCL" in l for l in labels)
assert any("LCL" in l for l in labels)
def test_lpk_imports_edges_have_import_context():
from graphify.extract import extract_lazarus_package
r = extract_lazarus_package(FIXTURES / "sample.lpk")
import_edges = _edges_with_relation(r, "imports")
assert import_edges
assert all(e.get("context") == "import" for e in import_edges)
def test_lpk_contains_listed_units():
from graphify.extract import extract_lazarus_package
r = extract_lazarus_package(FIXTURES / "sample.lpk")
labels = _labels(r)
assert any("sample" in l.lower() for l in labels)
assert any("sampleutils" in l.lower() for l in labels)
def test_lpk_no_dangling_edges():
from graphify.extract import extract_lazarus_package
r = extract_lazarus_package(FIXTURES / "sample.lpk")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["edges"]:
assert e["source"] in node_ids, f"Dangling source: {e}"
# ── Delphi Form (.dfm) ───────────────────────────────────────────────────────
def test_dfm_no_error():
from graphify.extract import extract_delphi_form
r = extract_delphi_form(FIXTURES / "sample.dfm")
assert "error" not in r
def test_dfm_finds_root_form_class():
from graphify.extract import extract_delphi_form
r = extract_delphi_form(FIXTURES / "sample.dfm")
assert any("TMainForm" in l for l in _labels(r))
def test_dfm_finds_component_classes():
from graphify.extract import extract_delphi_form
r = extract_delphi_form(FIXTURES / "sample.dfm")
labels = _labels(r)
assert any("TPanel" in l for l in labels)
assert any("TButton" in l for l in labels)
assert any("TMemo" in l for l in labels)
assert any("TStatusBar" in l for l in labels)
def test_dfm_finds_event_handlers():
from graphify.extract import extract_delphi_form
r = extract_delphi_form(FIXTURES / "sample.dfm")
labels = _labels(r)
assert any("FormCreate" in l for l in labels)
assert any("ButtonOKClick" in l for l in labels)
def test_dfm_event_edges_have_event_context():
from graphify.extract import extract_delphi_form
r = extract_delphi_form(FIXTURES / "sample.dfm")
ref_edges = [e for e in r["edges"] if e["relation"] == "references"]
assert ref_edges
assert all(e.get("context") == "event" for e in ref_edges)
def test_dfm_contains_edges_form_hierarchy():
from graphify.extract import extract_delphi_form
r = extract_delphi_form(FIXTURES / "sample.dfm")
assert "contains" in _relations(r)
def test_dfm_no_dangling_edges():
from graphify.extract import extract_delphi_form
r = extract_delphi_form(FIXTURES / "sample.dfm")
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_dfm_binary_returns_empty_not_crash():
from graphify.extract import extract_delphi_form
import tempfile, pathlib
# Write a fake binary DFM (FF 0A magic header)
with tempfile.NamedTemporaryFile(suffix=".dfm", delete=False) as f:
f.write(b"\xff\x0a\x00\x00some binary data")
tmp = pathlib.Path(f.name)
try:
r = extract_delphi_form(tmp)
assert r["nodes"] == []
assert r["edges"] == []
assert "error" in r
finally:
tmp.unlink()
def test_dfm_dispatch_registered():
from graphify.extract import _DISPATCH
assert ".dfm" in _DISPATCH
def test_dfm_detect_extension_registered():
from graphify.detect import CODE_EXTENSIONS
assert ".dfm" in CODE_EXTENSIONS