@liuxincuit/pi-codegraph 0.1.0 → 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
@@ -15,6 +15,8 @@
15
15
  npm i -g @colbymchenry/codegraph
16
16
  ```
17
17
 
18
+ 未检测到 CLI 时,插件**不会注入任何工具、命令或技能**(`codegraph_explore`、`/codegraph-*`、CodeGraph 技能均不加载),仅在会话开始时弹出一条安装提示;安装后 `/reload` 或重启 pi 即恢复全部功能。
19
+
18
20
  ## 安装
19
21
 
20
22
  ### npm(推荐)
@@ -47,7 +49,13 @@ pi -e ./extensions/codegraph.ts
47
49
 
48
50
  ## 功能一览
49
51
 
50
- - **`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`)
51
59
  - **`/codegraph-init [path]`** — 为项目建立索引(`codegraph init`)。
52
60
  - **`/codegraph-sync [path]`** — 手动同步自上次索引以来的改动(`codegraph sync`)。
53
61
  - **`/codegraph-status [path]`** — 查看索引状态与统计信息(`codegraph status`)。
@@ -8,16 +8,21 @@
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
+ import { fileURLToPath } from "node:url";
14
15
 
15
16
  const INSTALL_HINT =
16
- "codegraph CLI not found on PATH. Install: npm i -g @colbymchenry/codegraph";
17
+ "未检测到 codegraph CLIPATH 中无 codegraph 命令),本插件未注入任何工具、命令或技能。" +
18
+ "安装:npm i -g @colbymchenry/codegraph,然后 /reload 或重启 pi 生效。";
19
+
20
+ // Whole-process dedup for the missing-CLI hint: extensions re-run per session and
21
+ // per subagent (separate jiti module copies), so gate on globalThis.
22
+ const MISSING_CLI_HINTED = Symbol.for("pi-codegraph.missing-cli-hinted");
17
23
 
18
24
  // Result of `codegraph version` this session — null until first check.
19
25
  let cliAvailable: boolean | null = null;
20
- let notifiedMissing = false;
21
26
 
22
27
  async function execCg(
23
28
  pi: ExtensionAPI,
@@ -74,29 +79,46 @@ function updateStatusBar(ctx: ExtensionContext, state: StatusState) {
74
79
  }
75
80
 
76
81
  // Modeled on upstream's MCP SERVER_INSTRUCTIONS (src/mcp/server-instructions.ts):
77
- // 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.
78
83
  const INDEX_HINT = `# CodeGraph — this project is indexed
79
84
 
80
- 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).
81
86
 
82
- - 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.
83
- - Call it BEFORE and WHILE writing or editing code: it puts the blast radius in view before you touch a symbol you can name.
84
- - 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.
85
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.
86
96
  - "Already sent earlier in this conversation": pointer means content is already in context — do not re-fetch or Read.
87
97
  - Staleness: if tool output contains "⚠️ Some files referenced below were edited since the last index sync", read only those flagged files directly.
88
98
  - Multi-project / Monorepo: pass \`path\` to query any indexed sub-project directory.
89
99
  - If a project has no \`.codegraph/\`, use built-in tools there; indexing is the user's decision — suggest /codegraph-init if it comes up.`;
90
100
 
91
- export default function codegraphExtension(pi: ExtensionAPI) {
101
+ // When the CLI is absent, register nothing but a one-shot hint handler: no
102
+ // tools, no commands, no resources_discover (so no skill injection), no sync.
103
+ export function registerMissingCliHint(pi: ExtensionAPI) {
104
+ pi.on("session_start", async (_event, ctx) => {
105
+ if ((globalThis as Record<symbol, boolean>)[MISSING_CLI_HINTED]) return;
106
+ (globalThis as Record<symbol, boolean>)[MISSING_CLI_HINTED] = true;
107
+ if (ctx.hasUI) ctx.ui.notify(INSTALL_HINT, "warning");
108
+ });
109
+ }
110
+
111
+ export default async function codegraphExtension(pi: ExtensionAPI) {
112
+ if (!(await ensureCli(pi))) {
113
+ registerMissingCliHint(pi);
114
+ return;
115
+ }
92
116
  // ── codegraph_explore tool ─────────────────────────────────────────────
93
117
  pi.registerTool({
94
118
  name: "codegraph_explore",
95
119
  label: "CodeGraph Explore",
96
120
  description:
97
- "PRIMARY tool for code questions call it BEFORE grep/read when the project has a .codegraph/ index. " +
98
- "One query returns the relevant symbols' verbatim line-numbered source plus the call paths between them and a blast-radius summary. " +
99
- "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.",
100
122
  promptSnippet:
101
123
  "codegraph_explore: symbol source + call paths in one shot from the project's CodeGraph index",
102
124
  promptGuidelines: [
@@ -109,7 +131,7 @@ export default function codegraphExtension(pi: ExtensionAPI) {
109
131
  }),
110
132
  path: Type.Optional(
111
133
  Type.String({
112
- description: "Project path to query; defaults to the current working directory",
134
+ description: "Project path (default: cwd)",
113
135
  }),
114
136
  ),
115
137
  maxFiles: Type.Optional(
@@ -137,6 +159,193 @@ export default function codegraphExtension(pi: ExtensionAPI) {
137
159
  },
138
160
  });
139
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
+
140
349
  // ── /codegraph-init ────────────────────────────────────────────────────
141
350
  pi.registerCommand("codegraph-init", {
142
351
  description: "Build the CodeGraph index for the current project (codegraph init)",
@@ -238,17 +447,15 @@ export default function codegraphExtension(pi: ExtensionAPI) {
238
447
  },
239
448
  });
240
449
 
241
- // ── session_start: CLI check + incremental sync + context hint ────────
242
- pi.on("session_start", async (event, ctx) => {
243
- if (!(await ensureCli(pi))) {
244
- updateStatusBar(ctx, false);
245
- if (ctx.hasUI && !notifiedMissing) {
246
- notifiedMissing = true;
247
- ctx.ui.notify(INSTALL_HINT, "warning");
248
- }
249
- return;
250
- }
450
+ // ── resources_discover: contribute the skill only when the CLI exists ──
451
+ pi.on("resources_discover", async () => {
452
+ return {
453
+ skillPaths: [fileURLToPath(new URL("../skills/codegraph/SKILL.md", import.meta.url))],
454
+ };
455
+ });
251
456
 
457
+ // ── session_start: incremental sync + context hint ────────────────────
458
+ pi.on("session_start", async (event, ctx) => {
252
459
  const indexed = await isIndexed(ctx.cwd);
253
460
  if (indexed) {
254
461
  updateStatusBar(ctx, "sync");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liuxincuit/pi-codegraph",
3
- "version": "0.1.0",
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": [
@@ -31,9 +31,6 @@
31
31
  "pi": {
32
32
  "extensions": [
33
33
  "./extensions"
34
- ],
35
- "skills": [
36
- "./skills"
37
34
  ]
38
35
  },
39
36
  "files": [
@@ -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.