Compare commits

...
19 Commits
v6 ... v5
Author SHA1 Message Date
Safi 762b85d7ca Merge pull request #622 from chronicgiardia/docs/colabfold-macos-install
docs: add LocalColabFold macOS Apple Silicon install runbook
2026-05-02 16:40:29 +01:00
Safi 267c392a96 Merge pull request #615 from mtt-ai/ci/v5-trigger-and-matrix
Ci/v5 trigger and matrix
2026-05-02 16:40:01 +01:00
Safi 832dc537b3 Merge pull request #599 from llongo-allora/fix/member-call-resolver-collisions
Fix: prevent cross-file member-call name collisions in extract resolver
2026-05-02 16:39:26 +01:00
Safi 6c82f81d13 Merge pull request #614 from robertmonka/codex/use-user-prompt-submit-hook
Use UserPromptSubmit for Codex graph reminders
2026-05-02 16:37:47 +01:00
6c9b5ef63c Wire --no-viz flag in cluster-only + GRAPHIFY_VIZ_NODE_LIMIT env var (closes #541) (#565)
* feat(export): GRAPHIFY_VIZ_NODE_LIMIT env var to override MAX_NODES_FOR_VIZ

Adds opt-in env var so users with large graphs (>5000 nodes) can either
raise the HTML viz limit or disable viz entirely (set to 0) without
patching the package.

- New _viz_node_limit() helper reads GRAPHIFY_VIZ_NODE_LIMIT, falls back
  to MAX_NODES_FOR_VIZ on unset/empty/non-integer values.
- to_html() now uses the helper; ValueError message references both
  --no-viz and GRAPHIFY_VIZ_NODE_LIMIT for discoverability.
- 7 new tests in test_export.py covering default, raise/lower, zero,
  invalid, empty, and end-to-end to_html behavior.

Addresses option 2 in #541 (env var as default behavior, zero-config
for most users, tunable for large repos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF
)

* feat(cluster-only): wire --no-viz flag and tolerate ValueError mid-write

Before this change, `graphify cluster-only <path>` called to_html()
unconditionally, so on graphs >5000 nodes the ValueError fired AFTER
graph.json was written but BEFORE the "Done — ..." print, leaving a
stale graph.html on disk and no clear signal in the CLI output.

This mirrors the watch.py rebuild pattern (already merged): try/except
around to_html, delete the stale graph.html when skipping, and emit a
"Done" line that accurately reflects which artifacts landed.

- Parse "--no-viz" from sys.argv (documented as such in skill.md but
  previously never wired into the Python CLI).
- Wrap to_html() in try/except so core outputs (graph.json +
  GRAPH_REPORT.md) always land.
- Remove stale graph.html when viz is skipped or fails — avoids the
  silent desync where graph.html lags behind graph.json by days.
- Update help text under `cluster-only` to advertise --no-viz.

Addresses option 1 in #541 (--no-viz flag, simplest opt-in).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Tayfun Sert,MBA <tayfunsert@hotmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 14:15:15 +01:00
Bichallaandhonbul 3145ca2e52 feat(detect): add hidden path allowlist (#583)
Summary:\n- Add .graphifyinclude loading for detect().\n- Allow curated hidden paths only when explicitly allowlisted.\n- Keep sensitive-looking filenames hard-skipped even when allowlisted.\n- Add tests for hidden .hermes document inclusion and sensitive allowlist hard-skip.\n\nVerification:\n- uv run --with pytest python -m pytest tests/test_detect.py -q\n- uv run --with pytest python -m pytest -q\n\nNotes:\n- .opencode/ remains untracked and intentionally unstaged.\n- origin is upstream safishamsi/graphify; push requires a user-owned fork/branch.

Co-authored-by: honbul <honbul@honbului-Macmini.local>
2026-05-02 14:15:12 +01:00
cod3warrior fd0ebb5957 wiki: sanitize Windows-reserved characters in filenames (#594)
On Windows, to_wiki crashes with OSError [Errno 22] when a node label
contains any of < > : " / \ | ? * (Windows reserved chars in
filenames). Repro: an Obsidian note titled "Czy Wii jeszcze ok?.md"
becomes a community label, then write_text fails because Windows
rejects the question mark in the path.

The previous _safe_filename only handled three characters (/ space :)
which is enough on Linux/macOS but not on Windows. Extended the
substitution to cover all Windows-reserved chars plus trailing dots
and spaces (also reserved on Windows), and added a 200-char length
cap to stay well under MAX_PATH-segment limits.

Falls back to 'unnamed' if sanitization produces an empty string,
so we never try to create a file named "" or ".".

Tested on a 1773-file vault with mixed Polish/English content where
~12 community labels and several god node labels contained reserved
characters. Generates 763 wiki articles cleanly.
2026-05-02 14:15:09 +01:00
opnsrcntrbtr b9871d7019 Fix #563: prevent rationale-node leakage and preserve calls direction (#576)
* Fix #563: prevent rationale-node leakage and preserve calls direction

Two AST-extractor bugs were inflating god-node centrality:

1. Rationale leakage in cross-file resolvers
   _resolve_cross_file_imports indexed any node whose label didn't end in
   ')' or '.py' as an importable entity, so rationale nodes (whose labels
   are docstring text) ended up in both stem_to_entities and local_classes.
   Result: phantom '<file>_rationale_N --uses--> ImportedThing' edges for
   every imported entity in every file with docstrings.

   The same leak existed in cross-file call resolution via
   global_label_to_nid, where rationale labels could collide with callee
   names.

   Fix: skip nodes with file_type == 'rationale' in all three index loops.

2. Calls / rationale_for direction lost at export
   to_json() called nx.json_graph.node_link_data() on a NetworkX undirected
   Graph, which canonicalizes endpoint order. The build path already
   stashes _src and _tgt on every edge for exactly this case (with a
   comment to that effect at build.py:100), but the exporter never
   consulted them, so 'calls' and 'rationale_for' edges were emitted with
   arbitrary direction.

   Fix: in to_json(), restore link['source'] / link['target'] from
   _src / _tgt, then pop those internal fields before writing graph.json.

Repro on a minimal 3-file project (queue.py + contact_form.py + a test
file with multi-paragraph docstrings) showed:

  Before fix: 31 edges, 12 incident on SQLiteQueue, 7 phantom uses-edges
              from rationale nodes, 1 inverted calls edge.
  After fix:  24 edges, 5 incident on SQLiteQueue, 0 phantom edges,
              all calls edges go caller -> callee.

Adds tests/test_issue_563.py with 5 regression tests covering both bugs
plus a direction-pin on the existing sample_calls.py fixture. Full suite
passes (446/446).

* Address Copilot review on #576

- tests: identify rationale nodes by file_type metadata, not id substring
  (decouples regression from current `<stem>_rationale_<line>` naming)
- tests: assert contact_form -> SQLiteQueue.enqueue calls edge directly
  (previously only inversions were guarded; a dropped enqueue edge would
  have passed silently)
- extract.py: clarify cross-file import indexing comment — the filter
  intentionally indexes only class-level entities (function/method labels
  end in "()" and are excluded by design)

* Fix #563 (HTML export): restore arrow direction in graph.html

to_json was patched to consult _src/_tgt before serializing edge
endpoints, but to_html still read endpoints directly from G.edges(),
so calls and rationale_for arrows in the rendered graph.html still
pointed in canonicalized (often inverted) order.

Apply the same direction restore in to_html when building vis.js
edges. Use data.get (not pop) since G.edges(data=True) yields the
live attribute dict and other exporters may run after to_html.

Adds test_to_html_preserves_calls_and_rationale_for_direction:
parses RAW_EDGES out of the rendered HTML and pins both the
caller->callee assertions from #563 and the rationale->parent
direction. Without the fix, the test reports 11 flipped arrows
on the 3-file repro.
2026-05-02 14:15:06 +01:00
teamclaw ac72cd3aaa fix(wiki): clear stale articles before regenerating to prevent orphan accumulation (#558)
to_wiki() writes a fresh set of community + god-node articles each call but
never deletes old files from previous runs. Since community labels are
LLM-generated and non-deterministic across rebuilds (per skill.md Step 5),
the same conceptual community is often named differently each time, leaving
its previous file as an orphan. After N rebuilds, wiki/ contains roughly N
times the active article count, with index.md only referencing the most
recent run's labels.

Real-world: a knowledge corpus accumulated 822 wiki .md files over 5
rebuilds, of which only 111 were referenced by index.md (710 orphans).

Fix: clear *.md files in the output directory at the start of to_wiki().
This is consistent with its existing fully-regenerative behavior — it
always writes the full set of articles + index, never partial updates.
Subdirectories and non-.md files are preserved (only top-level .md is
touched), so any user-placed auxiliary assets survive.

Tests: two new regression tests cover (1) stale article cleanup across
runs with different labels, and (2) preservation of non-.md user files
and nested subdirectories.
2026-05-02 14:15:03 +01:00
saxster 48c9f024fb docs(skill): forced-rank confidence scores for INFERRED edges (#546)
Closes #540.

Production audit on a 10,129-edge graph showed the INFERRED
confidence_score distribution is bimodal, not graded:

  | Score bucket | Count | % of INFERRED |
  |--------------|-------|---------------|
  | <0.4         |     0 | 0%            |
  | 0.4-0.6      | 5,807 | 57%           |
  | 0.6-0.8      |    14 | 0.1%          |
  | 0.8+         | 4,308 | 42%           |

Subagents collapse the continuous "0.4-0.9" guidance to a binary:
0.5 for "uncertain", 0.85+ for "confident", almost nothing in between.
Downstream filtering by confidence is therefore an on/off switch, not
the gradient the prompt promises.

Replace continuous ranges with a forced-rank discrete set:

  0.95  direct structural evidence
  0.85  strong inference
  0.75  reasonable inference
  0.65  weak inference
  0.55  speculative but plausible

Models follow discrete rubrics far better than continuous ranges
(documented in calibration literature; same reason MCQ rubrics
outperform 0-100 scales). The set is anchored at non-round midpoints
to discourage 0.5 as a default.

Applied uniformly across all 10 skill-*.md files:
- 7 long-form (skill.md, skill-codex.md, skill-copilot.md,
  skill-droid.md, skill-opencode.md, skill-windows.md, skill-trae.md):
  full forced-rank table.
- 3 short-form (skill-claw.md, skill-aider.md, skill-kiro.md):
  inline set notation INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95}.

Pure prompt edit — no code changes, no test impact. Effect is
observable only via re-extraction and inspection of the new
confidence_score distribution.
2026-05-02 14:14:55 +01:00
saxster e1636a0e88 docs(skill): save_manifest at end of --update merge step (#545)
Closes #538.

The full-pipeline path's Step 9 already calls save_manifest, so the
NEXT --update can diff against the full-rebuild's baseline.

But the --update flow itself does NOT save the manifest after merging
the incremental result. Consequence: a file deleted between
--update #1 and --update #2 keeps reappearing in #2's deleted_files
list (since the manifest still records its old mtime), generating a
spurious ghost-node prune attempt every run.

Add save_manifest(incremental['files']) at the end of the --update
merge step in both skill.md and skill-copilot.md (the only two skill
files carrying the merge step verbatim). The 'incremental' dict is
already in scope from the prune block above; its 'files' key is the
full current file list, which is exactly what save_manifest needs.

Pure prompt edit — no code changes, no test impact.
2026-05-02 14:14:52 +01:00
saxster 8b41440ad1 docs(skill): clarify --update prune message — split drift vs no-drift (#544)
Closes #539.

The current prune message in the --update flow is ambiguous:

    Pruned 0 ghost nodes from 13 deleted file(s)

A reader can't tell whether (a) 13 files deleted, 0 of them had nodes
worth pruning (benign — graph already clean), or (b) 13 ghost nodes
still exist and only 0 got pruned (bug). The denominator is opaque.

Split into two messages so the semantics are explicit:

- Drift case: "Pruned N ghost node(s) from M deleted file(s) — drift
  detected and corrected."
- No-drift case: "M file(s) deleted since last run, but no ghost
  nodes were present in the graph — no drift."

Applied to both skill.md and skill-copilot.md (the only two skill
files carrying the --update merge step verbatim).
2026-05-02 14:14:49 +01:00
Koushik-Salammagari e1947826fc fix(hooks): expand ~ in core.hooksPath before resolving install target (#554)
When a user configures core.hooksPath = ~/gitconfig/hooks in .gitconfig,
_hooks_dir() was constructing Path("~/gitconfig/hooks") without calling
expanduser(), so hooks were installed into <repo>/~/gitconfig/hooks instead
of the intended absolute path.

Add Path.expanduser() call immediately after reading the raw string from
git config, before the is_absolute() / root-relative fallback logic.

Fixes #547
2026-05-02 14:14:46 +01:00
Arun96980 441e3b6574 fix: add 'concept' to VALID_FILE_TYPES (#604) 2026-05-02 14:14:42 +01:00
Robert Mońka 18d697aac9 Preserve Codex user hooks 2026-04-30 21:25:20 +02:00
chronicgiardiaandOz e97379e551 docs: add LocalColabFold macOS Apple Silicon install runbook
Adds docs/colabfold-macos-install.md, a reproducible recipe for
installing LocalColabFold (ColabFold + AlphaFold2 weights) on Apple
Silicon Macs, so users can predict protein structures locally and feed
the resulting PDBs / confidence scores into a graphify corpus.

Notes upstream LocalColabFold's current top-level installer hardcodes
Linux x86_64 Miniforge and jax[cuda12], which fail on Apple Silicon (no
macOS CUDA wheels, no NVIDIA GPU). Recommends the bundled v1.5.5 M1
installer as the working Apple Silicon path. ColabFold 1.6.1 with
JAX 0.4.23 CPU build, verified by 60s smoke test on a 62-residue FASTA.

Linked from README.md under the existing 'Optional integrations' section
(also added by this PR if not already present from #620).

Co-Authored-By: Oz <oz-agent@warp.dev>
2026-04-30 03:23:00 -07:00
mtt-ai 7683df1cd5 Update ci.yml 2026-04-29 21:04:16 -04:00
mtt-ai ffc5427351 build: add [test] extras for pytest+pytest-cov
Defines a `test` optional-dependencies group so CI can install dev tooling
via `pip install -e ".[all,test]"` instead of an ad-hoc `pip install pytest`
sidecar. Kept out of `[all]` deliberately — `[all]` is runtime extras only.
2026-04-29 20:43:21 -04:00
Luke Longo 5f4f557034 Prevent phantom god nodes from cross-file member-call name collisions
graphify per-language AST extractors strip member-expression callees
(`x.foo()`, `obj.bar()`, `Pkg::baz()`) down to the trailing identifier,
queue them in `raw_calls`, and the cross-file resolver matches by bare
lowercase name against a global symbol table. When any file in the
corpus exposes a top-level helper with a common method name (e.g. a
`function log(...)` in a one-off smoke-test script), every unrelated
`Logger.log(...)` / `this.x.find(...)` / `Pkg::baz(...)` call across the
codebase resolves to that single helper, producing phantom god nodes
with hundreds of bogus INFERRED edges.

This patch:

  * Adds `_MEMBER_CALL_NODE_TYPES` enumerating member-expression AST
    node types across all supported languages.
  * Tags every `raw_calls.append(...)` site with `callee_node_type`.
  * Skips entries whose `callee_node_type` is in
    `_MEMBER_CALL_NODE_TYPES` from the cross-file resolver in
    `extract()`. In-file resolution behaviour is intentionally
    preserved.

On a real production codebase (~1,668 TS/JS files, NestJS + Nuxt) this
eliminates 1,262 phantom edges and removes a phantom `log()` god node
that previously sat at #2 with 265 inbound edges (255 of them bogus).

Includes 3 regression tests that fail on the original code and pass with
this patch.
2026-04-28 15:45:45 -04:00
26 changed files with 1363 additions and 98 deletions

No files matched your search

+15 -5
View File
@@ -2,16 +2,25 @@ name: CI
on:
push:
branches: ["v1", "v2", "v3", "v4", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
pull_request:
branches: ["v1", "v2", "v3", "v4", "main"]
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.12"]
python-version: ["3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v4
@@ -20,11 +29,12 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
cache-dependency-path: 'pyproject.toml'
- name: Install dependencies
run: |
pip install -e ".[mcp,pdf,watch]"
pip install pytest
pip install -e ".[all,test]"
- name: Run tests
run: |
+11 -3
View File
@@ -97,7 +97,7 @@ pip install graphifyy && graphify install
| Cursor | `graphify cursor install` |
| Google Antigravity | `graphify antigravity install` |
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports UserPromptSubmit hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
Then open your AI coding assistant and type:
@@ -131,7 +131,7 @@ After building a graph, run this once in your project:
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
**Codex** writes to `AGENTS.md` and also installs a **UserPromptSubmit hook** in `.codex/hooks.json` that fires when the user submits a prompt. This reminds Codex about `GRAPH_REPORT.md` before it decides whether to search files.
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
@@ -299,7 +299,7 @@ graphify hook status
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
graphify codex install # AGENTS.md + UserPromptSubmit hook in .codex/hooks.json (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify cursor uninstall
@@ -426,6 +426,14 @@ Token reduction scales with corpus size. 6 files fits in a context window anyway
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
## Optional integrations
Runbooks for setting up extra tooling alongside graphify. None of these are required.
| Integration | Doc |
|---|---|
| LocalColabFold (ColabFold + AlphaFold2) on macOS Apple Silicon | [`docs/colabfold-macos-install.md`](docs/colabfold-macos-install.md) |
## Tech stack
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
+170
View File
@@ -0,0 +1,170 @@
# Installing LocalColabFold on macOS Apple Silicon
A reproducible runbook for installing
[LocalColabFold](https://github.com/YoshitakaMo/localcolabfold)
(ColabFold + AlphaFold2 weights) on Apple Silicon (arm64) Macs, so you can
predict protein structures locally and feed the resulting PDBs / confidence
scores into a graphify corpus.
This document is **optional** and unrelated to graphify's pipeline. It is
included as a known-good recipe for users who want a CPU-capable local
ColabFold install alongside graphify on the same machine.
## Why a separate runbook
LocalColabFold's current top-level installer (`install_colabbatch_linux.sh`)
hardcodes `Miniforge3-Linux-x86_64.sh` and later runs
`pip install jax[cuda12]==0.5.3`. Both fail on Apple Silicon: there are no
macOS CUDA wheels, and Apple GPUs are unreachable from JAX's CUDA backend.
Upstream stopped shipping a current macOS installer after v1.5.5. The
**v1.5.5 M1 installer** (bundled in the LocalColabFold repo at
`v1.5.5_old_installers/install_colabbatch_M1mac.sh`) is the working Apple
Silicon path — ColabFold 1.6.1, JAX 0.4.23 CPU build.
## Verified configuration
- Hardware: Apple Silicon (arm64)
- OS: macOS (Darwin)
- ColabFold installed: 1.6.1 (commit `de5ab5f`)
- JAX: 0.4.23 (CPU build)
- 62-residue smoke test (1 model, 1 recycle, single-sequence MSA): ~60 s wall
## Prerequisites (Homebrew)
The M1 installer fail-fasts on these. Install once before running:
```bash
brew tap brewsci/bio # custom tap for hh-suite
brew install brewsci/bio/hh-suite \
kalign \
mmseqs2
# verify
for c in wget hhsearch kalign mmseqs; do
printf "%-10s " "$c" && command -v "$c" || echo MISSING
done
```
Roughly ~600 MB of brew downloads (gcc, open-mpi, hh-suite are the heavy
items); 5–10 minutes on a modern internet link.
## Install
Clone LocalColabFold (or use an existing clone), then from the repo root:
```bash
git clone https://github.com/YoshitakaMo/localcolabfold.git
cd localcolabfold
bash v1.5.5_old_installers/install_colabbatch_M1mac.sh
```
What the installer does, in order:
1. Downloads `Miniforge3-MacOSX-arm64.sh` and installs into
`localcolabfold/conda/`
2. `conda update -n base conda -y`
3. Creates env at `localcolabfold/colabfold-conda` with
`python=3.10 openmm==8.0.0 pdbfixer==1.9` from conda-forge
4. `pip install "colabfold[alphafold] @ git+https://github.com/sokrypton/ColabFold"`
5. `pip install jax==0.4.23 jaxlib==0.4.23` (CPU build)
6. `pip install silence_tensorflow`
7. Downloads `update_M1mac.sh`
8. `python -m colabfold.download` — pulls AlphaFold2 weights into
`~/Library/Caches/colabfold` (~5.3 GB total: 3.82 GB multimer_v3 +
3.47 GB AlphaFold2-ptm)
Total install time: ~10–30 min depending on network and AlphaFold weight
download speed.
## Add to PATH
The installer's last step prints the line for your shell. Adapt the prefix
to wherever you cloned LocalColabFold:
```bash
export PATH="$(pwd)/localcolabfold/colabfold-conda/bin:$PATH"
```
Add the line to `~/.zshrc` to persist across shell sessions.
## Smoke test
A minimal CPU-only inference exercising the JAX path (no MMseqs2 server,
no templates, single model, single recycle). Use any short FASTA — the
LocalColabFold repo ships `1BJP_1.fasta` (62 residues).
```bash
colabfold_batch \
--num-models 1 --num-recycle 1 \
--msa-mode single_sequence \
--random-seed 0 \
1BJP_1.fasta out_smoketest/
```
Expected output in `out_smoketest/`:
- `*.pdb` — predicted structure
- `*_scores_*.json` — per-residue confidence
- `*_pae.png`, `*_plddt.png`, `*_coverage.png` — diagnostic plots
- `1BJP_1.done.txt` — sentinel marker
Sample log lines on success:
```
Running colabfold 1.6.1 (de5ab5f795ed95c70a7a9b6a9dc6bb5625016142)
WARNING: no GPU detected, will be using CPU
Query 1/1: 1BJP_1 (length 62)
alphafold2_ptm_model_1_seed_000 recycle=0 pLDDT=56.7 pTM=0.363
alphafold2_ptm_model_1_seed_000 took 18.1s (1 recycles)
```
The low pLDDT (~57) is **expected** — single-sequence MSA, 1 model, and
1 recycle is the cheapest config that still exercises the JAX inference
path. It is **not** representative of structure quality. Use the
production config below for real predictions.
## Production run (CPU-friendly defaults)
LocalColabFold's bundled `run_colabfoldbatch_sample.sh` uses
`--use-gpu-relax`, `--templates`, and `--amber` — all of which require
either GPU or extra setup that doesn't apply on macOS. Use this
CPU-friendly variant instead:
```bash
colabfold_batch \
--num-recycle 3 \
--num-models 5 \
--model-order 1,2,3,4,5 \
--random-seed 0 \
YOUR_INPUT.fasta out_dir/
# Dropped from the sample script:
# --use-gpu-relax (no GPU)
# --amber (slow on CPU; pdbfixer-only is fine for many use cases)
# --templates (requires hhsearch + a PDB templates DB)
```
MSA defaults to MMseqs2 server-side queries — needs network, ~30–90 s
roundtrip per sequence.
Expect 5–15 min per ~100-residue monomer on this hardware. Multimers and
longer chains scale much worse on CPU.
## Honest caveats
- **CPU-only.** No CUDA wheels for macOS exist; JAX has experimental
Metal support but LocalColabFold's pinned `jax==0.4.23` is the CPU
build. Inference can be 30–100× slower than a recent NVIDIA GPU.
- **ColabFold version is 1.6.1**, pinned by the v1.5.5 installer track.
Newer features in ColabFold `main` aren't available here. For latest
features either use Google Colab or a Linux + NVIDIA box.
- **Weights cache is ~5.3 GB** at `~/Library/Caches/colabfold`. Move with
`XDG_CACHE_HOME` if disk is tight.
- **Apple Silicon Metal** is not used by this JAX. There's no
straightforward way to enable it without changing the pinned versions
in the installer script.
## Update
```bash
bash localcolabfold/update_M1mac.sh
```
## Uninstall / reset
```bash
# Remove the conda env + Miniforge (keeps weights cache)
rm -rf localcolabfold/
# Optionally drop weights cache
rm -rf ~/Library/Caches/colabfold
# Optionally remove brew prereqs
brew uninstall brewsci/bio/hh-suite kalign mmseqs2
brew untap brewsci/bio
```
+102 -21
View File
@@ -712,15 +712,14 @@ def _uninstall_opencode_plugin(project_dir: Path) -> None:
_CODEX_HOOK = {
"hooks": {
"PreToolUse": [
"UserPromptSubmit": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": (
"[ -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":"UserPromptSubmit","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
"|| true"
),
}
@@ -731,40 +730,103 @@ _CODEX_HOOK = {
}
_LEGACY_CODEX_PRE_TOOL_HOOK = {
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": (
"[ -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."}}' """
"|| true"
),
}
],
}
def _is_graphify_codex_hook(hook: object) -> bool:
"""Return True for Codex hooks generated by graphify."""
return hook in (
_CODEX_HOOK["hooks"]["UserPromptSubmit"][0],
_LEGACY_CODEX_PRE_TOOL_HOOK,
)
def _remove_graphify_codex_hooks(existing: dict) -> None:
"""Remove graphify Codex hooks while preserving unrelated hooks."""
hooks = existing.get("hooks")
if not isinstance(hooks, dict):
return
for event in ("UserPromptSubmit", "PreToolUse"):
event_hooks = hooks.get(event)
if not isinstance(event_hooks, list):
continue
filtered = [h for h in event_hooks if not _is_graphify_codex_hook(h)]
if filtered:
hooks[event] = filtered
else:
hooks.pop(event, None)
if not hooks:
existing.pop("hooks", None)
def _install_codex_hook(project_dir: Path) -> None:
"""Add graphify PreToolUse hook to .codex/hooks.json."""
"""Add graphify UserPromptSubmit hook to .codex/hooks.json."""
hooks_path = project_dir / ".codex" / "hooks.json"
hooks_path.parent.mkdir(parents=True, exist_ok=True)
if hooks_path.exists():
try:
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
existing = {}
print(" .codex/hooks.json -> invalid JSON; left unchanged")
return
if not isinstance(loaded, dict):
print(" .codex/hooks.json -> top-level value is not an object; left unchanged")
return
existing = loaded
else:
existing = {}
pre_tool = existing.setdefault("hooks", {}).setdefault("PreToolUse", [])
existing["hooks"]["PreToolUse"] = [h for h in pre_tool if "graphify" not in str(h)]
existing["hooks"]["PreToolUse"].extend(_CODEX_HOOK["hooks"]["PreToolUse"])
_remove_graphify_codex_hooks(existing)
hooks = existing.get("hooks")
if hooks is None:
hooks = existing["hooks"] = {}
elif not isinstance(hooks, dict):
print(" .codex/hooks.json -> existing hooks value is not an object; left unchanged")
return
user_prompt = hooks.get("UserPromptSubmit")
if user_prompt is None:
user_prompt = hooks["UserPromptSubmit"] = []
elif not isinstance(user_prompt, list):
print(" .codex/hooks.json -> UserPromptSubmit hooks are not a list; left unchanged")
return
user_prompt.extend(_CODEX_HOOK["hooks"]["UserPromptSubmit"])
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
print(f" .codex/hooks.json -> PreToolUse hook registered")
print(f" .codex/hooks.json -> UserPromptSubmit hook registered")
def _uninstall_codex_hook(project_dir: Path) -> None:
"""Remove graphify PreToolUse hook from .codex/hooks.json."""
"""Remove graphify Codex hooks from .codex/hooks.json."""
hooks_path = project_dir / ".codex" / "hooks.json"
if not hooks_path.exists():
return
try:
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return
pre_tool = existing.get("hooks", {}).get("PreToolUse", [])
filtered = [h for h in pre_tool if "graphify" not in str(h)]
existing["hooks"]["PreToolUse"] = filtered
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
print(f" .codex/hooks.json -> PreToolUse hook removed")
if not isinstance(loaded, dict):
return
before = json.dumps(loaded, sort_keys=True)
_remove_graphify_codex_hooks(loaded)
if json.dumps(loaded, sort_keys=True) != before:
hooks_path.write_text(json.dumps(loaded, indent=2), encoding="utf-8")
print(f" .codex/hooks.json -> graphify hooks removed")
def _agents_install(project_dir: Path, platform: str) -> None:
@@ -1002,6 +1064,7 @@ def main() -> None:
print(" watch <path> watch a folder and rebuild the graph on code changes")
print(" update <path> re-extract code files and update the graph (no LLM needed)")
print(" cluster-only <path> rerun clustering on an existing graph.json and regenerate report")
print(" --no-viz skip graph.html generation (useful for >5000 node graphs / CI)")
print(" query \"<question>\" BFS traversal of graph.json for a question")
print(" --dfs use depth-first instead of breadth-first")
print(" --budget N cap output at N tokens (default 2000)")
@@ -1023,8 +1086,8 @@ def main() -> None:
print(" cursor uninstall remove .cursor/rules/graphify.mdc")
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
print(" codex install write graphify section to AGENTS.md (Codex)")
print(" codex uninstall remove graphify section from AGENTS.md")
print(" codex install write AGENTS.md section + UserPromptSubmit hook (Codex)")
print(" codex uninstall remove AGENTS.md section + graphify Codex hook")
print(" opencode install write graphify section to AGENTS.md + tool.execute.before plugin (OpenCode)")
print(" opencode uninstall remove graphify section from AGENTS.md + plugin")
print(" aider install write graphify section to AGENTS.md (Aider)")
@@ -1379,6 +1442,7 @@ def main() -> None:
elif cmd == "cluster-only":
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
no_viz = "--no-viz" in sys.argv
graph_json = watch_path / "graphify-out" / "graph.json"
if not graph_json.exists():
print(f"error: no graph found at {graph_json} — run /graphify first", file=sys.stderr)
@@ -1407,8 +1471,25 @@ def main() -> None:
out = watch_path / "graphify-out"
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
to_json(G, communities, str(out / "graph.json"))
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.")
# Mirror watch.py pattern: gate to_html so core outputs (graph.json +
# GRAPH_REPORT.md) always land. Honor --no-viz explicitly; otherwise
# fall back to ValueError handling so an oversized graph doesn't crash
# the CLI mid-write and leave a stale graph.html on disk.
html_target = out / "graph.html"
if no_viz:
if html_target.exists():
html_target.unlink()
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md and graph.json updated (--no-viz; graph.html removed).")
else:
try:
to_html(G, communities, str(html_target), community_labels=labels or None)
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.")
except ValueError as viz_err:
if html_target.exists():
html_target.unlink()
print(f"Skipped graph.html: {viz_err}")
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md and graph.json updated.")
elif cmd == "update":
if len(sys.argv) > 2:
+94 -23
View File
@@ -263,13 +263,13 @@ def _is_noise_dir(part: str) -> bool:
return False
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyignore from root **and ancestor directories**.
def _load_pattern_file(root: Path, filename: str) -> list[tuple[Path, str]]:
"""Read a Graphify pattern file from root **and ancestor directories**.
Returns a list of (anchor_dir, pattern) pairs. Each pattern is matched
against paths relative to both the scan root and the anchor_dir where
the .graphifyignore file was found — so patterns written relative to a
parent directory still work when graphify is run on a subfolder.
the pattern file was found — so patterns written relative to a parent
directory still work when graphify is run on a subfolder.
Walks upward from *root* towards the filesystem root, stopping at a
``.git`` boundary. Lines starting with # are comments; blank lines ignored.
@@ -277,9 +277,9 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
patterns: list[tuple[Path, str]] = []
current = root.resolve()
while True:
ignore_file = current / ".graphifyignore"
if ignore_file.exists():
for line in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
pattern_file = current / filename
if pattern_file.exists():
for line in pattern_file.read_text(encoding="utf-8", errors="ignore").splitlines():
line = line.strip()
if line and not line.startswith("#"):
patterns.append((current, line))
@@ -293,13 +293,29 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
return patterns
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if path matches any .graphifyignore pattern."""
if not patterns:
return False
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyignore patterns from root and ancestor directories."""
return _load_pattern_file(root, ".graphifyignore")
def _matches(rel: str, p: str) -> bool:
parts = rel.split("/")
def _load_graphifyinclude(root: Path) -> list[tuple[Path, str]]:
"""Read .graphifyinclude allowlist patterns from root and ancestors.
Include patterns are intentionally narrow: they only opt matching files and
the directories needed to reach them into hidden-path traversal. Sensitive
files and hard-skipped noise directories are still excluded later.
"""
return _load_pattern_file(root, ".graphifyinclude")
def _pattern_matches(path: Path, rel: str, pattern: str) -> bool:
"""Return True if *rel* or path.name matches a Graphify glob pattern."""
parts = rel.split("/")
candidates = [pattern]
if "/**/" in pattern:
# Treat foo/**/*.md as matching both foo/bar.md and foo/a/bar.md.
candidates.append(pattern.replace("/**/", "/"))
for p in candidates:
if fnmatch.fnmatch(rel, p):
return True
if fnmatch.fnmatch(path.name, p):
@@ -309,6 +325,12 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
return True
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
return True
return False
def _matches_patterns(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if path matches any pattern loaded for root/ancestors."""
if not patterns:
return False
for anchor, pattern in patterns:
@@ -318,22 +340,64 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
# Try path relative to the scan root
try:
rel = str(path.relative_to(root)).replace(os.sep, "/")
if _matches(rel, p):
if _pattern_matches(path, rel, p):
return True
except ValueError:
pass
# Also try relative to the anchor dir (the .graphifyignore's location),
# so patterns written at a parent level still fire when running on a subfolder
# Also try relative to the anchor dir (the pattern file's location),
# so parent-level patterns still fire when running on a subfolder.
if anchor != root:
try:
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
if _matches(rel_anchor, p):
if _pattern_matches(path, rel_anchor, p):
return True
except ValueError:
pass
return False
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if path matches any .graphifyignore pattern."""
return _matches_patterns(path, root, patterns)
def _is_included(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if path matches any .graphifyinclude allowlist pattern."""
return _matches_patterns(path, root, patterns)
def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
"""Return True if a directory may contain files matched by .graphifyinclude."""
if not patterns:
return False
rels: list[str] = []
try:
rels.append(str(path.relative_to(root)).replace(os.sep, "/"))
except ValueError:
pass
for anchor, _ in patterns:
if anchor != root:
try:
rels.append(str(path.relative_to(anchor)).replace(os.sep, "/"))
except ValueError:
pass
for rel in rels:
rel = rel.strip("/")
if not rel:
return True
for _, pattern in patterns:
p = pattern.strip("/")
if not p:
continue
if p == rel or p.startswith(rel + "/"):
return True
if _pattern_matches(path, rel, p):
return True
return False
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
root = root.resolve()
files: dict[FileType, list[str]] = {
@@ -347,6 +411,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
skipped_sensitive: list[str] = []
ignore_patterns = _load_graphifyignore(root)
include_patterns = _load_graphifyinclude(root)
# Always include graphify-out/memory/ - query results filed back into the graph
memory_dir = root / "graphify-out" / "memory"
@@ -368,11 +433,13 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
dirnames.clear()
continue
if not in_memory_tree:
# Prune noise dirs in-place so os.walk never descends into them
# Prune noise dirs in-place so os.walk never descends into them.
# Hidden dirs remain skipped by default, but .graphifyinclude can
# opt in the exact hidden subtrees needed to reach allowlisted files.
dirnames[:] = [
d for d in dirnames
if not d.startswith(".")
and not _is_noise_dir(d)
if not _is_noise_dir(d)
and (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
and not _is_ignored(dp / d, root, ignore_patterns)
]
for fname in filenames:
@@ -389,9 +456,12 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
# 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
if p.name.startswith("."):
try:
rel_parts = p.relative_to(root).parts
except ValueError:
rel_parts = p.parts
# Hidden files/directories are excluded unless this exact file is allowlisted.
if any(part.startswith(".") for part in rel_parts) 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)):
@@ -442,6 +512,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
"warning": warning,
"skipped_sensitive": skipped_sensitive,
"graphifyignore_patterns": len(ignore_patterns),
"graphifyinclude_patterns": len(include_patterns),
}
+40 -7
View File
@@ -25,6 +25,22 @@ COMMUNITY_COLORS = [
MAX_NODES_FOR_VIZ = 5_000
def _viz_node_limit() -> int:
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
"""
import os
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
if raw is None or not raw.strip():
return MAX_NODES_FOR_VIZ
try:
return int(raw)
except ValueError:
return MAX_NODES_FOR_VIZ
def _html_styles() -> str:
return """<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
@@ -327,6 +343,15 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
if "confidence_score" not in link:
conf = link.get("confidence", "EXTRACTED")
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
# Restore original edge direction. Undirected NetworkX storage may
# canonicalize endpoint order, flipping `calls` and other directional
# edges in graph.json. The build path stashes the true endpoints in
# _src/_tgt for exactly this purpose (#563).
true_src = link.pop("_src", None)
true_tgt = link.pop("_tgt", None)
if true_src is not None and true_tgt is not None:
link["source"] = true_src
link["target"] = true_tgt
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
with open(output_path, "w", encoding="utf-8") as f: # nosec
json.dump(data, f, indent=2)
@@ -386,15 +411,18 @@ def to_html(
Features: node size by degree, click-to-inspect panel, search box,
community filter, physics clustering by community, confidence-styled edges.
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
Raises ValueError if graph exceeds the effective viz node limit
(MAX_NODES_FOR_VIZ by default; overridable via GRAPHIFY_VIZ_NODE_LIMIT env var).
If member_counts is provided (aggregated community view), node sizes are
based on community member counts rather than graph degree.
"""
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
limit = _viz_node_limit()
if G.number_of_nodes() > limit:
raise ValueError(
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
f"Use --no-viz or reduce input size."
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
f"or reduce input size."
)
node_community = _node_community_map(communities)
@@ -431,14 +459,19 @@ def to_html(
"degree": deg,
})
# Build edges list
# Build edges list. Restore original edge direction from _src/_tgt
# (stashed by build.py for exactly this reason): undirected NetworkX
# canonicalizes endpoint order, which would otherwise flip the arrow
# for `calls` and `rationale_for` in the rendered graph (#563).
vis_edges = []
for u, v, data in G.edges(data=True):
confidence = data.get("confidence", "EXTRACTED")
relation = data.get("relation", "")
true_src = data.get("_src", u)
true_tgt = data.get("_tgt", v)
vis_edges.append({
"from": u,
"to": v,
"from": true_src,
"to": true_tgt,
"label": relation,
"title": _html.escape(f"{relation} [{confidence}]"),
"dashes": confidence != "EXTRACTED",
+68 -4
View File
@@ -11,6 +11,29 @@ from typing import Callable, Any
from .cache import load_cached, save_cached
# AST node types that represent a member-expression callee
# (`x.foo()`, `obj.bar()`, `Pkg::baz()`). Cross-file name-only resolution of
# these is unsafe — without receiver type info we routinely link them to the
# wrong target, producing phantom god nodes (e.g. every `Logger.log(...)` call
# in a NestJS codebase collapsing onto a one-off `function log(...)` defined
# in a smoke-test script). The cross-file resolver in `extract()` skips
# entries whose `callee_node_type` falls in this set.
_MEMBER_CALL_NODE_TYPES = frozenset({
"member_expression", # JS / TS / Python attribute calls
"selector_expression", # Go
"field_expression", # Rust, C++, Scala
"navigation_expression", # Swift, Kotlin
"qualified_identifier", # C++ (Foo::bar())
"scoped_identifier", # Rust (foo::bar())
"scoped_call_expression", # PHP (Foo::bar())
"member_call_expression", # PHP ($obj->method())
"field_access", # Java
"method_invocation", # Java (when receiver-qualified)
"dot", # Elixir
"_zig_dotted_callee", # synthetic marker for Zig (callee text contains ".")
})
def _make_id(*parts: str) -> str:
"""Build a stable node ID from one or more name parts."""
combined = "_".join(p.strip("_.") for p in parts if p)
@@ -1172,13 +1195,16 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
"weight": 1.0,
})
elif callee_name and not tgt_nid:
# Callee not in this file — save for cross-file resolution in extract()
# Callee not in this file — save for cross-file resolution in extract().
# Track the AST node type so the cross-file resolver can refuse to
# name-match member-expression callees (`x.foo()`).
raw_calls.append({
"caller_nid": caller_nid,
"callee": callee_name,
"is_member_call": is_member_call,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
"callee_node_type": func_node.type if func_node is not None else None,
})
# Helper function calls: config('foo.bar') → uses_config edge to "foo"
@@ -2131,6 +2157,7 @@ def extract_go(path: Path) -> dict:
"is_member_call": is_member_call,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
"callee_node_type": func_node.type if func_node is not None else None,
})
for child in node.children:
walk_calls(child, caller_nid)
@@ -2311,6 +2338,7 @@ def extract_rust(path: Path) -> dict:
"is_member_call": is_member_call,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
"callee_node_type": func_node.type if func_node is not None else None,
})
for child in node.children:
walk_calls(child, caller_nid)
@@ -2482,6 +2510,13 @@ def extract_zig(path: Path) -> dict:
"is_member_call": is_member_call,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
# Zig: callee is `_read_text(fn, source).split(".")[-1]`,
# so a "." in the original text means it was a member call.
"callee_node_type": (
"_zig_dotted_callee"
if "." in _read_text(fn, source)
else fn.type
),
})
for child in node.children:
walk_calls(child, caller_nid)
@@ -2647,6 +2682,7 @@ def extract_powershell(path: Path) -> dict:
"is_member_call": False,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
"callee_node_type": "command_name",
})
for child in node.children:
walk_calls(child, caller_nid)
@@ -2699,8 +2735,17 @@ def _resolve_cross_file_imports(
stem = Path(src).stem
label = node.get("label", "")
nid = node.get("id", "")
# Only index real classes/functions (not file nodes, not method stubs)
if label and not label.endswith((")", ".py")) and "_" not in label[:1]:
# Index class-level entities only. Function/method labels end in "()"
# so are excluded by the `endswith(")")` filter; file nodes end in ".py";
# private/internal labels start with "_"; rationale nodes carry
# file_type=="rationale" and must never participate in cross-file
# import resolution (#563).
if (
label
and not label.endswith((")", ".py"))
and "_" not in label[:1]
and node.get("file_type") != "rationale"
):
stem_to_entities.setdefault(stem, {})[label] = nid
# Pass 2: for each file, find `from .X import A, B, C` and resolve
@@ -2711,12 +2756,15 @@ def _resolve_cross_file_imports(
stem = _file_stem(path)
str_path = str(path)
# Find all classes defined in this file (the importers)
# Find all classes defined in this file (the importers).
# Excludes rationale nodes whose labels happen not to end in ")" or ".py"
# but which must never be treated as importing entities (#563).
local_classes = [
n["id"] for n in file_result.get("nodes", [])
if n.get("source_file") == str_path
and not n["label"].endswith((")", ".py"))
and n["id"] != _make_id(stem) # exclude file-level node
and n.get("file_type") != "rationale"
]
if not local_classes:
continue
@@ -3253,6 +3301,9 @@ def extract_elixir(path: Path) -> dict:
"is_member_call": is_member_call,
"source_file": str_path,
"source_location": f"L{node.start_point[0] + 1}",
# Elixir: `child` is the node we just inspected — `dot` for
# `Mod.fn(...)`, `identifier` for a bare local call.
"callee_node_type": child.type,
})
for child in node.children:
walk_calls(child, caller_nid)
@@ -3435,8 +3486,13 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
# Cross-file call resolution for all languages
# Each extractor saved unresolved calls in raw_calls. Now that we have all
# nodes from all files, resolve any callee that exists in another file.
# Build label -> node_id index for cross-file call resolution.
# Skip rationale nodes (their labels are docstring text, not callable
# identifiers, and they were polluting matches for short names — #563).
global_label_to_nid: dict[str, str] = {}
for n in all_nodes:
if n.get("file_type") == "rationale":
continue
raw = n.get("label", "")
normalised = raw.strip("()").lstrip(".")
if normalised:
@@ -3445,6 +3501,14 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
existing_pairs = {(e["source"], e["target"]) for e in all_edges}
for result in per_file:
for rc in result.get("raw_calls", []):
# Member-expression callees (`x.foo()`, `obj.bar()`, `Pkg::baz()`)
# cannot be safely resolved by bare property name across files —
# without receiver-type analysis we routinely link them to the
# wrong target, producing phantom god nodes (e.g. every
# `Logger.log(...)` call collapsing onto a one-off
# `function log(...)` defined in a smoke-test script).
if rc.get("callee_node_type") in _MEMBER_CALL_NODE_TYPES:
continue
callee = rc.get("callee", "")
if not callee:
continue
+1 -1
View File
@@ -240,7 +240,7 @@ Process each file one at a time. For each file:
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
3. Accumulate results across all files
Schema for each file's output:
+1 -1
View File
@@ -240,7 +240,7 @@ Process each file one at a time. For each file:
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
3. Accumulate results across all files
Schema for each file's output:
+10 -4
View File
@@ -293,10 +293,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+22 -5
View File
@@ -289,10 +289,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
@@ -819,11 +825,22 @@ deleted = set(incremental.get('deleted_files', []))
if deleted:
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
G_existing.remove_nodes_from(to_remove)
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
if to_remove:
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
else:
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
# Merge: new nodes/edges into existing graph
G_existing.update(G_new)
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
# Save manifest with the CURRENT full file list so the next --update
# diffs against today's filesystem state, not the prior --update's
# baseline. Without this, deleted files get reported as ghosts again
# on every subsequent --update until a full rebuild runs.
from graphify.detect import save_manifest
save_manifest(incremental['files'])
print('[graphify update] Manifest saved.')
"
```
+10 -4
View File
@@ -290,10 +290,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+1 -1
View File
@@ -239,7 +239,7 @@ Process each file one at a time. For each file:
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
3. Accumulate results across all files
Schema for each file's output:
+10 -4
View File
@@ -291,10 +291,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+10 -4
View File
@@ -280,10 +280,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+10 -4
View File
@@ -279,10 +279,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Output exactly this JSON (no other text):
+22 -5
View File
@@ -337,10 +337,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: reason about each edge individually.
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
Reasonable inference with some uncertainty: 0.6-0.7.
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
@@ -923,7 +929,10 @@ deleted = set(incremental.get('deleted_files', []))
if deleted:
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
G_existing.remove_nodes_from(to_remove)
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
if to_remove:
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
else:
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
# Merge: new nodes/edges into existing graph
G_existing.update(G_new)
@@ -939,6 +948,14 @@ merged_out = {
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out))
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
# Save manifest with the CURRENT full file list so the next --update
# diffs against today's filesystem state, not the prior --update's
# baseline. Without this, deleted files get reported as ghosts again
# on every subsequent --update until a full rebuild runs.
from graphify.detect import save_manifest
save_manifest(incremental['files'])
print('[graphify update] Manifest saved.')
"
```
+21 -1
View File
@@ -7,7 +7,18 @@ import networkx as nx
def _safe_filename(name: str) -> str:
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
"""Make a label safe for use as a filename across platforms.
Substitutes characters that Windows reserves in filenames
(< > : " / \\ | ? *) and strips trailing dots/spaces, also reserved.
Falls back to 'unnamed' for empty results and caps length at 200
chars to stay well under common filesystem limits.
"""
import re
s = name.replace("/", "-").replace(" ", "_").replace(":", "-")
s = re.sub(r'[<>:"/\\|?*]', '_', s)
s = s.strip('. ')
return s[:200] if s else 'unnamed'
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
@@ -185,6 +196,15 @@ def to_wiki(
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
# Clear stale .md files from previous runs to prevent orphan accumulation.
# Community labels are LLM-generated (per skill.md Step 5) and non-deterministic
# across runs — the same conceptual community may be named differently each time
# (e.g. "AutoAgent Skills" → "AutoAgent Methodology"), leaving the previous file
# as an orphan. Since to_wiki() owns wiki/ entirely (always writes the full set),
# it can safely clear .md files at the start of each call.
for old_article in out.glob("*.md"):
old_article.unlink()
labels = community_labels or {cid: f"Community {cid}" for cid in communities}
cohesion = cohesion or {}
god_nodes_data = god_nodes_data or []
+1
View File
@@ -51,6 +51,7 @@ leiden = ["graspologic; python_version < '3.13'"]
office = ["python-docx", "openpyxl"]
video = ["faster-whisper", "yt-dlp"]
kimi = ["openai"]
test = ["pytest>=7", "pytest-cov"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai"]
[project.scripts]
+36
View File
@@ -104,6 +104,42 @@ def test_graphifyignore_missing_is_fine(tmp_path):
assert result["graphifyignore_patterns"] == 0
def test_graphifyinclude_allows_curated_files_inside_hidden_dirs(tmp_path):
"""A .graphifyinclude allowlist can opt curated hidden markdown paths into detect()."""
(tmp_path / ".graphifyinclude").write_text(".hermes/plans/**/*.md\n")
plans = tmp_path / ".hermes" / "plans"
plans.mkdir(parents=True)
(plans / "knowledge-plan.md").write_text("# Knowledge Plan\nThis is the searchable plan.")
context = tmp_path / ".hermes" / "context"
context.mkdir(parents=True)
(context / "scratch.md").write_text("# Scratch\nThis should stay out.")
(tmp_path / "README.md").write_text("# Visible\nVisible docs still work.")
result = detect(tmp_path)
docs = result["files"]["document"]
assert any(".hermes/plans/knowledge-plan.md" in f for f in docs)
assert not any(".hermes/context/scratch.md" in f for f in docs)
assert any("README.md" in f for f in docs)
assert result["graphifyinclude_patterns"] == 1
def test_graphifyinclude_does_not_override_sensitive_file_skips(tmp_path):
"""Even allowlisted hidden paths must not index secret-looking files."""
(tmp_path / ".graphifyinclude").write_text(".hermes/plans/**/*.md\n")
plans = tmp_path / ".hermes" / "plans"
plans.mkdir(parents=True)
(plans / "api_token.md").write_text("token: should not be indexed")
(plans / "public-plan.md").write_text("# Public Plan\nSafe searchable material.")
result = detect(tmp_path)
docs = result["files"]["document"]
assert any(".hermes/plans/public-plan.md" in f for f in docs)
assert not any("api_token.md" in f for f in docs)
assert len(result["skipped_sensitive"]) == 1
def test_graphifyignore_comments_ignored(tmp_path):
"""Comment lines in .graphifyignore are not treated as patterns."""
(tmp_path / ".graphifyignore").write_text("# this is a comment\n\nmain.py\n")
+67 -1
View File
@@ -1,9 +1,19 @@
import json
import os
import tempfile
import pytest
from pathlib import Path
from graphify.build import build_from_json
from graphify.cluster import cluster
from graphify.export import to_json, to_cypher, to_graphml, to_html, to_canvas
from graphify.export import (
to_json,
to_cypher,
to_graphml,
to_html,
to_canvas,
_viz_node_limit,
MAX_NODES_FOR_VIZ,
)
FIXTURES = Path(__file__).parent / "fixtures"
@@ -127,6 +137,62 @@ def test_to_html_contains_nodes_and_edges():
assert "RAW_EDGES" in content
# --- GRAPHIFY_VIZ_NODE_LIMIT env var --------------------------------------------
@pytest.fixture
def restore_viz_env(monkeypatch):
"""Ensure each test runs without GRAPHIFY_VIZ_NODE_LIMIT bleeding across cases."""
monkeypatch.delenv("GRAPHIFY_VIZ_NODE_LIMIT", raising=False)
yield
def test_viz_node_limit_default(restore_viz_env):
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
def test_viz_node_limit_env_override_higher(restore_viz_env, monkeypatch):
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "20000")
assert _viz_node_limit() == 20000
def test_viz_node_limit_env_override_zero_disables(restore_viz_env, monkeypatch):
"""Setting to 0 lets users disable HTML viz unconditionally (CI runners)."""
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "0")
assert _viz_node_limit() == 0
def test_viz_node_limit_invalid_falls_back_to_default(restore_viz_env, monkeypatch):
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "not-an-int")
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
def test_viz_node_limit_empty_falls_back_to_default(restore_viz_env, monkeypatch):
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", " ")
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
def test_to_html_raises_with_lowered_limit(restore_viz_env, monkeypatch):
"""Lowering the limit below the test graph's size triggers ValueError."""
G = make_graph()
communities = cluster(G)
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "1")
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
with pytest.raises(ValueError, match="too large for HTML viz"):
to_html(G, communities, str(out))
def test_to_html_writes_with_raised_limit(restore_viz_env, monkeypatch):
"""Raising the limit above the graph's size lets to_html proceed normally."""
G = make_graph()
communities = cluster(G)
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "100000")
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "graph.html"
to_html(G, communities, str(out))
assert out.exists()
def test_to_html_member_counts_accepted():
"""to_html accepts member_counts without raising."""
G = make_graph()
+27
View File
@@ -123,3 +123,30 @@ def test_hook_skips_head_on_exe():
"""Hook script must skip shebang extraction for .exe binaries (Windows)."""
from graphify.hooks import _PYTHON_DETECT
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
def test_hooks_dir_expands_tilde(tmp_path, monkeypatch):
"""_hooks_dir must call expanduser() so ~/... paths in core.hooksPath resolve correctly."""
from graphify.hooks import _hooks_dir
import types
repo = _make_git_repo(tmp_path)
custom_hooks = tmp_path / "custom_hooks"
custom_hooks.mkdir()
# expanduser() reads $HOME, so override it to make ~/custom_hooks predictable
monkeypatch.setenv("HOME", str(tmp_path))
real_run = subprocess.run
def fake_run(cmd, **kwargs):
if isinstance(cmd, list) and "config" in cmd and "core.hooksPath" in cmd:
return types.SimpleNamespace(returncode=0, stdout="~/custom_hooks")
return real_run(cmd, **kwargs)
monkeypatch.setattr(subprocess, "run", fake_run)
resolved = _hooks_dir(repo)
assert resolved == custom_hooks, (
f"expected {custom_hooks}, got {resolved} — tilde was not expanded"
)
+64
View File
@@ -1,4 +1,5 @@
"""Tests for graphify install --platform routing."""
import json
from pathlib import Path
from unittest.mock import patch
import pytest
@@ -129,6 +130,69 @@ def test_codex_agents_install_writes_agents_md(tmp_path):
assert "GRAPH_REPORT.md" in agents_md.read_text()
def test_codex_agents_install_writes_user_prompt_submit_hook(tmp_path):
_agents_install(tmp_path, "codex")
hooks_path = tmp_path / ".codex" / "hooks.json"
hooks = json.loads(hooks_path.read_text())
command = hooks["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"]
assert "UserPromptSubmit" in hooks["hooks"]
assert "PreToolUse" not in hooks["hooks"]
assert "UserPromptSubmit" in command
assert "additionalContext" in command
assert "graphify-out/GRAPH_REPORT.md" in command
def test_codex_agents_install_removes_only_graphify_generated_hooks(tmp_path):
from graphify.__main__ import _LEGACY_CODEX_PRE_TOOL_HOOK
unrelated_hook = {
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo graphify for my own plugin",
}
],
}
hooks_path = tmp_path / ".codex" / "hooks.json"
hooks_path.parent.mkdir(parents=True)
hooks_path.write_text(json.dumps({
"hooks": {
"PreToolUse": [
_LEGACY_CODEX_PRE_TOOL_HOOK,
unrelated_hook,
]
}
}))
_agents_install(tmp_path, "codex")
hooks = json.loads(hooks_path.read_text())
pre_tool = hooks["hooks"].get("PreToolUse", [])
user_prompt = hooks["hooks"].get("UserPromptSubmit", [])
assert pre_tool == [unrelated_hook]
assert len(user_prompt) == 1
assert "graphify-out/GRAPH_REPORT.md" in user_prompt[0]["hooks"][0]["command"]
def test_codex_agents_install_preserves_non_object_hooks_value(tmp_path):
hooks_path = tmp_path / ".codex" / "hooks.json"
hooks_path.parent.mkdir(parents=True)
hooks_path.write_text(json.dumps({
"hooks": ["recoverable user config"],
"other": {"keep": True},
}))
_agents_install(tmp_path, "codex")
hooks = json.loads(hooks_path.read_text())
assert hooks["hooks"] == ["recoverable user config"]
assert hooks["other"] == {"keep": True}
def test_opencode_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "opencode")
assert (tmp_path / "AGENTS.md").exists()
+326
View File
@@ -0,0 +1,326 @@
"""Regression tests for issue #563.
Two extractor bugs were inflating god-node centrality:
1. `_resolve_cross_file_imports` accepted rationale nodes as "importing
classes", causing a phantom `<file>_rationale_N --uses--> ImportedThing`
edge for every imported entity in every file with docstrings. Cross-file
call resolution had the same leak via `global_label_to_nid`.
2. The `to_json` exporter serialized a NetworkX undirected graph and lost
edge direction; `_src` / `_tgt` were stashed by `build` precisely to
restore direction at export time, but were not consulted.
Both bugs are observable in the AST-only path (no LLM required).
Note: the fixture uses module name ``jobq`` rather than ``queue`` to avoid
colliding with the Python stdlib ``queue`` module that graphify's update
path imports.
"""
from __future__ import annotations
import json
import subprocess
import sys
import textwrap
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent
def _write_repro(root: Path) -> None:
(root / "jobq.py").write_text(textwrap.dedent('''
"""Job-queue module — provides SQLiteQueue for idempotent job tracking."""
class SQLiteQueue:
"""Lightweight SQLite-backed queue.
Used by middleware routers and CLI commands to enqueue work and
deduplicate via idempotency keys.
"""
def check_idempotency(self, key):
"""Return existing lead for key, or None."""
return None
def enqueue(self, payload):
"""Persist payload to the queue."""
return True
''').lstrip())
(root / "contact_form.py").write_text(textwrap.dedent('''
"""HTTP router for the contact form endpoint."""
from jobq import SQLiteQueue
q = SQLiteQueue()
def contact_form(payload_obj):
"""Handle a contact form submission.
Idempotency is keyed on payload_obj.idempotency_key.
"""
existing_lead = q.check_idempotency(payload_obj.idempotency_key)
if existing_lead:
return existing_lead
q.enqueue(payload_obj)
return {"ok": True}
''').lstrip())
(root / "test_customer_dedup.py").write_text(textwrap.dedent('''
"""Tests for customer dedup — exercises phone normalization and Odoo tagging."""
from jobq import SQLiteQueue
from contact_form import contact_form
def test_us_phone_no_country_code():
"""US phone without country code uses default region US -> +1 prefix."""
assert True
def test_uk_phone_with_prefix():
"""UK phone with +44 prefix parses regardless of default region."""
assert True
def test_invalid_phone_returns_none():
"""Phone that parses but isn't a valid number -> None."""
assert True
def test_odoo_tag_missing_still_chatter():
"""If the tag isn't seeded, still post the chatter note."""
queue = SQLiteQueue()
queue.enqueue({})
contact_form(None)
''').lstrip())
def _run_graphify_update(root: Path) -> dict:
result = subprocess.run(
[sys.executable, "-m", "graphify", "update", str(root)],
capture_output=True,
text=True,
cwd=str(root),
)
assert result.returncode == 0, (
f"graphify update failed: {result.stderr}\nstdout: {result.stdout}"
)
graph_path = root / "graphify-out" / "graph.json"
assert graph_path.exists(), f"graph.json not produced. stderr: {result.stderr}"
return json.loads(graph_path.read_text())
@pytest.fixture
def repro_graph(tmp_path: Path) -> dict:
_write_repro(tmp_path)
return _run_graphify_update(tmp_path)
# ─────────────────────────────────────────────────────────────────────────────
# Bug 1: rationale node leakage into cross-file resolvers
# ─────────────────────────────────────────────────────────────────────────────
def _file_type_map(graph: dict) -> dict[str, str]:
"""Map node id -> file_type from the serialized graph.
Identifying rationale nodes via node metadata (file_type == "rationale")
is more durable than substring-matching on the id, which couples to the
current `<stem>_rationale_<line>` naming scheme.
"""
return {n["id"]: n.get("file_type", "") for n in graph["nodes"]}
def test_no_rationale_nodes_in_uses_or_calls_edges(repro_graph):
"""Rationale nodes describe code; they cannot `use`, `call`, or `reference`
anything. The only relation a rationale node may participate in is
`rationale_for` (extractor emits `rationale --rationale_for--> parent`)."""
ftype = _file_type_map(repro_graph)
bad = [
e for e in repro_graph["links"]
if (ftype.get(e["source"]) == "rationale"
or ftype.get(e["target"]) == "rationale")
and e["relation"] != "rationale_for"
]
assert bad == [], (
f"Rationale nodes must only appear in rationale_for edges. "
f"Found {len(bad)} bad edges with relations "
f"{sorted({e['relation'] for e in bad})}: {bad[:3]}"
)
def test_rationale_for_direction_is_rationale_to_parent(repro_graph):
"""Rationale_for edges encode "this docstring fragment is the rationale
for this code entity": source is the rationale node, target is the parent.
The export-side direction restore (#563) was the only thing that made
this hold under undirected NetworkX storage."""
ftype = _file_type_map(repro_graph)
rats = [e for e in repro_graph["links"] if e["relation"] == "rationale_for"]
assert rats, "expected some rationale_for edges in the repro"
bad = [e for e in rats if ftype.get(e["source"]) != "rationale"]
assert bad == [], (
f"rationale_for edges must have a rationale node as source. "
f"Found {len(bad)} flipped: {bad[:3]}"
)
# ─────────────────────────────────────────────────────────────────────────────
# Bug 2: `calls` direction must be caller -> callee
# ─────────────────────────────────────────────────────────────────────────────
def _calls(graph: dict) -> list[tuple[str, str]]:
return [
(e["source"], e["target"])
for e in graph["links"]
if e.get("relation") == "calls"
]
def test_calls_direction_is_caller_to_callee(repro_graph):
"""The exact directions reported as inverted in #563 must hold."""
calls = _calls(repro_graph)
# contact_form() calls SQLiteQueue.check_idempotency() and SQLiteQueue.enqueue()
assert (
"contact_form_contact_form",
"jobq_sqlitequeue_check_idempotency",
) in calls, f"expected caller->callee edge missing. got: {calls}"
assert (
"contact_form_contact_form",
"jobq_sqlitequeue_enqueue",
) in calls, f"contact_form->enqueue edge missing. got: {calls}"
# The test function calls contact_form()
assert (
"test_customer_dedup_test_odoo_tag_missing_still_chatter",
"contact_form_contact_form",
) in calls, f"test->contact_form edge missing. got: {calls}"
# And critically, none of the inversions exist:
inversions = {
("jobq_sqlitequeue_check_idempotency", "contact_form_contact_form"),
("jobq_sqlitequeue_enqueue", "contact_form_contact_form"),
("contact_form_contact_form",
"test_customer_dedup_test_odoo_tag_missing_still_chatter"),
}
leaked = set(calls) & inversions
assert not leaked, f"Found inverted calls edges: {leaked}"
def test_calls_direction_on_existing_sample_calls_fixture():
"""Pin the direction on the in-tree fixture too — adds direction
coverage to the existing AST extractor tests."""
from graphify.extract import extract_python
fixture = REPO_ROOT / "tests" / "fixtures" / "sample_calls.py"
result = extract_python(fixture)
calls = [
(e["source"], e["target"])
for e in result["edges"]
if e.get("relation") == "calls"
]
assert calls, "sample_calls.py must produce some calls edges"
# In sample_calls.py:
# compute_score and normalize are LEAF functions — they call nothing.
# They must appear as callees, never as callers.
leaf_callers = [
src for src, _ in calls
if src.endswith("compute_score") or src.endswith("normalize")
]
assert leaf_callers == [], (
f"Leaf functions appearing as callers means direction is inverted: "
f"{leaf_callers}"
)
# And they should appear at least once as callees.
leaf_callees = [
tgt for _, tgt in calls
if "compute_score" in tgt or "normalize" in tgt
]
assert leaf_callees, f"leaf functions should appear as callees. got: {calls}"
def test_src_tgt_metadata_not_leaked_into_graph_json(repro_graph):
"""The _src/_tgt direction-preservation fields are an internal detail
of the build path; they must be consumed by the exporter and stripped
from graph.json."""
leaks = [e for e in repro_graph["links"] if "_src" in e or "_tgt" in e]
assert leaks == [], (
f"_src/_tgt are internal; must not appear in graph.json. Leaks: {leaks[:3]}"
)
# ─────────────────────────────────────────────────────────────────────────────
# Bug 2 (HTML export): graph.html arrows must respect direction too
# ─────────────────────────────────────────────────────────────────────────────
def _vis_edges_from_html(html: str) -> list[dict]:
"""Extract the vis.js edges array embedded in graph.html.
`_html_script` emits `const RAW_EDGES = <json>;` — pull that JSON out
directly rather than parsing the surrounding script.
"""
import re
m = re.search(r"const RAW_EDGES = (\[.*?\]);", html, re.DOTALL)
assert m, "could not locate RAW_EDGES in graph.html"
return json.loads(m.group(1))
def test_to_html_preserves_calls_and_rationale_for_direction(tmp_path: Path):
"""to_html must read _src/_tgt before assigning vis.js `from`/`to`,
otherwise undirected NetworkX storage flips arrows on render (#563)."""
from graphify.build import build_from_json
from graphify.export import to_html
_write_repro(tmp_path)
repro_graph = _run_graphify_update(tmp_path)
G = build_from_json(repro_graph)
out_html = tmp_path / "graph.html"
to_html(G, communities={0: list(G.nodes())}, output_path=str(out_html))
vis_edges = _vis_edges_from_html(out_html.read_text(encoding="utf-8"))
pairs = {(e["from"], e["to"]): e.get("label") for e in vis_edges}
# rationale_for: source must be the rationale node (file_type metadata
# isn't on vis_edges, so we check via the json graph's node map).
ftype = _file_type_map(repro_graph)
rats_html = [
(frm, to) for (frm, to), rel in pairs.items() if rel == "rationale_for"
]
assert rats_html, "expected rationale_for edges in graph.html"
flipped_rats = [
(frm, to) for (frm, to) in rats_html if ftype.get(frm) != "rationale"
]
assert flipped_rats == [], (
f"rationale_for arrows in graph.html must point rationale->parent. "
f"Flipped: {flipped_rats[:3]}"
)
# calls: pin the same caller->callee directions asserted on graph.json.
assert (
"contact_form_contact_form",
"jobq_sqlitequeue_check_idempotency",
) in pairs, "contact_form->check_idempotency arrow missing in graph.html"
assert (
"contact_form_contact_form",
"jobq_sqlitequeue_enqueue",
) in pairs, "contact_form->enqueue arrow missing in graph.html"
# And the inversions must not be present.
inversions = {
("jobq_sqlitequeue_check_idempotency", "contact_form_contact_form"),
("jobq_sqlitequeue_enqueue", "contact_form_contact_form"),
}
leaked = inversions & {
(frm, to) for (frm, to), rel in pairs.items() if rel == "calls"
}
assert not leaked, f"Inverted calls arrows in graph.html: {leaked}"
+177
View File
@@ -0,0 +1,177 @@
"""
Regression test for the cross-file member-call name-collision bug fixed by
the `_MEMBER_CALL_NODE_TYPES` resolver guard.
Bug summary
-----------
graphify's per-language AST extractors strip member-expression callees
(`this.logger.log(...)`, `obj.find(...)`, `Pkg::baz(...)`) down to the
trailing identifier (`log`, `find`, `baz`) and queue them in `raw_calls`
for cross-file resolution. The cross-file resolver then matches that bare
identifier against a global lowercase name → id map. If any other file in
the corpus defines a top-level helper with the same name (e.g. a
`function log(id, name, pass) { ... }` in a smoke-test script), every
unrelated `Logger.log` / `this.logger.log` / `logger.log` call across the
codebase resolves to that single helper, producing a phantom god node with
hundreds of bogus INFERRED edges.
Fix
---
Each `raw_calls.append(...)` now records `callee_node_type` (the AST node
type of the callee). The cross-file resolver in `extract()` skips entries
whose `callee_node_type` is in `_MEMBER_CALL_NODE_TYPES`.
Run with:
pytest tests/test_member_call_resolution.py -v
"""
from __future__ import annotations
from pathlib import Path
import pytest
from graphify.extract import extract
try:
from graphify.extract import _MEMBER_CALL_NODE_TYPES
except ImportError:
_MEMBER_CALL_NODE_TYPES = None # patched constant absent on unpatched code
# ---------------------------------------------------------------------------
# Source fixtures — written verbatim to a tmp dir so tree-sitter sees real files
# ---------------------------------------------------------------------------
_SMOKE_TEST_JS = """\
const results = [];
function log(id, name, pass, detail = '') {
const status = pass ? 'PASS' : 'FAIL';
console.log(`${id} ${status} ${name}`);
results.push({ id, name, pass });
}
function testAuth() {
log('A1', 'auth-login', true);
log('A2', 'auth-refresh', true);
}
testAuth();
"""
_NESTJS_SERVICE_TS = """\
import { Logger } from '@nestjs/common';
export class AppointmentsService {
private readonly logger = new Logger('AppointmentsService');
async create(payload: unknown): Promise<void> {
this.logger.log('Creating appointment');
Logger.log('static-style log call');
}
async cancel(id: string): Promise<void> {
this.logger.log(`Cancelled ${id}`);
}
}
"""
_NESTJS_OTHER_SERVICE_TS = """\
import { Logger } from '@nestjs/common';
const logger = new Logger('eprescribing-metrics');
export function logTransmissionAttempt(rxId: string): void {
logger.log({ event: 'tx-attempt', rxId });
}
export function logWebhookReceived(payload: unknown): void {
logger.log({ event: 'webhook', payload });
}
"""
@pytest.fixture
def project(tmp_path: Path) -> Path:
(tmp_path / "validation").mkdir()
(tmp_path / "src").mkdir()
(tmp_path / "validation" / "smoke-test.mjs").write_text(_SMOKE_TEST_JS)
(tmp_path / "src" / "appointments.service.ts").write_text(_NESTJS_SERVICE_TS)
(tmp_path / "src" / "eprescribing-metrics.ts").write_text(_NESTJS_OTHER_SERVICE_TS)
return tmp_path
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
def test_member_call_node_types_constant_present() -> None:
"""The constant must exist and cover every language extractor."""
assert _MEMBER_CALL_NODE_TYPES is not None, (
"_MEMBER_CALL_NODE_TYPES is missing from graphify.extract — patch not applied"
)
assert isinstance(_MEMBER_CALL_NODE_TYPES, frozenset)
# Spot-check that the most important node types are tracked.
for required in (
"member_expression", # JS/TS
"selector_expression", # Go
"field_expression", # Rust / C++
"navigation_expression", # Swift / Kotlin
"dot", # Elixir
):
assert required in _MEMBER_CALL_NODE_TYPES, f"missing: {required}"
def test_smoke_test_log_does_not_steal_nestjs_logger_calls(project: Path) -> None:
"""
Regression: with a corpus containing both `validation/smoke-test.mjs`
(which defines `function log(...)`) AND NestJS service files (which
call `this.logger.log(...)` / `Logger.log(...)` / `logger.log(...)`),
NONE of the NestJS calls should resolve to the smoke-test `log` node.
"""
files = sorted(project.rglob("*.mjs")) + sorted(project.rglob("*.ts"))
result = extract(files, cache_root=project)
log_nodes = [n for n in result["nodes"]
if n.get("label", "").strip().rstrip("()") == "log"]
assert len(log_nodes) == 1, "expected exactly one top-level log() symbol"
log_id = log_nodes[0]["id"]
log_source_file = log_nodes[0]["source_file"]
# Every inbound edge to log() must come from the same file (validation/smoke-test.mjs).
inbound = [e for e in result["edges"] if e.get("target") == log_id]
cross_file = [e for e in inbound if e.get("source_file") != log_source_file]
assert not cross_file, (
f"phantom edges leaked to log() from other files: "
f"{[(e['source_file'], e['source_location']) for e in cross_file]}"
)
# And we should still capture the legitimate intra-file calls
# (testAuth → log in the smoke-test file).
assert any(e for e in inbound if e.get("source_file") == log_source_file), (
"lost legitimate intra-file call edges to log()"
)
def test_raw_calls_emit_callee_node_type_for_member_expressions(project: Path) -> None:
"""
Direct check on the raw-calls payload: any unresolved member-expression
callee should carry a `callee_node_type` that's in _MEMBER_CALL_NODE_TYPES.
We can't easily inspect raw_calls after extract() returns (they get
consumed by the resolver), so we test indirectly: the absence of phantom
edges (above test) is the observable proof.
"""
# Sanity: just exercise extract() with something that triggers raw_calls
# so we know our test corpus is meaningful.
files = sorted(project.rglob("*.mjs")) + sorted(project.rglob("*.ts"))
result = extract(files, cache_root=project)
# We expect nodes from all three files.
source_files = {n.get("source_file") for n in result["nodes"]}
assert any("smoke-test" in (s or "") for s in source_files)
assert any("appointments.service" in (s or "") for s in source_files)
assert any("eprescribing-metrics" in (s or "") for s in source_files)
+47
View File
@@ -137,3 +137,50 @@ def test_community_article_truncation_notice(tmp_path):
to_wiki(G, communities, tmp_path, community_labels={0: "Big Community"})
article = (tmp_path / "Big_Community.md").read_text()
assert "and 5 more nodes" in article
def test_to_wiki_clears_stale_articles(tmp_path):
"""Regression: previous-run articles must be removed when labels change.
Real-world impact: community labels are LLM-generated (per skill.md Step 5)
and non-deterministic across runs, so the same conceptual community gets a
different 2-5 word name each rebuild. Without cleanup, every rebuild leaves
the previous run's files as orphans, growing wiki/ unboundedly.
"""
G = _make_graph()
# First run with one set of labels
to_wiki(G, COMMUNITIES, tmp_path, community_labels={0: "Old Name A", 1: "Old Name B"})
assert (tmp_path / "Old_Name_A.md").exists()
assert (tmp_path / "Old_Name_B.md").exists()
# Second run simulates LLM picking different names for the same communities
to_wiki(G, COMMUNITIES, tmp_path, community_labels={0: "New Name A", 1: "New Name B"})
# Old files should be gone; new files should exist
assert not (tmp_path / "Old_Name_A.md").exists(), "stale article from previous run not cleared"
assert not (tmp_path / "Old_Name_B.md").exists(), "stale article from previous run not cleared"
assert (tmp_path / "New_Name_A.md").exists()
assert (tmp_path / "New_Name_B.md").exists()
# index.md is always rewritten
assert (tmp_path / "index.md").exists()
def test_to_wiki_preserves_non_md_files(tmp_path):
"""Cleanup only touches top-level .md files; subdirectories and other files survive.
Some users may keep auxiliary assets (images, .json sidecars) in wiki/ —
cleanup must not be destructive beyond its own .md output domain.
"""
G = _make_graph()
tmp_path.mkdir(parents=True, exist_ok=True)
(tmp_path / "user_image.png").write_bytes(b"\x89PNG fake")
(tmp_path / "user_data.json").write_text('{"key": "value"}')
(tmp_path / "subdir").mkdir()
(tmp_path / "subdir" / "nested.md").write_text("# user content")
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
assert (tmp_path / "user_image.png").exists(), "non-.md file deleted"
assert (tmp_path / "user_data.json").exists(), "non-.md file deleted"
assert (tmp_path / "subdir" / "nested.md").exists(), "subdirectory .md deleted"