@liuxincuit/pi-codegraph 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -49,7 +49,13 @@ pi -e ./extensions/codegraph.ts
49
49
 
50
50
  ## 功能一览
51
51
 
52
- - **`codegraph_explore` 工具**面向智能体的核心代码智能工具。输入符号名或自然语言问题即可查询;可选传 `path` 查询其他已建索引的项目,传 `maxFiles` 限制返回的源码行数。
52
+ - **`codegraph_*` 工具集**面向智能体的代码智能工具,均支持 `path` 参数查询其他已建索引的项目:
53
+ - `codegraph_explore` — 一揽子探索:相关符号逐字源码 + 调用路径 + 影响范围(`maxFiles` 限制返回行数)
54
+ - `codegraph_query` — 按名称搜索符号(位置 + 签名,可选 `kind`/`limit` 过滤)
55
+ - `codegraph_node` — 单个符号的源码 + 调用轨迹,可链式追踪调用图
56
+ - `codegraph_callers` / `codegraph_callees` — 谁调用了它 / 它调用了谁(`limit`)
57
+ - `codegraph_impact` — 修改符号的影响半径(`depth`)
58
+ - `codegraph_files` — 从索引查看文件结构(tree/flat/grouped,`pattern`、`maxDepth`)
53
59
  - **`/codegraph-init [path]`** — 为项目建立索引(`codegraph init`)。
54
60
  - **`/codegraph-sync [path]`** — 手动同步自上次索引以来的改动(`codegraph sync`)。
55
61
  - **`/codegraph-status [path]`** — 查看索引状态与统计信息(`codegraph status`)。
@@ -8,7 +8,7 @@
8
8
  // Upstream: https://github.com/colbymchenry/codegraph
9
9
 
10
10
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
- import { Type } from "typebox";
11
+ import { TSchema, Type } from "typebox";
12
12
  import * as fs from "node:fs/promises";
13
13
  import * as path from "node:path";
14
14
  import { fileURLToPath } from "node:url";
@@ -79,14 +79,19 @@ function updateStatusBar(ctx: ExtensionContext, state: StatusState) {
79
79
  }
80
80
 
81
81
  // Modeled on upstream's MCP SERVER_INSTRUCTIONS (src/mcp/server-instructions.ts):
82
- // lead the agent to codegraph_explore BEFORE grep/read, plus anti-patterns and staleness handling.
82
+ // lead the agent to the codegraph_* tools BEFORE grep/read, plus anti-patterns and staleness handling.
83
83
  const INDEX_HINT = `# CodeGraph — this project is indexed
84
84
 
85
- A \`.codegraph/\` index exists here: SQLite knowledge graph of every symbol, edge, and file (30+ languages). ONE \`codegraph_explore\` call returns the relevant symbols' verbatim line-numbered source (treat it as already Read — safe to Edit from) PLUS call paths between them and a blast-radius summary of what depends on them.
85
+ A \`.codegraph/\` index exists here: SQLite knowledge graph of every symbol, edge, and file (30+ languages). It answers structural code questions with verbatim, line-numbered source (treat codegraph output as already Read — safe to Edit from).
86
86
 
87
- - For structural questions (how does X work / where is X / who calls Y / what breaks if I change Z), call \`codegraph_explore\` INSTEAD of grep + read — usually ONE call answers the whole question.
88
- - Call it BEFORE and WHILE writing or editing code: it puts the blast radius in view before you touch a symbol you can name.
89
- - Flow tracing: name endpoint symbols (e.g. \`mutateElement renderScene\`) to surface the path across dynamic-dispatch hops.
87
+ - For structural questions (how does X work / where is X / who calls Y / what breaks if I change Z), use the codegraph_* tools INSTEAD of grep + read — usually ONE call answers the whole question.
88
+ - Choose the right tool:
89
+ - \`codegraph_query\` locate a symbol: locations + signatures only.
90
+ - \`codegraph_node\` — one symbol's source + caller/callee trail (chain it to follow a call graph).
91
+ - \`codegraph_callers\` — who calls a symbol. \`codegraph_callees\` — what a symbol calls.
92
+ - \`codegraph_impact\` — blast radius of changing a symbol (call before editing).
93
+ - \`codegraph_files\` — indexed file tree (tree/flat/grouped by language).
94
+ - \`codegraph_explore\` — broad questions: relevant symbols' source + call paths in one shot. Name endpoint symbols (e.g. \`mutateElement renderScene\`) to surface paths across dynamic-dispatch hops.
90
95
  - Anti-patterns: don't grep or Read first; don't re-verify codegraph output with grep (AST-derived, more accurate than grep); don't reconstruct a flow by hand.
91
96
  - "Already sent earlier in this conversation": pointer means content is already in context — do not re-fetch or Read.
92
97
  - Staleness: if tool output contains "⚠️ Some files referenced below were edited since the last index sync", read only those flagged files directly.
@@ -113,9 +118,7 @@ export default async function codegraphExtension(pi: ExtensionAPI) {
113
118
  name: "codegraph_explore",
114
119
  label: "CodeGraph Explore",
115
120
  description:
116
- "PRIMARY tool for code questions call it BEFORE grep/read when the project has a .codegraph/ index. " +
117
- "One query returns the relevant symbols' verbatim line-numbered source plus the call paths between them and a blast-radius summary. " +
118
- "If the project is not indexed the output says so: continue with built-in tools and suggest the user run /codegraph-init.",
121
+ "Broad code exploration in one shot: relevant symbols' verbatim line-numbered source, call paths between them, and a blast-radius summary.",
119
122
  promptSnippet:
120
123
  "codegraph_explore: symbol source + call paths in one shot from the project's CodeGraph index",
121
124
  promptGuidelines: [
@@ -128,7 +131,7 @@ export default async function codegraphExtension(pi: ExtensionAPI) {
128
131
  }),
129
132
  path: Type.Optional(
130
133
  Type.String({
131
- description: "Project path to query; defaults to the current working directory",
134
+ description: "Project path (default: cwd)",
132
135
  }),
133
136
  ),
134
137
  maxFiles: Type.Optional(
@@ -156,6 +159,193 @@ export default async function codegraphExtension(pi: ExtensionAPI) {
156
159
  },
157
160
  });
158
161
 
162
+ // ── codegraph_* fine-grained tools (CLI parity with the MCP tools) ────
163
+ // Each maps 1:1 to a codegraph CLI subcommand; `path` selects the project,
164
+ // defaults to the session cwd (same convention as codegraph_explore).
165
+ const projectPath = () =>
166
+ Type.Optional(
167
+ Type.String({
168
+ description: "Project path (default: cwd)",
169
+ }),
170
+ );
171
+
172
+ type CliToolDef = {
173
+ name: string;
174
+ label: string;
175
+ description: string;
176
+ snippet: string;
177
+ guidelines: string[];
178
+ subcommand: string;
179
+ parameters: TSchema;
180
+ positional?: (p: Record<string, unknown>) => string[];
181
+ flags?: (p: Record<string, unknown>) => string[];
182
+ timeout?: number;
183
+ };
184
+
185
+ function registerCliTool(pi: ExtensionAPI, def: CliToolDef) {
186
+ pi.registerTool({
187
+ name: def.name,
188
+ label: def.label,
189
+ description: def.description,
190
+ promptSnippet: def.snippet,
191
+ promptGuidelines: def.guidelines,
192
+ parameters: def.parameters,
193
+ execute: async (_toolCallId, params: Record<string, unknown>, signal, _onUpdate, ctx) => {
194
+ const cwd = (params.path as string | undefined) ?? ctx.cwd;
195
+ const args = [
196
+ def.subcommand,
197
+ ...(def.positional?.(params) ?? []),
198
+ "-p",
199
+ cwd,
200
+ ...(def.flags?.(params) ?? []),
201
+ ];
202
+ const result = await execCg(pi, args, {
203
+ signal,
204
+ timeout: def.timeout ?? 60_000,
205
+ });
206
+ if (result.killed) return textResult(`codegraph ${def.subcommand} timed out`);
207
+ // Non-zero exits carry upstream's agent-friendly guidance — pass it through.
208
+ if (result.code !== 0) return textResult(outputOf(result));
209
+ return textResult(result.stdout.trim());
210
+ },
211
+ });
212
+ }
213
+
214
+ const cliTools: CliToolDef[] = [
215
+ {
216
+ name: "codegraph_query",
217
+ label: "CodeGraph Query",
218
+ description:
219
+ "Search symbols by name. Returns locations and signatures only (no source). Use to locate where a symbol is declared.",
220
+ snippet: "codegraph_query: symbol locations + signatures by name",
221
+ guidelines: [
222
+ "To locate where a symbol is declared (kind, file, line), use codegraph_query before grep.",
223
+ ],
224
+ subcommand: "query",
225
+ parameters: Type.Object({
226
+ search: Type.String({ description: "Symbol name or partial name to search" }),
227
+ kind: Type.Optional(
228
+ Type.String({
229
+ description:
230
+ "Filter by node kind: function, method, class, interface, type, variable, route, component",
231
+ }),
232
+ ),
233
+ limit: Type.Optional(Type.Integer({ description: "Maximum results (default 10)" })),
234
+ path: projectPath(),
235
+ }),
236
+ positional: (p) => [p.search as string],
237
+ flags: (p) => [
238
+ ...(p.kind ? ["--kind", p.kind as string] : []),
239
+ ...(typeof p.limit === "number" && p.limit > 0 ? ["--limit", String(p.limit)] : []),
240
+ ],
241
+ },
242
+ {
243
+ name: "codegraph_node",
244
+ label: "CodeGraph Node",
245
+ description:
246
+ "One symbol's source plus its caller/callee trail. Chain it to follow a call graph across files.",
247
+ snippet: "codegraph_node: a symbol's source + caller/callee trail",
248
+ guidelines: [
249
+ "To deep-dive one known symbol (verbatim source + who it calls / is called by), use codegraph_node.",
250
+ ],
251
+ subcommand: "node",
252
+ parameters: Type.Object({
253
+ name: Type.String({ description: "Symbol name to inspect" }),
254
+ path: projectPath(),
255
+ }),
256
+ positional: (p) => [p.name as string],
257
+ },
258
+ {
259
+ name: "codegraph_callers",
260
+ label: "CodeGraph Callers",
261
+ description: "Find all functions or methods that call a specific symbol.",
262
+ snippet: "codegraph_callers: who calls a symbol",
263
+ guidelines: [
264
+ "To find what calls a symbol (reverse dependencies), use codegraph_callers.",
265
+ ],
266
+ subcommand: "callers",
267
+ parameters: Type.Object({
268
+ symbol: Type.String({ description: "Symbol name whose callers to find" }),
269
+ limit: Type.Optional(Type.Integer({ description: "Maximum results (default 20)" })),
270
+ path: projectPath(),
271
+ }),
272
+ positional: (p) => [p.symbol as string],
273
+ flags: (p) => [
274
+ ...(typeof p.limit === "number" && p.limit > 0 ? ["--limit", String(p.limit)] : []),
275
+ ],
276
+ },
277
+ {
278
+ name: "codegraph_callees",
279
+ label: "CodeGraph Callees",
280
+ description: "Find all functions or methods that a specific symbol calls.",
281
+ snippet: "codegraph_callees: what a symbol calls",
282
+ guidelines: [
283
+ "To find what a symbol calls (its outgoing edges), use codegraph_callees.",
284
+ ],
285
+ subcommand: "callees",
286
+ parameters: Type.Object({
287
+ symbol: Type.String({ description: "Symbol name whose callees to find" }),
288
+ limit: Type.Optional(Type.Integer({ description: "Maximum results (default 20)" })),
289
+ path: projectPath(),
290
+ }),
291
+ positional: (p) => [p.symbol as string],
292
+ flags: (p) => [
293
+ ...(typeof p.limit === "number" && p.limit > 0 ? ["--limit", String(p.limit)] : []),
294
+ ],
295
+ },
296
+ {
297
+ name: "codegraph_impact",
298
+ label: "CodeGraph Impact",
299
+ description: "Analyze what code is affected by changing a symbol (blast radius).",
300
+ snippet: "codegraph_impact: blast radius of changing a symbol",
301
+ guidelines: [
302
+ "Before editing a symbol, use codegraph_impact to see what depends on it.",
303
+ ],
304
+ subcommand: "impact",
305
+ parameters: Type.Object({
306
+ symbol: Type.String({ description: "Symbol name to analyze impact of changing" }),
307
+ depth: Type.Optional(Type.Integer({ description: "Traversal depth (default 2)" })),
308
+ path: projectPath(),
309
+ }),
310
+ positional: (p) => [p.symbol as string],
311
+ flags: (p) => [
312
+ ...(typeof p.depth === "number" && p.depth > 0 ? ["--depth", String(p.depth)] : []),
313
+ ],
314
+ },
315
+ {
316
+ name: "codegraph_files",
317
+ label: "CodeGraph Files",
318
+ description:
319
+ "Show the indexed project's file structure (tree, flat, or grouped by language), with per-file symbol counts.",
320
+ snippet: "codegraph_files: indexed file tree with symbol counts",
321
+ guidelines: [
322
+ "To get a structured view of the project files, use codegraph_files.",
323
+ ],
324
+ subcommand: "files",
325
+ parameters: Type.Object({
326
+ dir: Type.Optional(Type.String({ description: "Subdirectory within the project to show" })),
327
+ pattern: Type.Optional(Type.String({ description: "Glob pattern to filter files" })),
328
+ format: Type.Optional(
329
+ Type.Union([Type.Literal("tree"), Type.Literal("flat"), Type.Literal("grouped")]),
330
+ ),
331
+ maxDepth: Type.Optional(Type.Integer({ description: "Maximum directory depth for tree format" })),
332
+ path: projectPath(),
333
+ }),
334
+ positional: (p) => (p.dir ? [p.dir as string] : []),
335
+ flags: (p) => [
336
+ ...(p.pattern ? ["--pattern", p.pattern as string] : []),
337
+ ...(p.format ? ["--format", p.format as string] : []),
338
+ ...(typeof p.maxDepth === "number" && p.maxDepth > 0
339
+ ? ["--max-depth", String(p.maxDepth)]
340
+ : []),
341
+ ],
342
+ },
343
+ ];
344
+
345
+ for (const tool of cliTools) {
346
+ registerCliTool(pi, tool);
347
+ }
348
+
159
349
  // ── /codegraph-init ────────────────────────────────────────────────────
160
350
  pi.registerCommand("codegraph-init", {
161
351
  description: "Build the CodeGraph index for the current project (codegraph init)",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liuxincuit/pi-codegraph",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "CodeGraph support for pi — symbol source + call paths via the codegraph CLI",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -1,27 +1,30 @@
1
- ---
2
- name: codegraph
3
- description: Query the project's CodeGraph index (symbol source + call paths) via the codegraph_explore tool. Use when answering structural code questions — how X works, where X is, what a change affects — in a project that has a .codegraph/ index.
4
- ---
5
-
6
- # CodeGraph
7
-
8
- The `codegraph_explore` tool answers structural code questions in one shot: the relevant symbols' verbatim line-numbered source, the call paths between them, and a blast-radius summary. It reads the project's CodeGraph index (`.codegraph/`), built and maintained by the `codegraph` CLI.
9
-
10
- ## When to use
11
-
12
- - "How does X work?" / "Where is X?" / "What calls Y?" / "What breaks if I change Z?"
13
- - Before an edit, to map the symbols you are about to touch and inspect the blast radius.
14
- - Prefer it over grep/read for structural exploration **when the project has a `.codegraph/` index**.
15
-
16
- ## How to query
17
-
18
- - `query`: symbol names (`CodeGraph open`, `MCPSession`), endpoint flows (`mutateElement renderScene`), or a natural-language question. Naming a file or symbol returns its current line-numbered source.
19
- - `path`: optional project path. Defaults to the current working directory. In a monorepo, pass the sub-project directory that contains `.codegraph/`.
20
- - `maxFiles`: optional integer to limit how many file sources are returned.
21
-
22
- ## Anti-patterns & Guidance
23
-
24
- - **Trust AST results.** Don't re-verify codegraph output with grep.
25
- - **Already sent earlier in this conversation.** When this pointer appears, the lines are already in your session context — scroll back instead of re-fetching or reading the file.
26
- - **Staleness banner.** If output warns `⚠️ Some files referenced below were edited since the last index sync`, read only those specific files directly; other files in the response remain fresh.
27
- - **No index, no tool.** If the output says the project isn't indexed, stop calling `codegraph_explore` for that project this session and use built-in tools. Indexing is the user's decision — suggest the user run `/codegraph-init` if appropriate.
1
+ ---
2
+ name: codegraph
3
+ description: Query the project's CodeGraph index (symbol source, call paths, blast radius) via the codegraph_* tools. Use when answering structural code questions — how X works, where X is, who calls Y, what a change affects — in a project that has a .codegraph/ index.
4
+ ---
5
+
6
+ # CodeGraph
7
+
8
+ The `codegraph_*` tools answer structural code questions from the project's CodeGraph index (`.codegraph/`), built and maintained by the `codegraph` CLI. Prefer them over grep/read for structural exploration **when the project has a `.codegraph/` index**.
9
+
10
+ ## Picking a tool
11
+
12
+ - `codegraph_query` locate a symbol: locations + signatures only. Start here when you don't know where something is declared.
13
+ - `codegraph_node` one known symbol's verbatim source + caller/callee trail. Chain it to follow a call graph across files.
14
+ - `codegraph_callers` / `codegraph_callees` who calls a symbol / what a symbol calls.
15
+ - `codegraph_impact` — blast radius of changing a symbol; call before editing.
16
+ - `codegraph_files` indexed file tree (tree/flat/grouped by language) with symbol counts.
17
+ - `codegraph_explore` — broad questions: relevant symbols' source + call paths in one shot. Name endpoint symbols (`mutateElement renderScene`) to surface paths across dynamic-dispatch hops.
18
+
19
+ ## How to query
20
+
21
+ - Every tool accepts `path`: the project to query. Defaults to the current working directory. In a monorepo, pass the sub-project directory that contains `.codegraph/`.
22
+ - `codegraph_query`: `search` (symbol name or partial), optional `kind` (function, method, class, ...) and `limit`.
23
+ - `codegraph_explore`: `query` (symbol names or natural language) and optional `maxFiles` to cap source lines returned.
24
+
25
+ ## Anti-patterns & Guidance
26
+
27
+ - **Trust AST results.** Don't re-verify codegraph output with grep.
28
+ - **Already sent earlier in this conversation.** When this pointer appears, the lines are already in your session context — scroll back instead of re-fetching or reading the file.
29
+ - **Staleness banner.** If output warns `⚠️ Some files referenced below were edited since the last index sync`, read only those specific files directly; other files in the response remain fresh.
30
+ - **No index, no tool.** If output says the project isn't indexed, stop calling `codegraph_*` for that project this session and use built-in tools. Indexing is the user's decision — suggest the user run `/codegraph-init` if appropriate.