@polderlabs/bizar 3.16.0 → 3.19.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.
package/cli/graph.mjs DELETED
@@ -1,642 +0,0 @@
1
- /**
2
- * cli/graph.mjs
3
- *
4
- * `bizar graph` — Per-project knowledge graph powered by graphify.
5
- * Graph data lives in .bizar/graph/ inside the project.
6
- */
7
-
8
- import chalk from 'chalk';
9
- import { spawnSync } from 'node:child_process';
10
- import { existsSync, readFileSync, mkdirSync, writeFileSync, statSync, copyFileSync } from 'node:fs';
11
- import { join } from 'node:path';
12
-
13
- // ── Constants ─────────────────────────────────────────────────────────────────
14
-
15
- export const GRAPH_DIR = '.bizar/graph';
16
- export const GRAPHIFY_OUT_ENV = 'GRAPHIFY_OUT';
17
-
18
- /**
19
- * Env vars graphify recognises for semantic extraction of docs/papers/images.
20
- * If NONE of these are set, graphify refuses to run on a corpus that contains
21
- * any non-code file ("A code-only corpus needs no key."). We auto-detect this
22
- * and write a comprehensive .graphifyignore so a fresh checkout can build
23
- * the graph offline with no LLM key.
24
- */
25
- const GRAPHIFY_LLM_KEY_ENVS = [
26
- 'GEMINI_API_KEY', 'GOOGLE_API_KEY',
27
- 'MOONSHOT_API_KEY',
28
- 'ANTHROPIC_API_KEY',
29
- 'OPENAI_API_KEY',
30
- 'DEEPSEEK_API_KEY',
31
- 'AZURE_OPENAI_API_KEY',
32
- ];
33
-
34
- /**
35
- * Minimal .graphifyignore that restricts graphify to code-only extraction.
36
- * Written automatically by `bizar graph build` when no LLM key is set.
37
- * The user can override this file with their own .graphifyignore — we
38
- * never overwrite a pre-existing one.
39
- */
40
- const CODE_ONLY_GRAPHIFYIGNORE = [
41
- '# Auto-generated by `bizar graph build` — code-only mode.',
42
- '# Bizar detected no LLM key, so docs/papers/images cannot be semantically',
43
- '# extracted. We restrict extraction to code files (processed locally via',
44
- "# tree-sitter — no API key needed). Delete this file and re-run once you've",
45
- '# set one of: GEMINI_API_KEY, GOOGLE_API_KEY, MOONSHOT_API_KEY,',
46
- '# ANTHROPIC_API_KEY, OPENAI_API_KEY, DEEPSEEK_API_KEY, AZURE_OPENAI_API_KEY.',
47
- '',
48
- '# Heavy / vendored dirs to skip entirely',
49
- 'node_modules/',
50
- '.git/',
51
- '.bizar/',
52
- '.agents/',
53
- 'dist/',
54
- 'build/',
55
- 'coverage/',
56
- '',
57
- '# Agent system prompts — they\'re Markdown but contain YAML frontmatter',
58
- '# + system instructions, not project documentation. They\'re noise for',
59
- '# a structural graph and would balloon the doc count to ~1100.',
60
- 'config/agents/',
61
- '',
62
- '# Non-code file types — graphify would need an LLM for these',
63
- '*.md',
64
- '*.mdx',
65
- '*.qmd',
66
- '*.html',
67
- '*.txt',
68
- '*.rst',
69
- '*.pdf',
70
- '*.png',
71
- '*.jpg',
72
- '*.jpeg',
73
- '*.webp',
74
- '*.gif',
75
- '*.mp4',
76
- '*.mov',
77
- '*.mp3',
78
- '*.wav',
79
- '',
80
- ].join('\n');
81
-
82
- /**
83
- * Detect whether any graphify-recognised LLM API key is set in the
84
- * current process env. Used by `cmdBuild` to decide whether to write
85
- * the code-only .graphifyignore.
86
- */
87
- function hasLlmKey(env = process.env) {
88
- return GRAPHIFY_LLM_KEY_ENVS.some((k) => {
89
- const v = env[k];
90
- return typeof v === 'string' && v.trim().length > 0;
91
- });
92
- }
93
-
94
- // ── Python detection ───────────────────────────────────────────────────────────
95
-
96
- /**
97
- * Find a Python 3 interpreter on PATH.
98
- * Returns the absolute path string, or null if none found.
99
- *
100
- * On Windows the `py` launcher is the most reliable option; on Unix
101
- * we prefer python3 then python.
102
- */
103
- export function findPython() {
104
- const candidates = process.platform === 'win32'
105
- ? ['py', 'python', 'python3']
106
- : ['python3', 'python'];
107
- for (const name of candidates) {
108
- try {
109
- const result = spawnSync(name, ['--version'], { encoding: 'utf8', timeout: 5000 });
110
- if (result.status === 0 && result.stdout.includes('Python')) {
111
- return name;
112
- }
113
- } catch {
114
- // try next
115
- }
116
- }
117
- return null;
118
- }
119
-
120
- /**
121
- * Check whether graphify is available.
122
- *
123
- * Strategy:
124
- * 1. Probe PATH for the `graphify` binary (uv tool install puts a shim at
125
- * ~/.local/bin/graphify — invisible to the isolated python -m lookup).
126
- * 2. Fall back to `python -m graphify --version` for pip/pipx installs.
127
- *
128
- * Returns true if available, false otherwise.
129
- */
130
- function checkGraphify(python) {
131
- // Try 1: check for the graphify binary on PATH (uv tool install shim).
132
- // On Windows the Python launcher `py` is not on PATH by default, but the
133
- // graphify shim is placed next to pip/pipx so a plain `where` works.
134
- const whichCmd = process.platform === 'win32' ? 'where' : 'which';
135
- try {
136
- const whichResult = spawnSync(whichCmd, ['graphify'], {
137
- encoding: 'utf8',
138
- timeout: 5000,
139
- });
140
- if (whichResult.status === 0 && (whichResult.stdout || '').trim().length > 0) {
141
- return true;
142
- }
143
- } catch {
144
- // fall through to python -m check
145
- }
146
-
147
- // Try 2: check via python -m (catches pip/pipx installs into system python)
148
- try {
149
- const result = spawnSync(python, ['-m', 'graphify', '--version'], {
150
- encoding: 'utf8',
151
- timeout: 10000,
152
- env: { ...process.env },
153
- });
154
- return result.status === 0;
155
- } catch {
156
- return false;
157
- }
158
- }
159
-
160
- // ── Graph stats parsing ────────────────────────────────────────────────────────
161
-
162
- /**
163
- * Parse .bizar/graph/graph.json and return stats.
164
- * Returns null if the file does not exist or cannot be parsed.
165
- *
166
- * Expected NetworkX node-link JSON shape:
167
- * {
168
- * "directed": false,
169
- * "multigraph": false,
170
- * "graph": {},
171
- * "nodes": [{ "id": "...", "community": 0, ... }],
172
- * "links": [{ "source": "...", "target": "...", ... }]
173
- * }
174
- */
175
- export function parseGraphStats(jsonPath) {
176
- if (!existsSync(jsonPath)) return null;
177
- try {
178
- const content = readFileSync(jsonPath, 'utf8');
179
- const graph = JSON.parse(content);
180
-
181
- const nodes = Array.isArray(graph.nodes) ? graph.nodes : [];
182
- const links = Array.isArray(graph.links) ? graph.links : [];
183
-
184
- // Count unique community values among nodes
185
- const communitySet = new Set();
186
- for (const node of nodes) {
187
- if (node.community !== undefined && node.community !== null) {
188
- communitySet.add(node.community);
189
- }
190
- }
191
-
192
- const stats = statSync(jsonPath);
193
-
194
- return {
195
- nodes: nodes.length,
196
- edges: links.length,
197
- communities: communitySet.size,
198
- lastModified: stats.mtime.toISOString(),
199
- sizeBytes: stats.size,
200
- };
201
- } catch {
202
- return null;
203
- }
204
- }
205
-
206
- // ── Gitignore guard ────────────────────────────────────────────────────────────
207
-
208
- const GRAPH_GITIGNORE = `cache/
209
- .graphify_python
210
- cost.json
211
- `;
212
-
213
- /**
214
- * Ensure .bizar/graph/.gitignore exists so heavy cache artefacts are not committed.
215
- * Called after a successful first build.
216
- */
217
- function ensureGitignore(graphDir) {
218
- const gitignorePath = join(graphDir, '.gitignore');
219
- if (!existsSync(gitignorePath)) {
220
- writeFileSync(gitignorePath, GRAPH_GITIGNORE, 'utf8');
221
- }
222
- }
223
-
224
- // ── Run helpers ───────────────────────────────────────────────────────────────
225
-
226
- /**
227
- * Spawn a graphify command with GRAPHIFY_OUT set to GRAPH_DIR.
228
- * Streams stdout/stderr to the terminal. Returns the exit code.
229
- *
230
- * Resolution order:
231
- * 1. If the `graphify` binary is on PATH (the uv-tool shim), invoke it
232
- * directly. This is what `checkGraphify` already verified — we don't
233
- * need to know about its venv.
234
- * 2. Otherwise fall back to `python -m graphify` for pip/pipx installs.
235
- */
236
- function runGraphify(python, subArgs, extraEnv = {}) {
237
- const env = { ...process.env, [GRAPHIFY_OUT_ENV]: GRAPH_DIR, ...extraEnv };
238
- const whichCmd = process.platform === 'win32' ? 'where' : 'which';
239
- let bin = null;
240
- try {
241
- const r = spawnSync(whichCmd, ['graphify'], { encoding: 'utf8', timeout: 5000 });
242
- if (r.status === 0 && (r.stdout || '').trim().length > 0) {
243
- bin = 'graphify';
244
- }
245
- } catch {
246
- // ignore — fall through to python -m
247
- }
248
-
249
- if (bin) {
250
- const result = spawnSync(bin, subArgs, {
251
- stdio: 'inherit',
252
- env,
253
- timeout: 0, // no timeout — user may run long builds
254
- });
255
- return result.status ?? 1;
256
- }
257
-
258
- const result = spawnSync(python, ['-m', 'graphify', ...subArgs], {
259
- stdio: 'inherit',
260
- env,
261
- timeout: 0,
262
- });
263
- return result.status ?? 1;
264
- }
265
-
266
- // ── Subcommand handlers ────────────────────────────────────────────────────────
267
-
268
- async function cmdBuild(python) {
269
- // If no LLM key is set, fall back to a code-only build by writing a
270
- // comprehensive .graphifyignore. We never overwrite a user-provided
271
- // .graphifyignore — only create the file when it doesn't exist.
272
- let llmKeyPresent = hasLlmKey();
273
- if (!llmKeyPresent) {
274
- const ignorePath = '.graphifyignore';
275
- if (!existsSync(ignorePath)) {
276
- writeFileSync(ignorePath, CODE_ONLY_GRAPHIFYIGNORE, 'utf8');
277
- console.log(chalk.dim(' No LLM API key detected — switching to code-only build.'));
278
- console.log(chalk.dim(` Wrote ${ignorePath} restricting extraction to code files.`));
279
- console.log(chalk.dim(' Set GEMINI_API_KEY / OPENAI_API_KEY / etc. and re-run for full docs extraction.\n'));
280
- } else {
281
- console.log(chalk.dim(' No LLM API key detected — using existing .graphifyignore for code-only build.\n'));
282
- }
283
- }
284
-
285
- console.log(chalk.dim(' Running full graphify pipeline...'));
286
- let code = runGraphify(python, ['.']);
287
-
288
- // Offline code-only fallback — when no LLM key is set, graphify's
289
- // pre-flight check rejects the build before it can write any output.
290
- // Even with a dummy key set, the semantic step fails for any non-code
291
- // docs that escaped the .graphifyignore filter, and graphify refuses
292
- // to write graph.json. To unblock this case we:
293
- // 1. Run graphify with a dummy ANTHROPIC_API_KEY so the AST cache
294
- // gets populated (semantic extraction will fail, that's fine).
295
- // 2. Reconstruct graph.json from the per-file AST cache.
296
- // 3. Run cluster-only to generate graph.html + GRAPH_REPORT.md.
297
- if (code !== 0 && !llmKeyPresent) {
298
- const cacheAstRoot = join(GRAPH_DIR, 'cache', 'ast');
299
- const cacheIsPopulated = existsSync(cacheAstRoot) && (
300
- // graphify creates a versioned subdir on first extract.
301
- // Check if any version dir contains JSON files.
302
- (await import('node:fs/promises'))
303
- .readdir(cacheAstRoot, { withFileTypes: true })
304
- .then((entries) =>
305
- entries.some(async (e) => {
306
- if (!e.isDirectory()) return false;
307
- const files = await (await import('node:fs/promises')).readdir(join(cacheAstRoot, e.name));
308
- return files.some((f) => f.endsWith('.json'));
309
- }),
310
- )
311
- .catch(() => false)
312
- );
313
-
314
- if (!cacheIsPopulated) {
315
- console.log(chalk.yellow(' ⚠ No AST cache yet. Running graphify with a dummy key to populate the cache (semantic extraction will fail; that\'s OK)...'));
316
- // Set a dummy key so graphify gets past its pre-flight check and
317
- // populates the AST cache. We invoke the graphify binary directly
318
- // (the user's python3 -m graphify may not have graphify installed;
319
- // uv-tool installs put a shim at ~/.local/bin/graphify).
320
- const dummyRes = spawnSync('graphify', ['.'], {
321
- stdio: 'inherit',
322
- env: { ...process.env, ANTHROPIC_API_KEY: 'sk-bizar-graph-dummy', GRAPHIFY_OUT: GRAPH_DIR },
323
- timeout: 0,
324
- });
325
- void dummyRes; // exit code doesn't matter — we want the cache, not the merge
326
- }
327
-
328
- const cacheStillEmpty = !(await (async () => {
329
- try {
330
- const e = await (await import('node:fs/promises')).readdir(cacheAstRoot, { withFileTypes: true });
331
- for (const d of e) {
332
- if (!d.isDirectory()) continue;
333
- const f = await (await import('node:fs/promises')).readdir(join(cacheAstRoot, d.name));
334
- if (f.some((x) => x.endsWith('.json'))) return true;
335
- }
336
- return false;
337
- } catch {
338
- return false;
339
- }
340
- })());
341
-
342
- if (!cacheStillEmpty) {
343
- console.log(chalk.yellow(' ⚠ graphify exited non-zero. Falling back to AST-cache build...'));
344
- const fb = runCacheFallbackBuild();
345
- if (fb === 0) code = 0;
346
- }
347
- }
348
-
349
- if (code === 0) {
350
- ensureGitignore(GRAPH_DIR);
351
- // After extract, run cluster-only to write graph.html + GRAPH_REPORT.md
352
- // (extract only writes graph.json; cluster-only adds viz + report).
353
- const graphJson = join(GRAPH_DIR, 'graph.json');
354
- if (existsSync(graphJson)) {
355
- console.log(chalk.dim(' Generating graph.html + GRAPH_REPORT.md via cluster-only...'));
356
- // Pass "." as the cluster-only path so it writes graph.html +
357
- // GRAPH_REPORT.md to the current directory's graphify-out/.
358
- // (Passing `.bizar/graph` directly nests the output as
359
- // `.bizar/graph/.bizar/graph/...` which is wrong.) The explicit
360
- // --graph overrides the auto-discovery to find graph.json.
361
- const clusterArgs = ['cluster-only', '.', '--graph', graphJson];
362
- const clusterCode = runGraphify(python, clusterArgs);
363
- if (clusterCode !== 0) {
364
- console.log(chalk.yellow(` ⚠ cluster-only returned ${clusterCode} — graph.json was built but graph.html may be stale.`));
365
- } else {
366
- // cluster-only writes to ./graphify-out/ (relative to CWD).
367
- // Promote the artifacts up to .bizar/graph/ paths the dashboard
368
- // serves directly.
369
- const out = join(GRAPH_DIR, 'graphify-out');
370
- if (!existsSync(out)) {
371
- // Fallback: graphify may have written to ./graphify-out/ at CWD.
372
- const cwdOut = join(process.cwd(), 'graphify-out');
373
- if (existsSync(cwdOut)) {
374
- promoteFromDir(cwdOut, GRAPH_DIR);
375
- }
376
- } else {
377
- promoteClusterOutputs(GRAPH_DIR);
378
- }
379
- }
380
- }
381
- console.log(chalk.green(`\n ✓ Graph built → ${GRAPH_DIR}/\n`));
382
- }
383
- return code;
384
- }
385
-
386
- /**
387
- * Reconstruct graph.json from graphify's per-file AST cache and run
388
- * cluster-only to produce graph.html + GRAPH_REPORT.md. Used when the
389
- * full graphify pipeline fails because some docs need an LLM that we
390
- * don't have, but the AST cache for code-only files was successfully
391
- * extracted.
392
- *
393
- * Returns the exit code of the overall sequence (0 on success).
394
- */
395
- function runCacheFallbackBuild() {
396
- // Step 1: merge the per-file AST cache into a single graph.json.
397
- const scriptPath = new URL(import.meta.url).pathname;
398
- // cli/graph.mjs sits next to cli/graph-build-from-cache.mjs.
399
- const cacheScript = scriptPath.replace(/graph\.mjs$/, 'graph-build-from-cache.mjs');
400
- if (!existsSync(cacheScript)) {
401
- console.log(chalk.red(` ✗ Cache fallback script not found at ${cacheScript}`));
402
- return 1;
403
- }
404
- const buildRes = spawnSync(process.execPath, [cacheScript, GRAPH_DIR], {
405
- stdio: 'inherit',
406
- });
407
- if (buildRes.status !== 0) {
408
- return buildRes.status ?? 1;
409
- }
410
- // Step 2: cluster-only regenerates graph.html from the merged graph.json.
411
- return 0;
412
- }
413
-
414
- /**
415
- * Copy the named files from `srcDir` up to `dstDir`. Used to hoist
416
- * cluster-only's graph.html / GRAPH_REPORT.md / graph.json up to the
417
- * canonical .bizar/graph/ paths the dashboard serves.
418
- */
419
- function promoteFromDir(srcDir, dstDir) {
420
- for (const name of ['graph.html', 'GRAPH_REPORT.md', 'graph.json']) {
421
- const src = join(srcDir, name);
422
- const dst = join(dstDir, name);
423
- if (existsSync(src)) {
424
- copyFileSync(src, dst);
425
- }
426
- }
427
- }
428
-
429
- /**
430
- * cluster-only writes its outputs to a nested graphify-out/ directory
431
- * by default. This hoists them up to the standard paths the dashboard
432
- * serves (.bizar/graph/graph.html + .bizar/graph/GRAPH_REPORT.md).
433
- */
434
- function promoteClusterOutputs(graphDir) {
435
- const out = join(graphDir, 'graphify-out');
436
- if (existsSync(out)) promoteFromDir(out, graphDir);
437
- }
438
-
439
- async function cmdUpdate(python) {
440
- console.log(chalk.dim(' Running incremental graph update...'));
441
- return runGraphify(python, ['.', '--update']);
442
- }
443
-
444
- async function cmdQuery(python, query) {
445
- if (!query) {
446
- console.log(chalk.red(' Error: query text required.'));
447
- console.log(chalk.dim(' Usage: bizar graph query "<search term>"\n'));
448
- return 1;
449
- }
450
- return runGraphify(python, ['query', query]);
451
- }
452
-
453
- async function cmdPath(python, a, b) {
454
- if (!a || !b) {
455
- console.log(chalk.red(' Error: two concept names required.'));
456
- console.log(chalk.dim(' Usage: bizar graph path "<A>" "<B>"\n'));
457
- return 1;
458
- }
459
- return runGraphify(python, ['path', a, b]);
460
- }
461
-
462
- async function cmdExplain(python, concept) {
463
- if (!concept) {
464
- console.log(chalk.red(' Error: concept name required.'));
465
- console.log(chalk.dim(' Usage: bizar graph explain "<X>"\n'));
466
- return 1;
467
- }
468
- return runGraphify(python, ['explain', concept]);
469
- }
470
-
471
- async function cmdWatch(python) {
472
- console.log(chalk.dim(' Starting graphify watch mode (Ctrl-C to stop)...'));
473
- return runGraphify(python, ['.', '--watch']);
474
- }
475
-
476
- async function cmdStatus() {
477
- const graphJsonPath = join(GRAPH_DIR, 'graph.json');
478
- const stats = parseGraphStats(graphJsonPath);
479
-
480
- console.log(chalk.bold.hex('#10b981')('\n ᛗ BIZAR GRAPH STATUS ᛗ\n'));
481
- console.log(` Path: ${GRAPH_DIR}/`);
482
-
483
- if (!existsSync(GRAPH_DIR)) {
484
- console.log(` Exists: ${chalk.yellow('no')} (run \`bizar graph build\` first)`);
485
- console.log();
486
- return 0;
487
- }
488
-
489
- if (!stats) {
490
- console.log(` Exists: ${chalk.yellow('no graph.json found')}`);
491
- console.log();
492
- return 0;
493
- }
494
-
495
- console.log(` Exists: ${chalk.green('yes')}`);
496
- console.log(` Size: ${(stats.sizeBytes / 1024).toFixed(1)} KB`);
497
- console.log(` Last built: ${stats.lastModified}`);
498
- console.log(` Nodes: ${stats.nodes}`);
499
- console.log(` Edges: ${stats.edges}`);
500
- console.log(` Communities:${stats.communities}`);
501
- console.log();
502
- return 0;
503
- }
504
-
505
- async function cmdInstall() {
506
- const python = findPython();
507
- if (!python) {
508
- console.error(chalk.red(' Error: graphify requires Python 3.10+.'));
509
- console.error(chalk.dim(' Install Python from https://python.org or via your package manager, then re-run.\n'));
510
- return 1;
511
- }
512
-
513
- // Prefer uv (handles PEP 668 isolated installs cleanly); fall back to pip.
514
- const { detectUv } = await import('./utils.mjs');
515
- const hasUv = await detectUv();
516
-
517
- if (hasUv) {
518
- console.log(chalk.dim(' Installing graphify via uv...\n'));
519
- const result = spawnSync('uv', ['tool', 'install', 'graphifyy'], { stdio: 'inherit' });
520
- if (result.status !== 0) {
521
- console.log(chalk.red(' ✗ uv tool install graphifyy failed.\n'));
522
- return 1;
523
- }
524
- } else {
525
- console.log(chalk.dim(' Installing graphify via pip...\n'));
526
- // On Windows `pip` may not be on PATH; use `py -m pip` as the fallback.
527
- const pipCmd = process.platform === 'win32'
528
- ? [python, '-m', 'pip']
529
- : ['pip'];
530
- const result = spawnSync(pipCmd[0], pipCmd.slice(1).concat(['install', 'graphifyy']), { stdio: 'inherit' });
531
- if (result.status !== 0) {
532
- console.log(chalk.red(' ✗ pip install graphifyy failed.\n'));
533
- return 1;
534
- }
535
- }
536
-
537
- // graphify install --platform opencode --project
538
- console.log(chalk.dim('\n $ graphify install --platform opencode --project'));
539
- const result = spawnSync('graphify', ['install', '--platform', 'opencode', '--project'], {
540
- stdio: 'inherit',
541
- });
542
- if (result.status !== 0) {
543
- console.log(chalk.red(' ✗ graphify install failed.\n'));
544
- return 1;
545
- }
546
-
547
- console.log(chalk.green('\n ✓ graphify installed and OpenCode plugin configured.\n'));
548
- return 0;
549
- }
550
-
551
- // ── Help ──────────────────────────────────────────────────────────────────────
552
-
553
- export function showGraphHelp() {
554
- console.log(`
555
- ${chalk.bold.hex('#10b981')('bizar graph')} — Per-project knowledge graph (powered by graphify)
556
-
557
- ${chalk.dim('Usage:')}
558
- ${chalk.cyan('bizar graph build')} # full build of the project graph
559
- ${chalk.cyan('bizar graph update')} # incremental rebuild
560
- ${chalk.cyan('bizar graph query "<text>"')} # query the graph
561
- ${chalk.cyan('bizar graph path "<A>" "<B>"')} # shortest path between concepts
562
- ${chalk.cyan('bizar graph explain "<X>"')} # all nodes related to a concept
563
- ${chalk.cyan('bizar graph watch')} # watch for changes and rebuild
564
- ${chalk.cyan('bizar graph status')} # show graph path, size, node/edge/community counts
565
- ${chalk.cyan('bizar graph install')} # install graphify + drop OpenCode skill/plugin
566
-
567
- ${chalk.dim('Requires:')} Python 3.10+ and \`graphify\` (${chalk.cyan('pip install graphifyy')})
568
-
569
- ${chalk.dim('Graph data lives in')} ${chalk.cyan('.bizar/graph/')} ${chalk.dim('inside this project.')}
570
- `);
571
- }
572
-
573
- // ── Main entry point ───────────────────────────────────────────────────────────
574
-
575
- /**
576
- * `bizar graph` entry point.
577
- *
578
- * @param {string[]} args — subcommand + args after 'graph'
579
- */
580
- export async function runGraph(args) {
581
- // Show help when called with no args or --help / -h
582
- if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
583
- showGraphHelp();
584
- return 0;
585
- }
586
-
587
- const sub = args[0];
588
-
589
- // status and install are the only subcommands that don't need graphify
590
- if (sub !== 'status' && sub !== 'install') {
591
- // Detect Python
592
- const python = findPython();
593
- if (!python) {
594
- console.error(chalk.red(' Error: graphify requires Python 3.10+.'));
595
- console.error(chalk.dim(' Install Python from https://python.org or via your package manager, then re-run.\n'));
596
- return 1;
597
- }
598
-
599
- // Detect graphify
600
- if (!checkGraphify(python)) {
601
- console.error(chalk.red(' Error: graphify is not installed.'));
602
- console.error(chalk.dim(' Install it with:'));
603
- console.error(chalk.cyan(' pip install graphifyy\n'));
604
- console.error(chalk.dim(' Or run:'));
605
- console.error(chalk.cyan(' bizar graph install\n'));
606
- return 1;
607
- }
608
-
609
- // Ensure .bizar/ directory exists (graphify will create graph/ inside it)
610
- mkdirSync(GRAPH_DIR, { recursive: true });
611
-
612
- switch (sub) {
613
- case 'build':
614
- return await cmdBuild(python);
615
- case 'update':
616
- return await cmdUpdate(python);
617
- case 'query':
618
- return await cmdQuery(python, args.slice(1).join(' '));
619
- case 'path':
620
- return await cmdPath(python, args[1], args[2]);
621
- case 'explain':
622
- return await cmdExplain(python, args[1]);
623
- case 'watch':
624
- return await cmdWatch(python);
625
- default:
626
- console.error(chalk.red(` Error: unknown subcommand '${sub}'.\n`));
627
- showGraphHelp();
628
- return 1;
629
- }
630
- }
631
-
632
- // subcommands that don't need graphify
633
- switch (sub) {
634
- case 'status':
635
- return await cmdStatus();
636
- case 'install':
637
- return await cmdInstall();
638
- default:
639
- // unreachable — already caught unknown subcommands above
640
- return 1;
641
- }
642
- }