Compare commits

..
Author SHA1 Message Date
SafiandClaude Sonnet 4.6 137bc2d951 release 0.8.36
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 23:58:08 +01:00
SafiandClaude Sonnet 4.6 e477825a97 fix: three correctness bugs — cycle hang, label token budget, fuzzy dedup prefix merge
- analyze.py: pass length_bound=max_cycle_length to nx.simple_cycles() so
  networkx prunes during enumeration instead of post-filtering; drops report
  generation from never-returns to ~0.1s on dense graphs (#1196)

- llm.py: replace hardcoded min(40+16*n,4096) label_communities token budget
  with _resolve_max_tokens(min(64+24*n,8192)) — 24 tok/community covers 5-word
  JSON entries; 8192 cap fits 16k-context models; env var now honoured (#1200)

- dedup.py: add prefix-extension guard in Pass 2 and _llm_tiebreak — skip merge
  when one normalised label is a strict prefix of the other (getActiveSession /
  getActiveSessions, parseConfig / parseConfigFile). Option (a) rejected: dropping
  the >=12 early-out from _short_label_blocked breaks test_typo_merged (#1201)

- tests/test_dedup.py: two new regression tests verifying prefix guard fires for
  extension pairs and does not fire for same-length typo pairs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 23:49:16 +01:00
freiit 3602c8031e fix: guard label/text normalizers against None node labels (#1195)
Guards _norm, _norm_label, and _strip_diacritics against None node labels that cause TypeError in unicodedata.normalize(). Fixes #1194. Consistent with existing security.py:270 precedent.

Co-authored-by: freiit <freiit@users.noreply.github.com>
2026-06-08 23:22:15 +01:00
EirikWolfandEirikWolf 7477b469ee feat: extra_body for custom providers + multi-batch label_communities (#1197)
Adds extra_body parameter support for custom/OpenAI-compat providers so users can pass provider-specific params (e.g. thinking budget for Claude via Bedrock compat). Adds multi-batch label_communities for 16k-context models — batches multiple community descriptions into a single LLM call instead of one per community. Partial batch failures are handled gracefully.

Co-authored-by: EirikWolf <EirikWolf@users.noreply.github.com>
2026-06-08 23:22:00 +01:00
Rasmus Bækgaardandbakgaard 29e57cd295 feat: add .slnx solution file support (#1189)
Adds support for the XML-based `.slnx` solution format (VS 2022 17.13+ replacement for `.sln`). Extracts project references as `contains` edges and build dependencies as `imports` edges. XXE-protected XML parsing with size cap. Wired into `_DISPATCH` and `CODE_EXTENSIONS`. 6 new tests passing.

Co-authored-by: bakgaard <bakgaard@users.noreply.github.com>
2026-06-08 10:35:32 +01:00
Jan 42d1b8d02f feat: add graphify-mcp console script entry point (#1190)
Adds `graphify-mcp` as a named console script pointing to `graphify.serve:_main`, making the MCP stdio server directly invocable as a first-class CLI command from uv tool / pipx installs. MCP client configs can now use `"command": "graphify-mcp"` instead of `python -m graphify.serve`.

Co-authored-by: jr2804 <jr2804@users.noreply.github.com>
2026-06-08 10:35:21 +01:00
SafiandClaude Sonnet 4.6 8a04560bf5 fix: remove non-spec trigger: field from skill frontmatter (#1180)
The Agent Skills spec only defines name, description, license,
compatibility, metadata, and allowed-tools as valid frontmatter fields.
The trigger: /graphify line was non-spec, silently ignored by spec-
following hosts, and flagged by agentskills validate CI checks.

- gen.py: removed trigger emission from _render_frontmatter; added
  _is_trigger_line() helper for roundtrip allow-list
- fragments/core/aider.md: removed hardcoded trigger: /graphify
- platforms.toml: removed trigger doc comment and trigger="" entries
- test_skillgen.py: replaced trigger-assertion tests with a single
  test asserting no host has trigger: in frontmatter
- Regenerated all 125 skill artifacts

Routing intent is preserved: the description field already contains
"treated as a graphify query first" and "graphify-out/ exists".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 15:49:52 +01:00
SafiandClaude Sonnet 4.6 6dbcb89f3d release 0.8.35
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 14:42:30 +01:00
SafiandClaude Sonnet 4.6 660d2d32cf fix(codebuddy): install SKILL.md in codebuddy install subcommand + fix README hook description
graphify codebuddy install was writing CODEBUDDY.md and settings.json
but not copying the SKILL.md. Added _copy_skill_file("codebuddy") call
to match the --platform codebuddy path. README hook description updated
from "Glob and Grep" to "Bash search and file reads" to match actual
hook matchers (Bash + Read|Glob).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 14:39:16 +01:00
9e1ad425a9 feat: add CodeBuddy platform support (#1136)
Adds graphify skill installation for CodeBuddy (https://www.codebuddy.ai/).
CodeBuddy uses the same agent+hook mechanism as Claude Code.

- graphify codebuddy install — writes ~/.codebuddy/skills/graphify/SKILL.md
  and a CODEBUDDY.md always-on section
- graphify codebuddy uninstall — removes both cleanly
- graphify install --platform codebuddy — same as above
- Registers Bash + Read|Glob PreToolUse hooks in .codebuddy/settings.json
- Full install/uninstall roundtrip tests (35 tests)

Co-authored-by: studyzy <studyzy@gmail.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 14:34:13 +01:00
46 changed files with 499 additions and 87 deletions

No files matched your search

+17
View File
@@ -2,6 +2,23 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.8.36 (2026-06-08)
- Feat: `extra_body` field in `providers.json` forwarded to OpenAI-compat calls at extraction and labeling. Lets vLLM/Qwen3/Llama endpoints pass model-specific request shapes (e.g. `{"chat_template_kwargs": {"enable_thinking": false}}`). Explicit `extra_body` also bypasses Ollama `num_ctx` auto-derive. Thanks to @EirikWolf (#1197).
- Feat: `label_communities` multi-batch for 16k-context models. Chunks of 100 communities per call (configurable `batch_size=`); `max_communities` defaults to `None` (label all); partial batch failures no longer drop the whole pass. Thanks to @EirikWolf (#1197).
- Feat: `.slnx` Visual Studio solution file support. Extracts `contains` (project references) and `imports` (build dependencies) edges from the modern XML solution format (VS 2022 17.13+). Thanks to @bakgaard (#1189).
- Feat: `graphify-mcp` console script. MCP stdio server now directly invocable as `graphify-mcp` from `uv tool install` / `pipx`. Thanks to @jr2804 (#1190).
- Fix: `label_communities` token budget raised and `GRAPHIFY_MAX_OUTPUT_TOKENS` now honoured. Hardcoded `min(40+16n, 4096)` undershooted (~16 tok/community); raised to `min(64+24n, 8192)` and wrapped in `_resolve_max_tokens()` (#1200).
- Fix: `find_import_cycles` no longer hangs on large graphs. `nx.simple_cycles()` now receives `length_bound=max_cycle_length`, pruning during enumeration rather than post-filtering — drops from never-returns to ~0.1s on dense graphs (#1196).
- Fix: fuzzy dedup no longer merges prefix-extension symbol pairs. `getActiveSession`/`getActiveSessions`, `parseConfig`/`parseConfigFile` etc. scored ~98-99 JW and were auto-merged. A prefix-extension guard now prevents merge when one normalised label is a strict prefix of the other, in both Pass 2 and the LLM tiebreaker (#1201).
- Fix: `_norm`, `_norm_label`, `_strip_diacritics` guard against `None` node labels, preventing `TypeError` crash on corpora with explicit `null` label fields (#1194). Thanks to @freiit (#1195).
- Fix: skill frontmatter `trigger:` field removed from all 14 skill variants — not part of Agent Skills spec, flagged by `agentskills validate` CI (#1180).
## 0.8.35 (2026-06-07)
- Feat: CodeBuddy platform support. `graphify codebuddy install` installs the graphify skill to `~/.codebuddy/skills/graphify/SKILL.md`, writes a `CODEBUDDY.md` always-on section, and registers Bash + Read|Glob PreToolUse hooks in `.codebuddy/settings.json` that nudge the agent toward `graphify query` instead of grepping raw files when a graph exists. `graphify install --platform codebuddy` and `graphify codebuddy uninstall` also supported. Thanks to @studyzy (#1136).
- Fix: `graphify --update` no longer destructively collapses distinct same-named symbols across files. The skill's `--update` merge now passes re-extracted (changed) files to `prune_sources` alongside deleted files, so old nodes for changed files are pruned before fresh AST is inserted — no fuzzy reconciliation needed. Separately, `dedup.py` Pass 1 now skips nodes with an empty `source_file` so label-only merging across no-source-file nodes is prevented. The anti-shrink guard message now names fuzzy dedup as a possible cause rather than only blaming missing chunk files (#1178).
## 0.8.34 (2026-06-07)
- Feat: Streamable HTTP transport for the MCP server. `python -m graphify.serve graph.json --transport http --port 8080 --api-key $SECRET` serves the graph over the MCP Streamable HTTP transport (spec 2025-03-26) so a single shared process can serve the whole team. Flags: `--host`, `--port`, `--api-key` (env `GRAPHIFY_API_KEY`), `--path`, `--json-response`, `--stateless`, `--session-timeout`. Docker image included. stdio remains the default (#1143).
+2 -2
View File
@@ -211,7 +211,7 @@ Run this once in your project after building a graph:
This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions — preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files. On platforms that support payload-bearing hooks (Claude Code, Gemini CLI), a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools) and nudges your assistant toward the graph path. On the others (Codex, OpenCode, Cursor, etc.), the persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance. `GRAPH_REPORT.md` is still available for broad architecture review.
**CodeBuddy** does the same two things as Claude Code: writes a `CODEBUDDY.md` section telling CodeBuddy to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`.codebuddy/settings.json`) that fires before every Glob and Grep call.
**CodeBuddy** does the same two things as Claude Code: writes a `CODEBUDDY.md` section telling CodeBuddy to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs **PreToolUse hooks** (`.codebuddy/settings.json`) that fire before Bash search commands and file reads, nudging toward `graphify query` instead.
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
@@ -237,7 +237,7 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
| Type | Extensions |
|------|-----------|
| Code (28 tree-sitter grammars) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .csproj .fsproj .vbproj .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`) |
| Code (28 tree-sitter grammars) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .svh .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk .sh .bash .json .dm .dme .dmi .dmm .dmf .sln .slnx .csproj .fsproj .vbproj .razor .cshtml` (`.dm`/`.dme` requires `uv tool install graphifyy[dm]`) |
| Salesforce Apex | `.cls .trigger` (regex-based; classes, interfaces, enums, methods, triggers, SOQL/DML edges) |
| Terraform / HCL | `.tf .tfvars .hcl` (requires `uv tool install graphifyy[terraform]`) |
| MCP configs | `.mcp.json` `mcp.json` `mcp_servers.json` `claude_desktop_config.json` — extracts server nodes, package refs, env var requirements |
+2 -1
View File
@@ -1910,7 +1910,8 @@ def claude_uninstall(project_dir: Path | None = None, *, project: bool = False)
def codebuddy_install(project_dir: Path | None = None) -> None:
"""Write the graphify section to the local CODEBUDDY.md."""
"""Install the graphify skill and CODEBUDDY.md section for CodeBuddy."""
_copy_skill_file("codebuddy", project=bool(project_dir), project_dir=project_dir)
target = (project_dir or Path(".")) / "CODEBUDDY.md"
if target.exists():
+4 -1
View File
@@ -686,8 +686,11 @@ def find_import_cycles(
return []
# Step 2: Find simple cycles, bounded by length.
# Pass length_bound so networkx prunes during enumeration rather than
# enumerating all elementary cycles and post-filtering — avoids exponential
# blowup on dense graphs with many long cycles (#1196).
cycles: list[list[str]] = []
for cycle in nx.simple_cycles(file_graph):
for cycle in nx.simple_cycles(file_graph, length_bound=max_cycle_length):
if len(cycle) <= max_cycle_length:
cycles.append(cycle)
if len(cycles) >= top_n * 10:
+3 -1
View File
@@ -311,8 +311,10 @@ def build(
return build_from_json(combined, directed=directed, root=root)
def _norm_label(label: str) -> str:
def _norm_label(label: str | None) -> str:
"""Canonical dedup key — Unicode-aware, preserves CJK/word characters."""
if not isinstance(label, str):
label = "" if label is None else str(label)
label = unicodedata.normalize("NFKC", label)
return re.sub(r"[\W_ ]+", " ", label.casefold(), flags=re.UNICODE).strip()
+13 -1
View File
@@ -15,8 +15,10 @@ from rapidfuzz.distance import JaroWinkler
# ── helpers ───────────────────────────────────────────────────────────────────
def _norm(label: str) -> str:
def _norm(label: str | None) -> str:
"""Lowercase + collapse non-alphanumeric runs to space (Unicode-aware)."""
if not isinstance(label, str):
label = "" if label is None else str(label)
label = unicodedata.normalize("NFKC", label)
return re.sub(r"[\W_]+", " ", label.casefold(), flags=re.UNICODE).strip()
@@ -243,6 +245,13 @@ def deduplicate_entities(
continue
if _short_label_blocked(norm_label, neighbor_norm, score):
continue
# Prefix-extension pairs (getActiveSession / getActiveSessions,
# parseConfig / parseConfigFile) are almost never duplicates —
# one is a strict suffix-extension of the other. Block the merge
# regardless of JW score (#1201).
_lo, _hi = sorted((norm_label, neighbor_norm), key=len)
if _hi.startswith(_lo) and _hi != _lo:
continue
c1 = communities.get(node_id)
c2 = communities.get(neighbor_id)
@@ -370,6 +379,9 @@ def _llm_tiebreak(
continue
if _short_label_blocked(norm_i, norm_j, score):
continue
_lo, _hi = sorted((norm_i, norm_j), key=len)
if _hi.startswith(_lo) and _hi != _lo:
continue
c1 = communities.get(node["id"])
c2 = communities.get(neighbor["id"])
if (c1 is not None and c2 is not None and c1 == c2
+1 -1
View File
@@ -25,7 +25,7 @@ class FileType(str, Enum):
_MANIFEST_PATH = "graphify-out/manifest.json"
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml', '.cls', '.trigger'}
CODE_EXTENSIONS = {'.py', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.ejs', '.ets', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.svh', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk', '.sh', '.bash', '.json', '.tf', '.tfvars', '.hcl', '.dm', '.dme', '.dmi', '.dmm', '.dmf', '.sln', '.slnx', '.csproj', '.fsproj', '.vbproj', '.razor', '.cshtml', '.cls', '.trigger'}
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
+3 -1
View File
@@ -102,8 +102,10 @@ def _obsidian_tag(name: str) -> str:
return re.sub(r"[^a-zA-Z0-9_\-/]", "", name.replace(" ", "_"))
def _strip_diacritics(text: str) -> str:
def _strip_diacritics(text: str | None) -> str:
import unicodedata
if not isinstance(text, str):
text = "" if text is None else str(text)
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
+88 -1
View File
@@ -9814,7 +9814,7 @@ def extract_bash(path: Path) -> dict:
return {"nodes": nodes, "edges": edges}
# ── .NET project files (.sln, .csproj, .razor) ──────────────────────────────
# ── .NET project files (.sln, .slnx, .csproj, .razor) ───────────────────────
def extract_sln(path: Path) -> dict:
"""Extract projects and inter-project dependencies from a .sln file."""
@@ -9890,6 +9890,92 @@ def extract_sln(path: Path) -> dict:
return {"nodes": nodes, "edges": edges}
def extract_slnx(path: Path) -> dict:
"""Extract projects and inter-project dependencies from a .slnx file.
.slnx is the XML-based replacement for the legacy .sln format. Projects
are listed as ``<Project Path="..."/>`` elements (optionally nested inside
``<Folder>`` elements) and build-order dependencies as ``<BuildDependency
Project="..."/>`` children. Unlike .sln there are no GUIDs -- projects are
identified by their path.
"""
import xml.etree.ElementTree as ET
try:
src = path.read_bytes()
except OSError:
return {"nodes": [], "edges": [], "error": f"cannot read {path}"}
if len(src) > _PROJECT_XML_MAX_BYTES:
return {"nodes": [], "edges": [], "error": "project file too large"}
if not _project_xml_is_safe(src):
return {"nodes": [], "edges": [],
"error": "refusing XML with DOCTYPE/ENTITY declaration"}
try:
tree = ET.fromstring(src)
except ET.ParseError as e:
return {"nodes": [], "edges": [], "error": f"XML parse error: {e}"}
file_nid = _make_id(str(path))
str_path = str(path)
nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code",
"source_file": str_path, "source_location": None}]
edges: list[dict] = []
seen_ids: set[str] = set()
seen_ids.add(file_nid)
ns = ""
if tree.tag.startswith("{"):
ns = tree.tag.split("}")[0] + "}"
def _resolve(proj_path: str) -> str:
proj_path = proj_path.replace("\\", "/")
try:
return str((path.parent / proj_path).resolve())
except Exception:
return proj_path
# First pass: collect projects (anywhere in the tree, incl. <Folder>).
project_nids: set[str] = set()
for proj in tree.iter(f"{ns}Project"):
proj_path = proj.get("Path")
if not proj_path:
continue
abs_proj = _resolve(proj_path)
proj_nid = _make_id(abs_proj)
if proj_nid and proj_nid not in seen_ids:
seen_ids.add(proj_nid)
label = Path(proj_path).stem
nodes.append({"id": proj_nid, "label": label,
"file_type": "code", "source_file": abs_proj,
"source_location": None})
edges.append({"source": file_nid, "target": proj_nid,
"relation": "contains", "confidence": "EXTRACTED",
"source_file": str_path, "weight": 1.0})
if proj_nid:
project_nids.add(proj_nid)
# Second pass: build-order dependencies between known projects.
for proj in tree.iter(f"{ns}Project"):
proj_path = proj.get("Path")
if not proj_path:
continue
from_nid = _make_id(_resolve(proj_path))
for dep in proj.iter(f"{ns}BuildDependency"):
dep_path = dep.get("Project")
if not dep_path:
continue
to_nid = _make_id(_resolve(dep_path))
if (from_nid and to_nid and from_nid != to_nid
and to_nid in project_nids):
edges.append({"source": from_nid, "target": to_nid,
"relation": "imports", "confidence": "EXTRACTED",
"source_file": str_path, "weight": 1.0})
return {"nodes": nodes, "edges": edges}
def extract_csproj(path: Path) -> dict:
"""Extract packages, project refs, and target framework from a .csproj/.fsproj/.vbproj."""
import xml.etree.ElementTree as ET
@@ -11024,6 +11110,7 @@ _DISPATCH: dict[str, Any] = {
".dmm": extract_dmm,
".dmf": extract_dmf,
".sln": extract_sln,
".slnx": extract_slnx,
".csproj": extract_csproj,
".fsproj": extract_csproj,
".vbproj": extract_csproj,
+76 -19
View File
@@ -689,6 +689,7 @@ def _call_openai_compat(
backend: str = "",
deep_mode: bool = False,
images: list[_ImageRef] | None = None,
extra_body: dict | None = None,
) -> dict:
"""Call any OpenAI-compatible API (Kimi, OpenAI, etc.) and return parsed JSON."""
try:
@@ -715,8 +716,14 @@ def _call_openai_compat(
kwargs["temperature"] = temperature
if reasoning_effort is not None:
kwargs["reasoning_effort"] = reasoning_effort
# A custom provider in providers.json can pass its own extra_body (e.g.
# `chat_template_kwargs.enable_thinking=false` for self-hosted Qwen3 served
# by vLLM). When supplied, it wins over the moonshot default — the user has
# explicitly chosen the request shape for their endpoint.
if extra_body is not None:
kwargs["extra_body"] = extra_body
# Kimi-k2.6 is a reasoning model — disable thinking so content isn't empty
if "moonshot" in base_url:
elif "moonshot" in base_url:
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
# than that — the symptom is hollow 200 OK responses after the first few
@@ -726,7 +733,9 @@ def _call_openai_compat(
# hollow-200 symptom — just from a different direction (#798 follow-up).
# Formula: actual input tokens + output cap + system prompt headroom.
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
if backend == "ollama":
# The ollama num_ctx auto-derive is a default. A custom provider that
# explicitly sets extra_body has opted out — respect their request shape.
if backend == "ollama" and extra_body is None:
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
# Auto-derive num_ctx from actual chunk size regardless — used as the
# fallback and for the mismatch check below.
@@ -1153,6 +1162,7 @@ def extract_files_direct(
backend=backend,
deep_mode=deep_mode,
images=image_refs,
extra_body=cfg.get("extra_body"),
)
@@ -1638,7 +1648,11 @@ def _call_llm(prompt: str, *, backend: str, max_tokens: int = 200) -> str:
kwargs["temperature"] = temperature
if cfg.get("reasoning_effort"):
kwargs["reasoning_effort"] = cfg["reasoning_effort"]
if "moonshot" in cfg["base_url"]:
# Custom providers can override via providers.json `extra_body`; falls back
# to the moonshot default to preserve existing behavior.
if cfg.get("extra_body") is not None:
kwargs["extra_body"] = cfg["extra_body"]
elif "moonshot" in cfg["base_url"]:
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
resp = client.chat.completions.create(**kwargs)
if not resp.choices or resp.choices[0].message is None:
@@ -1767,9 +1781,10 @@ def detect_backend() -> str | None:
# batched call and return a complete ``{cid: name}`` map (#1097).
_LABEL_FENCE_RE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.IGNORECASE)
_LABEL_MAX_COMMUNITIES = 200 # cap LLM-named communities; tail stays placeholder
_LABEL_MAX_COMMUNITIES = 200 # legacy soft-cap; kept for callers that pin it.
_LABEL_TOP_K = 12 # node labels sampled per community for the prompt
_LABEL_MAXLEN = 60 # truncate individual labels to keep the prompt small
_LABEL_BATCH_SIZE = 100 # communities per LLM call; sized for ~16k context windows
def _placeholder_community_labels(communities) -> dict[int, str]:
@@ -1830,31 +1845,73 @@ def label_communities(
*,
backend: str,
gods=None,
max_communities: int = _LABEL_MAX_COMMUNITIES,
max_communities: int | None = None,
top_k: int = _LABEL_TOP_K,
batch_size: int = _LABEL_BATCH_SIZE,
) -> dict[int, str]:
"""Return a complete ``{cid: name}`` map using ``backend`` for naming.
Placeholders (``Community N``) are used for any community the backend did not
name. Raises on backend/parse failure - callers that want graceful
degradation should use :func:`generate_community_labels`.
Communities are labeled in batches of ``batch_size`` so the prompt fits in a
16k-token context window (which is enough for one batch of ~100 communities
× ``top_k`` node labels). With the previous hard cap of 200 communities in a
single call, self-hosted 16k models (Qwen3, Llama 3.1 8B-Instruct, etc.)
routinely overflowed context and dropped the entire labeling pass to
placeholders.
``max_communities=None`` (the default) labels every community. Pass an
integer to cap the total (the legacy 200 default preserved this behavior;
explicit callers can still pin it). Placeholders (``Community N``) are used
for any community the backend did not name. Per-batch failures are logged
to stderr and skipped — the surviving batches still contribute labels.
Raises on the first batch's backend/parse failure if it leaves *no* labels
written. Callers that want graceful degradation should use
:func:`generate_community_labels`.
"""
labels = _placeholder_community_labels(communities)
lines, labeled_cids = _community_label_lines(G, communities, gods, max_communities, top_k)
cap = len(communities) if max_communities is None else max_communities
lines, labeled_cids = _community_label_lines(G, communities, gods, cap, top_k)
if not lines:
return labels
prompt = (
"You are naming clusters in a knowledge graph. For each community below, "
"return a concise 2-5 word plain-language name describing what it is about "
"(e.g. \"Order Management\", \"Payment Flow\", \"Auth Middleware\"). "
"Respond ONLY with a JSON object mapping the community id (as a string) to "
"its name - no prose, no markdown fences.\n\n" + "\n".join(lines)
)
n_batches = (len(labeled_cids) + batch_size - 1) // batch_size
written = 0
first_error: Exception | None = None
for batch_idx in range(n_batches):
start = batch_idx * batch_size
end = min(start + batch_size, len(labeled_cids))
batch_lines = lines[start:end]
batch_cids = labeled_cids[start:end]
max_tokens = min(40 + 16 * len(labeled_cids), 4096)
text = _call_llm(prompt, backend=backend, max_tokens=max_tokens)
labels.update(_parse_label_response(text, labeled_cids))
prompt = (
"You are naming clusters in a knowledge graph. For each community below, "
"return a concise 2-5 word plain-language name describing what it is about "
"(e.g. \"Order Management\", \"Payment Flow\", \"Auth Middleware\"). "
"Respond ONLY with a JSON object mapping the community id (as a string) to "
"its name - no prose, no markdown fences.\n\n" + "\n".join(batch_lines)
)
# 24 tok/community covers 2-5 word JSON entries including id, quotes,
# and punctuation. Cap at 8192 for 16k-context models. Wrapped in
# _resolve_max_tokens so GRAPHIFY_MAX_OUTPUT_TOKENS applies here too (#1200).
max_tokens = _resolve_max_tokens(min(64 + 24 * len(batch_cids), 8192))
try:
text = _call_llm(prompt, backend=backend, max_tokens=max_tokens)
parsed = _parse_label_response(text, batch_cids)
labels.update(parsed)
written += len(parsed)
except Exception as exc:
if first_error is None:
first_error = exc
print(
f"[graphify label] batch {batch_idx + 1}/{n_batches} "
f"({len(batch_cids)} communities) failed: {exc}",
file=sys.stderr,
)
continue
if written == 0 and first_error is not None:
# Every batch failed; propagate so generate_community_labels degrades cleanly.
raise first_error
return labels
+3 -1
View File
@@ -51,8 +51,10 @@ def _communities_from_graph(G: nx.Graph) -> dict[int, list[str]]:
return communities
def _strip_diacritics(text: str) -> str:
def _strip_diacritics(text: str | None) -> str:
import unicodedata
if not isinstance(text, str):
text = "" if text is None else str(text)
nfkd = unicodedata.normalize("NFKD", text)
return "".join(c for c in nfkd if not unicodedata.combining(c))
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify-windows
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
+3 -2
View File
@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.8.34"
version = "0.8.36"
description = "AI coding assistant skill (Claude Code, CodeBuddy, Codex, OpenCode, Kilo Code, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Devin CLI, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codebuddy", "codex", "opencode", "kilo", "cursor", "gemini", "aider", "kiro", "pi", "devin", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
keywords = ["claude", "claude-code", "codex", "opencode", "kilo", "cursor", "gemini", "aider", "kiro", "pi", "devin", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10"
dependencies = [
"networkx>=3.4",
@@ -75,6 +75,7 @@ all = ["mcp", "neo4j", "pypdf", "markdownify", "watchdog", "graspologic; python_
[project.scripts]
graphify = "graphify.__main__:main"
graphify-mcp = "graphify.serve:_main"
[dependency-groups]
dev = [
+7
View File
@@ -0,0 +1,7 @@
<Solution>
<Project Path="src/Domain/Domain.csproj" />
<Project Path="src/WebApi/WebApi.csproj">
<BuildDependency Project="src/Domain/Domain.csproj" />
</Project>
<Project Path="tests/Tests/Tests.csproj" />
</Solution>
+61
View File
@@ -177,3 +177,64 @@ def test_variant_pair_helper():
assert _is_variant_pair("cortex a55", "cortex a55x")
assert not _is_variant_pair("graphextractor", "graphextracter")
assert not _is_variant_pair("foo", "foo")
def test_prefix_extension_symbols_not_merged():
"""Distinct symbols whose name is a strict prefix-extension of another must not
be merged (#1201). getActiveSession / getActiveSessions score ~98.82 JW but are
different functions; parseConfig / parseConfigFile likewise."""
import networkx as nx
from graphify.dedup import deduplicate_entities
pairs = [
("getActiveSession", "getActiveSessions"),
("parseConfig", "parseConfigFile"),
("load", "loadAll"),
("handleRequest", "handleRequestTimeout"),
]
for a, b in pairs:
nodes = [
{"id": f"{a}_id", "label": a, "type": "CODE", "src_file": "api.py"},
{"id": f"{b}_id", "label": b, "type": "CODE", "src_file": "api.py"},
]
edges = [{"src": f"{a}_id", "tgt": f"{b}_id", "relation": "calls",
"c": 1.0, "weight": 1.0}]
out_nodes, _ = deduplicate_entities(
nodes, edges, communities={f"{a}_id": 0, f"{b}_id": 0}
)
labels = {n["label"] for n in out_nodes}
assert a in labels and b in labels, (
f"#1201 regression: '{a}' and '{b}' were merged — they are distinct symbols"
)
def test_prefix_guard_does_not_block_same_length_typos():
"""The prefix-extension guard must not fire for same-length pairs — only strict
prefix-extensions (one is a substring of the other) should be blocked (#1201).
graphextractor / graphextractar have the same length, so neither starts-with the
other, and the guard must not fire."""
from graphify.dedup import _norm
a = _norm("GraphExtractor") # "graphextractor" — 14 chars
b = _norm("GraphExtractar") # "graphextractar" — 14 chars
lo, hi = sorted((a, b), key=len)
# Same-length pair: startswith only holds when strings are identical
assert not (hi.startswith(lo) and hi != lo), (
f"Prefix guard fires on same-length pair ({a!r}, {b!r}) — should not"
)
def test_prefix_guard_fires_for_extension_pairs():
"""The prefix-extension guard must fire for pairs where one is a strict prefix
of the other, preventing false merges (#1201)."""
from graphify.dedup import _norm
pairs = [
("getActiveSession", "getActiveSessions"),
("parseConfig", "parseConfigFile"),
("load", "loadAll"),
]
for a_raw, b_raw in pairs:
a, b = _norm(a_raw), _norm(b_raw)
lo, hi = sorted((a, b), key=len)
assert hi.startswith(lo) and hi != lo, (
f"Prefix guard should fire for ({a!r}, {b!r}) but did not"
)
+38 -3
View File
@@ -2,7 +2,7 @@
from pathlib import Path
import tempfile
import pytest
from graphify.extract import extract_sln, extract_csproj, extract_razor
from graphify.extract import extract_sln, extract_slnx, extract_csproj, extract_razor
FIXTURES = Path(__file__).parent / "fixtures"
@@ -37,6 +37,41 @@ def test_sln_project_dependency():
assert "imports" in _relations(r)
# ── .slnx ────────────────────────────────────────────────────────────────────
def test_slnx_extracts_projects():
r = extract_slnx(FIXTURES / "sample.slnx")
assert "error" not in r
labels = set(_labels(r))
assert "WebApi" in labels
assert "Domain" in labels
assert "Tests" in labels
def test_slnx_contains_edges():
r = extract_slnx(FIXTURES / "sample.slnx")
contains = [e for e in r["edges"] if e["relation"] == "contains"]
assert len(contains) == 3
def test_slnx_project_dependency():
r = extract_slnx(FIXTURES / "sample.slnx")
assert "imports" in _relations(r)
def test_slnx_invalid_xml():
with tempfile.NamedTemporaryFile(suffix=".slnx", mode="w", delete=False) as f:
f.write("<Solution><Project></Solution>")
f.flush()
r = extract_slnx(Path(f.name))
assert "error" in r
def test_slnx_missing_file():
r = extract_slnx(Path("/nonexistent/file.slnx"))
assert "error" in r
# ── .csproj ──────────────────────────────────────────────────────────────────
def test_csproj_packages():
@@ -115,11 +150,11 @@ def test_razor_missing_file():
def test_dispatch_table():
from graphify.extract import _get_extractor
for ext in (".sln", ".csproj", ".fsproj", ".vbproj", ".razor", ".cshtml"):
for ext in (".sln", ".slnx", ".csproj", ".fsproj", ".vbproj", ".razor", ".cshtml"):
assert _get_extractor(Path(f"foo{ext}")) is not None, f"{ext} not in dispatch"
def test_code_extensions():
from graphify.detect import CODE_EXTENSIONS
for ext in (".sln", ".csproj", ".fsproj", ".vbproj", ".razor", ".cshtml"):
for ext in (".sln", ".slnx", ".csproj", ".fsproj", ".vbproj", ".razor", ".cshtml"):
assert ext in CODE_EXTENSIONS, f"{ext} missing"
+93
View File
@@ -117,3 +117,96 @@ def test_empty_communities_returns_placeholders(monkeypatch):
labels = label_communities(G, {0: []}, backend="gemini")
assert labels == {0: "Community 0"}
assert called is False
# ---------------------------------------------------------------------------
# Multi-batch labeling: a single prompt with >100 communities overflows the
# 16k context window of self-hosted reasoning models (Qwen3, Llama-3.1 8B).
# label_communities now splits into batches so coverage stays complete.
# ---------------------------------------------------------------------------
def _wide_graph(n_communities: int):
G = nx.Graph()
communities: dict[int, list[str]] = {}
for cid in range(n_communities):
a, b = f"c{cid}_a", f"c{cid}_b"
G.add_node(a, label=f"node_{cid}_a")
G.add_node(b, label=f"node_{cid}_b")
communities[cid] = [a, b]
return G, communities
def test_label_communities_batches_when_over_batch_size(monkeypatch):
G, communities = _wide_graph(250)
calls = []
def fake_call(prompt, *, backend, max_tokens=200):
# The fake reads which cids the prompt asks about and answers all of them.
cids = [int(line.split(":", 1)[0].removeprefix("Community ").strip())
for line in prompt.splitlines() if line.startswith("Community ")]
calls.append(len(cids))
return "{" + ", ".join(f'"{c}": "Cluster {c}"' for c in cids) + "}"
monkeypatch.setattr("graphify.llm._call_llm", fake_call)
labels = label_communities(G, communities, backend="gemini", batch_size=100)
# 250 communities / 100 per batch -> 3 batches (100, 100, 50)
assert calls == [100, 100, 50]
# And every community got a real name, none left as a placeholder.
assert all(name.startswith("Cluster ") for name in labels.values()), \
f"some communities still have placeholders: {[k for k, v in labels.items() if not v.startswith('Cluster ')][:5]}"
assert len(labels) == 250
def test_label_communities_partial_batch_failure_keeps_successful_batches(monkeypatch):
G, communities = _wide_graph(150)
n_calls = [0]
def fake_call(prompt, *, backend, max_tokens=200):
n_calls[0] += 1
cids = [int(line.split(":", 1)[0].removeprefix("Community ").strip())
for line in prompt.splitlines() if line.startswith("Community ")]
if n_calls[0] == 2:
raise RuntimeError("simulated transient backend failure")
return "{" + ", ".join(f'"{c}": "Named {c}"' for c in cids) + "}"
monkeypatch.setattr("graphify.llm._call_llm", fake_call)
labels = label_communities(G, communities, backend="gemini", batch_size=50)
# 3 batches; second one fails. First and third produce real labels;
# the failed batch's cids stay as placeholders.
real = [cid for cid, name in labels.items() if name.startswith("Named ")]
placeholder = [cid for cid, name in labels.items() if name.startswith("Community ")]
assert len(real) == 100, f"expected 100 real labels from 2 successful batches, got {len(real)}"
assert len(placeholder) == 50, f"expected 50 placeholders from the failed batch, got {len(placeholder)}"
def test_label_communities_all_batches_fail_raises(monkeypatch):
G, communities = _wide_graph(150)
def always_fail(prompt, *, backend, max_tokens=200):
raise RuntimeError("backend down")
monkeypatch.setattr("graphify.llm._call_llm", always_fail)
# Every batch fails -> propagate so generate_community_labels can degrade.
with pytest.raises(RuntimeError, match="backend down"):
label_communities(G, communities, backend="gemini", batch_size=50)
def test_label_communities_max_communities_caps_total(monkeypatch):
# Backwards compat: explicit max_communities still caps the total labeled,
# so callers that pinned the legacy 200-default keep their behavior.
G, communities = _wide_graph(150)
captured_cids = []
def fake_call(prompt, *, backend, max_tokens=200):
cids = [int(line.split(":", 1)[0].removeprefix("Community ").strip())
for line in prompt.splitlines() if line.startswith("Community ")]
captured_cids.extend(cids)
return "{" + ", ".join(f'"{c}": "X{c}"' for c in cids) + "}"
monkeypatch.setattr("graphify.llm._call_llm", fake_call)
label_communities(G, communities, backend="gemini", max_communities=40, batch_size=100)
# Only 40 communities should have been sent to the backend.
assert len(captured_cids) == 40
+52
View File
@@ -429,6 +429,58 @@ def test_non_ollama_backend_gets_no_num_ctx_extra_body(monkeypatch):
assert eb is None or "options" not in eb, "non-ollama backends must not get num_ctx injection"
# ---------------------------------------------------------------------------
# Custom-provider extra_body: lets providers.json route around the moonshot-only
# default. Self-hosted Qwen3 served by vLLM needs
# `chat_template_kwargs.enable_thinking=false` or the model emits chain-of-thought
# instead of the JSON the extraction parser expects.
# ---------------------------------------------------------------------------
def test_call_openai_compat_uses_explicit_extra_body(monkeypatch):
captured = _install_capturing_openai(monkeypatch)
llm._call_openai_compat(
"https://kitor.example/vllm/v1", "tk", "Qwen3.6-27B",
"u", temperature=0, max_completion_tokens=8192, backend="kitor-vllm",
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
assert captured["extra_body"] == {"chat_template_kwargs": {"enable_thinking": False}}
def test_call_openai_compat_extra_body_wins_over_moonshot_default(monkeypatch):
# A user could legitimately set up a moonshot-compatible custom provider
# and want a different extra_body — explicit kwarg must override the default.
captured = _install_capturing_openai(monkeypatch)
llm._call_openai_compat(
"https://api.moonshot.ai/v1", "tk", "kimi-k2-thinking",
"u", temperature=0, max_completion_tokens=8192, backend="kimi",
extra_body={"thinking": {"type": "enabled"}},
)
assert captured["extra_body"] == {"thinking": {"type": "enabled"}}
def test_call_openai_compat_explicit_extra_body_skips_ollama_auto_derive(monkeypatch):
# An explicit extra_body means "I own this request shape" — Ollama's
# num_ctx auto-derive (a default) must step aside or we'd clobber it.
captured = _install_capturing_openai(monkeypatch)
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
llm._call_openai_compat(
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
extra_body={"options": {"num_ctx": 4096}},
)
assert captured["extra_body"] == {"options": {"num_ctx": 4096}}, (
"explicit extra_body must replace the ollama auto-derived num_ctx"
)
def test_extract_corpus_parallel_ollama_runs_serially(tmp_path, monkeypatch):
# With 3 chunks and backend=ollama, ThreadPoolExecutor must NOT be used
# (workers=1 takes the sequential path). We verify by ensuring all chunks
+12 -14
View File
@@ -365,20 +365,13 @@ def test_all_progressive_hosts_check_and_audit_clean():
assert probs == [], f"[{key}] audit\n" + "\n".join(probs)
def test_kiro_and_pi_omit_the_trigger_line():
"""kiro and pi render no frontmatter trigger (trigger absent in v8)."""
for key in ("kiro", "pi"):
def test_no_host_has_trigger_in_frontmatter():
"""No split host emits a trigger: field — not part of Agent Skills spec (#1180)."""
for key in ("claude", "codex", "opencode", "kilo", "copilot", "claw", "droid",
"amp", "trae", "vscode", "kiro", "pi"):
core, _ = _platform_artifacts(key)
head = core.split("---", 2)[1]
assert "trigger:" not in head, f"[{key}] unexpectedly has a trigger line"
def test_triggered_hosts_keep_the_trigger_line():
"""The other split hosts keep trigger: /graphify in the frontmatter."""
for key in ("opencode", "kilo", "copilot", "claw", "droid", "amp", "trae", "vscode"):
core, _ = _platform_artifacts(key)
head = core.split("---", 2)[1]
assert "trigger: /graphify" in head, f"[{key}] missing trigger line"
assert "trigger:" not in head, f"[{key}] unexpectedly has a trigger: line"
def test_kilo_renders_its_rules_tail_section():
@@ -466,10 +459,15 @@ def test_monoliths_change_only_the_enum_description_and_chunk_cleanup():
platforms = gen.load_platforms()
for key in ("aider", "devin"):
rendered = gen.render(platforms[key])[0].content.splitlines()
original = gen._normalise(gen._git_show(platforms[key].roundtrip_ref)).splitlines()
# Strip trigger: lines from the reference — their removal (#1180) is a
# permitted diff alongside enum, description, and chunk-cleanup changes.
original = [
l for l in gen._normalise(gen._git_show(platforms[key].roundtrip_ref)).splitlines()
if not gen._is_trigger_line(l)
]
assert len(rendered) == len(original), f"[{key}] line count changed"
diff_idx = [i for i, (r, o) in enumerate(zip(rendered, original)) if r != o]
# Exactly four lines change: the prose enum guidance, the schema line,
# Four lines change: the prose enum guidance, the schema line,
# the frontmatter description, and the chunk-cleanup rewrite.
assert len(diff_idx) == 4, f"[{key}] expected 4 changed lines, got {len(diff_idx)}"
enum_changes = 0
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify-windows
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
-1
View File
@@ -1,7 +1,6 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger: /graphify
---
# /graphify
+20 -10
View File
@@ -244,7 +244,7 @@ class Platform:
refs_dst: str | None = None
name: str = "graphify"
description: str | None = None
trigger: str | None = "/graphify"
trigger: str | None = None # removed — not part of Agent Skills spec (#1180)
dispatch: str | None = None
query_variant: str = "cli-inline"
extraction: str = "verbose"
@@ -283,7 +283,7 @@ def load_platforms() -> dict[str, Platform]:
refs_dst=cfg.get("refs_dst"),
name=cfg.get("name", "graphify"),
description=cfg.get("description"),
trigger=cfg.get("trigger", "/graphify"),
trigger=cfg.get("trigger"),
dispatch=cfg.get("dispatch"),
query_variant=cfg.get("query_variant", "cli-inline"),
extraction=cfg.get("extraction", "verbose"),
@@ -318,16 +318,14 @@ class RenderedArtifact:
def _render_frontmatter(platform: Platform) -> str:
"""Render the YAML frontmatter from the platform's name/description/trigger.
"""Render the YAML frontmatter from the platform's name and description.
The trigger line is omitted when the platform has no trigger (kiro/pi).
Only emits fields from the Agent Skills spec (name, description).
The description is preserved verbatim from platforms.toml — never invented.
"""
if platform.description is None:
raise ValueError(f"split platform '{platform.key}' is missing a description")
lines = ["---", f"name: {platform.name}", f'description: "{platform.description}"']
if platform.trigger:
lines.append(f"trigger: {platform.trigger}")
lines.append("---")
return "\n".join(lines)
@@ -718,6 +716,15 @@ def _is_chunk_cleanup_line(line: str) -> bool:
return line.lstrip().startswith("rm -f") and "find " in line and "-name '.graphify_chunk_" in line
def _is_trigger_line(line: str) -> bool:
"""Whether a line is the non-spec ``trigger:`` frontmatter field (#1180).
The Agent Skills spec does not include ``trigger:`` — only name/description
and a few optional fields. Removing it is a permitted monolith diff.
"""
return line.strip().startswith("trigger:")
def monolith_roundtrip(platform: Platform) -> list[str]:
"""Assert a monolith renders diff-clean vs its v8 blob modulo allowed changes.
@@ -735,14 +742,17 @@ def monolith_roundtrip(platform: Platform) -> list[str]:
original = _normalise(_git_show(platform.roundtrip_ref))
rendered_lines = rendered.splitlines()
original_lines = original.splitlines()
# Strip trigger lines from the original before comparing — they are non-spec
# and their removal (#1180) is a permitted diff. Filter here so the line-count
# check and the per-line zip both operate on the same reduced set.
original_lines = [l for l in original.splitlines() if not _is_trigger_line(l)]
problems: list[str] = []
if len(rendered_lines) != len(original_lines):
problems.append(
f"[{platform.key}] line count differs: rendered {len(rendered_lines)} vs v8 {len(original_lines)} "
"(the only allowed changes are the enum line(s) and the description line, "
"which must not add or remove lines)"
"(the only allowed changes are the enum line(s), the description line, "
"the chunk-cleanup rewrite, and trigger: removal — none must add or remove other lines)"
)
return problems
@@ -750,7 +760,7 @@ def monolith_roundtrip(platform: Platform) -> list[str]:
if r == o:
continue
# The permitted diffs are the enum unification, the unified description,
# and the shell-agnostic chunk-cleanup rewrite (#1172).
# the shell-agnostic chunk-cleanup rewrite (#1172), and trigger removal (#1180).
if _is_enum_line(r) or _is_frontmatter_description_line(r) or _is_chunk_cleanup_line(r):
continue
problems.append(
-3
View File
@@ -18,7 +18,6 @@
# refs_dst rendered references/ dir, relative to the repo root (split only).
# name frontmatter name (default "graphify"; graphify-windows for windows).
# description frontmatter description, PRESERVED VERBATIM per platform. Required.
# trigger frontmatter trigger (default "/graphify"; omit -> no trigger line).
# dispatch Part-B dispatch fragment basename under fragments/dispatch/.
# query_variant cli | cli-inline. Selects both the core query stub and the
# query reference body.
@@ -158,7 +157,6 @@ core = "core"
skill_dst = "graphify/skill-kiro.md"
refs_dst = "graphify/skills/kiro/references"
description = "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger = ""
dispatch = "agent-tool-disk"
query_variant = "cli-inline"
extraction = "compact"
@@ -169,7 +167,6 @@ core = "core"
skill_dst = "graphify/skill-pi.md"
refs_dst = "graphify/skills/pi/references"
description = "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
trigger = ""
dispatch = "agent-tool-disk"
query_variant = "cli-inline"
extraction = "compact"
Generated
+1 -1
View File
@@ -1146,7 +1146,7 @@ wheels = [
[[package]]
name = "graphifyy"
version = "0.8.33"
version = "0.8.35"
source = { editable = "." }
dependencies = [
{ name = "datasketch" },