graphify-rs 0.7.0

AI-powered knowledge graph builder - transform code, docs, papers into queryable graphs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;

use crate::skill::SKILL_CONTENT;

/// Current package version for staleness checks.
const VERSION: &str = env!("CARGO_PKG_VERSION");

struct PlatformConfig {
    skill_dst: &'static str,
    register_claude_md: bool,
}

const PLATFORMS: &[(&str, PlatformConfig)] = &[
    (
        "claude",
        PlatformConfig {
            skill_dst: ".claude/skills/graphify-rs/SKILL.md",
            register_claude_md: true,
        },
    ),
    (
        "codex",
        PlatformConfig {
            skill_dst: ".agents/skills/graphify-rs/SKILL.md",
            register_claude_md: false,
        },
    ),
    (
        "opencode",
        PlatformConfig {
            skill_dst: ".config/opencode/skills/graphify-rs/SKILL.md",
            register_claude_md: false,
        },
    ),
    (
        "claw",
        PlatformConfig {
            skill_dst: ".claw/skills/graphify-rs/SKILL.md",
            register_claude_md: false,
        },
    ),
    (
        "droid",
        PlatformConfig {
            skill_dst: ".factory/skills/graphify-rs/SKILL.md",
            register_claude_md: false,
        },
    ),
    (
        "trae",
        PlatformConfig {
            skill_dst: ".trae/skills/graphify-rs/SKILL.md",
            register_claude_md: false,
        },
    ),
    (
        "trae-cn",
        PlatformConfig {
            skill_dst: ".trae-cn/skills/graphify-rs/SKILL.md",
            register_claude_md: false,
        },
    ),
    (
        "codebuddy",
        PlatformConfig {
            skill_dst: ".codebuddy/skills/graphify-rs/SKILL.md",
            register_claude_md: false,
        },
    ),
    (
        "windows",
        PlatformConfig {
            skill_dst: ".claude/skills/graphify-rs/SKILL.md",
            register_claude_md: true,
        },
    ),
];

const SKILL_REGISTRATION: &str = r#"
# graphify
- **graphify-rs** (`~/.claude/skills/graphify-rs/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify-rs`
When the user types `/graphify-rs`, invoke the Skill tool with `skill: "graphify-rs"` before doing anything else.
"#;

fn graph_md_section(output_dir: &str) -> String {
    format!(
        r"## graphify

This project has a graphify-rs knowledge graph at {output_dir}/.

Rules:
- Before answering architecture or codebase questions, read {output_dir}/GRAPH_REPORT.md for god nodes and community structure
- If {output_dir}/wiki/index.md exists, navigate it instead of reading raw files
- After modifying code files in this session, run `graphify-rs build --path . --output {output_dir} --no-llm --update` to keep the graph current (fast, AST-only, ~2-5s)
"
    )
}

const CLAUDE_MD_MARKER: &str = "## graphify";

const AGENTS_MD_MARKER: &str = "## graphify";

/// Check all known skill install locations for stale versions.
/// Call this on startup (before executing any subcommand).
pub fn check_skill_versions() {
    let home = match home_dir() {
        Ok(h) => h,
        Err(_) => return,
    };
    for (_, config) in PLATFORMS {
        let version_file = home
            .join(config.skill_dst)
            .parent()
            .map(|p| p.join(".graphify_version"))
            .unwrap_or_default();
        if version_file.exists() {
            if let Ok(installed) = fs::read_to_string(&version_file) {
                let installed = installed.trim();
                if !installed.is_empty() && installed != VERSION {
                    eprintln!(
                        "  warning: skill is from graphify-rs {installed}, package is {VERSION}. Run 'graphify-rs install' to update."
                    );
                    return; // Only warn once
                }
            }
        }
    }
}

/// Install graphify skill file for a given platform (global install).
pub fn install_skill(platform: &str) -> Result<()> {
    let config = PLATFORMS
        .iter()
        .find(|(name, _)| *name == platform)
        .map(|(_, cfg)| cfg)
        .with_context(|| {
            let valid: Vec<&str> = PLATFORMS.iter().map(|(n, _)| *n).collect();
            format!(
                "Unknown platform '{}'. Valid platforms: {}",
                platform,
                valid.join(", ")
            )
        })?;

    let home = home_dir()?;
    let skill_path = home.join(config.skill_dst);

    if let Some(parent) = skill_path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory {}", parent.display()))?;
    }

    fs::write(&skill_path, SKILL_CONTENT)
        .with_context(|| format!("Failed to write skill file to {}", skill_path.display()))?;
    println!("  Wrote skill file to {}", skill_path.display());

    if let Some(parent) = skill_path.parent() {
        let version_file = parent.join(".graphify_version");
        let _ = fs::write(&version_file, VERSION);
    }

    if config.register_claude_md {
        let claude_md_path = home.join(".claude/CLAUDE.md");
        register_in_file(&claude_md_path, SKILL_REGISTRATION, "# graphify")?;
        println!("  Registered in {}", claude_md_path.display());
    }

    println!("\n  Installed graphify skill for '{platform}'.");
    println!("  Use `/graphify-rs` in your AI assistant to trigger the skill.");

    Ok(())
}

/// `graphify-rs claude install` — project-level Claude integration.
pub fn claude_install(project_root: &Path) -> Result<()> {
    let output_dir = crate::paths::resolve_default_output(project_root)
        .to_string_lossy()
        .to_string();
    let claude_md = project_root.join("CLAUDE.md");
    append_section(&claude_md, &graph_md_section(&output_dir), CLAUDE_MD_MARKER)?;
    println!("  Updated {}", claude_md.display());

    let settings_path = project_root.join(".claude/settings.json");
    write_claude_settings_hook(&settings_path, &output_dir)?;
    println!("  Wrote hook to {}", settings_path.display());

    println!("\n  Claude integration installed.");
    Ok(())
}

/// `graphify-rs claude uninstall` — remove project-level Claude integration.
pub fn claude_uninstall(project_root: &Path) -> Result<()> {
    let claude_md = project_root.join("CLAUDE.md");
    remove_section(&claude_md, CLAUDE_MD_MARKER)?;
    println!("  Cleaned {}", claude_md.display());

    let settings_path = project_root.join(".claude/settings.json");
    remove_claude_settings_hook(&settings_path)?;
    println!("  Cleaned {}", settings_path.display());

    println!("\n  Claude integration uninstalled.");
    Ok(())
}

/// `graphify-rs codebuddy install` — project-level CodeBuddy integration.
pub fn codebuddy_install(project_root: &Path) -> Result<()> {
    let output_dir = crate::paths::resolve_default_output(project_root)
        .to_string_lossy()
        .to_string();
    let agents_md = project_root.join("AGENTS.md");
    append_section(&agents_md, &graph_md_section(&output_dir), AGENTS_MD_MARKER)?;
    println!("  Updated {}", agents_md.display());

    let settings_path = project_root.join(".codebuddy/settings.json");
    write_codebuddy_settings_hook(&settings_path, &output_dir)?;
    println!("  Wrote hook to {}", settings_path.display());

    println!("\n  CodeBuddy integration installed.");
    Ok(())
}

/// `graphify-rs codebuddy uninstall` — remove project-level CodeBuddy integration.
pub fn codebuddy_uninstall(project_root: &Path) -> Result<()> {
    let agents_md = project_root.join("AGENTS.md");
    remove_section(&agents_md, AGENTS_MD_MARKER)?;
    println!("  Cleaned {}", agents_md.display());

    let settings_path = project_root.join(".codebuddy/settings.json");
    remove_codebuddy_settings_hook(&settings_path)?;
    println!("  Cleaned {}", settings_path.display());

    println!("\n  CodeBuddy integration uninstalled.");
    Ok(())
}

/// `graphify-rs codex install` — project-level Codex integration.
pub fn codex_install(project_root: &Path) -> Result<()> {
    let output_dir = crate::paths::resolve_default_output(project_root)
        .to_string_lossy()
        .to_string();
    let agents_md = project_root.join("AGENTS.md");
    append_section(&agents_md, &graph_md_section(&output_dir), AGENTS_MD_MARKER)?;
    println!("  Updated {}", agents_md.display());

    let hooks_path = project_root.join(".codex/hooks.json");
    write_codex_hooks(&hooks_path, &output_dir)?;
    println!("  Wrote hook to {}", hooks_path.display());

    println!("\n  Codex integration installed.");
    Ok(())
}

/// `graphify-rs codex uninstall`
pub fn codex_uninstall(project_root: &Path) -> Result<()> {
    let agents_md = project_root.join("AGENTS.md");
    remove_section(&agents_md, AGENTS_MD_MARKER)?;
    println!("  Cleaned {}", agents_md.display());

    let hooks_path = project_root.join(".codex/hooks.json");
    if hooks_path.exists() {
        fs::remove_file(&hooks_path)?;
        println!("  Removed {}", hooks_path.display());
    }

    println!("\n  Codex integration uninstalled.");
    Ok(())
}

/// `graphify-rs opencode install` — project-level OpenCode integration.
pub fn opencode_install(project_root: &Path) -> Result<()> {
    let output_dir = crate::paths::resolve_default_output(project_root)
        .to_string_lossy()
        .to_string();
    let agents_md = project_root.join("AGENTS.md");
    append_section(&agents_md, &graph_md_section(&output_dir), AGENTS_MD_MARKER)?;
    println!("  Updated {}", agents_md.display());

    let plugin_path = project_root.join(".opencode/plugins/graphify.js");
    write_opencode_plugin(&plugin_path, &output_dir)?;
    println!("  Wrote plugin to {}", plugin_path.display());

    let config_path = project_root.join("opencode.json");
    register_opencode_config(&config_path)?;
    println!("  Updated {}", config_path.display());

    println!("\n  OpenCode integration installed.");
    Ok(())
}

/// `graphify-rs opencode uninstall`
pub fn opencode_uninstall(project_root: &Path) -> Result<()> {
    let agents_md = project_root.join("AGENTS.md");
    remove_section(&agents_md, AGENTS_MD_MARKER)?;
    println!("  Cleaned {}", agents_md.display());

    let plugin_path = project_root.join(".opencode/plugins/graphify.js");
    if plugin_path.exists() {
        fs::remove_file(&plugin_path)?;
        println!("  Removed {}", plugin_path.display());
    }

    let config_path = project_root.join("opencode.json");
    unregister_opencode_config(&config_path)?;
    println!("  Cleaned {}", config_path.display());

    println!("\n  OpenCode integration uninstalled.");
    Ok(())
}

/// Generic platform install — just writes AGENTS.md section.
pub fn generic_platform_install(project_root: &Path, platform: &str) -> Result<()> {
    let output_dir = crate::paths::resolve_default_output(project_root)
        .to_string_lossy()
        .to_string();
    let agents_md = project_root.join("AGENTS.md");
    append_section(&agents_md, &graph_md_section(&output_dir), AGENTS_MD_MARKER)?;
    println!("  Updated {}", agents_md.display());
    println!("\n  {platform} integration installed.");
    Ok(())
}

/// Generic platform uninstall — just removes AGENTS.md section.
pub fn generic_platform_uninstall(project_root: &Path, platform: &str) -> Result<()> {
    let agents_md = project_root.join("AGENTS.md");
    remove_section(&agents_md, AGENTS_MD_MARKER)?;
    println!("  Cleaned {}", agents_md.display());
    println!("\n  {platform} integration uninstalled.");
    Ok(())
}

fn home_dir() -> Result<std::path::PathBuf> {
    dirs::home_dir().context("Could not determine home directory")
}

/// Append a section to a file if the marker is not already present.
fn append_section(path: &Path, section: &str, marker: &str) -> Result<()> {
    let existing = if path.exists() {
        fs::read_to_string(path)?
    } else {
        String::new()
    };

    if existing.contains(marker) {
        println!("  Section already present in {}, skipping.", path.display());
        return Ok(());
    }

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    let mut content = existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    content.push('\n');
    content.push_str(section);

    fs::write(path, content)?;
    Ok(())
}

/// Remove a section from a file identified by a marker line.
/// Removes from the marker line until the next `##` heading or end of file.
fn remove_section(path: &Path, marker: &str) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(path)?;
    if !content.contains(marker) {
        return Ok(());
    }

    let mut result = String::new();
    let mut skipping = false;

    for line in content.lines() {
        if line.starts_with(marker) {
            skipping = true;
            continue;
        }
        if skipping {
            if line.starts_with("## ") {
                skipping = false;
                result.push_str(line);
                result.push('\n');
            }
            continue;
        }
        result.push_str(line);
        result.push('\n');
    }

    let trimmed = result.trim_end().to_string() + "\n";
    fs::write(path, trimmed)?;
    Ok(())
}

/// Register a skill reference in a file (like ~/.claude/CLAUDE.md).
fn register_in_file(path: &Path, registration_text: &str, marker: &str) -> Result<()> {
    let existing = if path.exists() {
        fs::read_to_string(path)?
    } else {
        String::new()
    };

    if existing.contains(marker) {
        return Ok(());
    }

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    let mut content = existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    content.push_str(registration_text);

    fs::write(path, content)?;
    Ok(())
}

/// Write Claude PreToolUse hook to .claude/settings.json.
fn write_claude_settings_hook(path: &Path, output_dir: &str) -> Result<()> {
    let mut settings: serde_json::Value = if path.exists() {
        let content = fs::read_to_string(path)?;
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}))
    } else {
        serde_json::json!({})
    };

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    let cmd = format!(
        "[ -f \"{output_dir}/graph.json\" ] && echo '{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"graphify-rs: Knowledge graph exists. Read {output_dir}/GRAPH_REPORT.md for god nodes and community structure before searching raw files.\"}}}}' || true"
    );
    let hook_entry = serde_json::json!({
        "matcher": "Glob|Grep",
        "hooks": [{
            "type": "command",
            "command": cmd
        }]
    });

    let hooks = settings
        .as_object_mut()
        .context("settings is not an object")?
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let pre_tool_use = hooks
        .as_object_mut()
        .context("hooks is not an object")?
        .entry("PreToolUse")
        .or_insert_with(|| serde_json::json!([]));

    let arr = pre_tool_use
        .as_array_mut()
        .context("PreToolUse is not an array")?;

    let already = arr
        .iter()
        .any(|v| v.get("matcher").and_then(|m| m.as_str()) == Some("Glob|Grep"));
    if !already {
        arr.push(hook_entry);
    }

    let output = serde_json::to_string_pretty(&settings)?;
    fs::write(path, output)?;
    Ok(())
}

/// Remove Claude PreToolUse hook from .claude/settings.json.
fn remove_claude_settings_hook(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(path)?;
    let mut settings: serde_json::Value =
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}));

    if let Some(hooks) = settings.get_mut("hooks") {
        if let Some(pre_tool_use) = hooks.get_mut("PreToolUse") {
            if let Some(arr) = pre_tool_use.as_array_mut() {
                arr.retain(|v| v.get("matcher").and_then(|m| m.as_str()) != Some("Glob|Grep"));
            }
        }
    }

    let output = serde_json::to_string_pretty(&settings)?;
    fs::write(path, output)?;
    Ok(())
}

/// Write CodeBuddy PreToolUse hook to .codebuddy/settings.json.
fn write_codebuddy_settings_hook(path: &Path, output_dir: &str) -> Result<()> {
    let mut settings: serde_json::Value = if path.exists() {
        let content = fs::read_to_string(path)?;
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}))
    } else {
        serde_json::json!({})
    };

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    let cmd = format!(
        "[ -f \"{output_dir}/graph.json\" ] && echo '{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"graphify-rs: Knowledge graph exists. Read {output_dir}/GRAPH_REPORT.md for god nodes and community structure before searching raw files.\"}}}}' || true"
    );
    let hook_entry = serde_json::json!({
        "matcher": "Glob|Grep",
        "hooks": [{
            "type": "command",
            "command": cmd
        }]
    });

    let hooks = settings
        .as_object_mut()
        .context("settings is not an object")?
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let pre_tool_use = hooks
        .as_object_mut()
        .context("hooks is not an object")?
        .entry("PreToolUse")
        .or_insert_with(|| serde_json::json!([]));

    let arr = pre_tool_use
        .as_array_mut()
        .context("PreToolUse is not an array")?;

    let already = arr
        .iter()
        .any(|v| v.get("matcher").and_then(|m| m.as_str()) == Some("Glob|Grep"));
    if !already {
        arr.push(hook_entry);
    }

    let output = serde_json::to_string_pretty(&settings)?;
    fs::write(path, output)?;
    Ok(())
}

/// Remove CodeBuddy PreToolUse hook from .codebuddy/settings.json.
fn remove_codebuddy_settings_hook(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(path)?;
    let mut settings: serde_json::Value =
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}));

    if let Some(hooks) = settings.get_mut("hooks") {
        if let Some(pre_tool_use) = hooks.get_mut("PreToolUse") {
            if let Some(arr) = pre_tool_use.as_array_mut() {
                arr.retain(|v| v.get("matcher").and_then(|m| m.as_str()) != Some("Glob|Grep"));
            }
        }
    }

    let output = serde_json::to_string_pretty(&settings)?;
    fs::write(path, output)?;
    Ok(())
}

/// Write Codex hooks.json.
fn write_codex_hooks(path: &Path, output_dir: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    let cmd = format!(
        "[ -f \"{output_dir}/graph.json\" ] && echo '{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"systemMessage\":\"graphify-rs: Knowledge graph exists. Read {output_dir}/GRAPH_REPORT.md for god nodes and community structure before searching raw files.\"}}}}' || true"
    );
    let hooks = serde_json::json!({
        "hooks": {
            "PreToolUse": [{
                "matcher": "Bash",
                "hooks": [{
                    "type": "command",
                    "command": cmd
                }]
            }]
        }
    });

    let output = serde_json::to_string_pretty(&hooks)?;
    fs::write(path, output)?;
    Ok(())
}

/// Write OpenCode plugin file.
fn write_opencode_plugin(path: &Path, output_dir: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    let plugin_content = format!(
        r#"// graphify-rs plugin for OpenCode
module.exports = {{
    name: "graphify-rs",
    description: "Knowledge graph integration",
    hooks: {{
        preToolUse: async (ctx) => {{
            const fs = require("fs");
            if (fs.existsSync("{output_dir}/graph.json")) {{
                return {{
                    prefix: "[graphify-rs] Knowledge graph available. Read {output_dir}/GRAPH_REPORT.md for architecture overview."
                }};
            }}
        }}
    }}
}};
"#
    );

    fs::write(path, plugin_content)?;
    Ok(())
}

/// Register graphify plugin in opencode.json.
fn register_opencode_config(path: &Path) -> Result<()> {
    let mut config: serde_json::Value = if path.exists() {
        let content = fs::read_to_string(path)?;
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}))
    } else {
        serde_json::json!({})
    };

    let plugins = config
        .as_object_mut()
        .context("config is not an object")?
        .entry("plugin")
        .or_insert_with(|| serde_json::json!([]));

    if let Some(arr) = plugins.as_array_mut() {
        let already = arr
            .iter()
            .any(|v| v.as_str() == Some(".opencode/plugins/graphify.js"));
        if !already {
            arr.push(serde_json::json!(".opencode/plugins/graphify.js"));
        }
    }

    let output = serde_json::to_string_pretty(&config)?;
    fs::write(path, output)?;
    Ok(())
}

/// Remove graphify plugin from opencode.json.
fn unregister_opencode_config(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }

    let content = fs::read_to_string(path)?;
    let mut config: serde_json::Value =
        serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({}));

    if let Some(plugins) = config.get_mut("plugin") {
        if let Some(arr) = plugins.as_array_mut() {
            arr.retain(|v| v.as_str() != Some(".opencode/plugins/graphify.js"));
        }
    }

    let output = serde_json::to_string_pretty(&config)?;
    fs::write(path, output)?;
    Ok(())
}