[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78CPJ9C0K59MY1WFKAVMZS8":3,"skill-same:01M78CPJ9C0K59MY1WFKAVMZS8":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M78CPJ9C0K59MY1WFKAVMZS8","graphify",null,"any input (code, docs, papers, images, videos) to knowledge graph. Use when user asks any question about a codebase, documents, or project content - especially if graphify-out\u002F exists, treat the question as a \u002Fgraphify query.","princepatel04477-web\u002Ftrivoxa-group","princepatel04477-web","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F227740714?v=4","01M788ZAJ2KECD5KXVP55PZXKS","Prince Patel","01M788ZAJTCN8YSD737MRSKC5Q",0,"MIT","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fgraphify\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: graphify\ndescription: \"any input (code, docs, papers, images, videos) to knowledge graph. Use when user asks any question about a codebase, documents, or project content - especially if graphify-out\u002F exists, treat the question as a \u002Fgraphify query.\"\ntrigger: \u002Fgraphify\n---\n\n# \u002Fgraphify\n\nTurn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.\n\n## Usage\n\n```\n\u002Fgraphify                                             # full pipeline on current directory → Obsidian vault\n\u002Fgraphify \u003Cpath>                                      # full pipeline on specific path\n\u002Fgraphify https:\u002F\u002Fgithub.com\u002F\u003Cowner>\u002F\u003Crepo>           # clone repo then run full pipeline on it\n\u002Fgraphify https:\u002F\u002Fgithub.com\u002F\u003Cowner>\u002F\u003Crepo> --branch \u003Cbranch>  # clone a specific branch\n\u002Fgraphify \u003Curl1> \u003Curl2> ...                           # clone multiple repos, build each, merge into one cross-repo graph\n\u002Fgraphify \u003Cpath> --mode deep                          # thorough extraction, richer INFERRED edges\n\u002Fgraphify \u003Cpath> --update                             # incremental - re-extract only new\u002Fchanged files\n\u002Fgraphify \u003Cpath> --directed                            # build directed graph (preserves edge direction: source→target)\n\u002Fgraphify \u003Cpath> --whisper-model medium                # use a larger Whisper model for better transcription accuracy\n\u002Fgraphify \u003Cpath> --cluster-only                       # rerun clustering on existing graph\n\u002Fgraphify \u003Cpath> --no-viz                             # skip visualization, just report + JSON\n\u002Fgraphify \u003Cpath> --html                               # (HTML is generated by default - this flag is a no-op)\n\u002Fgraphify \u003Cpath> --svg                                # also export graph.svg (embeds in Notion, GitHub)\n\u002Fgraphify \u003Cpath> --graphml                            # export graph.graphml (Gephi, yEd)\n\u002Fgraphify \u003Cpath> --neo4j                              # generate graphify-out\u002Fcypher.txt for Neo4j\n\u002Fgraphify \u003Cpath> --neo4j-push bolt:\u002F\u002Flocalhost:7687   # push directly to Neo4j\n\u002Fgraphify \u003Cpath> --mcp                                # start MCP stdio server for agent access\n\u002Fgraphify \u003Cpath> --watch                              # watch folder, auto-rebuild on code changes (no LLM needed)\n\u002Fgraphify \u003Cpath> --wiki                               # build agent-crawlable wiki (index.md + one article per community)\n\u002Fgraphify \u003Cpath> --obsidian --obsidian-dir ~\u002Fvaults\u002Fmy-project  # write vault to custom path (e.g. existing vault)\n\u002Fgraphify add \u003Curl>                                   # fetch URL, save to .\u002Fraw, update graph\n\u002Fgraphify add \u003Curl> --author \"Name\"                   # tag who wrote it\n\u002Fgraphify add \u003Curl> --contributor \"Name\"              # tag who added it to the corpus\n\u002Fgraphify query \"\u003Cquestion>\"                          # BFS traversal - broad context\n\u002Fgraphify query \"\u003Cquestion>\" --dfs                    # DFS - trace a specific path\n\u002Fgraphify query \"\u003Cquestion>\" --budget 1500            # cap answer at N tokens\n\u002Fgraphify path \"AuthModule\" \"Database\"                # shortest path between two concepts\n\u002Fgraphify explain \"SwinTransformer\"                   # plain-language explanation of a node\n```\n\n## What graphify is for\n\nDrop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED\u002FINFERRED\u002FAMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.\n\n## What You Must Do When Invoked\n\nIf the user invoked `\u002Fgraphify --help` or `\u002Fgraphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.\n\nIf no path was given, use `.` (current directory). Do not ask the user for a path.\n\nIf the path argument starts with `https:\u002F\u002Fgithub.com\u002F` or `http:\u002F\u002Fgithub.com\u002F`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.\n\nFollow these steps in order. Do not skip steps.\n\n### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)\n\n**Single repo:**\n```bash\nLOCAL_PATH=$(graphify clone \u003Cgithub-url> [--branch \u003Cbranch>])\n# Use LOCAL_PATH as the target for all subsequent steps\n```\n\n**Multiple repos (cross-repo graph):**\n```bash\n# Clone each repo, run the full pipeline on each, then merge\ngraphify clone \u003Curl1>   # → ~\u002F.graphify\u002Frepos\u002F\u003Cowner1>\u002F\u003Crepo1>\ngraphify clone \u003Curl2>   # → ~\u002F.graphify\u002Frepos\u002F\u003Cowner2>\u002F\u003Crepo2>\n# Run \u002Fgraphify on each local path to produce their graph.json files\n# Then merge:\ngraphify merge-graphs \\\n  ~\u002F.graphify\u002Frepos\u002F\u003Cowner1>\u002F\u003Crepo1>\u002Fgraphify-out\u002Fgraph.json \\\n  ~\u002F.graphify\u002Frepos\u002F\u003Cowner2>\u002F\u003Crepo2>\u002Fgraphify-out\u002Fgraph.json \\\n  --out graphify-out\u002Fcross-repo-graph.json\n```\n\nGraphify clones into `~\u002F.graphify\u002Frepos\u002F\u003Cowner>\u002F\u003Crepo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.\n\n### Step 1 - Ensure graphify is installed\n\n```bash\n# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)\nPYTHON=\"\"\nGRAPHIFY_BIN=$(which graphify 2>\u002Fdev\u002Fnull)\n# 1. uv tool installs — most reliable on modern Mac\u002FLinux\nif [ -z \"$PYTHON\" ] && command -v uv >\u002Fdev\u002Fnull 2>&1; then\n    _UV_PY=$(uv tool run graphifyy python -c \"import sys; print(sys.executable)\" 2>\u002Fdev\u002Fnull)\n    if [ -n \"$_UV_PY\" ]; then PYTHON=\"$_UV_PY\"; fi\nfi\n# 2. Read shebang from graphify binary (pipx and direct pip installs)\nif [ -z \"$PYTHON\" ] && [ -n \"$GRAPHIFY_BIN\" ]; then\n    _SHEBANG=$(head -1 \"$GRAPHIFY_BIN\" | tr -d '#!')\n    case \"$_SHEBANG\" in\n        *[!a-zA-Z0-9\u002F_.-]*) ;;\n        *) \"$_SHEBANG\" -c \"import graphify\" 2>\u002Fdev\u002Fnull && PYTHON=\"$_SHEBANG\" ;;\n    esac\nfi\n# 3. Fall back to python3\nif [ -z \"$PYTHON\" ]; then PYTHON=\"python3\"; fi\n\"$PYTHON\" -c \"import graphify\" 2>\u002Fdev\u002Fnull || \"$PYTHON\" -m pip install graphifyy -q 2>\u002Fdev\u002Fnull || \"$PYTHON\" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3\n# Write interpreter path for all subsequent steps (persists across invocations)\nmkdir -p graphify-out\n\"$PYTHON\" -c \"import sys; open('graphify-out\u002F.graphify_python', 'w').write(sys.executable)\"\n# Save scan root so `graphify update` (no args) knows where to look next time\necho \"$(cd INPUT_PATH && pwd)\" > graphify-out\u002F.graphify_root\n```\n\nIf the import succeeds, print nothing and move straight to Step 2.\n\n**In every subsequent bash block, replace `python3` with `$(cat graphify-out\u002F.graphify_python)` to use the correct interpreter.**\n\n### Step 2 - Detect files\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.detect import detect\nfrom pathlib import Path\nresult = detect(Path('INPUT_PATH'))\nprint(json.dumps(result))\n\" > graphify-out\u002F.graphify_detect.json\n```\n\nReplace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:\n\n```\nCorpus: X files · ~Y words\n  code:     N files (.py .ts .go ...)\n  docs:     N files (.md .txt ...)\n  papers:   N files (.pdf ...)\n  images:   N files\n  video:    N files (.mp4 .mp3 ...)\n```\n\nOmit any category with 0 files from the summary.\n\nThen act on it:\n- If `total_files` is 0: stop with \"No supported files found in [path].\"\n- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.\n- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.\n- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.\n\n### Step 2.5 - Transcribe video \u002F audio files (only if video files detected)\n\nSkip this step entirely if `detect` returned zero `video` files.\n\nVideo and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.\n\n**Strategy:** Read the god nodes from `graphify-out\u002F.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.\n\n**However**, if the corpus has *only* video files and no other docs\u002Fcode, use the generic fallback prompt: `\"Use proper punctuation and paragraph breaks.\"`\n\n**Step 1 - Write the Whisper prompt yourself.**\n\nRead the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:\n\n- Labels: `transformer, attention, encoder, decoder` → `\"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks.\"`\n- Labels: `kubernetes, deployment, pod, helm` → `\"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks.\"`\n\nSet it as `WHISPER_PROMPT` to use in the next command.\n\n**Step 2 - Transcribe:**\n\n```bash\nGRAPHIFY_WHISPER_MODEL=base  # or whatever --whisper-model the user passed\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json, os\nfrom pathlib import Path\nfrom graphify.transcribe import transcribe_all\n\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nvideo_files = detect.get('files', {}).get('video', [])\nprompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')\n\ntranscript_paths = transcribe_all(video_files, initial_prompt=prompt)\nprint(json.dumps(transcript_paths))\n\" > graphify-out\u002F.graphify_transcripts.json\n```\n\nAfter transcription:\n- Read the transcript paths from `graphify-out\u002F.graphify_transcripts.json`\n- Add them to the docs list before dispatching semantic subagents in Step 3B\n- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`\n- If transcription fails for a file, print a warning and continue with the rest\n\n**Whisper model:** Default is `base`. If the user passed `--whisper-model \u003Cname>`, set `GRAPHIFY_WHISPER_MODEL=\u003Cname>` in the environment before running the command above.\n\n### Step 3 - Extract entities and relationships\n\n**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.\n\nThis step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).\n\n**Before dispatching subagents:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:\n> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).\n\nPrint it once, then continue. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend=\"gemini\")` for semantic extraction instead of dispatching Claude subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.\n\n**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**\n\nNote: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs\u002Fpapers.\n\n#### Part A - Structural extraction for code files\n\nFor any code files detected, run AST extraction in parallel with Part B subagents:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.extract import collect_files, extract\nfrom pathlib import Path\nimport json\n\ncode_files = []\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nfor f in detect.get('files', {}).get('code', []):\n    code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])\n\nif code_files:\n    result = extract(code_files, cache_root=Path('.'))\n    Path('graphify-out\u002F.graphify_ast.json').write_text(json.dumps(result, indent=2))\n    print(f'AST: {len(result[\\\"nodes\\\"])} nodes, {len(result[\\\"edges\\\"])} edges')\nelse:\n    Path('graphify-out\u002F.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))\n    print('No code files - skipping AST extraction')\n\"\n```\n\n#### Part B - Semantic extraction (parallel subagents)\n\n**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.\n\n**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**\n\nBefore dispatching subagents, print a timing estimate:\n- Load `total_words` and file counts from `graphify-out\u002F.graphify_detect.json`\n- Estimate agents needed: `ceil(uncached_non_code_files \u002F 22)` (chunk size is 20-25)\n- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents\u002Fparallel_limit))\n- Print: \"Semantic extraction: ~N files → X agents, estimated ~Ys\"\n\n**Step B0 - Check extraction cache first**\n\nBefore dispatching any subagents, check which files already have cached extraction results:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.cache import check_semantic_cache\nfrom pathlib import Path\n\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nall_files = [f for files in detect['files'].values() for f in files]\n\ncached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)\n\nif cached_nodes or cached_edges or cached_hyperedges:\n    Path('graphify-out\u002F.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))\nPath('graphify-out\u002F.graphify_uncached.txt').write_text('\\n'.join(uncached))\nprint(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')\n\"\n```\n\nOnly dispatch subagents for files listed in `graphify-out\u002F.graphify_uncached.txt`. If all files are cached, skip to Part C directly.\n\n**Step B1 - Split into chunks**\n\nLoad files from `graphify-out\u002F.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.\n\n**Step B2 - Dispatch ALL subagents in a single message**\n\nCall the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.\n\n**IMPORTANT - subagent type:** Always use `subagent_type=\"general-purpose\"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.\n\nConcrete example for 3 chunks:\n```\n[Agent tool call 1: files 1-15, subagent_type=\"general-purpose\"]\n[Agent tool call 2: files 16-30, subagent_type=\"general-purpose\"]\n[Agent tool call 3: files 31-45, subagent_type=\"general-purpose\"]\n```\nAll three in one message. Not three separate messages.\n\nEach subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).\n\nCHUNK_PATH must be an **absolute** path — derive it before dispatching:\n```bash\nPROJECT_ROOT=$(cat graphify-out\u002F.graphify_root)\n# Then for chunk N: CHUNK_PATH=\"${PROJECT_ROOT}\u002Fgraphify-out\u002F.graphify_chunk_0N.json\"\n```\n\nSubagent prompt template:\n\n```\nYou are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.\nOutput ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.\n\nFiles (chunk CHUNK_NUM of TOTAL_CHUNKS):\nFILE_LIST\n\nRules:\n- EXTRACTED: relationship explicit in source (import, call, citation, \"see §3.2\")\n- INFERRED: reasonable inference (shared data structure, implied dependency)\n- AMBIGUOUS: uncertain - flag for review, do not omit\n\nCode files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).\n  Do not re-extract imports - AST already has those.\nDoc\u002Fpaper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:\"rationale\"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.\nCode files: when adding `calls` edges, source MUST be the caller (the function\u002Fclass doing the calling), target MUST be the callee. Never reverse this direction.\nImage files: use vision to understand what the image IS - do not just OCR.\n  UI screenshot: layout patterns, design decisions, key elements, purpose.\n  Chart: metric, trend\u002Finsight, data source.\n  Tweet\u002Fpost: claim as node, author, concepts mentioned.\n  Diagram: components and connections.\n  Research figure: what it demonstrates, method, result.\n  Handwritten\u002Fwhiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.\n\nDEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,\n  shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.\n\nSemantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:\n- Two functions that both validate user input but never call each other\n- A class in code and a concept in a paper that describe the same algorithm\n- Two error types that handle the same failure mode differently\nOnly add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.\n\nHyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:\n- All classes that implement a common protocol or interface\n- All functions in an authentication flow (even if they don't all call each other)\n- All concepts from a paper section that form one coherent idea\nUse sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.\n\nIf a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,\n  contributor onto every node from that file.\n\nconfidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:\n- EXTRACTED edges: confidence_score = 1.0 always\n- INFERRED edges: pick exactly ONE value from this set — never 0.5:\n    0.95  direct structural evidence (shared data structure, named cross-file reference).\n    0.85  strong inference (clear functional alignment, no direct symbol link).\n    0.75  reasonable inference (shared problem domain + similar shape, requires interpretation).\n    0.65  weak inference (thematically related, no shape evidence).\n    0.55  speculative but plausible (surface-level co-occurrence only).\n  Models follow discrete rubrics better than continuous ranges; the bimodal\n  distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the\n  range guidance is being collapsed to a binary. If no value above fits, mark\n  the edge AMBIGUOUS rather than picking 0.4 or below.\n- AMBIGUOUS edges: 0.1-0.3\n\nNode 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\u002Fauth\u002Fsession.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.\n\nGenerate the extraction JSON matching this schema exactly:\n{\"nodes\":[{\"id\":\"session_validatetoken\",\"label\":\"Human Readable Name\",\"file_type\":\"code|document|paper|image|rationale\",\"source_file\":\"relative\u002Fpath\",\"source_location\":null,\"source_url\":null,\"captured_at\":null,\"author\":null,\"contributor\":null}],\"edges\":[{\"source\":\"node_id\",\"target\":\"node_id\",\"relation\":\"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for\",\"confidence\":\"EXTRACTED|INFERRED|AMBIGUOUS\",\"confidence_score\":1.0,\"source_file\":\"relative\u002Fpath\",\"source_location\":null,\"weight\":1.0}],\"hyperedges\":[{\"id\":\"snake_case_id\",\"label\":\"Human Readable Label\",\"nodes\":[\"node_id1\",\"node_id2\",\"node_id3\"],\"relation\":\"participate_in|implement|form\",\"confidence\":\"EXTRACTED|INFERRED\",\"confidence_score\":0.75,\"source_file\":\"relative\u002Fpath\"}],\"input_tokens\":0,\"output_tokens\":0}\n\nThen write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):\nCHUNK_PATH\n```\n\n**Step B3 - Collect, cache, and merge**\n\nWait for all subagents. For each result:\n- Check that `graphify-out\u002F.graphify_chunk_NN.json` exists on disk — this is the success signal\n- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache\n- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: \"chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent.\" Do not silently skip.\n- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort\n\nIf more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type=\"general-purpose\"` is used.\n\nMerge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json, glob\nfrom pathlib import Path\n\nchunks = sorted(glob.glob('graphify-out\u002F.graphify_chunk_*.json'))\nall_nodes, all_edges, all_hyperedges = [], [], []\ntotal_in, total_out = 0, 0\nfor c in chunks:\n    d = json.loads(Path(c).read_text())\n    all_nodes += d.get('nodes', [])\n    all_edges += d.get('edges', [])\n    all_hyperedges += d.get('hyperedges', [])\n    total_in += d.get('input_tokens', 0)\n    total_out += d.get('output_tokens', 0)\nPath('graphify-out\u002F.graphify_semantic_new.json').write_text(json.dumps({\n    'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,\n    'input_tokens': total_in, 'output_tokens': total_out,\n}, indent=2))\nprint(f'Merged {len(chunks)} chunks: {total_in:,} in \u002F {total_out:,} out tokens')\n\"\n```\n\nSave new results to cache:\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.cache import save_semantic_cache\nfrom pathlib import Path\n\nnew = json.loads(Path('graphify-out\u002F.graphify_semantic_new.json').read_text()) if Path('graphify-out\u002F.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}\nsaved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))\nprint(f'Cached {saved} files')\n\"\n```\n\nMerge cached + new results into `graphify-out\u002F.graphify_semantic.json`:\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\n\ncached = json.loads(Path('graphify-out\u002F.graphify_cached.json').read_text()) if Path('graphify-out\u002F.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}\nnew = json.loads(Path('graphify-out\u002F.graphify_semantic_new.json').read_text()) if Path('graphify-out\u002F.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}\n\nall_nodes = cached['nodes'] + new.get('nodes', [])\nall_edges = cached['edges'] + new.get('edges', [])\nall_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])\nseen = set()\ndeduped = []\nfor n in all_nodes:\n    if n['id'] not in seen:\n        seen.add(n['id'])\n        deduped.append(n)\n\nmerged = {\n    'nodes': deduped,\n    'edges': all_edges,\n    'hyperedges': all_hyperedges,\n    'input_tokens': new.get('input_tokens', 0),\n    'output_tokens': new.get('output_tokens', 0),\n}\nPath('graphify-out\u002F.graphify_semantic.json').write_text(json.dumps(merged, indent=2))\nprint(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\\\"nodes\\\"])} from cache, {len(new.get(\\\"nodes\\\",[]))} new)')\n\"\n```\nClean up temp files: `rm -f graphify-out\u002F.graphify_cached.json graphify-out\u002F.graphify_uncached.txt graphify-out\u002F.graphify_semantic_new.json`\n\n#### Part C - Merge AST + semantic into final extraction\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom pathlib import Path\n\nast = json.loads(Path('graphify-out\u002F.graphify_ast.json').read_text())\nsem = json.loads(Path('graphify-out\u002F.graphify_semantic.json').read_text())\n\n# Merge: AST nodes first, semantic nodes deduplicated by id\nseen = {n['id'] for n in ast['nodes']}\nmerged_nodes = list(ast['nodes'])\nfor n in sem['nodes']:\n    if n['id'] not in seen:\n        merged_nodes.append(n)\n        seen.add(n['id'])\n\nmerged_edges = ast['edges'] + sem['edges']\nmerged_hyperedges = sem.get('hyperedges', [])\nmerged = {\n    'nodes': merged_nodes,\n    'edges': merged_edges,\n    'hyperedges': merged_hyperedges,\n    'input_tokens': sem.get('input_tokens', 0),\n    'output_tokens': sem.get('output_tokens', 0),\n}\nPath('graphify-out\u002F.graphify_extract.json').write_text(json.dumps(merged, indent=2))\ntotal = len(merged_nodes)\nedges = len(merged_edges)\nprint(f'Merged: {total} nodes, {edges} edges ({len(ast[\\\"nodes\\\"])} AST + {len(sem[\\\"nodes\\\"])} semantic)')\n\"\n```\n\n### Step 4 - Build graph, cluster, analyze, generate outputs\n\n**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`.\n\n```bash\nmkdir -p graphify-out\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.build import build_from_json\nfrom graphify.cluster import cluster, score_all\nfrom graphify.analyze import god_nodes, surprising_connections, suggest_questions\nfrom graphify.report import generate\nfrom graphify.export import to_json\nfrom pathlib import Path\n\nextraction = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\ndetection  = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\n\nG = build_from_json(extraction)\ncommunities = cluster(G)\ncohesion = score_all(G, communities)\ntokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}\ngods = god_nodes(G)\nsurprises = surprising_connections(G, communities)\nlabels = {cid: 'Community ' + str(cid) for cid in communities}\n# Placeholder questions - regenerated with real labels in Step 5\nquestions = suggest_questions(G, communities, labels)\n\nreport = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)\nPath('graphify-out\u002FGRAPH_REPORT.md').write_text(report)\nto_json(G, communities, 'graphify-out\u002Fgraph.json')\n\nanalysis = {\n    'communities': {str(k): v for k, v in communities.items()},\n    'cohesion': {str(k): v for k, v in cohesion.items()},\n    'gods': gods,\n    'surprises': surprises,\n    'questions': questions,\n}\nPath('graphify-out\u002F.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))\nif G.number_of_nodes() == 0:\n    print('ERROR: Graph is empty - extraction produced no nodes.')\n    print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')\n    raise SystemExit(1)\nprint(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')\n\"\n```\n\nIf this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.\n\nReplace INPUT_PATH with the actual path.\n\n### Step 5 - Label communities\n\nRead `graphify-out\u002F.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. \"Attention Mechanism\", \"Training Pipeline\", \"Data Loading\").\n\nThen regenerate the report and save the labels for the visualizer:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.build import build_from_json\nfrom graphify.cluster import score_all\nfrom graphify.analyze import god_nodes, surprising_connections, suggest_questions\nfrom graphify.report import generate\nfrom pathlib import Path\n\nextraction = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\ndetection  = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nanalysis   = json.loads(Path('graphify-out\u002F.graphify_analysis.json').read_text())\n\nG = build_from_json(extraction)\ncommunities = {int(k): v for k, v in analysis['communities'].items()}\ncohesion = {int(k): v for k, v in analysis['cohesion'].items()}\ntokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}\n\n# LABELS - replace these with the names you chose above\nlabels = LABELS_DICT\n\n# Regenerate questions with real community labels (labels affect question phrasing)\nquestions = suggest_questions(G, communities, labels)\n\nreport = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)\nPath('graphify-out\u002FGRAPH_REPORT.md').write_text(report)\nPath('graphify-out\u002F.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))\nprint('Report updated with community labels')\n\"\n```\n\nReplace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: \"Attention Mechanism\", 1: \"Training Pipeline\"}`).\nReplace INPUT_PATH with the actual path.\n\n### Step 6 - Generate Obsidian vault (opt-in) + HTML\n\n**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.\n\nIf `--obsidian` was given:\n\n- If `--obsidian-dir \u003Cpath>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out\u002Fobsidian`.\n\n```bash\ngraphify export obsidian\n# or with custom dir: graphify export obsidian --dir ~\u002Fvaults\u002Fmy-project\n```\n\nGenerate the HTML graph (always, unless `--no-viz`):\n\n```bash\ngraphify export html  # auto-aggregates to community view if graph > 5000 nodes\n# or: graphify export html --no-viz\n```\n\n### Step 6b - Wiki (only if --wiki flag)\n\n**Only run this step if `--wiki` was explicitly given in the original command.**\n\nRun this before Step 9 (cleanup) so `.graphify_labels.json` is still available.\n\n```bash\ngraphify export wiki\n```\n\n### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)\n\n**If `--neo4j`** - generate a Cypher file for manual import:\n\n```bash\ngraphify export neo4j\n```\n\n**If `--neo4j-push \u003Curi>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:\n\n```bash\ngraphify export neo4j --push bolt:\u002F\u002Flocalhost:7687 --user neo4j --password PASSWORD\n```\n\nDefault URI is `bolt:\u002F\u002Flocalhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.\n\n### Step 7b - SVG export (only if --svg flag)\n\n```bash\ngraphify export svg\n```\n\n### Step 7c - GraphML export (only if --graphml flag)\n\n```bash\ngraphify export graphml\n```\n\n### Step 7d - MCP server (only if --mcp flag)\n\n```bash\npython3 -m graphify.serve graphify-out\u002Fgraph.json\n```\n\nThis starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.\n\nTo configure in Claude Desktop, add to `claude_desktop_config.json`:\n```json\n{\n  \"mcpServers\": {\n    \"graphify\": {\n      \"command\": \"python3\",\n      \"args\": [\"-m\", \"graphify.serve\", \"\u002Fabsolute\u002Fpath\u002Fto\u002Fgraphify-out\u002Fgraph.json\"]\n    }\n  }\n}\n```\n\n### Step 8 - Token reduction benchmark (only if total_words > 5000)\n\nIf `total_words` from `graphify-out\u002F.graphify_detect.json` is greater than 5,000, run:\n\n```bash\ngraphify benchmark\n```\n\nPrint the output directly in chat. If `total_words \u003C= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.\n\n---\n\n### Step 9 - Save manifest, update cost tracker, clean up, and report\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\nfrom datetime import datetime, timezone\nfrom graphify.detect import save_manifest\n\n# Save manifest for --update\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nsave_manifest(detect['files'])\n\n# Update cumulative cost tracker\nextract = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\ninput_tok = extract.get('input_tokens', 0)\noutput_tok = extract.get('output_tokens', 0)\n\ncost_path = Path('graphify-out\u002Fcost.json')\nif cost_path.exists():\n    cost = json.loads(cost_path.read_text())\nelse:\n    cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}\n\ncost['runs'].append({\n    'date': datetime.now(timezone.utc).isoformat(),\n    'input_tokens': input_tok,\n    'output_tokens': output_tok,\n    'files': detect.get('total_files', 0),\n})\ncost['total_input_tokens'] += input_tok\ncost['total_output_tokens'] += output_tok\ncost_path.write_text(json.dumps(cost, indent=2))\n\nprint(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')\nprint(f'All time: {cost[\\\"total_input_tokens\\\"]:,} input, {cost[\\\"total_output_tokens\\\"]:,} output ({len(cost[\\\"runs\\\"])} runs)')\n\"\nrm -f graphify-out\u002F.graphify_detect.json graphify-out\u002F.graphify_extract.json graphify-out\u002F.graphify_ast.json graphify-out\u002F.graphify_semantic.json graphify-out\u002F.graphify_analysis.json graphify-out\u002F.graphify_chunk_*.json\nrm -f graphify-out\u002F.needs_update 2>\u002Fdev\u002Fnull || true\n```\n\nTell the user (omit the obsidian line unless --obsidian was given):\n```\nGraph complete. Outputs in PATH_TO_DIR\u002Fgraphify-out\u002F\n\n  graph.html            - interactive graph, open in browser\n  GRAPH_REPORT.md       - audit report\n  graph.json            - raw graph data\n  obsidian\u002F             - Obsidian vault (only if --obsidian was given)\n```\n\nIf graphify saved you time, consider supporting it: https:\u002F\u002Fgithub.com\u002Fsponsors\u002Fsafishamsi\n\nReplace PATH_TO_DIR with the actual absolute path of the directory that was processed.\n\nThen paste these sections from GRAPH_REPORT.md directly into the chat:\n- God Nodes\n- Surprising Connections\n- Suggested Questions\n\nDo NOT paste the full report - just those three sections. Keep it concise.\n\nThen immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:\n\n> \"The most interesting question this graph can answer: **[question]**. Want me to trace it?\"\n\nIf the user says yes, run `\u002Fgraphify query \"[question]\"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up (\"this connects to X - want to go deeper?\") so the session feels like navigation, not a one-shot report.\n\nThe graph is the map. Your job after the pipeline is to be the guide.\n\n---\n\n## Interpreter guard for subcommands\n\nBefore running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out\u002F`), re-resolve the interpreter first:\n\n```bash\nif [ ! -f graphify-out\u002F.graphify_python ]; then\n    GRAPHIFY_BIN=$(which graphify 2>\u002Fdev\u002Fnull)\n    if [ -n \"$GRAPHIFY_BIN\" ]; then\n        PYTHON=$(head -1 \"$GRAPHIFY_BIN\" | tr -d '#!')\n        case \"$PYTHON\" in *[!a-zA-Z0-9\u002F_.-]*) PYTHON=\"python3\" ;; esac\n    else\n        PYTHON=\"python3\"\n    fi\n    mkdir -p graphify-out\n    \"$PYTHON\" -c \"import sys; open('graphify-out\u002F.graphify_python', 'w').write(sys.executable)\"\nfi\n```\n\n## For --update (incremental re-extraction)\n\nUse when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.detect import detect_incremental, save_manifest\nfrom pathlib import Path\n\nresult = detect_incremental(Path('INPUT_PATH'))\nnew_total = result.get('new_total', 0)\nprint(json.dumps(result, indent=2))\nPath('graphify-out\u002F.graphify_incremental.json').write_text(json.dumps(result))\nif new_total == 0:\n    print('No files changed since last run. Nothing to update.')\n    raise SystemExit(0)\nprint(f'{new_total} new\u002Fchanged file(s) to re-extract.')\n\"\n```\n\nIf new files exist, first check whether all changed files are code files:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\n\nresult = json.loads(open('graphify-out\u002F.graphify_incremental.json').read()) if Path('graphify-out\u002F.graphify_incremental.json').exists() else {}\ncode_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}\nnew_files = result.get('new_files', {})\nall_changed = [f for files in new_files.values() for f in files]\ncode_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)\nprint('code_only:', code_only)\n\"\n```\n\nIf `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.\n\nIf `code_only` is False (any changed file is a doc\u002Fpaper\u002Fimage): run the full Steps 3A–3C pipeline as normal.\n\nThen:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\nfrom graphify.build import build_merge\nfrom graphify.detect import save_manifest\n\n# Load new extraction and incremental state\nnew_extraction = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\nincremental = json.loads(Path('graphify-out\u002F.graphify_incremental.json').read_text())\ndeleted = list(incremental.get('deleted_files', []))\n\n# Use build_merge() — reads graph.json directly without NetworkX round-trip\n# so edge direction (calls, implements, imports) is always preserved (#801).\nG = build_merge(\n    [new_extraction],\n    graph_path='graphify-out\u002Fgraph.json',\n    prune_sources=deleted or None,\n)\nprint(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')\n\n# Write merged result back to .graphify_extract.json so Step 4 sees the full graph\nmerged_out = {\n    'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],\n    'edges': [\n        # Explicit source\u002Ftarget last so they win over any stale attrs in d.\n        {**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},\n         'source': d.get('_src', u), 'target': d.get('_tgt', v)}\n        for u, v, d in G.edges(data=True)\n    ],\n    # G.graph[\"hyperedges\"] holds hyperedges from both existing graph.json\n    # and new_extraction (build_merge combines them). Falling back to\n    # new_extraction only would silently drop prior-run hyperedges (#801).\n    'hyperedges': list(G.graph.get('hyperedges', [])),\n    'input_tokens': new_extraction.get('input_tokens', 0),\n    'output_tokens': new_extraction.get('output_tokens', 0),\n}\nPath('graphify-out\u002F.graphify_extract.json').write_text(json.dumps(merged_out))\nprint(f'[graphify update] Merged extraction written ({len(merged_out[\\\"nodes\\\"])} nodes, {len(merged_out[\\\"edges\\\"])} edges)')\n\n# Save manifest so next --update diffs against today's state, not the\n# prior run's baseline (prevents ghost-node reports on subsequent updates).\nsave_manifest(incremental['files'])\nprint('[graphify update] Manifest saved.')\n\"\n```\n\nThen run Steps 4–8 on the merged graph as normal.\n\nAfter Step 4, show the graph diff:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.analyze import graph_diff\nfrom graphify.build import build_from_json\nfrom networkx.readwrite import json_graph\nimport networkx as nx\nfrom pathlib import Path\n\n# Load old graph (before update) from backup written before merge\nold_data = json.loads(Path('graphify-out\u002F.graphify_old.json').read_text()) if Path('graphify-out\u002F.graphify_old.json').exists() else None\nnew_extract = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\nG_new = build_from_json(new_extract)\n\nif old_data:\n    G_old = json_graph.node_link_graph(old_data, edges='links')\n    diff = graph_diff(G_old, G_new)\n    print(diff['summary'])\n    if diff['new_nodes']:\n        print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))\n    if diff['new_edges']:\n        print('New edges:', len(diff['new_edges']))\n\"\n```\n\nBefore the merge step, save the old graph: `cp graphify-out\u002Fgraph.json graphify-out\u002F.graphify_old.json`\nClean up after: `rm -f graphify-out\u002F.graphify_old.json`\n\n---\n\n## For --cluster-only\n\nSkip Steps 1–3. Re-run clustering on the existing graph:\n\n```bash\ngraphify cluster-only .\n```\n\nThen run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).\n\n---\n\n## For \u002Fgraphify query\n\nTwo traversal modes - choose based on the question:\n\n| Mode | Flag | Best for |\n|------|------|----------|\n| BFS (default) | _(none)_ | \"What is X connected to?\" - broad context, nearest neighbors first |\n| DFS | `--dfs` | \"How does X reach Y?\" - trace a specific chain or dependency path |\n\n```bash\ngraphify query \"QUESTION\"\n# or: graphify query \"QUESTION\" --dfs --budget 3000\n```\n\nReplace `QUESTION` with the user's actual question. Answer using **only** what the graph output contains. Quote `source_location` when citing a specific fact. If the graph lacks enough information, say so - do not hallucinate edges.\n\nAfter writing the answer, save it back into the graph so it improves future queries:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -m graphify save-result --question \"QUESTION\" --answer \"ANSWER\" --type query --nodes NODE1 NODE2\n```\n\nReplace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.\n\n---\n\n## For \u002Fgraphify path\n\nFind the shortest path between two named concepts in the graph.\n\n```bash\ngraphify path \"NODE_A\" \"NODE_B\"\n```\n\nReplace `NODE_A` and `NODE_B` with the actual concept names. Then explain the path in plain language - what each hop means, why it's significant.\n\nAfter writing the explanation, save it back:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -m graphify save-result --question \"Path from NODE_A to NODE_B\" --answer \"ANSWER\" --type path_query --nodes NODE_A NODE_B\n```\n\n---\n\n## For \u002Fgraphify explain\n\nGive a plain-language explanation of a single node - everything connected to it.\n\n```bash\ngraphify explain \"NODE_NAME\"\n```\n\nReplace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.\n\nAfter writing the explanation, save it back:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -m graphify save-result --question \"Explain NODE_NAME\" --answer \"ANSWER\" --type explain --nodes NODE_NAME\n```\n\n---\n\n## For \u002Fgraphify add\n\nFetch a URL and add it to the corpus, then update the graph.\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys\nfrom graphify.ingest import ingest\nfrom pathlib import Path\n\ntry:\n    out = ingest('URL', Path('.\u002Fraw'), author='AUTHOR', contributor='CONTRIBUTOR')\n    print(f'Saved to {out}')\nexcept ValueError as e:\n    print(f'error: {e}', file=sys.stderr)\n    sys.exit(1)\nexcept RuntimeError as e:\n    print(f'error: {e}', file=sys.stderr)\n    sys.exit(1)\n\"\n```\n\nReplace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `.\u002Fraw` to merge the new file into the existing graph.\n\nSupported URL types (auto-detected):\n- YouTube \u002F any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)\n- Twitter\u002FX → fetched via oEmbed, saved as `.md` with tweet text and author\n- arXiv → abstract + metadata saved as `.md`\n- PDF → downloaded as `.pdf`\n- Images (.png\u002F.jpg\u002F.webp) → downloaded, Claude vision extracts on next run\n- Any webpage → converted to markdown via html2text\n\n---\n\n## For --watch\n\nStart a background watcher that monitors a folder and auto-updates the graph when files change.\n\n```bash\npython3 -m graphify.watch INPUT_PATH --debounce 3\n```\n\nReplace INPUT_PATH with the folder to watch. Behavior depends on what changed:\n\n- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.\n- **Docs, papers, or images:** writes a `graphify-out\u002Fneeds_update` flag and prints a notification to run `\u002Fgraphify --update` (LLM semantic re-extraction required).\n\nDebounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.\n\nPress Ctrl+C to stop.\n\nFor agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `\u002Fgraphify --update` after those waves.\n\n---\n\n## For git commit hook\n\nInstall a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.\n\n```bash\ngraphify hook install    # install\ngraphify hook uninstall  # remove\ngraphify hook status     # check\n```\n\nAfter every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc\u002Fimage changes are ignored by the hook - run `\u002Fgraphify --update` manually for those.\n\nIf a post-commit hook already exists, graphify appends to it rather than replacing it.\n\n---\n\n## For native CLAUDE.md integration\n\nRun once per project to make graphify always-on in Claude Code sessions:\n\n```bash\ngraphify claude install\n```\n\nThis writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `\u002Fgraphify` needed in future sessions.\n\n```bash\ngraphify claude uninstall  # remove the section\n```\n\n---\n\n## Honesty Rules\n\n- Never invent an edge. If unsure, use AMBIGUOUS.\n- Never skip the corpus check warning.\n- Always show token cost in the report.\n- Never hide cohesion scores behind symbols - show the raw number.\n- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.\n","# \u002Fgraphify\n\nTurn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.\n\n## Usage\n\n```\n\u002Fgraphify                                             # full pipeline on current directory → Obsidian vault\n\u002Fgraphify \u003Cpath>                                      # full pipeline on specific path\n\u002Fgraphify https:\u002F\u002Fgithub.com\u002F\u003Cowner>\u002F\u003Crepo>           # clone repo then run full pipeline on it\n\u002Fgraphify https:\u002F\u002Fgithub.com\u002F\u003Cowner>\u002F\u003Crepo> --branch \u003Cbranch>  # clone a specific branch\n\u002Fgraphify \u003Curl1> \u003Curl2> ...                           # clone multiple repos, build each, merge into one cross-repo graph\n\u002Fgraphify \u003Cpath> --mode deep                          # thorough extraction, richer INFERRED edges\n\u002Fgraphify \u003Cpath> --update                             # incremental - re-extract only new\u002Fchanged files\n\u002Fgraphify \u003Cpath> --directed                            # build directed graph (preserves edge direction: source→target)\n\u002Fgraphify \u003Cpath> --whisper-model medium                # use a larger Whisper model for better transcription accuracy\n\u002Fgraphify \u003Cpath> --cluster-only                       # rerun clustering on existing graph\n\u002Fgraphify \u003Cpath> --no-viz                             # skip visualization, just report + JSON\n\u002Fgraphify \u003Cpath> --html                               # (HTML is generated by default - this flag is a no-op)\n\u002Fgraphify \u003Cpath> --svg                                # also export graph.svg (embeds in Notion, GitHub)\n\u002Fgraphify \u003Cpath> --graphml                            # export graph.graphml (Gephi, yEd)\n\u002Fgraphify \u003Cpath> --neo4j                              # generate graphify-out\u002Fcypher.txt for Neo4j\n\u002Fgraphify \u003Cpath> --neo4j-push bolt:\u002F\u002Flocalhost:7687   # push directly to Neo4j\n\u002Fgraphify \u003Cpath> --mcp                                # start MCP stdio server for agent access\n\u002Fgraphify \u003Cpath> --watch                              # watch folder, auto-rebuild on code changes (no LLM needed)\n\u002Fgraphify \u003Cpath> --wiki                               # build agent-crawlable wiki (index.md + one article per community)\n\u002Fgraphify \u003Cpath> --obsidian --obsidian-dir ~\u002Fvaults\u002Fmy-project  # write vault to custom path (e.g. existing vault)\n\u002Fgraphify add \u003Curl>                                   # fetch URL, save to .\u002Fraw, update graph\n\u002Fgraphify add \u003Curl> --author \"Name\"                   # tag who wrote it\n\u002Fgraphify add \u003Curl> --contributor \"Name\"              # tag who added it to the corpus\n\u002Fgraphify query \"\u003Cquestion>\"                          # BFS traversal - broad context\n\u002Fgraphify query \"\u003Cquestion>\" --dfs                    # DFS - trace a specific path\n\u002Fgraphify query \"\u003Cquestion>\" --budget 1500            # cap answer at N tokens\n\u002Fgraphify path \"AuthModule\" \"Database\"                # shortest path between two concepts\n\u002Fgraphify explain \"SwinTransformer\"                   # plain-language explanation of a node\n```\n\n## What graphify is for\n\nDrop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED\u002FINFERRED\u002FAMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.\n\n## What You Must Do When Invoked\n\nIf the user invoked `\u002Fgraphify --help` or `\u002Fgraphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.\n\nIf no path was given, use `.` (current directory). Do not ask the user for a path.\n\nIf the path argument starts with `https:\u002F\u002Fgithub.com\u002F` or `http:\u002F\u002Fgithub.com\u002F`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.\n\nFollow these steps in order. Do not skip steps.\n\n### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)\n\n**Single repo:**\n```bash\nLOCAL_PATH=$(graphify clone \u003Cgithub-url> [--branch \u003Cbranch>])\n# Use LOCAL_PATH as the target for all subsequent steps\n```\n\n**Multiple repos (cross-repo graph):**\n```bash\n# Clone each repo, run the full pipeline on each, then merge\ngraphify clone \u003Curl1>   # → ~\u002F.graphify\u002Frepos\u002F\u003Cowner1>\u002F\u003Crepo1>\ngraphify clone \u003Curl2>   # → ~\u002F.graphify\u002Frepos\u002F\u003Cowner2>\u002F\u003Crepo2>\n# Run \u002Fgraphify on each local path to produce their graph.json files\n# Then merge:\ngraphify merge-graphs \\\n  ~\u002F.graphify\u002Frepos\u002F\u003Cowner1>\u002F\u003Crepo1>\u002Fgraphify-out\u002Fgraph.json \\\n  ~\u002F.graphify\u002Frepos\u002F\u003Cowner2>\u002F\u003Crepo2>\u002Fgraphify-out\u002Fgraph.json \\\n  --out graphify-out\u002Fcross-repo-graph.json\n```\n\nGraphify clones into `~\u002F.graphify\u002Frepos\u002F\u003Cowner>\u002F\u003Crepo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.\n\n### Step 1 - Ensure graphify is installed\n\n```bash\n# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)\nPYTHON=\"\"\nGRAPHIFY_BIN=$(which graphify 2>\u002Fdev\u002Fnull)\n# 1. uv tool installs — most reliable on modern Mac\u002FLinux\nif [ -z \"$PYTHON\" ] && command -v uv >\u002Fdev\u002Fnull 2>&1; then\n    _UV_PY=$(uv tool run graphifyy python -c \"import sys; print(sys.executable)\" 2>\u002Fdev\u002Fnull)\n    if [ -n \"$_UV_PY\" ]; then PYTHON=\"$_UV_PY\"; fi\nfi\n# 2. Read shebang from graphify binary (pipx and direct pip installs)\nif [ -z \"$PYTHON\" ] && [ -n \"$GRAPHIFY_BIN\" ]; then\n    _SHEBANG=$(head -1 \"$GRAPHIFY_BIN\" | tr -d '#!')\n    case \"$_SHEBANG\" in\n        *[!a-zA-Z0-9\u002F_.-]*) ;;\n        *) \"$_SHEBANG\" -c \"import graphify\" 2>\u002Fdev\u002Fnull && PYTHON=\"$_SHEBANG\" ;;\n    esac\nfi\n# 3. Fall back to python3\nif [ -z \"$PYTHON\" ]; then PYTHON=\"python3\"; fi\n\"$PYTHON\" -c \"import graphify\" 2>\u002Fdev\u002Fnull || \"$PYTHON\" -m pip install graphifyy -q 2>\u002Fdev\u002Fnull || \"$PYTHON\" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3\n# Write interpreter path for all subsequent steps (persists across invocations)\nmkdir -p graphify-out\n\"$PYTHON\" -c \"import sys; open('graphify-out\u002F.graphify_python', 'w').write(sys.executable)\"\n# Save scan root so `graphify update` (no args) knows where to look next time\necho \"$(cd INPUT_PATH && pwd)\" > graphify-out\u002F.graphify_root\n```\n\nIf the import succeeds, print nothing and move straight to Step 2.\n\n**In every subsequent bash block, replace `python3` with `$(cat graphify-out\u002F.graphify_python)` to use the correct interpreter.**\n\n### Step 2 - Detect files\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.detect import detect\nfrom pathlib import Path\nresult = detect(Path('INPUT_PATH'))\nprint(json.dumps(result))\n\" > graphify-out\u002F.graphify_detect.json\n```\n\nReplace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:\n\n```\nCorpus: X files · ~Y words\n  code:     N files (.py .ts .go ...)\n  docs:     N files (.md .txt ...)\n  papers:   N files (.pdf ...)\n  images:   N files\n  video:    N files (.mp4 .mp3 ...)\n```\n\nOmit any category with 0 files from the summary.\n\nThen act on it:\n- If `total_files` is 0: stop with \"No supported files found in [path].\"\n- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.\n- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.\n- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.\n\n### Step 2.5 - Transcribe video \u002F audio files (only if video files detected)\n\nSkip this step entirely if `detect` returned zero `video` files.\n\nVideo and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.\n\n**Strategy:** Read the god nodes from `graphify-out\u002F.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.\n\n**However**, if the corpus has *only* video files and no other docs\u002Fcode, use the generic fallback prompt: `\"Use proper punctuation and paragraph breaks.\"`\n\n**Step 1 - Write the Whisper prompt yourself.**\n\nRead the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:\n\n- Labels: `transformer, attention, encoder, decoder` → `\"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks.\"`\n- Labels: `kubernetes, deployment, pod, helm` → `\"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks.\"`\n\nSet it as `WHISPER_PROMPT` to use in the next command.\n\n**Step 2 - Transcribe:**\n\n```bash\nGRAPHIFY_WHISPER_MODEL=base  # or whatever --whisper-model the user passed\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json, os\nfrom pathlib import Path\nfrom graphify.transcribe import transcribe_all\n\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nvideo_files = detect.get('files', {}).get('video', [])\nprompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')\n\ntranscript_paths = transcribe_all(video_files, initial_prompt=prompt)\nprint(json.dumps(transcript_paths))\n\" > graphify-out\u002F.graphify_transcripts.json\n```\n\nAfter transcription:\n- Read the transcript paths from `graphify-out\u002F.graphify_transcripts.json`\n- Add them to the docs list before dispatching semantic subagents in Step 3B\n- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`\n- If transcription fails for a file, print a warning and continue with the rest\n\n**Whisper model:** Default is `base`. If the user passed `--whisper-model \u003Cname>`, set `GRAPHIFY_WHISPER_MODEL=\u003Cname>` in the environment before running the command above.\n\n### Step 3 - Extract entities and relationships\n\n**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.\n\nThis step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).\n\n**Before dispatching subagents:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:\n> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).\n\nPrint it once, then continue. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend=\"gemini\")` for semantic extraction instead of dispatching Claude subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.\n\n**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**\n\nNote: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs\u002Fpapers.\n\n#### Part A - Structural extraction for code files\n\nFor any code files detected, run AST extraction in parallel with Part B subagents:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.extract import collect_files, extract\nfrom pathlib import Path\nimport json\n\ncode_files = []\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nfor f in detect.get('files', {}).get('code', []):\n    code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])\n\nif code_files:\n    result = extract(code_files, cache_root=Path('.'))\n    Path('graphify-out\u002F.graphify_ast.json').write_text(json.dumps(result, indent=2))\n    print(f'AST: {len(result[\\\"nodes\\\"])} nodes, {len(result[\\\"edges\\\"])} edges')\nelse:\n    Path('graphify-out\u002F.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))\n    print('No code files - skipping AST extraction')\n\"\n```\n\n#### Part B - Semantic extraction (parallel subagents)\n\n**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do.\n\n**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**\n\nBefore dispatching subagents, print a timing estimate:\n- Load `total_words` and file counts from `graphify-out\u002F.graphify_detect.json`\n- Estimate agents needed: `ceil(uncached_non_code_files \u002F 22)` (chunk size is 20-25)\n- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents\u002Fparallel_limit))\n- Print: \"Semantic extraction: ~N files → X agents, estimated ~Ys\"\n\n**Step B0 - Check extraction cache first**\n\nBefore dispatching any subagents, check which files already have cached extraction results:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.cache import check_semantic_cache\nfrom pathlib import Path\n\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nall_files = [f for files in detect['files'].values() for f in files]\n\ncached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)\n\nif cached_nodes or cached_edges or cached_hyperedges:\n    Path('graphify-out\u002F.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))\nPath('graphify-out\u002F.graphify_uncached.txt').write_text('\\n'.join(uncached))\nprint(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')\n\"\n```\n\nOnly dispatch subagents for files listed in `graphify-out\u002F.graphify_uncached.txt`. If all files are cached, skip to Part C directly.\n\n**Step B1 - Split into chunks**\n\nLoad files from `graphify-out\u002F.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.\n\n**Step B2 - Dispatch ALL subagents in a single message**\n\nCall the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.\n\n**IMPORTANT - subagent type:** Always use `subagent_type=\"general-purpose\"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.\n\nConcrete example for 3 chunks:\n```\n[Agent tool call 1: files 1-15, subagent_type=\"general-purpose\"]\n[Agent tool call 2: files 16-30, subagent_type=\"general-purpose\"]\n[Agent tool call 3: files 31-45, subagent_type=\"general-purpose\"]\n```\nAll three in one message. Not three separate messages.\n\nEach subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).\n\nCHUNK_PATH must be an **absolute** path — derive it before dispatching:\n```bash\nPROJECT_ROOT=$(cat graphify-out\u002F.graphify_root)\n# Then for chunk N: CHUNK_PATH=\"${PROJECT_ROOT}\u002Fgraphify-out\u002F.graphify_chunk_0N.json\"\n```\n\nSubagent prompt template:\n\n```\nYou are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.\nOutput ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.\n\nFiles (chunk CHUNK_NUM of TOTAL_CHUNKS):\nFILE_LIST\n\nRules:\n- EXTRACTED: relationship explicit in source (import, call, citation, \"see §3.2\")\n- INFERRED: reasonable inference (shared data structure, implied dependency)\n- AMBIGUOUS: uncertain - flag for review, do not omit\n\nCode files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).\n  Do not re-extract imports - AST already has those.\nDoc\u002Fpaper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:\"rationale\"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.\nCode files: when adding `calls` edges, source MUST be the caller (the function\u002Fclass doing the calling), target MUST be the callee. Never reverse this direction.\nImage files: use vision to understand what the image IS - do not just OCR.\n  UI screenshot: layout patterns, design decisions, key elements, purpose.\n  Chart: metric, trend\u002Finsight, data source.\n  Tweet\u002Fpost: claim as node, author, concepts mentioned.\n  Diagram: components and connections.\n  Research figure: what it demonstrates, method, result.\n  Handwritten\u002Fwhiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.\n\nDEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,\n  shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.\n\nSemantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:\n- Two functions that both validate user input but never call each other\n- A class in code and a concept in a paper that describe the same algorithm\n- Two error types that handle the same failure mode differently\nOnly add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.\n\nHyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:\n- All classes that implement a common protocol or interface\n- All functions in an authentication flow (even if they don't all call each other)\n- All concepts from a paper section that form one coherent idea\nUse sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.\n\nIf a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,\n  contributor onto every node from that file.\n\nconfidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:\n- EXTRACTED edges: confidence_score = 1.0 always\n- INFERRED edges: pick exactly ONE value from this set — never 0.5:\n    0.95  direct structural evidence (shared data structure, named cross-file reference).\n    0.85  strong inference (clear functional alignment, no direct symbol link).\n    0.75  reasonable inference (shared problem domain + similar shape, requires interpretation).\n    0.65  weak inference (thematically related, no shape evidence).\n    0.55  speculative but plausible (surface-level co-occurrence only).\n  Models follow discrete rubrics better than continuous ranges; the bimodal\n  distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the\n  range guidance is being collapsed to a binary. If no value above fits, mark\n  the edge AMBIGUOUS rather than picking 0.4 or below.\n- AMBIGUOUS edges: 0.1-0.3\n\nNode 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\u002Fauth\u002Fsession.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.\n\nGenerate the extraction JSON matching this schema exactly:\n{\"nodes\":[{\"id\":\"session_validatetoken\",\"label\":\"Human Readable Name\",\"file_type\":\"code|document|paper|image|rationale\",\"source_file\":\"relative\u002Fpath\",\"source_location\":null,\"source_url\":null,\"captured_at\":null,\"author\":null,\"contributor\":null}],\"edges\":[{\"source\":\"node_id\",\"target\":\"node_id\",\"relation\":\"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for\",\"confidence\":\"EXTRACTED|INFERRED|AMBIGUOUS\",\"confidence_score\":1.0,\"source_file\":\"relative\u002Fpath\",\"source_location\":null,\"weight\":1.0}],\"hyperedges\":[{\"id\":\"snake_case_id\",\"label\":\"Human Readable Label\",\"nodes\":[\"node_id1\",\"node_id2\",\"node_id3\"],\"relation\":\"participate_in|implement|form\",\"confidence\":\"EXTRACTED|INFERRED\",\"confidence_score\":0.75,\"source_file\":\"relative\u002Fpath\"}],\"input_tokens\":0,\"output_tokens\":0}\n\nThen write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):\nCHUNK_PATH\n```\n\n**Step B3 - Collect, cache, and merge**\n\nWait for all subagents. For each result:\n- Check that `graphify-out\u002F.graphify_chunk_NN.json` exists on disk — this is the success signal\n- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache\n- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: \"chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent.\" Do not silently skip.\n- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort\n\nIf more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type=\"general-purpose\"` is used.\n\nMerge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json, glob\nfrom pathlib import Path\n\nchunks = sorted(glob.glob('graphify-out\u002F.graphify_chunk_*.json'))\nall_nodes, all_edges, all_hyperedges = [], [], []\ntotal_in, total_out = 0, 0\nfor c in chunks:\n    d = json.loads(Path(c).read_text())\n    all_nodes += d.get('nodes', [])\n    all_edges += d.get('edges', [])\n    all_hyperedges += d.get('hyperedges', [])\n    total_in += d.get('input_tokens', 0)\n    total_out += d.get('output_tokens', 0)\nPath('graphify-out\u002F.graphify_semantic_new.json').write_text(json.dumps({\n    'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,\n    'input_tokens': total_in, 'output_tokens': total_out,\n}, indent=2))\nprint(f'Merged {len(chunks)} chunks: {total_in:,} in \u002F {total_out:,} out tokens')\n\"\n```\n\nSave new results to cache:\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.cache import save_semantic_cache\nfrom pathlib import Path\n\nnew = json.loads(Path('graphify-out\u002F.graphify_semantic_new.json').read_text()) if Path('graphify-out\u002F.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}\nsaved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))\nprint(f'Cached {saved} files')\n\"\n```\n\nMerge cached + new results into `graphify-out\u002F.graphify_semantic.json`:\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\n\ncached = json.loads(Path('graphify-out\u002F.graphify_cached.json').read_text()) if Path('graphify-out\u002F.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}\nnew = json.loads(Path('graphify-out\u002F.graphify_semantic_new.json').read_text()) if Path('graphify-out\u002F.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}\n\nall_nodes = cached['nodes'] + new.get('nodes', [])\nall_edges = cached['edges'] + new.get('edges', [])\nall_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])\nseen = set()\ndeduped = []\nfor n in all_nodes:\n    if n['id'] not in seen:\n        seen.add(n['id'])\n        deduped.append(n)\n\nmerged = {\n    'nodes': deduped,\n    'edges': all_edges,\n    'hyperedges': all_hyperedges,\n    'input_tokens': new.get('input_tokens', 0),\n    'output_tokens': new.get('output_tokens', 0),\n}\nPath('graphify-out\u002F.graphify_semantic.json').write_text(json.dumps(merged, indent=2))\nprint(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\\\"nodes\\\"])} from cache, {len(new.get(\\\"nodes\\\",[]))} new)')\n\"\n```\nClean up temp files: `rm -f graphify-out\u002F.graphify_cached.json graphify-out\u002F.graphify_uncached.txt graphify-out\u002F.graphify_semantic_new.json`\n\n#### Part C - Merge AST + semantic into final extraction\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom pathlib import Path\n\nast = json.loads(Path('graphify-out\u002F.graphify_ast.json').read_text())\nsem = json.loads(Path('graphify-out\u002F.graphify_semantic.json').read_text())\n\n# Merge: AST nodes first, semantic nodes deduplicated by id\nseen = {n['id'] for n in ast['nodes']}\nmerged_nodes = list(ast['nodes'])\nfor n in sem['nodes']:\n    if n['id'] not in seen:\n        merged_nodes.append(n)\n        seen.add(n['id'])\n\nmerged_edges = ast['edges'] + sem['edges']\nmerged_hyperedges = sem.get('hyperedges', [])\nmerged = {\n    'nodes': merged_nodes,\n    'edges': merged_edges,\n    'hyperedges': merged_hyperedges,\n    'input_tokens': sem.get('input_tokens', 0),\n    'output_tokens': sem.get('output_tokens', 0),\n}\nPath('graphify-out\u002F.graphify_extract.json').write_text(json.dumps(merged, indent=2))\ntotal = len(merged_nodes)\nedges = len(merged_edges)\nprint(f'Merged: {total} nodes, {edges} edges ({len(ast[\\\"nodes\\\"])} AST + {len(sem[\\\"nodes\\\"])} semantic)')\n\"\n```\n\n### Step 4 - Build graph, cluster, analyze, generate outputs\n\n**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`.\n\n```bash\nmkdir -p graphify-out\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.build import build_from_json\nfrom graphify.cluster import cluster, score_all\nfrom graphify.analyze import god_nodes, surprising_connections, suggest_questions\nfrom graphify.report import generate\nfrom graphify.export import to_json\nfrom pathlib import Path\n\nextraction = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\ndetection  = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\n\nG = build_from_json(extraction)\ncommunities = cluster(G)\ncohesion = score_all(G, communities)\ntokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}\ngods = god_nodes(G)\nsurprises = surprising_connections(G, communities)\nlabels = {cid: 'Community ' + str(cid) for cid in communities}\n# Placeholder questions - regenerated with real labels in Step 5\nquestions = suggest_questions(G, communities, labels)\n\nreport = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)\nPath('graphify-out\u002FGRAPH_REPORT.md').write_text(report)\nto_json(G, communities, 'graphify-out\u002Fgraph.json')\n\nanalysis = {\n    'communities': {str(k): v for k, v in communities.items()},\n    'cohesion': {str(k): v for k, v in cohesion.items()},\n    'gods': gods,\n    'surprises': surprises,\n    'questions': questions,\n}\nPath('graphify-out\u002F.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))\nif G.number_of_nodes() == 0:\n    print('ERROR: Graph is empty - extraction produced no nodes.')\n    print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')\n    raise SystemExit(1)\nprint(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')\n\"\n```\n\nIf this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.\n\nReplace INPUT_PATH with the actual path.\n\n### Step 5 - Label communities\n\nRead `graphify-out\u002F.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. \"Attention Mechanism\", \"Training Pipeline\", \"Data Loading\").\n\nThen regenerate the report and save the labels for the visualizer:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.build import build_from_json\nfrom graphify.cluster import score_all\nfrom graphify.analyze import god_nodes, surprising_connections, suggest_questions\nfrom graphify.report import generate\nfrom pathlib import Path\n\nextraction = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\ndetection  = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nanalysis   = json.loads(Path('graphify-out\u002F.graphify_analysis.json').read_text())\n\nG = build_from_json(extraction)\ncommunities = {int(k): v for k, v in analysis['communities'].items()}\ncohesion = {int(k): v for k, v in analysis['cohesion'].items()}\ntokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}\n\n# LABELS - replace these with the names you chose above\nlabels = LABELS_DICT\n\n# Regenerate questions with real community labels (labels affect question phrasing)\nquestions = suggest_questions(G, communities, labels)\n\nreport = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)\nPath('graphify-out\u002FGRAPH_REPORT.md').write_text(report)\nPath('graphify-out\u002F.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))\nprint('Report updated with community labels')\n\"\n```\n\nReplace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: \"Attention Mechanism\", 1: \"Training Pipeline\"}`).\nReplace INPUT_PATH with the actual path.\n\n### Step 6 - Generate Obsidian vault (opt-in) + HTML\n\n**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.\n\nIf `--obsidian` was given:\n\n- If `--obsidian-dir \u003Cpath>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out\u002Fobsidian`.\n\n```bash\ngraphify export obsidian\n# or with custom dir: graphify export obsidian --dir ~\u002Fvaults\u002Fmy-project\n```\n\nGenerate the HTML graph (always, unless `--no-viz`):\n\n```bash\ngraphify export html  # auto-aggregates to community view if graph > 5000 nodes\n# or: graphify export html --no-viz\n```\n\n### Step 6b - Wiki (only if --wiki flag)\n\n**Only run this step if `--wiki` was explicitly given in the original command.**\n\nRun this before Step 9 (cleanup) so `.graphify_labels.json` is still available.\n\n```bash\ngraphify export wiki\n```\n\n### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)\n\n**If `--neo4j`** - generate a Cypher file for manual import:\n\n```bash\ngraphify export neo4j\n```\n\n**If `--neo4j-push \u003Curi>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:\n\n```bash\ngraphify export neo4j --push bolt:\u002F\u002Flocalhost:7687 --user neo4j --password PASSWORD\n```\n\nDefault URI is `bolt:\u002F\u002Flocalhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates.\n\n### Step 7b - SVG export (only if --svg flag)\n\n```bash\ngraphify export svg\n```\n\n### Step 7c - GraphML export (only if --graphml flag)\n\n```bash\ngraphify export graphml\n```\n\n### Step 7d - MCP server (only if --mcp flag)\n\n```bash\npython3 -m graphify.serve graphify-out\u002Fgraph.json\n```\n\nThis starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.\n\nTo configure in Claude Desktop, add to `claude_desktop_config.json`:\n```json\n{\n  \"mcpServers\": {\n    \"graphify\": {\n      \"command\": \"python3\",\n      \"args\": [\"-m\", \"graphify.serve\", \"\u002Fabsolute\u002Fpath\u002Fto\u002Fgraphify-out\u002Fgraph.json\"]\n    }\n  }\n}\n```\n\n### Step 8 - Token reduction benchmark (only if total_words > 5000)\n\nIf `total_words` from `graphify-out\u002F.graphify_detect.json` is greater than 5,000, run:\n\n```bash\ngraphify benchmark\n```\n\nPrint the output directly in chat. If `total_words \u003C= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.\n\n---\n\n### Step 9 - Save manifest, update cost tracker, clean up, and report\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\nfrom datetime import datetime, timezone\nfrom graphify.detect import save_manifest\n\n# Save manifest for --update\ndetect = json.loads(Path('graphify-out\u002F.graphify_detect.json').read_text())\nsave_manifest(detect['files'])\n\n# Update cumulative cost tracker\nextract = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\ninput_tok = extract.get('input_tokens', 0)\noutput_tok = extract.get('output_tokens', 0)\n\ncost_path = Path('graphify-out\u002Fcost.json')\nif cost_path.exists():\n    cost = json.loads(cost_path.read_text())\nelse:\n    cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}\n\ncost['runs'].append({\n    'date': datetime.now(timezone.utc).isoformat(),\n    'input_tokens': input_tok,\n    'output_tokens': output_tok,\n    'files': detect.get('total_files', 0),\n})\ncost['total_input_tokens'] += input_tok\ncost['total_output_tokens'] += output_tok\ncost_path.write_text(json.dumps(cost, indent=2))\n\nprint(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')\nprint(f'All time: {cost[\\\"total_input_tokens\\\"]:,} input, {cost[\\\"total_output_tokens\\\"]:,} output ({len(cost[\\\"runs\\\"])} runs)')\n\"\nrm -f graphify-out\u002F.graphify_detect.json graphify-out\u002F.graphify_extract.json graphify-out\u002F.graphify_ast.json graphify-out\u002F.graphify_semantic.json graphify-out\u002F.graphify_analysis.json graphify-out\u002F.graphify_chunk_*.json\nrm -f graphify-out\u002F.needs_update 2>\u002Fdev\u002Fnull || true\n```\n\nTell the user (omit the obsidian line unless --obsidian was given):\n```\nGraph complete. Outputs in PATH_TO_DIR\u002Fgraphify-out\u002F\n\n  graph.html            - interactive graph, open in browser\n  GRAPH_REPORT.md       - audit report\n  graph.json            - raw graph data\n  obsidian\u002F             - Obsidian vault (only if --obsidian was given)\n```\n\nIf graphify saved you time, consider supporting it: https:\u002F\u002Fgithub.com\u002Fsponsors\u002Fsafishamsi\n\nReplace PATH_TO_DIR with the actual absolute path of the directory that was processed.\n\nThen paste these sections from GRAPH_REPORT.md directly into the chat:\n- God Nodes\n- Surprising Connections\n- Suggested Questions\n\nDo NOT paste the full report - just those three sections. Keep it concise.\n\nThen immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:\n\n> \"The most interesting question this graph can answer: **[question]**. Want me to trace it?\"\n\nIf the user says yes, run `\u002Fgraphify query \"[question]\"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up (\"this connects to X - want to go deeper?\") so the session feels like navigation, not a one-shot report.\n\nThe graph is the map. Your job after the pipeline is to be the guide.\n\n---\n\n## Interpreter guard for subcommands\n\nBefore running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out\u002F`), re-resolve the interpreter first:\n\n```bash\nif [ ! -f graphify-out\u002F.graphify_python ]; then\n    GRAPHIFY_BIN=$(which graphify 2>\u002Fdev\u002Fnull)\n    if [ -n \"$GRAPHIFY_BIN\" ]; then\n        PYTHON=$(head -1 \"$GRAPHIFY_BIN\" | tr -d '#!')\n        case \"$PYTHON\" in *[!a-zA-Z0-9\u002F_.-]*) PYTHON=\"python3\" ;; esac\n    else\n        PYTHON=\"python3\"\n    fi\n    mkdir -p graphify-out\n    \"$PYTHON\" -c \"import sys; open('graphify-out\u002F.graphify_python', 'w').write(sys.executable)\"\nfi\n```\n\n## For --update (incremental re-extraction)\n\nUse when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys, json\nfrom graphify.detect import detect_incremental, save_manifest\nfrom pathlib import Path\n\nresult = detect_incremental(Path('INPUT_PATH'))\nnew_total = result.get('new_total', 0)\nprint(json.dumps(result, indent=2))\nPath('graphify-out\u002F.graphify_incremental.json').write_text(json.dumps(result))\nif new_total == 0:\n    print('No files changed since last run. Nothing to update.')\n    raise SystemExit(0)\nprint(f'{new_total} new\u002Fchanged file(s) to re-extract.')\n\"\n```\n\nIf new files exist, first check whether all changed files are code files:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\n\nresult = json.loads(open('graphify-out\u002F.graphify_incremental.json').read()) if Path('graphify-out\u002F.graphify_incremental.json').exists() else {}\ncode_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}\nnew_files = result.get('new_files', {})\nall_changed = [f for files in new_files.values() for f in files]\ncode_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)\nprint('code_only:', code_only)\n\"\n```\n\nIf `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8.\n\nIf `code_only` is False (any changed file is a doc\u002Fpaper\u002Fimage): run the full Steps 3A–3C pipeline as normal.\n\nThen:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom pathlib import Path\nfrom graphify.build import build_merge\nfrom graphify.detect import save_manifest\n\n# Load new extraction and incremental state\nnew_extraction = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\nincremental = json.loads(Path('graphify-out\u002F.graphify_incremental.json').read_text())\ndeleted = list(incremental.get('deleted_files', []))\n\n# Use build_merge() — reads graph.json directly without NetworkX round-trip\n# so edge direction (calls, implements, imports) is always preserved (#801).\nG = build_merge(\n    [new_extraction],\n    graph_path='graphify-out\u002Fgraph.json',\n    prune_sources=deleted or None,\n)\nprint(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')\n\n# Write merged result back to .graphify_extract.json so Step 4 sees the full graph\nmerged_out = {\n    'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],\n    'edges': [\n        # Explicit source\u002Ftarget last so they win over any stale attrs in d.\n        {**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},\n         'source': d.get('_src', u), 'target': d.get('_tgt', v)}\n        for u, v, d in G.edges(data=True)\n    ],\n    # G.graph[\"hyperedges\"] holds hyperedges from both existing graph.json\n    # and new_extraction (build_merge combines them). Falling back to\n    # new_extraction only would silently drop prior-run hyperedges (#801).\n    'hyperedges': list(G.graph.get('hyperedges', [])),\n    'input_tokens': new_extraction.get('input_tokens', 0),\n    'output_tokens': new_extraction.get('output_tokens', 0),\n}\nPath('graphify-out\u002F.graphify_extract.json').write_text(json.dumps(merged_out))\nprint(f'[graphify update] Merged extraction written ({len(merged_out[\\\"nodes\\\"])} nodes, {len(merged_out[\\\"edges\\\"])} edges)')\n\n# Save manifest so next --update diffs against today's state, not the\n# prior run's baseline (prevents ghost-node reports on subsequent updates).\nsave_manifest(incremental['files'])\nprint('[graphify update] Manifest saved.')\n\"\n```\n\nThen run Steps 4–8 on the merged graph as normal.\n\nAfter Step 4, show the graph diff:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport json\nfrom graphify.analyze import graph_diff\nfrom graphify.build import build_from_json\nfrom networkx.readwrite import json_graph\nimport networkx as nx\nfrom pathlib import Path\n\n# Load old graph (before update) from backup written before merge\nold_data = json.loads(Path('graphify-out\u002F.graphify_old.json').read_text()) if Path('graphify-out\u002F.graphify_old.json').exists() else None\nnew_extract = json.loads(Path('graphify-out\u002F.graphify_extract.json').read_text())\nG_new = build_from_json(new_extract)\n\nif old_data:\n    G_old = json_graph.node_link_graph(old_data, edges='links')\n    diff = graph_diff(G_old, G_new)\n    print(diff['summary'])\n    if diff['new_nodes']:\n        print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))\n    if diff['new_edges']:\n        print('New edges:', len(diff['new_edges']))\n\"\n```\n\nBefore the merge step, save the old graph: `cp graphify-out\u002Fgraph.json graphify-out\u002F.graphify_old.json`\nClean up after: `rm -f graphify-out\u002F.graphify_old.json`\n\n---\n\n## For --cluster-only\n\nSkip Steps 1–3. Re-run clustering on the existing graph:\n\n```bash\ngraphify cluster-only .\n```\n\nThen run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report).\n\n---\n\n## For \u002Fgraphify query\n\nTwo traversal modes - choose based on the question:\n\n| Mode | Flag | Best for |\n|------|------|----------|\n| BFS (default) | _(none)_ | \"What is X connected to?\" - broad context, nearest neighbors first |\n| DFS | `--dfs` | \"How does X reach Y?\" - trace a specific chain or dependency path |\n\n```bash\ngraphify query \"QUESTION\"\n# or: graphify query \"QUESTION\" --dfs --budget 3000\n```\n\nReplace `QUESTION` with the user's actual question. Answer using **only** what the graph output contains. Quote `source_location` when citing a specific fact. If the graph lacks enough information, say so - do not hallucinate edges.\n\nAfter writing the answer, save it back into the graph so it improves future queries:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -m graphify save-result --question \"QUESTION\" --answer \"ANSWER\" --type query --nodes NODE1 NODE2\n```\n\nReplace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.\n\n---\n\n## For \u002Fgraphify path\n\nFind the shortest path between two named concepts in the graph.\n\n```bash\ngraphify path \"NODE_A\" \"NODE_B\"\n```\n\nReplace `NODE_A` and `NODE_B` with the actual concept names. Then explain the path in plain language - what each hop means, why it's significant.\n\nAfter writing the explanation, save it back:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -m graphify save-result --question \"Path from NODE_A to NODE_B\" --answer \"ANSWER\" --type path_query --nodes NODE_A NODE_B\n```\n\n---\n\n## For \u002Fgraphify explain\n\nGive a plain-language explanation of a single node - everything connected to it.\n\n```bash\ngraphify explain \"NODE_NAME\"\n```\n\nReplace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.\n\nAfter writing the explanation, save it back:\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -m graphify save-result --question \"Explain NODE_NAME\" --answer \"ANSWER\" --type explain --nodes NODE_NAME\n```\n\n---\n\n## For \u002Fgraphify add\n\nFetch a URL and add it to the corpus, then update the graph.\n\n```bash\n$(cat graphify-out\u002F.graphify_python) -c \"\nimport sys\nfrom graphify.ingest import ingest\nfrom pathlib import Path\n\ntry:\n    out = ingest('URL', Path('.\u002Fraw'), author='AUTHOR', contributor='CONTRIBUTOR')\n    print(f'Saved to {out}')\nexcept ValueError as e:\n    print(f'error: {e}', file=sys.stderr)\n    sys.exit(1)\nexcept RuntimeError as e:\n    print(f'error: {e}', file=sys.stderr)\n    sys.exit(1)\n\"\n```\n\nReplace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `.\u002Fraw` to merge the new file into the existing graph.\n\nSupported URL types (auto-detected):\n- YouTube \u002F any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)\n- Twitter\u002FX → fetched via oEmbed, saved as `.md` with tweet text and author\n- arXiv → abstract + metadata saved as `.md`\n- PDF → downloaded as `.pdf`\n- Images (.png\u002F.jpg\u002F.webp) → downloaded, Claude vision extracts on next run\n- Any webpage → converted to markdown via html2text\n\n---\n\n## For --watch\n\nStart a background watcher that monitors a folder and auto-updates the graph when files change.\n\n```bash\npython3 -m graphify.watch INPUT_PATH --debounce 3\n```\n\nReplace INPUT_PATH with the folder to watch. Behavior depends on what changed:\n\n- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.\n- **Docs, papers, or images:** writes a `graphify-out\u002Fneeds_update` flag and prints a notification to run `\u002Fgraphify --update` (LLM semantic re-extraction required).\n\nDebounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.\n\nPress Ctrl+C to stop.\n\nFor agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `\u002Fgraphify --update` after those waves.\n\n---\n\n## For git commit hook\n\nInstall a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.\n\n```bash\ngraphify hook install    # install\ngraphify hook uninstall  # remove\ngraphify hook status     # check\n```\n\nAfter every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc\u002Fimage changes are ignored by the hook - run `\u002Fgraphify --update` manually for those.\n\nIf a post-commit hook already exists, graphify appends to it rather than replacing it.\n\n---\n\n## For native CLAUDE.md integration\n\nRun once per project to make graphify always-on in Claude Code sessions:\n\n```bash\ngraphify claude install\n```\n\nThis writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `\u002Fgraphify` needed in future sessions.\n\n```bash\ngraphify claude uninstall  # remove the section\n```\n\n---\n\n## Honesty Rules\n\n- Never invent an edge. If unsure, use AMBIGUOUS.\n- Never skip the corpus check warning.\n- Always show token cost in the report.\n- Never hide cohesion scores behind symbols - show the raw number.\n- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.\n",{"name":5,"trigger":24,"description":7},"\u002Fgraphify","master","877653a671c51fae6476bd9f0d34ee6c408d68b9",".github\u002Fskills\u002Fgraphify","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group","https:\u002F\u002Ftrivoxa-group.vercel.app","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web","2026-08-01 17:29:31",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add princepatel04477-web\u002Ftrivoxa-group --skill graphify",{"tool":38,"command":39},"bunx","bunx skills add princepatel04477-web\u002Ftrivoxa-group --skill graphify",{"tool":41,"command":42},"pnpm","pnpm dlx skills add princepatel04477-web\u002Ftrivoxa-group --skill graphify","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fgraphify\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},".graphify_version","OTHER","其他",6,"https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fgraphify\u002F.graphify_version",[53,60,67,74,81,88],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M78G4Z5RFJ72G536XYPC77PG","zustand-store-ts","Create Zustand stores following established patterns with proper TypeScript types and middleware.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzustand-store-ts\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M78G4WQMHRST36KDP7AV3NR3","zoom-automation","Automate Zoom meeting creation, management, recordings, webinars, and participant tracking via Rube MCP (Composio). Always search tools first for current schemas.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzoom-automation\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M78G4T37F4SPS7M4KT0A8JJB","zoho-crm-automation","Automate Zoho CRM tasks via Rube MCP (Composio): create\u002Fupdate records, search contacts, manage leads, and convert leads. Always search tools first for current schemas.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzoho-crm-automation\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M78G4QAJMF71KD1G38MNDQYK","zod-validation-expert","Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzod-validation-expert\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M78G4MS3WE96MH5P561KFY95","zipai-optimizer","Adaptive token optimizer: intelligent filtering, surgical output, ambiguity-first, context-window-aware, VCS-aware, MCP-aware.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzipai-optimizer\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M78G4GZ0T47C6929V9CVH1AK","zeroize-audit","Detects missing zeroization of sensitive data in source code and identifies zeroization removed by compiler optimizations, with assembly-level analysis, and control-flow verification. Use for auditing C\u002FC++\u002FRust code handling secrets, keys, passwords, or other sensitive data.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzeroize-audit\u002FSKILL.md",[],[]]