From e8a20be512dec56179c8d625351a3428d6027241 Mon Sep 17 00:00:00 2001 From: Hung Pham Date: Wed, 28 Oct 2026 06:26:53 +0700 Subject: [PATCH] feat: present skills for using codegraph --- docs/configuration.md | 4 + docs/development.md | 4 +- skills/codegraph-code-review/SKILL.md | 59 ++++++++++++++ .../codegraph-development-workflow/SKILL.md | 80 +++++++++++++++++++ skills/codegraph-figma-to-frontend/SKILL.md | 69 ++++++++++++++++ skills/codegraph-reverse-binary/SKILL.md | 48 +++++++++++ skills/codegraph-security-review/SKILL.md | 62 ++++++++++++++ 7 files changed, 325 insertions(+), 1 deletion(-) create mode 100644 skills/codegraph-code-review/SKILL.md create mode 100644 skills/codegraph-development-workflow/SKILL.md create mode 100644 skills/codegraph-figma-to-frontend/SKILL.md create mode 100644 skills/codegraph-reverse-binary/SKILL.md create mode 100644 skills/codegraph-security-review/SKILL.md diff --git a/docs/configuration.md b/docs/configuration.md index 0d0816fc2d..1e73efce2a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -30,6 +30,8 @@ php = true scala = true swift = true lua = true +svelte = true +astro = true # C/C++ header handling # headers = "auto" # "auto" (default), "c", or "cpp" @@ -89,6 +91,8 @@ Enable/disable individual language extractors. All 14 are enabled by default. | `scala` | Scala | tree-sitter-scala | | `swift` | Swift | tree-sitter-swift | | `lua` | Lua | tree-sitter-lua | +| `svelte` | Svelte | tree-sitter-svelte-next (script re-parse JS/TS) | +| `astro` | Astro | tree-sitter-astro-next (frontmatter/script re-parse JS/TS) | **Headers**: The `headers` key controls `.h` file parsing: - `"auto"` (default): Detect from project — C++ if `.cpp`/`.hpp` present, C if `.c` present, inspect each `.h` for C++ syntax in mixed projects diff --git a/docs/development.md b/docs/development.md index 3e818c51d3..85e5a2f732 100644 --- a/docs/development.md +++ b/docs/development.md @@ -96,7 +96,7 @@ cargo test -p codegraph-installer | Feature | Languages | |---------|-----------| -| `all-langs` (default) | All 14 | +| `all-langs` (default) | All 16 | | `lang-rust` | Rust | | `lang-go` | Go | | `lang-python` | Python | @@ -111,6 +111,8 @@ cargo test -p codegraph-installer | `lang-scala` | Scala | | `lang-swift` | Swift | | `lang-lua` | Lua | +| `lang-svelte` | Svelte (hybrid: markup + script re-parse JS/TS) | +| `lang-astro` | Astro (hybrid: markup + frontmatter/script re-parse JS/TS) | ```bash # Test single language diff --git a/skills/codegraph-code-review/SKILL.md b/skills/codegraph-code-review/SKILL.md new file mode 100644 index 0000000000..ea70697d46 --- /dev/null +++ b/skills/codegraph-code-review/SKILL.md @@ -0,0 +1,59 @@ +--- +name: codegraph-code-review +description: Review a diff, MR, or uncommitted changes with CodeGraph — use when asked to review code, assess a patch's blast radius, or explain what a change touches. +--- + +# Code Review with CodeGraph + +Use CodeGraph to turn a raw diff into a structural review: which symbols changed, who depends on them, and which control-flow paths the change lands in. The index is never mutated — all review tools are read-only drafts. + +## Review workflow + +``` +1. Get the diff: git diff (uncommitted) or git diff base...head (MR/PR) +2. codegraph_graphcode_diff {diff: ""} # draft impact report +3. For each touched symbol: codegraph_impact {node} # who transitively depends on it +4. codegraph_flow {node: } # branches/guards around the change +5. codegraph_mermaid {node, kind: "impact"|"callers"} # render a diagram for the review comment +6. Report findings, citing file:line from the diff report +``` + +### What `codegraph_graphcode_diff` reports + +- **Touched symbols** — functions/methods/classes whose lines overlap the diff. +- **Flows containing changed call sites** — the control-flow window (IF_TRUE, LOOP, BRANCH_END…) around each affected call, so you can see which branch or loop a change lives in. +- **Which flows call the touched functions** — the caller-side blast radius. + +Pass the full multi-file diff; added/removed/renamed files and `\ No newline at end of file` are handled. + +## Guidelines + +- **Re-index first if the working tree changed since the last index.** `codegraph_graphcode_diff` compares the diff against the *indexed* snapshot; stale index → stale touch lists. Run `codegraph_index {}` when unsure. +- For every touched function that is exported/public or has callers outside its module, run `codegraph_impact` and mention the top callers in the review. +- Use `codegraph_mermaid` with `kind: "impact"` for wide blast radius, `"callers"` for upstream only, `"flow"` to walk a single function's logic (guards, effects, marker positions). +- When the change alters behavior, follow up with `codegraph_graphcode_diff_simulate` (see codegraph-security-review skill) to compare traces before/after. +- Review checklist, in order: + 1. Correctness of the diff itself (read the files). + 2. Hidden dependents (`codegraph_impact`) the author may not have considered. + 3. Control-flow placement: does the change run on every loop iteration / only in the error branch? + 4. Contract-sensitive edits: marker ids and serialized types must not be renumbered (check the repo's conventions doc if present). +- Cite findings as `file:line` from the diff and the touched-symbol list, not from memory. + +### Example calls + +```json +codegraph_graphcode_diff {"diff": "diff --git a/src/foo.rs ...\n"} +codegraph_impact {"node": 1234, "max_depth": 3, "detail": "medium"} +codegraph_mermaid {"node": 1234, "kind": "impact", "depth": 2} +``` + +## Effects & markers in review + +Flow output annotates each call site with an **effect** (semantic class: `sql_query`, `http_call`, `panic`, …) and call chains carry **markers** (`try_start`, `throw`, `loop`, `return`, …). Classification comes from pattern rules — defaults plus project overrides in `.codegraph/config.toml` under one `[[effect_rules]]` table (legacy `[[flow_rules]]` is gone), editable at runtime via `codegraph_config_effects`. Rule changes re-classify call records only on the next `codegraph_index`. + +Review implications: +- If a diff adds a call to an external system (DB, HTTP, exec), check the diff report's flow window for the **expected effect** on that call site. A missing or wrong effect usually means the classifier needs a new `[[effect_rules]]` entry (matcher `exact`/`prefix` preferred over `contains`) — not a code change. +- If a diff edits control flow, check marker placement: markers must not be inserted between `CALL_ENTER` and `CALL_EXIT`, and existing marker ids must never be renumbered (serialized contract — `crates/codegraph-core/src/semgraph.rs`). +- Flag rule edits in the diff that change effect semantics of existing call patterns; those silently alter `codegraph_search_flow` results downstream. + +Note: `codegraph_graphcode_diff` returns a **draft** — it does not apply anything. Combine with reading the actual files before approving a change. diff --git a/skills/codegraph-development-workflow/SKILL.md b/skills/codegraph-development-workflow/SKILL.md new file mode 100644 index 0000000000..e48ea3fd37 --- /dev/null +++ b/skills/codegraph-development-workflow/SKILL.md @@ -0,0 +1,80 @@ +--- +name: codegraph-development-workflow +description: CodeGraph-first development workflow — use before grep/read when locating symbols, tracing call chains, or estimating change impact in a workspace indexed by CodeGraph MCP. +--- + +# CodeGraph-First Development Workflow + +CodeGraph answers **structural** questions (where is this symbol, who calls it, what breaks if I change it) faster and cheaper than grep. Use it as the FIRST step for structural questions; fall back to grep/read only for the cases listed below. + +## Standard loop + +``` +1. codegraph_init {path: ""} # bind session (does NOT index) +2. codegraph_context {query: "..."} # symbol + callers + callees in one call +3. codegraph_search_symbol / codegraph_symbol # locate + signature +4. codegraph_callers / codegraph_callees / codegraph_impact # upstream / downstream / blast radius + ... edit code ... +5. codegraph_index {} # re-index only when you need fresh data +6. codegraph_flow / codegraph_search_flow # verify control flow after the edit +``` + +### Tool cheatsheet + +| Question | Tool | +|---|---| +| Find symbols by name (contains/prefix/suffix/semantic) | `codegraph_search_symbol` | +| Exact symbol by id or name | `codegraph_symbol` | +| Who calls this / what does it call | `codegraph_callers` / `codegraph_callees` | +| What breaks if I change X | `codegraph_impact` | +| Control flow of one function (branches, loops, effects) | `codegraph_flow` | +| Full execution trace to a target: all caller→target paths with call/return/throw/branch info | `codegraph_trace_full_flow` | +| Which functions match a flow pattern (LOOP, THROW, CALL_ENTER…) | `codegraph_search_flow` | +| Bundled context (callers + callees + optional source) | `codegraph_context` | +| Where a library call is used | `codegraph_references` | +| List functions/params/locals of a function | `codegraph_graphcode_function_scope` | +| Class members, all types, files, stats | `codegraph_graphcode_class` / `codegraph_graphcode_list_types` / `codegraph_graphcode_files` / `codegraph_graphcode_stats` | +| Find by annotation (@Override, @GetMapping…) | `codegraph_graphcode_search_by_annotation` | + +There is no generic `codegraph_search` or `codegraph_flows` tool — symbol search is `codegraph_search_symbol` and flow-pattern search is `codegraph_search_flow`. + +### Example calls + +```json +codegraph_init {"path": "/abs/path/to/workspace"} +codegraph_context {"query": "parse config", "limit": 5} +codegraph_impact {"node": 1234, "max_depth": 3} +codegraph_search_flow {"pattern": "THROW,CATCH"} +``` + +## Effects & markers (how call sites get classified) + +Flow output annotates each call site with an **effect** (semantic class such as `sql_query`, `http_call`, `panic`, …) and the call chain carries **markers** (control-flow landmarks: `try_start`, `throw`, `loop`, `return`, …). Both come from pattern-match rules matched first-to-last: + +- Built-in default rules are bundled with the classifier; projects can add overrides in `.codegraph/config.toml` under a single `[[effect_rules]]` table — each rule sets `effect` and/or `marker` (at least one), with a `matcher` of `exact` | `prefix` | `contains` (prefer exact/prefix; `contains` can over-match, e.g. `longjmp` also hits `siglongjmp`). +- The legacy `[[flow_rules]]` key is gone: old keys are ignored with a warning. +- Runtime changes go through the MCP tool `codegraph_config_effects` (`op`: `list` | `add` | `remove`). New rules apply to the current thread immediately, but call records are **re-classified only on the next `codegraph_index`** — re-index to see effects change in flow output. +- Markers/ids are a stable serialization contract — never renumber existing ones (`crates/codegraph-core/src/semgraph.rs`). Do not insert markers between `CALL_ENTER` and `CALL_EXIT` (`CALL_ENTER` reads the next chain position as the callee). + +## When to fall back to grep/read + +| Situation | Use | +|---|---| +| Text literals (strings, comments, config keys) | grep | +| `docs/`, `README.md`, `config.toml`, `.md` files | read | +| Files not indexed by the language parsers | read | +| You just edited code and haven't re-indexed | read to confirm | +| You need the full implementation of a large file | read after `codegraph_symbol` narrows the location | + +## Critical rules + +1. **The index is a snapshot.** Results are stale until you run `codegraph_index`. After your own edits, always re-index (or read the file) before trusting a query about the edited code. +2. **`codegraph_init` does NOT index by default** — it just binds the session. Call `codegraph_index {}` when you need a fresh index. +3. **Large indexes:** search tools take `timeout_ms` (default 20000). On timeout the error returns a `resume` id — retry the SAME call with the SAME arguments plus `resume`, instead of re-scanning from scratch. +4. **Unbound session:** if tools report the session has no root, call `codegraph_init` with an absolute path. Never substitute a filesystem scan. +5. Symbol ids are per-index. After re-indexing, do not reuse ids from a previous snapshot — re-resolve by name via `codegraph_search_symbol` or `codegraph_symbol`. + +## Hygiene + +- `codegraph_deinit` releases the session; `.codegraph/` stays on disk and is git-ignored — never commit it. +- `codegraph_query_usage_report` shows token savings per tool; use it to tune how often you reach for graph queries vs grep. diff --git a/skills/codegraph-figma-to-frontend/SKILL.md b/skills/codegraph-figma-to-frontend/SKILL.md new file mode 100644 index 0000000000..4d12c81cad --- /dev/null +++ b/skills/codegraph-figma-to-frontend/SKILL.md @@ -0,0 +1,69 @@ +--- +name: codegraph-figma-to-frontend +description: Turn a Figma design into frontend code — use when the user gives a Figma file key and wants components/assets extracted, mapped onto the existing frontend codebase, and implemented. +--- + +# Figma → Frontend with figma-cli + CodeGraph + +Two-step pipeline: **figma-cli** (in `tools/figma-cli/`) fetches the design; **CodeGraph's document graph** ingests the exported JSON so components can be queried structurally; **CodeGraph's code index** maps each component onto the existing frontend codebase. + +## Prerequisites + +- `FIGMA_ACCESS_TOKEN` must be set (Figma personal access token). If missing, stop and ask the user for it — do not guess. +- Install once if needed: `uv pip install -e /tools/figma-cli` (provides the `figma` command). + +## Step 1 — Fetch the design + +```bash +export FIGMA_ACCESS_TOKEN=... +figma export -o design.json # file + components + styles, one JSON +figma list-components # quick inventory +figma list-styles # colors / text styles +figma export-assets 1:2 3:4 -f png -s 2 # export node images +``` + +- Get `` from the Figma URL (`figma.com/design//...`). +- Export assets into the project's asset directory (e.g. `web/src/assets/`) using node ids for the components you will implement. + +## Step 2 — Ingest into the document graph + +``` +codegraph_graphdoc_ingest {"path": "design.json"} # returns doc id + node count +codegraph_graphdoc_stats {} +``` + +The design JSON becomes a queryable document tree (MAP/ARRAY/FIELD nodes). + +## Step 3 — Query the design structurally + +| Question | Tool | +|---|---| +| Everything under `components` / `styles` | `codegraph_graphdoc_search {"pattern": "components"}` (dotted paths, matches at increasing depth) | +| Find nodes by value (name, color, font) | `codegraph_graphdoc_search_value {"query": "Button"}` | +| Find by structure (e.g. `MAP, FIELD, NUMBER` leaves) | `codegraph_graphdoc_search_struct {"pattern": "MAP,FIELD,NUMBER"}` | +| Characteristic/rare structures in the design | `codegraph_graphdoc_mine_patterns {}` → then `codegraph_graphdoc_list_patterns` | +| Expand one node into a small payload (path, key, value, children) | `codegraph_graphdoc_hydrate {"node_id": 123, "max_depth": 2}` | +| Paginate/large docs | `codegraph_graphdoc_hydrate` with small `max_depth` (1–3) | +| Remove a re-exported design | `codegraph_graphdoc_remove {"doc_id": }` | + +Use `codegraph_graphdoc_mine_patterns` first on a large design — rare patterns often reveal the component scaffolding; background structures rank last. + +## Step 4 — Map onto the codebase + +For each component to implement: + +1. Locate existing code: `codegraph_context {"query": ""}` on the workspace (bind first with `codegraph_init`). +2. If the component exists, plan the modification against its `codegraph_flow` and `codegraph_impact` (blast radius before editing). +3. If new, follow the project's frontend conventions; reuse tokens from `figma list-styles` for colors/typography. + +## Step 5 — Implement and verify + +- Write the component using the extracted values (sizes, colors, text) read via `graphdoc_hydrate`, not from screenshots. +- Reference exported assets by their project-relative paths. +- After editing source, `codegraph_index {}` before any further graph queries about the edited code (index is a snapshot). + +## Gotchas + +- The document graph and code graph are separate datasets — `codegraph_graphdoc_*` never sees source code, `codegraph_search_symbol` never sees the design. +- `figma export` output can be large; prefer `list-components` for inventory and targeted `graphdoc_search` over dumping the whole JSON into context. +- Node ids in the document graph are per-ingest; re-ingesting invalidates old ids. diff --git a/skills/codegraph-reverse-binary/SKILL.md b/skills/codegraph-reverse-binary/SKILL.md new file mode 100644 index 0000000000..08b2a59064 --- /dev/null +++ b/skills/codegraph-reverse-binary/SKILL.md @@ -0,0 +1,48 @@ +--- +name: codegraph-reverse-binary +description: Analyze compiled binaries with CodeGraph's binary graph — use when asked to reverse-engineer, enumerate entrypoints/imports/JNI symbols, or look up what lives at a binary address. +--- + +# Reverse Engineering Binaries with CodeGraph + +CodeGraph maintains a separate **binary graph** dataset (extracted via radare2 during indexing, feature `binary`). Query it with the `codegraph_graphbin_*` tools — these search the binary dataset, independent from source-code symbols. + +## Prerequisite: the binary must be indexed + +Binaries are discovered and extracted when the workspace is indexed (orchestrator scans for binaries and runs radare2; results land in the `BinaryGraph` dataset). So: + +1. `codegraph_init {"path": ""}` +2. `codegraph_index {}` — this is where extraction actually runs (radare2 must be on PATH). +3. Confirm with `codegraph_graphbin_stats` — it reports symbol/entrypoint/import/export counts and which binaries were indexed. If all zeros, the binary wasn't scanned (check extension, location, and that the build has feature `binary`). + +## Anchoring: start from entrypoints, not grep + +Do NOT grep the binary for strings as the first step. Anchor at symbols: + +``` +codegraph_graphbin_list {} # all symbols, paginated +codegraph_graphbin_list {"flag": "entrypoint"} # entrypoints — your starting anchors +codegraph_graphbin_list {"flag": "export"} # exported functions +codegraph_graphbin_list {"flag": "import"} # imported library calls (API surface) +codegraph_graphbin_list {"flag": "jni"} # JNI symbols (Android/Java interop) +codegraph_graphbin_list {"flag": "import", "kind": "Function", "limit": 100, "offset": 0} +codegraph_graphbin_addr {"addr": 4198400} # O(1) lookup at a virtual address +codegraph_graphbin_addr {"path": "/path/to/binary"} # entrypoints of one binary +codegraph_graphbin_stats {} # overview: what got indexed +``` + +- Results come back in two sections: `code` (source index hits) and `binary` (binary graph hits) when searching with `codegraph_search_symbol` and `source: "all"`. Use `source: "binary"` to restrict to binary symbols only. +- `codegraph_graphbin_addr` gives exact symbol-at-address lookups — use it to name addresses found in disassembly or crash logs. + +## Typical analysis flow + +1. `codegraph_graphbin_stats` → what binaries and symbol classes exist. +2. `codegraph_graphbin_list {flag: "entrypoint"}` → anchor list. +3. From an entrypoint symbol, switch to the source-side tools (`codegraph_flow`, `codegraph_callers`) when the binary was built from indexed sources — the shared symbol space lets you trace chains across both datasets. +4. `codegraph_graphbin_addr` to resolve any address you encounter. + +## Notes + +- Requires `radare2` on PATH for extraction. +- Results are a snapshot, same as the source index — re-run `codegraph_index` after adding/replacing a binary. +- `codegraph_graphbin_list` is paginated: use `offset`/`order` (`name` | `addr` | `id`) for large binaries. diff --git a/skills/codegraph-security-review/SKILL.md b/skills/codegraph-security-review/SKILL.md new file mode 100644 index 0000000000..8089206212 --- /dev/null +++ b/skills/codegraph-security-review/SKILL.md @@ -0,0 +1,62 @@ +--- +name: codegraph-security-review +description: Security-focused analysis with CodeGraph — use when hunting unvalidated paths, panic/error paths, or simulating how a change alters runtime behavior in a sandbox. +--- + +# Security Review with CodeGraph + +Use CodeGraph's marker search and sandbox simulation to find dangerous control-flow paths and prove (in a mocked sandbox) how a function behaves on different branches — without executing the real program. + +## 1. Hunt patterns with `codegraph_search_flow` + +Effects (semantic classes like `sql_query`, `http_call`, `panic`) and markers (`throw`, `try_start`, `loop`, …) are how call sites get classified — see the "Effects & markers" section in the codegraph-development-workflow skill. Rules are customized via `[[effect_rules]]` in `.codegraph/config.toml` or the `codegraph_config_effects` MCP tool (changes require a re-index to re-classify call records). Typical pattern uses: `panic` for crash paths, custom effects you declared (e.g. `sql_query`) as tokens in a pattern. + +Pattern = comma-separated tokens: numeric symbol ids, marker names, or symbol names. + +| Goal | Pattern | +|---|---| +| Error/panic paths without a nearby catch | `THROW` (then inspect flows for missing `CATCH`) | +| Exception handling structure | `THROW,CATCH` | +| Unbounded-looking loops | `LOOP` (review `loop_cap` and exit conditions) | +| Entry points into a subsystem | `CALL_ENTER` / specific callee names | +| Flows containing a known-dangerous call | `my_sql_exec,THROW` or the call name alone | + +Use `codegraph_references {query: "dangerous_lib_call"}` to find every call site of a library function (includes unresolved external calls), then walk each site with `codegraph_flow` to check the guards above it. + +For a dangerous **target** function, enumerate every path that can reach it with `codegraph_trace_full_flow {target_id}` — it returns all caller→target paths with call/return/throw/branch info. Defaults: `max_depth: 5` (caller hops), `max_paths: 50`, `max_loop_iter: 1` (loop body runs once — raise only if you must audit repeated iterations). Unvalidated-input review = for each returned path, check where the guard (if any) sits relative to the entry. + +## 2. Simulate with `codegraph_graphcode_sandbox` + +Run a function's compiled flow with mocks for callees: + +```json +codegraph_graphcode_sandbox { + "node": 1234, + "args": [1, 2, 3], + "mocks": {"read_config": "fn(args) { 0 }"}, + "branch_policy": "if_true", + "loop_cap": 10 +} +``` + +- `mocks` maps callee names to Rhai `fn` bodies — every callee reachable from the entry must have a mock or the call fails with `missing_mocks`; the response lists any callees that ran unmocked. +- `branch_policy: "if_true" | "if_false"` forces branch decisions (guards' *text* is not evaluated); sweep both to cover both sides. +- `loop_cap` bounds iterations — raise it only when auditing a loop body. +- Output: ordered mock invocations, branch decisions, entry return value. Anything that runs without a mock appears in `missing_mocks`. + +## 3. Compare behavior across a change + +- `codegraph_graphcode_diff_simulate {diff, entry, args, mocks}` — run the sandbox on the current index AND a temporary index built from `base_ref` (default HEAD = pre-change), then compare traces (mock call order, branch decisions). Requires a git repo. +- `codegraph_graphcode_origin_simulate {entry, ref: "origin/main"}` — same comparison without a diff (working tree vs a ref). + +Use these to demonstrate: a guard now skipped, a call now unreachable, a new panic path, or changed call ordering. + +## Review checklist + +1. Enumerate `THROW` flows in changed code; verify each has a catch or documented escalation. +2. For each external input, walk `codegraph_flow` upward from the consuming call — is there a guard before it? +3. Simulate both branch policies on handlers; check mock-call order for resource leaks (e.g., lock taken, never released on the throw path). +4. `diff_simulate` every behavioral change; report trace deltas as evidence. +5. Contracts: marker ids and serialized types must not be renumbered; markers must not be inserted between `CALL_ENTER` and `CALL_EXIT`. + +All simulate tools are **read-only** — the index is never mutated, no code is executed for real.