# Graphify Integration (Optional)

Protocol for optional knowledge graph enrichment across forge skills and commands. Graphify is a skill — graph building is handled by invoking `/graphify`. This protocol defines the reusable guard (install/build/update check) and the query interface skills use to consume graph data.

## How It Works

1. **`/graphify` skill** builds the graph — AST extraction (tree-sitter, free) + semantic extraction (LLM subagents) + Leiden clustering. Outputs `graphify-out/graph.json`, `graphify-out/GRAPH_REPORT.md`, and `graphify-out/graph.html`.
2. **Skills and commands** consume the graph — read static files and run CLI queries. They do not build or manage the graph.
3. **The guard** (below) is a reusable check any skill or command can run at its start to ensure graphify is available and the graph is current.

The graphify CLI provides queries (`query`, `path`, `explain`), platform installers, hooks, and benchmarking — but has no `build` subcommand. Graph construction is orchestrated by the `/graphify` skill, which calls graphify's Python library functions (`detect`, `extract`, `build`, `cluster`, `export`, `report`) and dispatches Claude subagents for semantic extraction. This system intentionally does not use graphify's installer or hook-writing commands (`graphify install`, `graphify hook install`) — it manages its own files.

## Guard: Graphify Status Check

Any skill or command that benefits from graph data can run this check at its start. The guard handles install, build, and update — so the skill's own methodology only needs to focus on querying.

**Step 1 — Check status:**

Three independent checks:
- **Graph file:** `test -f graphify-out/graph.json`
- **CLI installed:** `graphify --version` (exit 0 = installed)
- **`/graphify` skill installed:** `test -f ~/.claude/skills/graphify/SKILL.md`

Combine the results:

```
graphify-out/graph.json exists?  →  CLI installed?  →  /graphify skill installed?  →  Action
──────────────────────────────────────────────────────────────────────────────────
No                     No                   No                            Offer full install (CLI + skill)
No                     Yes                  No                            Offer skill install only
No                     Yes                  Yes                           Offer build via /graphify
Yes                    No                   (don't care)                  Use static files only
Yes                    Yes                  No                            Use static files + CLI queries; offer skill install for /graphify --update
Yes                    Yes                  Yes                           Offer update via /graphify --update (or use as-is)
```

**Step 2 — Prompt the user:**

For skills where graphify enriches but isn't essential:

```
This skill works great with graphify (knowledge graph).

  Current status: {not installed | installed, no graph | graph exists (N nodes, M communities)}

  {(a) Install now — runs these commands (skill-only, no project file changes):
         # Note: the PyPI package is `graphifyy` (double-y) — `graphify` on PyPI
         # is a different unrelated package. The CLI binary it installs is
         # still `graphify` (single-y). Do NOT "fix" this to `pip install graphify`.
         pip install graphifyy
         mkdir -p ~/.claude/skills/graphify
         # TODO pin version — replace `v1` with a commit SHA or release tag once one is published.
         curl -fsSL https://raw.githubusercontent.com/safishamsi/graphify/v1/skills/graphify/skill.md \
           > ~/.claude/skills/graphify/SKILL.md
       Then add this line to ~/.claude/CLAUDE.md (your global file):
         - **graphify** (`~/.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`} ← only if not installed
  {(b) Build graph now — /graphify}               ← only if installed but no graph
  {(c) Update graph — /graphify --update}         ← only if graph exists
  {(d) Skip — proceed without graph}
```

If the user picks install → run the manual-install commands above, then re-check. This path avoids modifying project files. Graphify's native `graphify install` is also available but NOT recommended here — it writes a graphify section to the project's CLAUDE.md and a PreToolUse hook to `.claude/settings.json`, which conflict with files this system manages. If a user wants those features, they can run `graphify install` themselves outside the guard. If they pick build/update → invoke the `/graphify` skill (or `/graphify --update`). If they skip → proceed without graph data.

**Step 3 — Save preference (optional):**

If `.forge/local.yaml` exists, respect stored preferences:

```yaml
graphify:
  build: ask          # always | ask | never  (default: ask)
  query: ask          # always | ask | never  (default: ask)
  install_hint: ask   # ask | never           (default: ask)
```

- `build: always` → invoke `/graphify` or `/graphify --update` without prompting.
- `build: never` → skip build/update silently, still use existing graph if present.
- `query: always` → run CLI queries without prompting.
- `query: never` → skip CLI queries, use static files only.
- `query: ask` → prompt on first CLI query per skill invocation.
- `install_hint: never` → don't suggest installation.

**First-use setup:**

- If `.forge/local.yaml` does not exist, create it with defaults (`ask` for all keys).
- If `.gitignore` does not contain `.forge/local.yaml`, append it.

### Query-only skills

Skills that only use CLI queries on an existing graph (e.g., `support-debug` using `graphify path`) do not need the full guard. They just check:

1. Does `graphify-out/graph.json` exist? → if no, skip graphify entirely.
2. Is the `graphify` CLI available? → if yes, run queries. If no, read static files only.
3. Check `query` preference in `.forge/local.yaml` before first CLI query.

No install/build prompts. The graph either exists (from a prior `/graphify` or `/setup` run) or it doesn't.

### Staleness

Graphify manages freshness internally. The `--update` flag re-extracts only new/changed files (using content hashes and file mtimes). There is no standalone staleness check command — `--update` IS the staleness check and is cheap if nothing changed.

Skills should not implement their own staleness heuristics (no mtime-vs-git-commit checks). Either offer `--update` via the guard, or use the graph as-is.

## Querying the Graph

### Static files

Skills can read these directly — no consent needed:

- **`graphify-out/graph.json`** — full graph with nodes, edges, communities
- **`graphify-out/GRAPH_REPORT.md`** — compact summary with god nodes, community labels
- **`graphify-out/graph.html`** — interactive visualization (reference in onboarding docs)

Key structures in `graphify-out/graph.json`:

- **God nodes** — highest-degree nodes (critical components, architectural hubs)
- **Communities** — Leiden-clustered subsystems with labels and cohesion scores. Use top 20 by cohesion; beyond that is typically noise (singletons).
- **Edge confidence** — `EXTRACTED` (trusted, from AST/source), `INFERRED` (hypothesis, verify before acting), `AMBIGUOUS` (investigation target). These labels come from semantic extraction via the `/graphify` skill.
- **Node metadata** — `source_file`, `source_location`, `file_type`, `community`

**Team-safe:** If a teammate committed `graphify-out/`, everyone benefits without needing graphify installed.

### CLI commands

Require the `graphify` CLI to be installed. Check `query` preference in `.forge/local.yaml` before first use.

| Command | Purpose | Token Cost |
|---------|---------|-----------|
| `graphify query "<question>" --budget N --graph graphify-out/graph.json` | BFS traversal, token-capped answer | ~345 tokens avg |
| `graphify query "<question>" --dfs --graph graphify-out/graph.json` | DFS traversal, trace dependency paths | ~345 tokens avg |
| `graphify path "NodeA" "NodeB" --graph graphify-out/graph.json` | Shortest path between two concepts | Minimal |
| `graphify explain "NodeName" --graph graphify-out/graph.json` | Plain-language node explanation | ~200 tokens |

Always use `--budget` with `query` to cap token usage. Default budget: 1500 tokens.

## Error Handling

- CLI query fails → log error, continue with static file data only.
- CLI query returns empty → treat as no result, do not retry.
- `graphify-out/graph.json` is malformed → skip graph context, note "`graphify-out/graph.json` could not be parsed."
- `pip install graphifyy` fails → note the error, proceed without graphify.
- **Graphify failure NEVER blocks the workflow.** Every graphify step is optional enrichment.

## Constraints

1. Do NOT manage graph rebuilds or freshness. The user invokes `/graphify --update` themselves (or accepts the guard's offer).
2. Do NOT invoke `graphify install` or `graphify hook install`. These commands modify CLAUDE.md and settings.json, which this system manages — the guard's install prompt uses the manual curl-based path instead. Users who want graphify's hook/CLAUDE.md integration can run `graphify install` themselves outside this workflow.
3. Treat `graphify-out/` as read-only input (except when building via the `/graphify` skill).
4. Always run CLI commands from the repo root, or use `--graph graphify-out/graph.json` explicitly to avoid path issues.

## Version Compatibility

Tested with: graphify v1 (TODO pin commit). Update when v2 lands.

- Minimum graphify CLI: v1 (PyPI package `graphifyy`).
- Pinned commit: TODO — replace the `v1` reference in the install snippet (Step 2 install URL) with a commit SHA or release tag once one is published.
- Breaking-change notes: when graphify v2 lands or the `graphify-out/graph.json` schema changes (god-node fields, community labels, edge-confidence enum), update the "Outputs" section and the BFS/DFS query examples, then bump the recorded version here.
