tokensave 3.4.0

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
use std::path::Path;

use tempfile::TempDir;
use tokensave::agents::{
    AgentIntegration, DoctorCounters, HealthcheckContext, InstallContext, OpenCodeIntegration,
    EXPECTED_TOOL_PERMS,
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn make_ctx(home: &Path) -> InstallContext {
    InstallContext {
        home: home.to_path_buf(),
        tokensave_bin: "/usr/local/bin/tokensave".to_string(),
        tool_permissions: EXPECTED_TOOL_PERMS,
    }
}

fn read_json(path: &Path) -> serde_json::Value {
    let contents = std::fs::read_to_string(path).unwrap();
    serde_json::from_str(&contents).unwrap()
}

fn opencode_config_path(home: &Path) -> std::path::PathBuf {
    home.join(".config/opencode/opencode.json")
}

fn opencode_prompt_path(home: &Path) -> std::path::PathBuf {
    // Mirrors the logic: if .config/opencode exists, use it
    let modern = home.join(".config/opencode/OPENCODE.md");
    if modern.exists() || home.join(".config/opencode").exists() {
        return modern;
    }
    home.join("OPENCODE.md")
}

// ===========================================================================
// Install content verification
// ===========================================================================

#[test]
fn test_install_creates_opencode_json() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    let config_path = opencode_config_path(home);
    assert!(config_path.exists(), "opencode.json should be created");

    let config = read_json(&config_path);
    let ts = &config["mcp"]["tokensave"];
    assert!(ts.is_object(), "mcp.tokensave should be an object");
    assert_eq!(ts["type"].as_str().unwrap(), "local", "type should be local");

    let command: Vec<&str> = ts["command"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert_eq!(
        command,
        vec!["/usr/local/bin/tokensave", "serve"],
        "command should be [bin, \"serve\"]"
    );
}

#[test]
fn test_install_creates_opencode_md_with_rules() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    let prompt_path = opencode_prompt_path(home);
    assert!(prompt_path.exists(), "OPENCODE.md should be created");

    let content = std::fs::read_to_string(&prompt_path).unwrap();
    assert!(
        content.contains("## Prefer tokensave MCP tools"),
        "OPENCODE.md should contain the tokensave rules marker"
    );
    assert!(
        content.contains("tokensave_context"),
        "OPENCODE.md should mention tokensave tools"
    );
}

#[test]
fn test_install_preserves_existing_opencode_json() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Pre-populate opencode.json with existing content
    let config_path = opencode_config_path(home);
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(
        &config_path,
        r#"{"theme": "dark", "mcp": {"other-tool": {"type": "local", "command": ["other"]}}}"#,
    )
    .unwrap();

    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    let config = read_json(&config_path);
    assert_eq!(
        config["theme"].as_str().unwrap(),
        "dark",
        "existing settings should be preserved"
    );
    assert!(
        config["mcp"]["other-tool"].is_object(),
        "existing MCP server should be preserved"
    );
    assert!(
        config["mcp"]["tokensave"].is_object(),
        "tokensave should be added"
    );
}

#[test]
fn test_install_idempotent_opencode_json() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);

    OpenCodeIntegration.install(&ctx).unwrap();
    OpenCodeIntegration.install(&ctx).unwrap();

    let config = read_json(&opencode_config_path(home));
    let mcp = config["mcp"].as_object().unwrap();
    let ts_count = mcp.keys().filter(|k| *k == "tokensave").count();
    assert_eq!(ts_count, 1, "tokensave should appear exactly once");
}

#[test]
fn test_install_idempotent_opencode_md() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);

    OpenCodeIntegration.install(&ctx).unwrap();
    OpenCodeIntegration.install(&ctx).unwrap();

    let prompt_path = opencode_prompt_path(home);
    let content = std::fs::read_to_string(&prompt_path).unwrap();
    let marker = "## Prefer tokensave MCP tools";
    let count = content.matches(marker).count();
    assert_eq!(
        count, 1,
        "marker should appear exactly once after double install, found {count}"
    );
}

#[test]
fn test_install_preserves_existing_opencode_md_content() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Create OPENCODE.md with pre-existing content
    let config_dir = home.join(".config/opencode");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("OPENCODE.md"),
        "## My Custom Rules\n\nAlways use TypeScript.\n",
    )
    .unwrap();

    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    let content = std::fs::read_to_string(config_dir.join("OPENCODE.md")).unwrap();
    assert!(
        content.contains("My Custom Rules"),
        "existing content should be preserved"
    );
    assert!(
        content.contains("Prefer tokensave MCP tools"),
        "tokensave rules should be appended"
    );
}

// ===========================================================================
// Uninstall verification
// ===========================================================================

#[test]
fn test_uninstall_removes_mcp_from_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);

    OpenCodeIntegration.install(&ctx).unwrap();
    OpenCodeIntegration.uninstall(&ctx).unwrap();

    let config_path = opencode_config_path(home);
    // When tokensave was the only content, file should be removed entirely
    if config_path.exists() {
        let config = read_json(&config_path);
        let has_tokensave = config
            .get("mcp")
            .and_then(|v| v.get("tokensave"))
            .is_some();
        assert!(!has_tokensave, "mcp.tokensave should be removed");
    }
}

#[test]
fn test_uninstall_removes_empty_config_file() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);

    OpenCodeIntegration.install(&ctx).unwrap();
    OpenCodeIntegration.uninstall(&ctx).unwrap();

    let config_path = opencode_config_path(home);
    // Since tokensave was the only entry, the file should be deleted
    assert!(
        !config_path.exists(),
        "opencode.json should be deleted when empty"
    );
}

#[test]
fn test_uninstall_preserves_other_mcp_servers() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Pre-populate with another server
    let config_path = opencode_config_path(home);
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(
        &config_path,
        r#"{"mcp": {"other-tool": {"type": "local", "command": ["other"]}}}"#,
    )
    .unwrap();

    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();
    OpenCodeIntegration.uninstall(&ctx).unwrap();

    assert!(config_path.exists(), "config should still exist with other servers");
    let config = read_json(&config_path);
    assert!(
        config["mcp"]["other-tool"].is_object(),
        "other server should be preserved"
    );
    let has_tokensave = config
        .get("mcp")
        .and_then(|v| v.get("tokensave"))
        .is_some();
    assert!(!has_tokensave, "tokensave should be removed");
}

#[test]
fn test_uninstall_removes_opencode_md_rules() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);

    OpenCodeIntegration.install(&ctx).unwrap();
    let prompt_path = opencode_prompt_path(home);
    assert!(prompt_path.exists());

    OpenCodeIntegration.uninstall(&ctx).unwrap();

    // OPENCODE.md had only tokensave rules, should be removed
    if prompt_path.exists() {
        let content = std::fs::read_to_string(&prompt_path).unwrap();
        assert!(
            !content.contains("Prefer tokensave MCP tools"),
            "OPENCODE.md should not contain tokensave rules after uninstall"
        );
    }
}

#[test]
fn test_uninstall_preserves_other_opencode_md_content() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Create OPENCODE.md with pre-existing content
    let config_dir = home.join(".config/opencode");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("OPENCODE.md"),
        "## My Custom Rules\n\nAlways use TypeScript.\n",
    )
    .unwrap();

    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();
    OpenCodeIntegration.uninstall(&ctx).unwrap();

    let prompt_path = config_dir.join("OPENCODE.md");
    assert!(prompt_path.exists(), "OPENCODE.md should still exist");
    let content = std::fs::read_to_string(&prompt_path).unwrap();
    assert!(
        content.contains("My Custom Rules"),
        "custom content should be preserved"
    );
    assert!(
        !content.contains("Prefer tokensave MCP tools"),
        "tokensave rules should be removed"
    );
}

#[test]
fn test_uninstall_without_install_does_not_crash() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    // Should not panic or error
    OpenCodeIntegration.uninstall(&ctx).unwrap();
}

#[test]
fn test_uninstall_config_with_no_tokensave_is_noop() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Create opencode.json without tokensave
    let config_path = opencode_config_path(home);
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(
        &config_path,
        r#"{"mcp": {"something-else": {"type": "local", "command": ["x"]}}}"#,
    )
    .unwrap();

    let ctx = make_ctx(home);
    OpenCodeIntegration.uninstall(&ctx).unwrap();

    // File should remain with existing content
    let config = read_json(&config_path);
    assert!(config["mcp"]["something-else"].is_object());
}

// ===========================================================================
// Healthcheck verification
// ===========================================================================

#[test]
fn test_healthcheck_clean_install_no_issues() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    OpenCodeIntegration.healthcheck(&mut dc, &hctx);
    assert_eq!(dc.issues, 0, "clean OpenCode install should have no issues");
}

#[test]
fn test_healthcheck_missing_config_produces_warnings() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    OpenCodeIntegration.healthcheck(&mut dc, &hctx);
    assert!(
        dc.warnings > 0 || dc.issues > 0,
        "healthcheck on empty dir should report warnings or issues"
    );
}

#[test]
fn test_healthcheck_detects_missing_mcp_entry() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Create opencode.json without tokensave
    let config_path = opencode_config_path(home);
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(&config_path, r#"{"theme": "dark"}"#).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    OpenCodeIntegration.healthcheck(&mut dc, &hctx);
    assert!(
        dc.issues > 0,
        "healthcheck should detect missing MCP entry"
    );
}

#[test]
fn test_healthcheck_detects_missing_serve_arg() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Create opencode.json with tokensave but no "serve" in command
    let config_path = opencode_config_path(home);
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(
        &config_path,
        r#"{"mcp": {"tokensave": {"type": "local", "command": ["/usr/local/bin/tokensave"]}}}"#,
    )
    .unwrap();

    // Also create OPENCODE.md so the prompt check passes
    let prompt_path = opencode_prompt_path(home);
    std::fs::write(&prompt_path, "## Prefer tokensave MCP tools\ntokensave rules here\n").unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    OpenCodeIntegration.healthcheck(&mut dc, &hctx);
    assert!(
        dc.issues > 0,
        "healthcheck should detect missing 'serve' in command array"
    );
}

#[test]
fn test_healthcheck_detects_missing_opencode_md() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    // Delete OPENCODE.md
    let prompt_path = opencode_prompt_path(home);
    std::fs::remove_file(&prompt_path).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    OpenCodeIntegration.healthcheck(&mut dc, &hctx);
    assert!(
        dc.warnings > 0,
        "healthcheck should warn about missing OPENCODE.md"
    );
}

#[test]
fn test_healthcheck_detects_missing_tokensave_rules_in_opencode_md() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    // Overwrite OPENCODE.md without any mention of tokensave
    let prompt_path = opencode_prompt_path(home);
    std::fs::write(&prompt_path, "## Some other content\n\nGeneric rules only.\n").unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    OpenCodeIntegration.healthcheck(&mut dc, &hctx);
    assert!(
        dc.issues > 0,
        "healthcheck should detect missing tokensave rules in OPENCODE.md"
    );
}

// ===========================================================================
// is_detected / has_tokensave
// ===========================================================================

#[test]
fn test_is_detected_empty_home() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(
        !OpenCodeIntegration.is_detected(home),
        "should not be detected on empty home"
    );
}

#[test]
fn test_is_detected_with_opencode_dir() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    std::fs::create_dir_all(home.join(".config/opencode")).unwrap();
    assert!(
        OpenCodeIntegration.is_detected(home),
        "should be detected when .config/opencode exists"
    );
}

#[test]
fn test_has_tokensave_before_install() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(
        !OpenCodeIntegration.has_tokensave(home),
        "has_tokensave should be false before install"
    );
}

#[test]
fn test_has_tokensave_after_install() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();
    assert!(
        OpenCodeIntegration.has_tokensave(home),
        "has_tokensave should be true after install"
    );
}

#[test]
fn test_has_tokensave_after_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();
    OpenCodeIntegration.uninstall(&ctx).unwrap();
    assert!(
        !OpenCodeIntegration.has_tokensave(home),
        "has_tokensave should be false after uninstall"
    );
}

#[test]
fn test_has_tokensave_with_config_but_no_mcp() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Create opencode.json without mcp section
    let config_path = opencode_config_path(home);
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(&config_path, r#"{"theme": "dark"}"#).unwrap();

    assert!(
        !OpenCodeIntegration.has_tokensave(home),
        "has_tokensave should be false when mcp section is missing"
    );
}

// ===========================================================================
// Name / ID
// ===========================================================================

#[test]
fn test_name_and_id() {
    assert_eq!(OpenCodeIntegration.name(), "OpenCode");
    assert_eq!(OpenCodeIntegration.id(), "opencode");
}