Compare commits

...
38 Commits
Author SHA1 Message Date
SafiandClaude Sonnet 4.6 d717415522 Bump version to 0.8.7, update CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:25:04 +01:00
SafiandClaude Sonnet 4.6 b82d5d147f fix review findings from #898 #895 #899 corrections
- Revert .h -> extract_c (C++ grammar rejects C++ keywords used as identifiers
  in Linux-kernel-style headers; .hpp/.hxx/.hh already route to extract_cpp)
- Fix field_declaration block: use children_by_field_name("declarator") instead
  of iterating all children with wrong type guard; replace ensure_node (undefined)
  with add_node
- Fix _import_c include resolution: use _make_id(str(resolved)) to match the
  file_nid scheme _extract_generic uses, not _make_id(_file_stem(resolved))
- Fix exact_merges counter in dedup Pass 1 to count only within-file merges
  actually performed, not the raw unpartitioned group sizes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:20:49 +01:00
SafiandClaude Sonnet 4.6 500e4a732d fix #898 #895 #899: C++ header extraction, dedup cross-file merge, include path resolution
- Route .h files through extract_cpp (was extract_c), fixing missing method nodes in C++ headers
- Extend _get_cpp_func_name to handle field_identifier, destructor_name, operator_name
- Add CPP-specific field_declaration branch in _extract_generic to emit class method/field nodes
- Partition dedup Pass 1 by source_file: only union same-label nodes within the same file;
  cross-file matches fall through to Pass 2 fuzzy, preventing generic-label god nodes
- Add _resolve_c_include_path: resolve quoted #include paths to real files on disk so
  target node IDs match what _extract_generic creates, fixing dangling include edges

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 20:12:09 +01:00
SafiandClaude Sonnet 4.6 a316590adc Fix query seed scoring: IDF weighting, dynamic K seeds, actionable truncation
Common terms like 'error'/'exception' were stealing BFS seed slots from
rare identifiers like 'FooBarService', burning the token budget on noise.

- _compute_idf: weights query terms by inverse document frequency, cached
  on G.graph so cost is paid once per graph load not per query
- _score_nodes: multiplies each tier bonus by IDF weight
- _pick_seeds: replaces fixed top-3 with gap-ratio selection — stops adding
  seeds when score drops below 20% of the top match
- _subgraph_to_text: truncation hint now tells Claude to narrow with
  context_filter or use get_node instead of just saying 'truncated'

Fixes #897

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 16:20:20 +01:00
SafiandClaude Sonnet 4.6 b1ade00ece Bump version to 0.8.6, update CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:37:32 +01:00
SafiandClaude Sonnet 4.6 0157d5f6ad Add pytest testpaths to stop crawling external repos in subdirs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:30:38 +01:00
SafiandClaude Sonnet 4.6 766566f6a8 Fill test gaps from PR #890 and fix case-insensitive path in _is_json_key_node
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:27:01 +01:00
SafiandClaude Sonnet 4.6 aa541a680a Suppress code-doc INFERRED edges and filter JSON key nodes from god_nodes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 14:23:38 +01:00
Safi 8105266800 Add .gitattributes to fix GitHub language detection showing HTML instead of Python 2026-05-16 14:16:07 +01:00
Safi f86b0309e7 Merge pull request #891 from jattree/fix/install-guidance-query-first
Clean merge — fixes real token-bloat regression where GRAPH_REPORT.md was loaded on every question. All 10 install surfaces now route to graphify query first. Also fixes hidden bug where re-running graphify install after upgrade didn't refresh stale hook text.
2026-05-16 14:13:01 +01:00
Safi c74b95c44c Merge pull request #888 from kanya-approve/feat/nuitka-build
Clean merge — PEP 735 [dependency-groups] is invisible to pip/uv tool install, zero runtime impact.
2026-05-16 14:12:58 +01:00
Safi 1ba3e37d27 Merge pull request #887 from alphanury/feat/auto-detect-symlinks-default
Clean merge — fixes real silent data-loss bug in --update on symlinked repos, backward-compatible, inherits existing cycle protection. Follow-up: consider tightening _auto_follow_symlinks to is_symlink() and is_dir() to avoid tripping on incidental symlinked files at root.
2026-05-16 14:12:54 +01:00
Safi 31a9f13cc7 Merge pull request #886 from kanya-approve/chore/commit-uv-lock
Clean merge — uv.lock is correct to commit per current uv guidance, all 152 packages from PyPI only, zero impact on pip/wheel consumers.
2026-05-16 14:12:52 +01:00
Jon Attree d1a2c3f958 Stop telling assistants to read GRAPH_REPORT.md first (#580)
The current install writes "ALWAYS read graphify-out/GRAPH_REPORT.md
before reading any source files, running grep/glob searches, or
answering codebase questions" into CLAUDE.md and equivalents, plus a
PreToolUse hook with the same instruction. On real corpora that report
is 47-91K characters, so Claude Code sessions pay roughly 12-25K tokens
of context up front for every search-able question. Three users on #580
reported this making token usage worse than no install at all.

Reproduced on a 1500-file Go monorepo: a "where is X defined" question
takes 5 tool calls and 34k agent tokens with stock graphify, 4 calls
and 30k tokens with no install, and 1 call and 30k tokens after this
patch. Stock graphify's Read of GRAPH_REPORT.md hit Claude Code's 25k
token cap and failed entirely, then recovered via a partial read plus
graphify explain.

Demote GRAPH_REPORT.md to a fallback for broad architecture review and
route first action to the existing scoped commands: graphify query,
path, explain. The 2k-budget BFS subgraph already exists in serve.py;
the install just wasn't pointing at it.

Updated across all ten install surfaces: _SETTINGS_HOOK,
_CLAUDE_MD_SECTION, _AGENTS_MD_SECTION, _GEMINI_MD_SECTION,
_GEMINI_HOOK, _VSCODE_INSTRUCTIONS_SECTION, _ANTIGRAVITY_RULES,
_KIRO_STEERING, _CURSOR_RULE, _OPENCODE_PLUGIN_JS. Plus the matching
sentence in README.md, which also fixes an inaccuracy about Codex
hooks (Codex's installed hook is intentionally a no-op because Codex
rejects additionalContext, so the guidance there comes from AGENTS.md,
not the hook).

Five installers (claude, agents, vscode, gemini, kiro, cursor) were
also writing their section only when no marker was present, so users
who installed pre-fix kept the old "ALWAYS read" text after upgrading.
Added _replace_or_append_section helper that updates in place when the
graphify marker is found. claude_install also no longer returns before
re-running _install_claude_hook, so stale settings.json hook payloads
get refreshed on upgrade.

Tests:
- tests/test_install_strings.py (3): every install constant still
  mentions `graphify query` and matches no banned report-first regex.
- tests/test_install_upgrade.py (7): seeds each platform's instruction
  file with pre-fix text, runs install, asserts the on-disk file
  reflects the new policy.
- test_claude_md.py idempotency tests still pass.

Fixes #580.
2026-05-15 20:17:52 -07:00
Brian Kanya 246f4001d2 build: add dev deps for Nuitka onefile binary builds
Run with:
  uv run python -m nuitka --project --mode=onefile \
    --output-dir=build --output-filename=graphify \
    --assume-yes-for-downloads

Produces build/graphify, a self-contained ~60 MB binary that bundles
the package's skill *.md files (picked up automatically from
[tool.setuptools.package-data] via Nuitka's --project flow). The
existing wheel-build path (uv build via setuptools.build_meta) is
unchanged.

[tool.nuitka] config in pyproject.toml is not used: in --project mode
Nuitka builds the option list from setuptools distribution metadata
(_dumpBuildConfiguration in nuitka/distutils/DistutilsCommands.py)
and never reads [tool.nuitka], so output-dir / output-filename / etc.
must be passed on the CLI.

patchelf is required at build time on Linux and macOS for Nuitka's
standalone/onefile linking; gated by sys_platform != 'win32' so
Windows dev installs skip it.
2026-05-15 21:58:16 -04:00
Alpha Nury 5e178b9cd4 feat(detect): auto-detect symlinked children when follow_symlinks is unset
When `root` has at least one direct symlinked child, default to following
symlinks instead of silently dropping their contents. This makes "fake
working dir" patterns (a folder full of symlinks pointing at scattered
source dirs) work transparently — the caller no longer has to know to
pass `follow_symlinks=True`.

Concrete motivating shape:

    ~/projects/research-corpus/
    ├── papers   -> /external/drive/papers
    ├── notes    -> /external/drive/notes
    └── code     -> /external/drive/code

Before: `--update` invoked `detect_incremental(root)` without passing
`follow_symlinks=True`, so the scan saw the small set of files actually
inside the root and missed everything reachable only through a symlink.
Result: every legitimate new file was missed, and the manifest paths
were marked as deleted.

After: when `follow_symlinks` is left at its default `None`, `detect()`
runs `_auto_follow_symlinks(root)` (one cheap `iterdir()` + `is_symlink()`
loop) and follows symlinks if any direct child is one. Behaviour is
unchanged for ordinary scans (no direct symlinks → False, as before).

Override is always possible by passing an explicit `follow_symlinks=True`
or `follow_symlinks=False`; existing tests confirming the explicit
behaviour continue to pass unchanged.

Backwards compatibility:
- Type annotation: `bool` -> `bool | None`. Callers passing `True`/`False`
  continue to work identically. Callers passing nothing get the new
  auto-detect.
- No new dependencies.
- Cheap: one `iterdir()` call once per detect() invocation.

Tests:
- 3 new tests in tests/test_detect.py:
  - test_detect_auto_detects_direct_symlink_child
  - test_detect_default_does_not_follow_when_no_symlinks
  - test_detect_explicit_false_overrides_auto_detect
- Full tests/test_detect.py + tests/test_incremental.py: 49/49 pass.
2026-05-16 02:23:02 +02:00
Brian Kanya 0b54974719 chore: commit uv.lock for reproducible installs
Removes uv.lock from .gitignore and tracks the lockfile so contributors
and CI get the same resolved dependency tree. graphify is shipped as a
CLI (uv tool install graphifyy / uvx graphifyy), so the application
convention of committing the lockfile fits better than the library
convention of ignoring it.
2026-05-15 19:36:40 -04:00
Safi d14e8a72d1 Suppress cross-language INFERRED calls/uses edges in surprising connections
In Python+TypeScript monorepos, the call and import resolvers match by
label across language boundaries (AuthError -> Member), producing false
positives that dominate 'Surprising Connections' due to cross-dir (+2)
and cross-community (+1) bonuses.

Expand the existing calls guard to also cover uses edges, and zero the
cross-dir and cross-community bonuses for these pairs — not just conf_bonus.
Leaves semantically_similar_to, EXTRACTED, and AMBIGUOUS edges unaffected.

5 new tests: calls suppressed, uses suppressed, semantically_similar_to
preserved, same-language INFERRED preserved, cross-language EXTRACTED preserved.
2026-05-16 00:07:18 +01:00
Safi fa70449d80 Suppress autogenerated module docstrings from rationale extraction (#882)
Alembic/Flask-Migrate revisions, Django migrations, and protobuf/OpenAPI
generated files produce hundreds of degree-1 rationale nodes labeled as
'possible documentation gaps'. Their module docstrings are revision
annotations or boilerplate, not architectural rationale.

- Add _is_autogenerated_python() in extract.py detecting Alembic, Django
  migrations, and generic DO-NOT-EDIT markers; skip module docstring only
- Function/class docstrings inside those files still extracted as normal
- report.py: exclude file_type=rationale nodes from isolated-node gaps
  section — rationale nodes are degree-1 by construction; flagging them
  as missing edges was always wrong
- 5 new tests covering Alembic, Django, protobuf, false-positive guard,
  and function-docstring passthrough
2026-05-16 00:01:57 +01:00
Safi 63926c5e39 Add rsl-siege-manager case study to 0.8.5 CHANGELOG 2026-05-15 23:42:12 +01:00
Safi 9ca27aad31 Update CHANGELOG for 0.8.2 through 0.8.5 2026-05-15 23:40:14 +01:00
Safi aaf66f1cee Bump version to 0.8.5 2026-05-15 23:35:36 +01:00
Safi Shamsi 8076687d52 worked(case-study): add rsl-siege-manager (Python + TypeScript monorepo)
Cherry-picked from PR #881 (merged into v7) — adds case study artifacts
matching the worked/karpathy-repos/ convention.
2026-05-15 23:28:37 +01:00
SafiandClaude Sonnet 4.6 6f8e6c59f5 fix gitignore parent-exclusion rule (#882) and dedup false merges on short labels (#878)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 22:57:36 +01:00
SafiandClaude Sonnet 4.6 299b6baa26 v0.8.4: SQL FK/trigger extraction, deletion pruning fixes, community label normalization
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 15:31:22 +01:00
SafiandClaude Sonnet 4.6 1b3296a093 Fix Windows skill temp files polluting project root
Move all intermediate data files and temp step scripts from the
project root into graphify-out/ to match the bash skill behaviour.
Also fix the > redirect on detect.json which wrote UTF-16LE in
PowerShell 5.1 - now uses Out-File -Encoding utf8 consistently.

Files moved: .graphify_detect.json, .graphify_ast.json,
.graphify_extract.json, .graphify_semantic.json,
.graphify_analysis.json, .graphify_labels.json,
.graphify_incremental.json, .graphify_old.json,
all .graphify_step_*.py temp scripts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 15:07:59 +01:00
Safi 5f2c55bc95 Bump version to 0.8.3 2026-05-15 14:12:59 +01:00
SafiandClaude Sonnet 4.6 ac9587bfda Fix antigravity Windows skill and Python detection for uv/pipx (#831)
antigravity install on Windows now installs skill-windows.md instead
of skill.md by redirecting to a new antigravity-windows platform config
at install time via sys.platform check.

Python detection in Find-GraphifyPython now uses uv tool dir (respects
UV_TOOL_DIR) and pipx environment --value PIPX_LOCAL_VENVS (respects
PIPX_HOME) instead of guessing from the shim location. The graphify.exe
shim and python.exe live in different directories for both uv and pipx
on Windows so the previous Get-Command approach was wrong.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 14:09:31 +01:00
Safi da4ec1d5e7 Bump version to 0.8.2 2026-05-15 11:29:31 +01:00
SafiandClaude Sonnet 4.6 1ac3b96897 Fix Windows skill Python detection for uv tool installs (#831)
graphify.exe and python.exe are co-located in the same Scripts\
directory for both uv tool and pipx installs. Use Get-Command graphify
to find that directory and pick up the correct Python instead of
falling through to bare python (which is a different interpreter
that doesn't have graphify).

Also replace all bare `python .graphify_*` invocations throughout
the skill with `& (Get-Content graphify-out\.graphify_python)` so
every step uses the saved interpreter, and fix the bash $(cat ...)
syntax to PowerShell & (Get-Content ...).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 11:25:59 +01:00
SafiandClaude Sonnet 4.6 df40e4d818 fix #873 index dot dirs, fix #874 MCP hot-reload on graph change
#873: Remove blanket dot-prefix exclusion from detect.py and
extract.py collect_files(). Add framework caches (.next, .nuxt,
.turbo, .angular, .idea, .cache, .parcel-cache, .svelte-kit,
.terraform, .serverless, .graphify) to _SKIP_DIRS so they stay
blocked. Meaningful dot dirs (.github, .claude, etc.) are now
indexed.

#874: Add _maybe_reload() with mtime+size stat key and threading.Lock
to serve.py. call_tool and read_resource call _maybe_reload() on
every request; the graph reloads automatically when graph.json changes
without restarting the MCP server.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 08:51:46 +01:00
SafiandClaude Sonnet 4.6 d172650065 Note callflow-html auto-regeneration in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:38:48 +01:00
SafiandClaude Sonnet 4.6 5f5b70ff91 Add 0.8.1 to CHANGELOG
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:34:32 +01:00
SafiandClaude Sonnet 4.6 daafec20ba Update README for v0.8.1: CI badge, file types, branch references
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:25:30 +01:00
SafiandClaude Sonnet 4.6 914a32d000 Bump version to 0.8.1
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:23:26 +01:00
SafiandClaude Sonnet 4.6 4d6818190d Fix detect.py missing .sh/.json extensions and security harden extractors
- Add .sh, .bash, .json to CODE_EXTENSIONS in detect.py so files reach extractor
- Fix test_detect_incremental manifest path collision with new .json extension
- Update test_watch to reflect .json/.sh are now watched extensions
- B-1: only emit source imports for paths that exist on disk
- J-1: replace stat()+read() with bounded read to eliminate TOCTOU
- J-3: move pair_count cap inside loop so it is honoured exactly
- J-4: namespace $ref/extends refs with "ref_" prefix to prevent ID collision

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:18:33 +01:00
SafiandClaude Sonnet 4.6 03dd794a80 Add v8 to CI branch list
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:09:16 +01:00
SafiandClaude Sonnet 4.6 40b9b84caa Add tree-sitter bash and JSON extractors (#866)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 00:07:09 +01:00
44 changed files with 66519 additions and 344 deletions

No files matched your search

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