Compare commits

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-15 11:08:27 -04:00
SafiandClaude Sonnet 4.6 7c561e6f82 Skip coverage/visual-test/snapshot/storybook-static noise dirs in detect (#869, #870)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:51:39 +01:00
SafiandClaude Sonnet 4.6 4e7648b4e2 fix #865: use git rev-parse --git-path hooks so hook install works in linked worktrees
In a linked worktree .git is a file not a directory, so root/.git/hooks
fails with NotADirectoryError. Fall back to git rev-parse --path-format=absolute
--git-path hooks which resolves the correct hooks dir from any worktree.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:37:05 +01:00
SafiandClaude Sonnet 4.6 972fdc1b87 fix #862 #861 #857: skill-windows.md path prefix, sidecar graphifyignore bypass, manifest ast/semantic split
- skill-windows.md: add graphify-out/ prefix to 5 paths in Step B3 that
  were being read/written without prefix (lines 244,245,373,387,388,407,413)
  causing semantic cache to always appear empty on Windows (#862)
- detect.py: gate converted office/Google Workspace sidecar paths through
  _is_ignored() before appending to files list so .graphifyignore rules
  apply to graphify-out/converted/ sidecars (#861)
- detect.py: split manifest entries from {mtime,hash} to
  {mtime,ast_hash,semantic_hash}; save_manifest() accepts kind="ast"|
  "semantic"|"both"; detect_incremental() accepts kind= and checks the
  right hash field so graphify update (kind=ast) no longer prevents
  graphify extract from re-running semantic extraction (#857)
- watch.py: all three save_manifest() calls use kind="ast" (AST-only rebuild)
- __main__.py: both extract save_manifest() calls use kind="both"
- backwards compatible: legacy {mtime,hash} entries treated as ast_hash only

775 tests passing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 23:31:14 +01:00
Safi a9b0ddbb86 add .astro to supported extensions in README 2026-05-14 11:48:59 +01:00
Safi 3baedc5bdb bump version to 0.7.19 2026-05-14 11:43:28 +01:00
Safiandvoidborne-d cfe18ea947 fix(watch): unlink .rebuild.lock on release, rewrite single PID line (PR #859, voidborne-d)
Co-Authored-By: voidborne-d <voidborne-d@users.noreply.github.com>
2026-05-14 10:49:10 +01:00
Safiandspindle79 fcafec7081 feat(extract): add .astro support (#850, PR #852, spindle79)
Co-Authored-By: spindle79 <spindle79@users.noreply.github.com>
2026-05-14 10:49:02 +01:00
SafiandJstottlemyer 6c78a74776 docs(skill): clarify no provider API key is read for semantic extraction (PR #864, Jstottlemyer)
Co-Authored-By: Jstottlemyer <Jstottlemyer@users.noreply.github.com>
2026-05-14 10:48:57 +01:00
Justin Stottlemyer a08f0de53b docs(skill): clarify that no provider API key is read for semantic extraction
Several host agents (Claude Code in particular) misread the current
phrasing and prompt the user for `ANTHROPIC_API_KEY` when no Gemini
key is set, instead of falling through to subagent dispatch. The
Gemini tip stays as-is; this just adds an explicit one-line callout
that no other provider keys are consulted, with `ANTHROPIC_API_KEY`
called out by name since that is the specific misread we hit in the
wild.

No behavior change — pure documentation.
2026-05-13 23:29:02 -07:00
voidborne-dandClaude Opus 4.7 2c975ee9fb fix(watch): unlink .rebuild.lock on release and rewrite single PID line (#858)
The rebuild lock file accumulated concatenated PIDs across post-commit
rebuilds without a separator, and was never removed when the rebuild
finished. Two practical consequences for users:

1. Downstream tooling that polls for `.rebuild.lock` to disappear before
   doing post-rebuild work (publish scripts copying graph.html to a web
   root, etc.) blocked forever / until its own timeout.
2. The accumulated digit string could not be parsed by humans or tooling
   to find the owning PID.

The `_rebuild_lock` context manager now:

- Opens the lock file with `a+` so a non-acquiring caller does not
  truncate the existing holder's PID.
- After flock acquisition, truncates and writes a single `<pid>\n` line
  so external readers can `kill -0 $(cat .rebuild.lock)` to check
  liveness.
- Unlinks the lock file in the finally block (only when *we* held the
  lock), restoring the "signal-by-absence" convention users rely on.

Four regression tests added under `tests/test_watch.py` covering the
PID-with-newline payload, post-release unlink, no-accumulation across
sequential acquisitions, and the non-blocking-caller-does-not-clobber
invariant.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 08:05:55 +08:00
Safi 77bb10c682 document --force for extract and ghost-duplicate cleanup in README 2026-05-14 00:59:58 +01:00
Safi b7e7ae5ad6 bump version to 0.7.18 2026-05-14 00:57:47 +01:00
Safi 7c68c84fac update README and CHANGELOG for v0.7.18 2026-05-14 00:37:47 +01:00
Safi f7c9a9ad82 fix watch.py labels churn, edges/links schema, shrink-check duplication, and skill.md ID edge cases 2026-05-14 00:29:54 +01:00
Safi 7d1c1096bc fix node ID format in skill.md: parent_dir+stem, not filename-only (fixes ghost-duplicate root cause from #807) 2026-05-14 00:12:04 +01:00
SafiandFatahChan 1b8b76816e fix: deterministic clustering, topology short-circuit on unchanged graph, --no-cluster for update (PR #824, FatahChan)
Co-Authored-By: FatahChan <FatahChan@users.noreply.github.com>
2026-05-14 00:11:41 +01:00
Safiandsachinampity ddb98226df docs: add prerequisites, extras table, env vars, troubleshooting, dev setup (PR #833, sachinampity)
Co-Authored-By: sachinampity <sachinampity@users.noreply.github.com>
2026-05-14 00:11:15 +01:00
Safi 76833f0281 document --backend claude-cli in README 2026-05-14 00:04:50 +01:00
258d2600cd feat: add --backend claude-cli (routes through Claude Code, no API key needed) (#855)
Co-Authored-By: spindle79 <spindle79@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:53:00 +01:00
SafiandClaude Sonnet 4.6 c4c2205658 bump version to 0.7.17
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:45:33 +01:00
53da14333e rename sample.F90 → sample_preprocessed.F90 to fix macOS case-collision
Co-Authored-By: FatahChan <FatahChan@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:39:01 +01:00
SafiandClaude Sonnet 4.6 822abd6e69 fix --update manifest shrink and align file_type enum (#837, #840)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:22:37 +01:00
Safi 7bb0919c72 fix path/explain arrow direction and bedrock CLI guard (#846, #849, #853) 2026-05-13 23:19:15 +01:00
SafiandClaude Sonnet 4.6 d0e09aa89d fix MCP tool arrow direction and hub-transit BFS (#830, #849, #853)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 23:18:52 +01:00
Adam Harris c0048d0a61 feat(extract): add .astro support (#850)
Astro files have a `---...---` TypeScript frontmatter block at the top
containing nearly all imports, followed by an HTML-with-expressions
template body, and optionally `<script>` blocks for client-side JS.
Feeding the whole file to the JS tree-sitter parser produces a top-level
ERROR node because the template isn't valid JS, so `import_statement`
nodes are never reached.

Mirrors `extract_svelte` (#713) — same regex-rescue strategy:

- Dynamic `import('...')` pass over the full source.
- Static `import X from '...'` pass over the frontmatter block plus any
  `<script>` blocks.

Both static and dynamic imports honor tsconfig.json path aliases and
resolve relative paths through `_resolve_js_module_path` so node ids
match the targets that `_extract_generic` produces for sibling files.

Wired in:
- `detect.py:27` — `.astro` added to `CODE_EXTENSIONS`.
- `extract.py:5492` — `".astro": extract_astro` in the dispatch table.

Tests in `tests/test_astro_extraction.py` cover: extension registration,
frontmatter static imports, dynamic import in frontmatter, client-side
`<script>` block imports, frontmatter-less pages (must not crash), and
tsconfig.json path-alias resolution.
2026-05-13 10:07:50 -07:00
SafiandClaude Sonnet 4.6 5f9ea2b80e document graphify --version in CLI reference
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 14:53:22 +01:00
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
sachinampityandClaude Sonnet 4.6 2db5d966f2 docs: comprehensive README overhaul with prerequisites, extras, env vars, troubleshooting, dev setup
Added sections:
- Prerequisites — Python 3.10+ requirement with per-OS install commands (Homebrew, winget, apt)
- Optional extras table — all graphifyy[...] extras with what each adds and install command
- Environment variables — consolidated reference for all GRAPHIFY_* vars and API keys
  needed for headless/CI extraction (ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY,
  MOONSHOT_API_KEY, OLLAMA_BASE_URL/MODEL, GRAPHIFY_MAX_WORKERS, etc.)
- Troubleshooting — 8 common issues with exact fix commands (PATH, PowerShell slash,
  Ollama VRAM, graph.json merge conflicts, empty extraction, version mismatch)
- Development setup (inside Contributing) — editable install steps, venv creation,
  pytest instructions, git workflow, macOS case-sensitive fixture note

Preserved all existing content unchanged: logo, badges, star chart, translations,
platform install tables, full command reference, privacy section, Penpax section.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 14:25:52 +05:30
Ahmad FathallahandCursor 28fc71eddc skip reclustering when topology is unchanged
Add a pre-cluster topology comparison fast path in update rebuilds so unchanged graphs short-circuit before clustering and report generation, preventing residual run-to-run community-count drift.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 03:36:26 +03:00
Ahmad FathallahandCursor ef0e6ee681 harden community serialization fallbacks
Use safe JSON serialization fallbacks for deterministic sort keys in clustering and graph canonicalization, and skip invalid community IDs with a stderr warning instead of raising during update rebuilds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 02:37:38 +03:00
Ahmad FathallahandCursor 8e4c803f31 reduce graph update churn and stabilize community IDs
Make `graphify update` idempotent by skipping output rewrites when graph/report content is unchanged, add `update --no-cluster`, and preserve community IDs across runs via overlap-based remapping with deterministic partition inputs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 02:23:51 +03: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
Safi f81e3bc215 bump version to 0.6.9 2026-05-03 17:41:56 +01:00
SafiandClaude Sonnet 4.6 8e81720bc8 Fix #686 #652: GRAPHIFY_OUT env var for worktrees, Antigravity install auto-updates rules/workflow
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:36:17 +01:00
SafiandClaude Sonnet 4.6 6df69dce6c Fix #683: normalize source_file path separators + two-phase cohesion re-clustering
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:26:13 +01:00
SafiandClaude Sonnet 4.6 f61bb27d9c Fix #688: stricter VS Code Copilot instructions to enforce GRAPH_REPORT.md first
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:23:31 +01:00
Safi de268a067c fix Penpax waitlist link to graphifylabs.ai 2026-05-03 14:09:16 +01:00
SafiandClaude Sonnet 4.6 b11a8a7813 simplify README, move technical details to docs/how-it-works.md
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:31:28 +01:00
SafiandClaude Sonnet 4.6 d753413409 bump version to 0.6.8
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:25:44 +01:00
SafiandClaude Sonnet 4.6 f065933391 Fix #676 #678 #681: graphifyignore negation, Antigravity slash command, Gemini hook Windows
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 13:22:17 +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
SafiandClaude Sonnet 4.6 893acb19df Fix #664: filter thin communities from GRAPH_REPORT.md by default
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 18:09:32 +01:00
SafiandClaude Sonnet 4.6 96267ad0a8 fix #651: resolve absolute graphify path at codex install time for VS Code extension on Windows
shutil.which() first; falls back to sys.executable sibling Scripts/graphify.exe
so the hook works even when venv/Scripts is not on Codex's PATH.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:38:24 +01:00
SafiandClaude Sonnet 4.6 cf7ce3a450 fix #651: hook-check exits silently instead of emitting unsupported additionalContext
Codex Desktop rejects hookSpecificOutput.additionalContext on PreToolUse.
hook-check is now a no-op — graph guidance reaches the agent via AGENTS.md/skill.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:29:40 +01:00
ba41258635 merge PR #663: parallel AST extraction with ProcessPoolExecutor (1.66x speedup on 84 files)
Co-Authored-By: hanzala-sohrab <hanzala-sohrab@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:24:57 +01:00
Safi e48428296c bump version to 0.6.7 2026-05-02 17:13:08 +01:00
SafiandClaude Sonnet 4.6 d819827ea2 fix #655 #656 #657 #658: cache dir crash, sanitize_label None, rationale file_type, token counting
#655 and #656 already fixed in cache.py and security.py.
#657: add rationale to file_type schema in all 12 skill variants; warn against inventing concept.
#658: add explicit chunk-merge step with token summation before save_semantic_cache.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:10:20 +01:00
Safi bd92ab67d6 docs: remove VB.NET from README language count and file type table 2026-05-02 17:06:00 +01:00
Hanzala Sohrab 0a99a46bfc chore: update project dependencies and metadata in pyproject.toml 2026-05-02 21:34:20 +05:30
SafiandClaude Sonnet 4.6 1e848458f9 remove VB.NET support: tree-sitter-vbnet only has Windows wheels, no Linux/macOS
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 17:02:24 +01:00
SafiandClaude Sonnet 4.6 2ca3a5994b merge PR #579: dynamic import() extraction for JS/TS
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:52:19 +01:00
SafiandClaude Sonnet 4.6 bfe18f0c83 fix: add context=import to JS/TS named-import edges (caught by PR #573 test)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:50:33 +01:00
SafiandClaude Sonnet 4.6 28047b502f merge PR #573: cross-language edge context filters in MCP query tool
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:49:22 +01:00
SafiandClaude Sonnet 4.6 9881d7ca30 merge PR #557: graphify tree — D3 v7 collapsible-tree HTML view of graph.json
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:48:09 +01:00
24808ef8e6 merge PR #625: token-aware chunking with split-and-retry on truncation
Co-Authored-By: Jason Matthew <jasonm4130@gmail.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 16:46:37 +01:00
Safi 66e61c76b1 docs: add Docker MCP Toolkit + SQLite MCP runbook (#620) 2026-05-02 16:42:08 +01:00
Safi 7237cd3290 feat: add VB.NET (.vb) language support via tree-sitter (#648) 2026-05-02 16:41:55 +01:00
Hanzala Sohrab d04e487877 Merge branch 'safishamsi:v6' into feat/parallel-ast-extraction 2026-05-02 21:11:02 +05:30
Safi 996e82b3d9 test: add regression test for ambiguous cross-file call resolution (#632) 2026-05-02 16:39:53 +01:00
Safi 9ab4f39020 Merge pull request #662 from RubenAAA/fix/ts-named-import-symbol-edges
fix(extract): emit symbol-level edges for TS/JS named imports
2026-05-02 16:37:17 +01:00
Safi 58271fb5af docs: add Pi to pyproject.toml description and keywords 2026-05-02 15:33:17 +01:00
Safi 893219d66f docs: add Pi coding agent to README platform table and install docs 2026-05-02 15:33:17 +01:00
SafiandClaude Sonnet 4.6 763a9359f5 Add Pi coding agent support and tighten wheel packaging
- Add skill-pi.md, graphify pi install/uninstall, --platform pi support (#661)
- Fix pyproject.toml: packages = ["graphify"] + include-package-data = false
  (wheel drops from 1.7MB to 285KB)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 15:33:12 +01:00
RubenAAA 5a342e385c fix(extract): emit symbol-level edges for TS/JS named imports
_import_js only created a file→file imports_from edge, leaving named
imported symbols (classes, error types, constants) as degree-1 orphans
with no connection to their consumers.

Track resolved_path when the import target resolves to a local file
(relative path or tsconfig alias). After emitting the file-level edge,
walk import_clause → named_imports → import_specifier to emit a
file → symbol EXTRACTED edge for each named specifier, using the same
_make_id(target_stem, name) key that _extract_generic uses when defining
the symbol.

On a 1696-file TypeScript monorepo this raised edge count from 8530 to
11267 (+2737 edges) and reduced isolated communities from 878 to 604.
2026-05-02 15:45:02 +02:00
Safi 47ca9228c3 security: add usedforsecurity=False to MD5/SHA1 hashes used for file diffing and filename generation 2026-05-02 14:32:16 +01:00
SafiandClaude Sonnet 4.6 36e894aa62 v0.6.6: Windows skill bash rewrite, wiki fixes, rationale-node fix, hidden allowlist, --no-viz cluster-only
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 14:25:26 +01:00
SafiandClaude Sonnet 4.6 d40e1c0cef Bump version to 0.6.5
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 14:00:32 +01:00
SafiandClaude Sonnet 4.6 e02c7cc60c Fix Codex PreToolUse hook on Windows by delegating to graphify hook-check
The python3 -c "..." approach still failed on Windows Conda (no python3
shim) and PowerShell (JSON curly brace/quote parsing). Replace the inline
command with 'graphify hook-check' — a new shell-agnostic subcommand that
prints the hookSpecificOutput JSON if graph.json exists and exits 0 silently
if not. Works on PowerShell, cmd.exe, macOS, and Linux with no quoting or
interpreter-name issues.

Users must re-run 'graphify codex install' to regenerate the hook.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 13:57:19 +01:00
SafiandClaude Sonnet 4.6 ca48092413 Add --force flag and GRAPHIFY_FORCE env var to graphify update
Bypasses the node-count safety check in to_json for refactors that
legitimately shrink the graph (renames, package deletions). Also
honored by post-commit and post-checkout hooks via GRAPHIFY_FORCE=1.

Implements the approach from #639 (targeted at v5) adapted for v6.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 13:52:09 +01:00
Hanzala Sohrab 8e01d686f7 feat: replace show/hide buttons with checkbox-based multi-select controls (#647) 2026-05-02 13:49:45 +01:00
Michal HarakalandClaude Opus 4.7 71423a1efb Kotlin call-walker: accept both simple_identifier and identifier (#659)
`extract_kotlin` previously emitted zero `calls` edges (and zero
`raw_calls` entries) on the current PyPI grammar. The Kotlin branch
of `walk_calls` only matched node type `simple_identifier`, but
PyPI's `tree_sitter_kotlin` produces `identifier` for the equivalent
plain-identifier node. The `simple_identifier` ↔ `identifier` rename
is a generation gap between tree-sitter-kotlin grammar versions —
older forks (and the JVM `io.github.bonede:tree-sitter-kotlin`
binding) still use `simple_identifier`.

Accept both names so the extractor works across grammar generations.
Also widens `_KOTLIN_CONFIG.name_fallback_child_types` for the same
reason (defensive — currently the `name` field path covers
class/function name resolution, but if that field is dropped in a
future grammar update the fallback would face the same rename).

Tested against `tests/fixtures/sample.kt`: edges go from 6
(file-contains + class-method only) to 10 (adds 4 in-file `calls`
edges resolved by the walker:
  - .get() → .buildRequest() @ L8
  - .post() → .buildRequest() @ L12
  - createClient() → Config @ L21
  - createClient() → HttpClient @ L22).

A new regression test `test_kotlin_emits_in_file_calls` asserts the
four edges so this exact bug can't recur.

Found via graphify-kmp (Kotlin Multiplatform port of graphify) —
its `PythonParityTest` flagged 4 KMP-only edges that Python missed.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 13:49:42 +01:00
SafiandClaude Sonnet 4.6 c3ddace690 Update README git hooks description to reflect detached background rebuild
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 09:37:46 +01:00
SafiandClaude Sonnet 4.6 a61b25ce5f Bump version to 0.6.4
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 09:36:20 +01:00
SafiandClaude Sonnet 4.6 8c9ee1818b Fix Codex PreToolUse hook failing on Windows
Replace bash-only [ -f ] file check with a cross-platform Python one-liner
so the hook works on Windows where cmd.exe has no [ builtin.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 09:35:28 +01:00
SafiandClaude Sonnet 4.6 a4149dffcd Bump version to 0.6.3
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 08:57:57 +01:00
SafiandClaude Sonnet 4.6 028f585356 Fix ambiguous cross-file call resolution inflating god_nodes and guard cluster-only to_html
extract.py: build name -> all candidates map instead of last-write-wins dict.
Skip cross-file INFERRED calls where the callee name resolves to 2+ nodes
(common names like log/execute/find with no import evidence to pick the right
target) — prevents spurious edges from polluting god_nodes degree ranking.

__main__.py: wrap cluster-only to_html in try/except ValueError so large
graphs (>5000 nodes) don't crash the cluster command.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 08:56:20 +01:00
SafiandClaude Sonnet 4.6 c8969edd3c Fix semantic node preservation on incremental rebuild and detach git hooks
watch.py: filter preserved nodes by ID membership in new AST output instead
of file_type — INFERRED/AMBIGUOUS nodes on code files also carry file_type=code
and were being wrongly dropped, triggering the to_json safety check refusal.

hooks.py: detach post-commit and post-checkout rebuilds with nohup + disown
so git commit returns immediately instead of blocking for the full rebuild
duration. Rebuild log written to ~/.cache/graphify-rebuild.log.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 08:53:17 +01:00
Hanzala Sohrab 0fc2dc6ad3 feat: implement parallel AST extraction using ProcessPoolExecutor with benchmarking support 2026-05-02 12:54:08 +05:30
Rangarajan Ramaswamy af15e33f57 feat: add extraction support for VB.NET files 2026-05-02 03:22:58 +03:00
Safi be83a8cc55 bump to v0.6.2 2026-05-01 22:18:18 +01:00
SafiandClaude Sonnet 4.6 3fdae8f334 fix #623 #621 #605 #638 #589 #586 #593: kimi thinking, manifest, inline comments, query boost, cache race, markdownify, content hash
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 22:15:24 +01:00
SafiandClaude Sonnet 4.6 e73b6060b1 fix #590 #628 #629 #630 #619 #617: directed graph, negation patterns, Windows paths, cross-lang noise, shebang, R
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 21:56:17 +01:00
Rangarajan Ramaswamy 5dbbcf7dad feat: add VB.NET (.vb) language support via tree-sitter
This commit adds full VB.NET language support to graphify, raising the
supported language count from 25 to 26. The implementation follows the
established LanguageConfig pattern used by all other tree-sitter-backed
extractors.

New dependency:
- Adds optional extra [vbnet] backed by tree-sitter-vbnet (published
  to PyPI at https://pypi.org/project/tree-sitter-vbnet/0.1.0/).
  Install with: pip install graphifyy[vbnet]

graphify/detect.py:
- Added .vb to CODE_EXTENSIONS so VB.NET files are discovered during
  corpus ingestion and file-system watching.

graphify/extract.py:
- _import_vbnet(): import handler for imports_statement nodes; emits
  imports edges using the namespace_name child text.
- _vbnet_extra_walk(): extra-walk hook that intercepts namespace_block
  nodes, emits a namespace node, and recurses.
- _VBNET_CONFIG: full LanguageConfig covering class_block / module_block /
  structure_block / interface_block as class types; method_declaration /
  constructor_declaration / property_declaration as function types;
  invocation call nodes with target/member_access fields.
- VB.NET-specific branches in _extract_generic:
  * Class body: VB.NET has no wrapper body node; inherits and implements
    are named fields directly on the class_block. Emits separate inherits
    and implements edges for each base type, stripping generic arguments.
  * Constructor name: constructor_declaration carries no name field in
    the grammar; always resolves to New.
  * Function body: uses the declaration node itself as body sentinel so
    the call-graph pass can find invocations inside methods.
- extract_vbnet(path): public wrapper that delegates to _extract_generic.
- _DISPATCH['.vb']: routes .vb files to extract_vbnet.

pyproject.toml:
- Added vbnet = ['tree-sitter-vbnet'] optional dependency group.
- Added 'tree-sitter-vbnet' to the all extra.

tests/fixtures/sample.vb:
- New fixture file exercising: Imports statements, Namespace block,
  Interface, Class with Inherits + Implements, Module, Structure,
  Sub/Function/Property methods, and method calls.

tests/test_languages.py:
- Added 13 tests covering: no-error, class/interface/module/structure
  detection, method detection, imports relation, inherits edge,
  implements edge, and no-dangling-edges invariant.

README.md:
- Updated language count 25 to 26.
- Added VB.NET to language list and file-extension table.
2026-05-01 21:20:36 +03:00
Safi 2dc759a951 bump to v0.6.1 2026-05-01 18:50:12 +01:00
Safi 14fd14a284 combine what+when in skill description 2026-05-01 18:47:40 +01:00
SafiandClaude Sonnet 4.6 7f336acfd9 fix .graphifyignore: correct gitignore semantics + hermetic non-VCS scan + skill auto-invoke
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 18:45:12 +01:00
SafiandClaude Sonnet 4.6 8a6306f769 make .graphifyignore hermetic: stop at VCS root, not project boundaries (closes #643)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 15:28:33 +01:00
Safi 6b68de140c stop .graphifyignore walk at any VCS root or home dir, not just .git (fixes #643) 2026-05-01 14:54:04 +01:00
Safi 17fb524a91 bump to v0.6.0 2026-05-01 10:18:37 +01:00
Safi ad1e11a035 update README: add SQL support to file type table and feature description 2026-05-01 10:16:20 +01:00
SafiandClaude Sonnet 4.6 7d604e8141 v6: SQL AST extractor + xlsx structural extraction utility (fixes #349)
- extract_sql(): deterministic tree-sitter extraction of tables, views,
  functions, foreign key references, and FROM/JOIN reads_from edges
- .sql added to CODE_EXTENSIONS and dispatch table
- tree-sitter-sql added as optional dep under [sql] extra
- xlsx_extract_structure(): extracts sheet/table/column nodes from .xlsx
  (utility — pipeline wiring in follow-up)
- 6 new SQL tests, 447 total passing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 10:15:06 +01:00
Jason Matthew 2d13a17c3b feat(llm): split and retry chunks that hit max_completion_tokens truncation
Token-budget chunking cuts the truncation rate but doesn't eliminate
it. Output token cost scales with extractable concept density rather
than input tokens — a chunk that lands on a directory of dense design
docs can pack under the input budget while needing more than
`max_completion_tokens=8192` to express every named concept, so the
response is truncated mid-string and `_parse_llm_json` returns an
empty fragment.

Pre-tuning chunk size to be conservative enough that this never
happens leaves throughput on the table for the common case. Adding a
hard `max_files_per_chunk` cap on top of `token_budget` reintroduces
the "tune a static constant" problem the previous commit set out to
fix.

The fix uses the API's own truncation signal:

1. `_call_openai_compat` and `_call_claude` now expose `finish_reason`
   on the result dict (Anthropic's `stop_reason == "max_tokens"` is
   normalised to `"length"`).
2. `_extract_with_adaptive_retry` checks it: when truncated, splits
   the chunk in half and recurses on each half. Recursion is bounded
   by `max_retry_depth` (default 3 → at most 8x fanout per top-level
   chunk).
3. Single-file chunks that truncate can't recover and surface a
   warning rather than infinite-loop.
4. `extract_corpus_parallel` routes every chunk through the retry
   wrapper. The `on_chunk_done` callback fires once per top-level
   chunk with the merged result — recursive splits are invisible to
   callers.
2026-04-30 22:08:28 +10:00
Jason Matthew cc5c54574d feat(llm): pack chunks by token budget, parallelise, accept tiktoken
Three independent improvements to extract_corpus_parallel:

1. Token-aware chunking. Replaces `chunk_size=20` static packing with
   a greedy packer keyed on `token_budget` (default 60_000), grouped
   by parent directory so related artefacts share a chunk. Pass
   `token_budget=None` to fall back to fixed-count packing.

2. Optional tiktoken (added to the [kimi] extra). When available,
   `_estimate_file_tokens` uses cl100k_base for accurate counts;
   without it, the existing chars/4 heuristic kicks in. Kimi-K2 ships
   a tiktoken-based tokenizer so estimates against Moonshot are very
   close to truth.

3. True parallelism. The function name said "parallel" but the body
   was a sequential for-loop. Now uses ThreadPoolExecutor capped at
   `max_concurrency` (default 4 — conservative against provider rate
   limits). `on_chunk_done(idx, total, result)` still fires once per
   chunk with the original submission idx so progress UIs work
   unchanged. `max_concurrency=1` skips the pool to preserve
   sequential semantics.

Plus failure tolerance: a chunk raising is now caught, logged to
stderr, and the run continues. Other chunks' results merge as normal.

On a 162-file repo (~125k words), the same work that took ~36 min
sequential under the old code finishes in ~7 min.
2026-04-30 22:08:28 +10:00
chronicgiardiaandOz abb1450b24 docs: add Docker MCP Toolkit + SQLite MCP runbook
Adds docs/docker-mcp-sqlite.md, a reproducible recipe for installing the
SQLite MCP server into Docker MCP Toolkit so any connected MCP client
(Claude Code, Cursor, VS Code, etc.) gains six SQLite tools alongside
graphify's knowledge-graph tools.

Notes the catalog has two SQLite images at time of writing: `mcp/sqlite`
(marked Archived but works) and `mcp/sqlite-mcp-server` (broken
entrypoint). Recommends the working one.

Linked from README.md under a new 'Optional integrations' section.

This is unrelated to the upstream graphify pipeline; it lives as an
optional companion runbook for users who want a lightweight persistent
SQL workspace exposed to their MCP-aware AI clients.

Co-Authored-By: Oz <oz-agent@warp.dev>
2026-04-29 16:50:57 -07:00
Danil Tarasov a9946fb7a0 Merge remote-tracking branch 'upstream/v5' into v5
# Conflicts:
#	graphify/extract.py
2026-04-29 17:55:21 +03:00
Yalkowni 563ee80494 fix(extract): skip dynamic template literals in import() args
import(`./handlers/${name}`) previously produced a garbage edge to a
path containing the unresolved ${name} expression. Now detects
template_substitution child nodes and breaks without emitting an edge.
Static template literals (no interpolation) still resolve correctly.

Adds 2 new tests: one asserting dynamic templates produce no edge,
one asserting static templates resolve like plain strings.
2026-04-27 16:41:19 -07:00
Yalkowni 88e2b832f7 fix: drop Python <3.14 upper bound 2026-04-27 16:27:28 -07:00
Yalkowni a1dc610079 feat(extract): add dynamic import() extraction for JS/TS
Adds _dynamic_import_js() helper (65 lines) that detects import() call
expressions in JS/TS, resolves the module path (same logic as static
imports including .js→.ts mapping and tsconfig aliases), and emits
imports_from edges from the enclosing function. Hooked into walk_calls
for JS/TS configs.

Also adds tests/fixtures/dynamic_import.ts fixture and 5 new tests
in tests/test_languages.py (all passing alongside 110 existing tests).
2026-04-27 16:23:38 -07:00
dsremo a52350940a fix(tree): escape title, header, and JSON blob in emit_html
html.escape() the values that land in <title> and <h1>, and replace </
with <\/ in the JSON embedded inside <script> so crafted graph labels
or --label values cannot break out. Mirrors the _js_safe() pattern in
export.py.

Reported by Qodo on PR #557.
2026-04-27 11:55:21 +05:30
dsremo c3ba79f5aa feat(tree): graphify tree — D3 v7 collapsible-tree HTML emitter
Adds a new `graphify tree` subcommand that emits a self-contained D3
v7 collapsible-tree HTML view of an existing graph.json.

Why
---
The existing `graph.html` (force-directed) is great for finding hubs
and unexpected connections.  But for code review and onboarding, a
hierarchical tree-of-modules view is much faster: you can collapse
everything and expand only the package you care about, the depth-
based colour palette gives instant orientation, and the layout
mirrors the on-disk structure.

UX choices include expand-all / collapse-all / reset-view buttons,
multi-line `wrapText` labels with separately-coloured name and count,
a depth-based palette, click-to-toggle subtrees, and a hover-inspector
that surfaces the top-K outbound edges per symbol.

Implementation
--------------
- `graphify/tree_html.py` (575 LOC, single file, no new runtime
  dependencies).  D3 v7 is loaded from cdn.jsdelivr.net at view time.
- Hierarchy is built from `source_file` longest-common-prefix;
  symbols are grouped by containing module so the tree mirrors the
  on-disk layout exactly.
- Inspector pre-computes top-K outbound edges per symbol so the page
  works fully offline once loaded.
- `__main__.py` adds the subcommand + help text after the
  `check-update` block.

Configuration
-------------
- `--graph PATH`     path to graph.json (default: graphify-out/graph.json)
- `--output HTML`    output path (default: graphify-out/GRAPH_TREE.html)
- `--root PATH`      filesystem root (default: LCP of source_files)
- `--max-children N` cap visible children per node (default: 200)
- `--top-k-edges N`  per-symbol outbound edges in inspector (default: 12)
- `--label NAME`     project label shown in the page header

Tested locally on a 17 641-node graph — emits a 4.9 MB HTML file
that renders smoothly in Firefox / Chromium.
2026-04-26 10:24:36 +05:30
Danil Tarasov 3ff7188fbf feat: add cross-language edge contexts and context-aware queries 2026-04-24 02:59:04 +03:00
96 changed files with 79561 additions and 1600 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 |
+269
View File
@@ -2,6 +2,275 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.7.19 (2026-05-14)
- Feat: `.astro` files now extracted as code — frontmatter static imports, dynamic imports, and `<script>` block imports all produce edges; tsconfig path aliases resolved (#850, PR #852)
- Fix: `.rebuild.lock` no longer accumulates PIDs across rebuilds — now contains a single owning PID while running and is unlinked on release so downstream tooling polling for its absence unblocks promptly (#858, PR #859)
- Docs: skill.md now clarifies that graphify does not read `ANTHROPIC_API_KEY` or other provider keys during `/graphify` skill runs — the host IDE session provides the LLM (PR #864)
## 0.7.18 (2026-05-14)
- Fix: `graphify update` is now idempotent — graph.json and GRAPH_REPORT.md are only rewritten when content actually changes; topology comparison short-circuits clustering entirely on unchanged graphs, eliminating residual community-count drift (#824)
- Fix: community IDs are now stable across rebuilds — Leiden/Louvain receive deterministically sorted input and a fixed random seed; greedy overlap remapper preserves existing IDs so hand-edited `.graphify_labels.json` labels don't drift onto wrong communities (#824)
- Fix: `--no-cluster` flag added to `graphify update` — writes raw AST graph without clustering, consistent with `graphify extract --no-cluster` (#824)
- Fix: `graphify update --no-cluster` now writes `"links"` key matching the schema of the full clustered path; previously wrote `"edges"`, causing schema toggle on every mode switch
- Fix: `.graphify_labels.json` was rewritten on every rebuild even when nothing changed; now only written when outputs actually change
- Fix: shrink-check (refuse overwrite when new graph has fewer nodes) was duplicated across two code paths; unified into a single `_check_shrink()` helper
- Fix: node ID format in skill.md corrected to `{parent_dir}_{filename_stem}_{entity}` — the old filename-only format caused ghost-duplicate nodes when AST and semantic extractors disagreed on the stem; top-level files use just the filename stem; existing graphs with ghost duplicates can be cleaned up with `graphify extract --force`
- Fix: safer JSON serialization in clustering sort keys (`default=str`) prevents crashes when edge attributes contain non-serializable values
- Docs: added Prerequisites, optional extras table, environment variables reference, troubleshooting, and dev setup to README (#833)
## 0.7.17 (2026-05-13)
- Fix: `graphify path` and `graphify explain` now render arrow direction correctly — `-->` for caller→callee, `<--` for callee←caller; previously the graph was loaded undirected so every hop printed `-->` regardless of stored direction (#849, #853)
- Fix: MCP `shortest_path` and `get_neighbors` tools had the same reversed-arrow bug; now fixed in `serve.py` alongside the CLI commands (#849, #853)
- Fix: `graphify extract --backend bedrock` was rejected by the CLI guard even when `AWS_PROFILE`/`AWS_REGION`/`AWS_DEFAULT_REGION`/`AWS_ACCESS_KEY_ID` were set — boto3 session auth was never reached (#846)
- Fix: BFS/DFS query traversal now skips expanding high-degree hub nodes (threshold: `max(50, p99_degree)`) as transit — hubs can still be destinations but no longer produce semantically meaningless 2-hop paths like `ClassA → View → ClassB` in Android/Spring corpora (#830)
- Fix: `--update` manifest shrink — after an incremental run, `manifest.json` was overwritten with only the changed-file subset, causing the next `--update` to re-flag the entire unchanged corpus as new; Step 9 now persists the full corpus via `all_files` fallback (#837)
- Fix: `file_type` enum aligned across `skill.md` and `llm.py` (both now enumerate all six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`); synonym mapper in `build.py` silently coerces known LLM-emitted synonyms (`pattern→concept`, `markdown→document`, `tool→code`, etc.) before validation (#840)
- Fix: Fortran test fixture renamed `sample.F90` → `sample_preprocessed.F90` to avoid case-collision with `sample.f90` on macOS case-insensitive filesystems (credit: @FatahChan, #823)
## 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)
- Fix: two-phase cohesion re-clustering — communities with cohesion < 0.05 and ≥ 50 nodes are re-split, preventing doc-hub nodes (e.g. `CLAUDE.md`) from merging unrelated subsystems into one giant community (#683)
- Fix: VS Code Copilot instructions rewritten to be prescriptive — agent's first tool call must read `GRAPH_REPORT.md`, explicit trigger list, narrow allowlist for raw source reads (#688)
- Feat: `GRAPHIFY_OUT` env var overrides the output directory — accepts a relative name or absolute path, wires through `cache.py`, `watch.py`, and the CLI; useful for sharing one graph across multiple git worktrees (#686)
- Fix: `graphify antigravity install` now auto-updates stale rules and workflow files on re-run instead of silently skipping them (#652)
- Docs: README simplified — less dense, plain language; technical pipeline details moved to `docs/how-it-works.md`
## 0.6.8 (2026-05-03)
- Fix: `.graphifyignore` negation patterns (`!src/**`) now work correctly — when any `!` pattern is present, directory pruning is deferred to per-file checks so negated files inside ignored directories are reached (#676)
- Fix: Antigravity slash command `/graphify` now appears in the command dropdown — workflow file now includes YAML frontmatter with `name: graphify` required for Antigravity discovery (#678)
- Fix: Gemini CLI BeforeTool hook replaced `[ -f ... ] && echo` (bash-only) with cross-platform `python -c` using `json.dumps` — fixes hook failure on Windows CMD and Git Bash (#681)
- Fix: Codex hook-check exits silently — resolves `additionalContext` rejection on Codex Desktop PreToolUse (#651)
- Fix: `graphify install --platform codex` now writes absolute path to `graphify` executable — fixes PATH resolution in VS Code extension on Windows (#651)
- Fix: thin communities (fewer than 3 concept nodes) are now omitted from the Communities section in `GRAPH_REPORT.md` by default; report header shows `(N total, M thin omitted)` and Knowledge Gaps collapses thin communities to one summary line (#664)
## 0.6.7 (2026-05-02)
- Feat: `graphify tree` — self-contained D3 v7 collapsible-tree HTML view of `graph.json`; expand/collapse controls, depth-based colours, hover inspector; XSS-safe (#557)
- Feat: token-aware chunking with split-and-retry on truncation (#625)
- Feat: cross-language edge context filters in MCP `query_graph` tool (#573)
- Feat: dynamic `import()` extraction for JS/TS (#579)
- Fix: `save_semantic_cache` crashed with `IsADirectoryError` when a node's `source_file` was a directory path — `p.exists()` → `p.is_file()` (#655)
- Fix: `sanitize_label(None)` raised `TypeError` crashing `to_html` on graphs with null `source_file` rationale nodes — return `""` early (#656)
- Fix: chunk-extraction prompt omitted `rationale` from valid `file_type` values — model hallucinated `concept` on every doc/paper run; explicit merge step added to all skill variants (#657)
- Fix: `cost.json` always reported 0 tokens — chunk JSONs have placeholder zeros; orchestrator now globs and sums real token counts before merging (#658)
## 0.6.6 (2026-05-02)
- Fix: `skill-windows.md` rewritten from PowerShell to bash — Claude Code on Windows uses git-bash so PowerShell syntax (`$null`, `$LASTEXITCODE`, `Select-Object`, `& (Get-Content ...)`, `Remove-Item`) caused exit code 49 failures; now mirrors `skill.md` structure with `python` added as fallback after `python3` for Windows Conda (#39)
- Fix: wiki `to_wiki()` now clears stale articles before regenerating, preventing orphan .md accumulation (#558)
- Fix: `_safe_filename()` in wiki.py now strips Windows-reserved characters (`< > : " / \ | ? *`) and caps length at 200 chars (#594)
- Fix: rationale-node leakage in cross-file INFERRED call resolution — rationale nodes now excluded from name lookup; edge direction (`calls`, `rationale_for`) preserved correctly at JSON export (#576)
- Feat: `.graphifyinclude` hidden path allowlist — opt specific hidden dirs into traversal (e.g. `.hermes/plans/**/*.md`) (#583)
- Feat: `--no-viz` flag wired in `cluster-only`; `GRAPHIFY_VIZ_NODE_LIMIT` env var overrides 5000-node HTML threshold (#565)
- Fix: stray colon SyntaxError in `skill-trae.md` `--cluster-only` block (#603)
- Docs: skill INFERRED confidence score guidance changed to discrete rubric (0.55/0.65/0.75/0.85/0.95) backed by calibration data (#546)
- Docs: skill `--update` prune output clarified — splits no-drift vs drift cases (#544)
- Docs: skill `--update` merge step now calls `save_manifest` to prevent deleted files reappearing (#545)
- Feat: `graphify tree` — self-contained D3 v7 collapsible-tree HTML view of `graph.json`; expand/collapse controls, depth-based colours, hover inspector; XSS-safe via `html.escape()` and `_js_safe()` (#557)
## 0.6.5 (2026-05-02)
- Fix: Kotlin call-walker now accepts both `simple_identifier` and `identifier` node types — PyPI's `tree_sitter_kotlin` grammar uses `identifier` while older forks use `simple_identifier`, causing zero `calls` edges to be emitted (#659)
- Feat: community sidebar now uses checkbox-based multi-select instead of show/hide buttons — supports indeterminate "select all" state (#647)
- Feat: `graphify update --force` and `GRAPHIFY_FORCE=1` env var — bypass the node-count safety check after refactors that legitimately shrink the graph (#639)
- Fix: Codex PreToolUse hook on Windows — replaced `python3 -c "..."` inline command (fails on Conda where only `python` exists, and breaks PowerShell JSON parsing) with `graphify hook-check`, a new shell-agnostic subcommand. Re-run `graphify codex install` to regenerate the hook (#651, #522)
## 0.6.4 (2026-05-02)
- Fix: Codex PreToolUse hook failed on Windows — `[ -f ]` is bash-only and crashes on `cmd.exe`; replaced with a cross-platform Python one-liner (`pathlib.Path.exists()`) (#651)
## 0.6.3 (2026-05-02)
- Fix: incremental rebuild (`graphify update`, post-commit hook) dropped INFERRED/AMBIGUOUS semantic nodes extracted from code files — node preservation now filters by ID membership in the new AST output instead of `file_type`, so LLM-extracted call/data-flow edges survive code-only rebuilds (#653)
- Fix: post-commit and post-checkout hooks blocked `git commit` for the full rebuild duration (hours on large repos) — rebuilds now detach via `nohup & disown`, git returns in ~100ms, log written to `~/.cache/graphify-rebuild.log` (#650)
- Fix: cross-file INFERRED `calls` resolution used a last-write-wins name map, causing common short names (`log`, `execute`, `find`) to accumulate hundreds of spurious edges and dominate god_nodes ranking — resolution now skips any callee name that matches 2+ candidates (ambiguous, no import evidence to pick the right target) (#543)
- Fix: `cluster-only` command crashed on graphs with >5000 nodes due to unguarded `to_html` call — now wrapped in try/except ValueError matching the watch/hook path (#541)
## 0.6.2 (2026-05-01)
- Fix: Kimi K2.6 reasoning mode consumed entire token budget leaving `content` empty — thinking now disabled on Moonshot calls so graphs actually populate (#623)
- Fix: `graphify update` / `graphify watch` never persisted the manifest, so every subsequent `--update` re-extracted all files — manifest now saved after each rebuild (#621)
- Fix: inline comments in `.graphifyignore` (e.g. `vendor/ # legacy`) now stripped correctly — whitespace + `#` suffix is treated as a comment, `path#hash.py` preserved (#605)
- Fix: `graphify query "FunctionName"` now returns the exact matching node first instead of high-degree hub modules hijacking the output — 100-point exact-match bonus + seeds render before BFS expansion (#638)
- Fix: concurrent AST extractors raced on a shared `.tmp` cache file — each writer now gets a unique tempfile via `mkstemp`, eliminating cache corruption under parallel extraction (#589)
- Fix: `_clone_repo` branch names starting with `-` could be interpreted as git flags — validation added, `--` separator inserted before positional args (#589)
- Fix: replaced `html2text` (GPL-3.0) with `markdownify` (MIT) — removes the only copyleft dependency from a MIT project (#586)
- Fix: `--update` re-extracted files whose mtime was bumped by sync tools (Obsidian, Nextcloud) without content changes — manifest now stores content hash alongside mtime; mtime bump triggers an MD5 check before re-extraction (#593)
- Feat: R language support — `.r` files classified as code and processed via LLM semantic extraction (#617)
- Feat: extensionless shell scripts now detected via shebang (`#!/bin/bash`, `#!/usr/bin/env python3`, etc.) and included as code (#619)
- Fix: cross-language INFERRED `calls` edges (e.g. Python→TypeScript name collision) no longer appear as top surprising connections in GRAPH_REPORT.md (#630)
- Fix: `cluster-only` CLI silently flipped directed graphs to undirected — `directed` flag now read from graph.json and preserved through re-clustering (#590)
- Fix: Windows UNC / extended-length paths (`\\?\C:\...`) now normalize to consistent cache keys (#629)
- Fix: `.graphifyignore` negation patterns (`!src/lib/secrets.ts`) now work — full last-match-wins evaluation with `!` un-ignore support (#628)
## 0.6.1 (2026-05-01)
- Fix: `.graphifyignore` discovery now uses correct gitignore semantics — outer rules are loaded first so inner (closer) rules always win via last-match-wins, matching standard gitignore behavior (#643)
- Fix: without a VCS root, `.graphifyignore` discovery is now hermetic to the scan folder — no leakage across sibling projects in a shared workspace (#643)
- Fix: anchored patterns (leading `/`) in a parent `.graphifyignore` now correctly apply only relative to their own directory, not the scan root (#643)
- Fix: trailing spaces in patterns are now handled per gitignore spec — unescaped trailing spaces are stripped, `vendor\ ` (escaped) is preserved (#643)
## 0.6.0 (2026-05-01)
- Feat: SQL AST extractor — `.sql` files now processed deterministically via tree-sitter. Extracts tables, views, functions/procedures, foreign key references, and FROM/JOIN reads_from edges. No LLM needed. Requires `pip install 'graphifyy[sql]'` (#349)
- Feat: `xlsx_extract_structure()` utility — extracts sheet names, named tables, and column headers from .xlsx files as structural nodes
## 0.5.7 (2026-04-30)
- Feat: YAML/YML files now indexed for semantic extraction — Kubernetes, Kustomize, Helm, and any YAML corpus now picked up automatically (#633)
+390 -294
View File
@@ -8,80 +8,105 @@
<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>
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, or Google Antigravity - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
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.
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. YAML/YML files (Kubernetes, Kustomize, Helm, config) are indexed for semantic extraction. 25 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia, Verilog, SystemVerilog, Vue, Svelte, Dart).
> Andrej Karpathy keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. graphify is the answer to that problem - 71.5x fewer tokens per query vs reading the raw files, persistent across sessions, honest about what it found vs guessed.
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 . # works on any folder - your codebase, notes, papers, anything
/graphify .
```
That's it. You get three files:
```
graphify-out/
├── graph.html interactive graph - open in any browser, click nodes, search, filter by community
├── GRAPH_REPORT.md god nodes, surprising connections, suggested questions
├── graph.json persistent graph - query weeks later without re-reading
└── cache/ SHA256 cache - re-runs only process changed files
├── graph.html open in any browser — click nodes, filter, search
├── GRAPH_REPORT.md the highlights: key concepts, surprising connections, suggested questions
└── graph.json the full graph — query it anytime without re-reading your files
```
Add a `.graphifyignore` file to exclude folders you don't want in the graph:
For a readable architecture page with Mermaid call-flow diagrams, run:
```
# .graphifyignore
vendor/
node_modules/
dist/
*.generated.py
```bash
graphify export callflow-html
```
Same syntax as `.gitignore`. You can keep a single `.graphifyignore` at your repo root — patterns work correctly even when graphify is run on a subfolder.
---
## How it works
## Prerequisites
graphify runs in three passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, video and audio files are transcribed locally with faster-whisper using a domain-aware prompt derived from corpus god nodes — transcripts are cached so re-runs are instant. Third, Claude subagents run in parallel over docs, papers, images, and transcripts to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
| Requirement | Minimum | Check | Install |
|---|---|---|---|
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
| uv *(recommended)* | any | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| pipx *(alternative)* | any | `pipx --version` | `pip install pipx` |
**Clustering is graph-topology-based — no embeddings.** Leiden finds communities by edge density. The semantic similarity edges that Claude extracts (`semantically_similar_to`, marked INFERRED) are already in the graph, so they influence community detection directly. The graph structure is the similarity signal — no separate embedding step or vector database needed.
**macOS quick install (Homebrew):**
```bash
brew install python@3.12 uv
```
Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED` (reasonable inference, with a confidence score), or `AMBIGUOUS` (flagged for review). You always know what was found vs guessed.
**Windows quick install:**
```powershell
winget install astral-sh.uv
```
**Ubuntu/Debian:**
```bash
sudo apt install python3.12 python3-pip pipx
# or install uv:
curl -LsSf https://astral.sh/uv/install.sh | sh
```
---
## Install
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [VS Code Copilot Chat](https://code.visualstudio.com/docs/copilot/overview), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), [Trae](https://trae.ai), [Kiro](https://kiro.dev), Hermes, or [Google Antigravity](https://antigravity.google)
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
**Step 1 — install the package:**
```bash
# Recommended — works on Mac and Linux with no PATH setup needed
uv tool install graphifyy && graphify install
# or with pipx
pipx install graphifyy && graphify install
# or plain pip
pip install graphifyy && graphify install
# Recommended (uv puts graphify on PATH automatically):
uv tool install graphifyy
# Alternatives:
pipx install graphifyy
pip install graphifyy
```
> **Official package:** The PyPI package is named `graphifyy` (install with `pip install graphifyy`). Other packages named `graphify*` on PyPI are not affiliated with this project. The only official repository is [safishamsi/graphify](https://github.com/safishamsi/graphify). The CLI and skill command are still `graphify`.
**Step 2 — register the skill with your AI assistant:**
> **`graphify: command not found`?** Use `uv tool install graphifyy` (recommended) or `pipx install graphifyy` — both put the CLI in a managed location that's automatically on PATH. With plain `pip`, you may need to add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify` instead. On Windows, pip scripts land in `%APPDATA%\Python\PythonXY\Scripts`.
```bash
graphify install
```
### Platform support
That's it. Open your AI assistant and type `/graphify .`
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell.
> **`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
| Platform | Install command |
|----------|----------------|
| Claude Code (Linux/Mac) | `graphify install` |
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
| Claude Code (Windows) | `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
@@ -93,23 +118,41 @@ pip 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` |
| Google Antigravity | `graphify antigravity install` |
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
> Codex users: also add `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
> Codex uses `$graphify` instead of `/graphify`.
Then open your AI coding assistant and type:
### Optional extras
```
/graphify .
```
Install only what you need:
Note: Codex uses `$` instead of `/` for skill calling, so type `$graphify .` instead.
| Extra | What it adds | Install |
|---|---|---|
| `pdf` | PDF extraction | `pip install "graphifyy[pdf]"` |
| `office` | `.docx` and `.xlsx` support | `pip install "graphifyy[office]"` |
| `google` | Google Sheets rendering | `pip install "graphifyy[google]"` |
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `pip install "graphifyy[video]"` |
| `mcp` | MCP stdio server | `pip install "graphifyy[mcp]"` |
| `neo4j` | Neo4j push support | `pip install "graphifyy[neo4j]"` |
| `svg` | SVG graph export | `pip install "graphifyy[svg]"` |
| `leiden` | Leiden community detection (Python < 3.13 only) | `pip install "graphifyy[leiden]"` |
| `ollama` | Ollama local inference | `pip install "graphifyy[ollama]"` |
| `openai` | OpenAI / OpenAI-compatible APIs | `pip install "graphifyy[openai]"` |
| `gemini` | Google Gemini API | `pip install "graphifyy[gemini]"` |
| `bedrock` | AWS Bedrock (uses IAM, no API key) | `pip install "graphifyy[bedrock]"` |
| `sql` | SQL schema extraction | `pip install "graphifyy[sql]"` |
| `all` | Everything above | `pip install "graphifyy[all]"` |
### Make your assistant always use the graph (recommended)
---
After building a graph, run this once in your project:
## Make your assistant always use the graph
Run this once in your project after building a graph:
| Platform | Command |
|----------|---------|
@@ -126,336 +169,389 @@ After building a graph, run this once in your project:
| 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` |
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
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.
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
To remove graphify from all platforms at once: `graphify uninstall` (add `--purge` to also delete `graphify-out/`). Or use the per-platform command (e.g. `graphify claude uninstall`).
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
---
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
## What's in the report
**Gemini CLI** copies the skill to `~/.gemini/skills/graphify/SKILL.md`, writes a `GEMINI.md` section, and installs a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls — same always-on mechanism as Claude Code.
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
- **Surprising connections** — links between things that live in different files or modules. Ranked by how unexpected they are.
- **The "why"** — inline comments (`# NOTE:`, `# WHY:`, `# HACK:`), docstrings, and design rationale from docs are extracted as separate nodes linked to the code they explain.
- **Suggested questions** — 4–5 questions the graph is uniquely positioned to answer.
- **Confidence tags** — every inferred relationship is marked `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`. You always know what was found vs guessed.
**Aider, OpenClaw, Factory Droid, Trae, and Hermes** write the same rules to `AGENTS.md` in your project root and copy the skill to the platform's global skill directory. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
---
**Kiro IDE/CLI** writes the skill to `.kiro/skills/graphify/SKILL.md` (invoked via `/graphify`) and a steering file to `.kiro/steering/graphify.md` with `inclusion: always` — Kiro injects this into every conversation automatically, no hook needed.
## What files it handles
**Google Antigravity** writes `.agents/rules/graphify.md` (always-on rules) and `.agents/workflows/graphify.md` (registers `/graphify` as a slash command). No hook equivalent exists in Antigravity — rules are the always-on mechanism.
| Type | Extensions |
|------|-----------|
| Code (29 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk` |
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
| Office | `.docx .xlsx` (requires `pip install graphifyy[office]`) |
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `pip install graphifyy[google]`) |
| PDFs | `.pdf` |
| Images | `.png .jpg .webp .gif` |
| Video / Audio | `.mp4 .mov .mp3 .wav` and more (requires `pip install graphifyy[video]`) |
| YouTube / URLs | any video URL (requires `pip install graphifyy[video]`) |
**GitHub Copilot CLI** copies the skill to `~/.copilot/skills/graphify/SKILL.md`. Run `graphify copilot install` to set it up.
Code is extracted locally with no API calls (AST via tree-sitter). Everything else goes through your AI assistant's model API.
**VS Code Copilot Chat** installs a Python-only skill (works on Windows PowerShell and macOS/Linux alike) and writes `.github/copilot-instructions.md` in your project root — VS Code reads this automatically every session, making graph context always-on without any hook mechanism. Run `graphify vscode install`. Note: this configures the chat panel in VS Code, not the Copilot CLI terminal tool.
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:
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
```bash
pip install "graphifyy[google]" # needed for Google Sheets table rendering
gws auth login -s drive
graphify extract ./docs --google-workspace
```
**Always-on vs explicit trigger — what's the difference?**
You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into
`graphify-out/converted/` as Markdown sidecars, then extracts those files.
The always-on hook surfaces `GRAPH_REPORT.md` — a one-page summary of god nodes, communities, and surprising connections. Your assistant reads this before searching files, so it navigates by structure instead of keyword matching. That covers most everyday questions.
---
`/graphify query`, `/graphify path`, and `/graphify explain` go deeper: they traverse the raw `graph.json` hop by hop, trace exact paths between nodes, and surface edge-level detail (relation type, confidence score, source location). Use them when you want a specific question answered from the graph rather than a general orientation.
## Common commands
Think of it this way: the always-on hook gives your assistant a map. The `/graphify` commands let it navigate the map precisely.
```bash
/graphify . # build graph for current folder
/graphify ./docs --update # re-extract only changed files
/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/
### Team workflows
/graphify query "what connects auth to the database?"
/graphify path "UserService" "DatabasePool"
/graphify explain "RateLimiter"
`graphify-out/` is designed to be committed to git so every teammate starts with a fresh map.
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper and add it
/graphify add <youtube-url> # transcribe and add a video
graphify hook install # auto-rebuild on git commit
graphify merge-graphs a.json b.json # combine two graphs
```
See the [full command reference](#full-command-reference) below.
---
## Ignoring files
Create a `.graphifyignore` in your project root — same syntax as `.gitignore`, including `!` negation:
```
# .graphifyignore
node_modules/
dist/
*.generated.py
# only index src/, ignore everything else
*
!src/
!src/**
```
---
## Team setup
`graphify-out/` is meant to be committed to git so everyone on the team starts with a map.
**Recommended `.gitignore` additions:**
```
# keep graph outputs, skip heavy/local-only files
# optional: commit for shared extraction speed, skip to keep repo small
graphify-out/cache/
# mtime-based, invalid after git clone - always gitignore this
graphify-out/manifest.json
# local token tracking, not useful to share
graphify-out/cost.json
graphify-out/manifest.json # mtime-based, breaks after git clone
graphify-out/cost.json # local only
# graphify-out/cache/ # optional: commit for speed, skip to keep repo small
```
**Shared setup:**
1. One person runs `/graphify .` to build the initial graph and commits `graphify-out/`.
2. Everyone else pulls — their assistant reads `GRAPH_REPORT.md` immediately with no extra steps.
3. Install the post-commit hook (`graphify hook install`) so the graph rebuilds automatically after code changes — no LLM calls needed for code-only updates.
4. For doc/paper changes, whoever edits the files runs `/graphify --update` to refresh semantic nodes.
**Workflow:**
1. One person runs `/graphify .` and commits `graphify-out/`.
2. Everyone pulls — their assistant reads the graph immediately.
3. Run `graphify hook install` to auto-rebuild after each commit (AST only, no API cost). This also sets up a git merge driver so `graph.json` is never left with conflict markers — two devs committing in parallel get their graphs union-merged automatically.
4. When docs or papers change, run `/graphify --update` to refresh those nodes.
**Excluding paths** — create `.graphifyignore` in your project root (same syntax as `.gitignore`). Files matching those patterns are skipped during detection and extraction.
---
```
# .graphifyignore example
AGENTS.md # graphify install files — don't extract your own instructions as knowledge
CLAUDE.md
GEMINI.md
.gemini/
.opencode/
docs/translations/ # generated content you don't want in the graph
```
## Using `graph.json` with an LLM
`graph.json` is not meant to be pasted into a prompt all at once. The useful
workflow is:
1. Start with `graphify-out/GRAPH_REPORT.md` for the high-level overview.
2. Use `graphify query` to pull a smaller subgraph for the specific question
you want to answer.
3. Give that focused output to your assistant instead of dumping the full raw
corpus.
For example, after running graphify on a project:
## Using the graph directly
```bash
graphify query "show the auth flow" --graph graphify-out/graph.json
# query the graph from the terminal
graphify query "show the auth flow"
graphify query "what connects DigestAuth to Response?" --graph graphify-out/graph.json
```
The output includes node labels, edge types, confidence tags, source files, and
source locations. That makes it a good intermediate context block for an LLM:
```text
Use this graph query output to answer the question. Prefer the graph structure
over guessing, and cite the source files when possible.
```
If your assistant supports tool calling or MCP, use the graph directly instead
of pasting text. graphify can expose `graph.json` as an MCP server:
```bash
# 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
```
That gives the assistant structured graph access for repeated queries such as
`query_graph`, `get_node`, `get_neighbors`, and `shortest_path`.
The MCP server gives your assistant structured access: `query_graph`, `get_node`, `get_neighbors`, `shortest_path`.
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Install into a project venv to avoid PEP 668 conflicts, and use the full venv path in your `.mcp.json`:
> **WSL / Linux note:** Ubuntu ships `python3`, not `python`. Use a venv to avoid conflicts:
> ```bash
> python3 -m venv .venv && .venv/bin/pip install "graphifyy[mcp]"
> ```
> ```json
> { "mcpServers": { "graphify": { "type": "stdio", "command": ".venv/bin/python3", "args": ["-m", "graphify.serve", "graphify-out/graph.json"] } } }
> ```
> Also note: the PyPI package is `graphifyy` (double-y) — `pip install graphify` installs an unrelated package.
<details>
<summary>Manual install (curl)</summary>
---
## Environment variables
These are only needed for **headless / CI extraction** (`graphify extract`). When running via the `/graphify` skill inside your IDE, the model API is provided by your IDE session — no extra keys needed.
| Variable | Used for | When required |
|---|---|---|
| `ANTHROPIC_API_KEY` | Claude (Anthropic) backend | `--backend claude` |
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Google Gemini backend | `--backend gemini` |
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` |
| `MOONSHOT_API_KEY` | Kimi Code backend | `--backend kimi` |
| `OLLAMA_BASE_URL` | Ollama local inference URL | `--backend ollama` (default: `http://localhost:11434`) |
| `OLLAMA_MODEL` | Ollama model name | `--backend ollama` (default: auto-detect) |
| `GRAPHIFY_OLLAMA_NUM_CTX` | Override Ollama KV-cache window size | optional — auto-sized by default |
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | Minutes to keep Ollama model loaded | optional — set `0` to unload after each chunk |
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — standard credential chain | `--backend bedrock` (no API key, uses IAM) |
| `GRAPHIFY_MAX_WORKERS` | AST parallelism thread count | optional — also `--max-workers` flag |
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Raise output cap for dense corpora | optional — e.g. `32768` for large files |
| `GRAPHIFY_API_TIMEOUT` | HTTP timeout in seconds (default: 600) | optional — also `--api-timeout` flag |
| `GRAPHIFY_FORCE` | Force graph rebuild even with fewer nodes | optional — also `--force` flag |
| `GRAPHIFY_GOOGLE_WORKSPACE` | Auto-enable Google Workspace export | optional — set to `1` |
---
## Privacy
- **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 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`), AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM), or the `claude` CLI binary (Claude Code - no API key needed, uses your Claude subscription). The `--dedup-llm` flag uses the same key.
- No telemetry, no usage tracking, no analytics.
---
## Troubleshooting
**`graphify: command not found` after `pip install graphifyy`**
pip installs scripts to a user bin directory that may not be on your PATH. Fix:
- macOS: add `~/Library/Python/3.x/bin` to your PATH in `~/.zshrc`
- Linux: add `~/.local/bin` to your PATH in `~/.bashrc`
- Or use `uv tool install graphifyy` / `pipx install graphifyy` — both manage PATH automatically.
**`python -m graphify` works but `graphify` command doesn't**
Your shell's PATH doesn't include the Python scripts directory. Use `uv` or `pipx` instead of plain `pip`.
**`/graphify .` causes "path not recognized" in PowerShell**
PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash) on Windows.
**Graph has fewer nodes after `--update` or rebuild**
If a refactor deleted files, the old nodes linger. Pass `--force` (or set `GRAPHIFY_FORCE=1`) to overwrite even when the rebuild has fewer nodes.
**Graph has duplicate nodes for the same entity (ghost duplicates)**
This happens when semantic and AST extraction disagreed on the node ID format. Run a full re-extract to clean up:
```bash
mkdir -p ~/.claude/skills/graphify
curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v4/graphify/skill.md \
> ~/.claude/skills/graphify/SKILL.md
graphify extract . --force
```
Add to `~/.claude/CLAUDE.md`:
```
- **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"` before doing anything else.
**Ollama runs out of VRAM / context window exceeded**
The KV-cache window is auto-sized but may be too large for your GPU. Reduce it:
```bash
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
```
</details>
**Graph HTML is too large to open in a browser (>5000 nodes)**
Skip HTML generation and use the JSON directly:
```bash
graphify cluster-only ./my-project --no-viz
graphify query "..."
```
## Usage
**`graph.json` has conflict markers after two devs commit at once**
Run `graphify hook install` — it sets up a git merge driver that union-merges `graph.json` automatically so conflicts never happen.
**Extraction returns empty nodes/edges for docs or PDFs**
Docs and PDFs require an LLM call. Check that your API key is set and the backend is correct:
```bash
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
```
**Skill version mismatch warning in your IDE**
Your installed graphify version is different from the skill file. Update:
```bash
uv tool upgrade graphifyy
graphify install # overwrites the skill file
```
---
## Full command reference
```
/graphify # run on current directory
/graphify ./raw # run on a specific folder
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
/graphify ./raw --update # re-extract only changed files, merge into existing graph
/graphify ./raw --directed # build directed graph (preserves edge direction: source→target)
/graphify ./raw --cluster-only # rerun clustering on existing graph, no re-extraction
/graphify ./raw --no-viz # skip HTML, just produce report + JSON
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
/graphify ./raw --obsidian --obsidian-dir ~/vaults/myproject # write vault to a specific directory
/graphify ./raw --mode deep # more aggressive relationship extraction
/graphify ./raw --update # re-extract only changed files
/graphify ./raw --directed # preserve edge direction
/graphify ./raw --cluster-only # rerun clustering on existing graph
/graphify ./raw --no-viz # skip HTML visualization
/graphify ./raw --obsidian # generate Obsidian vault
/graphify ./raw --wiki # build agent-crawlable markdown wiki
/graphify ./raw --svg # export graph.svg
/graphify ./raw --graphml # export for Gephi / yEd
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687
/graphify ./raw --watch # auto-sync as files change
/graphify ./raw --mcp # start MCP stdio server
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
/graphify add https://x.com/karpathy/status/... # fetch a tweet
/graphify add <video-url> # download audio, transcribe, add to graph
/graphify add https://... --author "Name" # tag the original author
/graphify add https://... --contributor "Name" # tag who added it to the corpus
/graphify add https://arxiv.org/abs/1706.03762
/graphify add <video-url>
/graphify add https://... --author "Name" --contributor "Name"
/graphify query "what connects attention to the optimizer?"
/graphify query "what connects attention to the optimizer?" --dfs # trace a specific path
/graphify query "what connects attention to the optimizer?" --budget 1500 # cap at N tokens
/graphify query "..." --dfs --budget 1500
/graphify path "DigestAuth" "Response"
/graphify explain "SwinTransformer"
/graphify ./raw --watch # auto-sync graph as files change (code: instant, docs: notifies you)
/graphify ./raw --wiki # build agent-crawlable wiki (index.md + article per community)
/graphify ./raw --svg # export graph.svg
/graphify ./raw --graphml # export graph.graphml (Gephi, yEd)
/graphify ./raw --neo4j # generate cypher.txt for Neo4j
/graphify ./raw --neo4j-push bolt://localhost:7687 # push directly to a running Neo4j instance
/graphify ./raw --mcp # start MCP stdio server
graphify uninstall # remove from all platforms in one shot
graphify uninstall --purge # also delete graphify-out/
# git hooks - platform-agnostic, rebuild graph on commit and branch switch
graphify hook install
graphify hook install # post-commit + post-checkout hooks
graphify hook uninstall
graphify hook status
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify cursor uninstall
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
graphify gemini uninstall
graphify copilot install # skill file (GitHub Copilot CLI)
graphify copilot uninstall
graphify aider install # AGENTS.md (Aider)
graphify aider uninstall
graphify claw install # AGENTS.md (OpenClaw)
graphify droid install # AGENTS.md (Factory Droid)
graphify trae install # AGENTS.md (Trae)
graphify trae uninstall
graphify trae-cn install # AGENTS.md (Trae CN)
graphify trae-cn uninstall
graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
graphify hermes uninstall
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
graphify kiro uninstall
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
graphify antigravity uninstall
graphify claude install / uninstall
graphify codex install / uninstall
graphify opencode install
graphify cursor install / uninstall
graphify gemini install / uninstall
graphify copilot install / uninstall
graphify aider install / uninstall
graphify claw install / uninstall
graphify droid install / uninstall
graphify trae install / uninstall
graphify trae-cn install / uninstall
graphify hermes install / uninstall
graphify kiro install / uninstall
graphify antigravity install / uninstall
# query and navigate the graph directly from the terminal (no AI assistant needed)
graphify query "what connects attention to the optimizer?"
graphify query "show the auth flow" --dfs
graphify query "what is CfgNode?" --budget 500
graphify query "..." --graph path/to/graph.json
graphify path "DigestAuth" "Response" # shortest path between two nodes
graphify explain "SwinTransformer" # plain-language explanation of a node
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, ollama, bedrock, or claude-cli
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL) - no API key needed for loopback
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 --backend claude-cli # route through Claude Code CLI - no API key, uses your Claude subscription
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 --force # overwrite graph.json even if new graph has fewer nodes (use after refactors or to clear ghost duplicates)
graphify extract ./docs --dedup-llm # LLM tiebreaker for ambiguous entity pairs (uses same API key)
graphify extract ./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
# add content and update the graph from the terminal
graphify add https://arxiv.org/abs/1706.03762 # fetch paper, save to ./raw, update graph
graphify add https://... --author "Name" --contributor "Name"
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
# clone any GitHub repo and run the full pipeline on it
graphify clone https://github.com/karpathy/nanoGPT # clones to ~/.graphify/repos/karpathy/nanoGPT
graphify clone https://github.com/org/repo --branch dev --out ./my-clone
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
# cross-repo graphs — merge two or more graph.json outputs into one
graphify merge-graphs repo1/graphify-out/graph.json repo2/graphify-out/graph.json
graphify merge-graphs g1.json g2.json g3.json --out cross-repo.json
# incremental update and maintenance
graphify watch ./src # auto-rebuild on code changes
graphify check-update ./src # check if semantic re-extraction is pending (cron-safe)
graphify update ./src # re-extract code files, no LLM needed
graphify cluster-only ./my-project # rerun clustering on existing graph.json
graphify clone https://github.com/karpathy/nanoGPT
graphify merge-graphs a.json b.json --out merged.json
graphify --version # print installed version
graphify watch ./src
graphify check-update ./src
graphify update ./src
graphify update ./src --no-cluster # skip reclustering, write raw AST graph only
graphify update ./src --force # overwrite even if new graph has fewer nodes
graphify cluster-only ./my-project
graphify cluster-only ./my-project --graph path/to/graph.json # custom graph location
```
Works with any mix of file types:
---
| Type | Extensions | Extraction |
|------|-----------|------------|
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + Java extends/implements + docstring/comment rationale |
| Docs | `.md .mdx .html .txt .rst .yaml .yml` | Concepts + relationships + design rationale via Claude |
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
| Papers | `.pdf` | Citation mining + concept extraction |
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
| Video / Audio | `.mp4 .mov .mkv .webm .avi .m4v .mp3 .wav .m4a .ogg` | Transcribed locally with faster-whisper, transcript fed into Claude extraction (requires `pip install graphifyy[video]`) |
| YouTube / URLs | any video URL | Audio downloaded via yt-dlp, then same Whisper pipeline (requires `pip install graphifyy[video]`) |
## Learn more
## Video and audio corpus
- [How it works](docs/how-it-works.md) — the extraction pipeline, community detection, confidence scoring, benchmarks
- [ARCHITECTURE.md](ARCHITECTURE.md) — module breakdown, how to add a language
- [Optional integrations](docs/docker-mcp-sqlite.md) — Docker MCP Toolkit + SQLite
Drop video or audio files into your corpus folder alongside your code and docs — graphify picks them up automatically:
```bash
pip install 'graphifyy[video]' # one-time setup
/graphify ./my-corpus # transcribes any video/audio files it finds
```
Add a YouTube video (or any public video URL) directly:
```bash
/graphify add <video-url>
```
yt-dlp downloads audio-only (fast, small), Whisper transcribes it locally, and the transcript is fed into the same extraction pipeline as your other docs. Transcripts are cached in `graphify-out/transcripts/` so re-runs skip already-transcribed files.
For better accuracy on technical content, use a larger model:
```bash
/graphify ./my-corpus --whisper-model medium
```
Audio never leaves your machine. All transcription runs locally.
> **Legal notice:** Only use `/graphify add <url>` to download content you have the rights to. graphify uses yt-dlp for audio extraction — the same terms of service and copyright rules apply.
## What you get
**God nodes** - highest-degree concepts (what everything connects through)
**Surprising connections** - ranked by composite score. Code-paper edges rank higher than code-code. Each result includes a plain-English why.
**Suggested questions** - 4-5 questions the graph is uniquely positioned to answer
**The "why"** - docstrings, inline comments (`# NOTE:`, `# IMPORTANT:`, `# HACK:`, `# WHY:`), and design rationale from docs are extracted as `rationale_for` nodes. Not just what the code does - why it was written that way.
**Confidence scores** - every INFERRED edge has a `confidence_score` (0.0-1.0). You know not just what was guessed but how confident the model was. EXTRACTED edges are always 1.0.
**Semantic similarity edges** - cross-file conceptual links with no structural connection. Two functions solving the same problem without calling each other, a class in code and a concept in a paper describing the same algorithm.
**Hyperedges** - group relationships connecting 3+ nodes that pairwise edges can't express. All classes implementing a shared protocol, all functions in an auth flow, all concepts from a paper section forming one idea.
**Token benchmark** - printed automatically after every run. On a mixed corpus (Karpathy repos + papers + images): **71.5x** fewer tokens per query vs reading raw files. The first run extracts and builds the graph (this costs tokens). Every subsequent query reads the compact graph instead of raw files — that's where the savings compound. The SHA256 cache means re-runs only re-process changed files.
**Auto-sync** (`--watch`) - run in a background terminal and the graph updates itself as your codebase changes. Code file saves trigger an instant rebuild (AST only, no LLM). Doc/image changes notify you to run `--update` for the LLM re-pass.
**Git hooks** (`graphify hook install`) - installs post-commit and post-checkout hooks. Graph rebuilds automatically after every commit and every branch switch. If a rebuild fails, the hook exits with a non-zero code so git surfaces the error instead of silently continuing. No background process needed.
**Wiki** (`--wiki`) - Wikipedia-style markdown articles per community and god node, with an `index.md` entry point. Point any agent at `index.md` and it can navigate the knowledge base by reading files instead of parsing JSON.
## Worked examples
| Corpus | Files | Reduction | Output |
|--------|-------|-----------|--------|
| Karpathy repos + 5 papers + 4 images | 52 | **71.5x** | [`worked/karpathy-repos/`](worked/karpathy-repos/) |
| graphify source + Transformer paper | 4 | **5.4x** | [`worked/mixed-corpus/`](worked/mixed-corpus/) |
| httpx (synthetic Python library) | 6 | ~1x | [`worked/httpx/`](worked/httpx/) |
Token reduction scales with corpus size. 6 files fits in a context window anyway, so graph value there is structural clarity, not compression. At 52 files (code + papers + images) you get 71x+. Each `worked/` folder has the raw input files and the actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify the numbers.
## Privacy
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
## Tech stack
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
---
## Built on graphify — Penpax
[**Penpax**](https://safishamsi.github.io/penpax.ai) is the enterprise layer on top of graphify. Where graphify turns a folder of files into a knowledge graph, Penpax applies the same graph to your entire working life — continuously.
[**Penpax**](https://graphifylabs.ai) is the always-on layer built on top of graphify — it applies the same graph approach to your entire working life: meetings, browser history, emails, files, and code, updating continuously in the background.
| | graphify | Penpax |
|---|---|---|
| Input | A folder of files | Browser history, meetings, emails, files, code — everything |
| Runs | On demand | Continuously in the background |
| Scope | A project | Your entire working life |
| Query | CLI / MCP / AI skill | Natural language, always on |
| Privacy | Local by default | Fully on-device, no cloud |
Built for people whose work lives across hundreds of conversations and documents they can never fully reconstruct. No cloud, fully on-device.
Built for lawyers, consultants, executives, doctors, researchers — anyone whose work lives across hundreds of conversations and documents they can never fully reconstruct.
**Free trial launching soon.** [Join the waitlist →](https://graphifylabs.ai)
**Free trial launching soon.** [Join the waitlist →](https://safishamsi.github.io/penpax.ai)
## What we are building next
graphify is the graph layer. Penpax is the always-on layer on top of it — an on-device digital twin that connects your meetings, browser history, files, emails, and code into one continuously updating knowledge graph. No cloud, no training on your data. [Join the waitlist.](https://safishamsi.github.io/penpax.ai)
---
<details>
<summary>Contributing</summary>
**Worked examples** are the most trust-building contribution. Run `/graphify` on a real corpus, save output to `worked/{slug}/`, write an honest `review.md` evaluating what the graph got right and wrong, submit a PR.
### Development setup
**Extraction bugs** - open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or invented.
Clone the repo and install in editable mode:
```bash
git clone https://github.com/safishamsi/graphify.git
cd graphify
git checkout v7 # active development branch
# Create a virtual environment (Python 3.10+ required):
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install in editable mode with all optional extras:
pip install -e ".[all]"
```
Verify the editable install:
```bash
graphify --version
python -c "import graphify; print(graphify.__file__)"
```
### Running tests
```bash
pip install pytest
pytest tests/ -q # run the full suite
pytest tests/test_extract.py -q # one module
pytest tests/ -q -k "python" # filter by name
```
> macOS note: the test suite includes both `sample.f90` and `sample.F90` fixtures. These collide on case-insensitive HFS+ / APFS file systems. Run on Linux or in a Docker container if you need to test both Fortran variants simultaneously.
### Git workflow
- Active development happens on the `v7` branch.
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
- Before opening a PR, run `pytest tests/ -q` and confirm it passes.
- Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py` for any new language extractor.
### What to contribute
**Worked examples** are the most useful contribution. Run `/graphify` on a real corpus, save the output to `worked/{slug}/`, write an honest `review.md` covering what the graph got right and wrong, and open a PR.
**Extraction bugs** — open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or wrong.
See [ARCHITECTURE.md](ARCHITECTURE.md) for module responsibilities and how to add a language.
+138
View File
@@ -0,0 +1,138 @@
# Docker MCP Toolkit + SQLite MCP server
A reproducible runbook for installing the **SQLite MCP server** into the
[Docker MCP Toolkit](https://docs.docker.com/desktop/features/mcp/) so any
connected MCP client (Claude Code, Claude Desktop, Cursor, VS Code, etc.) gains
six SQLite tools: `read_query`, `write_query`, `create_table`, `list_tables`,
`describe_table`, and `append_insight`.
This document is *not* required to use graphify — it lives here as a known-good
recipe for users who want a lightweight, persistent SQL workspace exposed to
their AI clients alongside graphify's knowledge-graph tools.
## Why SQLite (and not `sqlite-mcp-server`)
At time of writing the catalog ships two SQLite MCP images:
| Catalog name | Image | Status |
| ------------------- | ---------------------- | ------ |
| `SQLite` | `mcp/sqlite` | Marked "Archived" in catalog metadata, but **boots and serves correctly** |
| `sqlite-mcp-server` | `mcp/sqlite-mcp-server`| **Broken**: entrypoint `/app/.venv/bin/mcp-server-sqlite` does not exist in the published layer |
Use `SQLite` (`mcp/sqlite`) until the newer image is fixed upstream.
## Prerequisites
- Docker Desktop running and healthy
- `docker info` returns a `Server Version`
- Public socket present at `/var/run/docker.sock` (or its symlink to
`~/.docker/run/docker.sock`)
- Docker MCP Toolkit CLI plugin (`docker mcp`)
- Bundled with recent Docker Desktop releases; `docker mcp --version` should
print a version string
## Install
```bash
# Add the working SQLite server to the default MCP profile
docker mcp profile server add default \
--server catalog://mcp/docker-mcp-catalog/SQLite
# Pre-pull the image so the first tool call is fast
docker pull mcp/sqlite:latest
```
Verify the profile now contains both `fetch` (built-in) and `SQLite`:
```bash
docker mcp profile show default | grep -E '^[[:space:]]+name:'
```
Expected output:
```
name: fetch
name: SQLite
```
The Docker MCP gateway should now expose 6 additional tools:
```bash
docker mcp tools count
# → 15 tools (was 9 before adding SQLite)
```
## Smoke test
The CLI can call MCP tools directly (each call boots a fresh gateway, ~5s
overhead per call):
```bash
docker mcp tools call list_tables
docker mcp tools call create_table \
query='CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP)'
docker mcp tools call write_query \
query="INSERT INTO notes(body) VALUES ('first row'), ('second row')"
docker mcp tools call read_query \
query='SELECT * FROM notes ORDER BY id'
docker mcp tools call describe_table table_name=notes
docker mcp tools call append_insight insight='3 rows inserted; aggregates work.'
```
`read_query` should return the inserted rows with timestamps.
## Storage layout
Database file lives in a Docker named volume `mcp-sqlite`, mounted at `/mcp`
inside containers:
```
mcp-sqlite (named volume) → /mcp/db.sqlite
```
Inspect from the host:
```bash
docker volume inspect mcp-sqlite
docker run --rm -v mcp-sqlite:/mcp:ro alpine ls -la /mcp
docker run --rm -v mcp-sqlite:/mcp:ro keinos/sqlite3 \
sqlite3 /mcp/db.sqlite '.schema'
```
The volume persists across `docker run --rm` invocations of the SQLite MCP
container, so writes from one MCP tool call are visible to the next.
## Wiring into MCP clients
Connect once per client; the gateway exposes every server in the active profile:
```bash
docker mcp client connect claude-code # already connected for many users
docker mcp client connect cursor
docker mcp client connect vscode
docker mcp client connect claude-desktop
# Supported: claude-code, claude-desktop, cline, codex, continue, crush,
# cursor, gemini, goose, gordon, kiro, lmstudio, opencode, sema4,
# vscode, zed
```
Verify wiring:
```bash
docker mcp client ls
```
## Uninstall / reset
```bash
# Remove server from the profile
docker mcp profile server remove default SQLite
# Drop the database volume (irreversible)
docker volume rm mcp-sqlite
# Remove the image
docker rmi mcp/sqlite:latest
```
## Troubleshooting
- **`starting client: calling "initialize": EOF`** — the requested server
failed its MCP handshake. Run the image directly to see the error:
```bash
printf '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"smoke","version":"0.0"}}}\n' \
| docker run --rm -i -v mcp-sqlite:/mcp <image-ref> --db-path /mcp/db.sqlite
```
Common causes: missing entrypoint binary in the image (the
`sqlite-mcp-server` failure mode) or missing required env/secrets.
- **`cannot use --enable-all-servers with --servers flag`** — these gateway
args are mutually exclusive; pick one.
- **No new tools appear in `docker mcp tools count` after install** — the
gateway may be running with `dynamic-tools` enabled, exposing only meta-tools
(`mcp-add`, `mcp-find`, …) until a profile is activated mid-session. Either
invoke `docker mcp tools` (which spins up an ephemeral gateway against the
default profile) or call `mcp-activate-profile` from inside an MCP session.
+96
View File
@@ -0,0 +1,96 @@
# How graphify works
## The three passes
graphify processes your files in three passes:
**Pass 1 — Code structure (free, no API calls)**
Tree-sitter parses your code files and extracts classes, functions, imports, call graphs, and inline comments. This runs locally with no LLM involved. 25 languages supported. SQL files get special treatment: tables, views, foreign keys, and JOIN relationships are extracted deterministically.
**Pass 2 — Video and audio (local, no API calls)**
Video and audio files are transcribed with faster-whisper. To focus the transcript on your domain, the transcription prompt is seeded with your top god nodes (the most-connected concepts in your code graph so far). Transcripts are cached — re-runs skip already-processed files.
**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
Communities are found using the [Leiden algorithm](https://www.nature.com/articles/s41598-019-41695-z) — a graph-clustering method that groups nodes by edge density. Nodes with many connections between them end up in the same community.
**No embeddings needed.** The semantic similarity edges that Claude extracts (`semantically_similar_to`) are already in the graph, so they influence community shape directly. The graph structure is the similarity signal — there's no separate embedding step or vector database.
---
## Confidence tagging
Every relationship is tagged with one of three labels:
| Tag | Meaning |
|-----|---------|
| `EXTRACTED` | Found directly in the source (e.g. a function call, an import) |
| `INFERRED` | A reasonable inference Claude made, with a `confidence_score` (0.0–1.0) |
| `AMBIGUOUS` | Uncertain — flagged in the report for manual review |
EXTRACTED edges always have confidence 1.0. INFERRED edges use a discrete rubric:
- **0.95** — near-certain (explicit cross-file reference, one plausible target)
- **0.85** — strong evidence (naming + context align)
- **0.75** — reasonable (contextual but not explicit)
- **0.65** — weak (naming similarity only)
- **0.55** — speculative
---
## Token benchmark
The first run extracts and builds the graph — this costs tokens. Every subsequent query reads the compact graph instead of raw files. That's where the savings compound.
On a mixed corpus (Karpathy repos + 5 papers + 4 images, 52 files): **71.5x fewer tokens per query** vs reading the raw files directly.
| Corpus | Files | Reduction |
|--------|-------|-----------|
| Karpathy repos + papers + images | 52 | **71.5x** |
| graphify source + Transformer paper | 4 | **5.4x** |
| httpx (synthetic Python library) | 6 | ~1x |
Token reduction scales with corpus size. Six files already fits in a context window — the graph value there is structural clarity, not compression. At 52 files the savings compound quickly.
Each `worked/` folder in the repo has the raw input files and actual output (`GRAPH_REPORT.md`, `graph.json`) so you can run it yourself and verify.
---
## Parallel extraction
Code files are extracted in parallel using `ProcessPoolExecutor` — bypasses Python's GIL for genuine multiprocessing. Doc/paper/image batches are dispatched as parallel Claude subagents. On a corpus of 84 code files, parallel AST extraction runs in about 1.66x less time than sequential.
---
## SHA256 cache
Every extracted file is fingerprinted by content hash. Re-runs skip unchanged files entirely — only new or modified files go through extraction again. The cache lives in `graphify-out/cache/`.
---
## The graph format
The output `graph.json` uses NetworkX's node-link format. Each node has:
- `id` — stable identifier
- `label` — human-readable name
- `file_type` — `code`, `document`, `paper`, `image`, `rationale`
- `source_file` — where it came from
Each edge has:
- `source`, `target` — node IDs
- `relation` — verb phrase (e.g. `calls`, `imports`, `implements`, `semantically_similar_to`)
- `confidence` — `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`
- `confidence_score` — float (INFERRED only)
- `source_file` — where the relationship was found
Hyperedges (group relationships connecting 3+ nodes) live in `G.graph["hyperedges"]`.
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
+1352 -92
View File
File diff suppressed because it is too large. Load diff
+36 -1
View File
@@ -1,7 +1,36 @@
"""Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
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")},
**{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
**{e: "go" for e in (".go",)},
**{e: "rust" for e in (".rs",)},
**{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
**{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
**{e: "ruby" for e in (".rb",)},
**{e: "swift" for e in (".swift",)},
**{e: "dotnet" for e in (".cs",)},
**{e: "php" for e in (".php",)},
**{e: "r" for e in (".r",)},
}
def _cross_language(src_a: str, src_b: str) -> bool:
"""Return True if two source files belong to different language families."""
ext_a = Path(src_a).suffix.lower()
ext_b = Path(src_b).suffix.lower()
fam_a = _LANG_FAMILY.get(ext_a)
fam_b = _LANG_FAMILY.get(ext_b)
if fam_a is None or fam_b is None:
return False
return fam_a != fam_b
def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
"""Invert communities dict: node_id -> community_id."""
@@ -143,7 +172,13 @@ def _surprise_score(
# 1. Confidence weight - uncertain connections are more noteworthy
conf = data.get("confidence", "EXTRACTED")
relation = data.get("relation", "")
conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
# Cross-language INFERRED calls are likely resolver pollution, not real surprises
if conf == "INFERRED" and relation == "calls" and _cross_language(u_source, v_source):
conf_bonus = 0 # downgrade: don't promote likely false positives
score += conf_bonus
if conf in ("AMBIGUOUS", "INFERRED"):
reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
@@ -268,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")
+141 -22
View File
@@ -24,19 +24,71 @@ 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
# Synonym mapper for known invalid file_type values that LLM subagents commonly
# emit. Keeps semantic intent close (markdown→document, tool→code) and falls
# back to "concept" for any other invalid value (see #840).
_FILE_TYPE_SYNONYMS = {
"markdown": "document",
"text": "document",
"tool": "code",
"library": "code",
"pattern": "concept",
"principle": "concept",
"constraint": "concept",
"tech": "concept",
"technology": "concept",
"data-source": "concept",
"data_source": "concept",
"gotcha": "concept",
"framework": "concept",
}
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:
"""Normalize path separators to forward slashes so Windows backslash paths
and POSIX paths from semantic subagents resolve to the same node identity."""
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:
@@ -51,7 +103,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(
@@ -65,6 +119,15 @@ 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"
ft = node.get("file_type", "")
if ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
node["file_type"] = _FILE_TYPE_SYNONYMS.get(ft, "concept")
errors = validate_extraction(extraction)
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
@@ -73,6 +136,8 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
G: nx.Graph = nx.DiGraph() if directed else nx.Graph()
for node in extraction.get("nodes", []):
if "source_file" in node:
node["source_file"] = _norm_source_file(node["source_file"])
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
node_set = set(G.nodes())
# Normalized ID map: lets edges survive when the LLM generates IDs with
@@ -95,6 +160,8 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
if src not in node_set or tgt not in node_set:
continue # skip edges to external/stdlib nodes - expected, not an error
attrs = {k: v for k, v in edge.items() if k not in ("source", "target")}
if "source_file" in attrs:
attrs["source_file"] = _norm_source_file(attrs["source_file"])
# Preserve original edge direction - undirected graphs lose it otherwise,
# causing display functions to show edges backwards.
attrs["_src"] = src
@@ -106,17 +173,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", []))
@@ -124,6 +201,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)
@@ -184,32 +266,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:
@@ -218,11 +302,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:
@@ -232,3 +328,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)
+47 -15
View File
@@ -4,8 +4,14 @@ from __future__ import annotations
import hashlib
import json
import os
import tempfile
from pathlib import Path
# Output directory name — override with GRAPHIFY_OUT env var for worktrees or
# shared-output setups. Accepts a relative name ("graphify-out-feature") or an
# absolute path ("/shared/graphify-out").
_GRAPHIFY_OUT = os.environ.get("GRAPHIFY_OUT", "graphify-out")
def _body_content(content: bytes) -> bytes:
"""Strip YAML frontmatter from Markdown content, returning only the body."""
@@ -17,6 +23,17 @@ def _body_content(content: bytes) -> bytes:
return content
def _normalize_path(path: Path) -> Path:
"""Normalize path for consistent cache keys across Windows path spellings."""
import sys
if sys.platform != "win32":
return path
s = str(path)
if s.startswith("\\\\?\\"):
s = s[4:] # strip extended-length prefix \\?\
return Path(os.path.normcase(s))
def file_hash(path: Path, root: Path = Path(".")) -> str:
"""SHA256 of file contents + path relative to root.
@@ -27,7 +44,8 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
"""
p = Path(path)
p = _normalize_path(Path(path))
root = _normalize_path(Path(root))
if not p.is_file():
raise IsADirectoryError(f"file_hash requires a file, got: {p}")
raw = p.read_bytes()
@@ -37,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()
@@ -49,7 +67,9 @@ def cache_dir(root: Path = Path("."), kind: str = "ast") -> Path:
kind is "ast" or "semantic". Separate subdirectories prevent semantic cache
entries from overwriting AST cache entries for the same source_file (#582).
"""
d = Path(root).resolve() / "graphify-out" / "cache" / kind
_out = Path(_GRAPHIFY_OUT)
base = _out if _out.is_absolute() else Path(root).resolve() / _out
d = base / "cache" / kind
d.mkdir(parents=True, exist_ok=True)
return d
@@ -76,7 +96,7 @@ def load_cached(path: Path, root: Path = Path("."), kind: str = "ast") -> dict |
return None
# Migration fallback: check legacy flat cache/ dir for AST entries
if kind == "ast":
legacy = Path(root).resolve() / "graphify-out" / "cache" / f"{h}.json"
legacy = Path(root).resolve() / _GRAPHIFY_OUT / "cache" / f"{h}.json"
if legacy.exists():
try:
return json.loads(legacy.read_text(encoding="utf-8"))
@@ -99,26 +119,35 @@ def save_cached(path: Path, result: dict, root: Path = Path("."), kind: str = "a
if not p.is_file():
return
h = file_hash(p, root)
entry = cache_dir(root, kind) / f"{h}.json"
tmp = entry.with_suffix(".tmp")
target_dir = cache_dir(root, kind)
entry = target_dir / f"{h}.json"
fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=f"{h}.", suffix=".tmp")
try:
tmp.write_text(json.dumps(result), encoding="utf-8")
os.write(fd, json.dumps(result).encode())
os.close(fd)
try:
os.replace(tmp, entry)
os.replace(tmp_path, entry)
except PermissionError:
# Windows: os.replace can fail with WinError 5 if the target is
# briefly locked. Fall back to copy-then-delete.
import shutil
shutil.copy2(tmp, entry)
tmp.unlink(missing_ok=True)
shutil.copy2(tmp_path, entry)
os.unlink(tmp_path)
except Exception:
tmp.unlink(missing_ok=True)
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(tmp_path)
except OSError:
pass
raise
def cached_files(root: Path = Path(".")) -> set[str]:
"""Return set of file hashes that have a valid cache entry (any kind)."""
base = Path(root).resolve() / "graphify-out" / "cache"
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
hashes: set[str] = set()
# Legacy flat entries
if base.is_dir():
@@ -133,7 +162,7 @@ def cached_files(root: Path = Path(".")) -> set[str]:
def clear_cache(root: Path = Path(".")) -> None:
"""Delete all cache entries (ast/, semantic/, and legacy flat entries)."""
base = Path(root).resolve() / "graphify-out" / "cache"
base = Path(root).resolve() / _GRAPHIFY_OUT / "cache"
# Legacy flat entries
if base.is_dir():
for f in base.glob("*.json"):
@@ -161,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
+86 -2
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import contextlib
import inspect
import io
import json
import sys
import networkx as nx
@@ -27,15 +28,34 @@ def _partition(G: nx.Graph) -> dict[str, int]:
Output from graspologic is suppressed to prevent ANSI escape codes
from corrupting terminal scroll buffers on Windows PowerShell 5.1.
"""
stable = nx.Graph()
stable.add_nodes_from(sorted(G.nodes(), key=str))
edge_rows = sorted(
G.edges(data=True),
key=lambda row: (
str(row[0]),
str(row[1]),
json.dumps(row[2], sort_keys=True, ensure_ascii=False, default=str),
),
)
for src, tgt, attrs in edge_rows:
stable.add_edge(src, tgt, **attrs)
try:
from graspologic.partition import leiden
lsig = inspect.signature(leiden).parameters
kwargs: dict = {}
if "random_seed" in lsig:
kwargs["random_seed"] = 42
if "trials" in lsig:
kwargs["trials"] = 1
# Suppress graspologic output to prevent ANSI escape codes from
# corrupting PowerShell 5.1 scroll buffer (issue #19)
old_stderr = sys.stderr
try:
sys.stderr = io.StringIO()
with _suppress_output():
result = leiden(G)
result = leiden(stable, **kwargs)
finally:
sys.stderr = old_stderr
return result
@@ -48,12 +68,14 @@ def _partition(G: nx.Graph) -> dict[str, int]:
kwargs: dict = {"seed": 42, "threshold": 1e-4}
if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:
kwargs["max_level"] = 10
communities = nx.community.louvain_communities(G, **kwargs)
communities = nx.community.louvain_communities(stable, **kwargs)
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
_MAX_COMMUNITY_FRACTION = 0.25 # communities larger than 25% of graph get split
_MIN_SPLIT_SIZE = 10 # only split if community has at least this many nodes
_COHESION_SPLIT_THRESHOLD = 0.05 # re-split communities with cohesion below this
_COHESION_SPLIT_MIN_SIZE = 50 # only cohesion-split if community has at least this many nodes
def cluster(G: nx.Graph) -> dict[int, list[str]]:
@@ -99,6 +121,17 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
else:
final_communities.append(nodes)
# Second pass: re-split low-cohesion communities caused by doc-hub nodes
# that bridge otherwise-unrelated subsystems (e.g. CLAUDE.md connected to everything).
second_pass: list[list[str]] = []
for nodes in final_communities:
if len(nodes) >= _COHESION_SPLIT_MIN_SIZE and cohesion_score(G, nodes) < _COHESION_SPLIT_THRESHOLD:
splits = _split_community(G, nodes)
second_pass.extend(splits if len(splits) > 1 else [nodes])
else:
second_pass.append(nodes)
final_communities = second_pass
# Re-index by size descending for deterministic ordering
final_communities.sort(key=len, reverse=True)
return {i: sorted(nodes) for i, nodes in enumerate(final_communities)}
@@ -135,3 +168,54 @@ def cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
def score_all(G: nx.Graph, communities: dict[int, list[str]]) -> dict[int, float]:
return {cid: cohesion_score(G, nodes) for cid, nodes in communities.items()}
def remap_communities_to_previous(
communities: dict[int, list[str]],
previous_node_community: dict[str, int],
) -> dict[int, list[str]]:
"""Remap community IDs to maximize overlap with a previous assignment.
Uses greedy one-to-one matching by intersection size, then assigns fresh IDs
to unmatched communities in deterministic order (size desc, lexical tie-break).
"""
if not communities:
return {}
new_sets = {cid: set(nodes) for cid, nodes in communities.items()}
old_sets: dict[int, set[str]] = {}
for node, old_cid in previous_node_community.items():
old_sets.setdefault(old_cid, set()).add(node)
overlaps: list[tuple[int, int, int]] = []
for old_cid, old_nodes in old_sets.items():
for new_cid, new_nodes in new_sets.items():
overlap = len(old_nodes & new_nodes)
if overlap > 0:
overlaps.append((overlap, old_cid, new_cid))
overlaps.sort(key=lambda x: (-x[0], x[1], x[2]))
new_to_final: dict[int, int] = {}
used_old_ids: set[int] = set()
matched_new_ids: set[int] = set()
for _overlap, old_cid, new_cid in overlaps:
if old_cid in used_old_ids or new_cid in matched_new_ids:
continue
new_to_final[new_cid] = old_cid
used_old_ids.add(old_cid)
matched_new_ids.add(new_cid)
unmatched = [cid for cid in communities if cid not in matched_new_ids]
unmatched.sort(key=lambda cid: (-len(communities[cid]), tuple(sorted(communities[cid]))))
next_id = 0
for new_cid in unmatched:
while next_id in used_old_ids:
next_id += 1
new_to_final[new_cid] = next_id
used_old_ids.add(next_id)
next_id += 1
remapped: dict[int, list[str]] = {}
for new_cid, nodes in communities.items():
remapped[new_to_final[new_cid]] = sorted(nodes)
return dict(sorted(remapped.items(), key=lambda kv: kv[0]))
+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)
+482 -55
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'}
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', '.astro', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
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),
@@ -78,11 +84,42 @@ def _looks_like_paper(path: Path) -> bool:
_ASSET_DIR_MARKERS = {".imageset", ".xcassets", ".appiconset", ".colorset", ".launchimage"}
_SHEBANG_CODE_INTERPRETERS = {
"python", "python3", "python2",
"ruby", "perl", "node", "nodejs",
"bash", "sh", "dash", "zsh", "fish", "ksh", "tcsh",
"lua", "php", "julia", "Rscript",
}
def _shebang_file_type(path: Path) -> FileType | None:
"""Peek at the first line of an extensionless file for a shebang."""
try:
with path.open("rb") as f:
first = f.read(128)
if not first.startswith(b"#!"):
return None
line = first.split(b"\n")[0].decode(errors="replace")
parts = line[2:].strip().split()
if not parts:
return None
interp = parts[0].split("/")[-1] # /usr/bin/env → env
if interp == "env" and len(parts) > 1:
interp = parts[1].split("/")[-1]
if interp in _SHEBANG_CODE_INTERPRETERS:
return FileType.CODE
except OSError:
pass
return None
def classify_file(path: Path) -> FileType | None:
# Compound extensions must be checked before simple suffix lookup
if path.name.lower().endswith(".blade.php"):
return FileType.CODE
ext = path.suffix.lower()
if not ext:
return _shebang_file_type(path)
if ext in CODE_EXTENSIONS:
return FileType.CODE
if ext in PAPER_EXTENSIONS:
@@ -99,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
@@ -169,7 +208,6 @@ def xlsx_to_markdown(path: Path) -> str:
ws = wb[sheet_name]
rows = []
for row in ws.iter_rows(values_only=True):
# Skip entirely empty rows
if all(cell is None for cell in row):
continue
rows.append([str(cell) if cell is not None else "" for cell in row])
@@ -190,6 +228,96 @@ def xlsx_to_markdown(path: Path) -> str:
return ""
def xlsx_extract_structure(path: Path) -> dict:
"""Extract structural nodes (sheets, named tables, column headers) from an .xlsx file.
Returns a nodes/edges dict compatible with the graphify extract pipeline.
Used in addition to xlsx_to_markdown so Claude sees both structure and content.
"""
def _nid(*parts: str) -> str:
return re.sub(r"[^a-z0-9_]", "_", "_".join(p.lower() for p in parts).strip("_"))
try:
import openpyxl
except ImportError:
return {"nodes": [], "edges": []}
try:
wb = openpyxl.load_workbook(str(path), read_only=False, data_only=True)
except Exception:
return {"nodes": [], "edges": []}
# 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",
"source_file": str_path, "source_location": None}]
edges: list[dict] = []
seen: set[str] = {file_nid}
def _add(nid: str, label: str) -> None:
if nid not in seen:
seen.add(nid)
nodes.append({"id": nid, "label": label, "file_type": "document",
"source_file": str_path, "source_location": None})
def _edge(src: str, tgt: str, relation: str) -> None:
edges.append({"source": src, "target": tgt, "relation": relation,
"confidence": "EXTRACTED", "source_file": str_path,
"source_location": None, "weight": 1.0})
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
sheet_nid = _nid(stem, sheet_name)
_add(sheet_nid, f"{sheet_name} (sheet)")
_edge(file_nid, sheet_nid, "contains")
# Named Excel Tables (ListObjects)
if hasattr(ws, "tables"):
for tbl in ws.tables.values():
tbl_nid = _nid(stem, sheet_name, tbl.name)
_add(tbl_nid, tbl.name)
_edge(sheet_nid, tbl_nid, "contains")
# Column headers from table header row
ref = tbl.ref # e.g. "A1:D10"
if ref:
try:
from openpyxl.utils import range_boundaries
min_col, min_row, max_col, _ = range_boundaries(ref)
header_row = list(ws.iter_rows(min_row=min_row, max_row=min_row,
min_col=min_col, max_col=max_col,
values_only=True))
if header_row:
for col_name in header_row[0]:
if col_name:
col_nid = _nid(stem, tbl.name, str(col_name))
_add(col_nid, str(col_name))
_edge(tbl_nid, col_nid, "contains")
except Exception:
pass
else:
# Fallback: first non-empty row as column headers
for row in ws.iter_rows(max_row=1, values_only=True):
for cell in row:
if cell:
col_nid = _nid(stem, sheet_name, str(cell))
_add(col_nid, str(cell))
_edge(sheet_nid, col_nid, "contains")
break
try:
wb.close()
except Exception:
pass
return {"nodes": nodes, "edges": edges}
def convert_office_file(path: Path, out_dir: Path) -> Path | None:
"""Convert a .docx or .xlsx to a markdown sidecar in out_dir.
@@ -242,6 +370,12 @@ _SKIP_DIRS = {
".pytest_cache", ".mypy_cache", ".ruff_cache",
".tox", ".eggs", "*.egg-info",
"graphify-out", # never treat own output as source input (#524)
# Coverage/test-artefact dirs — generated, never architecturally meaningful
"coverage", "lcov-report", # Vitest/Istanbul/nyc HTML reports (#870)
"visual-tests", "visual-test", # Playwright/visual-regression bundles (#869)
"__snapshots__", "snapshots", # Jest/Vitest snapshot dirs
"storybook-static", # Storybook production build output
"dist-protected", # Protected dist variants (same noise as dist)
}
# Large generated files that are never useful to extract
@@ -263,38 +397,169 @@ def _is_noise_dir(part: str) -> bool:
return False
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyignore from root **and ancestor directories**.
_VCS_MARKERS = (".git", ".hg", ".svn", "_darcs", ".fossil")
Returns a list of (anchor_dir, pattern) pairs. Each pattern is matched
against paths relative to both the scan root and the anchor_dir where
the .graphifyignore file was found — so patterns written relative to a
parent directory still work when graphify is run on a subfolder.
Walks upward from *root* towards the filesystem root, stopping at a
``.git`` boundary. Lines starting with # are comments; blank lines ignored.
def _parse_gitignore_line(raw: str) -> str:
"""Parse one raw line from a .graphifyignore file per gitignore spec.
- Strip newline chars
- Strip inline comments (whitespace + # suffix), but only when # is
preceded by whitespace — so path#with#hash.py is preserved
- Unescape \\# to literal #
- Remove trailing spaces unless escaped with backslash
- Strip leading whitespace
- Return empty string for blank lines and full-line comments
"""
patterns: list[tuple[Path, str]] = []
current = root.resolve()
line = raw.rstrip("\n\r")
line = line.lstrip()
if not line or line.startswith("#"):
return ""
# Strip inline comments: require whitespace before # (gitignore extension)
line = re.sub(r"\s+#+[^\\].*$", "", line)
# Unescape \# → literal #
line = line.replace("\\#", "#")
# Remove unescaped trailing spaces (per gitignore spec)
line = re.sub(r"(?<!\\) +$", "", line)
return line
def _find_vcs_root(start: Path) -> Path | None:
"""Walk upward from start; return the first directory containing a VCS marker."""
current = start.resolve()
home = Path.home()
while True:
ignore_file = current / ".graphifyignore"
if ignore_file.exists():
for line in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = line.strip()
if line and not line.startswith("#"):
patterns.append((current, line))
# Stop climbing once we've processed the git repo root
if (current / ".git").exists():
break
if any((current / m).exists() for m in _VCS_MARKERS):
return current
parent = current.parent
if parent == current:
break # filesystem root
if parent == current or current == home:
return None
current = parent
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyignore files and return (anchor_dir, pattern) pairs.
Patterns are returned outer-first so that inner (closer) rules are
appended last and win via last-match-wins semantics — matching gitignore
behavior exactly.
Walk ceiling: the nearest VCS root if inside a repo, otherwise the scan
root itself (hermetic — no leakage across unrelated sibling projects).
"""
root = root.resolve()
ceiling = _find_vcs_root(root) or root
# Collect ancestor dirs from ceiling down to root (outer → inner)
dirs: list[Path] = []
current = root
while True:
dirs.append(current)
if current == ceiling:
break
current = current.parent
dirs.reverse() # ceiling first, scan root last
patterns: list[tuple[Path, str]] = []
for d in dirs:
ignore_file = d / ".graphifyignore"
if ignore_file.exists():
for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = _parse_gitignore_line(raw)
if line:
patterns.append((d, line))
return patterns
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if path matches any .graphifyignore pattern."""
"""Return True if the path should be ignored per .graphifyignore patterns.
Uses gitignore last-match-wins semantics: all patterns are evaluated in
order; the final matching pattern determines the result. Negation patterns
(starting with !) un-ignore a previously ignored path.
"""
if not patterns:
return False
def _matches(rel: str, p: str) -> bool:
parts = rel.split("/")
if fnmatch.fnmatch(rel, p):
return True
if fnmatch.fnmatch(path.name, p):
return True
for i, part in enumerate(parts):
if fnmatch.fnmatch(part, p):
return True
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
return True
return False
result = False
for anchor, pattern in patterns:
negated = pattern.startswith("!")
raw = pattern[1:] if negated else pattern
anchored = raw.startswith("/")
p = raw.strip("/")
if not p:
continue
matched = False
if anchored:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p)
except ValueError:
pass
else:
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
matched = _matches(rel, p)
except ValueError:
pass
if not matched and anchor != root:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
matched = _matches(rel_anchor, p)
except ValueError:
pass
if matched:
result = not negated # last match wins; ! flips to un-ignore
return result
def _load_graphifyinclude(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyinclude allowlist patterns from root and ancestors.
Include patterns opt matching hidden files/dirs into traversal. Sensitive
files and hard-skipped noise directories are still excluded later.
Uses the same VCS-root ceiling logic as _load_graphifyignore.
"""
root = root.resolve()
ceiling = _find_vcs_root(root) or root
dirs: list[Path] = []
current = root
while True:
dirs.append(current)
if current == ceiling:
break
current = current.parent
dirs.reverse()
patterns: list[tuple[Path, str]] = []
for d in dirs:
include_file = d / ".graphifyinclude"
if include_file.exists():
for raw in include_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = _parse_gitignore_line(raw)
if line:
patterns.append((d, line))
return patterns
def _is_included(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if path matches any .graphifyinclude allowlist pattern."""
if not patterns:
return False
@@ -312,30 +577,69 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
return False
for anchor, pattern in patterns:
anchored = pattern.startswith("/")
p = pattern.strip("/")
if not p:
continue
# Try path relative to the scan root
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
if _matches(rel, p):
return True
except ValueError:
pass
# Also try relative to the anchor dir (the .graphifyignore's location),
# so patterns written at a parent level still fire when running on a subfolder
if anchor != root:
if anchored:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _matches(rel_anchor, p):
return True
except ValueError:
pass
else:
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
if _matches(rel, p):
return True
except ValueError:
pass
if anchor != root:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _matches(rel_anchor, p):
return True
except ValueError:
pass
return False
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if a directory may contain files matched by .graphifyinclude."""
if not patterns:
return False
rels: list[str] = []
try:
rels.append(str(path.relative_to(root)).replace(os.sep, "/"))
except ValueError:
pass
for anchor, _ in patterns:
if anchor != root:
try:
rels.append(str(path.relative_to(anchor)).replace(os.sep, "/"))
except ValueError:
pass
for rel in rels:
rel = rel.strip("/")
if not rel:
return True
for _, pattern in patterns:
p = pattern.strip("/")
if not p:
continue
if p == rel or p.startswith(rel + "/"):
return True
if fnmatch.fnmatch(rel, p):
return True
return False
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: [],
@@ -347,6 +651,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
skipped_sensitive: list[str] = []
ignore_patterns = _load_graphifyignore(root)
include_patterns = _load_graphifyinclude(root)
# Always include graphify-out/memory/ - query results filed back into the graph
memory_dir = root / "graphify-out" / "memory"
@@ -368,12 +673,17 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
dirnames.clear()
continue
if not in_memory_tree:
# Prune noise dirs in-place so os.walk never descends into them
# Prune noise dirs in-place so os.walk never descends into them.
# Hidden dirs are allowed through if they could contain an
# explicitly included path (.graphifyinclude allowlist).
# When negation patterns (!) exist, skip directory-level ignore
# pruning so negated files inside can still be reached.
has_negation = any(p.startswith("!") for _, p in ignore_patterns)
dirnames[:] = [
d for d in dirnames
if not d.startswith(".")
if (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
and not _is_noise_dir(d)
and not _is_ignored(dp / d, root, ignore_patterns)
and (has_negation or not _is_ignored(dp / d, root, ignore_patterns))
]
for fname in filenames:
if fname in _SKIP_FILES:
@@ -390,8 +700,9 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
if not in_memory:
# Hidden files are already excluded via dir pruning above,
# but catch hidden files at the root level
if p.name.startswith("."):
# but catch hidden files at the root level. A .graphifyinclude
# entry can opt a specific hidden file back in.
if p.name.startswith(".") and not _is_included(p, root, include_patterns):
continue
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
if str(p).startswith(str(converted_dir)):
@@ -403,10 +714,33 @@ 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:
if _is_ignored(md_path, root, ignore_patterns):
continue
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)
if md_path:
if _is_ignored(md_path, root, ignore_patterns):
continue
files[ftype].append(str(md_path))
total_words += count_words(md_path)
else:
@@ -445,34 +779,104 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
}
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict[str, float]:
"""Load the file modification time manifest from a previous run."""
def _md5_file(path: Path) -> str:
"""MD5 of file contents streamed in 64KB chunks — for change detection only."""
import hashlib as _hl
h = _hl.md5(usedforsecurity=False)
try:
with path.open("rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
except OSError:
return ""
return h.hexdigest()
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
"""Load the manifest from a previous run. Returns {} on any error."""
try:
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except Exception:
return {}
def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PATH) -> None:
"""Save current file mtimes so the next --update run can diff against them."""
manifest: dict[str, float] = {}
def save_manifest(
files: dict[str, list[str]],
manifest_path: str = _MANIFEST_PATH,
*,
kind: str = "both",
) -> None:
"""Save current file mtimes + content hashes for change detection.
kind="ast" — written by `graphify update` (AST-only rebuild). Stamps
ast_hash; preserves an existing semantic_hash only when
the file content is unchanged (mtime + hash match).
kind="semantic" — written by `graphify extract` after semantic extraction.
Stamps semantic_hash; preserves existing ast_hash.
kind="both" — full pipeline: stamps both hashes (default).
"""
existing = load_manifest(manifest_path)
manifest: dict[str, dict] = {}
for file_list in files.values():
for f in file_list:
try:
manifest[f] = Path(f).stat().st_mtime
p = Path(f)
mtime = p.stat().st_mtime
h = _md5_file(p)
except OSError:
pass # file deleted between detect() and manifest write - skip it
continue # file deleted between detect() and manifest write
prev = existing.get(f, {})
# Normalise legacy {mtime, hash} entries to new schema
if isinstance(prev, (int, float)):
prev = {"mtime": prev, "ast_hash": "", "semantic_hash": ""}
elif isinstance(prev, dict) and "hash" in prev and "ast_hash" not in prev:
prev = {"mtime": prev.get("mtime", 0), "ast_hash": prev["hash"], "semantic_hash": ""}
entry: dict = {"mtime": mtime}
if kind in ("ast", "both"):
entry["ast_hash"] = h
else:
entry["ast_hash"] = prev.get("ast_hash", "")
if kind in ("semantic", "both"):
entry["semantic_hash"] = h
else:
# Preserve semantic_hash only when content is unchanged
entry["semantic_hash"] = prev.get("semantic_hash", "") if h == prev.get("ast_hash", "") else ""
manifest[f] = entry
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
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,
kind: str = "semantic",
) -> dict:
"""Like detect(), but returns only new or modified files since the last run.
Compares current file mtimes against the stored manifest.
Use for --update mode: re-extract only what changed, merge into existing graph.
kind="semantic" (default for extract): a file is "changed" when its
semantic_hash is missing or its content has changed since the last
semantic extraction pass. Use this for `graphify extract` so that
files touched by `graphify update` (AST-only) are re-extracted
semantically.
kind="ast": a file is "changed" when its ast_hash is missing or its
content has changed. Use this for `graphify update`.
Fast path: mtime unchanged + hash matches → unchanged (free, no disk IO
beyond stat). Slow path: mtime bumped → compare MD5 against the relevant
hash field before re-extracting.
Backwards compatible with legacy manifests storing plain float mtime values
or {mtime, hash} dicts (treated as ast_hash only; semantic_hash = miss).
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:
@@ -488,12 +892,35 @@ def detect_incremental(root: Path, manifest_path: str = _MANIFEST_PATH) -> dict:
for ftype, file_list in full["files"].items():
for f in file_list:
stored_mtime = manifest.get(f)
stored = manifest.get(f)
try:
current_mtime = Path(f).stat().st_mtime
except Exception:
current_mtime = 0
if stored_mtime is None or current_mtime > stored_mtime:
# Legacy manifest: plain float value — treat as ast_hash only
if isinstance(stored, (int, float)):
changed = stored is None or current_mtime > stored
elif isinstance(stored, dict):
# Normalise legacy {mtime, hash} to new schema
if "hash" in stored and "ast_hash" not in stored:
stored = {"mtime": stored.get("mtime", 0), "ast_hash": stored["hash"], "semantic_hash": ""}
hash_key = "semantic_hash" if kind == "semantic" else "ast_hash"
stored_hash = stored.get(hash_key, "")
# Missing semantic_hash means update ran but extract hasn't — always re-extract
if not stored_hash:
changed = True
else:
stored_mtime = stored.get("mtime")
if stored_mtime is None or current_mtime != stored_mtime:
# mtime bumped — verify with content hash before re-extracting
changed = _md5_file(Path(f)) != stored_hash
else:
changed = False
else:
changed = True # unknown format, re-extract to be safe
if changed:
new_files[ftype].append(f)
else:
unchanged_files[ftype].append(f)
+235 -35
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",
@@ -25,6 +73,22 @@ COMMUNITY_COLORS = [
MAX_NODES_FOR_VIZ = 5_000
def _viz_node_limit() -> int:
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
"""
import os
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
if raw is None or not raw.strip():
return MAX_NODES_FOR_VIZ
try:
return int(raw)
except ValueError:
return MAX_NODES_FOR_VIZ
def _html_styles() -> str:
return """<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
@@ -55,9 +119,14 @@ def _html_styles() -> str:
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.legend-count { color: #666; font-size: 11px; }
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
#legend-controls { display: flex; gap: 6px; margin-bottom: 8px; }
#legend-controls button { flex: 1; background: #0f0f1a; border: 1px solid #3a3a5e; color: #aaa; padding: 4px 0; border-radius: 4px; font-size: 11px; cursor: pointer; }
#legend-controls button:hover { border-color: #4E79A7; color: #e0e0e0; }
#legend-controls { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; padding: 4px 0; }
#legend-controls label { display: flex; align-items: center; gap: 6px; cursor: pointer; font-size: 12px; color: #aaa; user-select: none; }
#legend-controls label:hover { color: #e0e0e0; }
.legend-cb, #select-all-cb { appearance: none; -webkit-appearance: none; width: 14px; height: 14px; border: 1.5px solid #3a3a5e; border-radius: 3px; background: #0f0f1a; cursor: pointer; position: relative; flex-shrink: 0; }
.legend-cb:checked, #select-all-cb:checked { background: #4E79A7; border-color: #4E79A7; }
.legend-cb:checked::after, #select-all-cb:checked::after { content: ''; position: absolute; left: 3.5px; top: 1px; width: 4px; height: 7px; border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg); }
#select-all-cb:indeterminate { background: #4E79A7; border-color: #4E79A7; }
#select-all-cb:indeterminate::after { content: ''; position: absolute; left: 2px; top: 5px; width: 8px; height: 2px; background: #fff; border: none; transform: none; }
</style>"""
@@ -244,26 +313,41 @@ document.addEventListener('click', e => {{
const hiddenCommunities = new Set();
const selectAllCb = document.getElementById('select-all-cb');
function updateSelectAllState() {{
const total = LEGEND.length;
const hidden = hiddenCommunities.size;
selectAllCb.checked = hidden === 0;
selectAllCb.indeterminate = hidden > 0 && hidden < total;
}}
function toggleAllCommunities(hide) {{
document.querySelectorAll('.legend-item').forEach(item => {{
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
}});
document.querySelectorAll('.legend-cb').forEach(cb => {{
cb.checked = !hide;
}});
LEGEND.forEach(c => {{
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
}});
const updates = RAW_NODES.map(n => ({{ id: n.id, hidden: hide }}));
nodesDS.update(updates);
updateSelectAllState();
}}
const legendEl = document.getElementById('legend');
LEGEND.forEach(c => {{
const item = document.createElement('div');
item.className = 'legend-item';
item.innerHTML = `<div class="legend-dot" style="background:${{c.color}}"></div>
<span class="legend-label">${{c.label}}</span>
<span class="legend-count">${{c.count}}</span>`;
item.onclick = () => {{
if (hiddenCommunities.has(c.cid)) {{
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'legend-cb';
cb.checked = true;
cb.addEventListener('change', (e) => {{
e.stopPropagation();
if (cb.checked) {{
hiddenCommunities.delete(c.cid);
item.classList.remove('dimmed');
}} else {{
@@ -272,8 +356,18 @@ LEGEND.forEach(c => {{
}}
const updates = RAW_NODES
.filter(n => n.community === c.cid)
.map(n => ({{ id: n.id, hidden: hiddenCommunities.has(c.cid) }}));
.map(n => ({{ id: n.id, hidden: !cb.checked }}));
nodesDS.update(updates);
updateSelectAllState();
}});
item.innerHTML = `<div class="legend-dot" style="background:${{c.color}}"></div>
<span class="legend-label">${{c.label}}</span>
<span class="legend-count">${{c.count}}</span>`;
item.prepend(cb);
item.onclick = (e) => {{
if (e.target === cb) return;
cb.checked = !cb.checked;
cb.dispatchEvent(new Event('change'));
}};
legendEl.appendChild(item);
}});
@@ -294,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():
@@ -327,7 +431,19 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
if "confidence_score" not in link:
conf = link.get("confidence", "EXTRACTED")
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
# Restore original edge direction. Undirected NetworkX storage may
# canonicalize endpoint order, flipping `calls` and other directional
# edges in graph.json. The build path stashes the true endpoints in
# _src/_tgt for exactly this purpose (#563).
true_src = link.pop("_src", None)
true_tgt = link.pop("_tgt", None)
if true_src is not None and true_tgt is not None:
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
@@ -349,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:
@@ -358,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)
@@ -381,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.
@@ -390,11 +552,43 @@ 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.
"""
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
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"Use --no-viz or reduce input size."
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
f"or reduce input size."
)
node_community = _node_community_map(communities)
@@ -431,14 +625,19 @@ def to_html(
"degree": deg,
})
# Build edges list
# Build edges list. Restore original edge direction from _src/_tgt
# (stashed by build.py for exactly this reason): undirected NetworkX
# canonicalizes endpoint order, which would otherwise flip the arrow
# for `calls` and `rationale_for` in the rendered graph (#563).
vis_edges = []
for u, v, data in G.edges(data=True):
confidence = data.get("confidence", "EXTRACTED")
relation = data.get("relation", "")
true_src = data.get("_src", u)
true_tgt = data.get("_tgt", v)
vis_edges.append({
"from": u,
"to": v,
"from": true_src,
"to": true_tgt,
"label": relation,
"title": _html.escape(f"{relation} [{confidence}]"),
"dashes": confidence != "EXTRACTED",
@@ -488,8 +687,7 @@ def to_html(
<div id="legend-wrap">
<h3>Communities</h3>
<div id="legend-controls">
<button onclick="toggleAllCommunities(false)">Show All</button>
<button onclick="toggleAllCommunities(true)">Hide All</button>
<label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
</div>
<div id="legend"></div>
</div>
@@ -532,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] = {}
@@ -578,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:
@@ -603,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("")
@@ -690,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")
@@ -770,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)
+2734 -187
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
+82 -23
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"
@@ -61,8 +62,14 @@ fi
""" + _PYTHON_DETECT + """
export GRAPHIFY_CHANGED="$CHANGED"
$GRAPHIFY_PYTHON -c "
import os, sys
# Run rebuild detached so git commit returns immediately.
# Full repo rebuilds can take hours; blocking the post-commit hook stalls the shell.
_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, signal, sys
from pathlib import Path
changed_raw = os.environ.get('GRAPHIFY_CHANGED', '')
@@ -74,12 +81,22 @@ if not changed:
print(f'[graphify hook] {len(changed)} file(s) changed - rebuilding graph...')
try:
from graphify.watch import _rebuild_code
_rebuild_code(Path('.'))
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)
"
" > "$_GRAPHIFY_LOG" 2>&1 < /dev/null &
disown 2>/dev/null || true
# graphify-hook-end
"""
@@ -111,17 +128,32 @@ GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
[ -f "$GIT_DIR/CHERRY_PICK_HEAD" ] && exit 0
""" + _PYTHON_DETECT + """
echo "[graphify] Branch switched - rebuilding knowledge graph (code files)..."
$GRAPHIFY_PYTHON -c "
from graphify.watch import _rebuild_code
_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, _apply_resource_limits
from pathlib import Path
import sys
import os, signal, sys
try:
_rebuild_code(Path('.'))
_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)
"
" > "$_GRAPHIFY_LOG" 2>&1 < /dev/null &
disown 2>/dev/null || true
# graphify-checkout-hook-end
"""
@@ -138,22 +170,49 @@ 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 (configparser.Error, OSError) as exc:
# Narrow the exception (PR747-NEW-2): a bare `except Exception: pass`
# was hiding tampering signals (corrupt .git/config, permission flips
# by another tool). Surface them on stderr instead of silently
# falling through to the default hooks directory.
print(
f"[graphify hooks] could not read core.hooksPath from "
f"{root / '.git' / 'config'}: {exc}",
file=sys.stderr,
)
# In a linked worktree .git is a file not a directory, so constructing
# root/.git/hooks directly fails. Ask git for the real hooks path instead.
import subprocess as _sp
try:
res = _sp.run(
["git", "-C", str(root), "rev-parse", "--path-format=absolute", "--git-path", "hooks"],
capture_output=True, text=True,
)
if res.returncode == 0:
d = Path(res.stdout.strip())
d.mkdir(parents=True, exist_ok=True)
return d
except (OSError, FileNotFoundError):
pass
d = root / ".git" / "hooks"
d.mkdir(exist_ok=True)
d.mkdir(parents=True, exist_ok=True)
return d
+47 -13
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:
@@ -49,19 +86,16 @@ def _fetch_html(url: str) -> str:
def _html_to_markdown(html: str, url: str) -> str:
"""Convert HTML to clean markdown. Uses html2text if available, else basic strip."""
"""Convert HTML to clean markdown. Uses markdownify if available, else basic strip."""
# Always pre-strip script/style so their text content never leaks into output
html = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
html = re.sub(r"<style[^>]*>.*?</style>", "", html, flags=re.DOTALL | re.IGNORECASE)
try:
import html2text
h = html2text.HTML2Text()
h.ignore_links = False
h.ignore_images = True
h.body_width = 0
return h.handle(html)
from markdownify import markdownify
return markdownify(html, heading_style="ATX", bullets="-", strip=["img"])
except ImportError:
# Fallback: strip tags
text = re.sub(r"<script[^>]*>.*?</script>", "", html, flags=re.DOTALL | re.IGNORECASE)
text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL | re.IGNORECASE)
text = re.sub(r"<[^>]+>", " ", text)
# Fallback: basic tag strip
text = re.sub(r"<[^>]+>", " ", html)
text = re.sub(r"\s+", " ", text).strip()
return text[:8000]
+896 -38
View File
File diff suppressed because it is too large. Load diff
+22 -7
View File
@@ -23,6 +23,8 @@ def generate(
token_cost: dict,
root: str,
suggested_questions: list[dict] | None = None,
min_community_size: int = 3,
built_at_commit: str | None = None,
) -> str:
today = date.today().isoformat()
@@ -52,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:
@@ -108,7 +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}]")
lines += ["", "## Communities"]
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)
@@ -116,6 +133,8 @@ def generate(
real_nodes = [n for n in nodes if not _ifn(G, n)]
if not real_nodes:
continue
if len(real_nodes) < min_community_size:
continue
display = [G.nodes[n].get("label", n) for n in real_nodes[:8]]
suffix = f" (+{len(real_nodes)-8} more)" if len(real_nodes) > 8 else ""
lines += [
@@ -157,11 +176,7 @@ def generate(
lines.append(f"- **{len(isolated)} isolated node(s):** {', '.join(f'`{l}`' for l in isolated_labels)}{suffix}")
lines.append(" These have ≤1 connection - possible missing edges or undocumented components.")
if thin_communities:
for cid, nodes in thin_communities.items():
label = community_labels.get(cid, f"Community {cid}")
node_labels = [G.nodes[n].get("label", n) for n in nodes]
lines.append(f"- **Thin community `{label}`** ({len(nodes)} nodes): {', '.join(f'`{l}`' for l in node_labels)}")
lines.append(" Too small to be a meaningful cluster - may be noise or needs more connections extracted.")
lines.append(f"- **{len(thin_communities)} thin communities (<{min_community_size} nodes) omitted from report** — run `graphify query` to explore isolated nodes.")
if amb_pct > 20:
lines.append(f"- **High ambiguity: {amb_pct}% of edges are AMBIGUOUS.** Review the Ambiguous Edges section above.")
+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"
)
+329 -32
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,9 @@ 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"])
data = {**data, "directed": True}
try:
return json_graph.node_link_graph(data, edges="links")
except TypeError:
@@ -45,25 +49,119 @@ def _strip_diacritics(text: str) -> str:
return "".join(c for c in nfkd if not unicodedata.combining(c))
_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]]:
scored = []
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)
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)
_CONTEXT_HINTS: tuple[tuple[str, tuple[str, ...]], ...] = (
("call", ("call", "calls", "called", "invoke", "invokes", "invoked")),
("import", ("import", "imports", "imported", "module", "modules")),
("field", ("field", "fields", "member", "members", "property", "properties")),
("parameter_type", ("parameter", "parameters", "param", "params", "argument", "arguments")),
("return_type", ("return", "returns", "returned")),
("generic_arg", ("generic", "generics", "template", "templates")),
)
def _normalize_context_filters(filters: list[str] | None) -> list[str]:
if not filters:
return []
normalized: list[str] = []
seen: set[str] = set()
for value in filters:
key = _strip_diacritics(str(value)).strip().lower()
if key and key not in seen:
seen.add(key)
normalized.append(key)
return normalized
def _infer_context_filters(question: str) -> list[str]:
lowered = {
_strip_diacritics(token).lower()
for token in question.replace("?", " ").replace(",", " ").split()
}
inferred: list[str] = []
for context, hints in _CONTEXT_HINTS:
if any(hint in lowered for hint in hints):
inferred.append(context)
return inferred
def _resolve_context_filters(question: str, explicit_filters: list[str] | None = None) -> tuple[list[str], str | None]:
normalized = _normalize_context_filters(explicit_filters)
if normalized:
return normalized, "explicit"
inferred = _infer_context_filters(question)
if inferred:
return inferred, "heuristic"
return [], None
def _filter_graph_by_context(G: nx.Graph, context_filters: list[str] | None) -> nx.Graph:
filters = set(_normalize_context_filters(context_filters))
if not filters:
return G
H = G.__class__()
H.add_nodes_from(G.nodes(data=True))
if isinstance(G, (nx.MultiGraph, nx.MultiDiGraph)):
for u, v, key, data in G.edges(keys=True, data=True):
if data.get("context") in filters:
H.add_edge(u, v, key=key, **data)
else:
for u, v, data in G.edges(data=True):
if data.get("context") in filters:
H.add_edge(u, v, **data)
return H
def _bfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], list[tuple]]:
# Compute hub threshold: nodes above this degree are not expanded as transit.
# p99 of degree distribution, floored at 50 to avoid over-blocking small graphs.
degrees = [G.degree(n) for n in G.nodes()]
if degrees:
degrees_sorted = sorted(degrees)
p99_idx = int(len(degrees_sorted) * 0.99)
hub_threshold = max(50, degrees_sorted[p99_idx])
else:
hub_threshold = 50
seed_set = set(start_nodes)
visited: set[str] = set(start_nodes)
frontier = set(start_nodes)
edges_seen: list[tuple] = []
for _ in range(depth):
next_frontier: set[str] = set()
for n in frontier:
# Don't expand through high-degree hubs (except seeds - a hub that
# is the starting node should still be explored).
if n not in seed_set and G.degree(n) >= hub_threshold:
continue
for neighbor in G.neighbors(n):
if neighbor not in visited:
next_frontier.add(neighbor)
@@ -74,6 +172,14 @@ def _bfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], list[tuple]]:
degrees = [G.degree(n) for n in G.nodes()]
if degrees:
degrees_sorted = sorted(degrees)
p99_idx = int(len(degrees_sorted) * 0.99)
hub_threshold = max(50, degrees_sorted[p99_idx])
else:
hub_threshold = 50
seed_set = set(start_nodes)
visited: set[str] = set()
edges_seen: list[tuple] = []
stack = [(n, 0) for n in reversed(start_nodes)]
@@ -82,6 +188,8 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
if node in visited or d > depth:
continue
visited.add(node)
if node not in seed_set and G.degree(node) >= hub_threshold:
continue
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, d + 1))
@@ -89,19 +197,43 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
return visited, edges_seen
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000) -> str:
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token)."""
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *, seeds: list[str] | None = None) -> str:
"""Render subgraph as text, cutting at token_budget (approx 3 chars/token).
seeds: exact-match nodes rendered first before the degree-sorted expansion,
so the queried symbol always appears at the top of the output.
"""
char_budget = token_budget * 3
lines = []
for nid in sorted(nodes, key=lambda n: G.degree(n), reverse=True):
seed_set = set(seeds or [])
ordered = [n for n in (seeds or []) if n in nodes] + \
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
line = f"EDGE {sanitize_label(G.nodes[u].get('label', u))} --{d.get('relation', '')} [{d.get('confidence', '')}]--> {sanitize_label(G.nodes[v].get('label', v))}"
context = d.get("context")
context_suffix = f" context={sanitize_label(str(context))}" if context else ""
line = (
f"EDGE {sanitize_label(G.nodes[u].get('label', u))} "
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)
output = "\n".join(lines)
if len(output) > char_budget:
@@ -109,12 +241,55 @@ def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_bu
return output
def _query_graph_text(
G: nx.Graph,
question: str,
*,
mode: str = "bfs",
depth: int = 3,
token_budget: int = 2000,
context_filters: list[str] | None = None,
) -> str:
terms = [t.lower() for t in question.split() if len(t) > 2]
scored = _score_nodes(G, terms)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
return "No matching nodes found."
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
traversal_graph = _filter_graph_by_context(G, resolved_filters)
nodes, edges = _dfs(traversal_graph, start_nodes, depth) if mode == "dfs" else _bfs(traversal_graph, start_nodes, depth)
header_parts = [
f"Traversal: {mode.upper()} depth={depth}",
f"Start: {[G.nodes[n].get('label', n) for n in start_nodes]}",
]
if resolved_filters:
header_parts.append(f"Context: {', '.join(resolved_filters)} ({filter_source})")
header_parts.append(f"{len(nodes)} nodes found")
header = " | ".join(header_parts) + "\n\n"
return header + _subgraph_to_text(traversal_graph, nodes, edges, token_budget)
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:
@@ -153,6 +328,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
@@ -175,6 +351,11 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
"description": "bfs=broad context, dfs=trace a specific path"},
"depth": {"type": "integer", "default": 3, "description": "Traversal depth (1-6)"},
"token_budget": {"type": "integer", "default": 2000, "description": "Max output tokens"},
"context_filter": {
"type": "array",
"items": {"type": "string"},
"description": "Optional explicit edge-context filter, e.g. ['call', 'field']",
},
},
"required": ["question"],
},
@@ -239,14 +420,15 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
mode = arguments.get("mode", "bfs")
depth = min(int(arguments.get("depth", 3)), 6)
budget = int(arguments.get("token_budget", 2000))
terms = [t.lower() for t in question.split() if len(t) > 2]
scored = _score_nodes(G, terms)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
return "No matching nodes found."
nodes, edges = _dfs(G, start_nodes, depth) if mode == "dfs" else _bfs(G, start_nodes, depth)
header = f"Traversal: {mode.upper()} depth={depth} | Start: {[G.nodes[n].get('label', n) for n in start_nodes]} | {len(nodes)} nodes found\n\n"
return header + _subgraph_to_text(G, nodes, edges, budget)
context_filter = arguments.get("context_filter")
return _query_graph_text(
G,
question,
mode=mode,
depth=depth,
token_budget=budget,
context_filters=context_filter,
)
def _tool_get_node(arguments: dict) -> str:
label = arguments["label"].lower()
@@ -255,12 +437,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)}",
])
@@ -271,13 +454,25 @@ 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)}:"]
for neighbor in G.neighbors(nid):
d = G.edges[nid, neighbor]
lines = [f"Neighbors of {sanitize_label(G.nodes[nid].get('label', nid))}:"]
for nb in G.successors(nid):
d = edge_data(G, nid, nb)
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[nb].get('label', nb))} "
f"[{sanitize_label(str(rel))}] [{sanitize_label(str(d.get('confidence', '')))}]"
)
for nb in G.predecessors(nid):
d = edge_data(G, nb, nid)
rel = d.get("relation", "")
if rel_filter and rel_filter not in rel.lower():
continue
lines.append(
f" <-- {sanitize_label(G.nodes[nb].get('label', nb))} "
f"[{sanitize_label(str(rel))}] [{sanitize_label(str(d.get('confidence', '')))}]"
)
return "\n".join(lines)
def _tool_get_community(arguments: dict) -> str:
@@ -288,7 +483,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:
@@ -318,9 +517,27 @@ 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)
# Use undirected view for path-finding (works regardless of query src/tgt order)
path_nodes = nx.shortest_path(G.to_undirected(as_view=True), src_nid, tgt_nid)
except (nx.NetworkXNoPath, nx.NodeNotFound):
return f"No path found between '{G.nodes[src_nid].get('label', src_nid)}' and '{G.nodes[tgt_nid].get('label', tgt_nid)}'."
hops = len(path_nodes) - 1
@@ -329,14 +546,23 @@ 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]
if G.has_edge(u, v):
edata = edge_data(G, u, v)
forward = True
else:
edata = edge_data(G, v, u)
forward = False
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)
if forward:
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
else:
segments.append(f"<--{rel}{conf_str}-- {G.nodes[v].get('label', v)}")
prefix = ("\n".join(warnings) + "\n") if warnings else ""
return prefix + f"Shortest path ({hops} hops):\n " + " ".join(segments)
_handlers = {
"query_graph": _tool_query_graph,
@@ -348,6 +574,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)
+32 -6
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.
@@ -235,7 +237,7 @@ Process each file one at a time. For each file:
- INFERRED: reasonable inference (shared structure, implied dependency)
- AMBIGUOUS: uncertain — flag it, do not omit
- Code files: semantic edges AST cannot find. Do not re-extract imports.
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms). Do NOT invent file_types like `concept`. When adding `calls` edges: source is caller, target is callee.
- Image files: use vision — understand what the image IS, not just OCR
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
@@ -244,7 +246,7 @@ Process each file one at a time. For each file:
3. Accumulate results across all files
Schema for each file's output:
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
After processing all files, write the accumulated result to `.graphify_semantic_new.json`.
@@ -254,6 +256,30 @@ For the accumulated result:
If more than half the chunks failed, stop and tell the user.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat .graphify_python) -c "
@@ -928,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)
@@ -1000,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}]')
@@ -1070,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', '')
+32 -6
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.
@@ -235,7 +237,7 @@ Process each file one at a time. For each file:
- INFERRED: reasonable inference (shared structure, implied dependency)
- AMBIGUOUS: uncertain — flag it, do not omit
- Code files: semantic edges AST cannot find. Do not re-extract imports.
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms). Do NOT invent file_types like `concept`. When adding `calls` edges: source is caller, target is callee.
- Image files: use vision — understand what the image IS, not just OCR
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
@@ -244,7 +246,7 @@ Process each file one at a time. For each file:
3. Accumulate results across all files
Schema for each file's output:
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
After processing all files, write the accumulated result to `.graphify_semantic_new.json`.
@@ -254,6 +256,30 @@ For the accumulated result:
If more than half the chunks failed, stop and tell the user.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat .graphify_python) -c "
@@ -928,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)
@@ -1000,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}]')
@@ -1070,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', '')
+32 -6
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.
@@ -263,7 +265,7 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
@@ -300,7 +302,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
```
**Step B3 - Collect, cache, and merge**
@@ -313,6 +315,30 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat .graphify_python) -c "
@@ -987,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)
@@ -1059,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}]')
@@ -1129,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', '')
+36 -7
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.
@@ -259,7 +261,7 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
@@ -296,7 +298,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
```
**Step B3 - Collect, cache, and merge**
@@ -309,6 +311,30 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -819,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)
@@ -1013,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)
@@ -1085,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}]')
@@ -1155,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', '')
+32 -6
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.
@@ -260,7 +262,7 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
@@ -297,7 +299,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
```
**Step B3 - Collect, cache, and merge**
@@ -310,6 +312,30 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat .graphify_python) -c "
@@ -984,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)
@@ -1056,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}]')
@@ -1126,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', '')
+31 -5
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.
@@ -234,7 +236,7 @@ Process each file one at a time. For each file:
- INFERRED: reasonable inference (shared structure, implied dependency)
- AMBIGUOUS: uncertain — flag it, do not omit
- Code files: semantic edges AST cannot find. Do not re-extract imports.
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. When adding `calls` edges: source is caller, target is callee.
- Doc/paper files: named concepts, entities, citations. Store rationale (WHY decisions were made) as a `rationale` attribute on the relevant node, not as a separate node. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms). Do NOT invent file_types like `concept`. When adding `calls` edges: source is caller, target is callee.
- Image files: use vision — understand what the image IS, not just OCR
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
@@ -243,7 +245,7 @@ Process each file one at a time. For each file:
3. Accumulate results across all files
Schema for each file's output:
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
After processing all files, write the accumulated result to `.graphify_semantic_new.json`.
@@ -253,6 +255,30 @@ For the accumulated result:
If more than half the chunks failed, stop and tell the user.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat .graphify_python) -c "
@@ -927,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)
@@ -999,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}]')
@@ -1069,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', '')
+32 -6
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.
@@ -261,7 +263,7 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
@@ -298,7 +300,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
```
**Step B3 - Collect, cache, and merge**
@@ -311,6 +313,30 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -1037,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)
@@ -1109,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}]')
@@ -1179,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', '')
+1209
View File
File diff suppressed because it is too large. Load diff
+33 -7
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.
@@ -250,7 +252,7 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
@@ -287,7 +289,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
```
After all subagents complete, collect their results. For each result:
@@ -306,6 +308,30 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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())
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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))
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat .graphify_python) -c "
@@ -826,7 +852,7 @@ 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}
tokens = {'input': 0, 'output': 0}
communities = cluster(G)
cohesion = score_all(G, communities)
@@ -952,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)
@@ -1024,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}]')
@@ -1093,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', '')
+7 -2
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.
@@ -151,13 +153,16 @@ if cached_path.exists():
all_hyperedges.extend(cached.get('hyperedges', []))
# PASTE each subagent response here as chunk_1, chunk_2, etc.
total_in, total_out = 0, 0
for chunk_json in []: # replace [] with your chunk results
chunk = json.loads(chunk_json) if isinstance(chunk_json, str) else chunk_json
all_nodes.extend(chunk.get('nodes', []))
all_edges.extend(chunk.get('edges', []))
all_hyperedges.extend(chunk.get('hyperedges', []))
total_in += chunk.get('input_tokens', 0)
total_out += chunk.get('output_tokens', 0)
merged = {'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, 'input_tokens': 0, 'output_tokens': 0}
merged = {'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, 'input_tokens': total_in, 'output_tokens': total_out}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
print(f'Merged: {len(all_nodes)} nodes, {len(all_edges)} edges')
"
+282 -149
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-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
'@ | Out-File -FilePath .graphify_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.
@@ -249,7 +283,7 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
@@ -279,14 +313,20 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","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}
{"nodes":[{"id":"filestem_entityname","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}
```
**Step B3 - Collect, cache, and merge**
@@ -299,27 +339,53 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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(encoding=\"utf-8\"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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, 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-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
print(f'Cached {saved} files')
"
'@ | Out-File -FilePath .graphify_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-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', [])
@@ -338,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-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
'@ | Out-File -FilePath .graphify_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`
Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.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']}
@@ -371,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
@@ -391,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)
@@ -405,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 = {
@@ -415,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.
@@ -435,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
@@ -443,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()}
@@ -459,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"}`).
@@ -477,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()}
@@ -504,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()}
@@ -529,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)
@@ -537,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.
@@ -574,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()}
@@ -590,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)
@@ -638,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.
@@ -656,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}
@@ -685,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
```
@@ -730,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.
@@ -769,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
@@ -778,17 +872,38 @@ 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(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]
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')
"
# 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(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.
@@ -796,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
@@ -805,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:
@@ -817,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`
@@ -830,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
@@ -840,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,
@@ -854,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 = {
@@ -863,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).
@@ -883,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.
@@ -901,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'
@@ -971,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.
@@ -1005,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'
@@ -1049,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}]')
@@ -1059,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.
@@ -1078,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'
@@ -1112,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.
@@ -1143,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
@@ -1157,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.
+181 -499
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, videos) to knowledge graph. Use when user asks any question about a codebase, documents, or project content - especially if graphify-out/ exists, treat the question as a /graphify query."
trigger: /graphify
---
@@ -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,12 @@ 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.
> **No other API keys are read.** If `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, fall straight through to Claude Code subagent dispatch (Part B below) — the host session itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key from the environment. If a host agent prompts the user for `ANTHROPIC_API_KEY` to run extraction, that prompt is a misread of this skill — ignore it and dispatch subagents as written.
**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 +225,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 +261,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 +293,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.
@@ -307,7 +317,7 @@ Rules:
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
@@ -337,16 +347,25 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
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.
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. 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):
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image","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}
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","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**
@@ -359,6 +378,30 @@ Wait for all subagents. For each result:
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
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(encoding=\"utf-8\"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
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, ensure_ascii=False), encoding=\"utf-8\")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache:
```bash
$(cat graphify-out/.graphify_python) -c "
@@ -366,7 +409,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')
"
@@ -378,8 +421,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', [])
@@ -398,7 +441,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)')
"
```
@@ -411,8 +454,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']}
@@ -431,7 +474,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)')
@@ -453,8 +496,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)
@@ -467,7 +510,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 = {
@@ -477,7 +520,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.')
@@ -505,9 +548,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()}
@@ -521,8 +564,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')
"
```
@@ -536,84 +579,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)
@@ -623,27 +600,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)
@@ -651,80 +608,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)
@@ -752,15 +656,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.
@@ -777,17 +673,19 @@ 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())
save_manifest(detect['files'])
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
save_manifest(detect.get('all_files') or 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}
@@ -799,7 +697,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)')
@@ -853,7 +751,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
```
@@ -869,8 +767,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)
@@ -878,6 +776,24 @@ print(f'{new_total} new/changed file(s) to re-extract.')
"
```
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
'files': r.get('new_files', {}),
'all_files': r.get('files', {}),
'total_files': r.get('new_total', 0),
'total_words': r.get('total_words', 0),
'skipped_sensitive': r.get('skipped_sensitive', []),
'needs_graph': True,
}, ensure_ascii=False), encoding=\"utf-8\")
"
```
If new files exist, first check whether all changed files are code files:
```bash
@@ -885,8 +801,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)
@@ -902,44 +818,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)
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
# 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 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.
@@ -956,8 +877,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:
@@ -978,45 +899,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).
@@ -1032,113 +918,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:
@@ -1154,66 +939,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:
@@ -1227,56 +957,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.
+1 -1
View File
@@ -58,7 +58,7 @@ def download_audio(url: str, output_dir: Path) -> Path:
# yt-dlp uses %(title)s which can be long/weird — use a stable name based on URL hash
import hashlib
url_hash = hashlib.sha1(url.encode()).hexdigest()[:12]
url_hash = hashlib.sha1(url.encode(), usedforsecurity=False).hexdigest()[:12]
out_template = str(output_dir / f"yt_{url_hash}.%(ext)s")
# Check for already-downloaded file
+580
View File
@@ -0,0 +1,580 @@
"""tree_html — emit a D3 v7 collapsible-tree HTML view of a graph.
A self-contained printable / browseable tree-of-modules view
intended to complement the existing force-directed ``graph.html``.
Key visual elements:
* Expand-all / collapse-all / reset-view buttons.
* Multi-line label wrapping (``wrapText``) with separately-coloured
name and descendant-count.
* Depth-based colour palette (top-level directories get distinct
accent colours; deeper levels follow a level-specific palette).
* Click-to-toggle subtree.
Tree-data shape:
{
"name": "<root label>",
"total_count": <int>,
"children": [ { "name", "total_count", "children": [...] }, ... ]
}
CLI: ``graphify tree [--graph PATH] [--output HTML] [--root PATH]
[--max-children N] [--label NAME]``.
Implementation notes:
- ``total_count`` is the descendant leaf count, so collapsed nodes
can show ``(Total Count: 95)`` without needing the children loaded.
- ``--max-children`` (default 200) caps how many children render
under any one node; a synthetic ``(+N more)`` leaf appears when the
cap fires so very wide directories stay usable.
- The first-level palette is auto-populated from the live top-level
directories so each gets a stable accent colour.
"""
from __future__ import annotations
import html as _html
import json
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Optional
DEFAULT_MAX_CHILDREN = 200
# ── Tree builder (filesystem hierarchy → JSON) ──────────────────
def _common_root(paths: List[str]) -> str:
if not paths:
return ""
parts = [Path(p).parts for p in paths if p]
if not parts:
return ""
common = parts[0]
for p in parts[1:]:
i = 0
while i < len(common) and i < len(p) and common[i] == p[i]:
i += 1
common = common[:i]
return str(Path(*common)) if common else ""
def _make_truncation_leaf(extra: int) -> Dict[str, Any]:
return {"name": f"(+{extra} more)", "total_count": extra, "children": []}
def build_tree(
graph: Dict[str, Any],
*,
root: Optional[str] = None,
max_children: int = DEFAULT_MAX_CHILDREN,
project_label: Optional[str] = None,
) -> Dict[str, Any]:
"""Build a ``{name, total_count, children}`` hierarchy.
Each leaf is either a code symbol (class / top-level function) or
a synthetic "(+N more)" placeholder for truncated wide directories.
Each interior node carries ``total_count = sum of leaf counts``.
"""
nodes: List[Dict[str, Any]] = list(graph.get("nodes", []))
file_nodes = [n for n in nodes if n.get("source_file")]
if not file_nodes:
return {"name": "(empty graph)", "total_count": 0, "children": []}
if root is None:
root = _common_root([n["source_file"] for n in file_nodes])
root_path = Path(root)
by_file: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
for n in file_nodes:
by_file[n["source_file"]].append(n)
# Build dir tree.
dir_index: Dict[str, Dict[str, Any]] = {}
label_root = project_label or root_path.name or root or "/"
root_node: Dict[str, Any] = {
"name": label_root, "total_count": 0, "children": [],
}
dir_index[str(root_path)] = root_node
def _ensure_dir(abs_path: Path) -> Dict[str, Any]:
key = str(abs_path)
if key in dir_index:
return dir_index[key]
if abs_path == abs_path.parent:
return root_node
parent = (_ensure_dir(abs_path.parent)
if abs_path.parent != abs_path else root_node)
node = {"name": abs_path.name, "total_count": 0, "children": []}
dir_index[key] = node
parent["children"].append(node)
return node
for src_file, syms in sorted(by_file.items()):
src_path = Path(src_file)
try:
rel = src_path.relative_to(root_path)
parent_path = (root_path / rel).parent
except ValueError:
parent_path = root_path
parent_dir = _ensure_dir(parent_path)
# File node — children are the symbols.
sym_children: List[Dict[str, Any]] = []
for n in syms:
label = n.get("label", n.get("id", "?"))
# Skip the redundant file-name node graphify emits.
if label == src_path.name and n.get("file_type") == "code":
continue
sym_children.append({
"name": label,
"total_count": 1,
"children": [],
})
# Sort: code symbols first by name, then anything else.
sym_children.sort(key=lambda c: (
c["name"].startswith("_"),
c["name"].lower(),
))
if len(sym_children) > max_children:
extra = len(sym_children) - max_children
sym_children = sym_children[:max_children] + [
_make_truncation_leaf(extra),
]
file_node = {
"name": src_path.name,
"total_count": len(sym_children) or 1,
"children": sym_children,
}
parent_dir["children"].append(file_node)
# Sort each dir's children + propagate total_count up.
def _finalise(d: Dict[str, Any]) -> int:
kids = d.get("children") or []
kids.sort(key=lambda c: (
0 if (c.get("children") and len(c["children"]) > 0) else 1,
c["name"].lower(),
))
if not kids:
return d.get("total_count") or 1
n = 0
for c in kids:
n += _finalise(c)
d["total_count"] = n or 1
return d["total_count"]
_finalise(root_node)
return root_node
# ── HTML emitter (single-data-blob substitution) ──────────────────
# We emit a Python f-string with literal CSS/JS braces escaped as {{ }}.
_HTML_TEMPLATE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title}</title>
<style>
body {{
font-family: 'Segoe UI', sans-serif;
margin: 0;
padding: 0;
background: #f9f9f9;
color: #333;
}}
h1 {{
margin: 20px 0 0 24px;
font-size: 2.2rem;
font-weight: bold;
color: #1e3a56;
}}
.controls {{
margin: 20px 0 15px 24px;
}}
button {{
margin-right: 10px;
padding: 8px 18px;
background: #007bff;
color: #fff;
border: none;
border-radius: 5px;
font-size: 0.95rem;
cursor: pointer;
transition: background 0.2s ease-in-out;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}}
button:hover {{
background: #0056b3;
}}
button:active {{
background: #004085;
}}
#tree-container {{
width: calc(100vw - 48px); /* Adjust for body margin/padding */
height: 85vh;
overflow: auto;
border-radius: 8px;
background: #fff;
margin-left: 24px;
margin-right: 24px;
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
border: 1px solid #ddd;
}}
svg {{
background: #fff;
border-radius: 8px;
display: block; /* Important for D3 */
}}
.node circle {{
stroke-width: 2.5px;
}}
.node text {{ /* Base style for the <text> container */
font: 13px 'Segoe UI', sans-serif;
paint-order: stroke fill; /* Ensures text is readable over lines */
stroke: #fff; /* White halo */
stroke-width: 3px; /* Halo thickness */
stroke-linejoin: round;
stroke-opacity: 0.85; /* Halo opacity */
}}
.link {{
fill: none;
stroke-opacity: 0.7;
stroke-width: 2px;
}}
</style>
</head>
<body>
<h1>{header}</h1>
<div class="controls">
<button onclick="expandAll()">Expand All</button>
<button onclick="collapseAll()">Collapse All</button>
<button onclick="resetView()">Reset View</button>
</div>
<div id="tree-container">
<svg id="tree-svg" width="{svg_width}" height="{svg_height}"></svg>
</div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
const initialJsonData = {data_json};
function transformData(jsonData) {{
// Helper function to recursively build the children structure
function processNode(node, parentL1StageName) {{
let displayName = node.name;
// Append total_count if it exists and is not already in the name
if (node.total_count !== undefined) {{
if (!/\(Total Count: \d+\)$/.test(displayName)) {{
displayName += ` (Total Count: ${{node.total_count}})`;
}}
}}
const newNode = {{ name: displayName }};
if (parentL1StageName === "Root") {{
newNode.originalStageName = node.name;
}} else {{
newNode.originalStageName = parentL1StageName;
}}
if (node.children && node.children.length > 0) {{
const stageNameToPass = (parentL1StageName === "Root") ? node.name : parentL1StageName;
newNode.children = node.children.map(child => processNode(child, stageNameToPass));
}}
return newNode;
}}
let rootDisplayName = jsonData.name;
if (jsonData.total_count !== undefined && !/\(Total Count: \d+\)$/.test(rootDisplayName)) {{
rootDisplayName += ` (Total Count: ${{jsonData.total_count}})`;
}}
return {{
name: rootDisplayName,
originalStageName: "Root",
children: (jsonData.children || []).map(child => processNode(child, "Root"))
}};
}}
const treeData = transformData(initialJsonData);
// Auto-populated phaseColors: every depth-1 child of the root gets
// a stable colour from a bigger palette so all top-level dirs are
// distinguishable.
const PALETTE = [
["#3498DB","#2980B9","#AED6F1"], ["#2ECC71","#27AE60","#A9DFBF"],
["#E74C3C","#C0392B","#F5B7B1"], ["#9B59B6","#8E44AD","#D7BDE2"],
["#F39C12","#D68910","#FAD7A0"], ["#1ABC9C","#117864","#A2D9CE"],
["#34495E","#1B2631","#ABB2B9"], ["#E67E22","#BA4A00","#F5CBA7"],
["#16A085","#0E6655","#A2D9CE"], ["#D35400","#A04000","#EDBB99"],
["#7F8C8D","#566573","#D5DBDB"], ["#C0392B","#7B241C","#F5B7B1"],
["#2E86C1","#1B4F72","#A9CCE3"], ["#28B463","#196F3D","#A9DFBF"],
["#AF7AC5","#6C3483","#D2B4DE"],
];
const phaseColors = {{ "Root": {{ fill: "#4A4A4A", stroke: "#333333", collapsedFill: "#6C757D" }},
"Default": {{ fill: "#BDC3C7", stroke: "#95A5A6", collapsedFill: "#ECF0F1" }} }};
(initialJsonData.children || []).forEach((c, i) => {{
const pal = PALETTE[i % PALETTE.length];
phaseColors[c.name] = {{ fill: pal[0], stroke: pal[1], collapsedFill: pal[2] }};
}});
const levelSpecificPalettes = {{
0: {{ fill: "#4A4A4A", stroke: "#333333", collapsedFill: "#6C757D" }},
2: {{ fill: "#6ab04c", stroke: "#508a38", collapsedFill: "#a3d391" }},
3: {{ fill: "#f0932b", stroke: "#d0730f", collapsedFill: "#f6c07e" }},
4: {{ fill: "#be2edd", stroke: "#a01cb3", collapsedFill: "#e08bf2" }},
5: {{ fill: "#00a8ff", stroke: "#007ac1", collapsedFill: "#74d2ff" }},
6: {{ fill: "#e55039", stroke: "#c23620", collapsedFill: "#f09a8d" }},
default: {{ fill: "#747d8c", stroke: "#57606f", collapsedFill: "#a4b0be" }}
}};
const svgElement = d3.select("#tree-svg");
const initialSvgWidth = +svgElement.attr("width");
const initialSvgHeight = +svgElement.attr("height");
const margin = {{ top: 40, right: 120, bottom: 80, left: 450 }};
let width = initialSvgWidth - margin.left - margin.right;
let height = initialSvgHeight - margin.top - margin.bottom;
const duration = 500;
let nodeCounter = 0;
const g = svgElement.append("g").attr("transform", `translate(${{margin.left}},${{margin.top}})`);
const treemap = d3.tree().nodeSize([40, 0]);
let rootNode = d3.hierarchy(treeData, d => d.children);
rootNode.x0 = 0;
rootNode.y0 = 0;
if (rootNode.children) {{
rootNode.children.forEach(d_child => {{
if (d_child.children) {{ collapseBranch(d_child); }}
}});
}}
updateTree(rootNode);
function collapseBranch(d) {{ if (d.children) {{ d._children = d.children; d._children.forEach(collapseBranch); d.children = null; }} }}
function expandBranch(d) {{ if (d._children) {{ d.children = d._children; d._children = null; }} if (d.children) {{ d.children.forEach(expandBranch); }} }}
window.expandAll = () => {{ expandBranch(rootNode); updateTree(rootNode); }};
window.collapseAll = () => {{ if (rootNode.children) {{ rootNode.children.forEach(collapseBranch); }} updateTree(rootNode); }};
window.resetView = () => {{ if (rootNode.children) {{ rootNode.children.forEach(d_child => {{ if (d_child.children || d_child._children) {{ collapseBranch(d_child); }} }}); }} if (rootNode._children && !rootNode.children) {{ rootNode.children = rootNode._children; rootNode._children = null; }} updateTree(rootNode); }};
function updateTree(source) {{
const treeLayoutData = treemap(rootNode);
let nodes = treeLayoutData.descendants();
let links = treeLayoutData.descendants().slice(1);
let minX = 0;
let maxX = 0;
if (nodes.length > 0) {{
minX = d3.min(nodes, d => d.x);
maxX = d3.max(nodes, d => d.x);
}}
let neededHeight = Math.max(initialSvgHeight, maxX - minX + margin.top + margin.bottom + 100);
svgElement.transition().duration(duration / 2).attr("height", neededHeight);
g.transition().duration(duration / 2).attr("transform", `translate(${{margin.left}},${{margin.top - minX + 40}})`);
nodes.forEach(d => {{ d.y = d.depth * 400; }}); // Adjust horizontal separation if needed
const node = g.selectAll('g.node').data(nodes, d => d.id || (d.id = ++nodeCounter));
const nodeEnter = node.enter().append('g')
.attr('class', d => "node" + (d.children || d._children ? " node--internal" : " node--leaf") + (d._children ? " _children" : ""))
.attr('transform', d => `translate(${{source.y0}},${{source.x0}})`)
.on('click', (event, d) => {{ if (d.children) {{ d._children = d.children; d.children = null; }} else if (d._children) {{ d.children = d._children; d._children = null; }} updateTree(d); }})
.style('cursor', d => (d.children || d._children) ? 'pointer' : 'default');
nodeEnter.append('circle').attr('r', 1e-6);
nodeEnter.append('text')
.attr('dy', '.35em')
.attr('x', d => d.children || d._children ? -14 : 14)
.attr('text-anchor', d => d.children || d._children ? 'end' : 'start')
.style("fill-opacity", 1e-6)
.call(wrapText, 380);
const nodeUpdate = nodeEnter.merge(node);
nodeUpdate.transition().duration(duration)
.attr('transform', d => `translate(${{d.y}},${{d.x}})`)
.attr('class', d => "node" + (d.children ? " node--internal" : " node--leaf") + (d._children ? " node--internal _children" : ""));
nodeUpdate.select('circle').attr('r', 8.5)
.style('fill', d => {{
let palette;
if (d.depth === 0) {{
palette = levelSpecificPalettes[0];
}} else if (d.depth === 1) {{
palette = phaseColors[d.data.originalStageName] || phaseColors.Default;
}} else {{
palette = levelSpecificPalettes[d.depth] || levelSpecificPalettes.default;
}}
if (d._children) return palette.collapsedFill;
if (d.children) return palette.fill;
return "#fff";
}})
.style('stroke', d => {{
let palette;
if (d.depth === 0) {{
palette = levelSpecificPalettes[0];
}} else if (d.depth === 1) {{
palette = phaseColors[d.data.originalStageName] || phaseColors.Default;
}} else {{
palette = levelSpecificPalettes[d.depth] || levelSpecificPalettes.default;
}}
return palette.stroke;
}});
nodeUpdate.select('text').style("fill-opacity", 1).call(wrapText, 380);
const nodeExit = node.exit().transition().duration(duration).attr('transform', d => `translate(${{source.y}},${{source.x}})`).remove();
nodeExit.select('circle').attr('r', 1e-6);
nodeExit.select('text').style('fill-opacity', 1e-6);
const link = g.selectAll('path.link').data(links, d => d.id);
const linkEnter = link.enter().insert('path', "g").attr('class', 'link').attr('d', d => {{ const o = {{ x: source.x0, y: source.y0 }}; return diagonal(o, o); }});
linkEnter.merge(link).transition().duration(duration).attr('d', d => diagonal(d, d.parent))
.style('stroke', d => {{
const sourceNode = d.parent;
if (!sourceNode) return phaseColors.Default.stroke;
const l1AncestorName = sourceNode.data.originalStageName;
const colorPalette = phaseColors[l1AncestorName] || phaseColors.Default;
return colorPalette.stroke;
}});
link.exit().transition().duration(duration).attr('d', d => {{ const o = {{ x: source.x, y: source.y }}; return diagonal(o, o); }}).remove();
nodes.forEach(d => {{ d.x0 = d.x; d.y0 = d.y; }});
}}
function diagonal(s, d) {{ return `M ${{s.y}} ${{s.x}} C ${{(s.y + d.y) / 2}} ${{s.x}}, ${{(s.y + d.y) / 2}} ${{d.x}}, ${{d.y}} ${{d.x}}`; }}
function wrapText(textElements, maxWidth) {{
const textPartColors = {{
name: '#343a40',
count: '#0056b3'
}};
const countRegex = /(\s\(Total Count: \d+\))$/;
textElements.each(function () {{
const textD3 = d3.select(this);
const originalNodeText = textD3.datum().data.name;
const x = parseFloat(textD3.attr("x") || 0);
const initialDy = textD3.attr("dy");
const textAnchor = textD3.attr("text-anchor");
const lineHeight = 1.1;
textD3.text(null);
let namePart = originalNodeText;
let countPartText = "";
const countMatch = originalNodeText.match(countRegex);
if (countMatch && originalNodeText.endsWith(countMatch[0])) {{
namePart = originalNodeText.substring(0, originalNodeText.length - countMatch[0].length).trim();
countPartText = countMatch[0].trim();
}}
const tokens = [];
namePart.split(/\s+/).filter(Boolean).forEach(word => {{
tokens.push({{ text: word, type: 'name' }});
}});
if (countPartText) {{
tokens.push({{ text: countPartText, type: 'count' }});
}}
if (tokens.length === 0 && originalNodeText) {{
tokens.push({{ text: originalNodeText, type: 'name' }});
}}
let currentTspan = textD3.append("tspan").attr("x", x).attr("dy", initialDy);
if (textAnchor === "end") currentTspan.attr("text-anchor", "end");
let lineTokens = [];
for (let i = 0; i < tokens.length; i++) {{
const tokenObj = tokens[i];
lineTokens.push(tokenObj);
currentTspan.text(lineTokens.map(t => t.text).join(" "));
if (currentTspan.node().getComputedTextLength() > maxWidth && lineTokens.length > 1) {{
lineTokens.pop();
currentTspan.text(null);
lineTokens.forEach((prevToken, idx) => {{
currentTspan.append("tspan")
.text((idx > 0 ? " " : "") + prevToken.text)
.style("fill", textPartColors[prevToken.type] || textPartColors.name)
.style("font-weight", prevToken.type === 'count' ? "bold" : "normal");
}});
lineTokens = [tokenObj];
currentTspan = textD3.append("tspan").attr("x", x).attr("dy", lineHeight + "em");
if (textAnchor === "end") currentTspan.attr("text-anchor", "end");
}}
}}
currentTspan.text(null);
lineTokens.forEach((token, idx) => {{
currentTspan.append("tspan")
.text((idx > 0 ? " " : "") + token.text)
.style("fill", textPartColors[token.type] || textPartColors.name)
.style("font-weight", token.type === 'count' ? "bold" : "normal");
}});
if (textD3.selectAll("tspan > tspan").empty() && textD3.select("tspan").text().length === 0 && originalNodeText) {{
let t = textD3.select("tspan");
let displayText = originalNodeText;
t.text(displayText).style("fill", textPartColors.name);
if (t.node() && t.node().getComputedTextLength() > maxWidth && displayText.length > 20) {{
let estimatedChars = Math.floor(maxWidth / (t.node().getComputedTextLength()/displayText.length) );
displayText = displayText.substring(0, Math.max(0, estimatedChars - 3)) + "...";
t.text(displayText);
}}
}}
}});
}}
</script>
</body>
</html>
"""
def emit_html(
tree: Dict[str, Any],
*,
title: str,
header: str,
svg_width: int = 6000,
svg_height: int = 8000,
) -> str:
# Escape </script> sequences so embedded JSON cannot break out of the
# <script> tag, and HTML-escape values that land in <title>/<h1>.
data_json = json.dumps(tree, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
return _HTML_TEMPLATE.format(
title=_html.escape(title),
header=_html.escape(header),
svg_width=svg_width,
svg_height=svg_height,
data_json=data_json,
)
def write_tree_html(
graph_path: Path,
output_path: Path,
*,
root: Optional[str] = None,
max_children: int = DEFAULT_MAX_CHILDREN,
project_label: Optional[str] = None,
# kept for CLI compatibility with the older signature; ignored now
top_k_edges: int = 0,
) -> Path:
graph = json.loads(graph_path.read_text(encoding="utf-8"))
tree = build_tree(graph, root=root, max_children=max_children,
project_label=project_label)
title = f"{tree['name']} — graphify tree viewer"
header = f"{tree['name']} — Knowledge Graph"
html = emit_html(tree, title=title, header=header)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(html, encoding="utf-8")
return output_path
+503 -42
View File
@@ -1,10 +1,113 @@
# monitor a folder and auto-trigger --update when files change
from __future__ import annotations
import contextlib
import json
import os
import re
import sys
import time
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).
While the lock is held, ``.rebuild.lock`` contains the owning PID followed
by a newline so external pollers (publish scripts, etc.) can read it.
On successful release the file is unlinked so downstream tooling that
waits for the lock to clear by polling for its absence unblocks promptly.
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"
# "a+" creates the file if missing without truncating an existing holder's
# PID payload — important because another process may have already written
# its PID before we attempt the flock.
fh = open(lock_path, "a+", encoding="utf-8")
acquired = False
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
acquired = True
# Replace any prior owner's PID with ours so external readers see a
# single parseable line, not a digit-concatenation across rebuilds.
try:
fh.seek(0)
fh.truncate()
fh.write(f"{os.getpid()}\n")
fh.flush()
except OSError:
pass
yield True
finally:
if acquired:
try:
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
except OSError:
pass
fh.close()
# Signal "rebuild done" by removing the lock file. Only the holder
# unlinks; a non-acquiring caller leaves the existing lock in place.
if acquired:
with contextlib.suppress(OSError):
lock_path.unlink()
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
@@ -33,19 +136,191 @@ def _relativize_source_files(payload: dict, root: Path) -> None:
continue
def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
"""Re-run AST extraction + build + cluster + report for code files. No LLM needed.
def _node_community_map(graph_data: dict) -> dict[str, int]:
out: dict[str, int] = {}
for node in graph_data.get("nodes", []):
node_id = node.get("id")
cid = node.get("community")
if node_id is None or cid is None:
continue
try:
out[str(node_id)] = int(cid)
except (TypeError, ValueError):
print(
f"[graphify watch] Skipping node with invalid community id: "
f"node_id={node_id!r} community={cid!r}",
file=sys.stderr,
)
continue
return out
Returns True on success, False on error.
def _canonical_graph_for_compare(graph_data: dict) -> dict:
canonical = dict(graph_data)
canonical.pop("built_at_commit", None)
for key in ("nodes", "links", "edges", "hyperedges"):
if key in canonical and isinstance(canonical[key], list):
canonical[key] = sorted(
canonical[key],
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
)
return canonical
def _canonical_topology_for_compare(graph_data: dict) -> dict:
canonical = dict(graph_data)
canonical.pop("built_at_commit", None)
nodes = canonical.get("nodes")
if isinstance(nodes, list):
norm_nodes = []
for node in nodes:
if not isinstance(node, dict):
continue
n = dict(node)
n.pop("community", None)
n.pop("norm_label", None)
norm_nodes.append(n)
canonical["nodes"] = sorted(
norm_nodes,
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
)
for key in ("links", "edges"):
items = canonical.get(key)
if not isinstance(items, list):
continue
norm_edges = []
for edge in items:
if not isinstance(edge, dict):
continue
e = dict(edge)
# to_json writes _src/_tgt as the canonical directed endpoints and
# overwrites source/target with them before serialising, so the
# on-disk graph has no _src/_tgt. The candidate topology (fresh from
# node_link_data) still has them. Popping and reassigning here makes
# both sides comparable: existing gets no-op pops (None), candidate
# gets source/target overwritten from _src/_tgt — same result.
true_src = e.pop("_src", None)
true_tgt = e.pop("_tgt", None)
if true_src is not None and true_tgt is not None:
e["source"] = true_src
e["target"] = true_tgt
e.pop("confidence_score", None)
norm_edges.append(e)
canonical[key] = sorted(
norm_edges,
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
)
hyperedges = canonical.get("hyperedges")
if isinstance(hyperedges, list):
canonical["hyperedges"] = sorted(
hyperedges,
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
)
return canonical
def _topology_from_graph(G) -> dict:
from networkx.readwrite import json_graph
try:
data = json_graph.node_link_data(G, edges="links")
except TypeError:
data = json_graph.node_link_data(G)
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
return data
def _check_shrink(force: bool, existing_data: dict, new_data: dict, tmp: "Path | None" = None) -> bool:
"""Return True (ok to proceed) or False (shrink refused).
When False, cleans up *tmp* if provided and prints a warning to stderr.
"""
if force or not existing_data:
return True
existing_n = len(existing_data.get("nodes", []))
new_n = len(new_data.get("nodes", []))
if new_n < existing_n:
if tmp is not None:
tmp.unlink(missing_ok=True)
print(
f"[graphify] WARNING: new graph has {new_n} nodes but existing "
f"graph.json has {existing_n}. Refusing to overwrite — you may be "
f"missing chunk files from a previous session. "
f"Pass --force to override.",
file=sys.stderr,
)
return False
return True
def _report_for_compare(report_text: str) -> str:
return re.sub(r"^- Built from commit: `[^`]+`\n?", "", report_text, flags=re.MULTILINE)
def _json_text(data: dict) -> str:
return json.dumps(data, indent=2, ensure_ascii=False) + "\n"
def _rebuild_code(
watch_path: Path,
*,
changed_paths: list[Path] | None = None,
follow_symlinks: bool = False,
force: bool = False,
no_cluster: bool = False,
acquire_lock: bool = True,
block_on_lock: bool = False,
) -> bool:
"""Re-run AST extraction + build + optional 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.
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).
``no_cluster`` skips community detection and writes raw merged extraction
JSON to graphify-out/graph.json (mirrors ``extract --no-cluster``).
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,
no_cluster=no_cluster,
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
from graphify.cluster import cluster, remap_communities_to_previous, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json, to_html
@@ -53,27 +328,83 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
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 code nodes; doc/paper/image nodes are kept.
out = watch_path / "graphify-out"
# 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.
# 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"
existing_graph_data: dict = {}
if existing_graph.exists():
try:
existing = json.loads(existing_graph.read_text(encoding="utf-8"))
code_ids = {n["id"] for n in existing.get("nodes", []) if n.get("file_type") == "code"}
sem_nodes = [n for n in existing.get("nodes", []) if n.get("file_type") != "code"]
sem_edges = [e for e in existing.get("links", existing.get("edges", []))
if e.get("confidence") in ("INFERRED", "AMBIGUOUS")
or (e.get("source") not in code_ids and e.get("target") not in code_ids)]
existing_graph_data = existing
new_ast_ids = {n["id"] for n in result["nodes"]}
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", []))
if e.get("source") in all_ids and e.get("target") in all_ids
]
result = {
"nodes": result["nodes"] + sem_nodes,
"edges": result["edges"] + sem_edges,
"nodes": result["nodes"] + preserved_nodes,
"edges": result["edges"] + preserved_edges,
"hyperedges": existing.get("hyperedges", []),
"input_tokens": 0,
"output_tokens": 0,
@@ -82,6 +413,51 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
pass # corrupt graph.json - proceed with AST-only
_relativize_source_files(result, project_root)
out.mkdir(exist_ok=True)
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
if no_cluster:
# Normalise to "links" key so schema is consistent with the full clustered path.
candidate_graph_data = {
**{k: v for k, v in result.items() if k != "edges"},
"links": result.get("edges", []),
}
candidate_graph_text = _json_text(candidate_graph_data)
same_graph = False
if existing_graph.exists():
try:
existing_payload = json.loads(existing_graph.read_text(encoding="utf-8"))
same_graph = (
json.dumps(_canonical_graph_for_compare(existing_payload), sort_keys=True, ensure_ascii=False)
== json.dumps(_canonical_graph_for_compare(candidate_graph_data), sort_keys=True, ensure_ascii=False)
)
except Exception:
same_graph = False
if not same_graph:
if not _check_shrink(force, existing_graph_data, candidate_graph_data):
return False
existing_graph.write_text(candidate_graph_text, encoding="utf-8")
try:
from graphify.detect import save_manifest
save_manifest(detected["files"], kind="ast")
except Exception:
pass
# clear stale needs_update flag if present
flag = out / "needs_update"
if flag.exists():
flag.unlink()
if same_graph:
print("[graphify watch] No code-graph changes detected (--no-cluster); outputs left untouched.")
else:
print(
"[graphify watch] Rebuilt (no clustering): "
f"{len(result.get('nodes', []))} nodes, {len(result.get('edges', []))} edges"
)
print(f"[graphify watch] graph.json updated in {out}")
return True
detection = {
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
@@ -90,45 +466,128 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
}
G = build_from_json(result)
candidate_topology = _topology_from_graph(G)
if existing_graph_data:
try:
same_topology = (
json.dumps(_canonical_topology_for_compare(existing_graph_data), sort_keys=True, ensure_ascii=False)
== json.dumps(_canonical_topology_for_compare(candidate_topology), sort_keys=True, ensure_ascii=False)
)
except Exception:
same_topology = False
if same_topology:
try:
from graphify.detect import save_manifest
save_manifest(detected["files"], kind="ast")
except Exception:
pass
flag = out / "needs_update"
if flag.exists():
flag.unlink()
print("[graphify watch] No code-graph topology changes detected; outputs left untouched.")
return True
communities = cluster(G)
previous_node_community = _node_community_map(existing_graph_data)
if previous_node_community:
communities = remap_communities_to_previous(communities, previous_node_community)
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"))
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
{"input": 0, "output": 0}, report_root, suggested_questions=questions,
built_at_commit=commit)
report_path = out / "GRAPH_REPORT.md"
labels_json = json.dumps({str(k): v for k, v in sorted(labels.items())}, ensure_ascii=False, indent=2) + "\n"
graph_tmp = out / ".graph.tmp.json"
json_written = to_json(G, communities, str(graph_tmp), force=True, built_at_commit=commit)
if not json_written:
return False
candidate_graph_data = json.loads(graph_tmp.read_text(encoding="utf-8"))
same_graph = False
same_report = False
if existing_graph.exists():
try:
existing_payload = json.loads(existing_graph.read_text(encoding="utf-8"))
same_graph = (
json.dumps(_canonical_graph_for_compare(existing_payload), sort_keys=True, ensure_ascii=False)
== json.dumps(_canonical_graph_for_compare(candidate_graph_data), sort_keys=True, ensure_ascii=False)
)
except Exception:
same_graph = False
if report_path.exists():
old_report = report_path.read_text(encoding="utf-8")
same_report = _report_for_compare(old_report) == _report_for_compare(report)
no_change = same_graph and same_report
if no_change:
graph_tmp.unlink(missing_ok=True)
print("[graphify watch] No code-graph changes detected; graph.json/GRAPH_REPORT.md left untouched.")
else:
if not _check_shrink(force, existing_graph_data, candidate_graph_data, tmp=graph_tmp):
return False
graph_tmp.replace(existing_graph)
report_path.write_text(report, encoding="utf-8")
labels_file.write_text(labels_json, encoding="utf-8")
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
{"input": 0, "output": 0}, report_root, suggested_questions=questions)
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
try:
from graphify.detect import save_manifest
save_manifest(detected["files"], kind="ast")
except Exception:
pass
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
# Wrap so core outputs (graph.json + GRAPH_REPORT.md) always land.
html_written = False
try:
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
html_written = True
except ValueError as viz_err:
print(f"[graphify watch] Skipped graph.html: {viz_err}")
stale = out / "graph.html"
if stale.exists():
stale.unlink()
if not no_change:
try:
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
html_written = True
except ValueError as viz_err:
print(f"[graphify watch] Skipped graph.html: {viz_err}")
stale = out / "graph.html"
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 and not no_change:
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():
flag.unlink()
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"
print(f"[graphify watch] {products} updated in {out}")
if not no_change:
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
except Exception as exc:
@@ -144,7 +603,7 @@ def check_update(watch_path: Path) -> bool:
re-extraction via `/graphify --update` — this function only signals
that the update is needed.
"""
flag = Path(watch_path) / "graphify-out" / "needs_update"
flag = Path(watch_path) / _GRAPHIFY_OUT / "needs_update"
if flag.exists():
print(f"[graphify check-update] Pending non-code changes in {watch_path}.")
print("[graphify check-update] Run `/graphify --update` to apply semantic re-extraction.")
@@ -153,7 +612,7 @@ def check_update(watch_path: Path) -> bool:
def _notify_only(watch_path: Path) -> None:
"""Write a flag file and print a notification (fallback for non-code-only corpora)."""
flag = watch_path / "graphify-out" / "needs_update"
flag = watch_path / _GRAPHIFY_OUT / "needs_update"
flag.parent.mkdir(parents=True, exist_ok=True)
flag.write_text("1", encoding="utf-8")
print(f"\n[graphify watch] New or changed files detected in {watch_path}")
@@ -198,7 +657,7 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
return
if any(part.startswith(".") for part in path.parts):
return
if "graphify-out" in path.parts:
if _GRAPHIFY_OUT in path.parts:
return
last_trigger = time.monotonic()
pending = True
@@ -223,10 +682,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:
+31 -3
View File
@@ -5,9 +5,22 @@ from collections import Counter
from pathlib import Path
import networkx as nx
from graphify.build import edge_data
def _safe_filename(name: str) -> str:
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
"""Make a label safe for use as a filename across platforms.
Substitutes characters that Windows reserves in filenames
(< > : " / \\ | ? *) and strips trailing dots/spaces, also reserved.
Falls back to 'unnamed' for empty results and caps length at 200
chars to stay well under common filesystem limits.
"""
import re
s = name.replace("/", "-").replace(" ", "_").replace(":", "-")
s = re.sub(r'[<>:"/\\|?*]', '_', s)
s = s.strip('. ')
return s[:200] if s else 'unnamed'
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
@@ -37,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
@@ -107,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", "")
@@ -185,6 +198,21 @@ 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
# (e.g. "AutoAgent Skills" → "AutoAgent Methodology"), leaving the previous file
# as an orphan. Since to_wiki() owns wiki/ entirely (always writes the full set),
# it can safely clear .md files at the start of each call.
for old_article in out.glob("*.md"):
old_article.unlink()
labels = community_labels or {cid: f"Community {cid}" for cid in communities}
cohesion = cohesion or {}
god_nodes_data = god_nodes_data or []
+23 -10
View File
@@ -4,14 +4,16 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.5.7"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
version = "0.7.19"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "pi", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
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]
@@ -44,14 +48,20 @@ Issues = "https://github.com/safishamsi/graphify/issues"
[project.optional-dependencies]
mcp = ["mcp"]
neo4j = ["neo4j"]
pdf = ["pypdf", "html2text"]
pdf = ["pypdf", "markdownify"]
watch = ["watchdog"]
svg = ["matplotlib"]
leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
google = ["openpyxl"]
video = ["faster-whisper", "yt-dlp"]
kimi = ["openai"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai"]
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", "boto3", "tree-sitter-sql"]
[project.scripts]
graphify = "graphify.__main__:main"
@@ -61,9 +71,12 @@ graphify = "graphify.__main__:main"
# Run without installing: uvx graphifyy install
package = true
[tool.setuptools.packages.find]
where = ["."]
include = ["graphify*"]
[tool.setuptools]
packages = ["graphify"]
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"]
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"]
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Benchmark: sequential vs parallel AST extraction.
Usage:
python tests/bench_extract.py [path-to-repo]
Defaults to the current directory if no path is given.
Clears the AST cache between runs so every file is re-extracted.
Example output:
=== Graphify AST Extraction Benchmark ===
Files: 1,247
Languages: Python (412), TypeScript (389), Go (201), ...
Sequential: 4.32s (8,934 nodes, 12,456 edges)
Parallel (8): 1.28s (8,934 nodes, 12,456 edges)
Speedup: 3.38x
Results: ✓ identical
"""
from __future__ import annotations
import sys
import time
from collections import Counter
from pathlib import Path
# Ensure the project root is importable
_project_root = Path(__file__).resolve().parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
from graphify.extract import extract, collect_files
from graphify.cache import clear_cache
def _count_by_ext(paths: list[Path]) -> dict[str, int]:
"""Count files by extension."""
counter: Counter[str] = Counter()
for p in paths:
ext = p.suffix.lower()
counter[ext] += 1
return dict(counter.most_common())
_EXT_NAMES: dict[str, str] = {
".py": "Python",
".js": "JavaScript",
".jsx": "JSX",
".mjs": "MJS",
".ts": "TypeScript",
".tsx": "TSX",
".go": "Go",
".rs": "Rust",
".java": "Java",
".c": "C",
".h": "C Header",
".cpp": "C++",
".cc": "C++",
".cxx": "C++",
".hpp": "C++ Header",
".rb": "Ruby",
".cs": "C#",
".kt": "Kotlin",
".kts": "Kotlin Script",
".scala": "Scala",
".php": "PHP",
".swift": "Swift",
".lua": "Lua",
".toc": "Lua TOC",
".zig": "Zig",
".ps1": "PowerShell",
".ex": "Elixir",
".exs": "Elixir Script",
".m": "Obj-C",
".mm": "Obj-C++",
".jl": "Julia",
".vue": "Vue",
".svelte": "Svelte",
".dart": "Dart",
".v": "Verilog",
".sv": "SystemVerilog",
".sql": "SQL",
}
def _format_languages(ext_counts: dict[str, int]) -> str:
parts = []
for ext, count in ext_counts.items():
name = _EXT_NAMES.get(ext, ext)
parts.append(f"{name} ({count})")
return ", ".join(parts)
def _run_extraction(
paths: list[Path],
cache_root: Path,
parallel: bool,
max_workers: int | None = None,
) -> tuple[float, int, int]:
"""Run extraction, return (elapsed_seconds, node_count, edge_count)."""
clear_cache(cache_root)
t0 = time.perf_counter()
result = extract(
paths, cache_root=cache_root, parallel=parallel, max_workers=max_workers
)
elapsed = time.perf_counter() - t0
nodes = len(result.get("nodes", []))
edges = len(result.get("edges", []))
return elapsed, nodes, edges
def main() -> None:
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
target = target.resolve()
if not target.exists():
print(f"Error: {target} does not exist", file=sys.stderr)
sys.exit(1)
print("=== Graphify AST Extraction Benchmark ===\n")
print(f"Scanning {target} ...", flush=True)
paths = collect_files(target)
if not paths:
print("No extractable files found.", file=sys.stderr)
sys.exit(1)
ext_counts = _count_by_ext(paths)
print(f"Files: {len(paths):,}")
print(f"Languages: {_format_languages(ext_counts)}")
print()
cache_root = target if target.is_dir() else target.parent
# Workers count (same logic as _extract_parallel)
import os
workers = min(os.cpu_count() or 4, len(paths), 8)
# Run sequential
print("Running sequential extraction...", flush=True)
seq_time, seq_nodes, seq_edges = _run_extraction(paths, cache_root, parallel=False)
print(f"Sequential: {seq_time:.2f}s ({seq_nodes:,} nodes, {seq_edges:,} edges)")
# Run parallel
print(f"\nRunning parallel extraction ({workers} workers)...", flush=True)
par_time, par_nodes, par_edges = _run_extraction(
paths, cache_root, parallel=True, max_workers=workers
)
print(
f"Parallel ({workers}): {par_time:.2f}s ({par_nodes:,} nodes, {par_edges:,} edges)"
)
# Results
print()
if seq_time > 0:
speedup = seq_time / par_time if par_time > 0 else float("inf")
print(f"Speedup: {speedup:.2f}x")
print(f"Workers: {workers} (auto-detected)")
# Validate correctness
if seq_nodes == par_nodes and seq_edges == par_edges:
print("Results: ✓ identical (node count, edge count match)")
else:
print("Results: ✗ MISMATCH!")
print(f" Sequential: {seq_nodes} nodes, {seq_edges} edges")
print(f" Parallel: {par_nodes} nodes, {par_edges} edges")
sys.exit(1)
# Clean up cache after benchmark
clear_cache(cache_root)
print("\nCache cleared after benchmark.")
if __name__ == "__main__":
main()
+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])
```
+32
View File
@@ -0,0 +1,32 @@
import { logger } from './logger';
async function processInbound(orgId: string, phone: string) {
const { shouldHandle, processMessage } = await import('./mayaEngine.js');
const handle = await shouldHandle(orgId, phone);
if (handle.sessionId) {
await processMessage({ orgId, phone }, handle.sessionId);
}
}
async function pollMessages(orgId: string) {
const { commsQueue } = await import('./queue.js');
await commsQueue.add('check-inbound', { orgId });
}
async function loadHandler(handlerName: string) {
// dynamic template literal — path not statically resolvable, should produce no edge
const mod = await import(`./handlers/${handlerName}`);
return mod.default;
}
async function loadStatic() {
// static template literal (no interpolation) — should resolve like a plain string
const { helper } = await import(`./staticHelper`);
return helper;
}
function syncOnly() {
logger.info('no dynamic imports here');
}
export { processInbound, pollMessages, loadHandler, loadStatic, syncOnly };
+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.
+19
View File
@@ -0,0 +1,19 @@
CREATE TABLE organizations (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL,
org_id INT REFERENCES organizations(id)
);
CREATE VIEW active_users AS
SELECT * FROM users WHERE active = true;
CREATE FUNCTION get_user(user_id INT) RETURNS users AS $$
BEGIN
RETURN QUERY SELECT * FROM users WHERE id = user_id;
END;
$$ LANGUAGE plpgsql;
+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);
+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
+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 {}
+143
View File
@@ -0,0 +1,143 @@
"""Tests for `.astro` extraction (#850).
Astro files have a TypeScript frontmatter block (`---...---`) at the top where
nearly all imports live, followed by an HTML-with-expressions template and
optionally `<script>` blocks. Tree-sitter-javascript fed the whole file produces
a top-level ERROR node because the template is not valid JS, so the JS AST pass
recovers nothing. The :func:`extract_astro` regex pass salvages imports from the
frontmatter and any `<script>` blocks — same strategy as :func:`extract_svelte`.
"""
from __future__ import annotations
from pathlib import Path
from graphify.detect import CODE_EXTENSIONS
from graphify.extract import (
_make_id,
extract_astro,
)
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, *, relation: str | None = None) -> set[str]:
return {
str(e.get("target") or "")
for e in result.get("edges", [])
if relation is None or e.get("relation") == relation
}
def test_astro_is_in_code_extensions():
"""Without this, detect.py silently drops `.astro` from the AST pass (#850)."""
assert ".astro" in CODE_EXTENSIONS
def test_extract_astro_picks_up_frontmatter_static_imports(tmp_path):
page = _write(
tmp_path / "src/pages/index.astro",
"""---
import Layout from '../layouts/Layout.astro';
import Hero from '../components/Hero.astro';
const { title } = Astro.props;
---
<Layout title={title}>
<Hero />
</Layout>
""",
)
# Sibling files so the resolver lands on real node ids, not phantoms.
layout = _write(tmp_path / "src/layouts/Layout.astro", "---\n---\n<slot />\n")
hero = _write(tmp_path / "src/components/Hero.astro", "---\n---\n<h1>hi</h1>\n")
result = extract_astro(page)
targets = _import_targets(result, relation="imports_from")
assert _make_id(str(layout)) in targets
assert _make_id(str(hero)) in targets
def test_extract_astro_handles_dynamic_import_in_frontmatter(tmp_path):
page = _write(
tmp_path / "src/pages/lazy.astro",
"""---
const Mod = await import('./Other.astro');
---
<div>{Mod.default}</div>
""",
)
other = _write(tmp_path / "src/pages/Other.astro", "---\n---\n<p>o</p>\n")
result = extract_astro(page)
targets = _import_targets(result, relation="dynamic_import")
assert _make_id(str(other)) in targets
def test_extract_astro_picks_up_client_side_script_imports(tmp_path):
page = _write(
tmp_path / "src/pages/with-script.astro",
"""---
import Layout from '../layouts/Layout.astro';
---
<Layout>
<button id="b">click</button>
</Layout>
<script>
import { hydrate } from '../client/hydrate.ts';
hydrate(document.getElementById('b'));
</script>
""",
)
layout = _write(tmp_path / "src/layouts/Layout.astro", "---\n---\n<slot />\n")
hydrate = _write(tmp_path / "src/client/hydrate.ts", "export function hydrate(){}\n")
result = extract_astro(page)
targets = _import_targets(result, relation="imports_from")
assert _make_id(str(layout)) in targets
assert _make_id(str(hydrate)) in targets
def test_extract_astro_no_frontmatter_does_not_crash(tmp_path):
"""Astro permits frontmatter-less files (pure-HTML pages). Must not raise."""
page = _write(
tmp_path / "src/pages/plain.astro",
"<h1>no frontmatter here</h1>\n",
)
result = extract_astro(page)
# Empty/no-imports result is acceptable; the extractor must just not crash.
assert isinstance(result, dict)
assert _import_targets(result, relation="imports_from") == set()
def test_extract_astro_handles_tsconfig_path_alias(tmp_path):
_write(
tmp_path / "tsconfig.json",
"""{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@components/*": ["src/components/*"] }
}
}
""",
)
page = _write(
tmp_path / "src/pages/alias.astro",
"""---
import Hero from '@components/Hero.astro';
---
<Hero />
""",
)
hero = _write(tmp_path / "src/components/Hero.astro", "---\n---\n<h1>h</h1>\n")
result = extract_astro(page)
targets = _import_targets(result, relation="imports_from")
assert _make_id(str(hero)) in targets
+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
+239 -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"
@@ -50,6 +52,21 @@ def test_legacy_edge_from_to_canonicalized():
assert G.number_of_edges() == 1
def test_source_file_backslash_normalized():
"""Windows backslash paths and POSIX paths for the same file must produce one node."""
extraction = {
"nodes": [
{"id": "n1", "label": "A", "file_type": "code", "source_file": "src\\middleware\\auth.py"},
{"id": "n2", "label": "B", "file_type": "code", "source_file": "src/middleware/auth.py"},
],
"edges": [],
"input_tokens": 0, "output_tokens": 0,
}
G = build_from_json(extraction)
sources = {G.nodes[n]["source_file"] for n in G.nodes()}
assert sources == {"src/middleware/auth.py"}
def test_build_merges_multiple_extractions():
ext1 = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"}],
"edges": [], "input_tokens": 0, "output_tokens": 0}
@@ -60,3 +77,224 @@ 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_coerced_to_concept():
"""Unknown file_type values are coerced through the synonym mapper, falling
back to 'concept' for anything that isn't a known LLM synonym (#840)."""
ext = {
"nodes": [
{"id": "n1", "label": "Bad", "file_type": "weird_type", "source_file": "a.py"},
],
"edges": [],
"input_tokens": 0,
"output_tokens": 0,
}
G = build_from_json(ext)
assert G.nodes["n1"]["file_type"] == "concept"
def test_file_type_synonym_mapping():
"""Known invalid file_type values map to their canonical equivalents."""
ext = {
"nodes": [
{"id": "n1", "label": "MD", "file_type": "markdown", "source_file": "a.md"},
{"id": "n2", "label": "Tool", "file_type": "tool", "source_file": "b.py"},
{"id": "n3", "label": "Pat", "file_type": "pattern", "source_file": "c.md"},
],
"edges": [],
"input_tokens": 0,
"output_tokens": 0,
}
G = build_from_json(ext)
assert G.nodes["n1"]["file_type"] == "document"
assert G.nodes["n2"]["file_type"] == "code"
assert G.nodes["n3"]["file_type"] == "concept"
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
+452
View File
@@ -0,0 +1,452 @@
"""Tests for token-aware chunking and parallel chunk execution in graphify.llm."""
import time
from pathlib import Path
from unittest.mock import patch
import pytest
@pytest.fixture(autouse=False)
def no_tokenizer():
"""Force the chars/4 fallback so packing math is deterministic regardless
of whether tiktoken is installed in the test environment. tiktoken's BPE
compresses repeated/synthetic content heavily, which would make pack-size
assertions tied to specific input sizes flaky."""
from graphify import llm
with patch.object(llm, "_TOKENIZER", None):
yield
# ---- Token-aware packing -----------------------------------------------------
def test_pack_chunks_packs_small_files_together(tmp_path):
"""Many small files should land in a single chunk, not one chunk per file."""
from graphify.llm import _pack_chunks_by_tokens
files = []
for i in range(20):
f = tmp_path / f"small_{i}.py"
f.write_text("x = 1\n") # ~6 bytes => ~1 token
files.append(f)
chunks = _pack_chunks_by_tokens(files, token_budget=10_000)
assert len(chunks) == 1
assert sorted(chunks[0]) == sorted(files)
def test_pack_chunks_starts_new_chunk_when_budget_would_overflow(tmp_path, no_tokenizer):
"""When the next file would push the chunk past the budget, start a new chunk.
With chars/4 fallback: each 10,000-char file = (10000+80)/4 = 2520 tokens.
Budget 6000 fits two (5040 < 6000) but not three (7560 > 6000).
Five files → 2/2/1 = three chunks.
"""
from graphify.llm import _pack_chunks_by_tokens
files = []
for i in range(5):
f = tmp_path / f"file_{i}.py"
f.write_text("x" * 10_000)
files.append(f)
chunks = _pack_chunks_by_tokens(files, token_budget=6_000)
sizes = [len(c) for c in chunks]
assert sizes == [2, 2, 1], f"expected [2, 2, 1], got {sizes}"
assert sum(sizes) == 5 # all files accounted for
def test_pack_chunks_groups_by_directory(tmp_path):
"""Files in the same directory should land in the same chunk when they fit."""
from graphify.llm import _pack_chunks_by_tokens
dir_a = tmp_path / "a"
dir_b = tmp_path / "b"
dir_a.mkdir()
dir_b.mkdir()
a1 = dir_a / "x.py"; a1.write_text("a")
a2 = dir_a / "y.py"; a2.write_text("a")
b1 = dir_b / "x.py"; b1.write_text("b")
b2 = dir_b / "y.py"; b2.write_text("b")
# Big budget — everything fits in one chunk in principle, but the order
# within the chunk should keep dir_a's files contiguous and dir_b's
# contiguous (not interleaved).
chunks = _pack_chunks_by_tokens([a1, b1, a2, b2], token_budget=1_000_000)
assert len(chunks) == 1
chunk = chunks[0]
a_indices = [i for i, p in enumerate(chunk) if p.parent == dir_a]
b_indices = [i for i, p in enumerate(chunk) if p.parent == dir_b]
assert a_indices == sorted(a_indices)
assert b_indices == sorted(b_indices)
# all of one directory comes before all of the other
assert max(a_indices) < min(b_indices) or max(b_indices) < min(a_indices)
def test_pack_chunks_oversized_file_gets_its_own_chunk(tmp_path, no_tokenizer):
"""A file larger than the budget can't be split — it goes alone in a chunk."""
from graphify.llm import _pack_chunks_by_tokens
big = tmp_path / "big.py"; big.write_text("x" * 200_000) # ~50k tokens (cap-bound)
small = tmp_path / "small.py"; small.write_text("x")
chunks = _pack_chunks_by_tokens([big, small], token_budget=1_000)
sizes = [len(c) for c in chunks]
# big should be alone in its own chunk; small in its own (no other file
# to share with)
assert sizes == [1, 1]
def test_pack_chunks_rejects_non_positive_budget(tmp_path):
from graphify.llm import _pack_chunks_by_tokens
f = tmp_path / "x.py"; f.write_text("a")
with pytest.raises(ValueError):
_pack_chunks_by_tokens([f], token_budget=0)
# ---- Tokenizer fallback ------------------------------------------------------
def test_estimate_file_tokens_uses_tiktoken_when_available(tmp_path):
"""When tiktoken is installed, the estimator should call into it for
accurate counts rather than the chars/4 heuristic."""
from graphify import llm
f = tmp_path / "sample.py"
text = "def hello():\n return 'world'\n" * 50 # ~1500 chars
f.write_text(text)
# Force the tokenizer to be a mock that records calls and returns a known
# token list, so we can assert the tiktoken path is taken.
fake_encoder = type("E", (), {"encode": staticmethod(lambda s: [0] * 999)})()
with patch.object(llm, "_TOKENIZER", fake_encoder):
n = llm._estimate_file_tokens(f)
assert n == 999 + (llm._PER_FILE_OVERHEAD_CHARS // llm._CHARS_PER_TOKEN)
def test_estimate_file_tokens_falls_back_to_chars_when_no_tokenizer(tmp_path):
"""Without tiktoken installed, the estimator falls back to chars/4."""
from graphify import llm
f = tmp_path / "sample.py"
f.write_text("x" * 1_000) # 1000 bytes
with patch.object(llm, "_TOKENIZER", None):
n = llm._estimate_file_tokens(f)
# 1000 chars + 80 overhead = 1080 / 4 = 270 tokens
assert n == (1000 + llm._PER_FILE_OVERHEAD_CHARS) // llm._CHARS_PER_TOKEN
# ---- Parallel execution ------------------------------------------------------
def _stub_chunk_result(file_count: int, idx: int) -> dict:
"""Build a deterministic fake extraction result for a chunk."""
return {
"nodes": [{"id": f"chunk_{idx}_node_{i}"} for i in range(file_count)],
"edges": [],
"hyperedges": [],
"input_tokens": 100 * file_count,
"output_tokens": 50 * file_count,
}
def test_corpus_parallel_runs_chunks_concurrently(tmp_path):
"""With max_concurrency > 1, total wall time should be ~max(chunk times),
not the sum. Each stub extraction sleeps; we assert wall time."""
from graphify.llm import extract_corpus_parallel
files = []
for i in range(8):
f = tmp_path / f"f{i}.py"; f.write_text("x")
files.append(f)
def slow_extract(chunk, **kwargs):
time.sleep(0.3)
return _stub_chunk_result(len(chunk), 0)
with patch("graphify.llm.extract_files_direct", side_effect=slow_extract):
t0 = time.time()
# Force 4 chunks of 2 files each by setting a tight token budget.
result = extract_corpus_parallel(
files, backend="kimi", token_budget=None, chunk_size=2, max_concurrency=4
)
elapsed = time.time() - t0
# 4 chunks × 0.3s sequential = 1.2s. Parallel with 4 workers should land near 0.3-0.5s.
assert elapsed < 1.0, f"expected parallel speedup, took {elapsed:.2f}s"
assert len(result["nodes"]) == 8
def test_corpus_parallel_sequential_when_max_concurrency_is_one(tmp_path):
"""max_concurrency=1 should run sequentially (no thread pool)."""
from graphify.llm import extract_corpus_parallel
files = []
for i in range(3):
f = tmp_path / f"f{i}.py"; f.write_text("x")
files.append(f)
call_order = []
def record(chunk, **kwargs):
call_order.append(tuple(p.name for p in chunk))
return _stub_chunk_result(len(chunk), len(call_order))
with patch("graphify.llm.extract_files_direct", side_effect=record):
extract_corpus_parallel(
files, backend="kimi", token_budget=None, chunk_size=1, max_concurrency=1
)
# Sequential => we see calls in submission order
assert call_order == [("f0.py",), ("f1.py",), ("f2.py",)]
def test_corpus_parallel_continues_after_chunk_failure(tmp_path, capsys):
"""A single chunk raising should be logged but not abort the run.
Other chunks' results should still be merged."""
from graphify.llm import extract_corpus_parallel
files = []
for i in range(4):
f = tmp_path / f"f{i}.py"; f.write_text("x")
files.append(f)
call_count = {"n": 0}
def maybe_fail(chunk, **kwargs):
call_count["n"] += 1
if call_count["n"] == 2:
raise RuntimeError("simulated API error")
return _stub_chunk_result(len(chunk), call_count["n"])
with patch("graphify.llm.extract_files_direct", side_effect=maybe_fail):
result = extract_corpus_parallel(
files, backend="kimi", token_budget=None, chunk_size=1, max_concurrency=1
)
# 4 chunks dispatched, 1 failed → 3 chunks contributed nodes
assert len(result["nodes"]) == 3
err = capsys.readouterr().err
assert "failed" in err and "simulated API error" in err
def test_corpus_parallel_legacy_mode_when_token_budget_is_none(tmp_path):
"""token_budget=None should fall back to legacy fixed-count chunking."""
from graphify.llm import extract_corpus_parallel
files = []
for i in range(45):
f = tmp_path / f"f{i}.py"; f.write_text("x")
files.append(f)
chunks_seen = []
def record(chunk, **kwargs):
chunks_seen.append(len(chunk))
return _stub_chunk_result(len(chunk), len(chunks_seen))
with patch("graphify.llm.extract_files_direct", side_effect=record):
extract_corpus_parallel(
files, backend="kimi", token_budget=None, chunk_size=20, max_concurrency=1
)
# 45 files / chunk_size=20 = 3 chunks of 20, 20, 5
assert chunks_seen == [20, 20, 5]
def test_corpus_parallel_token_budget_default_packs_files(tmp_path):
"""With the default token_budget, many tiny files pack into one chunk."""
from graphify.llm import extract_corpus_parallel
files = []
for i in range(50):
f = tmp_path / f"f{i}.py"; f.write_text("x = 1\n")
files.append(f)
chunks_seen = []
def record(chunk, **kwargs):
chunks_seen.append(len(chunk))
return _stub_chunk_result(len(chunk), len(chunks_seen))
with patch("graphify.llm.extract_files_direct", side_effect=record):
extract_corpus_parallel(files, backend="kimi", max_concurrency=1)
# 50 tiny files at default 60k token budget should pack into 1 chunk
assert len(chunks_seen) == 1
assert chunks_seen[0] == 50
# ---- Adaptive retry on truncation -------------------------------------------
def _stub_with_finish(file_count: int, finish_reason: str = "stop") -> dict:
"""Build a stub extraction result with a controllable finish_reason."""
return {
"nodes": [{"id": f"n_{i}"} for i in range(file_count)],
"edges": [],
"hyperedges": [],
"input_tokens": 100 * file_count,
"output_tokens": 50 * file_count,
"finish_reason": finish_reason,
}
def test_adaptive_retry_returns_directly_when_not_truncated(tmp_path):
"""No retry when finish_reason='stop' — single call, result passes through."""
from graphify.llm import _extract_with_adaptive_retry
files = [tmp_path / f"f{i}.py" for i in range(4)]
for f in files:
f.write_text("x")
calls = []
def stub(chunk, **kwargs):
calls.append(len(chunk))
return _stub_with_finish(len(chunk), finish_reason="stop")
with patch("graphify.llm.extract_files_direct", side_effect=stub):
result = _extract_with_adaptive_retry(
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
)
assert calls == [4], f"expected 1 call of 4 files, got {calls}"
assert len(result["nodes"]) == 4
def test_adaptive_retry_splits_when_finish_reason_length(tmp_path):
"""finish_reason='length' triggers split-in-half. Both halves succeed
on the second try (mocked) and results merge."""
from graphify.llm import _extract_with_adaptive_retry
files = [tmp_path / f"f{i}.py" for i in range(4)]
for f in files:
f.write_text("x")
calls = []
def stub(chunk, **kwargs):
calls.append(len(chunk))
finish = "length" if len(chunk) == 4 else "stop"
return _stub_with_finish(len(chunk), finish_reason=finish)
with patch("graphify.llm.extract_files_direct", side_effect=stub):
result = _extract_with_adaptive_retry(
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
)
assert calls == [4, 2, 2], f"expected [4, 2, 2], got {calls}"
assert len(result["nodes"]) == 4
assert result["finish_reason"] == "stop"
def test_adaptive_retry_recurses_for_persistent_truncation(tmp_path):
"""When even the half-chunk truncates, split again. With 8 files and a
truncation cutoff at >2 files, splits 8 → 4 → 2 (4 leaves of 2)."""
from graphify.llm import _extract_with_adaptive_retry
files = [tmp_path / f"f{i}.py" for i in range(8)]
for f in files:
f.write_text("x")
calls = []
def stub(chunk, **kwargs):
calls.append(len(chunk))
finish = "length" if len(chunk) > 2 else "stop"
return _stub_with_finish(len(chunk), finish_reason=finish)
with patch("graphify.llm.extract_files_direct", side_effect=stub):
result = _extract_with_adaptive_retry(
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
)
# Tree: 8 (trunc) → 4 + 4 (both trunc) → 2+2+2+2 (all stop)
# Total calls: 1 + 2 + 4 = 7
assert sorted(calls) == [2, 2, 2, 2, 4, 4, 8]
assert len(result["nodes"]) == 8
def test_adaptive_retry_caps_at_max_depth(tmp_path, capsys):
"""If everything truncates, retries stop at max_depth — partial result
kept with a warning, no infinite loop."""
from graphify.llm import _extract_with_adaptive_retry
files = [tmp_path / f"f{i}.py" for i in range(8)]
for f in files:
f.write_text("x")
calls = []
def always_truncate(chunk, **kwargs):
calls.append(len(chunk))
return _stub_with_finish(len(chunk), finish_reason="length")
with patch("graphify.llm.extract_files_direct", side_effect=always_truncate):
_extract_with_adaptive_retry(
files, backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=2
)
# max_depth=2 bounds the tree: root + 2 + 4 = 7 calls maximum
assert len(calls) <= 7, f"recursion not bounded — {len(calls)} calls"
err = capsys.readouterr().err
assert "still truncated" in err
def test_adaptive_retry_single_file_truncation_does_not_recurse(tmp_path, capsys):
"""A single file that truncates can't be split further — surface a
warning and return what we got. No infinite loop."""
from graphify.llm import _extract_with_adaptive_retry
f = tmp_path / "huge.py"; f.write_text("x")
calls = []
def stub(chunk, **kwargs):
calls.append(len(chunk))
return _stub_with_finish(len(chunk), finish_reason="length")
with patch("graphify.llm.extract_files_direct", side_effect=stub):
_extract_with_adaptive_retry(
[f], backend="kimi", api_key=None, model=None, root=tmp_path, max_depth=3
)
assert calls == [1], f"single-file chunk recursed; calls = {calls}"
err = capsys.readouterr().err
assert "single-file chunk" in err and "truncated" in err
def test_corpus_parallel_uses_adaptive_retry(tmp_path):
"""End-to-end: extract_corpus_parallel routes through adaptive retry,
so a chunk that truncates gets split and merged transparently before
on_chunk_done fires."""
from graphify.llm import extract_corpus_parallel
files = [tmp_path / f"f{i}.py" for i in range(4)]
for f in files:
f.write_text("x")
calls = []
def stub(chunk, **kwargs):
calls.append(len(chunk))
finish = "length" if len(chunk) == 4 else "stop"
return _stub_with_finish(len(chunk), finish_reason=finish)
chunk_done_args = []
with patch("graphify.llm.extract_files_direct", side_effect=stub):
result = extract_corpus_parallel(
files,
backend="kimi",
token_budget=None,
chunk_size=4,
max_concurrency=1,
on_chunk_done=lambda i, t, r: chunk_done_args.append((i, t, len(r["nodes"]))),
)
# Adaptive retry runs INSIDE _run_one: 4 → 2 + 2 = 3 underlying API calls
assert calls == [4, 2, 2]
# User-visible: 1 chunk completion (the merged result)
assert len(chunk_done_args) == 1
assert chunk_done_args[0] == (0, 1, 4)
assert len(result["nodes"]) == 4
+117
View File
@@ -0,0 +1,117 @@
"""Tests for the `claude-cli` backend (#855/#856).
Mocks subprocess.run + shutil.which so the suite runs on CI without
the `claude` binary or a live network call.
"""
from __future__ import annotations
import json
from unittest.mock import MagicMock, patch
import pytest
from graphify import llm
_ENVELOPE = {
"type": "result",
"subtype": "success",
"is_error": False,
"result": json.dumps({
"nodes": [
{"id": "foo_module", "label": "Foo", "file_type": "document", "source_file": "foo.md"},
{"id": "foo_greet", "label": "greet", "file_type": "code", "source_file": "foo.md"},
],
"edges": [
{"source": "foo_module", "target": "foo_greet",
"relation": "references", "confidence": "EXTRACTED", "confidence_score": 1.0},
],
"hyperedges": [],
"input_tokens": 0,
"output_tokens": 0,
}),
"stop_reason": "end_turn",
"usage": {
"input_tokens": 6,
"output_tokens": 11,
"cache_read_input_tokens": 17837,
"cache_creation_input_tokens": 30800,
},
"modelUsage": {"claude-opus-4-7[1m]": {"inputTokens": 6, "outputTokens": 11}},
}
@pytest.fixture
def fake_claude(monkeypatch):
completed = MagicMock(returncode=0, stdout=json.dumps(_ENVELOPE), stderr="")
monkeypatch.setattr(llm, "_response_is_hollow", lambda raw, parsed: False)
with patch("shutil.which", return_value="/fake/bin/claude"), \
patch("subprocess.run", return_value=completed) as run:
yield run
def test_returns_parsed_nodes_and_edges(fake_claude):
result = llm._call_claude_cli("dummy", max_tokens=8192)
assert len(result["nodes"]) == 2
assert len(result["edges"]) == 1
def test_token_accounting_includes_cache(fake_claude):
result = llm._call_claude_cli("dummy", max_tokens=8192)
assert result["input_tokens"] == 6 + 17837 + 30800
assert result["output_tokens"] == 11
assert result["model"] == "claude-opus-4-7[1m]"
assert result["finish_reason"] == "stop"
def test_finish_reason_length_on_max_tokens(monkeypatch):
envelope = dict(_ENVELOPE, stop_reason="max_tokens")
completed = MagicMock(returncode=0, stdout=json.dumps(envelope), stderr="")
monkeypatch.setattr(llm, "_response_is_hollow", lambda raw, parsed: False)
with patch("shutil.which", return_value="/fake/bin/claude"), \
patch("subprocess.run", return_value=completed):
result = llm._call_claude_cli("dummy", max_tokens=8192)
assert result["finish_reason"] == "length"
def test_raises_when_cli_missing():
with patch("shutil.which", return_value=None):
with pytest.raises(RuntimeError, match="Claude Code CLI not found"):
llm._call_claude_cli("dummy", max_tokens=8192)
def test_raises_on_nonzero_exit():
completed = MagicMock(returncode=2, stdout="", stderr="auth failed")
with patch("shutil.which", return_value="/fake/bin/claude"), \
patch("subprocess.run", return_value=completed):
with pytest.raises(RuntimeError, match="exited 2"):
llm._call_claude_cli("dummy", max_tokens=8192)
def test_raises_on_garbage_envelope():
completed = MagicMock(returncode=0, stdout="not json", stderr="")
with patch("shutil.which", return_value="/fake/bin/claude"), \
patch("subprocess.run", return_value=completed):
with pytest.raises(RuntimeError, match="unparseable JSON envelope"):
llm._call_claude_cli("dummy", max_tokens=8192)
def test_extract_files_direct_dispatches_to_claude_cli(tmp_path, fake_claude):
f = tmp_path / "foo.md"
f.write_text("# Foo\n\nThe greet() helper formats a name.\n")
result = llm.extract_files_direct(files=[f], backend="claude-cli", root=tmp_path)
assert fake_claude.called
assert len(result["nodes"]) == 2
def test_backend_registered_with_zero_cost():
assert "claude-cli" in llm.BACKENDS
pricing = llm.BACKENDS["claude-cli"]["pricing"]
assert pricing["input"] == 0.0
assert pricing["output"] == 0.0
assert llm.estimate_cost("claude-cli", 1_000_000, 1_000_000) == 0.0
def test_no_session_persistence_flag_in_subprocess(fake_claude):
llm._call_claude_cli("dummy", max_tokens=8192)
call_args = fake_claude.call_args[0][0]
assert "--no-session-persistence" in call_args
+252
View File
@@ -0,0 +1,252 @@
"""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
def test_update_no_cluster_writes_raw_graph(tmp_path):
src = tmp_path / "sample.py"
src.write_text("def f():\n return 1\n", encoding="utf-8")
r = _run(["update", ".", "--no-cluster"], tmp_path)
assert r.returncode == 0, r.stderr
graph_path = tmp_path / "graphify-out" / "graph.json"
assert graph_path.exists()
data = json.loads(graph_path.read_text(encoding="utf-8"))
assert "nodes" in data and "links" in data
assert all("community" not in node for node in data["nodes"])
+25 -1
View File
@@ -3,7 +3,7 @@ import sys
import networkx as nx
from pathlib import Path
from graphify.build import build_from_json
from graphify.cluster import cluster, cohesion_score, score_all
from graphify.cluster import cluster, cohesion_score, remap_communities_to_previous, score_all
FIXTURES = Path(__file__).parent / "fixtures"
@@ -74,3 +74,27 @@ def test_cluster_does_not_write_to_stderr(capsys):
# Allow logging output (starts with [graphify]) but no raw ANSI codes
for line in captured.err.splitlines():
assert "\x1b" not in line, f"cluster() wrote ANSI to stderr: {line!r}"
def test_remap_communities_to_previous_reuses_old_ids():
communities = {
10: ["a", "b", "c"],
11: ["d", "e"],
}
previous = {"a": 5, "b": 5, "c": 5, "d": 1, "e": 1}
remapped = remap_communities_to_previous(communities, previous)
assert set(remapped.keys()) == {1, 5}
assert remapped[5] == ["a", "b", "c"]
assert remapped[1] == ["d", "e"]
def test_remap_communities_to_previous_assigns_deterministic_new_ids():
communities = {
7: ["x", "y", "z"],
8: ["m"],
}
previous = {"a": 3}
remapped = remap_communities_to_previous(communities, previous)
assert list(remapped.keys()) == [0, 1]
assert remapped[0] == ["x", "y", "z"]
assert remapped[1] == ["m"]
+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
+134 -3
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"
@@ -138,8 +138,27 @@ def test_detect_follows_symlinked_file(tmp_path):
assert any("link.py" in f for f in code)
def test_graphifyignore_discovered_from_parent(tmp_path):
"""A .graphifyignore in a parent directory applies to subdirectory scans."""
def test_graphifyignore_hermetic_without_vcs(tmp_path):
"""Without a VCS root, parent .graphifyignore does NOT apply (hermetic)."""
(tmp_path / ".graphifyignore").write_text("vendor/\n")
sub = tmp_path / "packages" / "mylib"
sub.mkdir(parents=True)
(sub / "main.py").write_text("x = 1")
vendor = sub / "vendor"
vendor.mkdir()
(vendor / "dep.py").write_text("y = 2")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
# parent .graphifyignore must NOT leak into a non-VCS scan
assert any("vendor" in f for f in code_files)
assert result["graphifyignore_patterns"] == 0
def test_graphifyignore_discovered_from_parent_in_vcs(tmp_path):
"""Inside a VCS repo, parent .graphifyignore applies to subdirectory scans."""
(tmp_path / ".git").mkdir()
(tmp_path / ".graphifyignore").write_text("vendor/\n")
sub = tmp_path / "packages" / "mylib"
sub.mkdir(parents=True)
@@ -201,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
@@ -212,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")
@@ -236,3 +316,54 @@ def test_detect_video_not_in_words(tmp_path):
result = detect(tmp_path)
# Only video file present — total_words should be 0
assert result["total_words"] == 0
def test_detect_skips_coverage_dir(tmp_path):
"""coverage/ and lcov-report/ are noise dirs — HTML reports inside must be excluded (#870)."""
cov = tmp_path / "coverage" / "lcov-report"
cov.mkdir(parents=True)
(cov / "index.html").write_text("<html>coverage report</html>")
(cov / "src.ts.html").write_text("<html>file coverage</html>")
(tmp_path / "main.py").write_text("def hello(): pass")
result = detect(tmp_path)
all_files = [f for files in result["files"].values() for f in files]
cov_prefix = str(tmp_path / "coverage")
assert not any(f.startswith(cov_prefix) for f in all_files)
assert any("main.py" in f for f in all_files)
def test_detect_skips_visual_tests_dir(tmp_path):
"""visual-tests/ bundles and snapshots are noise — must be excluded (#869)."""
vt = tmp_path / "visual-tests"
vt.mkdir()
(vt / "bundle.js").write_text("var u3=function(){};var d2=function(){}")
(vt / "screens.tsx").write_text("export const Screen = () => <div/>")
(tmp_path / "app.py").write_text("def main(): pass")
result = detect(tmp_path)
all_files = [f for files in result["files"].values() for f in files]
assert not any("visual-tests" in f for f in all_files)
assert any("app.py" in f for f in all_files)
def test_detect_skips_snapshots_dir(tmp_path):
"""__snapshots__/ and snapshots/ are jest/vitest artefacts — must be excluded."""
(tmp_path / "__snapshots__").mkdir()
(tmp_path / "__snapshots__" / "app.test.ts.snap").write_text("// Jest Snapshot\nexports[`test 1`] = `<div/>`")
(tmp_path / "app.ts").write_text("export function greet() { return 'hi'; }")
result = detect(tmp_path)
all_files = [f for files in result["files"].values() for f in files]
assert not any("__snapshots__" in f for f in all_files)
assert any("app.ts" in f for f in all_files)
def test_detect_skips_storybook_static_dir(tmp_path):
"""storybook-static/ is a build artefact — must be excluded."""
sb = tmp_path / "storybook-static"
sb.mkdir()
(sb / "index.html").write_text("<html>storybook</html>")
(sb / "main.js").write_text("(function(){var s=1;})()")
(tmp_path / "Button.tsx").write_text("export const Button = () => <button/>")
result = detect(tmp_path)
all_files = [f for files in result["files"].values() for f in files]
assert not any("storybook-static" in f for f in all_files)
assert any("Button.tsx" in f for f in all_files)
+56
View File
@@ -0,0 +1,56 @@
"""Regression tests for `graphify explain` arrow direction (#853)."""
from __future__ import annotations
import json
import graphify.__main__ as mainmod
def _write_graph(tmp_path):
graph_data = {
"directed": False, "multigraph": False, "graph": {},
"nodes": [
{"id": "validate", "label": "validateSanitySession()",
"source_file": "server/sanity-validate-session.ts", "community": 0},
{"id": "create_patch", "label": "createPatchHandler()",
"source_file": "server/create-patch-handler.ts", "community": 0},
{"id": "create_edit", "label": "createEditHandler()",
"source_file": "server/create-edit-handler.ts", "community": 0},
{"id": "stable_stringify", "label": "stableStringify()",
"source_file": "shared/stringify.ts", "community": 0},
],
"links": [
{"source": "create_patch", "target": "validate",
"relation": "calls", "confidence": "EXTRACTED"},
{"source": "create_edit", "target": "validate",
"relation": "calls", "confidence": "EXTRACTED"},
{"source": "validate", "target": "stable_stringify",
"relation": "calls", "confidence": "EXTRACTED"},
],
}
p = tmp_path / "graph.json"
p.write_text(json.dumps(graph_data))
return p
def _run(monkeypatch, graph_path, label, capsys):
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(mainmod.sys, "argv",
["graphify", "explain", label, "--graph", str(graph_path)])
mainmod.main()
return capsys.readouterr().out
def test_callee_shows_callers_as_inbound(monkeypatch, tmp_path, capsys):
p = _write_graph(tmp_path)
out = _run(monkeypatch, p, "validateSanitySession", capsys)
assert "<-- createPatchHandler() [calls]" in out
assert "<-- createEditHandler() [calls]" in out
assert "--> stableStringify() [calls]" in out
assert "--> createPatchHandler() [calls]" not in out
assert "--> createEditHandler() [calls]" not in out
def test_caller_shows_callee_as_outbound(monkeypatch, tmp_path, capsys):
p = _write_graph(tmp_path)
out = _run(monkeypatch, p, "createPatchHandler", capsys)
assert "--> validateSanitySession() [calls]" in out
assert "<-- " not in out
+262 -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
@@ -124,6 +121,13 @@ def test_calls_edges_are_extracted():
assert edge["weight"] == 1.0
def test_python_call_edges_have_call_context():
result = extract_python(FIXTURES / "sample_calls.py")
call_edges = [e for e in result["edges"] if e["relation"] == "calls"]
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_calls_no_self_loops():
result = extract_python(FIXTURES / "sample_calls.py")
for edge in result["edges"]:
@@ -168,3 +172,256 @@ def test_calls_deduplication():
result = extract_python(FIXTURES / "sample_calls.py")
call_pairs = [(e["source"], e["target"]) for e in result["edges"] if e["relation"] == "calls"]
assert len(call_pairs) == len(set(call_pairs)), "Duplicate calls edges found"
def test_cross_file_calls_skip_ambiguous_duplicate_labels(tmp_path):
"""Unqualified cross-file calls must not guess between duplicate helper names."""
caller = tmp_path / "caller.py"
helper_a = tmp_path / "a.py"
helper_b = tmp_path / "b.py"
caller.write_text("def run():\n log()\n")
helper_a.write_text("def log():\n return 'a'\n")
helper_b.write_text("def log():\n return 'b'\n")
result = extract([caller, helper_a, helper_b], cache_root=tmp_path)
nodes = {n["id"]: n for n in result["nodes"]}
calls = [
e for e in result["edges"]
if e["relation"] == "calls" and e["confidence"] == "INFERRED"
]
assert not any(
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()
+19
View File
@@ -123,3 +123,22 @@ def test_hook_skips_head_on_exe():
"""Hook script must skip shebang extraction for .exe binaries (Windows)."""
from graphify.hooks import _PYTHON_DETECT
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
def test_hook_check_no_additionalContext(tmp_path):
"""graphify hook-check must not emit additionalContext — Codex Desktop rejects it."""
import sys
out = tmp_path / "graphify-out"
out.mkdir()
(out / "graph.json").write_text("{}", encoding="utf-8")
result = subprocess.run(
[sys.executable, "-m", "graphify", "hook-check"],
cwd=tmp_path,
capture_output=True,
text=True,
)
assert result.returncode == 0
assert result.stdout == ""
assert result.stderr == ""
+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()
+406 -2
View File
@@ -1,11 +1,12 @@
"""Tests for language extractors: Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Go, Julia."""
"""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_swift, extract_go, extract_julia, extract_js, extract_fortran,
extract_groovy,
)
FIXTURES = Path(__file__).parent / "fixtures"
@@ -25,6 +26,22 @@ def _calls(r):
}
def _references(r):
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
return [
(
node_by_id.get(e["source"], e["source"]),
node_by_id.get(e["target"], e["target"]),
e,
)
for e in r["edges"] if e["relation"] == "references"
]
def _edges_with_relation(r, *relations):
return [e for e in r["edges"] if e["relation"] in relations]
# ── Java ──────────────────────────────────────────────────────────────────────
def test_java_no_error():
@@ -49,6 +66,13 @@ def test_java_finds_imports():
r = extract_java(FIXTURES / "sample.java")
assert "imports" in _relations(r)
def test_java_import_edges_have_import_context():
r = extract_java(FIXTURES / "sample.java")
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_java_no_dangling_edges():
r = extract_java(FIXTURES / "sample.java")
node_ids = {n["id"] for n in r["nodes"]}
@@ -83,6 +107,20 @@ def test_c_calls_are_extracted():
assert e["confidence"] == "EXTRACTED"
def test_c_import_edges_have_import_context():
r = extract_c(FIXTURES / "sample.c")
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_c_call_edges_have_call_context():
r = extract_c(FIXTURES / "sample.c")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
# ── C++ ───────────────────────────────────────────────────────────────────────
def test_cpp_no_error():
@@ -104,6 +142,13 @@ def test_cpp_finds_includes():
assert "imports" in _relations(r)
def test_cpp_import_edges_have_import_context():
r = extract_cpp(FIXTURES / "sample.cpp")
import_edges = _edges_with_relation(r, "imports", "imports_from")
assert import_edges
assert all(e.get("context") == "import" for e in import_edges)
# ── Ruby ─────────────────────────────────────────────────────────────────────
def test_ruby_no_error():
@@ -164,6 +209,33 @@ def test_csharp_inherits_iprocessor():
assert found, "DataProcessor should have inherits edge to IProcessor"
def test_csharp_field_type_references_have_field_context():
r = extract_csharp(FIXTURES / "sample.cs")
refs = _references(r)
assert any(
"DataProcessor" in src and "HttpClient" in tgt and edge.get("context") == "field"
for src, tgt, edge in refs
), "DataProcessor field declarations should reference HttpClient with field context"
def test_csharp_call_edges_have_call_context():
r = extract_csharp(FIXTURES / "sample.cs")
node_by_id = {n["id"]: n["label"] for n in r["nodes"]}
assert any(
"Process" in node_by_id.get(e["source"], "")
and "Validate" in node_by_id.get(e["target"], "")
and e.get("context") == "call"
for e in r["edges"] if e["relation"] == "calls"
), "C# call edges should retain call context"
def test_csharp_import_edges_have_import_context():
r = extract_csharp(FIXTURES / "sample.cs")
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert import_edges
assert all(e.get("context") == "import" for e in import_edges)
# ── Kotlin ───────────────────────────────────────────────────────────────────
def test_kotlin_no_error():
@@ -188,6 +260,18 @@ def test_kotlin_finds_function():
r = extract_kotlin(FIXTURES / "sample.kt")
assert any("createClient" in l for l in _labels(r))
def test_kotlin_emits_in_file_calls():
"""Regression test for the call-walker `simple_identifier` /
`identifier` rename — see graphify-kmp's PythonParityTest."""
r = extract_kotlin(FIXTURES / "sample.kt")
calls = _calls(r)
# In sample.kt: get() and post() both call buildRequest(), and
# createClient() invokes Config and HttpClient (constructor calls).
assert (".get()", ".buildRequest()") in calls
assert (".post()", ".buildRequest()") in calls
assert ("createClient()", "Config") in calls
assert ("createClient()", "HttpClient") in calls
# ── Scala ─────────────────────────────────────────────────────────────────────
@@ -210,6 +294,20 @@ def test_scala_finds_methods():
assert any("post" in l for l in labels)
def test_scala_import_edges_have_import_context():
r = extract_scala(FIXTURES / "sample.scala")
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_scala_call_edges_have_call_context():
r = extract_scala(FIXTURES / "sample.scala")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
# ── PHP ───────────────────────────────────────────────────────────────────────
def test_php_no_error():
@@ -234,6 +332,20 @@ def test_php_finds_imports():
r = extract_php(FIXTURES / "sample.php")
assert "imports" in _relations(r)
def test_php_import_edges_have_import_context():
r = extract_php(FIXTURES / "sample.php")
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_php_call_edges_have_call_context():
r = extract_php(FIXTURES / "sample.php")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_php_finds_static_property_access():
r = extract_php(FIXTURES / "sample_php_static_prop.php")
assert "uses_static_prop" in _relations(r)
@@ -319,6 +431,13 @@ def test_swift_finds_imports():
r = extract_swift(FIXTURES / "sample.swift")
assert "imports" in _relations(r)
def test_swift_import_edges_have_import_context():
r = extract_swift(FIXTURES / "sample.swift")
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_swift_no_dangling_edges():
r = extract_swift(FIXTURES / "sample.swift")
node_ids = {n["id"] for n in r["nodes"]}
@@ -405,6 +524,12 @@ def test_swift_emits_calls():
calls = _calls(r)
assert any("process" in src and "validate" in tgt for src, tgt in calls)
def test_swift_call_edges_have_call_context():
r = extract_swift(FIXTURES / "sample.swift")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
# ── Elixir ────────────────────────────────────────────────────────────────────
@@ -428,12 +553,26 @@ def test_elixir_finds_imports():
import_edges = [e for e in r["edges"] if e["relation"] == "imports"]
assert len(import_edges) >= 2
def test_elixir_import_edges_have_import_context():
r = extract_elixir(FIXTURES / "sample.ex")
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_elixir_finds_calls():
r = extract_elixir(FIXTURES / "sample.ex")
calls = {(e["source"], e["target"]) for e in r["edges"] if e["relation"] == "calls"}
labels = {n["id"]: n["label"] for n in r["nodes"]}
assert any("create" in labels.get(src, "") and "validate" in labels.get(tgt, "") for src, tgt in calls)
def test_elixir_call_edges_have_call_context():
r = extract_elixir(FIXTURES / "sample.ex")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_elixir_method_edges():
r = extract_elixir(FIXTURES / "sample.ex")
methods = [e for e in r["edges"] if e["relation"] == "method"]
@@ -468,6 +607,13 @@ def test_objc_finds_imports():
assert len(import_edges) >= 1
def test_objc_import_edges_have_import_context():
r = extract_objc(FIXTURES / "sample.m")
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_objc_inherits_edge():
r = extract_objc(FIXTURES / "sample.m")
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
@@ -543,6 +689,13 @@ def test_julia_finds_imports():
assert len(import_edges) >= 1
def test_julia_import_edges_have_import_context():
r = extract_julia(FIXTURES / "sample.jl")
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_julia_finds_inherits():
r = extract_julia(FIXTURES / "sample.jl")
inherits = [e for e in r["edges"] if e["relation"] == "inherits"]
@@ -555,8 +708,259 @@ def test_julia_finds_calls():
assert len(call_edges) >= 1
def test_julia_call_edges_have_call_context():
r = extract_julia(FIXTURES / "sample.jl")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_julia_no_dangling_edges():
r = extract_julia(FIXTURES / "sample.jl")
node_ids = {n["id"] for n in r["nodes"]}
for e in r["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_preprocessed.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():
r = extract_js(FIXTURES / "dynamic_import.ts")
assert "error" not in r
def test_ts_dynamic_import_extracts_edges():
"""Dynamic import() calls inside functions should produce imports_from edges."""
r = extract_js(FIXTURES / "dynamic_import.ts")
dyn_edges = [e for e in r["edges"] if e["relation"] == "imports_from"]
targets = {e["target"] for e in dyn_edges}
# Should find: static ./logger, dynamic ./mayaEngine.js, dynamic ./queue.js
assert any("logger" in t for t in targets), f"Missing static import of logger: {targets}"
assert any("mayaengine" in t.lower() for t in targets), f"Missing dynamic import of mayaEngine: {targets}"
assert any("queue" in t.lower() for t in targets), f"Missing dynamic import of queue: {targets}"
def test_ts_dynamic_import_confidence():
"""Dynamic imports should have EXTRACTED confidence (they are deterministic string literals)."""
r = extract_js(FIXTURES / "dynamic_import.ts")
dyn_edges = [e for e in r["edges"]
if e["relation"] == "imports_from"
and "mayaengine" in e["target"].lower()]
assert len(dyn_edges) >= 1
assert dyn_edges[0]["confidence"] == "EXTRACTED"
def test_ts_dynamic_import_source_is_function():
"""Dynamic import edge source should be the enclosing function, not the file."""
r = extract_js(FIXTURES / "dynamic_import.ts")
node_labels = {n["id"]: n["label"] for n in r["nodes"]}
dyn_edges = [e for e in r["edges"]
if e["relation"] == "imports_from"
and "mayaengine" in e["target"].lower()]
assert len(dyn_edges) >= 1
src_label = node_labels.get(dyn_edges[0]["source"], "")
assert "processInbound" in src_label, f"Expected processInbound as source, got {src_label}"
def test_ts_no_dynamic_import_in_sync_fn():
"""Functions without dynamic imports should not get spurious imports_from edges."""
r = extract_js(FIXTURES / "dynamic_import.ts")
node_ids = {n["label"]: n["id"] for n in r["nodes"]}
sync_nid = node_ids.get("syncOnly()")
if sync_nid:
sync_imports = [e for e in r["edges"]
if e["source"] == sync_nid and e["relation"] == "imports_from"]
assert len(sync_imports) == 0
def test_ts_dynamic_template_literal_skipped():
"""Dynamic template literals (with ${}) must not produce an imports_from edge."""
r = extract_js(FIXTURES / "dynamic_import.ts")
targets = {e["target"] for e in r["edges"] if e["relation"] == "imports_from"}
# loadHandler uses `./handlers/${handlerName}` — no static path, must be absent
assert not any("handler" in t.lower() and "$" in t for t in targets), \
f"Garbage edge from dynamic template literal found: {targets}"
# More robust: no target should contain a brace character
assert not any("{" in t or "}" in t for t in targets), \
f"Target contains unresolved template expression: {targets}"
def test_ts_static_template_literal_resolved():
"""Static template literals (no ${}) should resolve the same as a plain string."""
r = extract_js(FIXTURES / "dynamic_import.ts")
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
+110 -2
View File
@@ -1,9 +1,9 @@
"""Tests for multi-language AST extraction: JS/TS, Go, Rust."""
"""Tests for multi-language AST extraction: JS/TS, Go, Rust, SQL."""
from __future__ import annotations
import shutil
from pathlib import Path
import pytest
from graphify.extract import extract_js, extract_go, extract_rust, extract
from graphify.extract import extract_js, extract_go, extract_rust, extract, extract_sql
FIXTURES = Path(__file__).parent / "fixtures"
@@ -24,6 +24,10 @@ def _confidences(result):
return {e["confidence"] for e in result["edges"]}
def _edges_with_relation(result, *relations):
return [e for e in result["edges"] if e["relation"] in relations]
# ── TypeScript ────────────────────────────────────────────────────────────────
def test_ts_finds_class():
@@ -53,6 +57,20 @@ def test_ts_calls_are_extracted():
if e["relation"] == "calls":
assert e["confidence"] == "EXTRACTED"
def test_ts_import_edges_have_import_context():
r = extract_js(FIXTURES / "sample.ts")
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_ts_call_edges_have_call_context():
r = extract_js(FIXTURES / "sample.ts")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_ts_no_dangling_edges():
r = extract_js(FIXTURES / "sample.ts")
node_ids = {n["id"] for n in r["nodes"]}
@@ -87,6 +105,20 @@ def test_go_has_extracted_calls():
r = extract_go(FIXTURES / "sample.go")
assert "EXTRACTED" in _confidences(r)
def test_go_import_edges_have_import_context():
r = extract_go(FIXTURES / "sample.go")
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_go_call_edges_have_call_context():
r = extract_go(FIXTURES / "sample.go")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_go_no_dangling_edges():
r = extract_go(FIXTURES / "sample.go")
node_ids = {n["id"] for n in r["nodes"]}
@@ -123,6 +155,20 @@ def test_rust_calls_are_extracted():
if e["relation"] == "calls":
assert e["confidence"] == "EXTRACTED"
def test_rust_import_edges_have_import_context():
r = extract_rust(FIXTURES / "sample.rs")
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_rust_call_edges_have_call_context():
r = extract_rust(FIXTURES / "sample.rs")
call_edges = _edges_with_relation(r, "calls")
assert call_edges
assert all(e.get("context") == "call" for e in call_edges)
def test_rust_no_dangling_edges():
r = extract_rust(FIXTURES / "sample.rs")
node_ids = {n["id"] for n in r["nodes"]}
@@ -171,3 +217,65 @@ def test_cache_miss_after_file_change(tmp_path):
# bar() should appear in the second result
labels2 = [n["label"] for n in r2["nodes"]]
assert any("bar" in l for l in labels2)
# ── SQL ───────────────────────────────────────────────────────────────────────
def test_sql_finds_tables():
r = extract_sql(FIXTURES / "sample.sql")
labels = [n["label"] for n in r["nodes"]]
assert any("users" in l for l in labels)
assert any("organizations" in l for l in labels)
def test_sql_finds_view():
r = extract_sql(FIXTURES / "sample.sql")
labels = [n["label"] for n in r["nodes"]]
assert any("active_users" in l for l in labels)
def test_sql_finds_function():
r = extract_sql(FIXTURES / "sample.sql")
labels = [n["label"] for n in r["nodes"]]
assert any("get_user" in l for l in labels)
def test_sql_emits_foreign_key_edge():
r = extract_sql(FIXTURES / "sample.sql")
relations = {e["relation"] for e in r["edges"]}
assert "references" in relations
def test_sql_emits_reads_from_edge():
r = extract_sql(FIXTURES / "sample.sql")
relations = {e["relation"] for e in r["edges"]}
assert "reads_from" in relations
def test_sql_no_dangling_edges():
r = extract_sql(FIXTURES / "sample.sql")
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
+48
View File
@@ -0,0 +1,48 @@
"""Regression tests for `graphify path` arrow direction (#849)."""
from __future__ import annotations
import json
import networkx as nx
from networkx.readwrite import json_graph
import graphify.__main__ as mainmod
def _write_graph(tmp_path):
graph_data = {
"directed": False, "multigraph": False, "graph": {},
"nodes": [
{"id": "create_patch", "label": "createPatchHandler()",
"source_file": "server/create-patch-handler.ts", "community": 0},
{"id": "validate", "label": "validateSanitySession()",
"source_file": "server/sanity-validate-session.ts", "community": 0},
],
"links": [
{"source": "create_patch", "target": "validate",
"relation": "calls", "confidence": "EXTRACTED"},
],
}
p = tmp_path / "graph.json"
p.write_text(json.dumps(graph_data))
return p
def _run(monkeypatch, graph_path, src, tgt, capsys):
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(mainmod.sys, "argv",
["graphify", "path", src, tgt, "--graph", str(graph_path)])
mainmod.main()
return capsys.readouterr().out
def test_forward_arrow(monkeypatch, tmp_path, capsys):
p = _write_graph(tmp_path)
out = _run(monkeypatch, p, "createPatchHandler", "validateSanitySession", capsys)
assert "Shortest path (1 hops):" in out
assert "createPatchHandler() --calls [EXTRACTED]--> validateSanitySession()" in out
def test_reverse_arrow(monkeypatch, tmp_path, capsys):
p = _write_graph(tmp_path)
out = _run(monkeypatch, p, "validateSanitySession", "createPatchHandler", capsys)
assert "Shortest path (1 hops):" in out
assert "validateSanitySession() <--calls [EXTRACTED]-- createPatchHandler()" in out
assert "validateSanitySession() --calls [EXTRACTED]--> createPatchHandler()" not in out
+51
View File
@@ -0,0 +1,51 @@
"""Tests for graphify query CLI context filtering."""
from __future__ import annotations
import json
import networkx as nx
from networkx.readwrite import json_graph
import graphify.__main__ as mainmod
def _write_graph(tmp_path):
G = nx.Graph()
G.add_node("n1", label="extract", source_file="extract.py", source_location="L10", community=0)
G.add_node("n2", label="cluster", source_file="cluster.py", source_location="L5", community=0)
G.add_node("n3", label="build", source_file="build.py", source_location="L1", community=1)
G.add_edge("n1", "n2", relation="calls", confidence="EXTRACTED", context="call")
G.add_edge("n2", "n3", relation="imports", confidence="EXTRACTED", context="import")
graph_path = tmp_path / "graph.json"
graph_path.write_text(json.dumps(json_graph.node_link_data(G, edges="links")))
return graph_path
def test_query_cli_explicit_context_filter(monkeypatch, tmp_path, capsys):
graph_path = _write_graph(tmp_path)
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
mainmod.sys,
"argv",
["graphify", "query", "extract", "--context", "call", "--graph", str(graph_path)],
)
mainmod.main()
out = capsys.readouterr().out
assert "Context: call (explicit)" in out
assert "cluster" in out
assert "build" not in out
def test_query_cli_heuristic_context_filter(monkeypatch, tmp_path, capsys):
graph_path = _write_graph(tmp_path)
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
monkeypatch.setattr(
mainmod.sys,
"argv",
["graphify", "query", "who calls extract", "--graph", str(graph_path)],
)
mainmod.main()
out = capsys.readouterr().out
assert "Context: call (heuristic)" in out
assert "cluster" in out
assert "build" not in out
+1 -1
View File
@@ -57,7 +57,7 @@ def test_report_shows_token_cost():
def test_report_shows_raw_cohesion_scores():
G, communities, cohesion, labels, gods, surprises, detection, tokens = make_inputs()
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project")
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, "./project", min_community_size=1)
assert "Cohesion:" in report
assert "✓" not in report
assert "⚠" not in report
+47 -2
View File
@@ -9,6 +9,10 @@ from graphify.serve import (
_score_nodes,
_bfs,
_dfs,
_filter_graph_by_context,
_infer_context_filters,
_query_graph_text,
_resolve_context_filters,
_subgraph_to_text,
_load_graph,
)
@@ -21,8 +25,8 @@ def _make_graph() -> nx.Graph:
G.add_node("n3", label="build", source_file="build.py", source_location="L1", community=1)
G.add_node("n4", label="report", source_file="report.py", source_location="L1", community=1)
G.add_node("n5", label="isolated", source_file="other.py", source_location="L1", community=2)
G.add_edge("n1", "n2", relation="calls", confidence="INFERRED")
G.add_edge("n2", "n3", relation="imports", confidence="EXTRACTED")
G.add_edge("n1", "n2", relation="calls", confidence="INFERRED", context="call")
G.add_edge("n2", "n3", relation="imports", confidence="EXTRACTED", context="import")
G.add_edge("n3", "n4", relation="uses", confidence="EXTRACTED")
return G
@@ -73,6 +77,16 @@ def test_score_nodes_source_file_partial():
assert "n2" in nids
def test_infer_context_filters_for_calls_question():
assert _infer_context_filters("who calls extract") == ["call"]
def test_resolve_context_filters_explicit_overrides_heuristic():
filters, source = _resolve_context_filters("who calls extract", ["field"])
assert filters == ["field"]
assert source == "explicit"
# --- _bfs ---
def test_bfs_depth_1():
@@ -99,6 +113,15 @@ def test_bfs_returns_edges():
assert any(u == "n1" or v == "n1" for u, v in edges)
def test_filter_graph_by_context_limits_traversal():
G = _make_graph()
filtered = _filter_graph_by_context(G, ["call"])
visited, edges = _bfs(filtered, ["n1"], depth=2)
assert "n2" in visited
assert "n3" not in visited
assert edges == [("n1", "n2")]
# --- _dfs ---
def test_dfs_depth_1():
@@ -135,6 +158,28 @@ def test_subgraph_to_text_edge_included():
assert "calls" in text
def test_subgraph_to_text_includes_edge_context():
G = _make_graph()
text = _subgraph_to_text(G, {"n1", "n2"}, [("n1", "n2")])
assert "context=call" in text
def test_query_graph_text_explicit_context_filter_changes_traversal():
G = _make_graph()
text = _query_graph_text(G, "extract", mode="bfs", depth=2, token_budget=2000, context_filters=["call"])
assert "Context: call (explicit)" in text
assert "cluster" in text
assert "build" not in text
def test_query_graph_text_heuristic_context_filter_changes_traversal():
G = _make_graph()
text = _query_graph_text(G, "who calls extract", mode="bfs", depth=2, token_budget=2000)
assert "Context: call (heuristic)" in text
assert "cluster" in text
assert "build" not in text
# --- _load_graph ---
def test_load_graph_roundtrip(tmp_path):
+113 -1
View File
@@ -1,9 +1,11 @@
"""Tests for watch.py - file watcher helpers (no watchdog required)."""
import os
import sys
import time
from pathlib import Path
import pytest
from graphify.watch import _notify_only, _WATCHED_EXTENSIONS
from graphify.watch import _notify_only, _WATCHED_EXTENSIONS, _rebuild_lock
# --- _notify_only ---
@@ -94,3 +96,113 @@ def test_watch_raises_without_watchdog(tmp_path, monkeypatch):
from graphify.watch import watch
with pytest.raises(ImportError, match="watchdog not installed"):
watch(tmp_path)
# --- _rebuild_lock (GH-858) ---
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
def test_rebuild_lock_writes_pid_with_newline(tmp_path):
out = tmp_path / "graphify-out"
lock_path = out / ".rebuild.lock"
with _rebuild_lock(out) as got:
assert got is True
assert lock_path.exists()
contents = lock_path.read_text(encoding="utf-8")
assert contents == f"{os.getpid()}\n", contents
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
def test_rebuild_lock_removed_after_release(tmp_path):
"""GH-858: lock file must be unlinked once the rebuild completes so
downstream waiters that poll for its absence unblock promptly."""
out = tmp_path / "graphify-out"
lock_path = out / ".rebuild.lock"
with _rebuild_lock(out) as got:
assert got is True
assert not lock_path.exists(), "lock file should be unlinked after release"
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
def test_rebuild_lock_does_not_accumulate_pids_across_runs(tmp_path):
"""GH-858: each acquisition truncates and rewrites the PID line rather
than appending, so the file never grows into a digit-concatenation."""
out = tmp_path / "graphify-out"
lock_path = out / ".rebuild.lock"
expected = f"{os.getpid()}\n"
for _ in range(5):
with _rebuild_lock(out) as got:
assert got is True
assert lock_path.read_text(encoding="utf-8") == expected
assert not lock_path.exists()
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
def test_rebuild_lock_non_blocking_does_not_clobber_holder(tmp_path):
"""GH-858: a non-blocking caller that fails to acquire the lock must not
truncate the holder's PID payload."""
out = tmp_path / "graphify-out"
lock_path = out / ".rebuild.lock"
with _rebuild_lock(out) as outer:
assert outer is True
held_contents = lock_path.read_text(encoding="utf-8")
with _rebuild_lock(out, blocking=False) as inner:
assert inner is False
# Holder's PID line must still be intact.
assert lock_path.read_text(encoding="utf-8") == held_contents
def test_rebuild_code_is_idempotent_when_cluster_ids_flap(tmp_path, monkeypatch):
from graphify import cluster as cluster_mod
from graphify.watch import _rebuild_code
src = tmp_path / "app.py"
src.write_text("def alpha():\n return 1\n\ndef beta():\n return alpha()\n", encoding="utf-8")
calls = {"n": 0}
def flaky_cluster(G):
calls["n"] += 1
nodes = sorted(G.nodes())
if calls["n"] % 2 == 1:
return {100: nodes}
return {7: nodes}
monkeypatch.setattr(cluster_mod, "cluster", flaky_cluster)
monkeypatch.setattr(cluster_mod, "score_all", lambda _G, comm: {cid: 1.0 for cid in comm})
assert _rebuild_code(tmp_path)
graph_path = tmp_path / "graphify-out" / "graph.json"
report_path = tmp_path / "graphify-out" / "GRAPH_REPORT.md"
first_graph = graph_path.read_text(encoding="utf-8")
first_report = report_path.read_text(encoding="utf-8")
assert _rebuild_code(tmp_path)
second_graph = graph_path.read_text(encoding="utf-8")
second_report = report_path.read_text(encoding="utf-8")
assert first_graph == second_graph
assert first_report == second_report
def test_rebuild_code_skips_cluster_when_topology_unchanged(tmp_path, monkeypatch):
from graphify import cluster as cluster_mod
from graphify.watch import _rebuild_code
src = tmp_path / "app.py"
src.write_text("def alpha():\n return 1\n\ndef beta():\n return alpha()\n", encoding="utf-8")
calls = {"n": 0}
def cluster_once(G):
calls["n"] += 1
if calls["n"] > 1:
raise AssertionError("cluster() should be skipped when topology is unchanged")
return {0: sorted(G.nodes())}
monkeypatch.setattr(cluster_mod, "cluster", cluster_once)
monkeypatch.setattr(cluster_mod, "score_all", lambda _G, comm: {cid: 1.0 for cid in comm})
assert _rebuild_code(tmp_path)
assert _rebuild_code(tmp_path)
assert calls["n"] == 1
+467
View File
@@ -0,0 +1,467 @@
# Graph Report - . (2026-05-13)
## Corpus Check
- cluster-only mode — file stats not available
## Summary
- 1886 nodes · 3876 edges · 141 communities (89 shown, 52 thin omitted)
- Extraction: 90% EXTRACTED · 10% INFERRED · 0% AMBIGUOUS · INFERRED: 393 edges (avg confidence: 0.62)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `6085fd66`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- [[_COMMUNITY_Community 0|Community 0]]
- [[_COMMUNITY_Community 1|Community 1]]
- [[_COMMUNITY_Community 2|Community 2]]
- [[_COMMUNITY_Community 3|Community 3]]
- [[_COMMUNITY_Community 4|Community 4]]
- [[_COMMUNITY_Community 5|Community 5]]
- [[_COMMUNITY_Community 6|Community 6]]
- [[_COMMUNITY_Community 7|Community 7]]
- [[_COMMUNITY_Community 8|Community 8]]
- [[_COMMUNITY_Community 9|Community 9]]
- [[_COMMUNITY_Community 10|Community 10]]
- [[_COMMUNITY_Community 11|Community 11]]
- [[_COMMUNITY_Community 12|Community 12]]
- [[_COMMUNITY_Community 13|Community 13]]
- [[_COMMUNITY_Community 14|Community 14]]
- [[_COMMUNITY_Community 15|Community 15]]
- [[_COMMUNITY_Community 16|Community 16]]
- [[_COMMUNITY_Community 17|Community 17]]
- [[_COMMUNITY_Community 18|Community 18]]
- [[_COMMUNITY_Community 19|Community 19]]
- [[_COMMUNITY_Community 20|Community 20]]
- [[_COMMUNITY_Community 21|Community 21]]
- [[_COMMUNITY_Community 22|Community 22]]
- [[_COMMUNITY_Community 23|Community 23]]
- [[_COMMUNITY_Community 24|Community 24]]
- [[_COMMUNITY_Community 25|Community 25]]
- [[_COMMUNITY_Community 26|Community 26]]
- [[_COMMUNITY_Community 27|Community 27]]
- [[_COMMUNITY_Community 28|Community 28]]
- [[_COMMUNITY_Community 29|Community 29]]
- [[_COMMUNITY_Community 30|Community 30]]
- [[_COMMUNITY_Community 31|Community 31]]
- [[_COMMUNITY_Community 32|Community 32]]
- [[_COMMUNITY_Community 33|Community 33]]
- [[_COMMUNITY_Community 34|Community 34]]
- [[_COMMUNITY_Community 35|Community 35]]
- [[_COMMUNITY_Community 36|Community 36]]
- [[_COMMUNITY_Community 37|Community 37]]
- [[_COMMUNITY_Community 38|Community 38]]
- [[_COMMUNITY_Community 39|Community 39]]
- [[_COMMUNITY_Community 40|Community 40]]
- [[_COMMUNITY_Community 41|Community 41]]
- [[_COMMUNITY_Community 42|Community 42]]
- [[_COMMUNITY_Community 43|Community 43]]
- [[_COMMUNITY_Community 44|Community 44]]
- [[_COMMUNITY_Community 45|Community 45]]
- [[_COMMUNITY_Community 46|Community 46]]
- [[_COMMUNITY_Community 47|Community 47]]
- [[_COMMUNITY_Community 48|Community 48]]
- [[_COMMUNITY_Community 49|Community 49]]
- [[_COMMUNITY_Community 50|Community 50]]
- [[_COMMUNITY_Community 51|Community 51]]
- [[_COMMUNITY_Community 52|Community 52]]
- [[_COMMUNITY_Community 53|Community 53]]
- [[_COMMUNITY_Community 54|Community 54]]
- [[_COMMUNITY_Community 55|Community 55]]
- [[_COMMUNITY_Community 56|Community 56]]
- [[_COMMUNITY_Community 57|Community 57]]
- [[_COMMUNITY_Community 58|Community 58]]
- [[_COMMUNITY_Community 59|Community 59]]
- [[_COMMUNITY_Community 60|Community 60]]
- [[_COMMUNITY_Community 61|Community 61]]
- [[_COMMUNITY_Community 62|Community 62]]
- [[_COMMUNITY_Community 63|Community 63]]
- [[_COMMUNITY_Community 64|Community 64]]
- [[_COMMUNITY_Community 65|Community 65]]
- [[_COMMUNITY_Community 66|Community 66]]
- [[_COMMUNITY_Community 67|Community 67]]
- [[_COMMUNITY_Community 68|Community 68]]
- [[_COMMUNITY_Community 69|Community 69]]
- [[_COMMUNITY_Community 70|Community 70]]
- [[_COMMUNITY_Community 71|Community 71]]
- [[_COMMUNITY_Community 72|Community 72]]
- [[_COMMUNITY_Community 73|Community 73]]
- [[_COMMUNITY_Community 76|Community 76]]
- [[_COMMUNITY_Community 77|Community 77]]
- [[_COMMUNITY_Community 78|Community 78]]
- [[_COMMUNITY_Community 79|Community 79]]
- [[_COMMUNITY_Community 80|Community 80]]
- [[_COMMUNITY_Community 81|Community 81]]
- [[_COMMUNITY_Community 82|Community 82]]
- [[_COMMUNITY_Community 83|Community 83]]
- [[_COMMUNITY_Community 84|Community 84]]
- [[_COMMUNITY_Community 85|Community 85]]
- [[_COMMUNITY_Community 86|Community 86]]
- [[_COMMUNITY_Community 87|Community 87]]
- [[_COMMUNITY_Community 88|Community 88]]
- [[_COMMUNITY_Community 89|Community 89]]
- [[_COMMUNITY_Community 90|Community 90]]
- [[_COMMUNITY_Community 91|Community 91]]
- [[_COMMUNITY_Community 92|Community 92]]
- [[_COMMUNITY_Community 93|Community 93]]
- [[_COMMUNITY_Community 94|Community 94]]
- [[_COMMUNITY_Community 95|Community 95]]
- [[_COMMUNITY_Community 96|Community 96]]
- [[_COMMUNITY_Community 97|Community 97]]
- [[_COMMUNITY_Community 98|Community 98]]
- [[_COMMUNITY_Community 101|Community 101]]
- [[_COMMUNITY_Community 102|Community 102]]
- [[_COMMUNITY_Community 103|Community 103]]
- [[_COMMUNITY_Community 104|Community 104]]
- [[_COMMUNITY_Community 105|Community 105]]
- [[_COMMUNITY_Community 106|Community 106]]
- [[_COMMUNITY_Community 107|Community 107]]
- [[_COMMUNITY_Community 108|Community 108]]
- [[_COMMUNITY_Community 109|Community 109]]
- [[_COMMUNITY_Community 110|Community 110]]
- [[_COMMUNITY_Community 111|Community 111]]
- [[_COMMUNITY_Community 112|Community 112]]
- [[_COMMUNITY_Community 113|Community 113]]
- [[_COMMUNITY_Community 114|Community 114]]
- [[_COMMUNITY_Community 115|Community 115]]
- [[_COMMUNITY_Community 116|Community 116]]
- [[_COMMUNITY_Community 117|Community 117]]
- [[_COMMUNITY_Community 118|Community 118]]
- [[_COMMUNITY_Community 119|Community 119]]
- [[_COMMUNITY_Community 120|Community 120]]
- [[_COMMUNITY_Community 121|Community 121]]
- [[_COMMUNITY_Community 122|Community 122]]
- [[_COMMUNITY_Community 123|Community 123]]
- [[_COMMUNITY_Community 124|Community 124]]
- [[_COMMUNITY_Community 125|Community 125]]
## God Nodes (most connected - your core abstractions)
1. `_make_siege()` - 124 edges
2. `_make_member()` - 92 edges
3. `_make_position()` - 85 edges
4. `SiegeMember` - 78 edges
5. `_make_building()` - 64 edges
6. `_make_group()` - 60 edges
7. `BoardPage()` - 55 edges
8. `makeSiegeMember()` - 55 edges
9. `PostsPage()` - 37 edges
10. `_session_with_siege_and_configs()` - 35 edges
## Surprising Connections (you probably didn't know these)
- `PostPriorityResponse` --uses--> `PostPriorityConfig` [INFERRED]
backend/app/api/post_priority_config.py → frontend/src/api/posts.ts
- `PostPriorityUpdate` --uses--> `PostPriorityConfig` [INFERRED]
backend/app/api/post_priority_config.py → frontend/src/api/posts.ts
- `TestStartupValidation` --uses--> `MemberRole` [INFERRED]
backend/tests/test_auth.py → frontend/src/api/types.ts
- `AuthError` --uses--> `Member` [INFERRED]
backend/app/api/auth.py → frontend/src/api/types.ts
- `import_file()` --calls--> `seed_post_priority_config()` [INFERRED]
scripts/excel-import/import_excel.py → backend/app/db/seeds.py
## Communities (141 total, 52 thin omitted)
### Community 0 - "Community 0"
Cohesion: 0.05
Nodes (84): BuildingUpdate, _make_group(), _make_config(), Service-layer tests for update_building — focus on unbreak restoration., A Mana Shrine at level 5 has 13 teams = 4 full groups + 1 slot last group (4, Stronghold level 6: 10 groups × 3 slots. Break → reduces to base config (4 g, Adding a post-type building must use PostPriorityConfig to set the Post prio, Return a MagicMock shaped like scalars().all() → items. (+76 more)
### Community 1 - "Community 1"
Cohesion: 0.05
Nodes (45): Carousel(), CarouselProps, CarouselSlide, dot0, renderCarousel(), track, viewport, renderDropdown() (+37 more)
### Community 2 - "Community 2"
Cohesion: 0.07
Nodes (61): makeBoard(), _build_assignments_html(), _build_reserves_html(), generate_assignments_image(), generate_reserves_image(), Image generation service — renders HTML/CSS to PNG via Playwright., Build the reserves/members list HTML string. Args: members: Siege m, Render an HTML string to PNG bytes using headless Chromium. (+53 more)
### Community 3 - "Community 3"
Cohesion: 0.05
Nodes (41): activateSiege(), applyAttackDay(), cloneSiege(), completeSiege(), deleteSiege(), getSiege(), getSiegeMembers(), reopenSiege() (+33 more)
### Community 4 - "Community 4"
Cohesion: 0.06
Nodes (60): build_member_notification_message(), _build_section(), _position_label(), _position_sort_key(), PositionInfo, _positions_from_keys(), _positions_to_key_set(), Build rich per-member Discord DM messages for siege assignment notifications. (+52 more)
### Community 5 - "Community 5"
Cohesion: 0.05
Nodes (54): lifespan(), main(), FastAPI application factory and middleware wiring., Run the FastAPI/uvicorn HTTP sidecar on port 8001., Connect and run the Discord client., Start both the Discord client and HTTP server concurrently., Application lifespan — runs startup guards before serving requests., run_discord_client() (+46 more)
### Community 6 - "Community 6"
Cohesion: 0.08
Nodes (53): _make_member(), Return a minimal Member-like namespace., _preview(), Regression for #381. Setup: one member matches a condition that is active o, Invoke preview_post_suggestions with a mocked session., AC: single post with one matching member → suggestion targets that member., AC #6: post with no matching member → skip_reason='no_match'., Charge #1: is_reserve=True on the position → skip_reason='reserve'. (+45 more)
### Community 7 - "Community 7"
Cohesion: 0.09
Nodes (40): compareSiegesSpecific(), createSiege(), getSieges(), CONFIDENCE_LABEL, ConfidenceVariant, ComparisonPage(), formatPosition(), PositionTag() (+32 more)
### Community 8 - "Community 8"
Cohesion: 0.07
Nodes (40): getBoard(), PostPriorityResponse, PostPriorityUpdate, SiegeMemberCreate, AutofillApplyResult, AutofillAssignment, AutofillPreviewResult, BuildingGroupResponse (+32 more)
### Community 9 - "Community 9"
Cohesion: 0.05
Nodes (43): _make_mock_bot_with_guild(), _make_mock_member(), patch_guild_id(), Tests for GET /api/members/{discord_user_id} — guild member lookup endpoint., The @everyone role must never appear in the roles list., When Discord returns NotFound, respond 200 with is_member=false., When Discord raises an unexpected HTTPException, respond 503., When get_guild() returns None (bot not in guild), respond 503. (+35 more)
### Community 10 - "Community 10"
Cohesion: 0.05
Nodes (20): get_config(), Public config endpoint — exposes non-sensitive runtime flags to the frontend., Return public runtime configuration flags. This endpoint is intentionally u, Settings, BaseSettings, Tests for the /api/config public endpoint and startup guards. Covers: - /api/, Backend must refuse to start when SESSION_SECRET is missing and auth is enabled., GET /api/config returns the current auth_disabled flag. (+12 more)
### Community 11 - "Community 11"
Cohesion: 0.06
Nodes (42): Tests for the attack day auto-assign algorithm., Heavy hitters and advanced always get Day 2 regardless of threshold., Medium members are promoted to Day 2 (by power desc) when count < 10., Novice promoted by power desc after medium if still < 10., Overridden Day 2 members count toward the 10-threshold., attack_day_override=True members keep their existing attack_day., Exactly 10 HH/ADV → all remaining go to Day 1., Apply reads stored preview and updates siege_member attack_day values. (+34 more)
### Community 12 - "Community 12"
Cohesion: 0.08
Nodes (42): makeSiegeMember(), _make_batch(), _make_batch_result(), _make_db_session(), Endpoint tests for notification and post-to-channel routes., POST /notify must return 400 with a clear message when siege.date is None., POST /post-to-channel must return 400 with a clear message when siege.date is No, Build a mock DB session that returns the given objects. (+34 more)
### Community 13 - "Community 13"
Cohesion: 0.05
Nodes (43): Endpoints for Discord guild member ↔ clan member sync., Return proposed Discord ↔ clan member matches without writing to the DB., Apply accepted sync matches, updating discord_username and discord_id., applyDiscordSync(), previewDiscordSync(), SyncApply, SyncApplyResponse, Service logic for Discord guild member → clan member matching. (+35 more)
### Community 14 - "Community 14"
Cohesion: 0.06
Nodes (31): PostSuggestionStaleEntry, ChangeCell(), Classification, classify(), ExpiryCountdown, OutcomeFilter, Pill(), PRIORITY_META (+23 more)
### Community 15 - "Community 15"
Cohesion: 0.08
Nodes (30): createMember(), getMember(), getMemberRoles(), getPostConditions(), updateMember(), updateMemberPreferences(), MemberRoleInfo, SyncApplyItem (+22 more)
### Community 16 - "Community 16"
Cohesion: 0.17
Nodes (35): PostPriorityConfig, Building, Member, Post, PostCondition, Siege, SiegeStatus, Base (+27 more)
### Community 17 - "Community 17"
Cohesion: 0.09
Nodes (23): _cors_headers(), _make_app(), Integration tests for the CORS middleware wired in app/main.py. The middleware, Entries that are only whitespace after stripping must be dropped., A request from an explicitly allowed origin must get CORS response headers., The echoed origin must match the request, not be a wildcard., allow_credentials=True means the vary/credentials header is set., The default value from Settings must allow the dev frontend. (+15 more)
### Community 18 - "Community 18"
Cohesion: 0.05
Nodes (24): Tests for backend/app/telemetry.py. Verifies: - configure_telemetry() is a no-o, If configure_azure_monitor raises, the exception is swallowed., Regression tests: FastAPIInstrumentor.instrument_app() must be called. Issu, FastAPIInstrumentor.instrument_app() is called with the FastAPI app. Wh, When APPLICATIONINSIGHTS_CONNECTION_STRING is absent, nothing should happen., configure_azure_monitor() is called when both env vars are present. Reg, No exception and configure_azure_monitor is never imported or called., FastAPIInstrumentor.instrument_app() is NOT called when app argument is None. (+16 more)
### Community 19 - "Community 19"
Cohesion: 0.08
Nodes (36): _get(), Tests for rate limiting on the Discord OAuth2 auth endpoints. Covers: - /api/au, 3rd rapid request to /api/auth/login returns 429 when limit is 2/minute. Th, Two different X-Forwarded-For IPs have independent rate-limit buckets., 3rd rapid request to /api/auth/callback returns 429 when limit is 2/minute., When AUTH_DISABLED=true, 50 rapid requests to /login never return 429., Pathologically long X-Forwarded-For header is handled without error. Constr, Garbage XFF value falls back to the ASGI remote-address bucket. Sending ``X (+28 more)
### Community 20 - "Community 20"
Cohesion: 0.12
Nodes (34): _make_position(), _apply(), _entry_dict(), _preview_data(), Unit tests for the Suggest Post Assignments service. All tests use SimpleNamesp, Null suggested_member_id entries are skipped; no error raised., Position disabled since preview → 409 with reason position_disabled., Position set to reserve since preview → 409 with reason position_reserve. (+26 more)
### Community 21 - "Community 21"
Cohesion: 0.09
Nodes (31): build_group_structure(), compute_building_group_structure(), create_building_with_groups_and_positions(), import_file(), infer_building_level(), map_building_alias(), map_role(), parse_assignments_sheet() (+23 more)
### Community 22 - "Community 22"
Cohesion: 0.1
Nodes (17): apiClient, AppConfig, fetchConfig(), Layout(), navLinkClass(), renderLayout(), RequireAuth(), postsLink (+9 more)
### Community 23 - "Community 23"
Cohesion: 0.1
Nodes (17): downgrade(), initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16, upgrade(), add autofill and attack day preview columns to siege Revision ID: 0002 Revises:, make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1, Add post_priority_config table, Add description to post_priority_config, Replace power with power_level, drop sort_value (+9 more)
### Community 24 - "Community 24"
Cohesion: 0.1
Nodes (24): API router for the Suggest Post Assignments feature. Routes: POST /sieges/{, Generate a greedy post-assignment suggestion preview. Args: siege_i, Apply a caller-filtered subset of the stored preview atomically. Uses SELEC, applyAutofill(), applyPostSuggestions(), previewAttackDay(), previewPostSuggestions(), AttackDayApplyResult (+16 more)
### Community 25 - "Community 25"
Cohesion: 0.1
Nodes (24): compareSieges(), get_most_recent_completed(), _load_assignments(), _load_member_names(), Return {member_id: [PositionKey, ...]} for non-reserve, non-disabled assigned po, _build_siege_assignments(), Tests for siege comparison service and endpoints., Build (Position, BuildingGroup, Building) rows for mock execute results. (+16 more)
### Community 26 - "Community 26"
Cohesion: 0.1
Nodes (24): AuthError, callback(), _check_guild_membership(), _error_redirect(), _exchange_code_for_token(), _get_discord_user(), login(), logout() (+16 more)
### Community 27 - "Community 27"
Cohesion: 0.13
Nodes (22): _async_client_that_raises(), _async_client_that_returns(), _make_ok_response(), Tests for bot HTTP client graceful degradation., get_member() returns the member dict when sidecar responds 200., get_member() returns the dict as-is when sidecar responds with is_member=False., get_member() raises httpx.HTTPError when the sidecar is unreachable., get_member() raises httpx.HTTPStatusError when sidecar returns 503. (+14 more)
### Community 28 - "Community 28"
Cohesion: 0.09
Nodes (9): Tests for scripts/import_excel.py parsing logic. All tests are pure-function te, Stronghold: 4 groups all with 3 slots., Only assignments for the specified (type, number) pair are counted., Returns None when the extracted date components don't form a valid date., 1 total position in a post -> level 1., test_build_group_structure_stronghold(), test_compute_building_group_structure_filters_by_building_number(), test_infer_building_level_post() (+1 more)
### Community 29 - "Community 29"
Cohesion: 0.09
Nodes (22): Tests for GET /api/version endpoint and _read_backend_version helper., GET /api/version responds 200 with all required fields., backend_version includes build metadata when env vars are present., backend_version is bare semver when BUILD_NUMBER/GIT_SHA are absent., git_sha top-level field is still returned for backward compatibility., Force re-import of version module so env-var reads pick up monkeypatches., bot_version is null when the bot sidecar is unreachable., When BUILD_NUMBER / GIT_SHA are absent, return bare semver. (+14 more)
### Community 30 - "Community 30"
Cohesion: 0.1
Nodes (16): get_team_count(), Return the theoretical total team slots for a building type at a given level., compute_scroll_count(), Compute total scroll count from the theoretical capacity of every building., Enable SQLite foreign key enforcement (no-op on PostgreSQL)., _enable_sqlite_fk(), Enable SQLite foreign key enforcement., compute_scroll_count returns the sum of _LEVEL_TEAMS capacities for all building (+8 more)
### Community 31 - "Community 31"
Cohesion: 0.11
Nodes (21): _make_mock_db(), A correct Bearer token grants access as the bot-service principal., Full valid callback flow issues a session cookie and redirects to /., Guild member WITH the required role passes the role check and proceeds normally., Return an AsyncMock session whose db.get() returns `member`., test_callback_happy_path(), test_callback_with_required_role_proceeds_to_member_lookup(), test_valid_service_token_allows_access() (+13 more)
### Community 32 - "Community 32"
Cohesion: 0.15
Nodes (20): PostSuggestionApplyRequest, Request body for POST /post-suggestions/apply. Attributes: apply_po, engine(), Integration tests for the Suggest Post Assignments feature. These tests use a r, Charge #12: selectinload chain works against real DB. Verifies that no Miss, Second preview within TTL overwrites first in the DB JSON column. Asserts b, Charge #17: apply → re-read position from DB → matched_condition_id set. Wi, Charge #22: member_changed reason fires when position written between preview an (+12 more)
### Community 33 - "Community 33"
Cohesion: 0.1
Nodes (17): _make_expired_jwt(), Tests for Discord OAuth2 auth middleware and endpoints., A wrong Bearer token is rejected with 401., An expired JWT cookie is rejected with 401., /api/version is accessible without any credentials., Mismatched OAuth state redirects to /login?error=invalid_state., Guild member response without role_names key is treated as no roles (rejected)., Bot sidecar connection error redirects to /login?error=service_unavailable. (+9 more)
### Community 34 - "Community 34"
Cohesion: 0.22
Nodes (17): generate_images(), Image generation endpoints., Generate PNG images for siege assignments and members list., getNotificationBatch(), notifySiegeMembers(), postToChannel(), Notification endpoints — send DMs and post images to Discord., Send DM notifications to all siege members asynchronously. (+9 more)
### Community 35 - "Community 35"
Cohesion: 0.12
Nodes (17): apiAddBuilding(), apiCreateMember(), apiCreateSiege(), autofillBtn, buildingsTab, chevron, firstPositionSpan, positionCell (+9 more)
### Community 36 - "Community 36"
Cohesion: 0.11
Nodes (13): PostSuggestionPreviewResult, applyBtn, board, btn, chip, labels, makePostBoard(), makeTwoPostBoard() (+5 more)
### Community 37 - "Community 37"
Cohesion: 0.15
Nodes (14): Send DMs for each member and record results in a fresh DB session., _send_dms(), Find member by username in the guild, open DM, send message., Find text channel by name, post message., Find text channel by name, post image as Discord file attachment. Retur, Discord client for the Siege Assignment System., SiegeBot, _get_bot() (+6 more)
### Community 38 - "Community 38"
Cohesion: 0.14
Nodes (13): getPostPriorities(), getPosts(), updatePostPriority(), getSiegeMemberPreferences(), DuplicateConditionMap, MemberWithMatches, postsTab, priorityBadgeColor() (+5 more)
### Community 39 - "Community 39"
Cohesion: 0.19
Nodes (15): bulk_update_positions(), list_posts(), Build a PostResponse-compatible dict, denormalizing building_number from the rel, _serialize_post(), setPostConditions(), updatePost(), Update a single position's assignment. Raises: 404 if position not, Apply multiple position updates in a single transaction. Each update dict m (+7 more)
### Community 40 - "Community 40"
Cohesion: 0.17
Nodes (14): VersionInfo, _fetch_bot_version(), getVersion(), Return a version string for the backend. When both BUILD_NUMBER and GIT_SHA, Call the bot sidecar's /version endpoint. Returns None if unreachable., Return version information for all components., _read_backend_version(), useVersion() (+6 more)
### Community 41 - "Community 41"
Cohesion: 0.15
Nodes (11): ChangelogStatus, fetchChangelogStatus(), DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioItem, DropdownMenuSeparator (+3 more)
### Community 42 - "Community 42"
Cohesion: 0.16
Nodes (14): list_buildings(), list_members(), list_post_priorities(), list_siege_members(), delete_siege(), get_siege(), list_sieges(), previewAutofill() (+6 more)
### Community 43 - "Community 43"
Cohesion: 0.13
Nodes (14): db_session(), Schema constraint and seed data tests using in-memory SQLite., seed_building_type_config populates exactly 5 rows., Inserting a duplicate (siege_id, member_id) pair raises IntegrityError., Inserting two members with the same name must raise IntegrityError., The check constraint preventing is_reserve=True with a member_id is defined., slot_count check constraints (1–3) are declared on the table., seed_post_conditions populates exactly 36 rows. (+6 more)
### Community 44 - "Community 44"
Cohesion: 0.14
Nodes (13): Schema-aware tests for Member.last_seen_changelog_at (issue #295, AC 1). These, Mapped type annotation allows a datetime value. Assigning a real datetime m, Member mapper exposes last_seen_changelog_at as a mapped attribute., last_seen_changelog_at column is defined nullable=True. Null is the sentine, last_seen_changelog_at has no server-side default. Null is the intentional, last_seen_changelog_at uses SQLAlchemy DateTime (no timezone). Matches the, Mapped type annotation allows None (datetime | None). Constructing a Member, test_last_seen_changelog_at_accepts_datetime_at_python_level() (+5 more)
### Community 45 - "Community 45"
Cohesion: 0.23
Nodes (13): add_building(), add_group(), delete_group(), deleteBuilding(), getBuildings(), updateBuilding(), _create_groups_and_positions(), _get_building_type_config() (+5 more)
### Community 46 - "Community 46"
Cohesion: 0.2
Nodes (11): _make_post_priority_config(), _make_post_ns(), _make_src_building_ns(), _make_src_group_ns(), _make_src_position_ns(), Endpoint tests for siege lifecycle transitions: activate, complete, clone., Cloning a siege with stale priority=0 posts must use PostPriorityConfig.priority, test_activate_planning_siege() (+3 more)
### Community 47 - "Community 47"
Cohesion: 0.36
Nodes (12): _make_bot(), _make_guild(), _make_text_channel(), Unit tests for SiegeBot Discord client methods using mock guild/member objects., Create a SiegeBot instance with a pre-loaded guild (bypasses Discord connect)., test_get_members_returns_correct_dict_format(), test_post_image_returns_cdn_url(), test_post_message_finds_channel_and_sends() (+4 more)
### Community 48 - "Community 48"
Cohesion: 0.15
Nodes (13): _make_worksheet(), Create a mock openpyxl worksheet that yields the given rows., Parses name, power_level bucket, and role from correct column positions., Column E is parsed as a slash-separated list of keyword strings., Empty or None column E results in an empty list., test_parse_members_sheet_basic(), test_parse_members_sheet_post_preferences(), test_parse_members_sheet_skips_empty_rows() (+5 more)
### Community 49 - "Community 49"
Cohesion: 0.25
Nodes (10): get_changelog_status(), markChangelogSeen(), Changelog status and mark-seen endpoints. These endpoints let the frontend trac, Raise HTTP 400 if the caller is a service principal. Args: current_, Return the authenticated user's last-seen changelog timestamp. Args:, Set the authenticated user's last-seen changelog timestamp to now. Idempote, _require_member_session(), ChangelogStatusResponse (+2 more)
### Community 50 - "Community 50"
Cohesion: 0.18
Nodes (9): health(), get_guild_member(), NotifyRequest, PostMessageRequest, Look up a single guild member by Discord user ID. Returns ``{"is_member": f, Validate the Bearer token against the configured bot API key., Health check — no authentication required., set_bot() (+1 more)
### Community 51 - "Community 51"
Cohesion: 0.2
Nodes (8): Exception, disable_auth_for_tests(), _FakeClient, _FakeHTTPException, _FakeNotFound, _FakeTextChannel, Shared pytest configuration for backend tests. Sets required environment variab, Bypass auth middleware for all tests by default. Individual tests that exer
### Community 52 - "Community 52"
Cohesion: 0.33
Nodes (9): MemberRole, SyncMatch, SyncPreviewResponse, PowerLevel, MemberBase, MemberCreate, MemberPreferencesUpdate, MemberResponse (+1 more)
### Community 53 - "Community 53"
Cohesion: 0.24
Nodes (9): _get_client_ip(), _parse_retry_after_seconds(), rate_limit_exceeded_handler(), _rate_limit_key(), Rate-limiting utilities shared across the application. This module owns the sin, Composite key function that honours the AUTH_DISABLED bypass. When ``AUTH_D, Parse a slowapi rate-limit detail string into a window size in seconds. slo, Return a JSON 429 response with a ``Retry-After`` header. Replaces slowapi' (+1 more)
### Community 54 - "Community 54"
Cohesion: 0.24
Nodes (9): _build_valid_siege_graph(), Integration test: full siege lifecycle — create → validate → assign → activate →, Build a siege with exactly the right building counts and assigned active members, Return a mock async session that serves the siege + configs across multiple exec, Happy-path: validate (errors) → assign → validate (0 errors) → activate → comple, test_full_siege_lifecycle(), _make_session(), Return a minimal AsyncSession mock that scalar_one_or_none returns siege. (+1 more)
### Community 55 - "Community 55"
Cohesion: 0.2
Nodes (10): _make_jwt(), A valid JWT session cookie with an existing member grants access., A JWT signed with a different secret is rejected with 401., A valid JWT whose member no longer exists in the DB returns 401., GET /api/auth/me returns member info when authenticated via session cookie., test_jwt_with_deleted_member_returns_401(), test_jwt_with_wrong_secret_returns_401(), test_me_with_valid_session() (+2 more)
### Community 56 - "Community 56"
Cohesion: 0.22
Nodes (10): _make_empty_worksheet(), _make_session_mock(), _make_workbook_mock(), Worksheet that yields no rows., Minimal openpyxl workbook mock. Members / Assignments / Reserves are empty, AsyncMock session whose execute() returns a result whose scalars().all() is []., When is_most_recent=False, section 3c must not run even if the Posts sheet p, When is_most_recent=True and the DB has no PostPriorityConfig rows yet, sect (+2 more)
### Community 57 - "Community 57"
Cohesion: 0.32
Nodes (6): get_member(), getMemberPreferences(), Return list of guild members as dicts with id, username, and display_name., Retrieve guild member list., Check guild membership via bot sidecar. Returns the member dict (includi, deactivate_member()
### Community 58 - "Community 58"
Cohesion: 0.25
Nodes (8): _make_assignments_worksheet(), Build a mock assignments worksheet with the proper two header rows prepended., Rows with a None group cell are skipped., Whitespace-only cell values normalise to None., test_parse_assignments_sheet_empty_value_is_none(), test_parse_assignments_sheet_member_assignment(), test_parse_assignments_sheet_skips_incomplete_rows(), test_parse_assignments_sheet_skips_unknown_building_type()
### Community 59 - "Community 59"
Cohesion: 0.25
Nodes (8): _make_posts_config_worksheet(), Create a mock worksheet for parse_posts_sheet_config. The function calls ws, One high-priority section with two posts: both get priority=3 and correct descri, Rows before any priority header default to priority=1 (Low)., Posts fall into the correct priority section based on their position., test_parse_posts_sheet_config_basic(), test_parse_posts_sheet_config_default_priority(), test_parse_posts_sheet_config_multiple_sections()
### Community 60 - "Community 60"
Cohesion: 0.29
Nodes (3): test_create_member_returns_201(), test_delete_member_returns_204(), Endpoint tests for /api/sieges — mocks the service layer directly.
### Community 61 - "Community 61"
Cohesion: 0.4
Nodes (5): notify(), Send a DM notification to a guild member., BotClient, HTTP client for the Discord bot sidecar API., Send DM via bot. Returns True on success, False on error.
### Community 63 - "Community 63"
Cohesion: 0.33
Nodes (5): Tests for enum definitions and associated constants in app.models.enums., BUILDING_TYPE_LABELS values must be non-empty title-cased display strings., Every BuildingType member must have an entry in BUILDING_TYPE_LABELS. This, test_building_type_labels_are_friendly_strings(), test_building_type_labels_covers_all_values()
### Community 64 - "Community 64"
Cohesion: 0.33
Nodes (6): _make_posts_conditions_worksheet(), Create a mock worksheet for parse_posts_sheet_conditions. The function enum, Three post rows with 1–3 keywords each are parsed correctly., A row with all-None cells is not included in the result., test_parse_posts_sheet_conditions_basic(), test_parse_posts_sheet_conditions_skips_empty()
### Community 65 - "Community 65"
Cohesion: 0.4
Nodes (3): _make_post_condition(), Endpoint tests for /api reference data endpoints., test_get_post_conditions_returns_list()
### Community 67 - "Community 67"
Cohesion: 0.4
Nodes (5): Mana shrine with 2 groups: position 3 is an empty trailing sheet column for grou, Stronghold level 2 = 16 total slots = 5 full groups (3 slots each) + 1 last grou, Stronghold level 4 = 22 total slots = 7 full groups + 1 last group with 1 slot., Defense Tower level 4 = 6 total slots = 2 full groups × 3 slots each. At lev, test_compute_building_group_structure_basic()
### Community 69 - "Community 69"
Cohesion: 0.5
Nodes (3): configure_telemetry(), Application Insights / OpenTelemetry initialisation for the backend. Call ``con, Initialise Azure Monitor OpenTelemetry and instrument the app. The ``azure-
### Community 71 - "Community 71"
Cohesion: 0.5
Nodes (4): Magic tower (base_last_slots=2): position 3 is a trailing empty sheet column and, Magic tower at a higher level where position 3 is genuinely filled: slot_cou, Magic Tower level 3 = 4 total slots = 1 full group (3 slots) + 1 last group with, test_compute_building_group_structure_magic_tower_level3()
### Community 72 - "Community 72"
Cohesion: 0.67
Nodes (3): Mana Shrine level 2 = 7 total slots = 2 full groups + 1 last group with 1 slot., Mana Shrine level 4 = 11 total slots = 3 full groups + 1 last group with 2 slots, test_compute_building_group_structure_mana_shrine_level2()
### Community 73 - "Community 73"
Cohesion: 0.67
Nodes (3): Returns None for a filename that does not match the pattern., Returns None for a completely unrelated filename., test_parse_filename_invalid_random()
## Knowledge Gaps
- **752 isolated node(s):** `initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16`, `add autofill and attack day preview columns to siege Revision ID: 0002 Revises:`, `make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1`, `Add post_priority_config table`, `Add description to post_priority_config` (+747 more)
These have ≤1 connection - possible missing edges or undocumented components.
- **52 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `_make_siege()` connect `Community 12` to `Community 0`, `Community 1`, `Community 3`, `Community 36`, `Community 6`, `Community 11`, `Community 46`, `Community 20`, `Community 54`, `Community 22`, `Community 25`, `Community 30`?**
_High betweenness centrality (0.183) - this node is a cross-community bridge._
- **Why does `SiegeMember` connect `Community 3` to `Community 1`, `Community 34`, `Community 35`, `Community 36`, `Community 6`, `Community 38`, `Community 8`, `Community 7`, `Community 42`, `Community 12`, `Community 14`, `Community 15`, `Community 16`, `Community 22`, `Community 24`, `Community 57`?**
_High betweenness centrality (0.167) - this node is a cross-community bridge._
- **Why does `list` connect `Community 42` to `Community 0`, `Community 1`, `Community 56`, `Community 5`, `Community 6`, `Community 39`, `Community 38`, `Community 45`, `Community 13`, `Community 15`, `Community 21`, `Community 24`, `Community 57`, `Community 58`?**
_High betweenness centrality (0.089) - this node is a cross-community bridge._
- **Are the 17 inferred relationships involving `SiegeMember` (e.g. with `Base` and `TestSeedDemoMembers`) actually correct?**
_`SiegeMember` has 17 INFERRED edges - model-reasoned connections that need verification._
- **What connects `initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16`, `add autofill and attack day preview columns to siege Revision ID: 0002 Revises:`, `make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1` to the rest of the system?**
_752 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `Community 0` be split into smaller, more focused modules?**
_Cohesion score 0.05 - nodes in this community are weakly interconnected._
- **Should `Community 1` be split into smaller, more focused modules?**
_Cohesion score 0.05 - nodes in this community are weakly interconnected._
+88
View File
@@ -0,0 +1,88 @@
# Case Study: rsl-siege-manager (Python + TypeScript monorepo)
A graphify dry-run against [`glitchwerks/rsl-siege-manager`](https://github.com/glitchwerks/rsl-siege-manager) — a real-world web app with a Python (FastAPI) backend, a TypeScript (React + Vite) frontend, and a Python Discord bot, all in one repo. Captured here as a worked example of running graphify on a mixed-language full-stack codebase that includes a substantial test suite.
**Corpus:** `glitchwerks/rsl-siege-manager` @ commit `6085fd66`
**Date:** 2026-05-15
**Findings:** [`review.md`](./review.md)
**Raw artifacts:** [`GRAPH_REPORT.md`](./GRAPH_REPORT.md), [`graph.html`](./graph.html), [`graph.json`](./graph.json), [`manifest.json`](./manifest.json)
## How to reproduce
### 1. Clone the corpus
```bash
git clone https://github.com/glitchwerks/rsl-siege-manager
cd rsl-siege-manager
git checkout 6085fd66
```
### 2. Install the CLI
```powershell
uv tool install graphifyy
```
> The PyPI package is `graphifyy` (double-y). The CLI command is `graphify`.
Verify it's on PATH:
```powershell
graphify --version
```
If "not recognized" on Windows, open a new shell — `uv tool` updates PATH but the current session won't see it.
### 3. Run extraction
This case study ran extraction with no `.graphifyignore` (the run included tests). To reproduce a tests-included run:
```powershell
graphify extract .
```
Watch terminal output. graphify uses tree-sitter for code (free, fast) and LLM API calls only for non-code files (markdown, PDFs, images). On a code-heavy repo like rsl-siege-manager, the cost is dominated by docs.
Check the cost summary when it finishes:
```powershell
Get-Content .\graphify-out\cost.json
```
### 4. Inspect
```powershell
# The headline summary an assistant would read
code .\graphify-out\GRAPH_REPORT.md
# The interactive graph
Start-Process .\graphify-out\graph.html
```
## What's in this directory
| File | What it is |
|---|---|
| `README.md` | This file — corpus description + reproduction steps |
| `review.md` | Findings against the headline outputs in `GRAPH_REPORT.md` |
| `GRAPH_REPORT.md` | Raw graphify report (god nodes, communities, surprising connections, suggested questions) |
| `graph.html` | Interactive force-directed visualization |
| `graph.json` | Underlying graph data used by `graphify query` |
| `manifest.json` | Per-file extraction record |
The AST cache (`graphify-out/cache/`) is regenerable and not committed.
## Why this corpus
rsl-siege-manager is structurally interesting for graphify evaluation because:
- **Three services in one repo** — Python backend, TypeScript frontend, Python bot — exercises cross-language inference.
- **Substantial test suite** — both Python (`backend/tests/`) and TypeScript (`frontend/src/**/__tests__/`) — surfaces how degree-centrality behaves on covered codebases.
- **17 Alembic migrations** with revision docstrings — exercises how docstring-shaped content is or is not treated as graph entities.
- **Clean three-tier architecture** — a developer can describe the structure in one sentence, giving a clear ground truth to evaluate community detection against.
## Reference
- graphify repo: https://github.com/safishamsi/graphify
- graphify PyPI: https://pypi.org/project/graphifyy/
- rsl-siege-manager: https://github.com/glitchwerks/rsl-siege-manager
+305
View File
@@ -0,0 +1,305 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>graphify - graphify-out\graph.html</title>
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #0f0f1a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; display: flex; height: 100vh; overflow: hidden; }
#graph { flex: 1; }
#sidebar { width: 280px; background: #1a1a2e; border-left: 1px solid #2a2a4e; display: flex; flex-direction: column; overflow: hidden; }
#search-wrap { padding: 12px; border-bottom: 1px solid #2a2a4e; }
#search { width: 100%; background: #0f0f1a; border: 1px solid #3a3a5e; color: #e0e0e0; padding: 7px 10px; border-radius: 6px; font-size: 13px; outline: none; }
#search:focus { border-color: #4E79A7; }
#search-results { max-height: 140px; overflow-y: auto; padding: 4px 12px; border-bottom: 1px solid #2a2a4e; display: none; }
.search-item { padding: 4px 6px; cursor: pointer; border-radius: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.search-item:hover { background: #2a2a4e; }
#info-panel { padding: 14px; border-bottom: 1px solid #2a2a4e; min-height: 140px; }
#info-panel h3 { font-size: 13px; color: #aaa; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.05em; }
#info-content { font-size: 13px; color: #ccc; line-height: 1.6; }
#info-content .field { margin-bottom: 5px; }
#info-content .field b { color: #e0e0e0; }
#info-content .empty { color: #555; font-style: italic; }
.neighbor-link { display: block; padding: 2px 6px; margin: 2px 0; border-radius: 3px; cursor: pointer; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 3px solid #333; }
.neighbor-link:hover { background: #2a2a4e; }
#neighbors-list { max-height: 160px; overflow-y: auto; margin-top: 4px; }
#legend-wrap { flex: 1; overflow-y: auto; padding: 12px; }
#legend-wrap h3 { font-size: 13px; color: #aaa; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; }
.legend-item { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; font-size: 12px; }
.legend-item:hover { background: #2a2a4e; padding-left: 4px; }
.legend-item.dimmed { opacity: 0.35; }
.legend-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.legend-count { color: #666; font-size: 11px; }
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
#legend-controls { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; padding: 4px 0; }
#legend-controls label { display: flex; align-items: center; gap: 6px; cursor: pointer; font-size: 12px; color: #aaa; user-select: none; }
#legend-controls label:hover { color: #e0e0e0; }
.legend-cb, #select-all-cb { appearance: none; -webkit-appearance: none; width: 14px; height: 14px; border: 1.5px solid #3a3a5e; border-radius: 3px; background: #0f0f1a; cursor: pointer; position: relative; flex-shrink: 0; }
.legend-cb:checked, #select-all-cb:checked { background: #4E79A7; border-color: #4E79A7; }
.legend-cb:checked::after, #select-all-cb:checked::after { content: ''; position: absolute; left: 3.5px; top: 1px; width: 4px; height: 7px; border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg); }
#select-all-cb:indeterminate { background: #4E79A7; border-color: #4E79A7; }
#select-all-cb:indeterminate::after { content: ''; position: absolute; left: 2px; top: 5px; width: 8px; height: 2px; background: #fff; border: none; transform: none; }
</style>
</head>
<body>
<div id="graph"></div>
<div id="sidebar">
<div id="search-wrap">
<input id="search" type="text" placeholder="Search nodes..." autocomplete="off">
<div id="search-results"></div>
</div>
<div id="info-panel">
<h3>Node Info</h3>
<div id="info-content"><span class="empty">Click a node to inspect it</span></div>
</div>
<div id="legend-wrap">
<h3>Communities</h3>
<div id="legend-controls">
<label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
</div>
<div id="legend"></div>
</div>
<div id="stats">1886 nodes &middot; 3876 edges &middot; 141 communities</div>
</div>
<script>
const RAW_NODES = [{"id": "backend_alembic_env_py", "label": "env.py", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 11.0, "font": {"size": 0, "color": "#ffffff"}, "title": "env.py", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 4}, {"id": "alembic_env_run_migrations_offline", "label": "run_migrations_offline()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "run_migrations_offline()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 1}, {"id": "alembic_env_do_run_migrations", "label": "do_run_migrations()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "do_run_migrations()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 1}, {"id": "alembic_env_run_async_migrations", "label": "run_async_migrations()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.5, "font": {"size": 0, "color": "#ffffff"}, "title": "run_async_migrations()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 2}, {"id": "alembic_env_run_migrations_online", "label": "run_migrations_online()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.5, "font": {"size": 0, "color": "#ffffff"}, "title": "run_migrations_online()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 2}, {"id": "backend_alembic_versions_0001_initial_schema_py", "label": "0001_initial_schema.py", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.7, "font": {"size": 0, "color": "#ffffff"}, "title": "0001_initial_schema.py", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "code", "degree": 3}, {"id": "versions_0001_initial_schema_upgrade", "label": "upgrade()", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 13.1, "font": {"size": 0, "color": "#ffffff"}, "title": "upgrade()", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "code", "degree": 13}, {"id": "versions_0001_initial_schema_downgrade", "label": "downgrade()", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 13.1, "font": {"size": 0, "color": "#ffffff"}, "title": "downgrade()", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "code", "degree": 13}, {"id": "versions_0001_initial_schema_rationale_1", "label": "initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "rationale", "degree": 1}, {"id": "backend_alembic_versions_0002_add_preview_columns_py", "label": "0002_add_preview_columns.py", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.7, "font": {"size": 0, "color": "#ffffff"}, "title": "0002_add_preview_columns.py", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0002_add_preview_columns.py", "file_type": "code", "degree": 3}, {"id": "versions_0002_add_preview_columns_rationale_1", "label": "add autofill and attack day preview columns to siege Revision ID: 0002 Revises:", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "add autofill and attack day preview columns to siege Revision ID: 0002 Revises:", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0002_add_preview_columns.py", "file_type": "rationale", "degree": 1}, {"id": "backend_alembic_versions_0003_make_siege_date_nullable_py", "label"Line truncated
const RAW_EDGES = [{"from": "backend_alembic_env_py", "to": "alembic_env_run_migrations_offline", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_env_py", "to": "alembic_env_do_run_migrations", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_env_py", "to": "alembic_env_run_async_migrations", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_env_py", "to": "alembic_env_run_migrations_online", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "alembic_env_run_migrations_online", "to": "alembic_env_run_async_migrations", "label": "calls", "title": "calls [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0001_initial_schema_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0001_initial_schema_py", "to": "versions_0001_initial_schema_downgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "versions_0001_initial_schema_rationale_1", "to": "backend_alembic_versions_0001_initial_schema_py", "label": "rationale_for", "title": "rationale_for [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0002_add_preview_columns_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0003_make_siege_date_nullable_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0004_add_post_priority_config_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0005_add_description_to_post_priority_config_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0006_power_level_and_drop_sort_value_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0007_fix_group_number_max_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0008_add_matched_condition_id_to_position_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0009_add_discord_id_to_member_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0010_add_last_seen_changelog_at_to_member_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "versions_0010_add_last_seen_changelog_at_to_member_rationale_25", "to": "versions_0001_initial_schema_upgrade", "label": "rationale_for", "title": "rationale_for [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0011_add_post_suggest_preview_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "versions_0011_add_post_suggest_preview_rationale_23", "to": "versions_0001_initial_schema_upgrade", "label": "rationale_for", "title": "rationale_for [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0002_add_preLine truncated
const LEGEND = [{"cid": 0, "color": "#4E79A7", "label": "Community 0", "count": 87}, {"cid": 1, "color": "#F28E2B", "label": "Community 1", "count": 66}, {"cid": 2, "color": "#E15759", "label": "Community 2", "count": 63}, {"cid": 3, "color": "#76B7B2", "label": "Community 3", "count": 62}, {"cid": 4, "color": "#59A14F", "label": "Community 4", "count": 62}, {"cid": 5, "color": "#EDC948", "label": "Community 5", "count": 60}, {"cid": 6, "color": "#B07AA1", "label": "Community 6", "count": 55}, {"cid": 7, "color": "#FF9DA7", "label": "Community 7", "count": 51}, {"cid": 8, "color": "#9C755F", "label": "Community 8", "count": 51}, {"cid": 9, "color": "#BAB0AC", "label": "Community 9", "count": 50}, {"cid": 10, "color": "#4E79A7", "label": "Community 10", "count": 49}, {"cid": 11, "color": "#F28E2B", "label": "Community 11", "count": 47}, {"cid": 12, "color": "#E15759", "label": "Community 12", "count": 45}, {"cid": 13, "color": "#76B7B2", "label": "Community 13", "count": 45}, {"cid": 14, "color": "#59A14F", "label": "Community 14", "count": 40}, {"cid": 15, "color": "#EDC948", "label": "Community 15", "count": 40}, {"cid": 16, "color": "#B07AA1", "label": "Community 16", "count": 40}, {"cid": 17, "color": "#FF9DA7", "label": "Community 17", "count": 39}, {"cid": 18, "color": "#9C755F", "label": "Community 18", "count": 38}, {"cid": 19, "color": "#BAB0AC", "label": "Community 19", "count": 37}, {"cid": 20, "color": "#4E79A7", "label": "Community 20", "count": 35}, {"cid": 21, "color": "#F28E2B", "label": "Community 21", "count": 32}, {"cid": 22, "color": "#E15759", "label": "Community 22", "count": 28}, {"cid": 23, "color": "#76B7B2", "label": "Community 23", "count": 28}, {"cid": 24, "color": "#59A14F", "label": "Community 24", "count": 26}, {"cid": 25, "color": "#EDC948", "label": "Community 25", "count": 26}, {"cid": 26, "color": "#B07AA1", "label": "Community 26", "count": 25}, {"cid": 27, "color": "#FF9DA7", "label": "Community 27", "count": 23}, {"cid": 28, "color": "#9C755F", "label": "Community 28", "count": 23}, {"cid": 29, "color": "#BAB0AC", "label": "Community 29", "count": 23}, {"cid": 30, "color": "#4E79A7", "label": "Community 30", "count": 22}, {"cid": 31, "color": "#F28E2B", "label": "Community 31", "count": 22}, {"cid": 32, "color": "#E15759", "label": "Community 32", "count": 21}, {"cid": 33, "color": "#76B7B2", "label": "Community 33", "count": 21}, {"cid": 34, "color": "#59A14F", "label": "Community 34", "count": 20}, {"cid": 35, "color": "#EDC948", "label": "Community 35", "count": 19}, {"cid": 36, "color": "#B07AA1", "label": "Community 36", "count": 18}, {"cid": 37, "color": "#FF9DA7", "label": "Community 37", "count": 17}, {"cid": 38, "color": "#9C755F", "label": "Community 38", "count": 17}, {"cid": 39, "color": "#BAB0AC", "label": "Community 39", "count": 16}, {"cid": 40, "color": "#4E79A7", "label": "Community 40", "count": 15}, {"cid": 41, "color": "#F28E2B", "label": "Community 41", "count": 15}, {"cid": 42, "color": "#E15759", "label": "Community 42", "count": 15}, {"cid": 43, "color": "#76B7B2", "label": "Community 43", "count": 15}, {"cid": 44, "color": "#59A14F", "label": "Community 44", "count": 14}, {"cid": 45, "color": "#EDC948", "label": "Community 45", "count": 14}, {"cid": 46, "color": "#B07AA1", "label": "Community 46", "count": 14}, {"cid": 47, "color": "#FF9DA7", "label": "Community 47", "count": 13}, {"cid": 48, "color": "#9C755F", "label": "Community 48", "count": 13}, {"cid": 49, "color": "#BAB0AC", "label": "Community 49", "count": 11}, {"cid": 50, "color": "#4E79A7", "label": "Community 50", "count": 11}, {"cid": 51, "color": "#F28E2B", "label": "Community 51", "count": 11}, {"cid": 52, "color": "#E15759", "label": "Community 52", "count": 11}, {"cid": 53, "color": "#76B7B2", "label": "Community 53", "count": 10}, {"cid": 54, "color": "#59A14F", "label": "Community 54", "count": 10}, {"cid": 55, "color": "#EDC948", "label": "Community 55", "count": 10}, {"cid": 56, "color": "#B07AA1", "label": "Community 56", "count": 10}, {"cid": 57, "color": "#FF9DA7", "label": "Community 57", "count": 8}, {"cid": 58, "color": "#9C755F", "label": "Community 58", "count": 8}, {"cid": 59, "color": "#BAB0AC", "label": "Community 59", "count": 8}, {"cid": 60, "color": "#4E79A7", "label": "Community 60", "count": 7}, {"cid": 61, "color": "#F28E2B", "label": "Community 61", "count": 6}, {"cid": 62, "color": "#E15759", "label": "Community 62", "count": 6}, {"cid": 63, "color": "#76B7B2", "label": "Community 63", "count": 6}, {"cid": 64, "color": "#59A14F", "label": "Community 64", "count": 6}, {"cid": 65, "color": "#EDC948", "label": "Community 65", "count": 6}, {"cid": 66, "color": "#B07AA1", "label": "Community 66", "count": 5}, {"cid": 67, "color": "#FF9DA7", "label": "Community 67", "count": 5}, {"cid": 68, "color": "#9C755F", "label": "Community 68", "count": 4}, {"cid": 69, "color": "#BAB0AC", "label": "Community 69", "count": 4}, {"cid": 70, "color": "#4E79A7", "label": "CommLine truncated
// HTML-escape helper — prevents XSS when injecting graph data into innerHTML
function esc(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}
// Build vis datasets
const nodesDS = new vis.DataSet(RAW_NODES.map(n => ({
id: n.id, label: n.label, color: n.color, size: n.size,
font: n.font, title: n.title,
_community: n.community, _community_name: n.community_name,
_source_file: n.source_file, _file_type: n.file_type, _degree: n.degree,
})));
const edgesDS = new vis.DataSet(RAW_EDGES.map((e, i) => ({
id: i, from: e.from, to: e.to,
label: '',
title: e.title,
dashes: e.dashes,
width: e.width,
color: e.color,
arrows: { to: { enabled: true, scaleFactor: 0.5 } },
})));
const container = document.getElementById('graph');
const network = new vis.Network(container, { nodes: nodesDS, edges: edgesDS }, {
physics: {
enabled: true,
solver: 'forceAtlas2Based',
forceAtlas2Based: {
gravitationalConstant: -60,
centralGravity: 0.005,
springLength: 120,
springConstant: 0.08,
damping: 0.4,
avoidOverlap: 0.8,
},
stabilization: { iterations: 200, fit: true },
},
interaction: {
hover: true,
tooltipDelay: 100,
hideEdgesOnDrag: true,
navigationButtons: false,
keyboard: false,
},
nodes: { shape: 'dot', borderWidth: 1.5 },
edges: { smooth: { type: 'continuous', roundness: 0.2 }, selectionWidth: 3 },
});
network.once('stabilizationIterationsDone', () => {
network.setOptions({ physics: { enabled: false } });
});
function showInfo(nodeId) {
const n = nodesDS.get(nodeId);
if (!n) return;
const neighborIds = network.getConnectedNodes(nodeId);
const neighborItems = neighborIds.map(nid => {
const nb = nodesDS.get(nid);
const color = nb ? nb.color.background : '#555';
return `<span class="neighbor-link" style="border-left-color:${esc(color)}" onclick="focusNode(${JSON.stringify(nid)})">${esc(nb ? nb.label : nid)}</span>`;
}).join('');
document.getElementById('info-content').innerHTML = `
<div class="field"><b>${esc(n.label)}</b></div>
<div class="field">Type: ${esc(n._file_type || 'unknown')}</div>
<div class="field">Community: ${esc(n._community_name)}</div>
<div class="field">Source: ${esc(n._source_file || '-')}</div>
<div class="field">Degree: ${n._degree}</div>
${neighborIds.length ? `<div class="field" style="margin-top:8px;color:#aaa;font-size:11px">Neighbors (${neighborIds.length})</div><div id="neighbors-list">${neighborItems}</div>` : ''}
`;
}
function focusNode(nodeId) {
network.focus(nodeId, { scale: 1.4, animation: true });
network.selectNodes([nodeId]);
showInfo(nodeId);
}
// Track hovered node — hover detection is more reliable than click params
let hoveredNodeId = null;
network.on('hoverNode', params => {
hoveredNodeId = params.node;
container.style.cursor = 'pointer';
});
network.on('blurNode', () => {
hoveredNodeId = null;
container.style.cursor = 'default';
});
container.addEventListener('click', () => {
if (hoveredNodeId !== null) {
showInfo(hoveredNodeId);
network.selectNodes([hoveredNodeId]);
}
});
network.on('click', params => {
if (params.nodes.length > 0) {
showInfo(params.nodes[0]);
} else if (hoveredNodeId === null) {
document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
}
});
const searchInput = document.getElementById('search');
const searchResults = document.getElementById('search-results');
searchInput.addEventListener('input', () => {
const q = searchInput.value.toLowerCase().trim();
searchResults.innerHTML = '';
if (!q) { searchResults.style.display = 'none'; return; }
const matches = RAW_NODES.filter(n => n.label.toLowerCase().includes(q)).slice(0, 20);
if (!matches.length) { searchResults.style.display = 'none'; return; }
searchResults.style.display = 'block';
matches.forEach(n => {
const el = document.createElement('div');
el.className = 'search-item';
el.textContent = n.label;
el.style.borderLeft = `3px solid ${n.color.background}`;
el.style.paddingLeft = '8px';
el.onclick = () => {
network.focus(n.id, { scale: 1.5, animation: true });
network.selectNodes([n.id]);
showInfo(n.id);
searchResults.style.display = 'none';
searchInput.value = '';
};
searchResults.appendChild(el);
});
});
document.addEventListener('click', e => {
if (!searchResults.contains(e.target) && e.target !== searchInput)
searchResults.style.display = 'none';
});
const hiddenCommunities = new Set();
const selectAllCb = document.getElementById('select-all-cb');
function updateSelectAllState() {
const total = LEGEND.length;
const hidden = hiddenCommunities.size;
selectAllCb.checked = hidden === 0;
selectAllCb.indeterminate = hidden > 0 && hidden < total;
}
function toggleAllCommunities(hide) {
document.querySelectorAll('.legend-item').forEach(item => {
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
});
document.querySelectorAll('.legend-cb').forEach(cb => {
cb.checked = !hide;
});
LEGEND.forEach(c => {
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
});
const updates = RAW_NODES.map(n => ({ id: n.id, hidden: hide }));
nodesDS.update(updates);
updateSelectAllState();
}
const legendEl = document.getElementById('legend');
LEGEND.forEach(c => {
const item = document.createElement('div');
item.className = 'legend-item';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'legend-cb';
cb.checked = true;
cb.addEventListener('change', (e) => {
e.stopPropagation();
if (cb.checked) {
hiddenCommunities.delete(c.cid);
item.classList.remove('dimmed');
} else {
hiddenCommunities.add(c.cid);
item.classList.add('dimmed');
}
const updates = RAW_NODES
.filter(n => n.community === c.cid)
.map(n => ({ id: n.id, hidden: !cb.checked }));
nodesDS.update(updates);
updateSelectAllState();
});
item.innerHTML = `<div class="legend-dot" style="background:${c.color}"></div>
<span class="legend-label">${c.label}</span>
<span class="legend-count">${c.count}</span>`;
item.prepend(cb);
item.onclick = (e) => {
if (e.target === cb) return;
cb.checked = !cb.checked;
cb.dispatchEvent(new Event('change'));
};
legendEl.appendChild(item);
});
</script>
<script>
// Render hyperedges as shaded regions
const hyperedges = [];
// afterDrawing passes ctx already transformed to network coordinate space.
// Draw node positions raw — no manual pan/zoom/DPR math needed.
network.on('afterDrawing', function(ctx) {
hyperedges.forEach(h => {
const positions = h.nodes
.map(nid => network.getPositions([nid])[nid])
.filter(p => p !== undefined);
if (positions.length < 2) return;
ctx.save();
ctx.globalAlpha = 0.12;
ctx.fillStyle = '#6366f1';
ctx.strokeStyle = '#6366f1';
ctx.lineWidth = 2;
ctx.beginPath();
// Centroid and expanded hull in network coordinates
const cx = positions.reduce((s, p) => s + p.x, 0) / positions.length;
const cy = positions.reduce((s, p) => s + p.y, 0) / positions.length;
const expanded = positions.map(p => ({
x: cx + (p.x - cx) * 1.15,
y: cy + (p.y - cy) * 1.15
}));
ctx.moveTo(expanded[0].x, expanded[0].y);
expanded.slice(1).forEach(p => ctx.lineTo(p.x, p.y));
ctx.closePath();
ctx.fill();
ctx.globalAlpha = 0.4;
ctx.stroke();
// Label
ctx.globalAlpha = 0.8;
ctx.fillStyle = '#4f46e5';
ctx.font = 'bold 11px sans-serif';
ctx.textAlign = 'center';
ctx.fillText(h.label, cx, cy - 5);
ctx.restore();
});
});
</script>
</body>
</html>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+154
View File
@@ -0,0 +1,154 @@
# Review: rsl-siege-manager
**Corpus:** [`glitchwerks/rsl-siege-manager`](https://github.com/glitchwerks/rsl-siege-manager) @ `6085fd66`
**Date:** 2026-05-15
**Run:** tests included, no `.graphifyignore`
**Counts:** 1886 nodes · 3876 edges · 141 communities · 90% EXTRACTED / 10% INFERRED (avg INFERRED confidence 0.62)
**Cost:** $0 (tree-sitter only; this corpus's natural file mix surfaced no non-code files in meaningful quantity)
**Setup:** ~10 minutes of CLI time end-to-end
This review evaluates the **headline outputs** in `GRAPH_REPORT.md` — god nodes, surprising connections, communities, isolated nodes, suggested questions — against a single criterion: do they reflect things a developer familiar with this codebase would themselves nominate as core, surprising, or worth investigating? Each finding quotes the report directly so it is verifiable against the committed artifacts.
---
## Finding 1 — Test fixtures dominate "core abstractions" when tests are included
Top god nodes, verbatim from `GRAPH_REPORT.md` (lines 141–150):
```
1. `_make_siege()` - 124 edges
2. `_make_member()` - 92 edges
3. `_make_position()` - 85 edges
4. `SiegeMember` - 78 edges
5. `_make_building()` - 64 edges
6. `_make_group()` - 60 edges
7. `BoardPage()` - 55 edges
8. `makeSiegeMember()` - 55 edges
9. `PostsPage()` - 37 edges
10. `_session_with_siege_and_configs()` - 35 edges
```
Six of the top ten — positions 1, 2, 3, 5, 6, and 8 — are test factory functions (`_make_siege`, `_make_member`, `_make_position`, `_make_building`, `_make_group`, `makeSiegeMember`). Position 10 is a test session fixture. These are the highest-connectivity nodes in the graph, and they are infrastructure for verifying the codebase, not the codebase itself.
The god-node list is labeled "your core abstractions" in the report. On this corpus, no developer would nominate `_make_siege()` as a core abstraction of a siege-assignment web app. Degree centrality on a well-tested codebase will tend to surface test factories: by design, factories create the primary domain objects that every test then exercises, so they accumulate edges from every part of the suite. The pattern is structural — the better the test coverage, the more saturated the factory's degree count.
For users running graphify on a codebase with substantial test coverage, the documented mitigation (a `.graphifyignore` excluding `tests/`, `__tests__/`, etc.) is effective at removing this class of false-positive. See Finding 2 for what the same corpus surfaces without tests.
## Finding 2 — Without tests, god nodes mix domain types with entry points and utilities
For comparison, an earlier run of the same corpus with `.graphifyignore` excluding `backend/tests/` and `frontend/src/**/__tests__/` produced this god-node list:
```
1. `SiegeMember` - 55 edges
2. `BoardPage()` - 53 edges
3. `Post Suggestions Modal Handoff` - 40 edges
4. `postsTab` - 29 edges
5. `cn()` - 29 edges
6. `PostsPage()` - 28 edges
7. `BuildingType` - 27 edges
8. `MembersPage()` - 27 edges
9. `MemberRole` - 25 edges
10. `Self-Host on Azure Wiki Page` - 23 edges
```
(That run's artifacts are not committed here — only the tests-included artifacts are kept — but the list is reproducible by re-running with the same `.graphifyignore`.)
Three of ten — `SiegeMember`, `BuildingType`, `MemberRole` (positions 1, 7, 9) — are legitimate domain models a developer would identify.
The other seven illustrate a second pattern worth knowing about:
- **React top-level page components** (`BoardPage`, `PostsPage`, `MembersPage` at 2, 6, 8) — these import many things because they are entry points, not because they encode domain logic.
- **Class-merge utilities** — `cn()` (position 5) is a one-line Tailwind class-merging utility (`src/lib/utils.ts`). It scores 29 edges because every component that conditionally combines classes imports it. The connection count reflects a structural pattern (the React+Tailwind idiom), not semantic importance.
- **Document/wiki entities** — `Post Suggestions Modal Handoff` (position 3) is a planning document under `docs/design-refs/`; `Self-Host on Azure Wiki Page` (position 10) is a wiki article. Both are extracted as nodes alongside code entities and sort by edge count the same way.
This is informative for users tuning expectations: degree centrality on a React frontend with a shared `cn()` utility will surface that utility regardless of how aggressive the ignore filter is, because the connections are real even though the semantic importance is low.
## Finding 3 — Surprising connections cross language boundaries
Both runs surface INFERRED edges between Python backend types and TypeScript frontend types under "Surprising Connections (you probably didn't know these)." Examples:
```
- `AuthError` --uses--> `Member` [INFERRED]
backend/app/api/auth.py → frontend/src/api/types.ts
```
```
- `TestStartupValidation` --uses--> `MemberRole` [INFERRED]
backend/tests/test_auth.py → frontend/src/api/types.ts
```
A Python class does not "use" a TypeScript type at runtime. These are name-based similarity matches between identically-named constructs in two languages, surfaced as semantic relationships. The confidence values are flagged as INFERRED (avg 0.62 on this run), but the section header presents them as insights worth investigating.
The one cross-language INFERRED edge in this run that maps to a real design contract is:
```
- `PostPriorityResponse` --uses--> `PostPriorityConfig` [INFERRED]
backend/app/api/post_priority_config.py → frontend/src/api/posts.ts
```
The backend Pydantic schema and the frontend TypeScript type do mirror each other intentionally — this is the API contract. That relationship is real, but a developer who wrote either side already knows about it; INFERRED detection here recovers a fact rather than discovering one.
For corpora that mix Python and TypeScript with overlapping type names (common in monorepos with shared domain vocabulary), users should expect a high false-positive rate in this section and read it with the INFERRED confidence in mind.
## Finding 4 — Community cohesion is uniformly low on this corpus
Most of rsl-siege-manager's 141 communities (tests-included run) score between 0.05 and 0.17 on cohesion. The report itself flags 0.05 as "weakly interconnected" in the Suggested Questions section:
> "Should `Community 0` be split into smaller, more focused modules? — Cohesion score 0.05 - nodes in this community are weakly interconnected."
Community 0 has 112 nodes on this corpus.
rsl-siege-manager has a clean three-service architecture (backend / frontend / bot). The community-detection pass does not recover that structure as three large cohesive communities; it produces many small communities with low internal cohesion. Possible interpretations: the underlying graph has many INFERRED cross-language edges diluting the cluster signal, the chosen algorithm parameters favor over-segmentation on graphs of this density, or this corpus genuinely lacks tight intra-cluster topology that community detection can exploit.
A neutral framing for users: community cohesion is informative on this corpus mainly as a signal that the graph topology does not match the obvious three-tier mental model — which itself may be useful (it surfaces that the cross-language edges are doing the work). The "split this community" prompts the report generates from low cohesion scores are less actionable as direct architectural advice on this corpus.
## Finding 5 — Alembic migration docstrings surface as isolated nodes
The tests-included run reports 752 isolated nodes; the without-tests run reports 259. The leading examples are identical in both:
```
`initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16`,
`add autofill and attack day preview columns to siege Revision ID: 0002 Revises:`,
`make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1`,
`Add post_priority_config table`, ...
```
These are Alembic migration revision docstrings parsed as standalone graph nodes. There are 17 migration files in this corpus. The isolated-node count growing from 259 to 752 when tests are added is dominated by test docstrings parsed the same way.
The report labels these as "possible documentation gaps or missing edges." For users with corpora that contain Alembic migrations, pytest docstrings, or other docstring-heavy auto-generated files, this label can be misleading — these are change annotations or test descriptions, not architectural entities with missing connections.
A `.graphifyignore` rule for `**/alembic/versions/*.py` reduces the isolated-node count materially on this corpus; users with similar setups may want a default recipe.
## Finding 6 — Suggested questions skew toward graph-property prompts
The Suggested Questions section consists primarily of two kinds of questions:
1. **Betweenness centrality prompts:** "Why does `_make_siege()` connect Community 12 to Community 0, Community 1, Community 3...?" The answer on this corpus is direct: `_make_siege()` creates the primary domain object, every test that touches a siege uses it, and the test suite spans the codebase — so the fixture is a betweenness bridge by construction.
2. **Inferred-edge audits:** "Are the 17 inferred relationships involving `SiegeMember` (e.g. with `Base` and `TestSeedDemoMembers`) actually correct?" These ask the developer to validate the tool's own low-confidence connections.
A genuinely concrete question in this section — "What is the exact relationship between `bootstrap-images.ps1` and `scripts/bootstrap-images.ps1`?" — is tagged AMBIGUOUS by the report. The answer is concrete (they are the same script referenced by two slightly different paths), but it is a file-naming observation, not an architectural insight.
For users hoping the Suggested Questions section will surface domain-level prompts ("how does authentication flow?", "what enforces the siege-day invariant?"), this corpus's section is dominated by graph-property meta-questions.
---
## What worked well on this corpus
- **Throughput:** 1886 nodes extracted in a few minutes at $0 cost. tree-sitter handles all 29 supported languages locally; LLM calls fire only for non-code files.
- **Genuine domain extractions are present:** `SiegeMember`, `BuildingType`, and `MemberRole` in the god-node list are correct. `PostPriorityResponse --uses--> PostPriorityConfig` is a real API contract that INFERRED detection picked up across the Python/TypeScript boundary.
- **`graph.html` visualization:** clear, navigable, easy to filter and search. Useful for browsing communities even when the labelled cohesion scores are low.
The underlying graph build is solid. The findings above are about how the report layer summarizes that graph into headline metrics — specifically, what those metrics surface on a well-tested cross-language full-stack web app.
---
## Suggested follow-ups
Patterns from this review that may be worth tracking upstream:
1. **Test-fixture suppression** — degree centrality on covered codebases consistently surfaces test factories; documenting the ignore-pattern recipe in a "first run on a codebase with tests" section would shorten the iteration loop for users.
2. **Cross-language INFERRED edges in monorepos** — name-based matches between Python and TypeScript types in mixed-language repos may warrant a higher confidence threshold or a "potential contract" label rather than the current "surprising connection" framing.
3. **Docstring-heavy files (Alembic, pytest)** — defaulting to skip migration `versions/` directories, or detecting and grouping docstring nodes that share a structural pattern, would reduce the isolated-node noise materially.
These are observations, not change requests — users running graphify on similar corpora may find the same patterns useful to know about.