---
title: "ruflo-knowledge-graph"
url: "https://claudemods.dev/zh-tw/builds/ruflo-knowledge-graph-3b4256"
source: "https://github.com/ruvnet/ruflo/tree/main/plugins/ruflo-knowledge-graph"
source_type: "github"
repo: "https://github.com/ruvnet/ruflo/tree/main/plugins/ruflo-knowledge-graph"
author: "ruvnet"
author_handle: "ruvnet"
stars: 82516
category: "多代理與協作"
categories: ["agents"]
tags: ["agentdb", "guard", "hooks", "knowledge-graph", "pathfinder", "plugin"]
permission_level: 2
scan_complete: true
install: "claude plugin marketplace add ruvnet/ruflo\nclaude plugin install ruflo-knowledge-graph"
added: "2026-10-05T08:13:34.132Z"
updated: "2026-11-26T14:25:45Z"
locale: "zh-tw"
content_locale: "zh-tw"
---

# ruflo-knowledge-graph

知識圖譜建構——實體抽取、關係對應與 pathfinder 圖形遍歷。作為 mod（ADR-445）：讓機密資訊留在圖譜外、確認圖譜刪除操作，提供 /kg-mod，以及供主控台顯示的狀態檔

## Description

知識圖譜建構——實體抽取、關係對應與 pathfinder 圖形遍歷。

## 概覽

從原始碼與文件中抽取實體（類別、函式、模組、型別、概念）和關係（imports、extends、implements、depends-on、calls）。在 AgentDB 中建立可導覽的知識圖譜，以階層節點與因果邊儲存。使用 pathfinder 演算法遍歷圖譜，依邊權重與語意相似度為路徑評分。

## 安裝

```bash
claude --plugin-dir plugins/ruflo-knowledge-graph
```

## Agents

| Agent | 模型 | 角色 |
|-------|------|------|
| `graph-navigator` | sonnet | 實體抽取、關係對應、知識圖譜建構、pathfinder 遍歷 |

## Skills

| Skill | 用法 | 說明 |
|-------|------|------|
| `kg-extract` | `/kg-extract <path>` | 從原始檔案抽取實體與關係，建立知識圖譜 |
| `kg-traverse` | `/kg-traverse <entity> [--depth N]` | 從種子實體開始進行 pathfinder 遍歷 |

## 指令（5 個子指令）

```bash
kg extract <path>            # 從原始檔案抽取實體與關係
kg traverse <entity>         # 從種子實體開始進行 pathfinder 遍歷
kg relations <entity>        # 列出實體的所有直接關係
kg visualize                 # 以 ASCII 顯示知識圖譜
kg search <query>            # 在圖譜中進行語意搜尋
```

## 實體型別

| 型別 | 範例 |
|------|------|
| class | `UserService`、`AuthController` |
| function | `calculateDiscount`、`handleRequest` |
| module | `auth`、`payments`、`api` |
| concept | `authentication`、`caching` |
| type | `User`、`OrderStatus` |
| config | `database`、`redis`、`jwt` |

## 相容性

- **CLI：** 固定使用 `@claude-flow/cli` v3.6 的 major+minor 版本。
- **驗證：** `bash plugins/ruflo-knowledge-graph/scripts/smoke.sh` 是契約。

## 命名空間協調

此外掛擁有 `knowledge-graph` AgentDB 命名空間（kebab-case，遵循 [ruflo-agentdb ADR-0001 `"命名空間慣例"`](../ruflo-agentdb/docs/adrs/0001-agentdb-optimization.md) 的慣例）。保留命名空間（`pattern`、`claude-memories`、`default`）絕不能被覆寫。

實體節點透過 `agentdb_hierarchical-store` 儲存；關係邊透過 `agentdb_causal-edge` 儲存；語意索引使用 `embeddings_generate`（不是 `embeddings_embed`——這個工具名稱不存在；ADR-0001 修正了先前的引用）。

## Pathfinder 演算法

1. **Seed** —— 從目標實體節點開始
2. **Expand** —— 向外追蹤因果邊（可設定深度，預設 3）
3. **Score** —— `relevance = edge_weight * semantic_similarity(query, node)`
4. **Prune** —— 移除低於閾值的路徑（預設 0.3）
5. **Rank** —— 按累計相關性回傳排名靠前的路徑

## G7 控制器（在 ruflo 3.6.23+ / 3.6.24 啟用）

[ADR-095](../../v3/docs/adr/ADR-095-architectural-gaps-from-april-audit.md) 補上了五個 AgentDB 控制器，這個外掛的圖譜遍歷可以利用它們：

- **`gnnService`** —— 在 AgentDB 因果圖上產生 GNN 嵌入並進行關係評分。它會為 pathfinder 的 `semantic_similarity(query, node)` 項目加入結構感知評分；與已確認相關節點相鄰的圖節點會獲得加權提升。
- **`rvfOptimizer`** —— 在持久化前量化並去重向量區塊。知識圖譜索引通常有許多近似重複的實體向量（同一個類別從多個模組重新匯出）；`rvfOptimizer` 會透明地將它們合併。
- **`mutationGuard`** + **`attestationLog`** + **`GuardedVectorBackend`** —— 對底層向量儲存執行證明門控寫入。當圖譜跨越信任邊界（聯邦知識匯入）時特別相關——`.swarm/attestation.db` 中的證明鏈會記錄每次變更，供事後稽核。

尚未完成的 **`graphAdapter`** 控制器將為此外掛提供一流的圖資料庫後端（不再建立疊在 AgentDB 平面因果邊資料表上的圖譜檢視）。相關工作記錄在 ADR-095。

透過 `agentdb_controllers` 或 `agentdb_health` MCP 工具檢查執行階段狀態。

## 驗證

```bash
bash plugins/ruflo-knowledge-graph/scripts/smoke.sh
# 預期：「10 passed, 0 failed」
```

## 架構決策

- [`ADR-0001` —— ruflo-knowledge-graph 外掛契約（修正 embeddings_generate、命名空間協調、以 smoke 作為契約）](./docs/adrs/0001-knowledge-graph-contract.md)

## 相關外掛

- `ruflo-agentdb` —— 上述 G7 控制器透過此外掛的執行階段提供；安裝兩個外掛即可取得完整的圖譜與遍歷涵蓋範圍；命名空間慣例的擁有者
- `ruflo-ruvector` —— 為圖節點提供快速語意搜尋的 HNSW 索引
- `ruflo-adr` —— ADR 相依圖共用同一套因果邊模型

## 授權條款

MIT

## 作為 mod

此外掛提供函式掛鉤 mod（ADR-445，`hooks/register.ts`）。它不發出網路呼叫、不產生程序，也不呼叫模型。

- **Guard**（僅收緊，預設開啟）：拒絕包含金鑰、權杖或密碼的圖譜寫入（`agentdb_causal-edge`、`agentdb_hierarchical-store`、`agentdb_pattern-store`），以及未帶有 `confirm: true` 的 `agentdb_causal-edge-delete` / `agentdb_causal-node-delete` 呼叫。拒絕時絕不回顯機密資訊。
- **`/kg-mod`**：提供 `status`、`recent`、`tools`（此外掛的哪些工具已連線）與 `scan <text>`（Guard 是否會拒絕該文字）。在本機回應。
- **狀態檔：** `.claude-flow/kg-mod/status.json`（`{version: 1, updatedMs, guard, calls, total, blocked, recent}`，只有計數器，絕不包含工具輸入），在工作階段開始時及每次呼叫此外掛的工具後寫入。

選項（`userConfig`）：`guard`（開啟）、`confirmDeletes`（開啟）。

測試：`claude plugin validate plugins/ruflo-knowledge-graph`、`claude plugin test plugins/ruflo-knowledge-graph`、`bash plugins/ruflo-knowledge-graph/scripts/smoke.sh`。

## Install

```
claude plugin marketplace add ruvnet/ruflo
claude plugin install ruflo-knowledge-graph
```

## Original README

# ruflo-knowledge-graph

Knowledge graph construction -- entity extraction, relation mapping, and pathfinder graph traversal.

## Overview

Extracts entities (classes, functions, modules, types, concepts) and relations (imports, extends, implements, depends-on, calls) from source code and documentation. Builds a navigable knowledge graph stored in AgentDB with hierarchical nodes and causal edges. Traverses the graph using a pathfinder algorithm that scores paths by edge weight and semantic similarity.

## Installation

```bash
claude --plugin-dir plugins/ruflo-knowledge-graph
```

## Agents

| Agent | Model | Role |
|-------|-------|------|
| `graph-navigator` | sonnet | Entity extraction, relation mapping, knowledge graph construction, pathfinder traversal |

## Skills

| Skill | Usage | Description |
|-------|-------|-------------|
| `kg-extract` | `/kg-extract <path>` | Extract entities and relations from source files to build a knowledge graph |
| `kg-traverse` | `/kg-traverse <entity> [--depth N]` | Pathfinder traversal starting from a seed entity |

## Commands (5 subcommands)

```bash
kg extract <path>            # Extract entities and relations from source files
kg traverse <entity>         # Pathfinder traversal from a seed entity
kg relations <entity>        # List all direct relations for an entity
kg visualize                 # ASCII visualization of the knowledge graph
kg search <query>            # Semantic search across the graph
```

## Entity Types

| Type | Examples |
|------|----------|
| class | `UserService`, `AuthController` |
| function | `calculateDiscount`, `handleRequest` |
| module | `auth`, `payments`, `api` |
| concept | `authentication`, `caching` |
| type | `User`, `OrderStatus` |
| config | `database`, `redis`, `jwt` |

## Compatibility

- **CLI:** pinned to `@claude-flow/cli` v3.6 major+minor.
- **Verification:** `bash plugins/ruflo-knowledge-graph/scripts/smoke.sh` is the contract.

## Namespace coordination

This plugin owns the `knowledge-graph` AgentDB namespace (kebab-case, follows the convention from [ruflo-agentdb ADR-0001 §"Namespace convention"](../ruflo-agentdb/docs/adrs/0001-agentdb-optimization.md)). Reserved namespaces (`pattern`, `claude-memories`, `default`) MUST NOT be shadowed.

Entity nodes are stored via `agentdb_hierarchical-store`; relation edges via `agentdb_causal-edge`; semantic indexing via `embeddings_generate` (NOT `embeddings_embed` — that tool name doesn't exist; ADR-0001 fixes prior references).

## Pathfinder Algorithm

1. **Seed** -- start from the target entity node
2. **Expand** -- follow causal edges outward (configurable depth, default 3)
3. **Score** -- `relevance = edge_weight * semantic_similarity(query, node)`
4. **Prune** -- remove paths below threshold (default 0.3)
5. **Rank** -- return top-K paths by cumulative relevance

## G7 controllers (activated in ruflo 3.6.23+ / 3.6.24)

[ADR-095](../../v3/docs/adr/ADR-095-architectural-gaps-from-april-audit.md) closed five AgentDB controllers that this plugin's graph traversal can leverage:

- **`gnnService`** — GNN embeddings + relational scoring over the AgentDB causal graph. Augments the pathfinder's `semantic_similarity(query, node)` term with structurally-aware scoring; nodes that are graph-neighbors of confirmed-relevant nodes get a boost.
- **`rvfOptimizer`** — Quantizes + dedupes vector blocks before persistence. Knowledge-graph indexes commonly have many near-duplicate entity vectors (same class re-exported from multiple modules); rvfOptimizer collapses them transparently.
- **`mutationGuard`** + **`attestationLog`** + **`GuardedVectorBackend`** — Proof-gated writes to the underlying vector store. Relevant when the graph spans trust boundaries (federated knowledge import) — the attestation chain at `.swarm/attestation.db` records every mutation for after-the-fact audit.

The yet-pending **`graphAdapter`** controller will give this plugin a first-class graph-DB backend (instead of building the graph view on top of AgentDB's flat causal-edge table). Tracked in ADR-095.

Inspect runtime status via the `agentdb_controllers` or `agentdb_health` MCP tools.

## Verification

```bash
bash plugins/ruflo-knowledge-graph/scripts/smoke.sh
# Expected: "10 passed, 0 failed"
```

## Architecture Decisions

- [`ADR-0001` — ruflo-knowledge-graph plugin contract (embeddings_generate fix, namespace coordination, smoke as contract)](./docs/adrs/0001-knowledge-graph-contract.md)

## Related Plugins

- `ruflo-agentdb` -- The G7 controllers above ship via this plugin's runtime; install both for full graph + traversal coverage; namespace convention owner
- `ruflo-ruvector` -- HNSW indexing for fast semantic search across graph nodes
- `ruflo-adr` -- ADR dependency graphs share the same causal edge model

## License

MIT

## As a mod

This plugin ships a function-hook mod (ADR-445, `hooks/register.ts`). It makes no network call, spawns no process and makes no model call.

- **Guard** (tighten-only, on by default): Refuses graph writes (`agentdb_causal-edge`, `agentdb_hierarchical-store`, `agentdb_pattern-store`) that hold a key, token or password, and `agentdb_causal-edge-delete` / `agentdb_causal-node-delete` unless the call carries `confirm: true`. A refusal never echoes the secret.
- **`/kg-mod`**: `status`, `recent`, `tools` (which of this plugin's tools are connected) and `scan <text>` (would the guard refuse it). Answered locally.
- **Status file**: `.claude-flow/kg-mod/status.json` (`{version: 1, updatedMs, guard, calls, total, blocked, recent}`, counters only, never tool input), written at session start and after every call to this plugin's tools.

Options (`userConfig`): `guard` (on), `confirmDeletes` (on).

Test it: `claude plugin validate plugins/ruflo-knowledge-graph`, `claude plugin test plugins/ruflo-knowledge-graph`, `bash plugins/ruflo-knowledge-graph/scripts/smoke.sh`.
