tokensave 7.2.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// Rust guideline compliant 2026-07-02
//! Factory Droid agent integration.
//!
//! Handles registration of the tokensave MCP server in Factory Droid's MCP
//! config (`~/.factory/mcp.json` globally, `<project>/.factory/mcp.json` for
//! `--local`) under the `mcpServers.tokensave` key, prompt rules via
//! `AGENTS.md` (`~/.factory/AGENTS.md` globally, `<project>/AGENTS.md` for
//! `--local`), and the `PreToolUse` guardrail hook in Factory's `hooks`
//! object (`~/.factory/settings.json` globally, `<project>/.factory/settings.json`
//! for `--local` — the same file Factory's own `Stop`/`Notification`/
//! `PreToolUse`/`UserPromptSubmit` wrappers live in, per the live-config
//! verification in Factory's public hook docs; this is a separate
//! file from `mcp.json`). Droid blocks a tool call via **exit code 2 +
//! stderr** — the same mechanism as Kiro's `preToolUse` hook, not Claude
//! Code's stdout JSON decision.

use std::io::Write;
use std::path::{Path, PathBuf};

use serde_json::json;

use crate::errors::{Result, TokenSaveError};

use super::{
    backup_and_write_json, backup_config_file, load_json_file, load_json_file_strict,
    safe_write_json_file, AgentIntegration, DoctorCounters, HealthcheckContext, InstallContext,
    InstallScope,
};

/// Factory Droid agent.
pub struct DroidIntegration;

/// Hook event name under `settings.json`'s `hooks` object that Droid fires
/// before a tool call executes.
const DROID_PRE_TOOL_EVENT: &str = "PreToolUse";

/// The `Execute` tool is Droid's confirmed shell tool — the only tool name we
/// register a matcher for. The sub-agent/task launch tool name is
/// unconfirmed in Factory's public docs, so we
/// deliberately do not guess a matcher for it: an unmatched tool never
/// reaches our hook subprocess at all, which is the safest form of
/// "fail open" for a tool name we can't verify.
const DROID_HOOK_MATCHER: &str = "Execute";

/// Subcommand invoked by the installed hook.
const DROID_PRE_TOOL_HOOK: &str = "hook-droid-pre-tool-use";

impl AgentIntegration for DroidIntegration {
    fn name(&self) -> &'static str {
        "Factory Droid"
    }

    fn id(&self) -> &'static str {
        "droid"
    }

    fn supports_local(&self) -> bool {
        true
    }

    fn install(&self, ctx: &InstallContext) -> Result<()> {
        let mcp_path = droid_mcp_path_for(ctx);
        install_mcp_server(&mcp_path, &ctx.tokensave_bin)?;

        let agents_md = droid_agents_md_for(ctx);
        install_prompt_rules(&agents_md)?;

        let settings_path = droid_settings_path_for(ctx);
        install_hook(&settings_path, &ctx.tokensave_bin)?;

        eprintln!();
        eprintln!("Setup complete. Next steps:");
        eprintln!("  1. cd into your project and run: tokensave init");
        eprintln!("  2. Start a new droid session — tokensave tools are now available");
        Ok(())
    }

    fn uninstall(&self, ctx: &InstallContext) -> Result<()> {
        let mcp_path = droid_mcp_path_for(ctx);
        uninstall_mcp_server(&mcp_path);

        let agents_md = droid_agents_md_for(ctx);
        uninstall_prompt_rules(&agents_md);

        let settings_path = droid_settings_path_for(ctx);
        uninstall_hook(&settings_path);

        eprintln!();
        eprintln!("Uninstall complete. Tokensave has been removed from Factory Droid.");
        eprintln!("Start a new droid session for changes to take effect.");
        Ok(())
    }

    fn healthcheck(&self, dc: &mut DoctorCounters, ctx: &HealthcheckContext) {
        eprintln!("\n\x1b[1mFactory Droid integration\x1b[0m");
        doctor_check_config(dc, &ctx.home);
        doctor_check_prompt(dc, &ctx.home);
        doctor_check_hook(dc, &ctx.home);
    }

    fn is_detected(&self, home: &Path) -> bool {
        home.join(".factory").is_dir()
    }

    fn primary_config_path(&self, home: &Path) -> Option<PathBuf> {
        Some(droid_mcp_path(home))
    }

    fn has_tokensave(&self, home: &Path) -> bool {
        let mcp_path = droid_mcp_path(home);
        if !mcp_path.exists() {
            return false;
        }
        let json = load_json_file(&mcp_path);
        json.get("mcpServers")
            .and_then(|v| v.get("tokensave"))
            .is_some()
    }
}

// ---------------------------------------------------------------------------
// Config path resolution
// ---------------------------------------------------------------------------

/// Global Factory Droid MCP config path (`~/.factory/mcp.json`).
fn droid_mcp_path(home: &Path) -> PathBuf {
    home.join(".factory/mcp.json")
}

/// mcp.json path for this install: `~/.factory/mcp.json` globally, or
/// `<project>/.factory/mcp.json` for `--local` (same relative layout).
fn droid_mcp_path_for(ctx: &InstallContext) -> PathBuf {
    ctx.base_dir().join(".factory/mcp.json")
}

/// AGENTS.md path for this install: `~/.factory/AGENTS.md` globally, or
/// `<project>/AGENTS.md` for `--local` (Factory reads a repo-root AGENTS.md).
fn droid_agents_md_for(ctx: &InstallContext) -> PathBuf {
    match &ctx.scope {
        InstallScope::Global => ctx.home.join(".factory/AGENTS.md"),
        InstallScope::Local { project_path } => project_path.join("AGENTS.md"),
    }
}

/// Global Factory Droid settings path (`~/.factory/settings.json`) — the file
/// Factory reads its `hooks` object from.
fn droid_settings_path(home: &Path) -> PathBuf {
    home.join(".factory/settings.json")
}

/// settings.json path for this install: `~/.factory/settings.json` globally,
/// or `<project>/.factory/settings.json` for `--local` (same relative layout
/// as `mcp.json`).
fn droid_settings_path_for(ctx: &InstallContext) -> PathBuf {
    ctx.base_dir().join(".factory/settings.json")
}

// ---------------------------------------------------------------------------
// Install helpers
// ---------------------------------------------------------------------------

/// Register MCP server in mcp.json.
///
/// Safety: creates a `.bak` backup before writing and restores it on any
/// error. Uses strict JSON parsing so an existing file with invalid syntax
/// is never silently replaced with an empty object.
fn install_mcp_server(mcp_path: &Path, tokensave_bin: &str) -> Result<()> {
    if let Some(parent) = mcp_path.parent() {
        std::fs::create_dir_all(parent).ok();
    }

    let backup = backup_config_file(mcp_path)?;
    let mut settings = match load_json_file_strict(mcp_path) {
        Ok(v) => v,
        Err(e) => {
            if let Some(ref b) = backup {
                eprintln!("  Backup preserved at: {}", b.display());
            }
            return Err(e);
        }
    };

    let bin = crate::agents::preserve_mcp_command(
        settings.pointer("/mcpServers/tokensave/command"),
        tokensave_bin,
    );
    settings["mcpServers"]["tokensave"] = json!({
        "type": "stdio",
        "command": bin,
        "args": ["serve"]
    });

    safe_write_json_file(mcp_path, &settings, backup.as_deref())?;
    eprintln!(
        "\x1b[32m✔\x1b[0m Added tokensave MCP server to {}",
        mcp_path.display()
    );
    Ok(())
}

/// Append prompt rules to AGENTS.md (idempotent).
fn install_prompt_rules(agents_md: &Path) -> Result<()> {
    let marker = "## Prefer tokensave MCP tools";
    let existing = if agents_md.exists() {
        std::fs::read_to_string(agents_md).unwrap_or_default()
    } else {
        String::new()
    };
    if existing.contains(marker) {
        eprintln!("  AGENTS.md already contains tokensave rules, skipping");
        return Ok(());
    }
    if let Some(parent) = agents_md.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(agents_md)
        .map_err(|e| TokenSaveError::Config {
            message: format!("failed to open AGENTS.md: {e}"),
        })?;
    write!(
        f,
        "\n{marker}\n\n\
        Before reading source files or scanning the codebase, use the tokensave MCP tools \
        (`tokensave_context`, `tokensave_search`, `tokensave_callers`, `tokensave_callees`, \
        `tokensave_impact`, `tokensave_node`, `tokensave_files`, `tokensave_affected`). \
        They provide instant semantic results from a pre-built knowledge graph and are \
        faster than file reads.\n\n\
        If a code analysis question cannot be fully answered by tokensave MCP tools, \
        try querying the SQLite database directly at `.tokensave/tokensave.db` \
        (tables: `nodes`, `edges`, `files`). Use SQL to answer complex structural queries \
        that go beyond what the built-in tools expose.\n\n\
        If you discover a gap where an extractor, schema, or tokensave tool could be \
        improved to answer a question natively, propose to the user that they open an issue \
        at https://github.com/aovestdipaperino/tokensave describing the limitation. \
        **Remind the user to strip any sensitive or proprietary code from the bug description \
        before submitting.**\n"
    )
    .ok();
    eprintln!(
        "\x1b[32m✔\x1b[0m Appended tokensave rules to {}",
        agents_md.display()
    );
    Ok(())
}

/// Build the command string for a Droid hook entry: `<tokensave_bin> <subcommand>`
/// as a single string, matching the shape already confirmed live in
/// `~/.factory/settings.json` (Factory's own hook wrappers there use a bare
/// `command` string with no `args` array). This mirrors the Kiro adapter,
/// which makes the same choice for the same reason.
fn hook_command(tokensave_bin: &str, subcommand: &str) -> String {
    format!("{tokensave_bin} {subcommand}")
}

/// Extract the `command` string from a Droid hook wrapper entry (the object
/// holding `{"matcher": ..., "hooks": [{"type": "command", "command": ...}]}`).
/// Returns the first inner command.
fn droid_hook_entry_command(entry: &serde_json::Value) -> Option<&str> {
    entry
        .get("hooks")?
        .as_array()?
        .iter()
        .find_map(|c| c.get("command").and_then(|v| v.as_str()))
}

/// Install the `PreToolUse` guardrail hook into `settings.json`'s `hooks`
/// object (idempotent), preserving every other key — including hook wrappers
/// Factory or other tools already installed (e.g. the owner's own
/// `PreToolUse` permission wrapper). Adds a new array entry under the
/// `Execute` matcher rather than touching any existing entry.
fn install_hook(settings_path: &Path, tokensave_bin: &str) -> Result<()> {
    if let Some(parent) = settings_path.parent() {
        std::fs::create_dir_all(parent).ok();
    }

    let backup = backup_config_file(settings_path)?;
    let mut settings = match load_json_file_strict(settings_path) {
        Ok(v) => v,
        Err(e) => {
            if let Some(ref b) = backup {
                eprintln!("  Backup preserved at: {}", b.display());
            }
            return Err(e);
        }
    };

    let hooks_arr = settings["hooks"][DROID_PRE_TOOL_EVENT]
        .as_array()
        .cloned()
        .unwrap_or_default();

    let has_hook = hooks_arr.iter().any(|entry| {
        entry.get("matcher").and_then(|v| v.as_str()) == Some(DROID_HOOK_MATCHER)
            && droid_hook_entry_command(entry).is_some_and(|c| c.contains("tokensave"))
    });

    if has_hook {
        eprintln!("  {DROID_PRE_TOOL_EVENT} hook already present, skipping");
        return Ok(());
    }

    let mut new_hooks = hooks_arr;
    new_hooks.push(json!({
        "matcher": DROID_HOOK_MATCHER,
        "hooks": [{
            "type": "command",
            "command": hook_command(tokensave_bin, DROID_PRE_TOOL_HOOK),
        }]
    }));
    settings["hooks"][DROID_PRE_TOOL_EVENT] = serde_json::Value::Array(new_hooks);

    safe_write_json_file(settings_path, &settings, backup.as_deref())?;
    eprintln!(
        "\x1b[32m✔\x1b[0m Added tokensave PreToolUse hook to {}",
        settings_path.display()
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// Uninstall helpers
// ---------------------------------------------------------------------------

/// Remove the tokensave MCP server entry from mcp.json.
fn uninstall_mcp_server(mcp_path: &Path) {
    if !mcp_path.exists() {
        eprintln!("  {} not found, skipping", mcp_path.display());
        return;
    }

    let Ok(contents) = std::fs::read_to_string(mcp_path) else {
        return;
    };
    let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(&contents) else {
        return;
    };

    let Some(servers) = settings
        .get_mut("mcpServers")
        .and_then(|v| v.as_object_mut())
    else {
        eprintln!(
            "  No tokensave MCP server in {}, skipping",
            mcp_path.display()
        );
        return;
    };

    if servers.remove("tokensave").is_none() {
        eprintln!(
            "  No tokensave MCP server in {}, skipping",
            mcp_path.display()
        );
        return;
    }

    let is_empty = settings.as_object().is_some_and(|o| {
        o.iter()
            .all(|(k, v)| k == "mcpServers" && v.as_object().is_some_and(serde_json::Map::is_empty))
    });

    if is_empty {
        std::fs::remove_file(mcp_path).ok();
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed {} (was empty)",
            mcp_path.display()
        );
    } else if backup_and_write_json(mcp_path, &settings) {
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed tokensave MCP server from {}",
            mcp_path.display()
        );
    }
}

/// Remove tokensave rules from AGENTS.md.
fn uninstall_prompt_rules(agents_md: &Path) {
    if !agents_md.exists() {
        return;
    }
    let Ok(contents) = std::fs::read_to_string(agents_md) else {
        return;
    };
    if !contents.contains("tokensave") {
        eprintln!("  AGENTS.md does not contain tokensave rules, skipping");
        return;
    }
    let marker = "## Prefer tokensave MCP tools";
    let Some(start) = contents.find(marker) else {
        return;
    };
    let after_marker = start + marker.len();
    let end = contents[after_marker..]
        .find("\n## ")
        .map_or(contents.len(), |pos| after_marker + pos);
    let mut new_contents = String::new();
    new_contents.push_str(contents[..start].trim_end());
    let remainder = &contents[end..];
    if !remainder.is_empty() {
        new_contents.push_str("\n\n");
        new_contents.push_str(remainder.trim_start());
    }
    let new_contents = new_contents.trim().to_string();
    if new_contents.is_empty() {
        std::fs::remove_file(agents_md).ok();
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed {} (was empty)",
            agents_md.display()
        );
    } else {
        std::fs::write(agents_md, format!("{new_contents}\n")).ok();
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed tokensave rules from {}",
            agents_md.display()
        );
    }
}

/// Remove only tokensave's `PreToolUse` hook entry from `settings.json`,
/// preserving every other key — including hook wrappers Factory or other
/// tools installed under the same or other events.
fn uninstall_hook(settings_path: &Path) {
    if !settings_path.exists() {
        eprintln!("  {} not found, skipping", settings_path.display());
        return;
    }
    let Ok(contents) = std::fs::read_to_string(settings_path) else {
        return;
    };
    let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(&contents) else {
        return;
    };

    let Some(arr) = settings["hooks"][DROID_PRE_TOOL_EVENT].as_array().cloned() else {
        eprintln!(
            "  No tokensave PreToolUse hook in {}, skipping",
            settings_path.display()
        );
        return;
    };

    let original_len = arr.len();
    let filtered: Vec<serde_json::Value> = arr
        .into_iter()
        .filter(|entry| {
            !(entry.get("matcher").and_then(|v| v.as_str()) == Some(DROID_HOOK_MATCHER)
                && droid_hook_entry_command(entry).is_some_and(|c| c.contains("tokensave")))
        })
        .collect();

    if filtered.len() == original_len {
        eprintln!(
            "  No tokensave PreToolUse hook in {}, skipping",
            settings_path.display()
        );
        return;
    }

    if filtered.is_empty() {
        if let Some(hooks) = settings.get_mut("hooks").and_then(|v| v.as_object_mut()) {
            hooks.remove(DROID_PRE_TOOL_EVENT);
            if hooks.is_empty() {
                settings.as_object_mut().map(|o| o.remove("hooks"));
            }
        }
    } else {
        settings["hooks"][DROID_PRE_TOOL_EVENT] = serde_json::Value::Array(filtered);
    }

    let is_empty = settings.as_object().is_some_and(serde_json::Map::is_empty);
    if is_empty {
        std::fs::remove_file(settings_path).ok();
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed {} (was empty)",
            settings_path.display()
        );
    } else if backup_and_write_json(settings_path, &settings) {
        eprintln!(
            "\x1b[32m✔\x1b[0m Removed tokensave PreToolUse hook from {}",
            settings_path.display()
        );
    }
}

// ---------------------------------------------------------------------------
// Healthcheck helpers
// ---------------------------------------------------------------------------

/// Check mcp.json has tokensave registered.
fn doctor_check_config(dc: &mut DoctorCounters, home: &Path) {
    let mcp_path = droid_mcp_path(home);
    if !mcp_path.exists() {
        dc.warn(&format!(
            "{} not found — run `tokensave install --agent droid` if you use Factory Droid",
            mcp_path.display()
        ));
        return;
    }

    let config = load_json_file(&mcp_path);
    let mcp_entry = config.get("mcpServers").and_then(|v| v.get("tokensave"));
    if mcp_entry.and_then(|v| v.as_object()).is_none() {
        dc.fail(&format!(
            "MCP server NOT registered in {} — run `tokensave install --agent droid`",
            mcp_path.display()
        ));
        return;
    }
    dc.pass(&format!("MCP server registered in {}", mcp_path.display()));

    let args = mcp_entry
        .and_then(|v| v.get("args"))
        .and_then(|v| v.as_array());
    let has_serve = args.is_some_and(|arr| arr.iter().any(|v| v.as_str() == Some("serve")));
    if has_serve {
        dc.pass("MCP server args include \"serve\"");
    } else {
        dc.fail("MCP server args missing \"serve\" — run `tokensave install --agent droid`");
    }
}

/// Check AGENTS.md contains tokensave rules.
fn doctor_check_prompt(dc: &mut DoctorCounters, home: &Path) {
    let agents_md = home.join(".factory/AGENTS.md");
    if agents_md.exists() {
        let has_rules = std::fs::read_to_string(&agents_md)
            .unwrap_or_default()
            .contains("tokensave");
        if has_rules {
            dc.pass("AGENTS.md contains tokensave rules");
        } else {
            dc.fail("AGENTS.md missing tokensave rules — run `tokensave install --agent droid`");
        }
    } else {
        dc.warn("AGENTS.md does not exist");
    }
}

/// Check settings.json has the tokensave `PreToolUse` guardrail hook.
fn doctor_check_hook(dc: &mut DoctorCounters, home: &Path) {
    let path = droid_settings_path(home);
    if !path.exists() {
        dc.warn(&format!(
            "{} not found — run `tokensave install --agent droid` if you use Factory Droid",
            path.display()
        ));
        return;
    }

    let config = load_json_file(&path);
    let hook = config
        .get("hooks")
        .and_then(|v| v.get(DROID_PRE_TOOL_EVENT))
        .and_then(|v| v.as_array())
        .and_then(|arr| {
            arr.iter().find(|entry| {
                entry.get("matcher").and_then(|v| v.as_str()) == Some(DROID_HOOK_MATCHER)
                    && droid_hook_entry_command(entry).is_some_and(|c| c.contains("tokensave"))
            })
        });

    let Some(hook) = hook else {
        dc.fail(&format!(
            "PreToolUse hook NOT installed in {} — run `tokensave install --agent droid`",
            path.display()
        ));
        return;
    };

    dc.pass(&format!("PreToolUse hook installed in {}", path.display()));

    let command = droid_hook_entry_command(hook).unwrap_or("");
    let bin = command.split_whitespace().next().unwrap_or("");
    if bin.is_empty() {
        return;
    }
    if Path::new(bin).exists() {
        dc.pass(&format!("Hook binary exists: {bin}"));
    } else {
        dc.warn(&format!(
            "Hook binary not found: {bin} — run `tokensave install --agent droid`"
        ));
    }
}