diff --git a/.mimosa/hook-state/sess_5b750df8-4e1d-4e41-af03-159099d06328.json b/.mimosa/hook-state/sess_5b750df8-4e1d-4e41-af03-159099d06328.json new file mode 100644 index 00000000..2558837f --- /dev/null +++ b/.mimosa/hook-state/sess_5b750df8-4e1d-4e41-af03-159099d06328.json @@ -0,0 +1 @@ +{"touched":[],"bashMutation":true,"reportedFindings":[],"findingEvents":[],"baseline":null,"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-11-04T22:09:37.499Z"} \ No newline at end of file diff --git a/.mimosa/hook-status/sess_5b750df8-4e1d-4e41-af03-159099d06328-ca0588084a.json b/.mimosa/hook-status/sess_5b750df8-4e1d-4e41-af03-159099d06328-ca0588084a.json new file mode 100644 index 00000000..b53d1777 --- /dev/null +++ b/.mimosa/hook-status/sess_5b750df8-4e1d-4e41-af03-159099d06328-ca0588084a.json @@ -0,0 +1,14 @@ +{ + "schemaVersion": "mimosa-hook-status/v1", + "recordedAt": "2026-11-04T22:12:45.504Z", + "sessionId": "sess_5b750df8-4e1d-4e41-af03-159099d06328", + "event": "PostToolUse", + "toolName": "Write", + "file": "C:\\Users\\Saraye Tell\\.zcode\\workspace\\1793817739219-f969f7f5-f09b-41b6-bbb8-59977b8fdd35\\pr-body.md", + "outcome": "clear", + "coverage": "complete", + "findingCount": 0, + "durationMs": 9, + "hostState": "hook_complete", + "reportHint": ".mimosa/reports/" +} diff --git a/external_plugins/graphify-plugin/.gitignore b/external_plugins/graphify-plugin/.gitignore new file mode 100644 index 00000000..b1abea9d --- /dev/null +++ b/external_plugins/graphify-plugin/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +*.pyc +.graphify/ +.mimosa/ diff --git a/external_plugins/graphify-plugin/.zcode-plugin/plugin.json b/external_plugins/graphify-plugin/.zcode-plugin/plugin.json new file mode 100644 index 00000000..2f6663c7 --- /dev/null +++ b/external_plugins/graphify-plugin/.zcode-plugin/plugin.json @@ -0,0 +1,24 @@ +{ + "name": "graphify-plugin", + "version": "0.1.0", + "description": "Turns a codebase into a queryable knowledge graph: scans code, docs and config files, extracts files, symbols, imports and doc references, and produces graph.json (9 query commands), an interactive graph.html and a markdown report under /.graphify/.", + "description_i18n": { + "en": "Turns a codebase into a queryable knowledge graph: scans code, docs and config files, extracts files, symbols, imports and doc references, and produces graph.json (9 query commands), an interactive graph.html and a markdown report under /.graphify/.", + "zh-CN": "将代码库转换为可查询的知识图谱:扫描代码、文档与配置文件,提取文件、符号、import 与文档引用,在 /.graphify/ 下生成可查询的 graph.json(9 个查询命令)、自包含的交互式 graph.html 与 Markdown 报告。" + }, + "author": { + "name": "Movti Group", + "url": "https://github.com/movtigroup" + }, + "keywords": [ + "knowledge-graph", + "code-analysis", + "dependency-graph", + "static-analysis", + "architecture", + "codebase" + ], + "license": "MIT", + "repository": "https://github.com/movtigroup/Graphify-plugin", + "skills": "./skills" +} diff --git a/external_plugins/graphify-plugin/LICENSE b/external_plugins/graphify-plugin/LICENSE new file mode 100644 index 00000000..fac0053a --- /dev/null +++ b/external_plugins/graphify-plugin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Movti Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/graphify-plugin/README.md b/external_plugins/graphify-plugin/README.md new file mode 100644 index 00000000..448c4722 --- /dev/null +++ b/external_plugins/graphify-plugin/README.md @@ -0,0 +1,94 @@ +# Graphify — ZCode Knowledge-Graph Plugin + +[![CI](https://github.com/movtigroup/Graphify-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/movtigroup/Graphify-plugin/actions/workflows/ci.yml) +[![Release](https://github.com/movtigroup/Graphify-plugin/actions/workflows/release.yml/badge.svg)](https://github.com/movtigroup/Graphify-plugin/actions/workflows/release.yml) + +**EN** — Graphify turns a project directory into a **queryable knowledge graph**: it scans code, +docs and config files, extracts files, symbols, imports and doc references, and produces three +artifacts under `/.graphify/`: + +| Artifact | Purpose | +|---|---| +| `graph.json` | nodes (`code`, `doc`, `config`, `symbol`) + edges (`imports`, `contains`, `links`, `mentions`) — queryable with 9 commands | +| `graph.html` | self-contained interactive graph (no CDN, works offline) | +| `graph-report.md` | hubs, orphans (dead-code candidates), external deps, broken doc links | + +**FA** — گرافیفای یک پوشهٔ پروژه را به **گراف دانش قابل کوئری** تبدیل می‌کند: کدها، مستندات و +فایل‌های کانفیگ را اسکن می‌کند و سه خروجی می‌سازد؛ بعد ایجنت به‌جای خواندن مکرر فایل‌ها از خود +گراف کوئری می‌گیرد (قلب سیستم، شعاع تأثیر تغییر، کد بی‌استفاده، لینک‌های خراب مستندات). + +--- + +## Install (نصب) + +### 1) As a ZCode plugin from this repo (recommended) + +1. Open **Plugin Marketplace → Add → Add Plugin Marketplace** +2. Paste: `https://github.com/movtigroup/Graphify-plugin` +3. Install **Graphify** from the list and select the `graphify` skill in the composer picker. + +### 2) Manual — copy the skill + +```bash +# clone and copy the skill into your user skills directory +git clone https://github.com/movtigroup/Graphify-plugin.git +mkdir -p ~/.agents/skills +cp -r Graphify-plugin/skills/graphify ~/.agents/skills/graphify +``` + +### 3) Dev marketplace (local folder) + +Clone the repo and add its **directory** as a marketplace: +**Plugin Marketplace → Add → Add Plugin Marketplace** → paste the cloned folder path. + +--- + +## Usage (استفاده) + +Ask your agent naturally — Persian or English: + +``` +graphify روی پوشهٔ X اجرا کن و بگو قلب سیستم کجاست +who imports utils.py? تغییرش چه چیزی را می‌شکند؟ +این کدبیس رو graphify کن و فایل‌های مرده رو پیدا کن +``` + +Behind the scenes the agent runs `build_graph.py` once, reads `graph-report.md`, and answers +structural questions via `query_graph.py` (info / hubs / orphans / search / node / neighbors / +imports / imported-by / external). Full command reference in +[`skills/graphify/SKILL.md`](skills/graphify/SKILL.md). + +## Requirements (نیازمندی‌ها) + +- ZCode (or Claude Code) with plugin/skill support +- Python 3.8+ on PATH (`py -3` on Windows fallback). The scripts are **stdlib-only** — nothing to install. + +## Side effects (اثرات جانبی) + +- Runs only the two bundled Python scripts (`build_graph.py`, `query_graph.py`) — stdlib-only, **no + network access**, no third-party code or assets. +- Sole file writes: creates `.graphify/` inside the scanned project (graph.json, graph.html, + graph-report.md). Output paths are containment-checked (`realpath` + `commonpath`) and cannot + escape the output directory. +- No credentials, no machine-specific paths, no prebuilt binaries. + +## Development (توسعه) + +```bash +python tests/validate.py # manifest + skill structure checks +python tests/smoke_test.py # end-to-end: build + query on the sample fixture +``` + +CI runs both on **Ubuntu and Windows** for every push/PR; tagged releases (`v*`) are packaged as +zip and published on GitHub Releases automatically. + +## Status (وضعیت) + +- ✅ Plugin structure per ZCode manifest spec (`.zcode-plugin/plugin.json` + marketplace entry) +- ✅ CI on two OSes + tagged release pipeline +- ✅ Stdlib-only, no network access, writes only `/.graphify/` (containment-checked) +- 🚀 Submitted to the official ZCode plugin marketplace + +## License + +MIT © Movti Group diff --git a/external_plugins/graphify-plugin/README_CN.md b/external_plugins/graphify-plugin/README_CN.md new file mode 100644 index 00000000..29aab07b --- /dev/null +++ b/external_plugins/graphify-plugin/README_CN.md @@ -0,0 +1,57 @@ +# Graphify — ZCode 代码知识图谱插件 + +[![CI](https://github.com/movtigroup/Graphify-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/movtigroup/Graphify-plugin/actions/workflows/ci.yml) +[![Release](https://github.com/movtigroup/Graphify-plugin/actions/workflows/release.yml/badge.svg)](https://github.com/movtigroup/Graphify-plugin/actions/workflows/release.yml) + +**中文** — Graphify 将项目目录转换为**可查询的知识图谱**:扫描代码、文档与配置文件,提取文件、符号、import 与文档引用,并在 `<目标目录>/.graphify/` 下生成三个产物: + +| 产物 | 用途 | +|---|---| +| `graph.json` | 节点(`code`/`doc`/`config`/`symbol`)+ 边(`imports`/`contains`/`links`/`mentions`),支持 9 个查询命令 | +| `graph.html` | 自包含的交互式图谱(无 CDN,可离线打开) | +| `graph-report.md` | 枢纽文件、孤立文件(疑似死代码)、外部依赖、失效文档链接 | + +**English** — see [README.md](README.md). **فارسی** — [README.md](README.md) را ببینید. + +## 安装 + +1. **Plugin Marketplace → Add → Add Plugin Marketplace**,粘贴本仓库地址; +2. 合入 ZCode 官方市场后,直接在市场列表安装 **Graphify**; +3. 手动方式:克隆后将 `skills/graphify` 复制到 `~/.agents/skills/`。 + +## 使用 + +用自然语言向智能体提问(中英文均可): + +``` +graphify 扫描这个项目,告诉我系统的核心文件在哪 +谁 import 了 utils.py?改它会影响什么? +找出项目里的死代码 +``` + +底层流程:智能体运行一次 `build_graph.py`,先读 `graph-report.md` 概览,再用 `query_graph.py` +的 9 个命令(info / hubs / orphans / search / node / neighbors / imports / imported-by / external) +回答结构性问题,而不是反复阅读源码文件。 + +## 运行要求 + +- Python 3.8+(仅标准库,无需 pip 安装;Windows 可用 `py -3`)。 +- 支持 ZCode / Claude Code 插件或技能机制。 + +## 副作用与安全 + +- 仅运行插件自带的两个 Python 脚本(`build_graph.py` / `query_graph.py`),纯标准库,**无网络访问**。 +- 唯一的文件写入:在被扫描项目下创建 `.graphify/` 目录;输出路径经过 `realpath` + `commonpath` + 包含性校验,不会逃逸出输出目录。 +- 不含凭据、机器特定路径、混淆代码、预编译二进制或第三方代码/资产。 + +## 开发 + +```bash +python tests/validate.py # 结构校验 +python tests/smoke_test.py # 端到端:构建 + 查询 +``` + +## 许可证 + +MIT © Movti Group diff --git a/external_plugins/graphify-plugin/skills/graphify/SKILL.md b/external_plugins/graphify-plugin/skills/graphify/SKILL.md new file mode 100644 index 00000000..3ebbc693 --- /dev/null +++ b/external_plugins/graphify-plugin/skills/graphify/SKILL.md @@ -0,0 +1,86 @@ +--- +name: graphify +description: > + Build a queryable knowledge graph of a codebase — code, docs and config files — and answer + structural questions from the graph instead of re-reading the whole repo. Produces graph.json + (queryable), graph.html (interactive), graph-report.md (summary). Use whenever the user says + "graphify", asks for a knowledge graph, project map, architecture or dependency overview, + asks "who imports X", "where is X used", "how is this repo structured", or in Persian: + گراف دانش، نقشه پروژه، ساختار پروژه، گراف وابستگی. Trigger even when the user just wants to + understand a codebase before changing it. +--- + +# Graphify — codebase knowledge graph (گراف دانش کدبیس) + +Scan a project directory, build a knowledge graph of what is in it and how things connect, then +answer structural questions from that graph instead of loading file after file into context. + +> 🇮🇷 این اسکیل یک پوشهٔ پروژه را اسکن می‌کند، گراف دانشی از محتوا و ارتباط‌ها می‌سازد و بعد سؤال‌های ساختاری را از خود گراف جواب می‌دهد — نه با خواندن تک‌تک فایل‌ها. + +## Artifacts — everything lands in `/.graphify/` + +| File | Purpose | +|---|---| +| `graph.json` | nodes (`code`, `doc`, `config`, `symbol`) + edges (`imports`, `contains`, `links`, `mentions`) | +| `graph.html` | self-contained interactive graph — give this path to the user to open in a browser | +| `graph-report.md` | summary: hubs, orphans, external deps, missing links — **read this first** | + +> 🇮🇷 سه خروجی: JSON قابل کوئری، HTML تعاملی برای مرورگر، و گزارش مارک‌داون برای شروع. + +## Workflow + +1. If the target root is ambiguous, ask the user; otherwise default to the current working directory. +2. Build the graph (replace `` with this skill's base directory, and `` with the project root): + ```bash + python "/scripts/build_graph.py" "" + ``` + On Windows, if `python` is not found use `py -3`. The script is stdlib-only — nothing to install. +3. Read `/.graphify/graph-report.md` — it is short and answers most overview questions on its own. +4. For anything more specific, query the graph with `query_graph.py` (below) **instead of reading many + source files**. That is the whole point: a graph lookup is far cheaper than re-reading the repo. +5. Give the user the path to `graph.html` and summarize what you found. + +> 🇮🇷 مراحل: بساز → گزارش را بخوان → برای سؤال‌های دقیق‌تر از گراف کوئری بگیر → مسیر HTML را به کاربر بده. + +## Querying + +```bash +python "/scripts/query_graph.py" "/.graphify/graph.json" +``` + +| Command | Answers | +|---|---| +| `info` | size, node/edge counts, top external dependencies | +| `hubs [N]` | most-connected files — the core of the system | +| `orphans` | code files nothing imports — dead-code candidates | +| `search ` | find nodes by name or path | +| `node ` | full detail + direct edges of one node | +| `neighbors [--kind K] [--dir in/out]` | first-degree graph around a node | +| `imports ` | what this file imports (project-internal only) | +| `imported-by ` | what depends on this file — the blast radius of changing it | +| `external [N]` | top third-party packages | + +`` accepts a full node id (`src/app.py`), a bare file name (`app.py`), or a symbol id +(`src/app.py::main`). If several nodes match, the script lists them — pick the right one and re-run. +Add `--json` to any command for raw JSON output. + +> 🇮🇷 دستورهای کلیدی: `hubs` قلب سیستم را نشان می‌دهد، `imported-by` شعاع تأثیر تغییرها، `orphans` کد بی‌استفاده. + +## Reading the graph + +- Edge kinds: `imports` (file→file), `contains` (file→symbol), `links` (doc→file via markdown link), + `mentions` (doc references a path in backticks). +- Symbol nodes are `file.py::name`. Treat them as cheap pointers: answer "where is X defined/used" + from the graph; open the real file only when the user needs the implementation itself. + +> 🇮🇷 انواع یال: `imports` واردکردن فایل، `contains` داشتن نماد، `links` لینک مارک‌داون، `mentions` اشارهٔ متنی به مسیر. + +## Limits (so you don't over-promise) + +- Static and heuristic: regex/AST over text. Dynamic imports, reflection and re-exports may be missed. + A missing import edge is *not* a bug report. +- Scope is code + text docs + configs. Images, PDFs, binaries and notebooks are skipped. +- Very large repos: the HTML renders the 600 most-connected nodes (the JSON always has everything). +- The graph is a snapshot. If the user just made big edits, rebuild before answering. + +> 🇮🇷 محدودیت‌ها: تحلیل ایستا و تقریبی است؛ فقط کد، متن و کانفیگ؛ در مخزن‌های خیلی بزرگ HTML تا ۶۰۰ گرهٔ پرارتفاع را نشان می‌دهد؛ بعد از تغییرهای بزرگ گراف را دوباره بساز. diff --git a/external_plugins/graphify-plugin/skills/graphify/scripts/build_graph.py b/external_plugins/graphify-plugin/skills/graphify/scripts/build_graph.py new file mode 100644 index 00000000..7b995d2b --- /dev/null +++ b/external_plugins/graphify-plugin/skills/graphify/scripts/build_graph.py @@ -0,0 +1,671 @@ +#!/usr/bin/env python3 +"""graphify build — turn a project directory into a queryable knowledge graph. + +Outputs (under /.graphify by default): + graph.json nodes + edges (queryable with query_graph.py) + graph.html self-contained interactive graph + graph-report.md human-readable summary + +Stdlib only. Python 3.8+. +""" +import argparse +import ast +import datetime +import json +import os +import re +import sys +import urllib.parse +from collections import defaultdict +from pathlib import Path + +CODE_EXTS = {".py": "python", ".js": "javascript", ".mjs": "javascript", ".cjs": "javascript", + ".jsx": "javascript", ".ts": "typescript", ".tsx": "typescript"} +DOC_EXTS = {".md": "markdown", ".markdown": "markdown", ".rst": "rst", ".txt": "text"} +CFG_EXTS = {".json": "json", ".yml": "yaml", ".yaml": "yaml", ".toml": "toml", + ".ini": "ini", ".cfg": "ini"} +KNOWN_EXTS = set(CODE_EXTS) | set(DOC_EXTS) | set(CFG_EXTS) + +IGNORE_DIRS = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv", "env", + "dist", "build", "out", ".graphify", ".idea", ".vscode", ".mypy_cache", + ".pytest_cache", ".tox", "target", ".next", ".nuxt", "coverage", ".cache", + "__pypackages__", ".ruff_cache"} +KEEP_HIDDEN = {".github"} +MAX_FILE_BYTES = 1_000_000 +MAX_SYMBOLS = 300 # per file +MAX_MENTIONS = 50 # per doc +HTML_NODE_CAP = 600 + +MD_LINK = re.compile(r"\[[^\]]*\]\(\s*([^)\s]+)") +MD_CODESPAN = re.compile(r"`([^`\n]+)`") +JS_IMPORT = re.compile( + r"(?:import\s+(?:[\w*{}\s,]+?\s+from\s+)?|export\s+(?:[\w*{}\s,]+?\s+from\s+)?|" + r"require\s*\(\s*|import\s*\(\s*)['\"]([^'\"]+)['\"]") +JS_FUNC = re.compile(r"(?:function\s+([A-Za-z_$][\w$]*)\s*\(|class\s+([A-Za-z_$][\w$]*)|" + r"const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:\(|async\b|function\b))") +PY_IMPORT_FALLBACK = re.compile( + r"^\s*(?:from\s+([\w.]+)\s+import\b|import\s+([\w.]+(?:\s*,\s*[\w.]+)*))", re.M) + + +def read_text(path): + try: + with open(path, "r", encoding="utf-8", errors="replace") as f: + return f.read() + except OSError: + return "" + + +def walk_files(root): + """Return sorted [(rel_posix, abs_path)] for files we care about.""" + result = [] + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = sorted( + d for d in dirnames + if d not in IGNORE_DIRS and (not d.startswith(".") or d in KEEP_HIDDEN)) + for name in sorted(filenames): + if name.startswith("."): + continue + abs_path = os.path.join(dirpath, name) + rel = os.path.relpath(abs_path, root).replace(os.sep, "/") + result.append((rel, abs_path)) + return result + + +def classify(rel): + ext = os.path.splitext(rel)[1].lower() + if ext in CODE_EXTS: + return "code", CODE_EXTS[ext] + if ext in DOC_EXTS: + return "doc", DOC_EXTS[ext] + if ext in CFG_EXTS: + return "config", CFG_EXTS[ext] + return None, None + + +# ---------------------------------------------------------------- parsing + +def parse_python(text): + """Return ([(module, level), ...], [symbol, ...]).""" + imports, symbols = [], [] + try: + tree = ast.parse(text) + except SyntaxError: + for m in PY_IMPORT_FALLBACK.finditer(text): + if m.group(1): + imports.append((m.group(1), 0)) + elif m.group(2): + for part in m.group(2).split(","): + part = part.strip() + if part: + imports.append((part, 0)) + return imports, symbols + for node in tree.body: # top-level symbols only + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + symbols.append(node.name) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + imports.append((alias.name, 0)) + elif isinstance(node, ast.ImportFrom): + imports.append((node.module or "", node.level)) + return imports, symbols + + +def parse_js(text): + """Return ([(specifier, 0), ...], [symbol, ...]).""" + imports = [(m.group(1), 0) for m in JS_IMPORT.finditer(text)] + symbols = [] + for m in JS_FUNC.finditer(text): + name = m.group(1) or m.group(2) or m.group(3) + if name and name not in symbols: + symbols.append(name) + return imports, symbols + + +def resolve_py(module, level, rel, rel_set): + if level == 0: + cand = module.replace(".", "/") + else: + parts = rel.split("/")[:-1] + for _ in range(level - 1): + if parts: + parts.pop() + mod_parts = module.split(".") if module else [] + cand = "/".join(parts + mod_parts) + if not cand: + return None + for c in (cand + ".py", cand + "/__init__.py"): + if c in rel_set: + return c + return None + + +def resolve_js(spec, rel, rel_set): + """Return (target_rel_or_None, external_pkg_or_None).""" + if not spec.startswith(".") and not spec.startswith("/"): + pkg = spec if spec.startswith("@") and "/" in spec else spec.split("/")[0] + return None, pkg + parts = [] + for seg in spec.replace("\\", "/").split("/"): + if seg in ("", "."): + continue + if seg == "..": + if parts: + parts.pop() + else: + parts.append(seg) + if not parts: + return None, None + if spec.startswith("/"): + candidates = ["/".join(parts)] + else: + candidates = ["/".join(rel.split("/")[:-1] + parts)] + exts = [".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs", ".json"] + for base in candidates: + tried = [base] + [base + e for e in exts] + [base + "/index" + e for e in exts] + for t in tried: + if t in rel_set: + return t, None + return None, None + + +def make_doc_resolver(rel, rel_set): + base = rel.split("/")[:-1] + + def resolve_path(p): + p = urllib.parse.unquote(p.split("#")[0].split("?")[0]).replace("\\", "/") + if not p or p.startswith(("http://", "https://", "mailto:", "ftp:", "/")): + return None + out = [] + for seg in p.split("/"): + if seg in ("", "."): + continue + if seg == "..": + if out: + out.pop() + else: + out.append(seg) + if not out: + return None + tail = "/".join(out) + if base: # doc-relative first (that's what markdown means) + cand = "/".join(base + out) + if cand in rel_set: + return cand + return tail if tail in rel_set else None + + return resolve_path + + +def parse_doc(text, resolve_path): + """Return (links, mentions, missing). Each entry is a resolved rel path (missing = raw).""" + links, mentions, missing = [], [], [] + for m in MD_LINK.finditer(text): + raw = m.group(1) + target = resolve_path(raw) + if target: + links.append(target) + elif os.path.splitext(raw)[1].lower() in KNOWN_EXTS: + missing.append(raw) + n = 0 + for m in MD_CODESPAN.finditer(text): + if n >= MAX_MENTIONS: + break + tok = m.group(1).strip().rstrip(".,;:") + if not tok or "/" not in tok and os.path.splitext(tok)[1].lower() not in KNOWN_EXTS: + continue + target = resolve_path(tok) + if target: + mentions.append(target) + n += 1 + return links, mentions, missing + + +# ---------------------------------------------------------------- graph build + +def build_graph(root): + files = walk_files(root) + rel_set, parsed, abs_map = set(), {}, {} + for rel, abs_path in files: + kind, lang = classify(rel) + if not kind: + continue + try: + size = os.path.getsize(abs_path) + except OSError: + continue + if size > MAX_FILE_BYTES: + continue + rel_set.add(rel) + parsed[rel] = (kind, lang) + abs_map[rel] = abs_path + + nodes, edges = [], [] + edge_set = set() + external = defaultdict(int) + doc_missing = {} + + def add_edge(a, b, kind): + if a == b: + return + key = (a, b, kind) + if key not in edge_set: + edge_set.add(key) + edges.append({"from": a, "to": b, "kind": kind}) + + for rel in sorted(parsed): + kind, lang = parsed[rel] + label = rel.rsplit("/", 1)[-1] + nodes.append({"id": rel, "type": kind, "label": label, "lang": lang}) + text = read_text(abs_map[rel]) + if kind == "code": + if lang == "python": + imports, symbols = parse_python(text) + else: + imports, symbols = parse_js(text) + for name in symbols[:MAX_SYMBOLS]: + sid = rel + "::" + name + nodes.append({"id": sid, "type": "symbol", "label": name, + "lang": lang, "parent": rel}) + add_edge(rel, sid, "contains") + for raw, level in imports: + if lang == "python": + target = resolve_py(raw, level, rel, rel_set) + if target is None and level == 0 and raw: + external[raw.split(".")[0]] += 1 + else: + target, pkg = resolve_js(raw, rel, rel_set) + if target is None and pkg: + external[pkg] += 1 + if target: + add_edge(rel, target, "imports") + elif kind == "doc": + resolve_path = make_doc_resolver(rel, rel_set) + links, mentions, missing = parse_doc(text, resolve_path) + for t in links: + add_edge(rel, t, "links") + for t in mentions: + add_edge(rel, t, "mentions") + if missing: + doc_missing[rel] = missing[:10] + + by_type = defaultdict(int) + by_lang = defaultdict(int) + for n in nodes: + by_type[n["type"]] += 1 + if n["type"] != "symbol": + by_lang[n.get("lang") or "?"] += 1 + + meta = { + "root": os.path.basename(root) or root, + "generated": datetime.datetime.now().isoformat(timespec="seconds"), + "counts": {"nodes": len(nodes), "edges": len(edges), + "by_type": dict(by_type), "by_lang": dict(by_lang)}, + "external": sorted(external.items(), key=lambda kv: -kv[1])[:25], + "missing_links": dict(list(doc_missing.items())[:30]), + } + return {"meta": meta, "nodes": nodes, "edges": edges} + + +# ---------------------------------------------------------------- html + +HTML_TEMPLATE = r""" +Graphify — knowledge graph + + +
◎ Graphify + + + + +
+ +
+ + +""" + + +def contained_path(out_dir, filename): + """Resolve filename inside out_dir and refuse paths that escape it.""" + full = os.path.realpath(os.path.join(out_dir, filename)) + base = os.path.realpath(out_dir) + if os.path.commonpath([base, full]) != base: + sys.exit("output path escapes output directory: " + filename) + return full + + +def write_html(out_dir, graph): + path = contained_path(out_dir, "graph.html") + data = {"meta": graph["meta"], "nodes": graph["nodes"], "links": graph["edges"]} + ranked = sorted(graph["nodes"], + key=lambda n: -sum(1 for e in graph["edges"] + if e["from"] == n["id"] or e["to"] == n["id"])) + if len(ranked) > HTML_NODE_CAP: + keep = {n["id"] for n in ranked[:HTML_NODE_CAP]} + data["nodes"] = [n for n in graph["nodes"] if n["id"] in keep] + data["links"] = [e for e in graph["edges"] + if e["from"] in keep and e["to"] in keep] + data["meta"]["capped"] = True + data["meta"]["total_nodes"] = len(graph["nodes"]) + payload = json.dumps(data, ensure_ascii=False).replace(" 0] + if hubs: + ap("## Hubs (most connected)") + ap("") + ap("| Node | Type | Imports° | Total° |") + ap("|---|---|---|---|") + for n in hubs: + ap("| `" + n["id"] + "` | " + n["type"] + " | " + + str(import_deg.get(n["id"], 0)) + " | " + str(deg.get(n["id"], 0)) + " |") + ap("") + + orphans = [n for n in nodes + if n["type"] == "code" and import_deg.get(n["id"], 0) == 0] + if orphans: + ap("## Orphan code files (nothing imports them, they import nothing)") + ap("") + for n in orphans[:30]: + ap("- `" + n["id"] + "`") + if len(orphans) > 30: + ap("- … " + str(len(orphans) - 30) + " more") + ap("") + + if meta["external"]: + ap("## External dependencies (top)") + ap("") + ap(", ".join("`" + k + "`×" + str(v) for k, v in meta["external"][:20])) + ap("") + + docs = [n for n in nodes if n["type"] == "doc"] + if docs: + ap("## Docs") + ap("") + for n in sorted(docs, key=lambda n: -deg.get(n["id"], 0))[:15]: + ap("- `" + n["id"] + "` — degree " + str(deg.get(n["id"], 0))) + ap("") + + if meta["missing_links"]: + ap("## Broken doc links (target not found)") + ap("") + for rel, misses in meta["missing_links"].items(): + ap("- `" + rel + "` → " + ", ".join("`" + m + "`" for m in misses)) + ap("") + + big = top([n for n in nodes if symbol_count.get(n["id"])], + lambda n: symbol_count[n["id"]], 10) + if big: + ap("## Largest files by symbol count") + ap("") + for n in big: + ap("- `" + n["id"] + "` — " + str(symbol_count[n["id"]]) + " top-level symbols") + ap("") + + Path(path).write_text("\n".join(lines), encoding="utf-8") + + +# ---------------------------------------------------------------- main + +def main(): + ap = argparse.ArgumentParser(description="Build a knowledge graph of a project directory.") + ap.add_argument("root", help="project directory to scan") + ap.add_argument("--out", help="output directory (default: /.graphify)") + args = ap.parse_args() + root = os.path.realpath(os.path.abspath(args.root)) + if not os.path.isdir(root): + sys.exit("not a directory: " + root) + out_dir = os.path.realpath(os.path.abspath(args.out)) if args.out \ + else os.path.join(root, ".graphify") + os.makedirs(out_dir, exist_ok=True) + + graph = build_graph(root) + json_path = contained_path(out_dir, "graph.json") + html_path = os.path.join(out_dir, "graph.html") + report_path = os.path.join(out_dir, "graph-report.md") + Path(json_path).write_text(json.dumps(graph, ensure_ascii=False, indent=1), encoding="utf-8") + write_html(out_dir, graph) + write_report(out_dir, root, graph) + + c = graph["meta"]["counts"] + print("graphify: scanned %s" % root) + print(" nodes: %d edges: %d (code %d, doc %d, config %d, symbol %d)" % ( + c["nodes"], c["edges"], c["by_type"].get("code", 0), c["by_type"].get("doc", 0), + c["by_type"].get("config", 0), c["by_type"].get("symbol", 0))) + print(" wrote:") + print(" " + json_path) + print(" " + html_path) + print(" " + report_path) + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + main() diff --git a/external_plugins/graphify-plugin/skills/graphify/scripts/query_graph.py b/external_plugins/graphify-plugin/skills/graphify/scripts/query_graph.py new file mode 100644 index 00000000..23837b96 --- /dev/null +++ b/external_plugins/graphify-plugin/skills/graphify/scripts/query_graph.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""graphify query — query a knowledge graph produced by build_graph.py. + +Usage: + query_graph.py GRAPH.json COMMAND [REF] [--kind K] [--dir in|out|both] [--all] [--json] + +Commands: + info size, node/edge counts, top external dependencies + hubs [N] most-connected files (skip symbols unless --all) + orphans code files with no import edges at all + search TERM find nodes by name or path substring + node REF details + direct edges of one node + neighbors REF first-degree edges (--kind imports/contains/links/mentions, --dir in/out) + imports REF what REF imports (project-internal) + imported-by REF what depends on REF (blast radius) + external [N] top third-party packages +""" +import argparse +import json +import sys +from collections import defaultdict + + +def build_index(g): + out_map = defaultdict(list) + in_map = defaultdict(list) + for e in g["edges"]: + out_map[e["from"]].append(e) + in_map[e["to"]].append(e) + return out_map, in_map + + +def resolve(nodes, ref): + """Return (node_or_None, candidates_or_None).""" + for n in nodes: + if n["id"] == ref: + return n, None + exact = [n for n in nodes if n["label"] == ref] + if len(exact) == 1: + return exact[0], None + sub = [n for n in nodes if ref.lower() in n["id"].lower()] + if len(sub) == 1: + return sub[0], None + return None, (exact or sub) or [] + + +def print_candidates(cands): + print("ambiguous reference — matches:") + for n in cands[:20]: + print(" %s [%s]" % (n["id"], n["type"])) + if len(cands) > 20: + print(" … %d more" % (len(cands) - 20)) + print("re-run with a full node id from the list above.") + + +def degree_maps(g): + deg = defaultdict(int) + imp = defaultdict(int) + for e in g["edges"]: + deg[e["from"]] += 1 + deg[e["to"]] += 1 + if e["kind"] == "imports": + imp[e["from"]] += 1 + imp[e["to"]] += 1 + return deg, imp + + +def fmt_edges(edges, direction): + rows = [] + for e in edges: + other = e["to"] if direction == "out" else e["from"] + arrow = "->" if direction == "out" else "<-" + rows.append(" %s %s [%s] %s" % (arrow, other, e["kind"], "")) + return rows + + +def main(): + ap = argparse.ArgumentParser(description="Query a graphify graph.json.") + ap.add_argument("graph") + ap.add_argument("command", + choices=["info", "hubs", "orphans", "search", "node", + "neighbors", "imports", "imported-by", "external"]) + ap.add_argument("ref", nargs="?", help="node id, file name, symbol id, or search term") + ap.add_argument("--kind", help="filter edges by kind") + ap.add_argument("--dir", default="both", choices=["in", "out", "both"]) + ap.add_argument("--all", action="store_true", help="hubs: include symbol nodes") + ap.add_argument("--json", action="store_true", help="emit raw JSON") + args = ap.parse_args() + + try: + with open(args.graph, "r", encoding="utf-8") as f: + g = json.load(f) + except (OSError, ValueError) as exc: + sys.exit("cannot read graph: %s" % exc) + + nodes = g["nodes"] + out_map, in_map = build_index(g) + deg, imp = degree_maps(g) + need_ref = args.command in ("search", "node", "neighbors", "imports", "imported-by") + if need_ref and not args.ref: + sys.exit("command '%s' needs a reference argument" % args.command) + + if args.command == "info": + if args.json: + print(json.dumps(g["meta"], ensure_ascii=False, indent=2)) + return + m = g["meta"] + print("root: %s generated: %s" % (m["root"], m["generated"])) + c = m["counts"] + print("nodes: %d edges: %d" % (c["nodes"], c["edges"])) + print("by type: " + ", ".join("%s=%d" % kv for kv in sorted(c["by_type"].items()))) + print("by lang: " + ", ".join("%s=%d" % kv for kv in sorted(c["by_lang"].items()))) + if m.get("external"): + print("top external: " + ", ".join("%s×%d" % tuple(kv) for kv in m["external"][:10])) + + elif args.command == "hubs": + n = int(args.ref) if args.ref and args.ref.isdigit() else 15 + pool = nodes if args.all else [x for x in nodes if x["type"] != "symbol"] + pool = sorted(pool, key=lambda x: -deg.get(x["id"], 0))[:n] + pool = [x for x in pool if deg.get(x["id"], 0) > 0] + if args.json: + print(json.dumps([{"id": x["id"], "type": x["type"], + "degree": deg.get(x["id"], 0), + "imports_degree": imp.get(x["id"], 0)} for x in pool], + ensure_ascii=False, indent=2)) + return + print("top %d hubs:" % len(pool)) + for x in pool: + print(" %-4d imports=%-4d %s [%s]" % + (deg.get(x["id"], 0), imp.get(x["id"], 0), x["id"], x["type"])) + + elif args.command == "orphans": + orphans = [x for x in nodes if x["type"] == "code" and imp.get(x["id"], 0) == 0] + if args.json: + print(json.dumps([x["id"] for x in orphans], ensure_ascii=False, indent=2)) + return + print("%d orphan code files:" % len(orphans)) + for x in orphans[:50]: + print(" " + x["id"]) + if len(orphans) > 50: + print(" … %d more" % (len(orphans) - 50)) + + elif args.command == "search": + term = args.ref.lower() + hits = [x for x in nodes if term in x["id"].lower() or term in x["label"].lower()] + if args.json: + print(json.dumps(hits, ensure_ascii=False, indent=2)) + return + print("%d matches for %r:" % (len(hits), args.ref)) + for x in hits[:50]: + print(" %s [%s] degree=%d" % (x["id"], x["type"], deg.get(x["id"], 0))) + if len(hits) > 50: + print(" … %d more" % (len(hits) - 50)) + + elif args.command in ("node", "neighbors", "imports", "imported-by"): + node, cands = resolve(nodes, args.ref) + if node is None: + if cands: + print_candidates(cands) + sys.exit(2) + sys.exit("no node matches %r — try the search command" % args.ref) + if args.command == "node": + related = out_map.get(node["id"], []) + in_map.get(node["id"], []) + if args.json: + print(json.dumps({"node": node, "edges": related}, + ensure_ascii=False, indent=2)) + return + print("%s [%s] lang=%s degree=%d" % + (node["id"], node["type"], node.get("lang", "?"), deg.get(node["id"], 0))) + for line in fmt_edges(out_map.get(node["id"], []), "out"): + print(line) + for line in fmt_edges(in_map.get(node["id"], []), "in"): + print(line) + return + kind = args.kind or ("imports" if args.command in ("imports", "imported-by") else None) + direction = {"imports": "out", "imported-by": "in"}.get(args.command, args.dir) + selected = [] + if direction in ("out", "both"): + for e in out_map.get(node["id"], []): + if not kind or e["kind"] == kind: + selected.append(("out", e)) + if direction in ("in", "both"): + for e in in_map.get(node["id"], []): + if not kind or e["kind"] == kind: + selected.append(("in", e)) + if args.json: + print(json.dumps([{"direction": d, **e} for d, e in selected], + ensure_ascii=False, indent=2)) + return + print("%s (%s) — %d %s edges%s%s:" % ( + node["id"], node["type"], len(selected), + kind or "all", " dir=" + direction if direction != "both" else "", + "" if direction != "both" else "")) + shown = selected[:60] + for d, e in shown: + other = e["to"] if d == "out" else e["from"] + print(" %s %s [%s]" % ("->" if d == "out" else "<-", other, e["kind"])) + if len(selected) > len(shown): + print(" … %d more" % (len(selected) - len(shown))) + + elif args.command == "external": + n = int(args.ref) if args.ref and args.ref.isdigit() else 20 + ext = g["meta"].get("external", [])[:n] + if args.json: + print(json.dumps(ext, ensure_ascii=False, indent=2)) + return + print("top external packages:") + for name, cnt in ext: + print(" %-6d %s" % (cnt, name)) + + +if __name__ == "__main__": + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + main() diff --git a/external_plugins/graphify-plugin/tests/sample/app.py b/external_plugins/graphify-plugin/tests/sample/app.py new file mode 100644 index 00000000..1164b190 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/app.py @@ -0,0 +1,26 @@ +"""Entry point of the sample app.""" +import json +import os + +from models import User +from utils import merge_defaults, format_endpoint + + +class App: + def __init__(self, config): + self.config = config + + def run(self): + print("running with", self.config) + + +def main(): + cfg = merge_defaults({"name": "demo"}) + user = User("sara") + app = App(cfg) + print(format_endpoint(cfg)) + app.run() + + +if __name__ == "__main__": + main() diff --git a/external_plugins/graphify-plugin/tests/sample/config.json b/external_plugins/graphify-plugin/tests/sample/config.json new file mode 100644 index 00000000..087ab397 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/config.json @@ -0,0 +1,5 @@ +{ + "name": "sample-app", + "version": "1.0.0", + "port": 8080 +} diff --git a/external_plugins/graphify-plugin/tests/sample/docs/README.md b/external_plugins/graphify-plugin/tests/sample/docs/README.md new file mode 100644 index 00000000..d85ec0bf --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/docs/README.md @@ -0,0 +1,8 @@ +# Sample project + +Entry point is [app.py](../app.py). See also the [guide](guide.md). + +Config lives in `config.json`; helpers live in `utils.py` and `web/index.js`. + +- [Usage instructions](usage.md) (broken on purpose) +- [Source browser](../web/index.js) diff --git a/external_plugins/graphify-plugin/tests/sample/docs/guide.md b/external_plugins/graphify-plugin/tests/sample/docs/guide.md new file mode 100644 index 00000000..07614c72 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/docs/guide.md @@ -0,0 +1,5 @@ +# Guide + +The app entry is [app.py](app.py) (root-relative link, resolves via fallback). + +Models live in `models.py`. Run `python app.py` to start. diff --git a/external_plugins/graphify-plugin/tests/sample/legacy/old.py b/external_plugins/graphify-plugin/tests/sample/legacy/old.py new file mode 100644 index 00000000..27e0f86a --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/legacy/old.py @@ -0,0 +1,5 @@ +"""Old script nobody uses anymore.""" + + +def cleanup(): + pass diff --git a/external_plugins/graphify-plugin/tests/sample/models.py b/external_plugins/graphify-plugin/tests/sample/models.py new file mode 100644 index 00000000..1d6e37b6 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/models.py @@ -0,0 +1,13 @@ +"""Domain models.""" + +from utils import merge_defaults + + +class User: + def __init__(self, name): + self.name = name + + +class Order: + def __init__(self, user): + self.user = user diff --git a/external_plugins/graphify-plugin/tests/sample/utils.py b/external_plugins/graphify-plugin/tests/sample/utils.py new file mode 100644 index 00000000..fb4970b7 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/utils.py @@ -0,0 +1,11 @@ +"""Config helpers for the sample app (pure helpers, no I/O).""" + + +def merge_defaults(cfg): + base = {"name": "sample-app", "port": 8080} + base.update(cfg or {}) + return base + + +def format_endpoint(cfg): + return "%s:%s" % (cfg.get("name", "app"), cfg.get("port", 80)) diff --git a/external_plugins/graphify-plugin/tests/sample/web/index.js b/external_plugins/graphify-plugin/tests/sample/web/index.js new file mode 100644 index 00000000..21c9b1b5 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/web/index.js @@ -0,0 +1,8 @@ +import { formatName } from './lib.js'; +const express = require('express'); + +function render(user) { + return '

' + formatName(user) + '

'; +} + +const helper = () => console.log('hi'); diff --git a/external_plugins/graphify-plugin/tests/sample/web/lib.js b/external_plugins/graphify-plugin/tests/sample/web/lib.js new file mode 100644 index 00000000..abff932d --- /dev/null +++ b/external_plugins/graphify-plugin/tests/sample/web/lib.js @@ -0,0 +1,5 @@ +export function formatName(user) { + return user.name.toUpperCase(); +} + +export const helper = () => 'x'; diff --git a/external_plugins/graphify-plugin/tests/smoke_test.py b/external_plugins/graphify-plugin/tests/smoke_test.py new file mode 100644 index 00000000..72b57486 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/smoke_test.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""End-to-end smoke test: build a graph of the sample fixture and query it.""" +import json +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +BUILD = ROOT / "skills" / "graphify" / "scripts" / "build_graph.py" +QUERY = ROOT / "skills" / "graphify" / "scripts" / "query_graph.py" +SAMPLE = ROOT / "tests" / "sample" + + +def run(*argv): + p = subprocess.run([sys.executable, *argv], capture_output=True, text=True, + encoding="utf-8", errors="replace") + if p.returncode != 0: + raise SystemExit("command failed: %r\n%s%s" % (argv, p.stdout, p.stderr)) + return p.stdout + + +def main(): + run(str(BUILD), str(SAMPLE)) + graph = json.loads((SAMPLE / ".graphify" / "graph.json").read_text(encoding="utf-8")) + edges = {(e["from"], e["to"], e["kind"]) for e in graph["edges"]} + node_ids = {n["id"] for n in graph["nodes"]} + + for fid in ("app.py", "utils.py", "models.py", "web/index.js", "web/lib.js", + "docs/README.md", "config.json", "docs/guide.md", "legacy/old.py"): + assert fid in node_ids, "missing node: " + fid + + for e in (("app.py", "utils.py", "imports"), + ("app.py", "models.py", "imports"), + ("models.py", "utils.py", "imports"), + ("web/index.js", "web/lib.js", "imports")): + assert e in edges, "missing edge: " + str(e) + + assert ("docs/README.md", "app.py", "links") in edges, "doc link edge missing" + assert ("docs/README.md", "config.json", "mentions") in edges, "mention edge missing" + + for sym in ("app.py::App", "app.py::main", "models.py::User", "models.py::Order", + "web/index.js::render", "web/lib.js::formatName", "legacy/old.py::cleanup"): + assert sym in node_ids, "missing symbol: " + sym + + assert graph["meta"]["missing_links"].get("docs/README.md") == ["usage.md"], "broken link not reported" + + c = graph["meta"]["counts"] + assert (c["by_type"]["code"], c["by_type"]["doc"], c["by_type"]["config"], + c["by_type"]["symbol"]) == (6, 2, 1, 11), "counts wrong: " + str(c) + + q = str(SAMPLE / ".graphify" / "graph.json") + out = run(str(QUERY), q, "orphans") + assert "legacy/old.py" in out, "orphans query wrong" + out = run(str(QUERY), q, "imported-by", "utils.py") + assert "app.py" in out and "models.py" in out, "imported-by query wrong" + out = run(str(QUERY), q, "info") + assert "nodes: 20" in out, "info counts wrong" + out = run(str(QUERY), q, "hubs") + assert "app.py" in out, "hubs query wrong" + + html = (SAMPLE / ".graphify" / "graph.html").read_text(encoding="utf-8") + assert "Graphify" in html and "__DATA__" not in html, "html template broken" + report = (SAMPLE / ".graphify" / "graph-report.md").read_text(encoding="utf-8") + assert "Orphan code files" in report, "report section missing" + + print("smoke test OK —", c) + + +if __name__ == "__main__": + main() diff --git a/external_plugins/graphify-plugin/tests/validate.py b/external_plugins/graphify-plugin/tests/validate.py new file mode 100644 index 00000000..182f2c73 --- /dev/null +++ b/external_plugins/graphify-plugin/tests/validate.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Validate the plugin structure: manifests, skill frontmatter and declared paths.""" +import json +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +errors = [] + + +def check(cond, msg): + if not cond: + errors.append(msg) + + +def load_json(p): + return json.loads(Path(p).read_text(encoding="utf-8")) + + +manifest = load_json(ROOT / ".zcode-plugin" / "plugin.json") +check(manifest.get("name") == "graphify-plugin", "manifest name must be graphify-plugin") +check(bool(re.match(r"^\d+\.\d+\.\d+$", manifest.get("version", ""))), + "manifest version must be semver (x.y.z)") +check(bool(manifest.get("description")), "manifest description is empty") +check(bool(manifest.get("author")), "manifest author is empty") +check(manifest.get("skills") == "./skills", "manifest skills must point to ./skills") + +skill_md = ROOT / "skills" / "graphify" / "SKILL.md" +check(skill_md.is_file(), "skills/graphify/SKILL.md is missing") +front = skill_md.read_text(encoding="utf-8") if skill_md.is_file() else "" +fm = re.match(r"^---\n(.*?)\n---\n", front, re.S) +check(bool(fm), "SKILL.md frontmatter is missing") +if fm: + block = fm.group(1) + check(bool(re.search(r"^name:\s*graphify\s*$", block, re.M)), "SKILL.md name must be graphify") + check(bool(re.search(r"^description:\s*>", block, re.M)), "SKILL.md description is missing") + +for s in ("build_graph.py", "query_graph.py"): + check((ROOT / "skills" / "graphify" / "scripts" / s).is_file(), "script missing: " + s) + +market = load_json(ROOT / ".claude-plugin" / "marketplace.json") +entries = market.get("plugins", []) +match = [e for e in entries if e.get("name") == manifest["name"]] +check(len(match) == 1, "marketplace entry missing for graphify-plugin") +if match: + e = match[0] + check(e.get("version") == manifest["version"], "marketplace version != manifest version") + src = (ROOT / e.get("source", "")).resolve() + check(src == ROOT.resolve(), "marketplace source does not resolve to the plugin root") + check(bool(e.get("description")), "marketplace description is empty") + +declared = [manifest.get("skills", ""), *[x.get("source", "") for x in entries]] +for p in declared: + check(not str(p).startswith("..") and ".." not in Path(p).parts, + "declared path escapes plugin root: " + str(p)) + +if errors: + print("VALIDATION FAILED:") + for e in errors: + print(" -", e) + sys.exit(1) +print("plugin validation OK — %s %s" % (manifest["name"], manifest["version"])) diff --git a/marketplace.json b/marketplace.json index 88fad228..ef96f0fc 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1445,251 +1445,34 @@ ] }, { - "name": "image-generation", - "source": "./plugins/image-generation", - "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/image-generation/icon.png", - "requiresPaidPlan": true, - "displayName": "Seedream", - "displayName_i18n": { - "en": "Seedream", - "zh-CN": "Seedream" - }, - "description": "ZCode 官方生图:用文字生成图片,或按一张参考图改图,结果保存到工作区。", - "description_i18n": { - "en": "Official ZCode image generation: create an image from text, or edit one reference image, and save it to the workspace.", - "zh-CN": "ZCode 官方生图:用文字生成图片,或按一张参考图改图,结果保存到工作区。" - }, - "version": "0.1.2", - "author": { - "name": "Z.ai", - "url": "https://z.ai" - }, - "category": "utilities", - "keywords": [ - "image-generation", - "text-to-image", - "image-to-image", - "mcp" - ] - }, - { - "name": "video-generation", - "source": "./plugins/video-generation", - "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/video-generation/icon.png", - "requiresPaidPlan": true, - "displayName": "Seedance", - "displayName_i18n": { - "en": "Seedance", - "zh-CN": "Seedance" - }, - "description": "ZCode 官方视频生成:用文字生成短视频,或按参考素材、首尾帧生成,结果保存到工作区。", - "description_i18n": { - "en": "Official ZCode video generation: create a short video from text, reference media, or first/last frames, and save it to the workspace.", - "zh-CN": "ZCode 官方视频生成:用文字生成短视频,或按参考素材、首尾帧生成,结果保存到工作区。" - }, - "version": "0.2.1", - "author": { - "name": "Z.ai", - "url": "https://z.ai" - }, - "category": "utilities", - "keywords": [ - "video-generation", - "text-to-video", - "image-to-video", - "mcp" - ] - }, - { - "name": "happyhorse-video", - "source": "./plugins/happyhorse-video", - "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/happyhorse-video/icon.png", - "requiresPaidPlan": true, - "displayName": "HappyHorse", + "name": "graphify-plugin", + "displayName": "Graphify", "displayName_i18n": { - "en": "HappyHorse", - "zh-CN": "HappyHorse" + "en": "Graphify", + "zh-CN": "Graphify 代码知识图谱" }, - "description": "根据文字或参考图片生成视频,适合制作广告、社媒短片和创意视频。", + "source": "./external_plugins/graphify-plugin", + "description": "Turns a codebase into a queryable knowledge graph: scans code, docs and config files, extracts files, symbols, imports and doc references, and produces graph.json (9 query commands), an interactive graph.html and a markdown report under /.graphify/.", "description_i18n": { - "en": "Generate videos from text or reference images. Create ads, social clips, and creative videos.", - "zh-CN": "根据文字或参考图片生成视频,适合制作广告、社媒短片和创意视频。" - }, - "version": "0.1.1", - "author": { - "name": "Z.ai", - "url": "https://z.ai" - }, - "category": "utilities", - "keywords": [ - "happyhorse", - "video-generation", - "text-to-video", - "image-to-video", - "mcp" - ] - }, - { - "name": "rfauto", - "source": "./external_plugins/rfauto", - "displayName": "RFAuto", - "description": "把 RFAuto 射频/微波 EDA 框架接入 ZCode 会话:提供 208 个 MCP 工具(器件综合、仿真作业、质量门、结果判读),另附一个判读裁判 agent 和 7 张器件技能卡。所有物理数字都出自 RFAuto 确定性内核与求解器,不由模型生成。", - "description_i18n": { - "en": "Drive the RFAuto RF/microwave EDA framework from any ZCode session: 208 deterministic MCP tools covering device synthesis, simulation jobs, quality gates, and result verdicts, plus a judge agent and device skill cards. Every physical number comes from the RFAuto deterministic kernel and solvers, never from the model.", - "zh-CN": "把 RFAuto 射频/微波 EDA 框架接入 ZCode 会话:提供 208 个 MCP 工具(器件综合、仿真作业、质量门、结果判读),另附一个判读裁判 agent 和 7 张器件技能卡。所有物理数字都出自 RFAuto 确定性内核与求解器,不由模型生成。" + "en": "Turns a codebase into a queryable knowledge graph: scans code, docs and config files, extracts files, symbols, imports and doc references, and produces graph.json (9 query commands), an interactive graph.html and a markdown report under /.graphify/.", + "zh-CN": "将代码库转换为可查询的知识图谱:扫描代码、文档与配置文件,提取文件、符号、import 与文档引用,在 /.graphify/ 下生成可查询的 graph.json(9 个查询命令)、自包含的交互式 graph.html 与 Markdown 报告。" }, "version": "0.1.0", "author": { - "name": "geer1895", - "url": "https://github.com/geer1895" + "name": "Movti Group", + "url": "https://github.com/movtigroup" }, + "license": "MIT", + "repository": "https://github.com/movtigroup/Graphify-plugin", "category": "developer-tools", "keywords": [ - "rf", - "microwave", - "eda", - "hfss", - "openems", - "simulation", - "mcp", - "s-parameters", - "touchstone", - "RFAuto" - ], - "homepage": "https://github.com/geer1895/rfauto", - "repository": "https://github.com/geer1895/rfauto", - "license": "GPL-3.0-only", - "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/rfauto/icon.png" - }, - { - "name": "hyper3d-3d", - "source": "./plugins/hyper3d-3d", - "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/hyper3d-3d/icon.png", - "requiresPaidPlan": true, - "displayName": "Hyper3D", - "displayName_i18n": { - "en": "Hyper3D", - "zh-CN": "Hyper3D" - }, - "description": "根据文字或参考图片生成 3D 模型,支持低模(Smart Low Poly)、重新贴图、骨骼绑定和预设动画,适合制作角色、道具和 3D 展示素材。", - "description_i18n": { - "en": "Generate 3D models from text or reference images, create Smart Low Poly models, retexture existing models, and add rigs and preset animations for characters, props, and 3D presentations.", - "zh-CN": "根据文字或参考图片生成 3D 模型,支持低模(Smart Low Poly)、重新贴图、骨骼绑定和预设动画,适合制作角色、道具和 3D 展示素材。" - }, - "version": "0.1.0", - "author": { - "name": "Z.ai", - "url": "https://z.ai" - }, - "category": "游戏/3D", - "keywords": [ - "hyper3d", - "3d", - "text-to-3d", - "image-to-3d", - "texturing", - "rigging", - "mcp" - ], - "examplePrompts": [ - "Generate a 3D model of a small wooden treasure chest and save it as GLB", - "Turn assets/hero.png into a 3D character in T-pose, then rig it with a walking animation", - "Retexture https://example.com/knight.glb with silver armor using assets/armor-ref.png" - ], - "examplePrompts_i18n": { - "zh-CN": [ - "生成一个小木头宝箱的 3D 模型,保存成 GLB", - "把 assets/hero.png 做成 T 姿势的 3D 角色,再绑骨并加一个走路动画", - "用 assets/armor-ref.png 给 https://example.com/knight.glb 重新贴一套银色盔甲" - ] - } - }, - { - "name": "meshy-3d", - "source": "./plugins/meshy-3d", - "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/meshy-3d/icon.png", - "requiresPaidPlan": true, - "displayName": "Meshy", - "displayName_i18n": { - "en": "Meshy", - "zh-CN": "Meshy" - }, - "description": "根据文字或图片生成 3D 模型,支持贴图、减面、格式转换、人形角色绑骨与预设动画,适合制作游戏资产和 3D 展示素材。", - "description_i18n": { - "en": "Generate 3D models from text or images, with texturing, mesh simplification, format conversion, humanoid rigging, and preset animations.", - "zh-CN": "根据文字或图片生成 3D 模型,支持贴图、减面、格式转换、人形角色绑骨与预设动画,适合制作游戏资产和 3D 展示素材。" - }, - "version": "0.1.0", - "author": { - "name": "Z.ai", - "url": "https://z.ai" - }, - "category": "游戏/3D", - "keywords": [ - "meshy", - "3d", - "text-to-3d", - "image-to-3d", - "retexture", - "remesh", - "rigging", - "animation", - "mcp" - ], - "examplePrompts": [ - "Generate a 3D cartoon knight in A-pose and texture it with silver armor and a red cape", - "Turn assets/robot.png into a 3D model and export it as FBX", - "Remesh the knight, rig it, and make it wave and walk" - ], - "examplePrompts_i18n": { - "zh-CN": [ - "生成一个 A-pose 的卡通骑士 3D 模型,再贴上银色盔甲和红披风", - "把 assets/robot.png 做成 3D 模型,导出 FBX", - "给骑士减面后绑骨,让它挥手和走路" - ] - } - }, - { - "name": "hi3d-3d", - "source": "./plugins/hi3d-3d", - "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/hi3d-3d/icon.png", - "requiresPaidPlan": true, - "displayName": "Hi3D", - "displayName_i18n": { - "en": "Hi3D", - "zh-CN": "Hi3D" - }, - "description": "将单张或多视角图片转换为 3D 模型,支持贴图和模型拆件,便于继续编辑或制作 3D 资产。", - "description_i18n": { - "en": "Turn single or multi-view images into 3D models, add textures, and split models into parts for further editing and asset creation.", - "zh-CN": "将单张或多视角图片转换为 3D 模型,支持贴图和模型拆件,便于继续编辑或制作 3D 资产。" - }, - "version": "0.1.0", - "author": { - "name": "Z.ai", - "url": "https://z.ai" - }, - "category": "游戏/3D", - "keywords": [ - "hi3d", - "3d", - "image-to-3d", - "texturing", - "model-splitting", - "mcp" - ], - "examplePrompts": [ - "Turn assets/robot.png into a 3D model in glb format", - "Generate a 3D model from these front and left views, geometry only", - "Split the model from the last Hi3D task into character parts" - ], - "examplePrompts_i18n": { - "zh-CN": [ - "把 assets/robot.png 生成一个 glb 格式的 3D 模型", - "用这两张正面和左侧视角图生成一个白模", - "把上一个 Hi3D 任务生成的模型按角色拆分成部件" - ] - } + "knowledge-graph", + "code-analysis", + "dependency-graph", + "static-analysis", + "architecture", + "codebase" + ] } ] } \ No newline at end of file