Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5843ffc277 | ||
|
|
b326aa83c4 | ||
|
|
e915a877e2 | ||
|
|
64f38acf3e | ||
|
|
e4bdcc2487 | ||
|
|
8981f7c8ef | ||
|
|
4bc20527c3 | ||
|
|
85e713644e | ||
|
|
52ad45bd27 | ||
|
|
86d6d9317f | ||
|
|
d9b2928da1 | ||
|
|
f8fd8f8479 | ||
|
|
f938714df0 | ||
|
|
7cb639ae5d | ||
|
|
39bf0a3f80 | ||
|
|
e241ce96cf | ||
|
|
dbde78ca03 | ||
|
|
9c3d0fa517 | ||
|
|
69d4d7e9c3 | ||
|
|
2a35d7fd38 | ||
|
|
ed4f12ab82 | ||
|
|
de136676ef | ||
|
|
339d9783fb | ||
|
|
4738e88aaf | ||
|
|
81b6e7d7b4 | ||
|
|
f0ebd07fd5 | ||
|
|
2fd15115d9 | ||
|
|
0973af2be0 | ||
|
|
3bf096438f | ||
|
|
45643380d1 | ||
|
|
0f30cfb6ad | ||
|
|
cc53e00bcc | ||
|
|
3f5df2513b | ||
|
|
6892fd9309 | ||
|
|
9c2275ad82 | ||
|
|
d67436c065 | ||
|
|
f8a5328197 | ||
|
|
8171abf583 | ||
|
|
c24cde9d9e | ||
|
|
d0d8d80581 | ||
|
|
8666c6994c | ||
|
|
72d9779aaf | ||
|
|
1805813a56 | ||
|
|
a507c97822 | ||
|
|
826fd0ece1 | ||
|
|
bdfb917935 | ||
|
|
8a474eb1b3 | ||
|
|
022feee5fb | ||
|
|
2a4608cbb0 | ||
|
|
c8a9a6cdbc | ||
|
|
b2523fcdec | ||
|
|
429e46a665 | ||
|
|
7ec92ecc6d | ||
|
|
dc41eceb9e | ||
|
|
01fb51ba78 | ||
|
|
ac265ec495 | ||
|
|
b85184002c | ||
|
|
50afb69859 | ||
|
|
2993cce8b2 | ||
|
|
521487aa2e | ||
|
|
b00813bcb2 | ||
|
|
e737f5bf58 | ||
|
|
1fbcaf840f | ||
|
|
1dd4c41413 | ||
|
|
4210de270f | ||
|
|
f8c91a987f | ||
|
|
6724350665 | ||
|
|
5ab8eb34c5 | ||
|
|
8070909c04 | ||
|
|
d1808bab8c | ||
|
|
b23e5de5a1 | ||
|
|
457e2a1b1b | ||
|
|
8c17230586 | ||
|
|
1cb882a156 | ||
|
|
68abce8a04 | ||
|
|
cede5b6ca6 | ||
|
|
75c08a5b32 | ||
|
|
899bdd09e4 | ||
|
|
74cb9ce197 | ||
|
|
4b87e67ff3 | ||
|
|
1929495a99 | ||
|
|
2a7d2f4fdc | ||
|
|
db07e9f93a | ||
|
|
53d0ceb471 | ||
|
|
de6e341b07 | ||
|
|
cf5d721bee | ||
|
|
e3adc0417a | ||
|
|
4ff85debf1 | ||
|
|
2ea824533c | ||
|
|
6b6d90ac0f | ||
|
|
8b96d05da6 | ||
|
|
6d39432058 | ||
|
|
9c829d7a2e | ||
|
|
32986da448 | ||
|
|
16e36c7337 | ||
|
|
f18ea01530 | ||
|
|
efefd3960a | ||
|
|
244478bcee | ||
|
|
df26f85648 | ||
|
|
38381597d6 | ||
|
|
df77d5f8ce | ||
|
|
c99ac6c2df | ||
|
|
45e407db35 | ||
|
|
95f6c104d4 | ||
|
|
ca842472e5 | ||
|
|
bb2049cec1 | ||
|
|
036d904e31 | ||
|
|
e5760e6b03 | ||
|
|
2a550a3fe6 | ||
|
|
be2058d5d5 | ||
|
|
33482b0827 | ||
|
|
c3817d6144 | ||
|
|
91cbc74bb1 | ||
|
|
9cfaa3339b | ||
|
|
267f8d28c4 | ||
|
|
dbcb1253e8 | ||
|
|
7ff7bd2e8f | ||
|
|
1896379283 | ||
|
|
b4180a50dc | ||
|
|
a25f7629bd | ||
|
|
359ef86dd4 | ||
|
|
2b3accfe66 | ||
|
|
21a081b514 | ||
|
|
76bbb37c74 | ||
|
|
a87be4143a | ||
|
|
f937fc6ce1 | ||
|
|
22f79db72f | ||
|
|
ba7c395ce3 |
No files matched your search
+6
-1
@@ -21,4 +21,9 @@ skills/
|
||||
docs/superpowers/
|
||||
.vscode/
|
||||
openspec/
|
||||
uv.lock
|
||||
uv.lock
|
||||
# Local benchmark scripts — never commit
|
||||
scripts/run_k2_*.py
|
||||
scripts/llm.py
|
||||
scripts/benchmark_kimi*.json
|
||||
scripts/benchmark_kimi*.py
|
||||
@@ -329,6 +329,7 @@ graphify add https://... --author "Name" --contributor "Name"
|
||||
|
||||
# incremental update and maintenance
|
||||
graphify watch ./src # auto-rebuild on code changes
|
||||
graphify check-update ./src # check if semantic re-extraction is pending (cron-safe)
|
||||
graphify update ./src # re-extract code files, no LLM needed
|
||||
graphify cluster-only ./my-project # rerun clustering on existing graph.json
|
||||
```
|
||||
@@ -337,7 +338,7 @@ Works with any mix of file types:
|
||||
|
||||
| Type | Extensions | Extraction |
|
||||
|------|-----------|------------|
|
||||
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + docstring/comment rationale |
|
||||
| Code | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .zig .ps1 .ex .exs .m .mm .jl .vue .svelte` | AST via tree-sitter + call-graph (cross-file for all languages) + Java extends/implements + docstring/comment rationale |
|
||||
| Docs | `.md .mdx .html .txt .rst` | Concepts + relationships + design rationale via Claude |
|
||||
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
|
||||
| Papers | `.pdf` | Citation mining + concept extraction |
|
||||
|
||||
@@ -643,7 +643,7 @@ export const GraphifyPlugin = async ({ directory }) => {
|
||||
"""
|
||||
|
||||
_OPENCODE_PLUGIN_PATH = Path(".opencode") / "plugins" / "graphify.js"
|
||||
_OPENCODE_CONFIG_PATH = Path("opencode.json")
|
||||
_OPENCODE_CONFIG_PATH = Path(".opencode") / "opencode.json"
|
||||
|
||||
|
||||
def _install_opencode_plugin(project_dir: Path) -> None:
|
||||
@@ -940,6 +940,7 @@ def main() -> None:
|
||||
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)")
|
||||
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
|
||||
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
|
||||
print(" hook uninstall remove git hooks")
|
||||
@@ -1351,6 +1352,13 @@ def main() -> None:
|
||||
print("Nothing to update or rebuild failed — check output above.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
elif cmd == "check-update":
|
||||
if len(sys.argv) < 3:
|
||||
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 == "benchmark":
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
graph_path = sys.argv[2] if len(sys.argv) > 2 else "graphify-out/graph.json"
|
||||
|
||||
@@ -46,6 +46,12 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
# NetworkX <= 3.1 serialised edges as "links"; remap to "edges" for compatibility.
|
||||
if "edges" not in extraction and "links" in extraction:
|
||||
extraction = dict(extraction, edges=extraction["links"])
|
||||
|
||||
# Canonicalize legacy node/edge schema before validation.
|
||||
for node in extraction.get("nodes", []):
|
||||
if isinstance(node, dict) and "source" in node and "source_file" not in node:
|
||||
node["source_file"] = node.pop("source")
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
|
||||
real_errors = [e for e in errors if "does not match any node id" not in e]
|
||||
|
||||
+15
-5
@@ -344,12 +344,16 @@ def to_html(
|
||||
communities: dict[int, list[str]],
|
||||
output_path: str,
|
||||
community_labels: dict[int, str] | None = None,
|
||||
member_counts: dict[int, int] | None = None,
|
||||
) -> None:
|
||||
"""Generate an interactive vis.js HTML visualization of the graph.
|
||||
|
||||
Features: node size by degree, click-to-inspect panel, search box,
|
||||
community filter, physics clustering by community, confidence-styled edges.
|
||||
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
|
||||
|
||||
If member_counts is provided (aggregated community view), node sizes are
|
||||
based on community member counts rather than graph degree.
|
||||
"""
|
||||
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
|
||||
raise ValueError(
|
||||
@@ -360,6 +364,7 @@ def to_html(
|
||||
node_community = _node_community_map(communities)
|
||||
degree = dict(G.degree())
|
||||
max_deg = max(degree.values(), default=1) or 1
|
||||
max_mc = (max(member_counts.values(), default=1) or 1) if member_counts else 1
|
||||
|
||||
# Build nodes list for vis.js
|
||||
vis_nodes = []
|
||||
@@ -368,9 +373,14 @@ def to_html(
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
label = sanitize_label(data.get("label", node_id))
|
||||
deg = degree.get(node_id, 1)
|
||||
size = 10 + 30 * (deg / max_deg)
|
||||
# Only show label for high-degree nodes by default; others show on hover
|
||||
font_size = 12 if deg >= max_deg * 0.15 else 0
|
||||
if member_counts:
|
||||
mc = member_counts.get(cid, 1)
|
||||
size = 10 + 30 * (mc / max_mc)
|
||||
font_size = 12
|
||||
else:
|
||||
size = 10 + 30 * (deg / max_deg)
|
||||
# Only show label for high-degree nodes by default; others show on hover
|
||||
font_size = 12 if deg >= max_deg * 0.15 else 0
|
||||
vis_nodes.append({
|
||||
"id": node_id,
|
||||
"label": label,
|
||||
@@ -406,7 +416,7 @@ def to_html(
|
||||
for cid in sorted((community_labels or {}).keys()):
|
||||
color = COMMUNITY_COLORS[cid % len(COMMUNITY_COLORS)]
|
||||
lbl = _html.escape(sanitize_label((community_labels or {}).get(cid, f"Community {cid}")))
|
||||
n = len(communities.get(cid, []))
|
||||
n = member_counts.get(cid, len(communities.get(cid, []))) if member_counts else len(communities.get(cid, []))
|
||||
legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n})
|
||||
|
||||
# Escape </script> sequences so embedded JSON cannot break out of the script tag
|
||||
@@ -831,7 +841,7 @@ def to_canvas(
|
||||
canvas_nodes.append({
|
||||
"id": f"n_{node_id}",
|
||||
"type": "file",
|
||||
"file": f"graphify/obsidian/{fname}.md",
|
||||
"file": f"{fname}.md",
|
||||
"x": nx_x,
|
||||
"y": nx_y,
|
||||
"width": 180,
|
||||
|
||||
@@ -803,6 +803,49 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
seen_ids.add(base_nid)
|
||||
add_edge(class_nid, base_nid, "inherits", line)
|
||||
|
||||
# Java-specific: extends (superclass) / implements (interfaces) / interface-extends
|
||||
if config.ts_module == "tree_sitter_java":
|
||||
def _emit_java_parent(base_name: str, rel: str, at_line: int) -> None:
|
||||
if not base_name:
|
||||
return
|
||||
base_nid = _make_id(stem, base_name)
|
||||
if base_nid not in seen_ids:
|
||||
base_nid = _make_id(base_name)
|
||||
if base_nid not in seen_ids:
|
||||
nodes.append({
|
||||
"id": base_nid,
|
||||
"label": base_name,
|
||||
"file_type": "code",
|
||||
"source_file": "",
|
||||
"source_location": "",
|
||||
})
|
||||
seen_ids.add(base_nid)
|
||||
add_edge(class_nid, base_nid, rel, at_line)
|
||||
|
||||
sup = node.child_by_field_name("superclass")
|
||||
if sup is not None:
|
||||
for sub in sup.children:
|
||||
if sub.type == "type_identifier":
|
||||
_emit_java_parent(_read_text(sub, source), "extends", line)
|
||||
break
|
||||
|
||||
ifs = node.child_by_field_name("interfaces")
|
||||
if ifs is not None:
|
||||
for sub in ifs.children:
|
||||
if sub.type == "type_list":
|
||||
for tid in sub.children:
|
||||
if tid.type == "type_identifier":
|
||||
_emit_java_parent(_read_text(tid, source), "implements", line)
|
||||
|
||||
if t == "interface_declaration":
|
||||
for child in node.children:
|
||||
if child.type == "extends_interfaces":
|
||||
for sub in child.children:
|
||||
if sub.type == "type_list":
|
||||
for tid in sub.children:
|
||||
if tid.type == "type_identifier":
|
||||
_emit_java_parent(_read_text(tid, source), "extends", line)
|
||||
|
||||
# Find body and recurse
|
||||
body = _find_body(node, config)
|
||||
if body:
|
||||
@@ -2664,6 +2707,91 @@ def _resolve_cross_file_imports(
|
||||
return new_edges
|
||||
|
||||
|
||||
def _resolve_cross_file_java_imports(
|
||||
per_file: list[dict],
|
||||
paths: list[Path],
|
||||
) -> list[dict]:
|
||||
"""Two-pass Java import resolution.
|
||||
|
||||
Pass 1: build a global index {ClassName: [node_id, ...]} across all Java nodes.
|
||||
Pass 2: re-parse each Java file; for every `import a.b.C;`, resolve C against
|
||||
the index. Wildcard and stdlib imports produce no edge.
|
||||
"""
|
||||
try:
|
||||
import tree_sitter_java as tsjava
|
||||
from tree_sitter import Language, Parser
|
||||
except ImportError:
|
||||
return []
|
||||
|
||||
language = Language(tsjava.language())
|
||||
parser = Parser(language)
|
||||
|
||||
# Pass 1: class-name → node_id index (only internal, uppercase-starting names)
|
||||
name_to_ids: dict[str, list[str]] = {}
|
||||
for file_result in per_file:
|
||||
for node in file_result.get("nodes", []):
|
||||
label = node.get("label", "")
|
||||
nid = node.get("id", "")
|
||||
src = node.get("source_file", "")
|
||||
if not label or not nid or not src:
|
||||
continue
|
||||
if label.endswith(")") or label.endswith(".java"):
|
||||
continue
|
||||
if not label[0].isalpha() or not label[0].isupper():
|
||||
continue
|
||||
name_to_ids.setdefault(label, []).append(nid)
|
||||
|
||||
# Pass 2: resolve imports to real node IDs
|
||||
new_edges: list[dict] = []
|
||||
seen_pairs: set[tuple[str, str]] = set()
|
||||
for path in paths:
|
||||
file_nid = _make_id(path.stem)
|
||||
try:
|
||||
source = path.read_bytes()
|
||||
tree = parser.parse(source)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
def walk(n) -> None:
|
||||
if n.type == "import_declaration":
|
||||
raw = _read_text(n, source).strip()
|
||||
body = raw[len("import"):].strip().rstrip(";").strip()
|
||||
if body.startswith("static "):
|
||||
body = body[len("static "):].strip()
|
||||
if body.endswith(".*"):
|
||||
return
|
||||
parts = body.split(".")
|
||||
if not parts:
|
||||
return
|
||||
last = parts[-1]
|
||||
if last and last[0].islower() and len(parts) >= 2:
|
||||
last = parts[-2]
|
||||
at_line = n.start_point[0] + 1
|
||||
for tgt_nid in name_to_ids.get(last, []):
|
||||
if tgt_nid == file_nid:
|
||||
continue
|
||||
key = (file_nid, tgt_nid)
|
||||
if key in seen_pairs:
|
||||
continue
|
||||
seen_pairs.add(key)
|
||||
new_edges.append({
|
||||
"source": file_nid,
|
||||
"target": tgt_nid,
|
||||
"relation": "imports",
|
||||
"confidence": "EXTRACTED",
|
||||
"confidence_score": 1.0,
|
||||
"source_file": str(path),
|
||||
"source_location": f"L{at_line}",
|
||||
"weight": 1.0,
|
||||
})
|
||||
for child in n.children:
|
||||
walk(child)
|
||||
|
||||
walk(tree.root_node)
|
||||
|
||||
return new_edges
|
||||
|
||||
|
||||
def extract_objc(path: Path) -> dict:
|
||||
"""Extract interfaces, implementations, protocols, methods, and imports from .m/.mm/.h files."""
|
||||
try:
|
||||
@@ -3204,6 +3332,16 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("Cross-file import resolution failed, skipping: %s", exc)
|
||||
|
||||
# Cross-file Java import resolution
|
||||
java_paths = [p for p in paths if p.suffix == ".java"]
|
||||
if java_paths:
|
||||
java_results = [r for r, p in zip(per_file, paths) if p.suffix == ".java"]
|
||||
try:
|
||||
all_edges.extend(_resolve_cross_file_java_imports(java_results, java_paths))
|
||||
except Exception as exc:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("Java cross-file import resolution failed, skipping: %s", exc)
|
||||
|
||||
# Cross-file call resolution for all languages
|
||||
# Each extractor saved unresolved calls in raw_calls. Now that we have all
|
||||
# nodes from all files, resolve any callee that exists in another file.
|
||||
|
||||
+4
-1
@@ -13,7 +13,10 @@ _PYTHON_DETECT = """\
|
||||
# Detect the correct Python interpreter (handles pipx, venv, system installs)
|
||||
GRAPHIFY_BIN=$(command -v graphify 2>/dev/null)
|
||||
if [ -n "$GRAPHIFY_BIN" ]; then
|
||||
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//')
|
||||
case "$GRAPHIFY_BIN" in
|
||||
*.exe) _SHEBANG="" ;;
|
||||
*) _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | sed 's/^#![[:space:]]*//') ;;
|
||||
esac
|
||||
case "$_SHEBANG" in
|
||||
*/env\\ *) GRAPHIFY_PYTHON="${_SHEBANG#*/env }" ;;
|
||||
*) GRAPHIFY_PYTHON="$_SHEBANG" ;;
|
||||
|
||||
+143
-89
@@ -72,22 +72,24 @@ fi
|
||||
# Write interpreter path for all subsequent steps
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
# Force UTF-8 I/O on Windows (prevents garbled CJK/non-ASCII output)
|
||||
export PYTHONUTF8=1
|
||||
```
|
||||
|
||||
If the import succeeds, print nothing and move straight to Step 2.
|
||||
|
||||
**In every subsequent bash block, replace `python3` with `$(cat .graphify_python)` to use the correct interpreter.**
|
||||
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
|
||||
|
||||
### Step 2 - Detect files
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(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_detect.json
|
||||
" > graphify-out/.graphify_detect.json
|
||||
```
|
||||
|
||||
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
|
||||
@@ -168,23 +170,23 @@ Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is determin
|
||||
For any code files detected, run AST extraction in parallel with Part B subagents:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.extract import collect_files, extract
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
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)
|
||||
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
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')
|
||||
"
|
||||
```
|
||||
@@ -196,7 +198,7 @@ else:
|
||||
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
|
||||
|
||||
Before dispatching subagents, print a timing estimate:
|
||||
- Load `total_words` and file counts from `.graphify_detect.json`
|
||||
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
|
||||
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25)
|
||||
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
|
||||
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
|
||||
@@ -206,28 +208,28 @@ Before dispatching subagents, print a timing estimate:
|
||||
Before dispatching any subagents, check which files already have cached extraction results:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
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_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
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')
|
||||
"
|
||||
```
|
||||
|
||||
Only dispatch subagents for files listed in `.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly.
|
||||
|
||||
**Step B1 - Split into chunks**
|
||||
|
||||
Load files from `.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.
|
||||
Load files from `graphify-out/.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.
|
||||
|
||||
**Step B2 - Dispatch ALL subagents in a single message (OpenCode)**
|
||||
|
||||
@@ -241,7 +243,7 @@ Dispatch one `@mention` per chunk — ALL in the same response:
|
||||
@agent Chunk 2 of TOTAL_CHUNKS: [next chunk]
|
||||
```
|
||||
|
||||
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `.graphify_semantic_new.json`.
|
||||
Wait for all agents to return. Parse each response as JSON. Accumulate nodes/edges/hyperedges across all results and write to `graphify-out/.graphify_semantic_new.json`.
|
||||
|
||||
The extraction prompt each agent receives (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE):
|
||||
|
||||
@@ -310,25 +312,25 @@ If more than half the chunks failed or are missing, stop and tell the user to re
|
||||
|
||||
Save new results to cache:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
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':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
|
||||
print(f'Cached {saved} files')
|
||||
"
|
||||
```
|
||||
|
||||
Merge cached + new results into `.graphify_semantic.json`:
|
||||
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
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':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
@@ -347,21 +349,21 @@ merged = {
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
|
||||
"
|
||||
```
|
||||
Clean up temp files: `rm -f .graphify_cached.json .graphify_uncached.txt .graphify_semantic_new.json`
|
||||
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
|
||||
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
ast = json.loads(Path('.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('.graphify_semantic.json').read_text())
|
||||
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text())
|
||||
|
||||
# Merge: AST nodes first, semantic nodes deduplicated by id
|
||||
seen = {n['id'] for n in ast['nodes']}
|
||||
@@ -380,7 +382,7 @@ merged = {
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
total = len(merged_nodes)
|
||||
edges = len(merged_edges)
|
||||
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
|
||||
@@ -391,7 +393,7 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
|
||||
|
||||
```bash
|
||||
mkdir -p graphify-out
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
@@ -400,8 +402,8 @@ from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
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)
|
||||
@@ -424,7 +426,7 @@ analysis = {
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
@@ -439,12 +441,12 @@ Replace INPUT_PATH with the actual path.
|
||||
|
||||
### Step 5 - Label communities
|
||||
|
||||
Read `.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
|
||||
|
||||
Then regenerate the report and save the labels for the visualizer:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import score_all
|
||||
@@ -452,9 +454,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
|
||||
from graphify.report import generate
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -469,7 +471,7 @@ questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
print('Report updated with community labels')
|
||||
"
|
||||
```
|
||||
@@ -484,15 +486,15 @@ Replace INPUT_PATH with the actual path.
|
||||
If `--obsidian` was given:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_obsidian, to_canvas
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -515,40 +517,92 @@ print(' _COMMUNITY_* - overview notes with cohesion scores and dataview queries
|
||||
Generate the HTML graph (always, unless `--no-viz`):
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
if G.number_of_nodes() > 5000:
|
||||
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
|
||||
NODE_LIMIT = 5000
|
||||
if G.number_of_nodes() > NODE_LIMIT:
|
||||
from collections import Counter
|
||||
print(f'Graph has {G.number_of_nodes()} nodes (above {NODE_LIMIT} limit). Building aggregated community view...')
|
||||
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
|
||||
import networkx as nx_meta
|
||||
meta = nx_meta.Graph()
|
||||
for cid, members in communities.items():
|
||||
meta.add_node(str(cid), label=labels.get(cid, f'Community {cid}'))
|
||||
edge_counts = Counter()
|
||||
for u, v in G.edges():
|
||||
cu, cv = node_to_community.get(u), node_to_community.get(v)
|
||||
if cu is not None and cv is not None and cu != cv:
|
||||
edge_counts[(min(cu, cv), max(cu, cv))] += 1
|
||||
for (cu, cv), w in edge_counts.items():
|
||||
meta.add_edge(str(cu), str(cv), weight=w, relation=f'{w} cross-community edges', confidence='AGGREGATED')
|
||||
if meta.number_of_nodes() > 1:
|
||||
meta_communities = {cid: [str(cid)] for cid in communities}
|
||||
member_counts = {cid: len(members) for cid, members in communities.items()}
|
||||
to_html(meta, meta_communities, 'graphify-out/graph.html', community_labels=labels or None, member_counts=member_counts)
|
||||
print(f'graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)')
|
||||
print('Tip: run with --obsidian for full node-level detail.')
|
||||
else:
|
||||
print('Single community — aggregated view not useful. Skipping graph.html.')
|
||||
else:
|
||||
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
|
||||
print('graph.html written - open in any browser, no server needed')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 6b - Wiki (only if --wiki flag)
|
||||
|
||||
**Only run this step if `--wiki` was explicitly given in the original command.**
|
||||
|
||||
Run this before Step 9 (cleanup) so `graphify-out/.graphify_labels.json` is still available.
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.wiki import to_wiki
|
||||
from graphify.analyze import god_nodes
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
gods = god_nodes(G)
|
||||
|
||||
n = to_wiki(G, communities, 'graphify-out/wiki', community_labels=labels or None, cohesion=cohesion, god_nodes_data=gods)
|
||||
print(f'Wiki: {n} articles written to graphify-out/wiki/')
|
||||
print(' graphify-out/wiki/index.md -> agent entry point')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
|
||||
|
||||
**If `--neo4j`** - generate a Cypher file for manual import:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_cypher
|
||||
from pathlib import Path
|
||||
|
||||
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()))
|
||||
G = build_from_json(json.loads(Path('graphify-out/.graphify_extract.json').read_text()))
|
||||
to_cypher(G, 'graphify-out/cypher.txt')
|
||||
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
|
||||
"
|
||||
@@ -557,15 +611,15 @@ print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt'
|
||||
**If `--neo4j-push <uri>`** - push directly to a running Neo4j instance. Ask the user for credentials if not provided:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import push_to_neo4j
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
|
||||
@@ -579,15 +633,15 @@ Replace `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` with actual values. Default
|
||||
### Step 7b - SVG export (only if --svg flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_svg
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('graphify-out/.graphify_labels.json').read_text()) if Path('graphify-out/.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -601,14 +655,14 @@ print('graph.svg written - embeds in Obsidian, Notion, GitHub READMEs')
|
||||
### Step 7c - GraphML export (only if --graphml flag)
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -640,15 +694,15 @@ To configure in Claude Desktop, add to `claude_desktop_config.json`:
|
||||
|
||||
### Step 8 - Token reduction benchmark (only if total_words > 5000)
|
||||
|
||||
If `total_words` from `.graphify_detect.json` is greater than 5,000, run:
|
||||
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
|
||||
print_benchmark(result)
|
||||
"
|
||||
@@ -661,18 +715,18 @@ Print the output directly in chat. If `total_words <= 5000`, skip silently - the
|
||||
### Step 9 - Save manifest, update cost tracker, clean up, and report
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
save_manifest(detect['files'])
|
||||
|
||||
# Update cumulative cost tracker
|
||||
extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
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)
|
||||
|
||||
@@ -695,7 +749,7 @@ cost_path.write_text(json.dumps(cost, indent=2))
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
"
|
||||
rm -f .graphify_detect.json .graphify_extract.json .graphify_ast.json .graphify_semantic.json .graphify_analysis.json .graphify_labels.json .graphify_chunk_*.json
|
||||
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_labels.json graphify-out/.graphify_chunk_*.json
|
||||
rm -f graphify-out/.needs_update 2>/dev/null || true
|
||||
```
|
||||
|
||||
@@ -735,7 +789,7 @@ The graph is the map. Your job after the pipeline is to be the guide.
|
||||
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.detect import detect_incremental, save_manifest
|
||||
from pathlib import Path
|
||||
@@ -743,7 +797,7 @@ from pathlib import Path
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
|
||||
if new_total == 0:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
@@ -754,11 +808,11 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
|
||||
result = json.loads(open('graphify-out/.graphify_incremental.json').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
@@ -774,7 +828,7 @@ If `code_only` is False (any changed file is a doc/paper/image): run the full St
|
||||
Then:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_json
|
||||
@@ -787,7 +841,7 @@ existing_data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G_existing = json_graph.node_link_graph(existing_data, edges='links')
|
||||
|
||||
# Load new extraction
|
||||
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extraction)
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
@@ -801,7 +855,7 @@ Then run Steps 4–8 on the merged graph as normal.
|
||||
After Step 4, show the graph diff:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from graphify.analyze import graph_diff
|
||||
from graphify.build import build_from_json
|
||||
@@ -810,8 +864,8 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load old graph (before update) from backup written before merge
|
||||
old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text()) if Path('graphify-out/.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extract)
|
||||
|
||||
if old_data:
|
||||
@@ -825,8 +879,8 @@ if old_data:
|
||||
"
|
||||
```
|
||||
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json .graphify_old.json`
|
||||
Clean up after: `rm -f .graphify_old.json`
|
||||
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
|
||||
Clean up after: `rm -f graphify-out/.graphify_old.json`
|
||||
|
||||
---
|
||||
|
||||
@@ -835,7 +889,7 @@ Clean up after: `rm -f .graphify_old.json`
|
||||
Skip Steps 1–3. Load the existing graph from `graphify-out/graph.json` and re-run clustering:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
@@ -868,7 +922,7 @@ analysis = {
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
}
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
print(f'Re-clustered: {len(communities)} communities')
|
||||
"
|
||||
```
|
||||
@@ -888,7 +942,7 @@ Two traversal modes - choose based on the question:
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -906,7 +960,7 @@ Load `graphify-out/graph.json`, then:
|
||||
5. If the graph lacks enough information, say so - do not hallucinate edges.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
@@ -997,7 +1051,7 @@ Replace `QUESTION` with the user's actual question, `MODE` with `bfs` or `dfs`,
|
||||
After writing the answer, save it back into the graph so it improves future queries:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
|
||||
```
|
||||
|
||||
Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
|
||||
@@ -1010,7 +1064,7 @@ Find the shortest path between two named concepts in the graph.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1020,7 +1074,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1072,7 +1126,7 @@ Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1083,7 +1137,7 @@ Give a plain-language explanation of a single node - everything connected to it.
|
||||
|
||||
First check the graph exists:
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
from pathlib import Path
|
||||
if not Path('graphify-out/graph.json').exists():
|
||||
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
|
||||
@@ -1093,7 +1147,7 @@ if not Path('graphify-out/graph.json').exists():
|
||||
If it fails, stop and tell the user to run `/graphify <path>` first.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json, sys
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
@@ -1138,7 +1192,7 @@ Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sent
|
||||
After writing the explanation, save it back:
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1148,7 +1202,7 @@ $(cat .graphify_python) -m graphify save-result --question "Explain NODE_NAME" -
|
||||
Fetch a URL and add it to the corpus, then update the graph.
|
||||
|
||||
```bash
|
||||
$(cat .graphify_python) -c "
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys
|
||||
from graphify.ingest import ingest
|
||||
from pathlib import Path
|
||||
|
||||
+24
-2
@@ -550,8 +550,30 @@ G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
labels = {int(k): v for k, v in labels_raw.items()}
|
||||
|
||||
if G.number_of_nodes() > 5000:
|
||||
print(f'Graph has {G.number_of_nodes()} nodes - too large for HTML viz. Use Obsidian vault instead.')
|
||||
NODE_LIMIT = 5000
|
||||
if G.number_of_nodes() > NODE_LIMIT:
|
||||
from collections import Counter
|
||||
print(f'Graph has {G.number_of_nodes()} nodes (above {NODE_LIMIT} limit). Building aggregated community view...')
|
||||
node_to_community = {nid: cid for cid, members in communities.items() for nid in members}
|
||||
import networkx as nx_meta
|
||||
meta = nx_meta.Graph()
|
||||
for cid, members in communities.items():
|
||||
meta.add_node(str(cid), label=labels.get(cid, f'Community {cid}'))
|
||||
edge_counts = Counter()
|
||||
for u, v in G.edges():
|
||||
cu, cv = node_to_community.get(u), node_to_community.get(v)
|
||||
if cu is not None and cv is not None and cu != cv:
|
||||
edge_counts[(min(cu, cv), max(cu, cv))] += 1
|
||||
for (cu, cv), w in edge_counts.items():
|
||||
meta.add_edge(str(cu), str(cv), weight=w, relation=f'{w} cross-community edges', confidence='AGGREGATED')
|
||||
if meta.number_of_nodes() > 1:
|
||||
meta_communities = {cid: [str(cid)] for cid in communities}
|
||||
member_counts = {cid: len(members) for cid, members in communities.items()}
|
||||
to_html(meta, meta_communities, 'graphify-out/graph.html', community_labels=labels or None, member_counts=member_counts)
|
||||
print(f'graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)')
|
||||
print('Tip: run with --obsidian for full node-level detail.')
|
||||
else:
|
||||
print('Single community — aggregated view not useful. Skipping graph.html.')
|
||||
else:
|
||||
to_html(G, communities, 'graphify-out/graph.html', community_labels=labels or None)
|
||||
print('graph.html written - open in any browser, no server needed')
|
||||
|
||||
@@ -132,6 +132,21 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def check_update(watch_path: Path) -> bool:
|
||||
"""Check for pending semantic update flag and notify the user if set.
|
||||
|
||||
Cron-safe: always returns True so cron jobs do not alarm.
|
||||
Non-code file changes (docs, papers, images) require LLM-backed
|
||||
re-extraction via `/graphify --update` — this function only signals
|
||||
that the update is needed.
|
||||
"""
|
||||
flag = Path(watch_path) / "graphify-out" / "needs_update"
|
||||
if flag.exists():
|
||||
print(f"[graphify check-update] Pending non-code changes in {watch_path}.")
|
||||
print("[graphify check-update] Run `/graphify --update` to apply semantic re-extraction.")
|
||||
return True
|
||||
|
||||
|
||||
def _notify_only(watch_path: Path) -> None:
|
||||
"""Write a flag file and print a notification (fallback for non-code-only corpora)."""
|
||||
flag = watch_path / "graphify-out" / "needs_update"
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.4.27"
|
||||
version = "0.4.31"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
{
|
||||
"httpx": {
|
||||
"model": "kimi-k2.6",
|
||||
"chunk_size": 2,
|
||||
"total_nodes": 71,
|
||||
"total_edges": 57,
|
||||
"unique_rel_types": 6,
|
||||
"relation_types": {
|
||||
"references": 33,
|
||||
"semantically_similar_to": 7,
|
||||
"conceptually_related_to": 7,
|
||||
"rationale_for": 7,
|
||||
"calls": 2,
|
||||
"implements": 1
|
||||
},
|
||||
"input_tokens": 7243,
|
||||
"output_tokens": 41410,
|
||||
"cost_usd": 0.1203,
|
||||
"elapsed_seconds": 1151.9,
|
||||
"chunks_run": 3,
|
||||
"chunks_failed": 0
|
||||
},
|
||||
"click": {
|
||||
"model": "kimi-k2.6",
|
||||
"chunk_size": 2,
|
||||
"total_nodes": 62,
|
||||
"total_edges": 48,
|
||||
"unique_rel_types": 7,
|
||||
"relation_types": {
|
||||
"references": 13,
|
||||
"calls": 11,
|
||||
"shares_data_with": 8,
|
||||
"conceptually_related_to": 7,
|
||||
"rationale_for": 7,
|
||||
"implements": 1,
|
||||
"cites": 1
|
||||
},
|
||||
"input_tokens": 13776,
|
||||
"output_tokens": 35520,
|
||||
"cost_usd": 0.1077,
|
||||
"elapsed_seconds": 1022.8,
|
||||
"chunks_run": 3,
|
||||
"chunks_failed": 0
|
||||
},
|
||||
"rich": {
|
||||
"model": "kimi-k2.6",
|
||||
"chunk_size": 2,
|
||||
"total_nodes": 53,
|
||||
"total_edges": 52,
|
||||
"unique_rel_types": 6,
|
||||
"relation_types": {
|
||||
"implements": 18,
|
||||
"calls": 15,
|
||||
"conceptually_related_to": 7,
|
||||
"references": 6,
|
||||
"semantically_similar_to": 3,
|
||||
"rationale_for": 3
|
||||
},
|
||||
"input_tokens": 12474,
|
||||
"output_tokens": 28220,
|
||||
"cost_usd": 0.0865,
|
||||
"elapsed_seconds": 781.2,
|
||||
"chunks_run": 3,
|
||||
"chunks_failed": 0
|
||||
},
|
||||
"nanoGPT": {
|
||||
"model": "kimi-k2.6",
|
||||
"chunk_size": 2,
|
||||
"total_nodes": 28,
|
||||
"total_edges": 30,
|
||||
"unique_rel_types": 6,
|
||||
"relation_types": {
|
||||
"references": 16,
|
||||
"semantically_similar_to": 4,
|
||||
"shares_data_with": 3,
|
||||
"rationale_for": 3,
|
||||
"calls": 2,
|
||||
"conceptually_related_to": 2
|
||||
},
|
||||
"input_tokens": 4344,
|
||||
"output_tokens": 29463,
|
||||
"cost_usd": 0.0851,
|
||||
"elapsed_seconds": 915.9,
|
||||
"chunks_run": 3,
|
||||
"chunks_failed": 0
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
{
|
||||
"chunk_4": {
|
||||
"nanoGPT": {
|
||||
"node_count": 27,
|
||||
"edge_count": 31,
|
||||
"unique_rel_types": 5,
|
||||
"relation_types": {
|
||||
"references": 22,
|
||||
"conceptually_related_to": 3,
|
||||
"semantically_similar_to": 3,
|
||||
"calls": 1,
|
||||
"rationale_for": 2
|
||||
},
|
||||
"input_tokens": 2183,
|
||||
"output_tokens": 14699,
|
||||
"elapsed_seconds": 418.73,
|
||||
"cost_usd": 0.0425
|
||||
},
|
||||
"httpx": {
|
||||
"node_count": 20,
|
||||
"edge_count": 15,
|
||||
"unique_rel_types": 4,
|
||||
"relation_types": {
|
||||
"calls": 7,
|
||||
"rationale_for": 3,
|
||||
"conceptually_related_to": 4,
|
||||
"implements": 1
|
||||
},
|
||||
"input_tokens": 3208,
|
||||
"output_tokens": 15222,
|
||||
"elapsed_seconds": 405.59,
|
||||
"cost_usd": 0.0445
|
||||
}
|
||||
},
|
||||
"chunk_8": {
|
||||
"nanoGPT": {
|
||||
"node_count": 20,
|
||||
"edge_count": 21,
|
||||
"unique_rel_types": 6,
|
||||
"relation_types": {
|
||||
"rationale_for": 4,
|
||||
"references": 8,
|
||||
"semantically_similar_to": 4,
|
||||
"calls": 2,
|
||||
"shares_data_with": 1,
|
||||
"conceptually_related_to": 2
|
||||
},
|
||||
"input_tokens": 3568,
|
||||
"output_tokens": 15451,
|
||||
"elapsed_seconds": 327.97,
|
||||
"cost_usd": 0.0454
|
||||
},
|
||||
"httpx": {
|
||||
"node_count": 52,
|
||||
"edge_count": 35,
|
||||
"unique_rel_types": 7,
|
||||
"relation_types": {
|
||||
"calls": 6,
|
||||
"rationale_for": 8,
|
||||
"references": 2,
|
||||
"conceptually_related_to": 4,
|
||||
"cites": 7,
|
||||
"implements": 2,
|
||||
"semantically_similar_to": 6
|
||||
},
|
||||
"input_tokens": 12303,
|
||||
"output_tokens": 22718,
|
||||
"elapsed_seconds": 593.69,
|
||||
"cost_usd": 0.071
|
||||
}
|
||||
}
|
||||
}
|
||||
-391
@@ -1,391 +0,0 @@
|
||||
"""Direct LLM backend for semantic extraction.
|
||||
|
||||
Bypasses the Claude Code Agent tool and calls any OpenAI-compatible API directly.
|
||||
Supports Kimi (Moonshot AI), OpenAI, and Anthropic (via openai-compat proxy).
|
||||
|
||||
Usage:
|
||||
from graphify.llm import extract_files_direct
|
||||
|
||||
result = extract_files_direct(
|
||||
files=[Path("docs/design.md"), Path("src/auth.py")],
|
||||
backend="kimi",
|
||||
api_key="sk-...",
|
||||
)
|
||||
# result: {"nodes": [...], "edges": [...], "hyperedges": [...],
|
||||
# "input_tokens": N, "output_tokens": N}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ── Backend configs ────────────────────────────────────────────────────────────
|
||||
|
||||
BACKENDS: dict[str, dict] = {
|
||||
"kimi": {
|
||||
"base_url": "https://api.moonshot.ai/v1",
|
||||
"default_model": "kimi-k2.5", # 256K context, vision + reasoning
|
||||
"context_window": 256_000,
|
||||
# Kimi k2.5 pricing (approximate USD — verify at platform.moonshot.ai):
|
||||
"input_cost_per_1k": 0.0006,
|
||||
"output_cost_per_1k": 0.0028,
|
||||
},
|
||||
"openai": {
|
||||
"base_url": "https://api.openai.com/v1",
|
||||
"default_model": "gpt-4o",
|
||||
"context_window": 128_000,
|
||||
"input_cost_per_1k": 0.0025,
|
||||
"output_cost_per_1k": 0.01,
|
||||
},
|
||||
"claude": {
|
||||
# Claude via official Anthropic SDK (different interface, handled separately)
|
||||
"base_url": None,
|
||||
"default_model": "claude-sonnet-4-6",
|
||||
"context_window": 200_000,
|
||||
"input_cost_per_1k": 0.003,
|
||||
"output_cost_per_1k": 0.015,
|
||||
},
|
||||
}
|
||||
|
||||
# ── Extraction prompt ──────────────────────────────────────────────────────────
|
||||
|
||||
_FEW_SHOT_EXAMPLE = """
|
||||
Example input:
|
||||
=== FILE: auth/login.py ===
|
||||
from db import UserDB
|
||||
def login(username, password):
|
||||
user = UserDB.find(username)
|
||||
if user and user.check_password(password):
|
||||
return generate_token(user)
|
||||
|
||||
Example output:
|
||||
{"nodes":[{"id":"login_login","label":"login","file_type":"code","source_file":"auth/login.py","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null},{"id":"login_userdb","label":"UserDB","file_type":"code","source_file":"auth/login.py","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"login_login","target":"login_userdb","relation":"calls","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"auth/login.py","source_location":null,"weight":1.0}],"hyperedges":[],"input_tokens":0,"output_tokens":0}
|
||||
|
||||
Now extract from the files below using the same schema:
|
||||
"""
|
||||
|
||||
_SYSTEM_PROMPT = """You are a graphify extraction agent. Your task: read the file contents and extract a knowledge graph as JSON.
|
||||
Output ONLY valid JSON — no explanation, no markdown fences, no preamble, no trailing text after the closing brace.
|
||||
|
||||
Rules:
|
||||
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
|
||||
- INFERRED: reasonable inference (shared data structure, implied dependency)
|
||||
- AMBIGUOUS: uncertain - flag for review, do not omit
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. Also extract rationale — sections that explain WHY a decision was made, trade-offs chosen, or design intent. These become nodes with `rationale_for` edges pointing to the concept they explain.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
Chart: metric, trend/insight, data source.
|
||||
Tweet/post: claim as node, author, concepts mentioned.
|
||||
Diagram: components and connections.
|
||||
Research figure: what it demonstrates, method, result.
|
||||
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
|
||||
|
||||
Semantic 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). Only add these when the similarity is genuinely non-obvious and cross-cutting.
|
||||
|
||||
Hyperedges: 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. Use sparingly — maximum 3 hyperedges per chunk.
|
||||
|
||||
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, contributor onto every node from that file.
|
||||
|
||||
confidence_score is REQUIRED on every edge:
|
||||
- EXTRACTED edges: confidence_score must be 1.0
|
||||
- INFERRED edges: score 0.4-0.9 based on how certain you are. Strong structural inference: 0.8-0.9. Reasonable but not certain: 0.6-0.7. Weak: 0.4-0.5.
|
||||
- AMBIGUOUS edges: score 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"filestem_entityname","label":"Human Readable Name","file_type":"code|document|paper|image","source_file":"relative/path","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/path","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/path"}],"input_tokens":0,"output_tokens":0}"""
|
||||
|
||||
|
||||
def _build_user_message(files: list[Path], root: Path | None = None) -> str:
|
||||
"""Read files and build the user message for extraction."""
|
||||
parts = []
|
||||
for f in files:
|
||||
try:
|
||||
rel = f.relative_to(root) if root else f
|
||||
except ValueError:
|
||||
rel = f
|
||||
try:
|
||||
# Skip binary files (PDFs, images handled separately via vision)
|
||||
if f.suffix.lower() in {".pdf", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"}:
|
||||
parts.append(f"=== FILE: {rel} ===\n[Binary file — skipped in text extraction]")
|
||||
continue
|
||||
content = f.read_text(encoding="utf-8", errors="replace")
|
||||
# Truncate very large files — LLM has context limits even at 128K
|
||||
if len(content) > 80_000:
|
||||
content = content[:80_000] + f"\n... [truncated at 80K chars]"
|
||||
parts.append(f"=== FILE: {rel} ===\n{content}")
|
||||
except OSError as exc:
|
||||
parts.append(f"=== FILE: {rel} ===\n[Could not read: {exc}]")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _parse_response(text: str) -> dict:
|
||||
"""Extract JSON from LLM response, tolerating markdown fences."""
|
||||
text = text.strip()
|
||||
# Strip ```json fences if present
|
||||
if text.startswith("```"):
|
||||
lines = text.splitlines()
|
||||
# Remove first and last fence lines
|
||||
inner = lines[1:-1] if lines[-1].strip().startswith("```") else lines[1:]
|
||||
text = "\n".join(inner).strip()
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
# ── OpenAI-compatible backends (Kimi, OpenAI) ─────────────────────────────────
|
||||
|
||||
def _extract_openai_compat(
|
||||
files: list[Path],
|
||||
backend_cfg: dict,
|
||||
api_key: str,
|
||||
model: str,
|
||||
root: Path | None,
|
||||
) -> dict:
|
||||
try:
|
||||
from openai import OpenAI
|
||||
except ImportError:
|
||||
raise ImportError("openai package required: pip install openai")
|
||||
|
||||
timeout = 2400 if "k2.6" in model else 120
|
||||
client = OpenAI(api_key=api_key, base_url=backend_cfg["base_url"], timeout=timeout)
|
||||
user_msg = _build_user_message(files, root)
|
||||
|
||||
t0 = time.time()
|
||||
# kimi-k2.x reasoning models only accept temperature=1
|
||||
temperature = 1 if "k2" in model else 0.1
|
||||
# Prepend few-shot example to user message for reasoning models
|
||||
full_user_msg = (_FEW_SHOT_EXAMPLE + user_msg) if "k2" in model else user_msg
|
||||
# K2.6 does not support response_format=json_object — it handles JSON via prompt
|
||||
use_json_format = "k2.6" not in model
|
||||
kwargs = dict(
|
||||
model=model,
|
||||
messages=[
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": full_user_msg},
|
||||
],
|
||||
temperature=temperature,
|
||||
max_tokens=32768 if "k2.6" in model else 16384,
|
||||
)
|
||||
if use_json_format:
|
||||
kwargs["response_format"] = {"type": "json_object"}
|
||||
response = client.chat.completions.create(**kwargs)
|
||||
elapsed = time.time() - t0
|
||||
|
||||
msg = response.choices[0].message
|
||||
raw = msg.content or ""
|
||||
|
||||
# Reasoning models (kimi-k2.5) may put the answer in reasoning_content
|
||||
# and leave content empty — fall back to it
|
||||
if not raw.strip():
|
||||
raw = getattr(msg, "reasoning_content", "") or ""
|
||||
|
||||
# Some providers wrap JSON in a finish_reason=stop with content in tool_calls
|
||||
if not raw.strip() and response.choices[0].finish_reason:
|
||||
import pprint
|
||||
raise ValueError(
|
||||
f"Empty response from model.\n"
|
||||
f"finish_reason={response.choices[0].finish_reason!r}\n"
|
||||
f"message fields: {[k for k in vars(msg) if getattr(msg, k)]}"
|
||||
)
|
||||
|
||||
usage = response.usage
|
||||
|
||||
try:
|
||||
result = _parse_response(raw)
|
||||
except (json.JSONDecodeError, ValueError) as exc:
|
||||
raise ValueError(f"Backend returned invalid JSON: {exc}\nRaw response (first 500 chars):\n{raw[:500]}")
|
||||
|
||||
result["input_tokens"] = usage.prompt_tokens if usage else 0
|
||||
result["output_tokens"] = usage.completion_tokens if usage else 0
|
||||
result["elapsed_seconds"] = round(elapsed, 2)
|
||||
result["model"] = model
|
||||
result["backend"] = backend_cfg.get("base_url", "unknown")
|
||||
return result
|
||||
|
||||
|
||||
# ── Claude via claude CLI (no API key needed inside Claude Code) ───────────────
|
||||
|
||||
def _extract_claude(
|
||||
files: list[Path],
|
||||
api_key: str | None,
|
||||
model: str,
|
||||
root: Path | None,
|
||||
) -> dict:
|
||||
"""Extract using claude CLI subprocess — works inside Claude Code without an API key."""
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
user_msg = _build_user_message(files, root)
|
||||
prompt = _SYSTEM_PROMPT + "\n\n" + user_msg
|
||||
|
||||
t0 = time.time()
|
||||
# Pass prompt via stdin to avoid OS arg length limits
|
||||
proc = subprocess.run(
|
||||
["claude", "-p", "-", "--model", model, "--output-format", "text"],
|
||||
input=prompt,
|
||||
capture_output=True, text=True, timeout=300,
|
||||
encoding="utf-8", errors="replace",
|
||||
)
|
||||
raw = proc.stdout.strip()
|
||||
if proc.returncode != 0 and not raw:
|
||||
raise RuntimeError(f"claude CLI failed (exit {proc.returncode}): {proc.stderr[:300]}")
|
||||
|
||||
elapsed = time.time() - t0
|
||||
|
||||
try:
|
||||
result = _parse_response(raw)
|
||||
except (json.JSONDecodeError, ValueError) as exc:
|
||||
raise ValueError(f"Backend returned invalid JSON: {exc}\nRaw response (first 500 chars):\n{raw[:500]}")
|
||||
|
||||
# Estimate tokens (claude CLI doesn't return usage counts)
|
||||
result["input_tokens"] = len(prompt) // 4
|
||||
result["output_tokens"] = len(raw) // 4
|
||||
result["elapsed_seconds"] = round(elapsed, 2)
|
||||
result["model"] = model
|
||||
result["backend"] = "claude-cli"
|
||||
return result
|
||||
|
||||
|
||||
# ── Public API ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def extract_files_direct(
|
||||
files: list[Path],
|
||||
backend: str,
|
||||
api_key: str,
|
||||
model: str | None = None,
|
||||
root: Path | None = None,
|
||||
) -> dict:
|
||||
"""Extract knowledge graph from files using a direct LLM API call.
|
||||
|
||||
Args:
|
||||
files: list of file paths to extract from (one API call per batch)
|
||||
backend: "kimi", "openai", or "claude"
|
||||
api_key: API key for the backend
|
||||
model: override the default model for this backend
|
||||
root: project root for relative path display
|
||||
|
||||
Returns:
|
||||
dict with nodes, edges, hyperedges, input_tokens, output_tokens,
|
||||
elapsed_seconds, model, backend
|
||||
"""
|
||||
if backend not in BACKENDS:
|
||||
raise ValueError(f"Unknown backend {backend!r}. Choose from: {list(BACKENDS)}")
|
||||
|
||||
cfg = BACKENDS[backend]
|
||||
chosen_model = model or cfg["default_model"]
|
||||
|
||||
if backend == "claude":
|
||||
return _extract_claude(files, api_key, chosen_model, root)
|
||||
else:
|
||||
return _extract_openai_compat(files, cfg, api_key, chosen_model, root)
|
||||
|
||||
|
||||
def estimate_cost(backend: str, input_tokens: int, output_tokens: int) -> float:
|
||||
"""Estimate USD cost for a completed extraction call."""
|
||||
cfg = BACKENDS.get(backend, {})
|
||||
input_cost = (input_tokens / 1000) * cfg.get("input_cost_per_1k", 0)
|
||||
output_cost = (output_tokens / 1000) * cfg.get("output_cost_per_1k", 0)
|
||||
return round(input_cost + output_cost, 6)
|
||||
|
||||
|
||||
def _chunk_files(files: list[Path], chunk_size: int) -> list[list[Path]]:
|
||||
return [files[i:i + chunk_size] for i in range(0, len(files), chunk_size)]
|
||||
|
||||
|
||||
_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff", ".svg"}
|
||||
|
||||
|
||||
def _split_into_chunks(files: list[Path], chunk_size: int = 22) -> list[list[Path]]:
|
||||
"""Mirror graphify skill chunking: 20-25 files per chunk, images get their own chunk."""
|
||||
images = [f for f in files if f.suffix.lower() in _IMAGE_EXTENSIONS]
|
||||
non_images = [f for f in files if f.suffix.lower() not in _IMAGE_EXTENSIONS]
|
||||
chunks = _chunk_files(non_images, chunk_size)
|
||||
# Each image is its own chunk (vision needs isolated context)
|
||||
chunks += [[img] for img in images]
|
||||
return chunks
|
||||
|
||||
|
||||
def extract_corpus_parallel(
|
||||
files: list[Path],
|
||||
backend: str,
|
||||
api_key: str,
|
||||
model: str | None = None,
|
||||
root: Path | None = None,
|
||||
chunk_size: int = 22,
|
||||
max_workers: int = 5,
|
||||
on_chunk_done: "callable | None" = None,
|
||||
) -> dict:
|
||||
"""Extract a full corpus in parallel — mirrors graphify's multi-subagent dispatch.
|
||||
|
||||
Splits files into chunks of 20-25 (images solo), fires all chunks simultaneously
|
||||
via ThreadPoolExecutor (max_workers parallel API calls), then merges results.
|
||||
|
||||
Args:
|
||||
files: all files to extract from
|
||||
backend: "kimi", "openai", or "claude"
|
||||
api_key: API key for the backend
|
||||
model: override default model
|
||||
root: project root for relative path display
|
||||
chunk_size: non-image files per API call (default 22, matching graphify skill)
|
||||
max_workers: max parallel API calls (default 5)
|
||||
on_chunk_done: optional callback(chunk_idx, total, result) for progress reporting
|
||||
|
||||
Returns:
|
||||
merged dict with nodes, edges, hyperedges, input_tokens, output_tokens
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
chunks = _split_into_chunks(files, chunk_size)
|
||||
total = len(chunks)
|
||||
|
||||
all_nodes: list[dict] = []
|
||||
all_edges: list[dict] = []
|
||||
all_hyperedges: list[dict] = []
|
||||
total_input = 0
|
||||
total_output = 0
|
||||
failed = 0
|
||||
|
||||
def _call(idx_chunk: tuple[int, list[Path]]) -> tuple[int, dict | Exception]:
|
||||
idx, chunk = idx_chunk
|
||||
try:
|
||||
result = extract_files_direct(chunk, backend, api_key, model, root)
|
||||
return idx, result
|
||||
except Exception as exc:
|
||||
return idx, exc
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
||||
futures = {pool.submit(_call, (i, chunk)): i for i, chunk in enumerate(chunks)}
|
||||
for future in as_completed(futures):
|
||||
idx, result = future.result()
|
||||
if isinstance(result, Exception):
|
||||
print(f" [chunk {idx+1}/{total}] FAILED: {result}", flush=True)
|
||||
failed += 1
|
||||
else:
|
||||
# Deduplicate nodes by id
|
||||
seen = {n["id"] for n in all_nodes}
|
||||
for n in result.get("nodes", []):
|
||||
if n["id"] not in seen:
|
||||
all_nodes.append(n)
|
||||
seen.add(n["id"])
|
||||
all_edges.extend(result.get("edges", []))
|
||||
all_hyperedges.extend(result.get("hyperedges", []))
|
||||
total_input += result.get("input_tokens", 0)
|
||||
total_output += result.get("output_tokens", 0)
|
||||
if on_chunk_done:
|
||||
on_chunk_done(idx, total, result)
|
||||
|
||||
if failed > total // 2:
|
||||
raise RuntimeError(f"More than half the chunks failed ({failed}/{total}). Aborting.")
|
||||
|
||||
return {
|
||||
"nodes": all_nodes,
|
||||
"edges": all_edges,
|
||||
"hyperedges": all_hyperedges,
|
||||
"input_tokens": total_input,
|
||||
"output_tokens": total_output,
|
||||
"chunks_total": total,
|
||||
"chunks_failed": failed,
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run Kimi K2.6 extraction across the same corpora/files used in the K2.5 benchmark."""
|
||||
from __future__ import annotations
|
||||
import json, sys, time, random
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from llm import extract_files_direct, estimate_cost
|
||||
|
||||
KIMI_KEY = "sk-5rsh69xqeq2JRREJzelnTcnkxpn2hMcZdRpBb0iVgabnJ7br"
|
||||
MODEL = "kimi-k2.6"
|
||||
CHUNK = 2 # files per call, same as previous benchmark
|
||||
|
||||
CORPORA = {
|
||||
"httpx": Path("/home/safi/graphify_eval/codebase/httpx"),
|
||||
"click": Path("/home/safi/graphify_eval/codebase/click"),
|
||||
"rich": Path("/home/safi/graphify_eval/codebase/rich"),
|
||||
"nanoGPT": Path("/home/safi/graphify_eval/mixed/nanoGPT"),
|
||||
}
|
||||
|
||||
_SKIP = {".git","graphify-out","venv",".venv","build","dist","__pycache__",".pytest_cache","node_modules","egg-info"}
|
||||
_EXT = {".py",".ts",".js",".go",".rs",".java",".c",".cpp",".rb",".cs",
|
||||
".md",".txt",".rst",".php",".swift",".kt",".scala",".lua",".zig"}
|
||||
|
||||
def pick(path: Path, n: int = 60, seed: int = 42) -> list[Path]:
|
||||
candidates = [p for p in sorted(path.rglob("*"))
|
||||
if p.is_file()
|
||||
and p.suffix.lower() in _EXT
|
||||
and not any(x in _SKIP or x.endswith(".egg-info") for x in p.parts)]
|
||||
random.seed(seed)
|
||||
random.shuffle(candidates)
|
||||
return candidates[:n]
|
||||
|
||||
def chunk(lst, size):
|
||||
return [lst[i:i+size] for i in range(0, len(lst), size)]
|
||||
|
||||
def analyze(result):
|
||||
nodes = result.get("nodes", [])
|
||||
edges = result.get("edges", [])
|
||||
return {
|
||||
"node_count": len(nodes),
|
||||
"edge_count": len(edges),
|
||||
"relation_types": dict(Counter(e.get("relation","") for e in edges)),
|
||||
"node_labels": [n.get("label", n.get("id","")) for n in nodes],
|
||||
"input_tokens": result.get("input_tokens", 0),
|
||||
"output_tokens": result.get("output_tokens", 0),
|
||||
"elapsed_seconds":result.get("elapsed_seconds", 0),
|
||||
}
|
||||
|
||||
results = {}
|
||||
|
||||
for corpus, path in CORPORA.items():
|
||||
print(f"\n{'='*60}")
|
||||
print(f" {corpus} ({MODEL})")
|
||||
print(f"{'='*60}")
|
||||
|
||||
files = pick(path)
|
||||
chunks = chunk(files, CHUNK)[:3] # 3 chunks per corpus = 6 files
|
||||
print(f" {len(files)} files sampled → {len(chunks)} chunks of {CHUNK}")
|
||||
|
||||
all_nodes, all_edges, rel_types = [], [], Counter()
|
||||
total_in, total_out, total_cost, total_time = 0, 0, 0.0, 0.0
|
||||
failed = 0
|
||||
|
||||
for i, ch in enumerate(chunks):
|
||||
print(f" chunk {i+1}/{len(chunks)}: {[f.name for f in ch]} ...", end=" ", flush=True)
|
||||
try:
|
||||
r = extract_files_direct(ch, backend="kimi", api_key=KIMI_KEY, model=MODEL, root=path)
|
||||
m = analyze(r)
|
||||
all_nodes.extend(m["node_labels"])
|
||||
all_edges.append(m["edge_count"])
|
||||
rel_types.update(m["relation_types"])
|
||||
total_in += m["input_tokens"]
|
||||
total_out += m["output_tokens"]
|
||||
cost = estimate_cost("kimi", m["input_tokens"], m["output_tokens"])
|
||||
total_cost += cost
|
||||
total_time += m["elapsed_seconds"]
|
||||
print(f"nodes={m['node_count']} edges={m['edge_count']} rel_types={len(m['relation_types'])} cost=${cost:.4f} t={m['elapsed_seconds']:.1f}s")
|
||||
except Exception as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
failed += 1
|
||||
|
||||
results[corpus] = {
|
||||
"model": MODEL,
|
||||
"chunk_size": CHUNK,
|
||||
"total_nodes": len(all_nodes),
|
||||
"total_edges": sum(all_edges),
|
||||
"unique_rel_types":len(rel_types),
|
||||
"relation_types": dict(rel_types.most_common()),
|
||||
"input_tokens": total_in,
|
||||
"output_tokens": total_out,
|
||||
"cost_usd": round(total_cost, 4),
|
||||
"elapsed_seconds": round(total_time, 1),
|
||||
"chunks_run": len(chunks) - failed,
|
||||
"chunks_failed": failed,
|
||||
}
|
||||
|
||||
print(f"\n TOTAL: nodes={results[corpus]['total_nodes']} edges={results[corpus]['total_edges']} "
|
||||
f"rel_types={results[corpus]['unique_rel_types']} cost=${results[corpus]['cost_usd']:.4f}")
|
||||
|
||||
out = Path("scripts/benchmark_kimi_k2.6.json")
|
||||
out.write_text(json.dumps(results, indent=2))
|
||||
print(f"\n\nResults saved to {out}")
|
||||
|
||||
# Print comparison table vs K2.5 results
|
||||
k25_ref = {
|
||||
"httpx": {"total_nodes": 877+502+370, "total_edges": 907+543+358, "unique_rel_types": 48, "cost_usd": 0.72+0.47+0.40},
|
||||
"click": {"total_nodes": 653+540+310, "total_edges": 637+470+231, "unique_rel_types": 44, "cost_usd": 0.67+0.50+0.36},
|
||||
"rich": {"total_nodes": 447+397+311, "total_edges": 446+397+294, "unique_rel_types": 35, "cost_usd": 0.62+0.53+0.44},
|
||||
"nanoGPT": {"total_nodes": 183+126+100+103, "total_edges": 222+148+107+101, "unique_rel_types": 36, "cost_usd": 0.25+0.16+0.11+0.09},
|
||||
}
|
||||
|
||||
print(f"\n{'='*70}")
|
||||
print(f" Kimi K2.5 vs K2.6 — same corpora, chunk={CHUNK}")
|
||||
print(f"{'─'*70}")
|
||||
print(f" {'Corpus':<10} {'K2.5 nodes':>12} {'K2.6 nodes':>12} {'K2.5 rel':>10} {'K2.6 rel':>10} {'K2.5 $':>8} {'K2.6 $':>8}")
|
||||
print(f"{'─'*70}")
|
||||
for corpus in CORPORA:
|
||||
r = results[corpus]
|
||||
ref = k25_ref[corpus]
|
||||
print(f" {corpus:<10} {ref['total_nodes']:>12} {r['total_nodes']:>12} "
|
||||
f"{ref['unique_rel_types']:>10} {r['unique_rel_types']:>10} "
|
||||
f"${ref['cost_usd']:>7.2f} ${r['cost_usd']:>7.4f}")
|
||||
print(f"{'='*70}")
|
||||
@@ -1,120 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Kimi K2.6 large-context benchmark — 2 corpora, chunk=4 and chunk=8.
|
||||
|
||||
K2.5 reference (from previous benchmark):
|
||||
httpx chunk=4: nodes=502, edges=543, rel_types=34
|
||||
httpx chunk=8: nodes=370, edges=358, rel_types=37
|
||||
nanoGPT chunk=4: nodes=100, edges=107, rel_types=24
|
||||
nanoGPT chunk=8: nodes=103, edges=101, rel_types=26
|
||||
|
||||
Claude Sonnet reference (chunk=4 and chunk=8):
|
||||
httpx chunk=4: nodes=417, rel_types=8
|
||||
httpx chunk=8: nodes=290, rel_types=7
|
||||
nanoGPT chunk=4: nodes=108, rel_types=8
|
||||
nanoGPT chunk=8: nodes=83, rel_types=8
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import json, sys, time, random
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from llm import extract_files_direct, estimate_cost
|
||||
|
||||
KIMI_KEY = "sk-5rsh69xqeq2JRREJzelnTcnkxpn2hMcZdRpBb0iVgabnJ7br"
|
||||
MODEL = "kimi-k2.6"
|
||||
|
||||
CORPORA = {
|
||||
"nanoGPT": Path("/home/safi/graphify_eval/mixed/nanoGPT"),
|
||||
"httpx": Path("/home/safi/graphify_eval/codebase/httpx"),
|
||||
}
|
||||
|
||||
CHUNK_SIZES = [4, 8]
|
||||
|
||||
_SKIP = {".git","graphify-out","venv",".venv","build","dist","__pycache__",
|
||||
".pytest_cache","node_modules","egg-info"}
|
||||
_EXT = {".py",".ts",".js",".go",".rs",".java",".c",".cpp",".rb",".cs",
|
||||
".md",".txt",".rst",".php",".swift",".kt",".scala",".lua",".zig"}
|
||||
|
||||
def pick(path: Path, n: int = 60, seed: int = 42) -> list[Path]:
|
||||
candidates = [p for p in sorted(path.rglob("*"))
|
||||
if p.is_file()
|
||||
and p.suffix.lower() in _EXT
|
||||
and not any(x in _SKIP or x.endswith(".egg-info") for x in p.parts)]
|
||||
random.seed(seed)
|
||||
random.shuffle(candidates)
|
||||
return candidates[:n]
|
||||
|
||||
def analyze(result):
|
||||
nodes = result.get("nodes", [])
|
||||
edges = result.get("edges", [])
|
||||
return {
|
||||
"node_count": len(nodes),
|
||||
"edge_count": len(edges),
|
||||
"unique_rel_types":len(set(e.get("relation","") for e in edges)),
|
||||
"relation_types": dict(Counter(e.get("relation","") for e in edges)),
|
||||
"input_tokens": result.get("input_tokens", 0),
|
||||
"output_tokens": result.get("output_tokens", 0),
|
||||
"elapsed_seconds": result.get("elapsed_seconds", 0),
|
||||
}
|
||||
|
||||
all_results = {}
|
||||
|
||||
for chunk_size in CHUNK_SIZES:
|
||||
print(f"\n{'#'*65}")
|
||||
print(f" CHUNK = {chunk_size} files")
|
||||
print(f"{'#'*65}")
|
||||
chunk_results = {}
|
||||
|
||||
for corpus, path in CORPORA.items():
|
||||
files = pick(path)
|
||||
batch = files[:chunk_size]
|
||||
print(f"\n [{corpus}] sending {len(batch)} files...", end=" ", flush=True)
|
||||
try:
|
||||
r = extract_files_direct(batch, backend="kimi", api_key=KIMI_KEY,
|
||||
model=MODEL, root=path)
|
||||
m = analyze(r)
|
||||
cost = estimate_cost("kimi", m["input_tokens"], m["output_tokens"])
|
||||
print(f"nodes={m['node_count']} edges={m['edge_count']} "
|
||||
f"rel_types={m['unique_rel_types']} "
|
||||
f"tokens={m['input_tokens']:,}in/{m['output_tokens']:,}out "
|
||||
f"cost=${cost:.4f} t={m['elapsed_seconds']:.1f}s")
|
||||
chunk_results[corpus] = {**m, "cost_usd": round(cost, 4)}
|
||||
except Exception as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
chunk_results[corpus] = {"error": str(exc)}
|
||||
|
||||
all_results[f"chunk_{chunk_size}"] = chunk_results
|
||||
|
||||
out = Path("scripts/benchmark_kimi_k2.6_largechunk.json")
|
||||
out.write_text(json.dumps(all_results, indent=2))
|
||||
print(f"\nResults saved to {out}")
|
||||
|
||||
# Reference data
|
||||
REF = {
|
||||
"K2.5": {
|
||||
4: {"httpx": (502, 34), "nanoGPT": (100, 24)},
|
||||
8: {"httpx": (370, 37), "nanoGPT": (103, 26)},
|
||||
},
|
||||
"Sonnet": {
|
||||
4: {"httpx": (417, 8), "nanoGPT": (108, 8)},
|
||||
8: {"httpx": (290, 7), "nanoGPT": (83, 8)},
|
||||
},
|
||||
}
|
||||
|
||||
print(f"\n{'='*75}")
|
||||
print(f" Relation-type diversity — K2.6 vs K2.5 vs Claude Sonnet 4.6")
|
||||
print(f"{'─'*75}")
|
||||
print(f" {'Corpus+Chunk':<18} {'Sonnet nodes':>13} {'Sonnet rel':>11} {'K2.5 nodes':>11} {'K2.5 rel':>9} {'K2.6 nodes':>11} {'K2.6 rel':>9}")
|
||||
print(f"{'─'*75}")
|
||||
for chunk_size in CHUNK_SIZES:
|
||||
for corpus in CORPORA:
|
||||
k26 = all_results.get(f"chunk_{chunk_size}", {}).get(corpus, {})
|
||||
k25n, k25r = REF["K2.5"][chunk_size][corpus]
|
||||
snn, snr = REF["Sonnet"][chunk_size][corpus]
|
||||
k26n = k26.get("node_count", "ERR")
|
||||
k26r = k26.get("unique_rel_types", "ERR")
|
||||
label = f"{corpus} @{chunk_size}"
|
||||
print(f" {label:<18} {snn:>13} {snr:>11} {k25n:>11} {k25r:>9} {k26n!s:>11} {k26r!s:>9}")
|
||||
print(f"{'='*75}")
|
||||
@@ -29,6 +29,27 @@ def test_ambiguous_edge_preserved():
|
||||
data = G.edges["n_layernorm", "n_concept_attn"]
|
||||
assert data["confidence"] == "AMBIGUOUS"
|
||||
|
||||
def test_legacy_node_source_canonicalized():
|
||||
"""Legacy 'source' key on nodes is renamed to 'source_file' before graph build."""
|
||||
ext = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source": "a.py"}],
|
||||
"edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
G = build_from_json(ext)
|
||||
assert "source_file" in G.nodes["n1"]
|
||||
assert G.nodes["n1"]["source_file"] == "a.py"
|
||||
assert "source" not in G.nodes["n1"]
|
||||
|
||||
|
||||
def test_legacy_edge_from_to_canonicalized():
|
||||
"""Legacy 'from'/'to' keys on edges are accepted alongside 'source'/'target'."""
|
||||
ext = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"},
|
||||
{"id": "n2", "label": "B", "file_type": "code", "source_file": "b.py"}],
|
||||
"edges": [{"from": "n1", "to": "n2", "relation": "calls",
|
||||
"confidence": "EXTRACTED", "source_file": "a.py", "weight": 1.0}],
|
||||
"input_tokens": 0, "output_tokens": 0}
|
||||
G = build_from_json(ext)
|
||||
assert G.number_of_edges() == 1
|
||||
|
||||
|
||||
def test_build_merges_multiple_extractions():
|
||||
ext1 = {"nodes": [{"id": "n1", "label": "A", "file_type": "code", "source_file": "a.py"}],
|
||||
"edges": [], "input_tokens": 0, "output_tokens": 0}
|
||||
|
||||
+27
-1
@@ -3,7 +3,7 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import to_json, to_cypher, to_graphml, to_html
|
||||
from graphify.export import to_json, to_cypher, to_graphml, to_html, to_canvas
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -125,3 +125,29 @@ def test_to_html_contains_nodes_and_edges():
|
||||
content = out.read_text()
|
||||
assert "RAW_NODES" in content
|
||||
assert "RAW_EDGES" in content
|
||||
|
||||
|
||||
def test_to_html_member_counts_accepted():
|
||||
"""to_html accepts member_counts without raising."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
member_counts = {cid: len(members) for cid, members in communities.items()}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out), member_counts=member_counts)
|
||||
assert out.exists()
|
||||
|
||||
|
||||
def test_to_canvas_file_paths_relative_to_vault():
|
||||
"""Node file paths in canvas must be vault-root-relative (just fname.md), not hardcoded."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.canvas"
|
||||
to_canvas(G, communities, str(out))
|
||||
data = json.loads(out.read_text())
|
||||
file_nodes = [n for n in data["nodes"] if n.get("type") == "file"]
|
||||
assert file_nodes, "canvas should contain file nodes"
|
||||
for node in file_nodes:
|
||||
assert "/" not in node["file"], f"file path should not contain '/': {node['file']}"
|
||||
assert node["file"].endswith(".md")
|
||||
@@ -117,3 +117,9 @@ def test_status_shows_both_hooks(tmp_path):
|
||||
assert "post-commit" in result
|
||||
assert "post-checkout" in result
|
||||
assert result.count("installed") >= 2
|
||||
|
||||
|
||||
def test_hook_skips_head_on_exe():
|
||||
"""Hook script must skip shebang extraction for .exe binaries (Windows)."""
|
||||
from graphify.hooks import _PYTHON_DETECT
|
||||
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
|
||||
@@ -194,9 +194,9 @@ def test_opencode_agents_install_writes_plugin(tmp_path):
|
||||
|
||||
|
||||
def test_opencode_agents_install_registers_plugin_in_config(tmp_path):
|
||||
"""opencode install registers the plugin in opencode.json."""
|
||||
"""opencode install registers the plugin in .opencode/opencode.json."""
|
||||
_agents_install(tmp_path, "opencode")
|
||||
config_file = tmp_path / "opencode.json"
|
||||
config_file = tmp_path / ".opencode" / "opencode.json"
|
||||
assert config_file.exists()
|
||||
import json as _json
|
||||
config = _json.loads(config_file.read_text())
|
||||
@@ -204,9 +204,10 @@ 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.json keys."""
|
||||
"""opencode install preserves existing .opencode/opencode.json keys."""
|
||||
import json as _json
|
||||
config_file = tmp_path / "opencode.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": []}))
|
||||
_agents_install(tmp_path, "opencode")
|
||||
config = _json.loads(config_file.read_text())
|
||||
@@ -221,7 +222,7 @@ def test_opencode_agents_uninstall_removes_plugin(tmp_path):
|
||||
_agents_uninstall(tmp_path, platform="opencode")
|
||||
plugin = tmp_path / ".opencode" / "plugins" / "graphify.js"
|
||||
assert not plugin.exists()
|
||||
config_file = tmp_path / "opencode.json"
|
||||
config_file = tmp_path / ".opencode" / "opencode.json"
|
||||
if config_file.exists():
|
||||
config = _json.loads(config_file.read_text())
|
||||
assert not any("graphify.js" in p for p in config.get("plugin", []))
|
||||
|
||||
@@ -52,6 +52,34 @@ def test_watched_extensions_excludes_noise():
|
||||
|
||||
# --- watch() import error without watchdog ---
|
||||
|
||||
def test_check_update_no_flag_returns_true(tmp_path):
|
||||
"""check_update returns True and is silent when needs_update flag is absent."""
|
||||
from graphify.watch import check_update
|
||||
assert check_update(tmp_path) is True
|
||||
|
||||
|
||||
def test_check_update_with_flag_returns_true_and_prints(tmp_path, capsys):
|
||||
"""check_update returns True and prints notification when flag exists."""
|
||||
from graphify.watch import check_update
|
||||
flag = tmp_path / "graphify-out" / "needs_update"
|
||||
flag.parent.mkdir(parents=True, exist_ok=True)
|
||||
flag.write_text("1")
|
||||
result = check_update(tmp_path)
|
||||
assert result is True
|
||||
out = capsys.readouterr().out
|
||||
assert "graphify --update" in out
|
||||
|
||||
|
||||
def test_check_update_does_not_clear_flag(tmp_path):
|
||||
"""check_update never removes the needs_update flag (clearing is LLM's job)."""
|
||||
from graphify.watch import check_update
|
||||
flag = tmp_path / "graphify-out" / "needs_update"
|
||||
flag.parent.mkdir(parents=True, exist_ok=True)
|
||||
flag.write_text("1")
|
||||
check_update(tmp_path)
|
||||
assert flag.exists()
|
||||
|
||||
|
||||
def test_watch_raises_without_watchdog(tmp_path, monkeypatch):
|
||||
import builtins
|
||||
real_import = builtins.__import__
|
||||
|
||||
Reference in new issue
Block a user