feat: add Kilo Code support (#512)

Adds Kilo Code as a supported platform: native skill + /graphify command, install/uninstall, and a .kilo tool.execute.before plugin (mirroring the OpenCode integration).

JSONC config is handled non-destructively - existing .kilo/kilo.jsonc is read but never rewritten; automated plugin registration goes to kilo.json, preserving user comments (addresses the Qodo review flag).

Verified locally: full suite 1525 passed, install/uninstall smoke test works.
This commit is contained in:
alacasse
2026-06-01 16:05:07 +01:00
committed by GitHub
parent 4b17f199af
commit a8005c218a
7 changed files with 1100 additions and 69 deletions
+1
View File
@@ -20,6 +20,7 @@ graphify-out/
skills/
docs/superpowers/
.vscode/
.kilo
openspec/
# Local benchmark scripts — never commit
scripts/run_k2_*.py
+42 -17
View File
@@ -25,7 +25,7 @@
Type `/graphify` in your AI coding assistant and it maps your entire project — code, docs, PDFs, images, videos — into a knowledge graph you can query instead of grepping through files.
Works in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, and Google Antigravity.
Works in Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, GitHub Copilot CLI, VS Code Copilot Chat, Aider, Amp, OpenClaw, Factory Droid, Trae, Hermes, Kimi Code, Kiro, Pi, Devin CLI, and Google Antigravity.
```
/graphify .
@@ -126,6 +126,7 @@ for example `graphify claude install --project` or `graphify codex install --pro
| Claude Code (Windows) | `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| Kilo Code | `graphify install --platform kilo` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify install --platform aider` |
@@ -179,6 +180,7 @@ Run this once in your project after building a graph:
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| Kilo Code | `graphify kilo install` |
| GitHub Copilot CLI | `graphify copilot install` |
| VS Code Copilot Chat | `graphify vscode install` |
| Aider | `graphify aider install` |
@@ -202,6 +204,10 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
---
**Kilo Code** installs the Graphify skill to `~/.config/kilo/skills/graphify/SKILL.md` and a native `/graphify` command to `~/.config/kilo/command/graphify.md`. `graphify kilo install` also writes `AGENTS.md` plus a native **`tool.execute.before` plugin** (`.kilo/plugins/graphify.js` + `.kilo/kilo.json` or `.kilo/kilo.jsonc` registration) so Kilo gets the same always-on graph reminder behavior through native `.kilo` config.
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
## What's in the report
- **God nodes** — the most-connected concepts in your project. Everything flows through these.
@@ -462,22 +468,41 @@ graphify hook install # post-commit + post-checkout hooks
graphify hook uninstall
graphify hook status
graphify claude install / uninstall
graphify codex install / uninstall
graphify opencode install / uninstall
graphify cursor install / uninstall
graphify gemini install / uninstall
graphify copilot install / uninstall
graphify aider install / uninstall
graphify claw install / uninstall
graphify droid install / uninstall
graphify trae install / uninstall
graphify trae-cn install / uninstall
graphify hermes install / uninstall
graphify amp install / uninstall
graphify kiro install / uninstall
graphify devin install / uninstall
graphify antigravity install / uninstall
# always-on assistant instructions - platform-specific
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify kilo install # native Kilo skill + /graphify command + AGENTS.md + .kilo plugin
graphify kilo uninstall
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify cursor uninstall
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
graphify gemini uninstall
graphify copilot install # skill file (GitHub Copilot CLI)
graphify copilot uninstall
graphify aider install # AGENTS.md (Aider)
graphify aider uninstall
graphify claw install # AGENTS.md (OpenClaw)
graphify claw uninstall
graphify droid install # AGENTS.md (Factory Droid)
graphify droid uninstall
graphify trae install # AGENTS.md (Trae)
graphify trae uninstall
graphify trae-cn install # AGENTS.md (Trae CN)
graphify trae-cn uninstall
graphify hermes install # AGENTS.md + ~/.hermes/skills/ (Hermes)
graphify hermes uninstall
graphify amp install # skill file (Amp)
graphify amp uninstall
graphify kiro install # .kiro/skills/ + .kiro/steering/graphify.md (Kiro IDE/CLI)
graphify kiro uninstall
graphify pi install # skill file (Pi coding agent)
graphify pi uninstall
graphify devin install # skill file + .windsurf/rules/graphify.md (Devin CLI)
graphify devin uninstall
graphify antigravity install # .agents/rules + .agents/workflows (Google Antigravity)
graphify antigravity uninstall
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, deepseek, ollama, bedrock, or claude-cli
+415 -47
View File
@@ -1,4 +1,5 @@
"""graphify CLI - `graphify install` sets up the Claude Code skill."""
from __future__ import annotations
import json
import os
@@ -10,6 +11,7 @@ from pathlib import Path
try:
from importlib.metadata import version as _pkg_version
__version__ = _pkg_version("graphifyy")
except Exception:
__version__ = "unknown"
@@ -235,6 +237,11 @@ _PLATFORM_CONFIG: dict[str, dict] = {
"skill_dst": Path(".config") / "opencode" / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"kilo": {
"skill_file": "skill-kilo.md",
"skill_dst": Path(".config") / "kilo" / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"aider": {
"skill_file": "skill-aider.md",
"skill_dst": Path(".aider") / "graphify" / "SKILL.md",
@@ -381,6 +388,20 @@ def install(platform: str = "claude", *, project: bool = False, project_dir: Pat
project_dir = project_dir or Path(".")
skill_dst = _copy_skill_file(platform, project=project, project_dir=project_dir)
if platform == "kilo":
# Kilo Code also supports a native /graphify command file.
command_src = Path(__file__).parent / "command-kilo.md"
if not command_src.exists():
print(
f"error: command-kilo.md not found in package - reinstall graphify",
file=sys.stderr,
)
sys.exit(1)
command_dst = Path.home() / ".config" / "kilo" / "command" / "graphify.md"
command_dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(command_src, command_dst)
print(f" command installed -> {command_dst}")
if cfg["claude_md"]:
# Register in the matching Claude Code scope.
claude_md = (project_dir / ".claude" / "CLAUDE.md") if project else Path.home() / ".claude" / "CLAUDE.md"
@@ -521,11 +542,17 @@ def _install_gemini_hook(project_dir: Path) -> None:
settings_path = project_dir / ".gemini" / "settings.json"
settings_path.parent.mkdir(parents=True, exist_ok=True)
try:
settings = json.loads(settings_path.read_text(encoding="utf-8")) if settings_path.exists() else {}
settings = (
json.loads(settings_path.read_text(encoding="utf-8"))
if settings_path.exists()
else {}
)
except json.JSONDecodeError:
settings = {}
before_tool = settings.setdefault("hooks", {}).setdefault("BeforeTool", [])
settings["hooks"]["BeforeTool"] = [h for h in before_tool if "graphify" not in str(h)]
settings["hooks"]["BeforeTool"] = [
h for h in before_tool if "graphify" not in str(h)
]
settings["hooks"]["BeforeTool"].append(_GEMINI_HOOK)
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
print(" .gemini/settings.json -> BeforeTool hook registered")
@@ -561,7 +588,9 @@ def gemini_uninstall(project_dir: Path | None = None, *, project: bool = False)
if _GEMINI_MD_MARKER not in content:
print("graphify section not found in GEMINI.md - nothing to do")
return
cleaned = re.sub(r"\n*## graphify\n.*?(?=\n## |\Z)", "", content, flags=re.DOTALL).rstrip()
cleaned = re.sub(
r"\n*## graphify\n.*?(?=\n## |\Z)", "", content, flags=re.DOTALL
).rstrip()
if cleaned:
target.write_text(cleaned + "\n", encoding="utf-8")
print(f"graphify section removed from {target.resolve()}")
@@ -621,7 +650,9 @@ def vscode_install(project_dir: Path | None = None) -> None:
print(f" {instructions} -> created")
print()
print("VS Code Copilot Chat configured. Type /graphify in the chat panel to build the graph.")
print(
"VS Code Copilot Chat configured. Type /graphify in the chat panel to build the graph."
)
print("Note: for GitHub Copilot CLI (terminal), use: graphify copilot install")
@@ -634,7 +665,11 @@ def vscode_uninstall(project_dir: Path | None = None) -> None:
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
for d in (skill_dst.parent, skill_dst.parent.parent, skill_dst.parent.parent.parent):
for d in (
skill_dst.parent,
skill_dst.parent.parent,
skill_dst.parent.parent.parent,
):
try:
d.rmdir()
except OSError:
@@ -646,7 +681,9 @@ def vscode_uninstall(project_dir: Path | None = None) -> None:
content = instructions.read_text(encoding="utf-8")
if _VSCODE_INSTRUCTIONS_MARKER not in content:
return
cleaned = re.sub(r"\n*## graphify\n.*?(?=\n## |\Z)", "", content, flags=re.DOTALL).rstrip()
cleaned = re.sub(
r"\n*## graphify\n.*?(?=\n## |\Z)", "", content, flags=re.DOTALL
).rstrip()
if cleaned:
instructions.write_text(cleaned + "\n", encoding="utf-8")
print(f" graphify section removed from {instructions}")
@@ -801,11 +838,15 @@ def _antigravity_install(project_dir: Path) -> None:
print("Antigravity will now check the knowledge graph before answering")
print("codebase questions. Run /graphify first to build the graph.")
print()
print("To enable full MCP architecture navigation, add this to ~/.gemini/antigravity/mcp_config.json:")
print(
"To enable full MCP architecture navigation, add this to ~/.gemini/antigravity/mcp_config.json:"
)
print(' "graphify": {')
print(' "command": "uv",')
print(' "args": ["run", "--with", "graphifyy", "--with", "mcp", "-m", "graphify.serve", "${workspace.path}/graphify-out/graph.json"]')
print(' }')
print(
' "args": ["run", "--with", "graphifyy", "--with", "mcp", "-m", "graphify.serve", "${workspace.path}/graphify-out/graph.json"]'
)
print(" }")
def _antigravity_uninstall(project_dir: Path, *, project: bool = False) -> None:
@@ -832,7 +873,11 @@ def _antigravity_uninstall(project_dir: Path, *, project: bool = False) -> None:
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
for d in (skill_dst.parent, skill_dst.parent.parent, skill_dst.parent.parent.parent):
for d in (
skill_dst.parent,
skill_dst.parent.parent,
skill_dst.parent.parent.parent,
):
try:
d.rmdir()
except OSError:
@@ -919,6 +964,175 @@ def _devin_rules_uninstall(project_dir: Path) -> None:
print(f" rules removed -> {rules_path}")
_KILO_PLUGIN_JS = """\
// graphify Kilo plugin
// Injects a knowledge graph reminder before bash tool calls when the graph exists.
import { existsSync } from "fs";
import { join } from "path";
export const GraphifyPlugin = async ({ directory }) => {
let reminded = false;
return {
"tool.execute.before": async (input, output) => {
if (reminded) return;
if (!existsSync(join(directory, "graphify-out", "graph.json"))) return;
if (input.tool === "bash") {
output.args.command =
'echo "[graphify] Knowledge graph available. Read graphify-out/GRAPH_REPORT.md for god nodes and architecture context before searching files." && ' +
output.args.command;
reminded = true;
}
},
};
};
"""
_KILO_PLUGIN_PATH = Path(".kilo") / "plugins" / "graphify.js"
_KILO_CONFIG_JSON_PATH = Path(".kilo") / "kilo.json"
_KILO_CONFIG_JSONC_PATH = Path(".kilo") / "kilo.jsonc"
def _strip_json_comments(raw: str) -> str:
"""Remove JSONC-style comments while leaving string content intact."""
result: list[str] = []
in_string = False
escaped = False
line_comment = False
block_comment = False
i = 0
while i < len(raw):
ch = raw[i]
nxt = raw[i + 1] if i + 1 < len(raw) else ""
if line_comment:
if ch == "\n":
line_comment = False
result.append(ch)
i += 1
continue
if block_comment:
if ch == "*" and nxt == "/":
block_comment = False
i += 2
else:
i += 1
continue
if in_string:
result.append(ch)
if escaped:
escaped = False
elif ch == "\\":
escaped = True
elif ch == '"':
in_string = False
i += 1
continue
if ch == "/" and nxt == "/":
line_comment = True
i += 2
continue
if ch == "/" and nxt == "*":
block_comment = True
i += 2
continue
result.append(ch)
if ch == '"':
in_string = True
i += 1
return re.sub(r",(\s*[}\]])", r"\1", "".join(result))
def _load_json_like(config_file: Path) -> dict:
if not config_file.exists():
return {}
try:
raw = config_file.read_text(encoding="utf-8")
if config_file.suffix == ".jsonc":
raw = _strip_json_comments(raw)
loaded = json.loads(raw)
except (OSError, json.JSONDecodeError):
return {}
return loaded if isinstance(loaded, dict) else {}
def _kilo_config_path(project_dir: Path) -> Path:
kilo_dir = (project_dir or Path(".")) / ".kilo"
json_path = kilo_dir / _KILO_CONFIG_JSON_PATH.name
if json_path.exists():
return json_path
jsonc_path = kilo_dir / _KILO_CONFIG_JSONC_PATH.name
if jsonc_path.exists():
return jsonc_path
return json_path
def _kilo_config_write_path(project_dir: Path) -> Path:
"""Write automated Kilo edits to kilo.json so existing JSONC stays untouched."""
kilo_dir = (project_dir or Path(".")) / ".kilo"
return kilo_dir / _KILO_CONFIG_JSON_PATH.name
def _install_kilo_plugin(project_dir: Path) -> None:
"""Write graphify.js plugin and register it without rewriting user JSONC."""
plugin_file = project_dir / _KILO_PLUGIN_PATH
plugin_file.parent.mkdir(parents=True, exist_ok=True)
plugin_file.write_text(_KILO_PLUGIN_JS, encoding="utf-8")
print(f" {_KILO_PLUGIN_PATH} -> tool.execute.before hook written")
config_file = _kilo_config_path(project_dir)
write_config_file = _kilo_config_write_path(project_dir)
write_config_file.parent.mkdir(parents=True, exist_ok=True)
config = _load_json_like(config_file)
plugins = config.get("plugin")
if not isinstance(plugins, list):
plugins = []
config["plugin"] = plugins
entry = plugin_file.resolve().as_uri()
if entry not in plugins:
plugins.append(entry)
write_config_file.write_text(json.dumps(config, indent=2), encoding="utf-8")
print(f" {write_config_file.relative_to(project_dir)} -> plugin registered")
else:
print(
f" {config_file.relative_to(project_dir)} -> plugin already registered (no change)"
)
def _uninstall_kilo_plugin(project_dir: Path) -> None:
"""Remove graphify.js plugin and deregister it without rewriting user JSONC."""
plugin_file = project_dir / _KILO_PLUGIN_PATH
if plugin_file.exists():
plugin_file.unlink()
print(f" {_KILO_PLUGIN_PATH} -> removed")
config_file = _kilo_config_path(project_dir)
if not config_file.exists():
return
write_config_file = _kilo_config_write_path(project_dir)
config = _load_json_like(config_file)
plugins = config.get("plugin", [])
if not isinstance(plugins, list):
plugins = []
entry = plugin_file.resolve().as_uri()
if entry in plugins:
config["plugin"] = [plugin for plugin in plugins if plugin != entry]
if not config["plugin"]:
config.pop("plugin")
write_config_file.parent.mkdir(parents=True, exist_ok=True)
write_config_file.write_text(json.dumps(config, indent=2), encoding="utf-8")
print(
f" {write_config_file.relative_to(project_dir)} -> plugin deregistered"
)
# OpenCode tool.execute.before plugin — fires before every tool call.
# Injects a graph reminder into bash command output when graph.json exists.
_OPENCODE_PLUGIN_JS = """\
@@ -1090,7 +1304,7 @@ def _uninstall_codex_hook(project_dir: Path) -> None:
def _agents_install(project_dir: Path, platform: str) -> None:
"""Write the graphify section to the local AGENTS.md (Codex/OpenCode/OpenClaw)."""
"""Write the graphify section to the local AGENTS.md for always-on platforms."""
target = (project_dir or Path(".")) / "AGENTS.md"
if target.exists():
@@ -1111,14 +1325,20 @@ def _agents_install(project_dir: Path, platform: str) -> None:
_install_codex_hook(project_dir or Path("."))
elif platform == "opencode":
_install_opencode_plugin(project_dir or Path("."))
elif platform == "kilo":
_install_kilo_plugin(project_dir or Path("."))
print()
print(f"{platform.capitalize()} will now check the knowledge graph before answering")
print(
f"{platform.capitalize()} will now check the knowledge graph before answering"
)
print("codebase questions and rebuild it after code changes.")
if platform not in ("codex", "opencode"):
if platform not in ("codex", "opencode", "kilo"):
print()
print("Note: unlike Claude Code, there is no PreToolUse hook equivalent for")
print(f"{platform.capitalize()} - the AGENTS.md rules are the always-on mechanism.")
print(
f"{platform.capitalize()} — the AGENTS.md rules are the always-on mechanism."
)
def _project_install(platform_name: str, project_dir: Path | None = None) -> None:
@@ -1206,11 +1426,19 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
if not target.exists():
print("No AGENTS.md found in current directory - nothing to do")
if platform == "opencode":
_uninstall_opencode_plugin(project_dir or Path("."))
elif platform == "kilo":
_uninstall_kilo_plugin(project_dir or Path("."))
return
content = target.read_text(encoding="utf-8")
if _AGENTS_MD_MARKER not in content:
print("graphify section not found in AGENTS.md - nothing to do")
if platform == "opencode":
_uninstall_opencode_plugin(project_dir or Path("."))
elif platform == "kilo":
_uninstall_kilo_plugin(project_dir or Path("."))
return
cleaned = re.sub(
@@ -1228,6 +1456,52 @@ def _agents_uninstall(project_dir: Path, platform: str = "") -> None:
if platform == "opencode":
_uninstall_opencode_plugin(project_dir or Path("."))
elif platform == "kilo":
_uninstall_kilo_plugin(project_dir or Path("."))
def _kilo_uninstall_global() -> list[str]:
removed = []
command_dst = Path.home() / ".config" / "kilo" / "command" / "graphify.md"
if command_dst.exists():
command_dst.unlink()
removed.append(f"command removed: {command_dst}")
try:
command_dst.parent.rmdir()
except OSError:
pass
skill_dst = Path.home() / _PLATFORM_CONFIG["kilo"]["skill_dst"]
if skill_dst.exists():
skill_dst.unlink()
removed.append(f"skill removed: {skill_dst}")
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
for d in (
skill_dst.parent,
skill_dst.parent.parent,
skill_dst.parent.parent.parent,
):
try:
d.rmdir()
except OSError:
break
return removed
def _kilo_install(project_dir: Path) -> None:
"""Install native Kilo skill + command globally and always-on project wiring locally."""
install(platform="kilo")
_agents_install(project_dir or Path("."), "kilo")
def _kilo_uninstall(project_dir: Path) -> None:
"""Remove Kilo always-on project wiring and global skill/command files."""
_agents_uninstall(project_dir or Path("."), platform="kilo")
removed = _kilo_uninstall_global()
print("; ".join(removed) if removed else "nothing to remove")
def claude_install(project_dir: Path | None = None) -> None:
@@ -1365,7 +1639,9 @@ def claude_uninstall(project_dir: Path | None = None) -> None:
_uninstall_claude_hook(project_dir or Path("."))
def _clone_repo(url: str, branch: str | None = None, out_dir: Path | None = None) -> Path:
def _clone_repo(
url: str, branch: str | None = None, out_dir: Path | None = None
) -> Path:
"""Clone a GitHub repo to a local cache dir and return the path.
Clones into ~/.graphify/repos/<owner>/<repo> by default so repeated
@@ -1497,7 +1773,9 @@ def main() -> None:
print(" save-result save a Q&A result to graphify-out/memory/ for graph feedback loop")
print(" --question Q the question asked")
print(" --answer A the answer to save")
print(" --type T query type: query|path_query|explain (default: query)")
print(
" --type T query type: query|path_query|explain (default: query)"
)
print(" --nodes N1 N2 ... source node labels cited in the answer")
print(" --memory-dir DIR memory directory (default: graphify-out/memory)")
print(" check-update <path> check needs_update flag and notify if semantic re-extraction is pending (cron-safe)")
@@ -1531,35 +1809,67 @@ def main() -> None:
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
print(" hook uninstall remove git hooks")
print(" hook status check if git hooks are installed")
print(" gemini install write GEMINI.md section + BeforeTool hook (Gemini CLI)")
print(
" gemini install write GEMINI.md section + BeforeTool hook (Gemini CLI)"
)
print(" gemini uninstall remove GEMINI.md section + BeforeTool hook")
print(" cursor install write .cursor/rules/graphify.mdc (Cursor)")
print(" cursor uninstall remove .cursor/rules/graphify.mdc")
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
print(
" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)"
)
print(
" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook"
)
print(" codex install write graphify section to AGENTS.md (Codex)")
print(" codex uninstall remove graphify section from AGENTS.md")
print(" opencode install write graphify section to AGENTS.md + tool.execute.before plugin (OpenCode)")
print(" opencode uninstall remove graphify section from AGENTS.md + plugin")
print(
" opencode install write graphify section to AGENTS.md + tool.execute.before plugin (OpenCode)"
)
print(
" opencode uninstall remove graphify section from AGENTS.md + plugin"
)
print(
" kilo install install native Kilo skill + command + AGENTS.md + .kilo plugin"
)
print(
" kilo uninstall remove native Kilo skill + command + AGENTS.md + .kilo plugin"
)
print(" aider install write graphify section to AGENTS.md (Aider)")
print(" aider uninstall remove graphify section from AGENTS.md")
print(" copilot install copy graphify skill to ~/.copilot/skills (GitHub Copilot CLI)")
print(
" copilot install copy graphify skill to ~/.copilot/skills (GitHub Copilot CLI)"
)
print(" copilot uninstall remove graphify skill from ~/.copilot/skills")
print(" vscode install configure VS Code Copilot Chat (skill + .github/copilot-instructions.md)")
print(
" vscode install configure VS Code Copilot Chat (skill + .github/copilot-instructions.md)"
)
print(" vscode uninstall remove VS Code Copilot Chat configuration")
print(" claw install write graphify section to AGENTS.md (OpenClaw)")
print(
" claw install write graphify section to AGENTS.md (OpenClaw)"
)
print(" claw uninstall remove graphify section from AGENTS.md")
print(" droid install write graphify section to AGENTS.md (Factory Droid)")
print(
" droid install write graphify section to AGENTS.md (Factory Droid)"
)
print(" droid uninstall remove graphify section from AGENTS.md")
print(" trae install write graphify section to AGENTS.md (Trae)")
print(" trae uninstall remove graphify section from AGENTS.md")
print(" trae-cn install write graphify section to AGENTS.md (Trae CN)")
print(" trae-cn uninstall remove graphify section from AGENTS.md")
print(" antigravity install write .agents/rules + .agents/workflows + skill (Google Antigravity)")
print(" antigravity uninstall remove .agents/rules, .agents/workflows, and skill")
print(" hermes install write skill to ~/.hermes/skills/graphify/ (Hermes)")
print(
" antigravity install write .agents/rules + .agents/workflows + skill (Google Antigravity)"
)
print(
" antigravity uninstall remove .agents/rules, .agents/workflows, and skill"
)
print(
" hermes install write skill to ~/.hermes/skills/graphify/ (Hermes)"
)
print(" hermes uninstall remove skill from ~/.hermes/skills/graphify/")
print(" kiro install write skill to .kiro/skills/graphify/ + steering file (Kiro IDE/CLI)")
print(
" kiro install write skill to .kiro/skills/graphify/ + steering file (Kiro IDE/CLI)"
)
print(" kiro uninstall remove skill + steering file")
print(" pi install write skill to ~/.pi/agent/skills/graphify/ (Pi coding agent)")
print(" pi uninstall remove skill from ~/.pi/agent/skills/graphify/")
@@ -1716,6 +2026,15 @@ def main() -> None:
else:
print("Usage: graphify copilot [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "kilo":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
_kilo_install(Path("."))
elif subcmd == "uninstall":
_kilo_uninstall(Path("."))
else:
print("Usage: graphify kilo [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "kiro":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
@@ -1905,7 +2224,12 @@ def main() -> None:
from graphify.prs import cmd_prs
cmd_prs(sys.argv[2:])
elif cmd == "hook":
from graphify.hooks import install as hook_install, uninstall as hook_uninstall, status as hook_status
from graphify.hooks import (
install as hook_install,
uninstall as hook_uninstall,
status as hook_status,
)
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
print(hook_install(Path(".")))
@@ -1923,6 +2247,7 @@ def main() -> None:
from graphify.serve import _query_graph_text
from graphify.security import sanitize_label
from networkx.readwrite import json_graph
question = sys.argv[2]
use_dfs = "--dfs" in sys.argv
budget = 2000
@@ -1952,7 +2277,8 @@ def main() -> None:
context_filters.append(args[i].split("=", 1)[1])
i += 1
elif args[i] == "--graph" and i + 1 < len(args):
graph_path = args[i + 1]; i += 2
graph_path = args[i + 1]
i += 2
else:
i += 1
gp = Path(graph_path).resolve()
@@ -1966,6 +2292,7 @@ def main() -> None:
try:
import json as _json
import networkx as _nx
_raw = _json.loads(gp.read_text(encoding="utf-8"))
if "links" not in _raw and "edges" in _raw:
_raw = dict(_raw, links=_raw["edges"])
@@ -2049,6 +2376,7 @@ def main() -> None:
elif cmd == "save-result":
# graphify save-result --question Q --answer A --type T [--nodes N1 N2 ...]
import argparse as _ap
p = _ap.ArgumentParser(prog="graphify save-result")
p.add_argument("--question", required=True)
p.add_argument("--answer", required=True)
@@ -2057,6 +2385,7 @@ def main() -> None:
p.add_argument("--memory-dir", default="graphify-out/memory")
opts = p.parse_args(sys.argv[2:])
from graphify.ingest import save_query_result as _sqr
out = _sqr(
question=opts.question,
answer=opts.answer,
@@ -2067,11 +2396,15 @@ def main() -> None:
print(f"Saved to {out}")
elif cmd == "path":
if len(sys.argv) < 4:
print("Usage: graphify path \"<source>\" \"<target>\" [--graph path]", file=sys.stderr)
print(
'Usage: graphify path "<source>" "<target>" [--graph path]',
file=sys.stderr,
)
sys.exit(1)
from graphify.serve import _score_nodes
from networkx.readwrite import json_graph
import networkx as _nx
source_label = sys.argv[2]
target_label = sys.argv[3]
graph_path = _default_graph_path()
@@ -2151,10 +2484,11 @@ def main() -> None:
elif cmd == "explain":
if len(sys.argv) < 3:
print("Usage: graphify explain \"<node>\" [--graph path]", file=sys.stderr)
print('Usage: graphify explain "<node>" [--graph path]', file=sys.stderr)
sys.exit(1)
from graphify.serve import _find_node
from networkx.readwrite import json_graph
label = sys.argv[2]
graph_path = _default_graph_path()
args = sys.argv[3:]
@@ -2183,7 +2517,9 @@ def main() -> None:
d = G.nodes[nid]
print(f"Node: {d.get('label', nid)}")
print(f" ID: {nid}")
print(f" Source: {d.get('source_file', '')} {d.get('source_location', '')}".rstrip())
print(
f" Source: {d.get('source_file', '')} {d.get('source_location', '')}".rstrip()
)
print(f" Type: {d.get('file_type', '')}")
print(f" Community: {d.get('community', '')}")
print(f" Degree: {G.degree(nid)}")
@@ -2300,9 +2636,13 @@ def main() -> None:
elif cmd == "add":
if len(sys.argv) < 3:
print("Usage: graphify add <url> [--author Name] [--contributor Name] [--dir ./raw]", file=sys.stderr)
print(
"Usage: graphify add <url> [--author Name] [--contributor Name] [--dir ./raw]",
file=sys.stderr,
)
sys.exit(1)
from graphify.ingest import ingest as _ingest
url = sys.argv[2]
author: str | None = None
contributor: str | None = None
@@ -2311,11 +2651,14 @@ def main() -> None:
i = 0
while i < len(args):
if args[i] == "--author" and i + 1 < len(args):
author = args[i + 1]; i += 2
author = args[i + 1]
i += 2
elif args[i] == "--contributor" and i + 1 < len(args):
contributor = args[i + 1]; i += 2
contributor = args[i + 1]
i += 2
elif args[i] == "--dir" and i + 1 < len(args):
target_dir = Path(args[i + 1]); i += 2
target_dir = Path(args[i + 1])
i += 2
else:
i += 1
try:
@@ -2332,6 +2675,7 @@ def main() -> None:
print(f"error: path not found: {watch_path}", file=sys.stderr)
sys.exit(1)
from graphify.watch import watch as _watch
try:
_watch(watch_path)
except ImportError as exc:
@@ -2380,14 +2724,22 @@ def main() -> None:
watch_path = Path(".")
graph_json = graph_override if graph_override is not None else watch_path / "graphify-out" / "graph.json"
if not graph_json.exists():
print(f"error: no graph found at {graph_json} - run /graphify first", file=sys.stderr)
print(
f"error: no graph found at {graph_json} — run /graphify first",
file=sys.stderr,
)
sys.exit(1)
from networkx.readwrite import json_graph as _jg
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all, remap_communities_to_previous
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.analyze import (
god_nodes,
surprising_connections,
suggest_questions,
)
from graphify.report import generate
from graphify.export import to_json, to_html
print("Loading existing graph...")
_enforce_graph_size_cap_or_exit(graph_json)
_raw = json.loads(graph_json.read_text(encoding="utf-8"))
@@ -2499,6 +2851,7 @@ def main() -> None:
print(f"error: path not found: {watch_path}", file=sys.stderr)
sys.exit(1)
from graphify.watch import _rebuild_code
print(f"Re-extracting code files in {watch_path} (no LLM needed)...")
# Interactive CLI: block on the per-repo lock rather than skip, so the
# user sees their explicit `graphify update` complete instead of
@@ -2515,7 +2868,10 @@ def main() -> None:
):
print("Tip: set GEMINI_API_KEY or GOOGLE_API_KEY to use Gemini for semantic extraction.")
else:
print("Nothing to update or rebuild failed - check output above.", file=sys.stderr)
print(
"Nothing to update or rebuild failed — check output above.",
file=sys.stderr,
)
sys.exit(1)
elif cmd == "hook-check":
@@ -2528,6 +2884,7 @@ def main() -> None:
print("Usage: graphify check-update <path>", file=sys.stderr)
sys.exit(1)
from graphify.watch import check_update
check_update(Path(sys.argv[2]).resolve())
sys.exit(0)
elif cmd == "tree":
@@ -2649,11 +3006,16 @@ def main() -> None:
i = 0
while i < len(args):
if args[i] == "--out" and i + 1 < len(args):
out_path = Path(args[i + 1]); i += 2
out_path = Path(args[i + 1])
i += 2
else:
graph_paths.append(Path(args[i])); i += 1
graph_paths.append(Path(args[i]))
i += 1
if len(graph_paths) < 2:
print("Usage: graphify merge-graphs <graph1.json> <graph2.json> [...] [--out merged.json]", file=sys.stderr)
print(
"Usage: graphify merge-graphs <graph1.json> <graph2.json> [...] [--out merged.json]",
file=sys.stderr,
)
sys.exit(1)
import networkx as _nx
from networkx.readwrite import json_graph as _jg
@@ -2690,7 +3052,10 @@ def main() -> None:
elif cmd == "clone":
if len(sys.argv) < 3:
print("Usage: graphify clone <github-url> [--branch <branch>] [--out <dir>]", file=sys.stderr)
print(
"Usage: graphify clone <github-url> [--branch <branch>] [--out <dir>]",
file=sys.stderr,
)
sys.exit(1)
url = sys.argv[2]
branch: str | None = None
@@ -2699,9 +3064,11 @@ def main() -> None:
i = 0
while i < len(args):
if args[i] == "--branch" and i + 1 < len(args):
branch = args[i + 1]; i += 2
branch = args[i + 1]
i += 2
elif args[i] == "--out" and i + 1 < len(args):
out_dir = Path(args[i + 1]); i += 2
out_dir = Path(args[i + 1])
i += 2
else:
i += 1
local_path = _clone_repo(url, branch=branch, out_dir=out_dir)
@@ -2967,6 +3334,7 @@ def main() -> None:
elif cmd == "benchmark":
from graphify.benchmark import run_benchmark, print_benchmark
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
_enforce_graph_size_cap_or_exit(Path(graph_path))
# Try to load corpus_words from detect output
+15
View File
@@ -0,0 +1,15 @@
---
description: Build or query a graphify knowledge graph
---
Invoke the `graphify` skill immediately.
Pass the full `/graphify` argument string through unchanged.
If no arguments were supplied, treat the target path as `.`.
Examples:
- `/graphify`
- `/graphify src --update`
- `/graphify query "what connects auth to billing?"`
Do not answer from raw files before handing off to the `graphify` skill.
+414
View File
@@ -0,0 +1,414 @@
---
name: graphify
description: any input (code, docs, papers, images) -> knowledge graph -> clustered communities -> HTML + JSON + audit report
trigger: /graphify
---
# /graphify
Turn 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`.
## Usage
```text
/graphify
/graphify <path>
/graphify <path> --mode deep
/graphify <path> --update
/graphify <path> --cluster-only
/graphify <path> --no-viz
/graphify add <url>
/graphify query "<question>"
/graphify path "AuthModule" "Database"
/graphify explain "SwinTransformer"
```
## What You Must Do When Invoked
If no path was given, use `.`. Do not ask the user for a path.
Follow these steps in order. Do not skip steps.
### Step 1 - Ensure graphify is installed
```bash
# Detect the correct Python interpreter (handles pipx, venv, system installs)
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$PYTHON" in
*[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;;
esac
else
PYTHON="python3"
fi
"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
```
If the import succeeds, print nothing and move straight to Step 2.
**In every later bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to reuse the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
result = detect(Path('INPUT_PATH'))
print(json.dumps(result))
" > graphify-out/.graphify_detect.json
```
Replace `INPUT_PATH` with the actual path the user provided. Do not dump the JSON to the user. Read it silently and present a clean summary instead:
```text
Corpus: X files · ~Y words
code: N files
docs: N files
papers: N files
images: N files
video: N files
```
Omit any category with 0 files.
Then act on it:
- If `total_files` is 0: stop with `No supported files found in [path].`
- If `skipped_sensitive` is non-empty: mention the count skipped, not the filenames.
- If `total_words > 2_000_000` or `total_files > 200`: show the warning and ask which subfolder to run on.
- Otherwise continue directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video or audio files (only if video files were detected)
Skip this step entirely if detection found zero `video` files.
Transcribe the files first, then treat the transcripts as docs during semantic extraction.
Write a one-sentence Whisper prompt yourself from the top graph labels. If the corpus only contains video, use `Use proper punctuation and paragraph breaks.`
```bash
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before semantic extraction
- Print `Transcribed N video file(s) -> treating as docs`
- If a file fails, warn and continue with the rest
### Step 3 - Extract entities and relationships
Track whether `--mode deep` was given. Pass that through to every semantic extraction task.
This step has two parts: deterministic AST extraction for code and semantic extraction for docs, papers, and images.
#### Part A - Structural extraction for code files
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.extract import collect_files, extract
from pathlib import Path
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
result = extract(code_files, cache_root=Path('.'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
print('AST: {} nodes, {} edges'.format(len(result['nodes']), len(result['edges'])))
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes': [], 'edges': [], 'input_tokens': 0, 'output_tokens': 0}))
print('No code files - skipping AST extraction')
"
```
#### Part B - Semantic extraction for docs, papers, and images
If detection found zero docs, papers, and images, skip this part and go straight to Part C.
**You must use the native `Task` tool here.** Reading files sequentially yourself is too slow and defeats the purpose of the Kilo integration.
Before dispatching tasks, check the semantic cache first:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
all_files = [f for files in detect['files'].values() for f in files]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached))
print(f'Cache: {len(all_files) - len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
If every file is cached, skip directly to Part C.
Split `graphify-out/.graphify_uncached.txt` into chunks of 20-25 files, grouping related directories together. Each image should get its own chunk.
Dispatch **all** chunk tasks in the same response so they run in parallel. Always use `subagent_type="general"`.
Each task should receive a prompt like this, with the placeholders replaced:
```text
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Rules:
- EXTRACTED: relationship explicit in source
- INFERRED: reasonable inference
- AMBIGUOUS: uncertain, flag it instead of omitting it
- Code files: focus on semantic edges AST cannot find
- Doc and paper files: extract concepts, citations, and rationale nodes
- Image files: use vision to understand the artifact, not just OCR
- If DEEP_MODE is true, be more aggressive with INFERRED edges
- Include `confidence_score` on every edge
Write the result to `graphify-out/.graphify_chunk_CHUNK_NUM.json` and also return the same JSON.
Schema:
{"nodes": [], "edges": [], "hyperedges": [], "input_tokens": 0, "output_tokens": 0}
```
After all tasks finish, merge them into `graphify-out/.graphify_semantic_new.json`. Track the chunk filenames yourself and substitute them below.
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
chunk_files = CHUNK_FILES
combined = {'nodes': [], 'edges': [], 'hyperedges': [], 'input_tokens': 0, 'output_tokens': 0}
failures = 0
for chunk_file in chunk_files:
path = Path(chunk_file)
if not path.exists():
failures += 1
continue
try:
data = json.loads(path.read_text())
except Exception:
failures += 1
continue
combined['nodes'].extend(data.get('nodes', []))
combined['edges'].extend(data.get('edges', []))
combined['hyperedges'].extend(data.get('hyperedges', []))
combined['input_tokens'] += data.get('input_tokens', 0)
combined['output_tokens'] += data.get('output_tokens', 0)
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps(combined, indent=2))
print('Semantic extraction: {} nodes, {} edges, {} failed chunk(s)'.format(len(combined['nodes']), len(combined['edges']), failures))
"
```
If more than half the chunk tasks fail, stop and report the failure instead of silently continuing.
Cache the new semantic results and merge them with cached data:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes': [], 'edges': [], 'hyperedges': []}
save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes': [], 'edges': [], 'hyperedges': []}
all_nodes = cached.get('nodes', []) + new.get('nodes', [])
all_edges = cached.get('edges', []) + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped_nodes = []
for node in all_nodes:
node_id = node.get('id')
if node_id and node_id not in seen:
seen.add(node_id)
deduped_nodes.append(node)
merged = {
'nodes': deduped_nodes,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
print(f'Semantic merge complete - {len(deduped_nodes)} nodes, {len(all_edges)} edges')
"
```
#### Part C - Merge AST and semantic extraction
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text()) if Path('graphify-out/.graphify_semantic.json').exists() else {'nodes': [], 'edges': [], 'hyperedges': [], 'input_tokens': 0, 'output_tokens': 0}
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for node in sem.get('nodes', []):
if node['id'] not in seen:
merged_nodes.append(node)
seen.add(node['id'])
merged = {
'nodes': merged_nodes,
'edges': ast['edges'] + sem.get('edges', []),
'hyperedges': sem.get('hyperedges', []),
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
print('Merged extraction: {} nodes, {} edges'.format(len(merged_nodes), len(merged['edges'])))
"
```
### Step 4 - Build the graph and generate outputs
Use generic labels like `Community 0`, `Community 1`, and so on. Do not stop to ask for manual labels.
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json, to_html
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
G = build_from_json(extraction)
communities = cluster(G)
cohesion = score_all(G, communities)
labels = {cid: f'Community {cid}' for cid in communities}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
questions = suggest_questions(G, communities, labels)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding='utf-8')
to_json(G, communities, 'graphify-out/graph.json')
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps({'questions': questions, 'gods': gods, 'surprises': surprises, 'labels': labels}, indent=2), encoding='utf-8')
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
raise SystemExit(1)
if 'NO_VIZ' != 'true' and G.number_of_nodes() <= 5000:
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels)
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
"
```
Replace `INPUT_PATH` with the actual path. Replace `NO_VIZ` with `true` if `--no-viz` was given, otherwise `false`.
If the graph is empty, stop and report the failure.
### Step 5 - Save manifest, clean up, and report
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
save_manifest(detect['files'])
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
cost = json.loads(cost_path.read_text()) if cost_path.exists() else {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({'date': datetime.now(timezone.utc).isoformat(), 'input_tokens': input_tok, 'output_tokens': output_tok, 'files': detect.get('total_files', 0)})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2), encoding='utf-8')
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
"
rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_extract.json
```
Tell the user where the outputs were written:
```text
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
```
Then summarize the god nodes, surprising connections, and suggested questions from `GRAPH_REPORT.md` without pasting the entire report.
### Query mode
Before any query-style subcommand, ensure `graphify-out/.graphify_python` exists. If not, recreate it using the Step 1 interpreter detection.
When the user invokes one of these forms, use the CLI directly instead of rebuilding the graph:
- `/graphify query "..."`
- `/graphify path "A" "B"`
- `/graphify explain "X"`
Use:
```bash
$(cat graphify-out/.graphify_python) -m graphify query "QUESTION" --graph graphify-out/graph.json
$(cat graphify-out/.graphify_python) -m graphify path "SOURCE" "TARGET" --graph graphify-out/graph.json
$(cat graphify-out/.graphify_python) -m graphify explain "NODE" --graph graphify-out/graph.json
```
Prefer graph-backed answers over guesses, and cite source files when the graph provides them.
### Kilo-specific rules
- Use the native `Task` tool for semantic extraction fan-out.
- Launch all chunk tasks in the same response so they run in parallel.
- Always use `subagent_type="general"` for extraction chunks.
- After modifying code files during the session, run `graphify update .`.
+3 -3
View File
@@ -5,10 +5,10 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.8.27"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Devin CLI, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Devin CLI, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "gemini", "aider", "kiro", "pi", "devin", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
keywords = ["claude", "claude-code", "codex", "opencode", "kilo", "cursor", "gemini", "aider", "kiro", "pi", "devin", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10"
dependencies = [
"networkx",
@@ -98,7 +98,7 @@ packages = ["graphify"]
include-package-data = false
[tool.setuptools.package-data]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-aider.md", "skill-amp.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md", "skill-kiro.md", "skill-vscode.md", "skill-pi.md", "skill-devin.md"]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-kilo.md", "command-kilo.md", "skill-aider.md", "skill-amp.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md", "skill-kiro.md", "skill-vscode.md", "skill-pi.md", "skill-devin.md"]
[tool.pytest.ini_options]
testpaths = ["tests"]
+210 -2
View File
@@ -10,6 +10,10 @@ PLATFORMS = {
"claude": (".claude/skills/graphify/SKILL.md",),
"codex": (".agents/skills/graphify/SKILL.md",),
"opencode": (".config/opencode/skills/graphify/SKILL.md",),
"kilo": (
".config/kilo/skills/graphify/SKILL.md",
".config/kilo/command/graphify.md",
),
"claw": (".openclaw/skills/graphify/SKILL.md",),
"droid": (".factory/skills/graphify/SKILL.md",),
"trae": (".trae/skills/graphify/SKILL.md",),
@@ -20,6 +24,7 @@ PLATFORMS = {
def _install(tmp_path, platform):
from graphify.__main__ import install
old_cwd = Path.cwd()
try:
os.chdir(tmp_path)
@@ -41,7 +46,9 @@ def test_install_codex(tmp_path):
def test_install_opencode(tmp_path):
_install(tmp_path, "opencode")
assert (tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md").exists()
assert (
tmp_path / ".config" / "opencode" / "skills" / "graphify" / "SKILL.md"
).exists()
def test_install_positional_platform_opencode(tmp_path, monkeypatch):
@@ -199,6 +206,7 @@ def test_install_unknown_platform_exits(tmp_path):
def test_codex_skill_contains_spawn_agent():
"""Codex skill file must reference spawn_agent."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-codex.md").read_text()
assert "spawn_agent" in skill
@@ -224,6 +232,7 @@ def test_codex_agents_install_mentions_dirty_graph_output(tmp_path):
def test_opencode_skill_contains_mention():
"""OpenCode skill file must reference @mention."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-opencode.md").read_text()
assert "@mention" in skill
@@ -231,6 +240,7 @@ def test_opencode_skill_contains_mention():
def test_opencode_skill_uses_opencode_agent_guidance():
"""OpenCode skill must not reference Codex/Claude agent type names."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-opencode.md").read_text()
assert "general-purpose" not in skill
assert 'subagent_type="general-purpose"' not in skill
@@ -242,9 +252,27 @@ def test_opencode_skill_uses_opencode_agent_guidance():
assert "Wait for the user's answer before proceeding" not in skill
def test_kilo_skill_mentions_task_tool():
"""Kilo skill file should use the native Task tool flow."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-kilo.md").read_text()
assert "Task" in skill
def test_kilo_skill_avoids_double_quoted_python_c_fstring_dict_keys():
"""Kilo runs snippets through double-quoted python -c strings."""
import re
import graphify
skill = (Path(graphify.__file__).parent / "skill-kilo.md").read_text()
assert not re.search(r"print\(f'.*\[[\"'][^\"']+[\"']\]", skill)
def test_claw_skill_is_sequential():
"""OpenClaw skill file must describe sequential extraction."""
import graphify
skill = (Path(graphify.__file__).parent / "skill-claw.md").read_text()
assert "sequential" in skill.lower()
assert "spawn_agent" not in skill
@@ -254,11 +282,29 @@ def test_claw_skill_is_sequential():
def test_all_skill_files_exist_in_package():
"""All installable platform skill files must be present in the installed package."""
import graphify
pkg = Path(graphify.__file__).parent
for name in ("skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"):
for name in (
"skill.md",
"skill-codex.md",
"skill-opencode.md",
"skill-kilo.md",
"skill-claw.md",
"skill-windows.md",
"skill-droid.md",
"skill-trae.md",
"skill-kiro.md",
):
assert (pkg / name).exists(), f"Missing: {name}"
def test_kilo_command_file_exists_in_package():
import graphify
pkg = Path(graphify.__file__).parent
assert (pkg / "command-kilo.md").exists()
def test_claude_install_registers_claude_md(tmp_path):
"""Claude platform install writes CLAUDE.md; others do not."""
_install(tmp_path, "claude")
@@ -368,16 +414,33 @@ def test_antigravity_global_uninstall_removes_gemini_config_skill(tmp_path, monk
# --- always-on AGENTS.md install/uninstall tests ---
def _agents_install(tmp_path, platform):
from graphify.__main__ import _agents_install as _install_fn
_install_fn(tmp_path, platform)
def _agents_uninstall(tmp_path, platform=""):
from graphify.__main__ import _agents_uninstall as _uninstall_fn
_uninstall_fn(tmp_path, platform=platform)
def _kilo_install(project_dir, home_dir):
from graphify.__main__ import _kilo_install as _install_fn
with patch("graphify.__main__.Path.home", return_value=home_dir):
_install_fn(project_dir)
def _kilo_uninstall(project_dir, home_dir):
from graphify.__main__ import _kilo_uninstall as _uninstall_fn
with patch("graphify.__main__.Path.home", return_value=home_dir):
_uninstall_fn(project_dir)
def test_codex_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "codex")
agents_md = tmp_path / "AGENTS.md"
@@ -442,6 +505,7 @@ def test_agents_uninstall_no_op_when_not_installed(tmp_path, capsys):
# --- OpenCode plugin tests ---
def test_opencode_agents_install_writes_plugin(tmp_path):
"""opencode install writes .opencode/plugins/graphify.js."""
_agents_install(tmp_path, "opencode")
@@ -456,6 +520,7 @@ def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
config_file = tmp_path / ".opencode" / "opencode.json"
assert config_file.exists()
import json as _json
config = _json.loads(config_file.read_text())
assert any("graphify.js" in p for p in config.get("plugin", []))
@@ -463,6 +528,7 @@ def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
def test_opencode_agents_install_merges_existing_config(tmp_path):
"""opencode install preserves existing .opencode/opencode.json keys."""
import json as _json
config_file = tmp_path / ".opencode" / "opencode.json"
config_file.parent.mkdir(parents=True, exist_ok=True)
config_file.write_text(_json.dumps({"model": "claude-opus-4-5", "plugin": []}))
@@ -475,6 +541,7 @@ def test_opencode_agents_install_merges_existing_config(tmp_path):
def test_opencode_agents_uninstall_removes_plugin(tmp_path):
"""opencode uninstall removes the plugin file and deregisters from opencode.json."""
import json as _json
_agents_install(tmp_path, "opencode")
_agents_uninstall(tmp_path, platform="opencode")
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
@@ -485,11 +552,135 @@ def test_opencode_agents_uninstall_removes_plugin(tmp_path):
assert not any("graphify.js" in p for p in config.get("plugin", []))
def test_kilo_agents_install_writes_agents_md(tmp_path):
_agents_install(tmp_path, "kilo")
assert (tmp_path / "AGENTS.md").exists()
def test_kilo_agents_install_writes_plugin(tmp_path):
_agents_install(tmp_path, "kilo")
plugin = tmp_path / ".kilo" / "plugins" / "graphify.js"
assert plugin.exists()
assert "tool.execute.before" in plugin.read_text()
def test_kilo_agents_install_registers_plugin_in_config(tmp_path):
import json as _json
_agents_install(tmp_path, "kilo")
config_file = tmp_path / ".kilo" / "kilo.json"
assert config_file.exists()
config = _json.loads(config_file.read_text())
assert (
tmp_path / ".kilo" / "plugins" / "graphify.js"
).resolve().as_uri() in config.get("plugin", [])
def test_kilo_agents_install_merges_existing_config(tmp_path):
import json as _json
config_file = tmp_path / ".kilo" / "kilo.json"
config_file.parent.mkdir(parents=True, exist_ok=True)
config_file.write_text(
_json.dumps({"model": "anthropic/claude-sonnet", "plugin": []})
)
_agents_install(tmp_path, "kilo")
config = _json.loads(config_file.read_text())
assert config["model"] == "anthropic/claude-sonnet"
assert (
tmp_path / ".kilo" / "plugins" / "graphify.js"
).resolve().as_uri() in config["plugin"]
def test_kilo_agents_install_preserves_existing_jsonc_config(tmp_path):
import json as _json
config_file = tmp_path / ".kilo" / "kilo.jsonc"
config_file.parent.mkdir(parents=True, exist_ok=True)
original = """// user comment\n{\n // preferred model\n \"model\": \"anthropic/claude-haiku\",\n \"plugin\": []\n}\n"""
config_file.write_text(original)
_agents_install(tmp_path, "kilo")
json_file = tmp_path / ".kilo" / "kilo.json"
config = _json.loads(json_file.read_text())
assert config["model"] == "anthropic/claude-haiku"
assert (
tmp_path / ".kilo" / "plugins" / "graphify.js"
).resolve().as_uri() in config["plugin"]
assert config_file.read_text() == original
def test_kilo_agents_uninstall_preserves_existing_jsonc_config(tmp_path):
import json as _json
config_file = tmp_path / ".kilo" / "kilo.jsonc"
config_file.parent.mkdir(parents=True, exist_ok=True)
original = """// user comment\n{\n \"model\": \"anthropic/claude-haiku\",\n \"plugin\": []\n}\n"""
config_file.write_text(original)
_agents_install(tmp_path, "kilo")
_agents_uninstall(tmp_path, platform="kilo")
json_file = tmp_path / ".kilo" / "kilo.json"
config = _json.loads(json_file.read_text())
assert config_file.read_text() == original
assert (
tmp_path / ".kilo" / "plugins" / "graphify.js"
).resolve().as_uri() not in config.get("plugin", [])
def test_kilo_agents_install_idempotent(tmp_path):
import json as _json
_agents_install(tmp_path, "kilo")
_agents_install(tmp_path, "kilo")
content = (tmp_path / "AGENTS.md").read_text()
config = _json.loads((tmp_path / ".kilo" / "kilo.json").read_text())
plugin_uri = (tmp_path / ".kilo" / "plugins" / "graphify.js").resolve().as_uri()
assert content.count("## graphify") == 1
assert config["plugin"].count(plugin_uri) == 1
def test_kilo_install_writes_global_and_project_artifacts(tmp_path):
home_dir = tmp_path / "home"
project_dir = tmp_path / "project"
project_dir.mkdir()
home_dir.mkdir()
_kilo_install(project_dir, home_dir)
assert (home_dir / ".config" / "kilo" / "skills" / "graphify" / "SKILL.md").exists()
assert (home_dir / ".config" / "kilo" / "command" / "graphify.md").exists()
assert (project_dir / "AGENTS.md").exists()
assert (project_dir / ".kilo" / "plugins" / "graphify.js").exists()
def test_kilo_uninstall_removes_plugin_registration_and_command(tmp_path):
import json as _json
home_dir = tmp_path / "home"
project_dir = tmp_path / "project"
project_dir.mkdir()
home_dir.mkdir()
_kilo_install(project_dir, home_dir)
_kilo_uninstall(project_dir, home_dir)
assert not (home_dir / ".config" / "kilo" / "command" / "graphify.md").exists()
assert not (
home_dir / ".config" / "kilo" / "skills" / "graphify" / "SKILL.md"
).exists()
assert not (project_dir / ".kilo" / "plugins" / "graphify.js").exists()
config_file = project_dir / ".kilo" / "kilo.json"
if config_file.exists():
config = _json.loads(config_file.read_text())
assert (
project_dir / ".kilo" / "plugins" / "graphify.js"
).resolve().as_uri() not in config.get("plugin", [])
# ── Cursor ────────────────────────────────────────────────────────────────────
def test_cursor_install_writes_rule(tmp_path):
"""cursor install writes .cursor/rules/graphify.mdc."""
from graphify.__main__ import _cursor_install
_cursor_install(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
assert rule.exists()
@@ -501,6 +692,7 @@ def test_cursor_install_writes_rule(tmp_path):
def test_cursor_install_idempotent(tmp_path):
"""cursor install does not overwrite an existing rule file."""
from graphify.__main__ import _cursor_install
_cursor_install(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
original = rule.read_text()
@@ -511,6 +703,7 @@ def test_cursor_install_idempotent(tmp_path):
def test_cursor_uninstall_removes_rule(tmp_path):
"""cursor uninstall removes the rule file."""
from graphify.__main__ import _cursor_install, _cursor_uninstall
_cursor_install(tmp_path)
_cursor_uninstall(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
@@ -520,51 +713,64 @@ def test_cursor_uninstall_removes_rule(tmp_path):
def test_cursor_uninstall_noop_if_not_installed(tmp_path):
"""cursor uninstall does nothing if rule was never written."""
from graphify.__main__ import _cursor_uninstall
_cursor_uninstall(tmp_path) # should not raise
# ── Gemini CLI ────────────────────────────────────────────────────────────────
def test_gemini_install_writes_gemini_md(tmp_path):
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
md = tmp_path / "GEMINI.md"
assert md.exists()
assert "graphify-out/GRAPH_REPORT.md" in md.read_text()
def test_gemini_install_writes_hook(tmp_path):
import json as _json
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
settings = _json.loads((tmp_path / ".gemini" / "settings.json").read_text())
hooks = settings["hooks"]["BeforeTool"]
assert any("graphify" in str(h) for h in hooks)
def test_gemini_install_idempotent(tmp_path):
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
gemini_install(tmp_path)
md = tmp_path / "GEMINI.md"
assert md.read_text().count("## graphify") == 1
def test_gemini_install_merges_existing_gemini_md(tmp_path):
from graphify.__main__ import gemini_install
(tmp_path / "GEMINI.md").write_text("# My project rules\n")
gemini_install(tmp_path)
content = (tmp_path / "GEMINI.md").read_text()
assert "# My project rules" in content
assert "graphify-out/GRAPH_REPORT.md" in content
def test_gemini_uninstall_removes_section(tmp_path):
from graphify.__main__ import gemini_install, gemini_uninstall
gemini_install(tmp_path)
gemini_uninstall(tmp_path)
md = tmp_path / "GEMINI.md"
assert not md.exists()
def test_gemini_uninstall_removes_hook(tmp_path):
import json as _json
from graphify.__main__ import gemini_install, gemini_uninstall
gemini_install(tmp_path)
gemini_uninstall(tmp_path)
settings_path = tmp_path / ".gemini" / "settings.json"
@@ -573,6 +779,8 @@ def test_gemini_uninstall_removes_hook(tmp_path):
hooks = settings.get("hooks", {}).get("BeforeTool", [])
assert not any("graphify" in str(h) for h in hooks)
def test_gemini_uninstall_noop_if_not_installed(tmp_path):
from graphify.__main__ import gemini_uninstall
gemini_uninstall(tmp_path) # should not raise