dsh-go-codegraph 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/cordis.patch.yml +3 -0
- package/lib/cg.js +176 -0
- package/lib/index.js +550 -0
- package/lib/view.js +135 -0
- package/package.json +79 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wangtianyi00001-pixel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 🗺️ dsh-go-codegraph
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**给 DSH 装一张本地代码图谱**:让 agent 一次拿到「真实源码 + 调用链 + 改动影响面」,少读几十个文件。
|
|
4
|
+
|
|
5
|
+
> 🧬 图谱引擎来自 **[codegraph](https://github.com/colbymchenry/codegraph)**(Rust + tree-sitter,20 种语言,本地 SQLite,100% 离线)。
|
|
6
|
+
> 🪨 另一条「少读文件」的路子是 **[caveman](https://github.com/JuliusBrussee/caveman)**——把工具输出压短;它和代码图谱不冲突,可以一起用。
|
|
7
|
+
|
|
8
|
+
## ✨ 它给你什么
|
|
9
|
+
|
|
10
|
+
**给 agent 四个工具**(模型自己会挑):
|
|
11
|
+
|
|
12
|
+
| 🛠️ 工具 | 🎯 用途 |
|
|
13
|
+
|---|---|
|
|
14
|
+
| `codegraph_explore` | 一次拿到相关符号的真实源码、调用链、影响面 |
|
|
15
|
+
| `codegraph_node` | 已知符号名时,看它的源码和谁在调用 |
|
|
16
|
+
| `codegraph_impact` | 改一个符号会波及哪些函数/文件/测试 |
|
|
17
|
+
| `codegraph_status` | 索引状态:节点/文件数、索引时间、待同步改动 |
|
|
18
|
+
|
|
19
|
+
**给手机一张脸**:
|
|
20
|
+
|
|
21
|
+
- 📊 输入框上方一条状态条:`代码图谱 280 符号`(只在数字变化时更新)
|
|
22
|
+
- 🔍 点开是面板:索引概览 + 符号搜索,点结果直接把源码复制走
|
|
23
|
+
- 🔄 「同步」增量更新,「复制概览」把状态复制出来
|
|
24
|
+
|
|
25
|
+
## 📦 需要什么
|
|
26
|
+
|
|
27
|
+
- Node ≥ 22.5
|
|
28
|
+
- codegraph 命令行在 `PATH` 上:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npm i -g @colbymchenry/codegraph
|
|
32
|
+
codegraph --version # 1.6.7
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Linux(x64 / arm64)、macOS、Windows 都有预编译二进制,手机上也能跑(本项目就是在 arm64 手机上验证的)。
|
|
36
|
+
|
|
37
|
+
## 🚀 装
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
cp -r dsh-go-codegraph "$DSH_HOME/dsh-go/plugins/dsh-go-codegraph"
|
|
41
|
+
dsh plugin --profile web add "$DSH_HOME/dsh-go/plugins/dsh-go-codegraph"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
装完重启一次引擎(设置 → 引擎 → 重启引擎),状态条与面板才会出现;`lib/` 改动后同样需要重启。
|
|
45
|
+
|
|
46
|
+
## 🧠 索引是怎么管的
|
|
47
|
+
|
|
48
|
+
- 🏗️ 第一次调用任一工具:项目里没有 `.codegraph/` 就先 `codegraph init`
|
|
49
|
+
- 🔁 之后距上次同步超过 2 分钟会 `codegraph sync`;失败不让工具失败,只在结果末尾注明「基于上次索引」
|
|
50
|
+
- 🙈 建完把 `.codegraph/` 写进 `.git/info/exclude`(只改本地,不动 `.gitignore`)
|
|
51
|
+
- ✂️ 想排除大目录(比如 `deepinfer/`):在项目根放 `codegraph.json`:
|
|
52
|
+
|
|
53
|
+
```json
|
|
54
|
+
{ "exclude": ["deepinfer/"] }
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## 🧾 同步日志
|
|
58
|
+
|
|
59
|
+
每次同步都会往 `$DSH_HOME/cache/dsh-go-codegraph/sync.log` 追加一行 JSON:
|
|
60
|
+
|
|
61
|
+
```json
|
|
62
|
+
{"at":"2026-12-05T08:00:00.000Z","trigger":"panel:sync","cwd":"/root/workspace","ms":1832,"ok":true}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`trigger` 只有四种:`panel:sync`(面板点同步)、`tool:explore|node|impact|status`(工具调用前的 TTL 补同步)、`init`(首次建索引)。
|
|
66
|
+
所以「索引时间自己走了」时,看这个文件就能知道是谁触发的。面板上的「同步日志」按钮会复制它的路径。
|
|
67
|
+
|
|
68
|
+
## ⚙️ 配置
|
|
69
|
+
|
|
70
|
+
| 🔧 键 | 默认 | 说明 |
|
|
71
|
+
|---|---|---|
|
|
72
|
+
| `command` | `codegraph` | 可执行文件路径;不在 `PATH` 上时写绝对路径 |
|
|
73
|
+
| `autoIndex` | `true` | 关掉后不自动建索引,只提示 |
|
|
74
|
+
| `maxOutputChars` | `48000` | 单次工具输出上限,超出截断 |
|
|
75
|
+
|
|
76
|
+
## ⚠️ 已知限制
|
|
77
|
+
|
|
78
|
+
- 只读当前会话工作目录对应的项目;monorepo 子包要显式传 `path`
|
|
79
|
+
- 同步是「距上次 2 分钟才做一次」,不是实时
|
|
80
|
+
- 输出上限 48 KB,超长截断(explore 的结论在最前面)
|
|
81
|
+
- 依赖 codegraph 的 CLI;插件只调用它,不内嵌二进制
|
|
82
|
+
|
|
83
|
+
## 🔗 链接
|
|
84
|
+
|
|
85
|
+
- 🧬 上游引擎:[colbymchenry/codegraph](https://github.com/colbymchenry/codegraph)
|
|
86
|
+
- 🪨 相关项目:[caveman](https://github.com/JuliusBrussee/caveman)
|
|
87
|
+
|
|
88
|
+
## 📄 License
|
|
89
|
+
|
|
90
|
+
MIT
|
|
91
|
+
|
|
92
|
+
> 名字里的 `go` 是为了和 npm 上已有的 `dsh-codegraph`(另一个 MCP 方案)区分开。
|
package/cordis.patch.yml
ADDED
package/lib/cg.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* codegraph CLI 的薄封装。
|
|
3
|
+
*
|
|
4
|
+
* 这里只做四件事:找到可执行文件、跑一次命令、解析 `status --json`、把
|
|
5
|
+
* 输出裁剪到工具能接受的长度。所有解析函数都是纯函数,方便单测。
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from 'node:child_process'
|
|
8
|
+
import { access, appendFile, mkdir, readFile, rename, stat } from 'node:fs/promises'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_COMMAND = 'codegraph'
|
|
13
|
+
export const DEFAULT_TIMEOUT_MS = 120_000
|
|
14
|
+
export const STATUS_TIMEOUT_MS = 20_000
|
|
15
|
+
/** 距上次同步超过这么久才再同步一次,避免每次调用都付 2 秒。 */
|
|
16
|
+
export const SYNC_TTL_MS = 2 * 60_000
|
|
17
|
+
/** 单次工具输出上限(字符),超过就截断并附一行说明。 */
|
|
18
|
+
export const MAX_OUTPUT_CHARS = 48_000
|
|
19
|
+
|
|
20
|
+
export const INDEX_DIR = '.codegraph'
|
|
21
|
+
|
|
22
|
+
export function indexPath(cwd) {
|
|
23
|
+
return path.join(cwd, INDEX_DIR)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function hasIndex(cwd) {
|
|
27
|
+
// 只看目录不够:init 中断时会留下一个只有 .gitignore 的空目录,
|
|
28
|
+
// 之后每次调用都会以为「已经建好」而跳过重建。
|
|
29
|
+
try {
|
|
30
|
+
await access(path.join(indexPath(cwd), 'codegraph.db'))
|
|
31
|
+
return true
|
|
32
|
+
} catch {
|
|
33
|
+
return false
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 把任意数值收敛到整数区间;不可解析时用默认值。 */
|
|
38
|
+
export function clampInt(value, min, max, fallback) {
|
|
39
|
+
const n = Math.round(Number(value))
|
|
40
|
+
if (!Number.isFinite(n)) return fallback
|
|
41
|
+
return Math.min(max, Math.max(min, n))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 183 → "183",1234 → "1.2k",2_400_000 → "2.4m"。 */
|
|
45
|
+
export function fmtCount(n) {
|
|
46
|
+
if (!Number.isFinite(n)) return '—'
|
|
47
|
+
if (Math.abs(n) >= 1e6) return `${(n / 1e6).toFixed(1).replace(/\.0$/, '')}m`
|
|
48
|
+
if (Math.abs(n) >= 1e3) return `${(n / 1e3).toFixed(1).replace(/\.0$/, '')}k`
|
|
49
|
+
return String(Math.round(n))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 跑一次 codegraph。永不抛错:超时、命令缺失、非零退出都折进返回值,
|
|
54
|
+
* 由调用方决定怎么描述,工具层再把它们变成人话。
|
|
55
|
+
*/
|
|
56
|
+
export function runCli(command, args, { cwd, timeoutMs = DEFAULT_TIMEOUT_MS, signal, env } = {}) {
|
|
57
|
+
const bin = typeof command === 'string' && command.trim() ? command.trim() : DEFAULT_COMMAND
|
|
58
|
+
return new Promise((resolve) => {
|
|
59
|
+
execFile(
|
|
60
|
+
bin,
|
|
61
|
+
args,
|
|
62
|
+
{
|
|
63
|
+
cwd,
|
|
64
|
+
timeout: timeoutMs,
|
|
65
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
66
|
+
signal,
|
|
67
|
+
env: { ...process.env, CODEGRAPH_TELEMETRY: '0', ...(env || {}) },
|
|
68
|
+
},
|
|
69
|
+
(error, stdout, stderr) => {
|
|
70
|
+
const timedOut = Boolean(error?.killed) || error?.code === 'ETIMEDOUT'
|
|
71
|
+
resolve({
|
|
72
|
+
ok: !error,
|
|
73
|
+
code: typeof error?.code === 'number' ? error.code : error ? 1 : 0,
|
|
74
|
+
stdout: String(stdout ?? ''),
|
|
75
|
+
stderr: String(stderr ?? ''),
|
|
76
|
+
timedOut,
|
|
77
|
+
missing: error?.code === 'ENOENT',
|
|
78
|
+
})
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** `status --json` 的输出解析;不是 JSON 就返回 null。 */
|
|
85
|
+
export function parseStatus(text) {
|
|
86
|
+
const raw = String(text ?? '').trim()
|
|
87
|
+
if (!raw) return null
|
|
88
|
+
try {
|
|
89
|
+
const value = JSON.parse(raw)
|
|
90
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : null
|
|
91
|
+
} catch {
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 未初始化时 CLI 会在 stdout 打印 "✗ CodeGraph not initialized in …"。 */
|
|
97
|
+
export function looksUninitialized(text) {
|
|
98
|
+
return /not initialized/i.test(String(text ?? ''))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 一句能放进状态条(≤24 字)的摘要。 */
|
|
102
|
+
export function stripTextOf(status) {
|
|
103
|
+
if (!status) return '代码图谱 · 未索引'
|
|
104
|
+
if (status.initialized === false) return '代码图谱 · 未索引'
|
|
105
|
+
const nodes = Number(status.nodeCount)
|
|
106
|
+
const files = Number(status.fileCount)
|
|
107
|
+
if (!Number.isFinite(nodes)) return '代码图谱 · 已索引'
|
|
108
|
+
return `代码图谱 ${fmtCount(nodes)} 符号`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 面板/工具里给人看的索引概览。 */
|
|
112
|
+
export function describeStatus(status, cwd) {
|
|
113
|
+
if (!status || status.initialized === false) {
|
|
114
|
+
return `项目 ${cwd} 还没有索引。调用 codegraph_status 或任一 codegraph 工具会自动建立。`
|
|
115
|
+
}
|
|
116
|
+
const lines = [
|
|
117
|
+
`项目:${status.projectPath || cwd}`,
|
|
118
|
+
`索引:${fmtCount(status.nodeCount)} 节点 / ${fmtCount(status.edgeCount)} 边 / ${fmtCount(status.fileCount)} 文件`,
|
|
119
|
+
`语言:${Array.isArray(status.languages) && status.languages.length ? status.languages.join(', ') : '—'}`,
|
|
120
|
+
`索引时间:${status.lastIndexed || '—'}`,
|
|
121
|
+
`版本:${status.version || '—'}`,
|
|
122
|
+
]
|
|
123
|
+
const pending = status.pendingChanges
|
|
124
|
+
if (pending && (pending.added || pending.modified || pending.removed)) {
|
|
125
|
+
lines.push(`待同步:+${pending.added || 0} ~${pending.modified || 0} -${pending.removed || 0}`)
|
|
126
|
+
}
|
|
127
|
+
return lines.join('\n')
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 截断超长输出,保留开头(explore 的结论在最前面)。 */
|
|
131
|
+
export function truncateOutput(text, maxChars = MAX_OUTPUT_CHARS) {
|
|
132
|
+
const s = String(text ?? '')
|
|
133
|
+
if (s.length <= maxChars) return s
|
|
134
|
+
return `${s.slice(0, maxChars)}\n\n…(输出过长,已截断 ${s.length - maxChars} 字符;可缩小 query 或加 maxFiles)`
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 索引建立后把 `.codegraph/` 写进 `.git/info/exclude`,避免污染用户仓库的
|
|
139
|
+
* `git status`。只改本地 exclude,不动 `.gitignore`。
|
|
140
|
+
*/
|
|
141
|
+
export async function excludeFromGit(cwd) {
|
|
142
|
+
const gitDir = path.join(cwd, '.git')
|
|
143
|
+
try {
|
|
144
|
+
await access(gitDir)
|
|
145
|
+
} catch {
|
|
146
|
+
return false
|
|
147
|
+
}
|
|
148
|
+
const file = path.join(gitDir, 'info', 'exclude')
|
|
149
|
+
try {
|
|
150
|
+
const current = await readFile(file, 'utf8').catch(() => '')
|
|
151
|
+
if (current.split('\n').some((line) => line.trim() === `${INDEX_DIR}/` || line.trim() === INDEX_DIR)) return true
|
|
152
|
+
await appendFile(file, `${current.endsWith('\n') || !current ? '' : '\n'}${INDEX_DIR}/\n`)
|
|
153
|
+
return true
|
|
154
|
+
} catch {
|
|
155
|
+
return false
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
/** 同步日志:记下每次同步是谁触发的,用于解释「索引时间自己走了」。 */
|
|
161
|
+
export function syncLogPath() {
|
|
162
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
163
|
+
return path.join(home, 'cache', 'dsh-go-codegraph', 'sync.log')
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function appendSyncLog(entry) {
|
|
167
|
+
const file = syncLogPath()
|
|
168
|
+
try {
|
|
169
|
+
await mkdir(path.dirname(file), { recursive: true })
|
|
170
|
+
const info = await stat(file).catch(() => null)
|
|
171
|
+
if (info && info.size > 512 * 1024) await rename(file, `${file}.1`)
|
|
172
|
+
await appendFile(file, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, 'utf8')
|
|
173
|
+
} catch {
|
|
174
|
+
/* 日志写失败不影响主流程 */
|
|
175
|
+
}
|
|
176
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-codegraph:把 codegraph 的本地代码知识图谱接进 DSH。
|
|
3
|
+
*
|
|
4
|
+
* 两条腿:
|
|
5
|
+
* 1. 给 agent 四个工具(explore / node / impact / status),首次调用会为
|
|
6
|
+
* 当前会话工作区自动建索引,之后每次按 TTL 同步一次。
|
|
7
|
+
* 2. 给 dsh-go 一条输入框上方的状态条,显示当前项目的索引规模,点一下强制同步。
|
|
8
|
+
*
|
|
9
|
+
* 所有上游失败都变成工具结果里的一句话,不抛给桥接,也不让模型看到堆栈。
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
appendSyncLog,
|
|
13
|
+
syncLogPath,
|
|
14
|
+
DEFAULT_COMMAND,
|
|
15
|
+
STATUS_TIMEOUT_MS,
|
|
16
|
+
SYNC_TTL_MS,
|
|
17
|
+
clampInt,
|
|
18
|
+
describeStatus,
|
|
19
|
+
excludeFromGit,
|
|
20
|
+
hasIndex,
|
|
21
|
+
looksUninitialized,
|
|
22
|
+
parseStatus,
|
|
23
|
+
runCli,
|
|
24
|
+
stripTextOf,
|
|
25
|
+
truncateOutput,
|
|
26
|
+
} from './cg.js'
|
|
27
|
+
import { buildPanelView, normalizeQueryResult, panelDataOf } from './view.js'
|
|
28
|
+
|
|
29
|
+
export const name = 'dsh-codegraph'
|
|
30
|
+
|
|
31
|
+
/** 工具注册要等 tools 服务就绪;dshGo 在 apply 里可选注入。 */
|
|
32
|
+
export const inject = ['tools']
|
|
33
|
+
|
|
34
|
+
const INIT_TIMEOUT_MS = 170_000
|
|
35
|
+
const EXPLORE_TIMEOUT_MS = 120_000
|
|
36
|
+
|
|
37
|
+
function firstLine(text) {
|
|
38
|
+
return String(text ?? '').split('\n').map((line) => line.trim()).find(Boolean) ?? ''
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 工具结果的统一形状:一段 markdown 文本。 */
|
|
42
|
+
function textTool(name, description, parameters, timeoutMs, execute) {
|
|
43
|
+
return {
|
|
44
|
+
name,
|
|
45
|
+
description,
|
|
46
|
+
parameters,
|
|
47
|
+
timeoutMs,
|
|
48
|
+
output: {
|
|
49
|
+
schema: {
|
|
50
|
+
type: 'object',
|
|
51
|
+
properties: { text: { type: 'string', description: 'Markdown 结果或一句错误说明。' } },
|
|
52
|
+
required: ['text'],
|
|
53
|
+
additionalProperties: false,
|
|
54
|
+
},
|
|
55
|
+
render(_args, value) {
|
|
56
|
+
const text = typeof value?.text === 'string' ? value.text : ''
|
|
57
|
+
return [{ type: 'text', text }]
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
execute,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const PATH_PARAM = {
|
|
65
|
+
type: 'string',
|
|
66
|
+
description: '项目路径;省略时用当前会话的工作目录,通常不用写。',
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function apply(ctx, config = {}) {
|
|
70
|
+
const command = typeof config?.command === 'string' && config.command.trim() ? config.command.trim() : DEFAULT_COMMAND
|
|
71
|
+
const autoIndex = config?.autoIndex !== false
|
|
72
|
+
const maxOutputChars = clampInt(config?.maxOutputChars, 4_000, 200_000, 48_000)
|
|
73
|
+
/** cwd -> 上次同步完成时间 */
|
|
74
|
+
const lastSync = new Map()
|
|
75
|
+
|
|
76
|
+
async function sessionCwd(exec) {
|
|
77
|
+
const agent = exec?.agent
|
|
78
|
+
try {
|
|
79
|
+
const workingDirectory = ctx.get('workingDirectory')
|
|
80
|
+
if (agent && workingDirectory && typeof workingDirectory.ensure === 'function') {
|
|
81
|
+
return await workingDirectory.ensure(agent, exec.signal)
|
|
82
|
+
}
|
|
83
|
+
} catch {
|
|
84
|
+
/* 拿不到会话目录就用进程目录 */
|
|
85
|
+
}
|
|
86
|
+
return process.cwd()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function cwdArg(args) {
|
|
90
|
+
return typeof args?.path === 'string' && args.path.trim() ? args.path.trim() : ''
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function ensureIndex(cwd, exec) {
|
|
94
|
+
if (await hasIndex(cwd)) return { ok: true, created: false }
|
|
95
|
+
const initStarted = Date.now()
|
|
96
|
+
if (!autoIndex) return { ok: false, created: false, reason: `项目 ${cwd} 还没有索引,且插件关闭了自动建索引` }
|
|
97
|
+
const run = await runCli(command, ['init', cwd, '-y'], { cwd, timeoutMs: INIT_TIMEOUT_MS, signal: exec?.signal })
|
|
98
|
+
if (!run.ok || run.timedOut) {
|
|
99
|
+
const why = run.missing
|
|
100
|
+
? '没找到 codegraph 命令,请先安装:npm i -g @colbymchenry/codegraph'
|
|
101
|
+
: firstLine(run.stderr) || firstLine(run.stdout) || 'init 失败'
|
|
102
|
+
return { ok: false, created: false, reason: why }
|
|
103
|
+
}
|
|
104
|
+
// init 偶尔会留下一个只有 .gitignore 的空目录;确认数据库真的落地,不行再来一次。
|
|
105
|
+
if (!(await hasIndex(cwd))) {
|
|
106
|
+
const retry = await runCli(command, ['init', cwd, '-y'], { cwd, timeoutMs: INIT_TIMEOUT_MS, signal: exec?.signal })
|
|
107
|
+
if (!(await hasIndex(cwd))) {
|
|
108
|
+
return {
|
|
109
|
+
ok: false,
|
|
110
|
+
created: false,
|
|
111
|
+
reason: firstLine(retry.stderr) || firstLine(retry.stdout) || 'init 没有产出索引数据库',
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
await excludeFromGit(cwd)
|
|
116
|
+
lastSync.set(cwd, Date.now())
|
|
117
|
+
void appendSyncLog({ trigger: 'init', cwd, ms: Date.now() - initStarted, ok: true, created: true })
|
|
118
|
+
return { ok: true, created: true }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function syncIfStale(cwd, exec, trigger = 'tool') {
|
|
122
|
+
const at = lastSync.get(cwd) ?? 0
|
|
123
|
+
if (Date.now() - at < SYNC_TTL_MS) return { ok: true, skipped: true }
|
|
124
|
+
const started = Date.now()
|
|
125
|
+
const run = await runCli(command, ['sync', cwd, '--quiet'], { cwd, timeoutMs: 20_000, signal: exec?.signal })
|
|
126
|
+
lastSync.set(cwd, Date.now())
|
|
127
|
+
const ms = Date.now() - started
|
|
128
|
+
if (run.ok) {
|
|
129
|
+
void appendSyncLog({ trigger, cwd, ms, ok: true })
|
|
130
|
+
return { ok: true, skipped: false }
|
|
131
|
+
}
|
|
132
|
+
const reason = run.timedOut ? '同步超时' : firstLine(run.stderr) || '同步失败'
|
|
133
|
+
void appendSyncLog({ trigger, cwd, ms, ok: false, reason })
|
|
134
|
+
return { ok: false, skipped: false, reason }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 统一的前置:定位目录 → 必要时建索引 → 必要时同步。 */
|
|
138
|
+
async function prepare(exec, args, options = {}) {
|
|
139
|
+
const explicit = cwdArg(args)
|
|
140
|
+
const cwd = explicit || (await sessionCwd(exec))
|
|
141
|
+
if (options.skipIndex && explicit) return { cwd, sync: null }
|
|
142
|
+
const index = await ensureIndex(cwd, exec)
|
|
143
|
+
if (!index.ok) return { cwd, error: index.reason }
|
|
144
|
+
const sync = await syncIfStale(cwd, exec, options.trigger || 'tool')
|
|
145
|
+
return { cwd, indexCreated: index.created, sync }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
ctx.tools.register(
|
|
149
|
+
textTool(
|
|
150
|
+
'codegraph_explore',
|
|
151
|
+
[
|
|
152
|
+
'从本地代码知识图谱回答一个关于代码的问题:一次调用返回相关符号的**原始源码**、它们之间的**调用链**,以及**改动影响面**(哪些函数/测试会受影响)。',
|
|
153
|
+
'任何「这块怎么工作 / X 是怎么到 Y 的 / 改这里会动到什么」的问题,先用它,别急着 grep + read:它比逐个读文件少几十倍的来回。',
|
|
154
|
+
'查询用自然语言描述意图即可(英文效果最好,中文也能用)。项目没有索引时会自动建立(第一次可能等十几秒)。',
|
|
155
|
+
].join('\n'),
|
|
156
|
+
{
|
|
157
|
+
type: 'object',
|
|
158
|
+
properties: {
|
|
159
|
+
query: {
|
|
160
|
+
type: 'string',
|
|
161
|
+
description: '要查的问题或区域,例如 "面板刷新数据的链路" 或 "how does auth token refresh work"。',
|
|
162
|
+
},
|
|
163
|
+
maxFiles: { type: 'integer', minimum: 1, maximum: 20, description: '结果里最多带几个文件的源码,默认 6。' },
|
|
164
|
+
path: PATH_PARAM,
|
|
165
|
+
},
|
|
166
|
+
required: ['query'],
|
|
167
|
+
additionalProperties: false,
|
|
168
|
+
},
|
|
169
|
+
EXPLORE_TIMEOUT_MS + INIT_TIMEOUT_MS,
|
|
170
|
+
async (args, exec) => {
|
|
171
|
+
const query = String(args?.query ?? '').trim()
|
|
172
|
+
if (!query) return { text: '请给一个查询,例如 "面板怎么刷新数据"。' }
|
|
173
|
+
const prepared = await prepare(exec, args, { trigger: 'tool:explore' })
|
|
174
|
+
if (prepared.error) return { text: prepared.error }
|
|
175
|
+
const maxFiles = clampInt(args?.maxFiles, 1, 20, 6)
|
|
176
|
+
const run = await runCli(
|
|
177
|
+
command,
|
|
178
|
+
['explore', query, '-p', prepared.cwd, '--max-files', String(maxFiles)],
|
|
179
|
+
{ cwd: prepared.cwd, timeoutMs: EXPLORE_TIMEOUT_MS, signal: exec.signal },
|
|
180
|
+
)
|
|
181
|
+
const out = String(run.stdout ?? '').trim()
|
|
182
|
+
if (!out) {
|
|
183
|
+
return { text: `codegraph explore 没有返回内容(${firstLine(run.stderr) || (run.timedOut ? '超时' : '空输出')})。` }
|
|
184
|
+
}
|
|
185
|
+
const stale = prepared.sync && prepared.sync.ok === false ? `\n\n[codegraph] ${prepared.sync.reason},结果基于上一次索引。` : ''
|
|
186
|
+
return { text: truncateOutput(out, maxOutputChars) + stale }
|
|
187
|
+
},
|
|
188
|
+
),
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
ctx.tools.register(
|
|
192
|
+
textTool(
|
|
193
|
+
'codegraph_node',
|
|
194
|
+
'看一个符号(函数/类/方法)的**真实源码 + 谁在调用它**。已经知道符号名时用它,比 explore 更省。',
|
|
195
|
+
{
|
|
196
|
+
type: 'object',
|
|
197
|
+
properties: {
|
|
198
|
+
symbol: { type: 'string', description: '符号名(可带类名前缀)。' },
|
|
199
|
+
path: PATH_PARAM,
|
|
200
|
+
},
|
|
201
|
+
required: ['symbol'],
|
|
202
|
+
additionalProperties: false,
|
|
203
|
+
},
|
|
204
|
+
EXPLORE_TIMEOUT_MS + INIT_TIMEOUT_MS,
|
|
205
|
+
async (args, exec) => {
|
|
206
|
+
const symbol = String(args?.symbol ?? '').trim()
|
|
207
|
+
if (!symbol) return { text: '请给一个符号名。' }
|
|
208
|
+
const prepared = await prepare(exec, args, { trigger: 'tool:node' })
|
|
209
|
+
if (prepared.error) return { text: prepared.error }
|
|
210
|
+
const run = await runCli(command, ['node', symbol, '-p', prepared.cwd], {
|
|
211
|
+
cwd: prepared.cwd,
|
|
212
|
+
timeoutMs: EXPLORE_TIMEOUT_MS,
|
|
213
|
+
signal: exec.signal,
|
|
214
|
+
})
|
|
215
|
+
const out = String(run.stdout ?? '').trim()
|
|
216
|
+
if (!out || looksUninitialized(out)) {
|
|
217
|
+
const why = firstLine(run.stderr) || '索引里没有这个符号'
|
|
218
|
+
return { text: `没找到 "${symbol}"(${why})。可以先 codegraph_explore 用自然语言找。` }
|
|
219
|
+
}
|
|
220
|
+
return { text: truncateOutput(out, maxOutputChars) }
|
|
221
|
+
},
|
|
222
|
+
),
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
ctx.tools.register(
|
|
226
|
+
textTool(
|
|
227
|
+
'codegraph_impact',
|
|
228
|
+
'查改动一个符号的**影响面**:沿调用链找出会被波及的函数、文件,以及覆盖到它的测试文件。改代码前用它决定要跑哪些测试。',
|
|
229
|
+
{
|
|
230
|
+
type: 'object',
|
|
231
|
+
properties: {
|
|
232
|
+
symbol: { type: 'string', description: '要改的符号名。' },
|
|
233
|
+
depth: { type: 'integer', minimum: 1, maximum: 5, description: '调用链深度,默认 2。' },
|
|
234
|
+
path: PATH_PARAM,
|
|
235
|
+
},
|
|
236
|
+
required: ['symbol'],
|
|
237
|
+
additionalProperties: false,
|
|
238
|
+
},
|
|
239
|
+
EXPLORE_TIMEOUT_MS + INIT_TIMEOUT_MS,
|
|
240
|
+
async (args, exec) => {
|
|
241
|
+
const symbol = String(args?.symbol ?? '').trim()
|
|
242
|
+
if (!symbol) return { text: '请给一个符号名。' }
|
|
243
|
+
const prepared = await prepare(exec, args, { trigger: 'tool:impact' })
|
|
244
|
+
if (prepared.error) return { text: prepared.error }
|
|
245
|
+
const depth = clampInt(args?.depth, 1, 5, 2)
|
|
246
|
+
const run = await runCli(
|
|
247
|
+
command,
|
|
248
|
+
['impact', symbol, '-p', prepared.cwd, '--depth', String(depth), '--json'],
|
|
249
|
+
{ cwd: prepared.cwd, timeoutMs: EXPLORE_TIMEOUT_MS, signal: exec.signal },
|
|
250
|
+
)
|
|
251
|
+
const out = String(run.stdout ?? '').trim()
|
|
252
|
+
let parsed = null
|
|
253
|
+
try {
|
|
254
|
+
parsed = out ? JSON.parse(out) : null
|
|
255
|
+
} catch {
|
|
256
|
+
parsed = null
|
|
257
|
+
}
|
|
258
|
+
if (!parsed) {
|
|
259
|
+
const why = firstLine(run.stderr) || '输出不是 JSON'
|
|
260
|
+
return { text: `没拿到影响面(${why})。` }
|
|
261
|
+
}
|
|
262
|
+
return { text: truncateOutput(summarizeImpact(parsed), maxOutputChars) }
|
|
263
|
+
},
|
|
264
|
+
),
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
ctx.tools.register(
|
|
268
|
+
textTool(
|
|
269
|
+
'codegraph_status',
|
|
270
|
+
'看当前项目的代码图谱状态:建没建索引、多少节点/文件、什么时候索引的、有没有待同步的改动。在新的项目里第一次用 codegraph 工具前先看它;索引异常时也用它排查。',
|
|
271
|
+
{
|
|
272
|
+
type: 'object',
|
|
273
|
+
properties: { path: PATH_PARAM },
|
|
274
|
+
additionalProperties: false,
|
|
275
|
+
},
|
|
276
|
+
INIT_TIMEOUT_MS + STATUS_TIMEOUT_MS,
|
|
277
|
+
async (args, exec) => {
|
|
278
|
+
const prepared = await prepare(exec, args, { trigger: 'tool:status' })
|
|
279
|
+
if (prepared.error) return { text: prepared.error }
|
|
280
|
+
const run = await runCli(command, ['status', prepared.cwd, '--json'], {
|
|
281
|
+
cwd: prepared.cwd,
|
|
282
|
+
timeoutMs: STATUS_TIMEOUT_MS,
|
|
283
|
+
signal: exec.signal,
|
|
284
|
+
})
|
|
285
|
+
const status = parseStatus(run.stdout)
|
|
286
|
+
if (!status) {
|
|
287
|
+
return { text: `读不到索引状态(${firstLine(run.stderr) || 'status 输出不是 JSON'})。` }
|
|
288
|
+
}
|
|
289
|
+
const created = prepared.indexCreated ? '\n(刚刚为这个项目建立了索引)' : ''
|
|
290
|
+
return { text: describeStatus(status, prepared.cwd) + created }
|
|
291
|
+
},
|
|
292
|
+
),
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
/* ---------------- dsh-go:状态条 + 面板 ---------------- */
|
|
296
|
+
|
|
297
|
+
function scopeKeyOf(scope) {
|
|
298
|
+
if (!scope || typeof scope !== 'object') return '(global)'
|
|
299
|
+
const keys = ['callId', 'messageId', 'sessionId', 'turnId'].filter(
|
|
300
|
+
(k) => typeof scope[k] === 'string' && scope[k],
|
|
301
|
+
)
|
|
302
|
+
if (!keys.length) return '(global)'
|
|
303
|
+
return keys
|
|
304
|
+
.sort()
|
|
305
|
+
.map((k) => `${k}=${encodeURIComponent(scope[k])}`)
|
|
306
|
+
.join('&')
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function scopeCwd(scope) {
|
|
310
|
+
try {
|
|
311
|
+
const sessionId = scope && typeof scope === 'object' ? scope.sessionId : undefined
|
|
312
|
+
const agents = ctx.get('agents')
|
|
313
|
+
const agent = sessionId && agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined
|
|
314
|
+
const workingDirectory = ctx.get('workingDirectory')
|
|
315
|
+
if (agent && workingDirectory && typeof workingDirectory.ensure === 'function') {
|
|
316
|
+
return workingDirectory.ensure(agent).catch(() => process.cwd())
|
|
317
|
+
}
|
|
318
|
+
} catch {
|
|
319
|
+
/* 老桥接没有这些服务 */
|
|
320
|
+
}
|
|
321
|
+
return Promise.resolve(process.cwd())
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function quickStripText(cwd) {
|
|
325
|
+
if (!(await hasIndex(cwd))) return '代码图谱 · 未索引'
|
|
326
|
+
const run = await runCli(command, ['status', cwd, '--json'], { cwd, timeoutMs: STATUS_TIMEOUT_MS })
|
|
327
|
+
const status = parseStatus(run.stdout)
|
|
328
|
+
return status ? stripTextOf(status) : '代码图谱 · 状态未知'
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
ctx.inject(['dshGo'], (host) => {
|
|
332
|
+
const refreshPanel = (scope) => {
|
|
333
|
+
try {
|
|
334
|
+
host.dshGo.refresh?.('codegraph', scope)
|
|
335
|
+
} catch {
|
|
336
|
+
/* 老桥接没有 refresh */
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/* ---- 状态条:只在文字变化时推送,避免 45 秒闪一下 ---- */
|
|
341
|
+
|
|
342
|
+
host.dshGo.strip('cg-strip', (scope, emit) => {
|
|
343
|
+
let alive = true
|
|
344
|
+
let timer = null
|
|
345
|
+
let last = ''
|
|
346
|
+
const push = async () => {
|
|
347
|
+
const text = await quickStripText(await scopeCwd(scope))
|
|
348
|
+
if (!alive || text === last) return
|
|
349
|
+
last = text
|
|
350
|
+
try {
|
|
351
|
+
emit({ text, icon: 'chart', tone: text.includes('未索引') ? 'muted' : 'ok' })
|
|
352
|
+
} catch {
|
|
353
|
+
/* 订阅已断开 */
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
void push()
|
|
357
|
+
timer = setInterval(() => void push(), 45_000)
|
|
358
|
+
timer.unref?.()
|
|
359
|
+
return () => {
|
|
360
|
+
alive = false
|
|
361
|
+
if (timer) clearInterval(timer)
|
|
362
|
+
}
|
|
363
|
+
})
|
|
364
|
+
|
|
365
|
+
/* ---- 面板:索引概览 + 符号搜索 + 复制源码 ---- */
|
|
366
|
+
|
|
367
|
+
const states = new Map()
|
|
368
|
+
|
|
369
|
+
function stateOf(scope) {
|
|
370
|
+
const sk = scopeKeyOf(scope)
|
|
371
|
+
let st = states.get(sk)
|
|
372
|
+
if (!st) {
|
|
373
|
+
st = { q: '', results: [], status: null, error: '' }
|
|
374
|
+
states.set(sk, st)
|
|
375
|
+
}
|
|
376
|
+
return st
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function loadStatus(scope, st) {
|
|
380
|
+
const cwd = await scopeCwd(scope)
|
|
381
|
+
const run = await runCli(command, ['status', cwd, '--json'], { cwd, timeoutMs: STATUS_TIMEOUT_MS })
|
|
382
|
+
const status = parseStatus(run.stdout)
|
|
383
|
+
if (status) {
|
|
384
|
+
st.status = status
|
|
385
|
+
st.error = ''
|
|
386
|
+
} else {
|
|
387
|
+
st.error = `读不到索引状态(${firstLine(run.stderr) || '不是 JSON 输出'})`
|
|
388
|
+
}
|
|
389
|
+
return st
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async function runSearch(scope, st, q) {
|
|
393
|
+
const cwd = await scopeCwd(scope)
|
|
394
|
+
const index = await ensureIndex(cwd, { signal: undefined })
|
|
395
|
+
if (!index.ok) {
|
|
396
|
+
st.error = index.reason
|
|
397
|
+
refreshPanel(scope)
|
|
398
|
+
return
|
|
399
|
+
}
|
|
400
|
+
const run = await runCli(command, ['query', q, '-p', cwd, '--json', '--limit', '12'], {
|
|
401
|
+
cwd,
|
|
402
|
+
timeoutMs: 8_000,
|
|
403
|
+
})
|
|
404
|
+
let parsed = null
|
|
405
|
+
try {
|
|
406
|
+
parsed = run.stdout ? JSON.parse(run.stdout) : null
|
|
407
|
+
} catch {
|
|
408
|
+
parsed = null
|
|
409
|
+
}
|
|
410
|
+
if (!parsed) {
|
|
411
|
+
st.error = `搜索失败(${firstLine(run.stderr) || (run.timedOut ? '超时' : '输出不是 JSON')})`
|
|
412
|
+
} else {
|
|
413
|
+
st.results = normalizeQueryResult(parsed)
|
|
414
|
+
st.error = ''
|
|
415
|
+
}
|
|
416
|
+
await loadStatus(scope, st)
|
|
417
|
+
refreshPanel(scope)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function extractQuery(event) {
|
|
421
|
+
const v = event?.value ?? event
|
|
422
|
+
if (typeof v === 'string') return v.trim()
|
|
423
|
+
if (v && typeof v === 'object') {
|
|
424
|
+
const direct = v.q ?? v.data?.q ?? v.query
|
|
425
|
+
if (typeof direct === 'string') return direct.trim()
|
|
426
|
+
}
|
|
427
|
+
return ''
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const panelActions = {
|
|
431
|
+
search(scope, event) {
|
|
432
|
+
const st = stateOf(scope)
|
|
433
|
+
const q = extractQuery(event) || st.q
|
|
434
|
+
if (!q) return { toast: '先输入要搜的符号' }
|
|
435
|
+
st.q = q
|
|
436
|
+
st.error = ''
|
|
437
|
+
void runSearch(scope, st, q)
|
|
438
|
+
return { refresh: true }
|
|
439
|
+
},
|
|
440
|
+
|
|
441
|
+
async copyNode(scope, event) {
|
|
442
|
+
const name =
|
|
443
|
+
(typeof event?.value?.args?.name === 'string' && event.value.args.name) ||
|
|
444
|
+
(typeof event?.value?.name === 'string' && event.value.name) ||
|
|
445
|
+
''
|
|
446
|
+
if (!name) return { toast: '没有选中符号' }
|
|
447
|
+
const cwd = await scopeCwd(scope)
|
|
448
|
+
const run = await runCli(command, ['node', name, '-p', cwd], { cwd, timeoutMs: 2_500 })
|
|
449
|
+
const out = String(run.stdout ?? '').trim()
|
|
450
|
+
if (!out) return { toast: run.timedOut ? '源码太大,换 codegraph_node 工具看' : '没拿到源码' }
|
|
451
|
+
return { copy: out.slice(0, 8_000), toast: '源码已复制' }
|
|
452
|
+
},
|
|
453
|
+
|
|
454
|
+
sync(scope) {
|
|
455
|
+
const st = stateOf(scope)
|
|
456
|
+
void (async () => {
|
|
457
|
+
const cwd = await scopeCwd(scope)
|
|
458
|
+
const index = await ensureIndex(cwd, { signal: undefined })
|
|
459
|
+
if (!index.ok) {
|
|
460
|
+
st.error = index.reason
|
|
461
|
+
refreshPanel(scope)
|
|
462
|
+
return
|
|
463
|
+
}
|
|
464
|
+
lastSync.delete(cwd)
|
|
465
|
+
await syncIfStale(cwd, { signal: undefined }, 'panel:sync')
|
|
466
|
+
await loadStatus(scope, st)
|
|
467
|
+
refreshPanel(scope)
|
|
468
|
+
})()
|
|
469
|
+
return { toast: '正在同步…' }
|
|
470
|
+
},
|
|
471
|
+
|
|
472
|
+
async copyLog() {
|
|
473
|
+
return { copy: syncLogPath(), toast: '同步日志路径已复制' }
|
|
474
|
+
},
|
|
475
|
+
|
|
476
|
+
async copyStatus(scope) {
|
|
477
|
+
const st = stateOf(scope)
|
|
478
|
+
await loadStatus(scope, st)
|
|
479
|
+
refreshPanel(scope)
|
|
480
|
+
return { copy: describeStatus(st.status, await scopeCwd(scope)).slice(0, 8_000), toast: '概览已复制' }
|
|
481
|
+
},
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
host.dshGo.panel('codegraph', {
|
|
485
|
+
view: (scope, caps) => buildPanelView(stateOf(scope), caps),
|
|
486
|
+
data: (scope, emit) => {
|
|
487
|
+
const st = stateOf(scope)
|
|
488
|
+
let alive = true
|
|
489
|
+
const push = () => {
|
|
490
|
+
if (!alive) return
|
|
491
|
+
try {
|
|
492
|
+
emit(panelDataOf(st))
|
|
493
|
+
} catch {
|
|
494
|
+
/* 订阅已断开 */
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
push()
|
|
498
|
+
void loadStatus(scope, st).then(() => {
|
|
499
|
+
push()
|
|
500
|
+
refreshPanel(scope)
|
|
501
|
+
})
|
|
502
|
+
return () => {
|
|
503
|
+
alive = false
|
|
504
|
+
states.delete(scopeKeyOf(scope))
|
|
505
|
+
}
|
|
506
|
+
},
|
|
507
|
+
actions: panelActions,
|
|
508
|
+
})
|
|
509
|
+
|
|
510
|
+
host.dshGo.on('codegraph', (scope, event) => {
|
|
511
|
+
const action = event?.action ?? event?.value?.action
|
|
512
|
+
if (typeof action === 'string' && panelActions[action]) return panelActions[action](scope, event)
|
|
513
|
+
return panelActions.search(scope, event)
|
|
514
|
+
})
|
|
515
|
+
})
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** 把 impact --json 的树状结果折成 markdown 列表。 */
|
|
519
|
+
export function summarizeImpact(data) {
|
|
520
|
+
const targets = Array.isArray(data?.targets) ? data.targets : []
|
|
521
|
+
const definitions = Array.isArray(data?.definitions) ? data.definitions : []
|
|
522
|
+
const affected = []
|
|
523
|
+
for (const def of definitions) {
|
|
524
|
+
for (const item of Array.isArray(def?.affected) ? def.affected : []) {
|
|
525
|
+
if (!item || !item.name) continue
|
|
526
|
+
if (!affected.some((x) => x.id === item.id)) affected.push(item)
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
const files = new Set(affected.filter((x) => x.kind === 'file').map((x) => x.filePath))
|
|
530
|
+
const tests = affected.filter((x) => x.kind === 'file' && /(^|[\\/])(test|tests|__tests__|spec)\b|\.(test|spec)\./.test(`${x.filePath}`))
|
|
531
|
+
const lines = [
|
|
532
|
+
`**影响面:${targets.map((t) => t?.name).filter(Boolean).join(' / ') || data?.symbol || '—'}**(深度 ${data?.depth ?? '—'})`,
|
|
533
|
+
'',
|
|
534
|
+
`受影响 ${affected.filter((x) => x.kind !== 'file').length} 个符号 / ${files.size} 个文件${tests.length ? `,其中 ${tests.length} 个测试文件` : ''}`,
|
|
535
|
+
]
|
|
536
|
+
const byFile = new Map()
|
|
537
|
+
for (const item of affected) {
|
|
538
|
+
const key = item.filePath || '—'
|
|
539
|
+
if (!byFile.has(key)) byFile.set(key, [])
|
|
540
|
+
byFile.get(key).push(item)
|
|
541
|
+
}
|
|
542
|
+
for (const [file, items] of byFile) {
|
|
543
|
+
const names = items
|
|
544
|
+
.filter((x) => x.kind !== 'file')
|
|
545
|
+
.map((x) => `${x.name}${x.startLine ? `:${x.startLine}` : ''}`)
|
|
546
|
+
const isTest = tests.some((t) => t.filePath === file)
|
|
547
|
+
lines.push('', `- ${file}${isTest ? '(测试)' : ''}${names.length ? ` — ${names.join(', ')}` : ''}`)
|
|
548
|
+
}
|
|
549
|
+
return lines.join('\n')
|
|
550
|
+
}
|
package/lib/view.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 面板视图:只从一份只读状态渲染,不碰全局变量,方便单测。
|
|
3
|
+
*
|
|
4
|
+
* state = {
|
|
5
|
+
* q: 上次搜索的词,
|
|
6
|
+
* results: [{ name, kind, filePath, startLine }],
|
|
7
|
+
* status: codegraph status --json 的结果或 null,
|
|
8
|
+
* error: 一句人话或 '',
|
|
9
|
+
* updatedAt: 'MM-DD HH:mm',
|
|
10
|
+
* }
|
|
11
|
+
*/
|
|
12
|
+
import { fmtCount } from './cg.js'
|
|
13
|
+
|
|
14
|
+
/** `codegraph query --json` 的数组 → 扁平行。 */
|
|
15
|
+
export function normalizeQueryResult(json) {
|
|
16
|
+
const list = Array.isArray(json) ? json : []
|
|
17
|
+
const rows = []
|
|
18
|
+
for (const item of list) {
|
|
19
|
+
const node = item?.node ?? item
|
|
20
|
+
if (!node || typeof node !== 'object') continue
|
|
21
|
+
const name = String(node.name ?? '').trim()
|
|
22
|
+
if (!name) continue
|
|
23
|
+
rows.push({
|
|
24
|
+
name,
|
|
25
|
+
kind: String(node.kind ?? 'symbol'),
|
|
26
|
+
filePath: String(node.filePath ?? ''),
|
|
27
|
+
startLine: Number.isFinite(node.startLine) ? node.startLine : null,
|
|
28
|
+
score: Number.isFinite(item?.score) ? item.score : null,
|
|
29
|
+
})
|
|
30
|
+
if (rows.length >= 30) break
|
|
31
|
+
}
|
|
32
|
+
return rows
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function tsLabel(iso) {
|
|
36
|
+
if (!iso) return '暂无'
|
|
37
|
+
const d = new Date(iso)
|
|
38
|
+
if (Number.isNaN(d.getTime())) return '暂无'
|
|
39
|
+
const p = (n) => String(n).padStart(2, '0')
|
|
40
|
+
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function panelDataOf(state) {
|
|
44
|
+
return {
|
|
45
|
+
q: state.q || '',
|
|
46
|
+
updatedAt: tsLabel(state.status?.lastIndexed),
|
|
47
|
+
summary: state.status?.initialized === false ? '未索引' : fmtCount(state.status?.nodeCount),
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function buildPanelView(state, caps) {
|
|
52
|
+
const zh = !caps?.locale || String(caps.locale).startsWith('zh')
|
|
53
|
+
const status = state.status
|
|
54
|
+
const initialized = Boolean(status && status.initialized !== false)
|
|
55
|
+
const results = Array.isArray(state.results) ? state.results.slice(0, 12) : []
|
|
56
|
+
|
|
57
|
+
const metrics = {
|
|
58
|
+
type: 'row',
|
|
59
|
+
children: [
|
|
60
|
+
{ type: 'metric', label: zh ? '节点' : 'Nodes', value: initialized ? fmtCount(status.nodeCount) : '—' },
|
|
61
|
+
{ type: 'metric', label: zh ? '文件' : 'Files', value: initialized ? fmtCount(status.fileCount) : '—' },
|
|
62
|
+
{ type: 'metric', label: zh ? '索引时间' : 'Indexed', value: { $: 'data.updatedAt' }, caption: zh ? '本地快照' : 'local' },
|
|
63
|
+
],
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const notices = []
|
|
67
|
+
if (state.error) notices.push({ type: 'callout', tone: 'warn', text: state.error })
|
|
68
|
+
if (!initialized) {
|
|
69
|
+
notices.push({
|
|
70
|
+
type: 'callout',
|
|
71
|
+
tone: 'info',
|
|
72
|
+
text: zh ? '这个项目还没有索引:搜一次,或者点「同步」,会顺手建好。' : 'Not indexed yet. A search or sync builds it.',
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const form = {
|
|
77
|
+
type: 'form',
|
|
78
|
+
submit: 'search',
|
|
79
|
+
submitLabel: zh ? '查找' : 'Search',
|
|
80
|
+
children: [
|
|
81
|
+
{
|
|
82
|
+
type: 'textField',
|
|
83
|
+
label: zh ? '符号或文件' : 'Symbol or file',
|
|
84
|
+
bind: 'data.q',
|
|
85
|
+
placeholder: zh ? '例如 scopeKey' : 'e.g. scopeKey',
|
|
86
|
+
maxLength: 120,
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const body = []
|
|
92
|
+
if (results.length) {
|
|
93
|
+
body.push({
|
|
94
|
+
type: 'list',
|
|
95
|
+
items: results.map((row) => ({
|
|
96
|
+
title: row.name,
|
|
97
|
+
subtitle: `${row.kind} · ${row.filePath}${row.startLine ? `:${row.startLine}` : ''}`,
|
|
98
|
+
action: { id: 'copyNode', args: { name: row.name } },
|
|
99
|
+
})),
|
|
100
|
+
})
|
|
101
|
+
} else if (state.q) {
|
|
102
|
+
body.push({
|
|
103
|
+
type: 'text',
|
|
104
|
+
tone: 'muted',
|
|
105
|
+
text: zh ? `没找到和「${state.q}」匹配的符号` : `No symbol matches “${state.q}”`,
|
|
106
|
+
})
|
|
107
|
+
} else {
|
|
108
|
+
body.push({
|
|
109
|
+
type: 'text',
|
|
110
|
+
tone: 'muted',
|
|
111
|
+
text: zh ? '搜一个函数名或类名,点结果就能把它的源码复制走。' : 'Search a function or class; tap a hit to copy its source.',
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
v: 2,
|
|
117
|
+
accent: 'app',
|
|
118
|
+
type: 'stack',
|
|
119
|
+
title: zh ? '代码图谱' : 'Code Graph',
|
|
120
|
+
style: { card: 'surface', padding: 'M', gap: 'M' },
|
|
121
|
+
children: [
|
|
122
|
+
metrics,
|
|
123
|
+
...notices,
|
|
124
|
+
form,
|
|
125
|
+
...body,
|
|
126
|
+
{
|
|
127
|
+
type: 'actions',
|
|
128
|
+
items: [
|
|
129
|
+
{ label: zh ? '同步' : 'Sync', action: 'sync', icon: 'refresh' },
|
|
130
|
+
{ label: zh ? '复制概览' : 'Copy', action: 'copyStatus', icon: 'copy' },
|
|
131
|
+
],
|
|
132
|
+
},
|
|
133
|
+
],
|
|
134
|
+
}
|
|
135
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,81 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-go-codegraph",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
|
+
"description": "🗺️ dsh 插件:给 agent 装一张本地代码图谱(explore / node / impact),手机上一条状态条加一块搜索面板",
|
|
7
|
+
"files": [
|
|
8
|
+
"lib/",
|
|
9
|
+
"cordis.patch.yml",
|
|
10
|
+
"README.md",
|
|
11
|
+
"LICENSE"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"code-graph",
|
|
18
|
+
"code-intelligence",
|
|
19
|
+
"codegraph",
|
|
20
|
+
"dsh-go",
|
|
21
|
+
"dsh-plugin"
|
|
22
|
+
],
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=22.5",
|
|
26
|
+
"dsh": ">=0.2.1-rc.2 <0.3.0-0"
|
|
27
|
+
},
|
|
28
|
+
"dsh": {
|
|
29
|
+
"bundle": {
|
|
30
|
+
"patch": "./cordis.patch.yml"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"dshGo": {
|
|
34
|
+
"v": 1,
|
|
35
|
+
"title": {
|
|
36
|
+
"zh": "代码图谱",
|
|
37
|
+
"en": "Code Graph"
|
|
38
|
+
},
|
|
39
|
+
"icon": "chart",
|
|
40
|
+
"contributes": {
|
|
41
|
+
"composer.strip": [
|
|
42
|
+
{
|
|
43
|
+
"id": "cg-strip",
|
|
44
|
+
"icon": "chart",
|
|
45
|
+
"text": {
|
|
46
|
+
"zh": "代码图谱",
|
|
47
|
+
"en": "Code graph"
|
|
48
|
+
},
|
|
49
|
+
"panel": "codegraph"
|
|
50
|
+
}
|
|
51
|
+
],
|
|
52
|
+
"panels": [
|
|
53
|
+
{
|
|
54
|
+
"id": "codegraph",
|
|
55
|
+
"title": {
|
|
56
|
+
"zh": "代码图谱",
|
|
57
|
+
"en": "Code Graph"
|
|
58
|
+
},
|
|
59
|
+
"icon": "chart",
|
|
60
|
+
"placement": [
|
|
61
|
+
"session.tab",
|
|
62
|
+
"features",
|
|
63
|
+
"chat.panel"
|
|
64
|
+
],
|
|
65
|
+
"presentation": "sheet"
|
|
66
|
+
}
|
|
67
|
+
]
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"repository": {
|
|
71
|
+
"type": "git",
|
|
72
|
+
"url": "git+https://github.com/wangtianyi00001-pixel/dsh-go-codegraph.git"
|
|
73
|
+
},
|
|
74
|
+
"homepage": "https://github.com/wangtianyi00001-pixel/dsh-go-codegraph#readme",
|
|
75
|
+
"bugs": {
|
|
76
|
+
"url": "https://github.com/wangtianyi00001-pixel/dsh-go-codegraph/issues"
|
|
77
|
+
},
|
|
78
|
+
"publishConfig": {
|
|
79
|
+
"access": "public"
|
|
80
|
+
}
|
|
81
|
+
}
|