cgb-builder 1.0.0

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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +369 -0
  3. package/dist/bundle/generator.d.ts +51 -0
  4. package/dist/bundle/generator.d.ts.map +1 -0
  5. package/dist/bundle/generator.js +291 -0
  6. package/dist/bundle/generator.js.map +1 -0
  7. package/dist/cli/index.d.ts +7 -0
  8. package/dist/cli/index.d.ts.map +1 -0
  9. package/dist/cli/index.js +388 -0
  10. package/dist/cli/index.js.map +1 -0
  11. package/dist/graph/db.d.ts +43 -0
  12. package/dist/graph/db.d.ts.map +1 -0
  13. package/dist/graph/db.js +321 -0
  14. package/dist/graph/db.js.map +1 -0
  15. package/dist/graph/engine.d.ts +62 -0
  16. package/dist/graph/engine.d.ts.map +1 -0
  17. package/dist/graph/engine.js +246 -0
  18. package/dist/graph/engine.js.map +1 -0
  19. package/dist/index.d.ts +13 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +22 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/mcp/server.d.ts +17 -0
  24. package/dist/mcp/server.d.ts.map +1 -0
  25. package/dist/mcp/server.js +458 -0
  26. package/dist/mcp/server.js.map +1 -0
  27. package/dist/parser/adapter.d.ts +10 -0
  28. package/dist/parser/adapter.d.ts.map +1 -0
  29. package/dist/parser/adapter.js +6 -0
  30. package/dist/parser/adapter.js.map +1 -0
  31. package/dist/parser/adapters/csharp.d.ts +24 -0
  32. package/dist/parser/adapters/csharp.d.ts.map +1 -0
  33. package/dist/parser/adapters/csharp.js +318 -0
  34. package/dist/parser/adapters/csharp.js.map +1 -0
  35. package/dist/parser/adapters/go.d.ts +21 -0
  36. package/dist/parser/adapters/go.d.ts.map +1 -0
  37. package/dist/parser/adapters/go.js +186 -0
  38. package/dist/parser/adapters/go.js.map +1 -0
  39. package/dist/parser/adapters/java.d.ts +22 -0
  40. package/dist/parser/adapters/java.d.ts.map +1 -0
  41. package/dist/parser/adapters/java.js +235 -0
  42. package/dist/parser/adapters/java.js.map +1 -0
  43. package/dist/parser/adapters/python.d.ts +19 -0
  44. package/dist/parser/adapters/python.d.ts.map +1 -0
  45. package/dist/parser/adapters/python.js +201 -0
  46. package/dist/parser/adapters/python.js.map +1 -0
  47. package/dist/parser/adapters/typescript.d.ts +24 -0
  48. package/dist/parser/adapters/typescript.d.ts.map +1 -0
  49. package/dist/parser/adapters/typescript.js +349 -0
  50. package/dist/parser/adapters/typescript.js.map +1 -0
  51. package/dist/parser/index.d.ts +42 -0
  52. package/dist/parser/index.d.ts.map +1 -0
  53. package/dist/parser/index.js +191 -0
  54. package/dist/parser/index.js.map +1 -0
  55. package/dist/parser/tree-sitter-engine.d.ts +25 -0
  56. package/dist/parser/tree-sitter-engine.d.ts.map +1 -0
  57. package/dist/parser/tree-sitter-engine.js +107 -0
  58. package/dist/parser/tree-sitter-engine.js.map +1 -0
  59. package/dist/parser/utils.d.ts +19 -0
  60. package/dist/parser/utils.d.ts.map +1 -0
  61. package/dist/parser/utils.js +111 -0
  62. package/dist/parser/utils.js.map +1 -0
  63. package/dist/types.d.ts +93 -0
  64. package/dist/types.d.ts.map +1 -0
  65. package/dist/types.js +16 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/watcher/index.d.ts +36 -0
  68. package/dist/watcher/index.d.ts.map +1 -0
  69. package/dist/watcher/index.js +139 -0
  70. package/dist/watcher/index.js.map +1 -0
  71. package/package.json +81 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 VxLabs
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 ADDED
@@ -0,0 +1,369 @@
1
+ # cgb-builder
2
+
3
+ **Automated polyglot code graph builder for AI-ready context bundles.**
4
+
5
+ `cgb-builder` scans your codebase, builds a persistent dependency/call/inheritance graph, and generates compact Markdown context bundles (1 000–5 000 tokens) that give AI coding assistants exactly the structural context they need — instead of dumping entire files.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/cgb-builder.svg)](https://www.npmjs.com/package/cgb-builder)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+ [![Node.js >= 20](https://img.shields.io/node/v/cgb-builder)](https://nodejs.org)
10
+
11
+ ---
12
+
13
+ ## Why?
14
+
15
+ AI coding assistants (Cursor, Claude Code, GitHub Copilot) spend enormous context budgets loading whole files. A large project can burn 50–100 K tokens per session just on file reads, most of which is irrelevant.
16
+
17
+ `cgb` answers structural questions instantly:
18
+
19
+ - What does `UserService` import?
20
+ - If I change `auth/middleware.ts`, which files break?
21
+ - How does `StripeWebhook` transitively depend on `DatabasePool`?
22
+ - Generate a compact bundle of everything touching `PaymentService` for my AI agent.
23
+
24
+ ---
25
+
26
+ ## Supported Languages
27
+
28
+ | Language | Parser |
29
+ |------------|----------------------------|
30
+ | TypeScript | Tree-sitter (WASM) |
31
+ | JavaScript | Tree-sitter (WASM) |
32
+ | Python | Tree-sitter (WASM) |
33
+ | C# | Tree-sitter (WASM) |
34
+ | Java | Tree-sitter (WASM) |
35
+ | Go | Tree-sitter (WASM) |
36
+
37
+ No native compilation required — runs on any OS.
38
+
39
+ ---
40
+
41
+ ## Installation
42
+
43
+ ### Global CLI
44
+
45
+ ```bash
46
+ npm install -g cgb-builder
47
+ ```
48
+
49
+ ### Project dependency (API usage)
50
+
51
+ ```bash
52
+ npm install cgb-builder
53
+ ```
54
+
55
+ ### npx (no install)
56
+
57
+ ```bash
58
+ npx cgb-builder init
59
+ ```
60
+
61
+ ---
62
+
63
+ ## CLI Quick Start
64
+
65
+ ```bash
66
+ # 1. Build the graph for your project
67
+ cgb init
68
+
69
+ # 2. See what a file imports (direct + transitive)
70
+ cgb deps src/services/UserService.ts
71
+
72
+ # 3. Impact analysis — what breaks if this file changes?
73
+ cgb impact src/db/connection.ts
74
+
75
+ # 4. Generate an AI context bundle (~2 000 tokens)
76
+ cgb bundle src/api/payments.ts
77
+
78
+ # 5. Find shortest dependency path between two files
79
+ cgb path src/routes/checkout.ts src/db/pool.ts
80
+
81
+ # 6. Search for any class, function, or file
82
+ cgb search "PaymentService"
83
+
84
+ # 7. Watch for file changes and keep the graph up to date
85
+ cgb watch
86
+ ```
87
+
88
+ ---
89
+
90
+ ## CLI Reference
91
+
92
+ ### `cgb init`
93
+
94
+ Scan all source files and build the initial graph. Run this once before any other command.
95
+
96
+ ```
97
+ cgb init [options]
98
+
99
+ Options:
100
+ -r, --root <path> Project root directory (default: cwd)
101
+ -f, --force Force re-parse all files even if unchanged
102
+ --watch Keep watching for file changes after initial scan
103
+ ```
104
+
105
+ ### `cgb deps <target>`
106
+
107
+ Show what a file depends on (direct and transitive).
108
+
109
+ ```
110
+ cgb deps src/services/auth.ts [options]
111
+
112
+ Options:
113
+ -r, --root <path> Project root directory
114
+ -d, --depth <n> Traversal depth for transitive deps (default: 3)
115
+ --json Output as JSON
116
+ ```
117
+
118
+ ### `cgb impact <target>`
119
+
120
+ Show which files would be affected if the given file changes.
121
+
122
+ ```
123
+ cgb impact src/db/pool.ts [options]
124
+
125
+ Options:
126
+ -r, --root <path> Project root directory
127
+ -d, --depth <n> Maximum traversal depth (default: 10)
128
+ --json Output as JSON
129
+ ```
130
+
131
+ ### `cgb bundle <target>`
132
+
133
+ Generate an AI-optimised context bundle (Markdown) for a file. Contains: summary, direct deps, reverse deps, class hierarchy, and optionally the full source.
134
+
135
+ ```
136
+ cgb bundle src/services/payments.ts [options]
137
+
138
+ Options:
139
+ -r, --root <path> Project root directory
140
+ -d, --depth <n> Dependency traversal depth (default: 2)
141
+ --no-source Exclude source file from the bundle
142
+ -o, --output <file> Write bundle to a file
143
+ --json Output bundle structure as JSON
144
+ ```
145
+
146
+ ### `cgb search <query>`
147
+
148
+ Find nodes by name, description, or file path.
149
+
150
+ ```
151
+ cgb search "UserService" [options]
152
+
153
+ Options:
154
+ -r, --root <path> Project root directory
155
+ --json Output as JSON
156
+ ```
157
+
158
+ ### `cgb path <from> <to>`
159
+
160
+ Find the shortest dependency path between two files.
161
+
162
+ ```
163
+ cgb path src/routes/checkout.ts src/db/pool.ts [options]
164
+
165
+ Options:
166
+ -r, --root <path> Project root directory
167
+ --json Output as JSON
168
+ ```
169
+
170
+ ### `cgb stats`
171
+
172
+ Show graph statistics: file count, node types, cycles, orphan nodes, and architectural layers.
173
+
174
+ ```
175
+ cgb stats [options]
176
+
177
+ Options:
178
+ -r, --root <path> Project root directory
179
+ --json Output as JSON
180
+ ```
181
+
182
+ ### `cgb watch`
183
+
184
+ Watch for file changes and keep the graph incrementally updated.
185
+
186
+ ```
187
+ cgb watch [options]
188
+
189
+ Options:
190
+ -r, --root <path> Project root directory
191
+ ```
192
+
193
+ ### `cgb mcp`
194
+
195
+ Start the MCP server so Cursor / Claude Code can call `cgb` tools directly.
196
+
197
+ ```
198
+ cgb mcp [options]
199
+
200
+ Options:
201
+ -r, --root <path> Default project root
202
+ ```
203
+
204
+ ---
205
+
206
+ ## MCP Server (Cursor / Claude Code Integration)
207
+
208
+ `cgb-builder` ships a [Model Context Protocol](https://modelcontextprotocol.io/) server that exposes all graph tools to your AI coding assistant.
209
+
210
+ ### Setup in Cursor
211
+
212
+ Add to your MCP config (`.cursor/mcp.json` or global `~/.cursor/mcp.json`):
213
+
214
+ ```json
215
+ {
216
+ "mcpServers": {
217
+ "cgb": {
218
+ "command": "cgb",
219
+ "args": ["mcp"],
220
+ "env": {}
221
+ }
222
+ }
223
+ }
224
+ ```
225
+
226
+ ### Setup in Claude Code (global)
227
+
228
+ ```bash
229
+ claude mcp add cgb -- cgb mcp
230
+ ```
231
+
232
+ ### Available MCP Tools
233
+
234
+ | Tool | Description |
235
+ |--------------|-----------------------------------------------------------------------------|
236
+ | `cgb_init` | Scan a project and build/refresh the code graph |
237
+ | `cgb_deps` | Get dependencies of a file (direct + transitive) |
238
+ | `cgb_impact` | Which files would be affected if a given file changes |
239
+ | `cgb_search` | Search nodes by name, description, or file path |
240
+ | `cgb_bundle` | Generate a compact AI context bundle (Markdown, ~1 000–5 000 tokens) |
241
+ | `cgb_stats` | Graph statistics: counts, cycles, layers |
242
+ | `cgb_path` | Shortest dependency path between two files |
243
+
244
+ ---
245
+
246
+ ## Programmatic API
247
+
248
+ ```typescript
249
+ import { GraphDb, GraphEngine, Parser, BundleGenerator } from 'cgb-builder';
250
+
251
+ const root = '/path/to/your/project';
252
+
253
+ // 1. Initialise the database
254
+ const db = new GraphDb(root);
255
+ await db.init();
256
+
257
+ // 2. Parse all source files
258
+ const parser = new Parser(db, root);
259
+ await parser.scanAll();
260
+
261
+ // 3. Query the graph
262
+ const engine = new GraphEngine(db);
263
+
264
+ // Dependencies of a file
265
+ const deps = engine.deps('file:/path/to/your/project/src/index.ts', 3);
266
+
267
+ // Impact analysis
268
+ const impact = engine.impact('file:/path/to/your/project/src/db.ts');
269
+
270
+ // Search
271
+ const results = engine.search('UserService');
272
+
273
+ // Shortest path
274
+ const p = engine.path(
275
+ 'file:/path/to/your/project/src/routes/api.ts',
276
+ 'file:/path/to/your/project/src/db/pool.ts'
277
+ );
278
+
279
+ // 4. Generate an AI context bundle
280
+ const bundleGen = new BundleGenerator(db, engine, root);
281
+ const bundle = bundleGen.generate('/path/to/your/project/src/payments.ts', {
282
+ depth: 2,
283
+ includeSource: true,
284
+ });
285
+ const markdown = bundleGen.render(bundle);
286
+ console.log(`~${bundle.totalTokenEstimate} tokens`);
287
+
288
+ db.close();
289
+ ```
290
+
291
+ ### API Reference
292
+
293
+ #### `GraphDb`
294
+
295
+ | Method | Description |
296
+ |--------|-------------|
297
+ | `new GraphDb(root)` | Create instance; stores graph in `<root>/.cgb/graph.db` |
298
+ | `init()` | Initialise (async, must be called before use) |
299
+ | `getStats()` | `{ files, nodes, edges }` |
300
+ | `getNodeCountByKind()` | Node count broken down by kind |
301
+ | `close()` | Release the database |
302
+
303
+ #### `Parser`
304
+
305
+ | Method | Description |
306
+ |--------|-------------|
307
+ | `new Parser(db, root)` | Create instance |
308
+ | `scanAll(force?)` | Parse all supported source files; returns `{ parsed, skipped, errors, durationMs }` |
309
+
310
+ #### `GraphEngine`
311
+
312
+ | Method | Description |
313
+ |--------|-------------|
314
+ | `new GraphEngine(db)` | Create instance |
315
+ | `deps(nodeId, depth?)` | `DepsResult \| null` |
316
+ | `impact(nodeId, depth?)` | `ImpactResult \| null` |
317
+ | `search(query)` | `GraphNode[]` |
318
+ | `path(fromId, toId)` | `PathResult \| null` |
319
+ | `callers(nodeId)` | `CallersResult \| null` |
320
+ | `layers()` | Architectural layer summary |
321
+ | `detectCycles()` | Circular dependency chains |
322
+ | `orphans()` | Nodes with no edges |
323
+
324
+ #### `BundleGenerator`
325
+
326
+ | Method | Description |
327
+ |--------|-------------|
328
+ | `new BundleGenerator(db, engine, root)` | Create instance |
329
+ | `generate(filePath, options?)` | `ContextBundle` |
330
+ | `render(bundle)` | Render to Markdown string |
331
+
332
+ #### `Watcher`
333
+
334
+ ```typescript
335
+ import { Watcher } from 'cgb-builder';
336
+
337
+ const watcher = new Watcher(root, parser, {
338
+ onUpdate: ({ parsed, errors, files }) => console.log('Updated:', files),
339
+ onError: (err) => console.error(err),
340
+ });
341
+
342
+ watcher.start();
343
+ // ... later ...
344
+ await watcher.stop();
345
+ ```
346
+
347
+ ---
348
+
349
+ ## How It Works
350
+
351
+ 1. **Parse** — Tree-sitter WASM grammars extract imports, exports, classes, functions, and calls from each file.
352
+ 2. **Store** — Results are persisted in a local SQLite database (`.cgb/graph.db`) via `sql.js`.
353
+ 3. **Query** — Graph traversal algorithms answer dependency, impact, and path queries in milliseconds.
354
+ 4. **Bundle** — The bundle generator compiles a compact Markdown document with only the structural context an AI agent needs.
355
+
356
+ Incremental updates: only re-parses files whose content hash has changed since the last run.
357
+
358
+ ---
359
+
360
+ ## Requirements
361
+
362
+ - **Node.js** >= 20.0.0
363
+ - No native build tools required (all Tree-sitter grammars ship as WASM)
364
+
365
+ ---
366
+
367
+ ## License
368
+
369
+ MIT — see [LICENSE](./LICENSE)
@@ -0,0 +1,51 @@
1
+ /**
2
+ * AI Context Bundle Generator.
3
+ *
4
+ * Generates a compact, AI-optimized Markdown document from the graph that
5
+ * contains exactly the context needed for a task — no more, no less.
6
+ *
7
+ * Bundle anatomy:
8
+ * 1. Header — project root, generated-at, root file
9
+ * 2. Graph overview — stats, layers
10
+ * 3. Target file summary — nodes in this file
11
+ * 4. Direct dependencies — what this file imports (signatures only)
12
+ * 5. Reverse dependencies — who imports this file (impact surface)
13
+ * 6. Call chain — functions called and their call graph
14
+ * 7. Inheritance hierarchy — class/interface relationships
15
+ * 8. Source file — actual source of the root file
16
+ */
17
+ import type { GraphDb } from '../graph/db.js';
18
+ import type { GraphEngine } from '../graph/engine.js';
19
+ import type { ContextBundle } from '../types.js';
20
+ export interface BundleOptions {
21
+ /** How many levels of transitive dependencies to include */
22
+ depth?: number;
23
+ /** Include the full source of the root file */
24
+ includeSource?: boolean;
25
+ /** Max lines to include from dependent files */
26
+ maxDependencyLines?: number;
27
+ }
28
+ export declare class BundleGenerator {
29
+ private readonly db;
30
+ private readonly engine;
31
+ private readonly projectRoot;
32
+ constructor(db: GraphDb, engine: GraphEngine, projectRoot: string);
33
+ /**
34
+ * Generate a context bundle for a given file or node ID.
35
+ */
36
+ generate(filePathOrNodeId: string, opts?: BundleOptions): ContextBundle;
37
+ /**
38
+ * Render a bundle to a Markdown string ready for injection into an AI prompt.
39
+ */
40
+ render(bundle: ContextBundle): string;
41
+ private buildHeader;
42
+ private buildGraphOverview;
43
+ private buildFileNodes;
44
+ private buildDepsSection;
45
+ private buildReverseImporters;
46
+ private buildClassHierarchy;
47
+ private buildSourceSection;
48
+ private resolveTarget;
49
+ private groupByKind;
50
+ }
51
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../src/bundle/generator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAA4B,MAAM,aAAa,CAAC;AAO3E,MAAM,WAAW,aAAa;IAC5B,4DAA4D;IAC5D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+CAA+C;IAC/C,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,gDAAgD;IAChD,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAQD,qBAAa,eAAe;IAExB,OAAO,CAAC,QAAQ,CAAC,EAAE;IACnB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,WAAW;gBAFX,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,WAAW,EACnB,WAAW,EAAE,MAAM;IAGtC;;OAEG;IACH,QAAQ,CAAC,gBAAgB,EAAE,MAAM,EAAE,IAAI,GAAE,aAAkB,GAAG,aAAa;IA+C3E;;OAEG;IACH,MAAM,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM;IAkBrC,OAAO,CAAC,WAAW;IAWnB,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,cAAc;IA4BtB,OAAO,CAAC,gBAAgB;IAoCxB,OAAO,CAAC,qBAAqB;IA2B7B,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,kBAAkB;IAa1B,OAAO,CAAC,aAAa;IAKrB,OAAO,CAAC,WAAW;CAQpB"}