flavor-code 1.3.23 → 1.4.0-beta.3

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.
Files changed (156) hide show
  1. package/README.md +437 -434
  2. package/README.zh-CN.md +434 -431
  3. package/dist/agent/loop.d.ts +3 -0
  4. package/dist/{app-NTEUPJKJ.js → app-H7RYDMD3.js} +45 -157
  5. package/dist/{chunk-7OICVL2M.js → chunk-2BF7CVWZ.js} +0 -42
  6. package/dist/{chunk-VEUSROUQ.js → chunk-3BHKW5A7.js} +1 -1
  7. package/dist/{chunk-SUSLIHXO.js → chunk-IQAZ42TM.js} +1 -1
  8. package/dist/{chunk-RPFWB45Y.js → chunk-KBHWS7M6.js} +5 -5
  9. package/dist/{chunk-Z62P4LL7.js → chunk-NIKCPCJG.js} +9345 -8623
  10. package/dist/{chunk-RQTYHUMK.js → chunk-ZJCAQXA7.js} +17 -1
  11. package/dist/{claude-ink-6CEG2XZZ.js → claude-ink-ECZ6QF3P.js} +2 -3
  12. package/dist/cli-main.js +27 -11
  13. package/dist/config/load.d.ts +2 -0
  14. package/dist/desktop/main.js +1550 -816
  15. package/dist/desktop-renderer/assets/index-Bk6FYhyh.css +1 -0
  16. package/dist/desktop-renderer/assets/{index-D75ozXnZ.js → index-CYd5JkTR.js} +3 -3
  17. package/dist/desktop-renderer/assets/{interactive-terminal-CTFo4fK9.js → interactive-terminal-j52Ty3QO.js} +1 -1
  18. package/dist/desktop-renderer/index.html +2 -2
  19. package/dist/doctor.d.ts +38 -0
  20. package/dist/execution/docker.d.ts +5 -1
  21. package/dist/execution/types.d.ts +11 -0
  22. package/dist/git/service.d.ts +3 -3
  23. package/dist/git/tools.d.ts +1 -1
  24. package/dist/harness/local.d.ts +2 -0
  25. package/dist/init/project.d.ts +0 -6
  26. package/dist/jobs/registry.d.ts +2 -1
  27. package/dist/{load-4FWNXE6F.js → load-SLSL3IWR.js} +1 -1
  28. package/dist/sdk/index.js +4 -4
  29. package/dist/tools/lsp.d.ts +13 -10
  30. package/dist/tools/runtime.d.ts +2 -1
  31. package/dist/tools/search.d.ts +1 -0
  32. package/dist/tools/shell.d.ts +17 -12
  33. package/dist/tools/types.d.ts +2 -1
  34. package/dist/ui/commands.d.ts +1 -1
  35. package/dist/ui/session.d.ts +1 -0
  36. package/dist/update/check.d.ts +20 -0
  37. package/dist/utils/abort.d.ts +4 -0
  38. package/dist/utils/execFileNoThrow.d.ts +1 -0
  39. package/dist/utils/process-tree.d.ts +2 -0
  40. package/dist/utils/semver.d.ts +3 -0
  41. package/dist/utils/spawn-executable.d.ts +2 -0
  42. package/package.json +2 -2
  43. package//346/212/200/346/234/257/346/226/271/346/241/210/346/212/245/345/221/212.md +5848 -5848
  44. package/dist/astgraph/db.mjs +0 -237
  45. package/dist/astgraph/extract.mjs +0 -239
  46. package/dist/astgraph/flavor-plugin.json +0 -25
  47. package/dist/astgraph/grammars.mjs +0 -68
  48. package/dist/astgraph/index.js +0 -301
  49. package/dist/astgraph/indexer.mjs +0 -175
  50. package/dist/astgraph/query.mjs +0 -165
  51. package/dist/astgraph/resolve.mjs +0 -93
  52. package/dist/astgraph/vendor/tree-sitter-javascript.wasm +0 -0
  53. package/dist/astgraph/vendor/tree-sitter-tsx.wasm +0 -0
  54. package/dist/astgraph/vendor/tree-sitter-typescript.wasm +0 -0
  55. package/dist/astgraph/vendor/tree-sitter.js +0 -3980
  56. package/dist/astgraph/vendor/tree-sitter.wasm +0 -0
  57. package/dist/astgraph/vendor/zod/LICENSE +0 -21
  58. package/dist/astgraph/vendor/zod/index.js +0 -4
  59. package/dist/astgraph/vendor/zod/locales/index.js +0 -1
  60. package/dist/astgraph/vendor/zod/locales/package.json +0 -7
  61. package/dist/astgraph/vendor/zod/package.json +0 -135
  62. package/dist/astgraph/vendor/zod/v4/classic/checks.js +0 -1
  63. package/dist/astgraph/vendor/zod/v4/classic/coerce.js +0 -17
  64. package/dist/astgraph/vendor/zod/v4/classic/compat.js +0 -31
  65. package/dist/astgraph/vendor/zod/v4/classic/errors.js +0 -48
  66. package/dist/astgraph/vendor/zod/v4/classic/external.js +0 -20
  67. package/dist/astgraph/vendor/zod/v4/classic/from-json-schema.js +0 -599
  68. package/dist/astgraph/vendor/zod/v4/classic/index.js +0 -4
  69. package/dist/astgraph/vendor/zod/v4/classic/iso.js +0 -30
  70. package/dist/astgraph/vendor/zod/v4/classic/package.json +0 -7
  71. package/dist/astgraph/vendor/zod/v4/classic/parse.js +0 -15
  72. package/dist/astgraph/vendor/zod/v4/classic/schemas.js +0 -1395
  73. package/dist/astgraph/vendor/zod/v4/core/api.js +0 -1087
  74. package/dist/astgraph/vendor/zod/v4/core/checks.js +0 -575
  75. package/dist/astgraph/vendor/zod/v4/core/core.js +0 -78
  76. package/dist/astgraph/vendor/zod/v4/core/doc.js +0 -35
  77. package/dist/astgraph/vendor/zod/v4/core/errors.js +0 -185
  78. package/dist/astgraph/vendor/zod/v4/core/index.js +0 -16
  79. package/dist/astgraph/vendor/zod/v4/core/json-schema-generator.js +0 -95
  80. package/dist/astgraph/vendor/zod/v4/core/json-schema-processors.js +0 -601
  81. package/dist/astgraph/vendor/zod/v4/core/json-schema.js +0 -1
  82. package/dist/astgraph/vendor/zod/v4/core/package.json +0 -7
  83. package/dist/astgraph/vendor/zod/v4/core/parse.js +0 -93
  84. package/dist/astgraph/vendor/zod/v4/core/regexes.js +0 -139
  85. package/dist/astgraph/vendor/zod/v4/core/registries.js +0 -51
  86. package/dist/astgraph/vendor/zod/v4/core/schemas.js +0 -2239
  87. package/dist/astgraph/vendor/zod/v4/core/standard-schema.js +0 -1
  88. package/dist/astgraph/vendor/zod/v4/core/to-json-schema.js +0 -448
  89. package/dist/astgraph/vendor/zod/v4/core/util.js +0 -674
  90. package/dist/astgraph/vendor/zod/v4/core/versions.js +0 -5
  91. package/dist/astgraph/vendor/zod/v4/index.js +0 -3
  92. package/dist/astgraph/vendor/zod/v4/locales/ar.js +0 -106
  93. package/dist/astgraph/vendor/zod/v4/locales/az.js +0 -105
  94. package/dist/astgraph/vendor/zod/v4/locales/be.js +0 -156
  95. package/dist/astgraph/vendor/zod/v4/locales/bg.js +0 -120
  96. package/dist/astgraph/vendor/zod/v4/locales/ca.js +0 -107
  97. package/dist/astgraph/vendor/zod/v4/locales/cs.js +0 -111
  98. package/dist/astgraph/vendor/zod/v4/locales/da.js +0 -115
  99. package/dist/astgraph/vendor/zod/v4/locales/de.js +0 -108
  100. package/dist/astgraph/vendor/zod/v4/locales/el.js +0 -109
  101. package/dist/astgraph/vendor/zod/v4/locales/en.js +0 -113
  102. package/dist/astgraph/vendor/zod/v4/locales/eo.js +0 -109
  103. package/dist/astgraph/vendor/zod/v4/locales/es.js +0 -132
  104. package/dist/astgraph/vendor/zod/v4/locales/fa.js +0 -114
  105. package/dist/astgraph/vendor/zod/v4/locales/fi.js +0 -112
  106. package/dist/astgraph/vendor/zod/v4/locales/fr-CA.js +0 -107
  107. package/dist/astgraph/vendor/zod/v4/locales/fr.js +0 -125
  108. package/dist/astgraph/vendor/zod/v4/locales/he.js +0 -214
  109. package/dist/astgraph/vendor/zod/v4/locales/hr.js +0 -122
  110. package/dist/astgraph/vendor/zod/v4/locales/hu.js +0 -108
  111. package/dist/astgraph/vendor/zod/v4/locales/hy.js +0 -147
  112. package/dist/astgraph/vendor/zod/v4/locales/id.js +0 -106
  113. package/dist/astgraph/vendor/zod/v4/locales/index.js +0 -52
  114. package/dist/astgraph/vendor/zod/v4/locales/is.js +0 -109
  115. package/dist/astgraph/vendor/zod/v4/locales/it.js +0 -108
  116. package/dist/astgraph/vendor/zod/v4/locales/ja.js +0 -107
  117. package/dist/astgraph/vendor/zod/v4/locales/ka.js +0 -112
  118. package/dist/astgraph/vendor/zod/v4/locales/kh.js +0 -5
  119. package/dist/astgraph/vendor/zod/v4/locales/km.js +0 -110
  120. package/dist/astgraph/vendor/zod/v4/locales/ko.js +0 -111
  121. package/dist/astgraph/vendor/zod/v4/locales/lt.js +0 -203
  122. package/dist/astgraph/vendor/zod/v4/locales/mk.js +0 -109
  123. package/dist/astgraph/vendor/zod/v4/locales/ms.js +0 -107
  124. package/dist/astgraph/vendor/zod/v4/locales/nl.js +0 -110
  125. package/dist/astgraph/vendor/zod/v4/locales/no.js +0 -108
  126. package/dist/astgraph/vendor/zod/v4/locales/ota.js +0 -109
  127. package/dist/astgraph/vendor/zod/v4/locales/package.json +0 -7
  128. package/dist/astgraph/vendor/zod/v4/locales/pl.js +0 -109
  129. package/dist/astgraph/vendor/zod/v4/locales/ps.js +0 -114
  130. package/dist/astgraph/vendor/zod/v4/locales/pt.js +0 -108
  131. package/dist/astgraph/vendor/zod/v4/locales/ro.js +0 -119
  132. package/dist/astgraph/vendor/zod/v4/locales/ru.js +0 -156
  133. package/dist/astgraph/vendor/zod/v4/locales/sl.js +0 -109
  134. package/dist/astgraph/vendor/zod/v4/locales/sv.js +0 -110
  135. package/dist/astgraph/vendor/zod/v4/locales/ta.js +0 -110
  136. package/dist/astgraph/vendor/zod/v4/locales/th.js +0 -110
  137. package/dist/astgraph/vendor/zod/v4/locales/tr.js +0 -105
  138. package/dist/astgraph/vendor/zod/v4/locales/ua.js +0 -5
  139. package/dist/astgraph/vendor/zod/v4/locales/uk.js +0 -108
  140. package/dist/astgraph/vendor/zod/v4/locales/ur.js +0 -110
  141. package/dist/astgraph/vendor/zod/v4/locales/uz.js +0 -110
  142. package/dist/astgraph/vendor/zod/v4/locales/vi.js +0 -108
  143. package/dist/astgraph/vendor/zod/v4/locales/yo.js +0 -107
  144. package/dist/astgraph/vendor/zod/v4/locales/zh-CN.js +0 -109
  145. package/dist/astgraph/vendor/zod/v4/locales/zh-TW.js +0 -107
  146. package/dist/astgraph/vendor/zod/v4/mini/checks.js +0 -1
  147. package/dist/astgraph/vendor/zod/v4/mini/coerce.js +0 -22
  148. package/dist/astgraph/vendor/zod/v4/mini/external.js +0 -14
  149. package/dist/astgraph/vendor/zod/v4/mini/index.js +0 -3
  150. package/dist/astgraph/vendor/zod/v4/mini/iso.js +0 -34
  151. package/dist/astgraph/vendor/zod/v4/mini/package.json +0 -7
  152. package/dist/astgraph/vendor/zod/v4/mini/parse.js +0 -1
  153. package/dist/astgraph/vendor/zod/v4/mini/schemas.js +0 -961
  154. package/dist/astgraph/vendor/zod/v4/package.json +0 -7
  155. package/dist/chunk-OTYFL4AG.js +0 -16
  156. package/dist/desktop-renderer/assets/index-ZZsUx916.css +0 -1
@@ -1,301 +0,0 @@
1
- // astgraph flavor-code plugin — codegraph-style code graph for precise navigation.
2
- //
3
- // Registers:
4
- // command /ast init | sync | status | search | impact | callers | callees | context | help
5
- // tools ast_search / ast_callers / ast_callees / ast_impact / ast_context
6
- // hooks SessionStart (cache workspace), PostToolUse (incremental sync after edits)
7
- //
8
- // Heavy lifting is lazy: activation only registers handlers so it stays well
9
- // inside the host's activation timeout; WASM grammars and the database load on
10
- // first use.
11
-
12
- import { existsSync } from "node:fs";
13
- import { isAbsolute, join, relative } from "node:path";
14
-
15
- import { z } from "./vendor/zod/index.js";
16
-
17
- const ALLOW = Object.freeze({ decision: "allow" });
18
-
19
- function workspaceFrom(event) {
20
- const workspace = event?.payload?.workspace;
21
- if (typeof workspace === "string" && workspace.length > 0) return workspace;
22
- return undefined;
23
- }
24
-
25
- function dbPath(root) {
26
- return join(root, ".flavor", "astgraph", "index.db");
27
- }
28
-
29
- async function mod(name) {
30
- return import(new URL(`./${name}`, import.meta.url).href);
31
- }
32
-
33
- /** Open the graph database when it exists; otherwise undefined (not indexed yet). */
34
- async function openIndex(root) {
35
- const path = dbPath(root);
36
- if (!existsSync(path)) return undefined;
37
- const { openDb } = await mod("db.mjs");
38
- return { db: openDb(path), path };
39
- }
40
-
41
- function workspaceRelative(root, path) {
42
- if (path === undefined) return undefined;
43
- const candidate = isAbsolute(path) ? relative(root, path) : path;
44
- return candidate.split("\\").join("/").replace(/^\.\//, "");
45
- }
46
-
47
- async function runIndex(root, options = {}) {
48
- const { openDb } = await mod("db.mjs");
49
- const { indexProject } = await mod("indexer.mjs");
50
- const db = openDb(dbPath(root));
51
- try {
52
- return await indexProject(root, { db, ...options });
53
- } finally {
54
- db.close();
55
- }
56
- }
57
-
58
- const HELP = {
59
- usage: [
60
- "/ast init Build the full code graph (.flavor/astgraph/index.db)",
61
- "/ast sync [path...] Incrementally re-index (defaults to changed files only)",
62
- "/ast status Show graph statistics",
63
- "/ast search <query> Find anchor symbols (FTS + identifier segments)",
64
- "/ast callers <node-id> Who calls this node",
65
- "/ast callees <node-id> What this node calls",
66
- "/ast impact <node-id> [--hops N] [--direction up|down|both] Blast radius",
67
- "/ast context <node-id> [--hops N] Precise file:line read ranges around a node",
68
- ],
69
- hint: "Node ids look like 'src/order.ts#cancelOrder'. Agent tools: ast_search, ast_callers, ast_callees, ast_impact, ast_context.",
70
- };
71
-
72
- async function commandAst(args, context) {
73
- const root = context.workspace;
74
- const [sub, ...rest] = args;
75
- switch (sub) {
76
- case undefined:
77
- case "help":
78
- return HELP;
79
- case "init": {
80
- const result = await runIndex(root);
81
- return { command: "init", workspace: root, db: dbPath(root), ...result };
82
- }
83
- case "sync": {
84
- const onlyPaths = rest.map((path) => workspaceRelative(root, path)).filter((path) => path !== undefined);
85
- const result = await runIndex(root, onlyPaths.length > 0 ? { onlyPaths } : {});
86
- return { command: "sync", ...result };
87
- }
88
- case "status": {
89
- const index = await openIndex(root);
90
- if (index === undefined) return { command: "status", indexed: false, hint: "Run /ast init first." };
91
- try {
92
- const { stats, getMetadata } = await mod("db.mjs");
93
- const lastIndex = getMetadata(index.db, "last_index");
94
- return { command: "status", indexed: true, db: index.path, ...stats(index.db), lastIndex: lastIndex === undefined ? undefined : JSON.parse(lastIndex) };
95
- } finally {
96
- index.db.close();
97
- }
98
- }
99
- default: {
100
- const nodeId = rest[0];
101
- if (["search", "callers", "callees", "impact", "context"].includes(sub) && (sub === "search" ? rest.length === 0 : nodeId === undefined)) {
102
- return { command: sub, error: `Missing ${sub === "search" ? "query" : "node id"}. See /ast help.` };
103
- }
104
- const index = await openIndex(root);
105
- if (index === undefined) return { command: sub, error: "Graph not built. Run /ast init first." };
106
- try {
107
- const { search, callers, callees, impact, subgraphContext, getNode } = await mod("query.mjs");
108
- if (sub === "search") return { command: sub, query: rest.join(" "), results: search(index.db, rest.join(" ")) };
109
- const anchor = getNode(index.db, nodeId);
110
- if (anchor === undefined) return { command: sub, error: `Unknown node id "${nodeId}". Use /ast search to find anchors.` };
111
- if (sub === "callers") return { command: sub, node: anchor, callers: callers(index.db, nodeId) };
112
- if (sub === "callees") return { command: sub, node: anchor, callees: callees(index.db, nodeId) };
113
- const hops = Math.min(5, Math.max(1, parseFlag(rest, "--hops", 2)));
114
- const direction = parseStringFlag(rest, "--direction", "up");
115
- if (sub === "impact") return { command: sub, ...impact(index.db, nodeId, { hops, direction: ["up", "down", "both"].includes(direction) ? direction : "up" }) };
116
- return { command: "context", ...subgraphContext(index.db, nodeId, { hops }) };
117
- } finally {
118
- index.db.close();
119
- }
120
- }
121
- }
122
- }
123
-
124
- function parseFlag(args, name, fallback) {
125
- const index = args.indexOf(name);
126
- if (index < 0) return fallback;
127
- const value = Number(args[index + 1]);
128
- return Number.isFinite(value) ? value : fallback;
129
- }
130
-
131
- function parseStringFlag(args, name, fallback) {
132
- const index = args.indexOf(name);
133
- return index < 0 ? fallback : args[index + 1] ?? fallback;
134
- }
135
-
136
- // Numeric fields use z.coerce so providers that serialize numbers as JSON
137
- // strings ("10" instead of 10) still validate without a repair round-trip.
138
- const boundedInt = (min, max) => z.coerce.number().int().min(min).max(max).optional();
139
-
140
- function toolSchemas() {
141
- const nodeInput = z.object({
142
- id: z.string().describe("Node id, e.g. 'src/order.ts#cancelOrder' (find with ast_search)"),
143
- });
144
- return {
145
- ast_search: z.object({
146
- query: z.string().describe("Natural-language or symbol keywords, e.g. '订单 取消' or 'cancelOrder'"),
147
- limit: boundedInt(1, 50).describe("Max results (default 10)"),
148
- }),
149
- ast_callers: nodeInput,
150
- ast_callees: nodeInput,
151
- ast_impact: z.object({
152
- id: z.string().describe("Node id, e.g. 'src/order.ts#cancelOrder'"),
153
- hops: boundedInt(1, 5).describe("Traversal depth (default 2)"),
154
- direction: z.enum(["up", "down", "both"]).optional().describe("up=who depends on me, down=what I depend on (default up)"),
155
- }),
156
- ast_context: z.object({
157
- id: z.string().describe("Node id, e.g. 'src/order.ts#cancelOrder'"),
158
- hops: boundedInt(1, 3).describe("Subgraph depth (default 1)"),
159
- }),
160
- };
161
- }
162
-
163
- function createTools(rootRef) {
164
- const schemas = toolSchemas();
165
- const notIndexed = { ok: false, error: "astgraph index not built. Ask the user to run /ast init." };
166
-
167
- const withDb = async (fn) => {
168
- const root = rootRef();
169
- const index = await openIndex(root);
170
- if (index === undefined) return notIndexed;
171
- try {
172
- return await fn(index.db, root);
173
- } finally {
174
- index.db.close();
175
- }
176
- };
177
-
178
- return [
179
- {
180
- name: "ast_search",
181
- description: "Search the code graph for anchor symbols by keyword (full-text + identifier segments). Use before grep/read when locating where a change belongs.",
182
- inputSchema: schemas.ast_search,
183
- modelInputSchema: undefined,
184
- readOnly: true,
185
- paths: () => [],
186
- summarize: (input) => input.query,
187
- execute: async (input) => withDb(async (db) => {
188
- const { search } = await mod("query.mjs");
189
- return { results: search(db, input.query, { limit: input.limit ?? 10 }) };
190
- }),
191
- },
192
- {
193
- name: "ast_callers",
194
- description: "List the functions/classes that call or import a node in the code graph (upward dependencies).",
195
- inputSchema: schemas.ast_callers,
196
- readOnly: true,
197
- paths: () => [],
198
- summarize: (input) => input.id,
199
- execute: async (input) => withDb(async (db) => {
200
- const { callers, getNode } = await mod("query.mjs");
201
- const node = getNode(db, input.id);
202
- return node === undefined ? { error: `Unknown node id "${input.id}"` } : { node, callers: callers(db, input.id) };
203
- }),
204
- },
205
- {
206
- name: "ast_callees",
207
- description: "List the functions a node calls or imports (downward dependencies).",
208
- inputSchema: schemas.ast_callees,
209
- readOnly: true,
210
- paths: () => [],
211
- summarize: (input) => input.id,
212
- execute: async (input) => withDb(async (db) => {
213
- const { callees, getNode } = await mod("query.mjs");
214
- const node = getNode(db, input.id);
215
- return node === undefined ? { error: `Unknown node id "${input.id}"` } : { node, callees: callees(db, input.id) };
216
- }),
217
- },
218
- {
219
- name: "ast_impact",
220
- description: "Compute the K-hop blast radius of changing a node: who depends on it (up) or what it depends on (down). Use to scope a modification safely.",
221
- inputSchema: schemas.ast_impact,
222
- readOnly: true,
223
- paths: () => [],
224
- summarize: (input) => `${input.id} ${input.direction ?? "up"}x${input.hops ?? 2}`,
225
- execute: async (input) => withDb(async (db) => {
226
- const { impact, getNode } = await mod("query.mjs");
227
- if (getNode(db, input.id) === undefined) return { error: `Unknown node id "${input.id}"` };
228
- return impact(db, input.id, { hops: input.hops ?? 2, direction: input.direction ?? "up" });
229
- }),
230
- },
231
- {
232
- name: "ast_context",
233
- description: "Assemble the precise subgraph around a node: file paths and line ranges of the anchor, its callers and callees. Read only these ranges instead of grepping.",
234
- inputSchema: schemas.ast_context,
235
- readOnly: true,
236
- paths: () => [],
237
- summarize: (input) => input.id,
238
- execute: async (input) => withDb(async (db) => {
239
- const { subgraphContext } = await mod("query.mjs");
240
- return subgraphContext(db, input.id, { hops: input.hops ?? 1 });
241
- }),
242
- },
243
- ];
244
- }
245
-
246
- /** Extract workspace-relative file paths from a PostToolUse event's tool input. */
247
- function changedPaths(event, root) {
248
- const payload = event?.payload;
249
- if (payload === undefined) return [];
250
- const input = payload.input ?? {};
251
- const tool = payload.tool;
252
- const paths = [];
253
- if (tool === "Edit" || tool === "Write") {
254
- if (typeof input.path === "string") paths.push(input.path);
255
- } else if (tool === "ApplyPatch" && typeof input.patch === "string") {
256
- for (const line of input.patch.split("\n")) {
257
- if (!line.startsWith("+++ ")) continue;
258
- const target = line.slice(4).trim().replace(/^b\//, "");
259
- if (target !== "/dev/null") paths.push(target);
260
- }
261
- }
262
- return paths
263
- .map((path) => workspaceRelative(root, path))
264
- .filter((path) => path !== undefined && /\.(ts|tsx|js|jsx|mjs|cjs|mts|cts)$/.test(path));
265
- }
266
-
267
- export function activate(context) {
268
- // Per-plugin-instance workspace cache, populated by SessionStart; falls back
269
- // to the host's command context workspace or the process cwd.
270
- let workspaceRoot;
271
- const rootRef = () => workspaceRoot ?? process.cwd();
272
-
273
- context.registerCommand("ast", commandAst, "Build and query the code AST graph");
274
-
275
- const disposers = [];
276
- for (const tool of createTools(rootRef)) disposers.push(context.registerTool(tool.name, tool));
277
-
278
- disposers.push(context.registerHook("SessionStart", (event) => {
279
- workspaceRoot = workspaceFrom(event) ?? workspaceRoot;
280
- return ALLOW;
281
- }, { failurePolicy: "allow" }));
282
-
283
- // Incremental sync after file-mutating tools. Fire-and-forget semantics:
284
- // never block or fail the agent's edit.
285
- let syncing = Promise.resolve();
286
- disposers.push(context.registerHook("PostToolUse", (event) => {
287
- const root = rootRef();
288
- const paths = changedPaths(event, root);
289
- if (paths.length === 0) return ALLOW;
290
- syncing = syncing
291
- .then(() => runIndex(root, { onlyPaths: paths }))
292
- .catch((error) => context.logger.debug(`astgraph sync skipped: ${error?.message ?? error}`));
293
- return ALLOW;
294
- }, { failurePolicy: "allow", timeoutMs: 10_000 }));
295
-
296
- return async () => {
297
- for (const dispose of disposers.reverse()) {
298
- try { await dispose(); } catch { /* ignore */ }
299
- }
300
- };
301
- }
@@ -1,175 +0,0 @@
1
- // astgraph indexer — full and incremental project indexing.
2
- // Walks the workspace, extracts symbols per file (content-hash incremental),
3
- // then resolves cross-file references into graph edges.
4
-
5
- import { createHash } from "node:crypto";
6
- import { readdirSync, readFileSync, statSync } from "node:fs";
7
- import { relative, sep } from "node:path";
8
-
9
- import {
10
- deleteEdgesForFile,
11
- deleteFileRecord,
12
- deleteUnresolvedRefsForFile,
13
- getFileRecord,
14
- insertEdge,
15
- insertUnresolvedRef,
16
- replaceNodes,
17
- setMetadata,
18
- upsertFileRecord,
19
- } from "./db.mjs";
20
- import { extract } from "./extract.mjs";
21
- import { languageForFile, SUPPORTED_LANGUAGES } from "./grammars.mjs";
22
- import { resolveImportPath, resolveRefs } from "./resolve.mjs";
23
-
24
- /** Directory names never indexed, regardless of depth. */
25
- const EXCLUDED_DIRS = new Set([
26
- "node_modules", "dist", "build", "out", "coverage", "release", ".git",
27
- ".flavor", ".claude", ".worktrees", ".cache", ".idea", ".vscode", "vendor",
28
- ]);
29
-
30
- function toPosix(path) {
31
- return path.split(sep).join("/");
32
- }
33
-
34
- /** Walk the workspace and return code files as workspace-relative posix paths. */
35
- export function listCodeFiles(workspace) {
36
- const files = [];
37
- const walk = (dir) => {
38
- let entries;
39
- try { entries = readdirSync(dir, { withFileTypes: true }); }
40
- catch { return; }
41
- for (const entry of entries) {
42
- const full = `${dir}/${entry.name}`;
43
- if (entry.isDirectory()) {
44
- if (!EXCLUDED_DIRS.has(entry.name)) walk(full);
45
- } else if (entry.isFile() && languageForFile(entry.name) !== undefined) {
46
- files.push(toPosix(relative(workspace, full)));
47
- }
48
- }
49
- };
50
- walk(workspace);
51
- return files.sort();
52
- }
53
-
54
- /** SHA-256 content hash used for incremental detection. */
55
- export function contentHash(content) {
56
- return createHash("sha256").update(content).digest("hex");
57
- }
58
-
59
- async function indexOneFile(db, workspace, relativePath) {
60
- const content = readFileSync(`${workspace}/${relativePath}`, "utf8");
61
- const language = languageForFile(relativePath);
62
- const { nodes, edges, refs } = await extract(content, relativePath, language);
63
-
64
- deleteEdgesForFile(db, relativePath);
65
- deleteUnresolvedRefsForFile(db, relativePath);
66
- replaceNodes(db, relativePath, nodes);
67
- for (const edge of edges) insertEdge(db, edge);
68
- for (const ref of refs) {
69
- insertUnresolvedRef(db, {
70
- fromNodeId: ref.fromNodeId, referenceName: ref.referenceName,
71
- referenceKind: ref.referenceKind, line: ref.line, col: ref.col,
72
- filePath: ref.filePath, moduleSpecifier: ref.moduleSpecifier,
73
- });
74
- }
75
- let size;
76
- try { size = statSync(`${workspace}/${relativePath}`).size; } catch { size = content.length; }
77
- upsertFileRecord(db, {
78
- path: relativePath, contentHash: contentHash(content), language, size, nodeCount: nodes.length,
79
- });
80
- return { nodeCount: nodes.length };
81
- }
82
-
83
- /** Resolve every pending unresolved_ref whose module specifier points at an indexed file. */
84
- function resolvePass(db, workspace) {
85
- const rows = db.prepare(`
86
- SELECT id, from_node_id, reference_name, reference_kind, line, col, file_path, module_specifier
87
- FROM unresolved_refs WHERE status = 'pending' AND module_specifier IS NOT NULL
88
- `).all();
89
- if (rows.length === 0) return 0;
90
-
91
- const nodesByFile = new Map();
92
- for (const file of db.prepare("SELECT DISTINCT file_path FROM nodes").all()) {
93
- nodesByFile.set(file.file_path, db.prepare(
94
- "SELECT id, name, is_exported FROM nodes WHERE file_path = ?",
95
- ).all(file.file_path).map((row) => ({ id: row.id, name: row.name, isExported: row.is_exported === 1 })));
96
- }
97
- const exists = (path) => {
98
- try { statSync(`${workspace}/${path}`); return true; } catch { return false; }
99
- };
100
-
101
- const refs = rows.map((row) => ({
102
- id: row.id, fromNodeId: row.from_node_id, referenceName: row.reference_name,
103
- referenceKind: row.reference_kind, line: row.line, col: row.col,
104
- filePath: row.file_path, moduleSpecifier: row.module_specifier,
105
- }));
106
- // Import statements live outside any function, so their refs carry no from-node.
107
- // Attribute them to a node that actually uses the binding (same file + name);
108
- // unused imports resolve silently without an edge.
109
- for (const ref of refs) {
110
- if (ref.fromNodeId !== null || ref.referenceKind !== "import") continue;
111
- const user = refs.find((other) => other.referenceKind !== "import"
112
- && other.referenceName === ref.referenceName
113
- && other.filePath === ref.filePath
114
- && other.fromNodeId !== null);
115
- ref.fromNodeId = user?.fromNodeId ?? null;
116
- }
117
- const { edges, resolvedIds } = resolveRefs(refs.filter((ref) => ref.fromNodeId !== null), nodesByFile, exists);
118
- for (const edge of edges) insertEdge(db, edge);
119
- if (resolvedIds.length > 0) {
120
- db.exec("BEGIN");
121
- try {
122
- const mark = db.prepare("DELETE FROM unresolved_refs WHERE id = ?");
123
- for (const id of resolvedIds) mark.run(id);
124
- db.exec("COMMIT");
125
- } catch (error) { db.exec("ROLLBACK"); throw error; }
126
- }
127
- return resolvedIds.length;
128
- }
129
-
130
- /**
131
- * Index (or re-index) a workspace into the graph database.
132
- *
133
- * Options:
134
- * onlyPaths — restrict the pass to these workspace-relative paths (hook-driven sync).
135
- * Disappeared files are still pruned; everything else is left untouched.
136
- * Returns { files, indexed, skipped, removed, resolved }.
137
- */
138
- export async function indexProject(workspace, { db, onlyPaths } = {}) {
139
- const restrict = onlyPaths === undefined ? undefined : new Set(onlyPaths.map(toPosix));
140
- const diskFiles = listCodeFiles(workspace).filter((path) => restrict === undefined || restrict.has(path));
141
-
142
- let indexed = 0;
143
- let skipped = 0;
144
- for (const path of diskFiles) {
145
- const current = readFileSync(`${workspace}/${path}`, "utf8");
146
- const hash = contentHash(current);
147
- const record = getFileRecord(db, path);
148
- if (record !== undefined && record.contentHash === hash) { skipped += 1; continue; }
149
- await indexOneFile(db, workspace, path);
150
- indexed += 1;
151
- }
152
-
153
- // Prune files that no longer exist on disk.
154
- let removed = 0;
155
- const known = db.prepare("SELECT path FROM files").all();
156
- const diskSet = new Set(diskFiles);
157
- for (const row of known) {
158
- if (restrict !== undefined && !restrict.has(row.path)) continue;
159
- if (!diskSet.has(row.path)) {
160
- deleteEdgesForFile(db, row.path);
161
- deleteUnresolvedRefsForFile(db, row.path);
162
- replaceNodes(db, row.path, []);
163
- deleteFileRecord(db, row.path);
164
- removed += 1;
165
- }
166
- }
167
-
168
- const resolved = resolvePass(db, workspace);
169
- setMetadata(db, "last_index", JSON.stringify({ at: Date.now(), files: diskFiles.length, indexed, removed }));
170
-
171
- return { files: diskFiles.length, indexed, skipped, removed, resolved };
172
- }
173
-
174
- /** Exposed for diagnostics. */
175
- export const INDEXER_LANGUAGES = SUPPORTED_LANGUAGES;
@@ -1,165 +0,0 @@
1
- // astgraph query layer — anchor search, K-hop traversal, blast radius and
2
- // subgraph context assembly. All coordinates are 1-based to match Read/editor use.
3
-
4
- const NODE_FIELDS = "id, kind, name, qualified_name, file_path, language, start_line, end_line, signature, docstring, is_exported, is_async";
5
-
6
- function mapNode(row) {
7
- if (row === undefined) return undefined;
8
- return {
9
- id: row.id, kind: row.kind, name: row.name, qualifiedName: row.qualified_name,
10
- filePath: row.file_path, language: row.language,
11
- startLine: row.start_line, endLine: row.end_line,
12
- signature: row.signature ?? undefined, docstring: row.docstring ?? undefined,
13
- isExported: row.is_exported === 1, isAsync: row.is_async === 1,
14
- };
15
- }
16
-
17
- /** Fetch one node by id, or undefined. */
18
- export function getNode(db, id) {
19
- return mapNode(db.prepare(`SELECT ${NODE_FIELDS} FROM nodes WHERE id = ?`).get(id));
20
- }
21
-
22
- /** Split camelCase/PascalCase/snake_case identifiers into lowercase word segments. */
23
- export function identifierSegments(name) {
24
- return name
25
- .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
26
- .split(/[^A-Za-z0-9]+/)
27
- .filter(Boolean)
28
- .map((segment) => segment.toLowerCase());
29
- }
30
-
31
- function queryWords(query) {
32
- return query
33
- .toLowerCase()
34
- .split(/[^a-z0-9]+/)
35
- .filter((word) => word.length > 0);
36
- }
37
-
38
- /**
39
- * Anchor search: FTS5 first (prefix-matched terms), then identifier-segment
40
- * matching so natural-language words ("order cancel") hit camelCase symbols.
41
- * Returns scored node records, best first.
42
- */
43
- export function search(db, query, { limit = 20 } = {}) {
44
- const words = queryWords(query);
45
- if (words.length === 0) return [];
46
-
47
- const scored = new Map();
48
-
49
- // FTS pass — each query word as a prefix term.
50
- try {
51
- const match = words.map((word) => `${word}*`).join(" ");
52
- const rows = db.prepare(`
53
- SELECT n.${NODE_FIELDS.split(", ").join(", n.")}, rank
54
- FROM nodes_fts
55
- JOIN nodes n ON n.rowid = nodes_fts.rowid
56
- WHERE nodes_fts MATCH ?
57
- ORDER BY rank LIMIT ?
58
- `).all(match, limit * 2);
59
- for (const row of rows) scored.set(row.id, { node: mapNode(row), score: 100 - Math.min(50, Math.max(0, row.rank)) });
60
- } catch { /* Invalid MATCH syntax falls through to segment matching. */ }
61
-
62
- // Segment pass — words of the query appear as camelCase segments of node names.
63
- const candidates = db.prepare(`SELECT ${NODE_FIELDS} FROM nodes`).all();
64
- for (const row of candidates) {
65
- const segments = identifierSegments(row.name).concat(identifierSegments(row.qualified_name));
66
- const matched = words.filter((word) => segments.some((segment) => segment === word || segment.startsWith(word)));
67
- if (matched.length === 0) continue;
68
- const score = matched.length * 25 + (matched.length === words.length ? 20 : 0);
69
- const existing = scored.get(row.id);
70
- if (existing === undefined || existing.score < score) {
71
- scored.set(row.id, { node: mapNode(row), score });
72
- }
73
- }
74
-
75
- return [...scored.values()]
76
- .sort((a, b) => b.score - a.score)
77
- .slice(0, limit)
78
- .map((entry) => entry.node);
79
- }
80
-
81
- /** Nodes that call the target (reverse call edges). */
82
- export function callers(db, id) {
83
- return db.prepare(`
84
- SELECT DISTINCT n.${NODE_FIELDS.split(", ").join(", n.")}
85
- FROM edges e JOIN nodes n ON n.id = e.source
86
- WHERE e.target = ? AND e.kind IN ('calls', 'imports')
87
- `).all(id).map(mapNode);
88
- }
89
-
90
- /** Nodes the target calls (forward call edges). */
91
- export function callees(db, id) {
92
- return db.prepare(`
93
- SELECT DISTINCT n.${NODE_FIELDS.split(", ").join(", n.")}
94
- FROM edges e JOIN nodes n ON n.id = e.target
95
- WHERE e.source = ? AND e.kind IN ('calls', 'imports')
96
- `).all(id).map(mapNode);
97
- }
98
-
99
- /**
100
- * K-hop blast radius from a node.
101
- * direction "up" — who depends on me (callers chain)
102
- * direction "down" — what I depend on (callees chain)
103
- * direction "both" — union
104
- */
105
- export function impact(db, id, { hops = 2, direction = "up", limit = 200 } = {}) {
106
- const visited = new Map();
107
- const frontier = [id];
108
- for (let hop = 1; hop <= hops && frontier.length > 0; hop += 1) {
109
- const next = [];
110
- for (const current of frontier) {
111
- let rows = [];
112
- if (direction === "up" || direction === "both") {
113
- rows = rows.concat(db.prepare("SELECT source AS other FROM edges WHERE target = ?").all(current));
114
- }
115
- if (direction === "down" || direction === "both") {
116
- rows = rows.concat(db.prepare("SELECT target AS other FROM edges WHERE source = ?").all(current));
117
- }
118
- for (const row of rows) {
119
- if (row.other === id || visited.has(row.other)) continue;
120
- visited.set(row.other, hop);
121
- next.push(row.other);
122
- if (visited.size >= limit) break;
123
- }
124
- if (visited.size >= limit) break;
125
- }
126
- frontier.length = 0;
127
- frontier.push(...next);
128
- }
129
- const nodes = [...visited.entries()]
130
- .map(([nodeId, hop]) => ({ ...getNode(db, nodeId), hop }))
131
- .filter((node) => node.name !== undefined)
132
- .sort((a, b) => a.hop - b.hop);
133
- return { origin: getNode(db, id), nodes, hops };
134
- }
135
-
136
- /**
137
- * Subgraph context assembly: the anchor plus its K-hop callers and callees,
138
- * rendered as precise file:start-end read ranges for the agent.
139
- */
140
- export function subgraphContext(db, id, { hops = 1, limit = 50 } = {}) {
141
- const origin = getNode(db, id);
142
- if (origin === undefined) return { anchor: undefined, context: [] };
143
-
144
- const result = impact(db, id, { hops, direction: "both", limit });
145
- const seen = new Map([[origin.filePath, origin]]);
146
- const entries = [origin, ...result.nodes];
147
- for (const node of entries) {
148
- const existing = seen.get(node.filePath);
149
- if (existing === undefined || node.startLine < existing.startLine) {
150
- // Prefer the widest node per file only when ranges are identical; otherwise
151
- // keep each node individually below.
152
- seen.set(node.filePath, node);
153
- }
154
- }
155
-
156
- const context = entries
157
- .map((node) => ({
158
- nodeId: node.id, name: node.name, kind: node.kind,
159
- filePath: node.filePath, startLine: node.startLine, endLine: node.endLine,
160
- signature: node.signature, docstring: node.docstring,
161
- }))
162
- .sort((a, b) => a.filePath.localeCompare(b.filePath) || a.startLine - b.startLine);
163
-
164
- return { anchor: origin, context };
165
- }