visdom-cli 1.1.0

Visdom developer CLI: checks a project's Visdom wiring and launches the coding agent
Documentation
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
//! Asking for what `visdom init` was not told on the command line. Only ever
//! used when both stdin and stderr are a terminal; without one, init behaves
//! as if nothing could be asked and says what to pass instead.

use std::io::{BufRead, IsTerminal, Write};
use std::path::Path;

use tracevault_cli::agent::Agent;

use crate::mode::TracingMode;

/// Whether there is somebody to ask.
pub fn is_interactive() -> bool {
    std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
}

/// Print `question` and read one line, trimmed. `None` at end of input.
fn ask_line(question: &str) -> Option<String> {
    eprint!("{question} ");
    let _ = std::io::stderr().flush();
    let mut line = String::new();
    match std::io::stdin().lock().read_line(&mut line) {
        Ok(0) | Err(_) => None,
        Ok(_) => Some(line.trim().to_string()),
    }
}

/// The agent an answer names: its number in the list, or its name. An empty
/// answer takes the default, Claude Code. `None` when it names neither.
pub fn parse_agent_choice(answer: &str) -> Option<Agent> {
    match answer.trim().to_ascii_lowercase().as_str() {
        "" | "1" | "claude" | "claude-code" => Some(Agent::ClaudeCode),
        "2" | "codex" => Some(Agent::Codex),
        _ => None,
    }
}

/// Ask which agent to set up. End of input takes the default.
pub fn ask_agent() -> Agent {
    loop {
        let Some(answer) = ask_line("Which agent? [1] Claude Code  [2] Codex  (default 1):") else {
            return Agent::ClaudeCode;
        };
        match parse_agent_choice(&answer) {
            Some(agent) => return agent,
            None => eprintln!("Answer 1 or 2."),
        }
    }
}

/// What `visdom init` sets up.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InitScope {
    /// The repository `visdom init` is run in.
    Repo,
    /// Every session of the agent on this machine (`--global`).
    Machine,
    /// The directory `visdom init` is run in, as a folder of checkouts
    /// recorded to one project (`--workspace`).
    Workspace,
}

/// The scope an answer names: its number in the list, or its name. An empty
/// answer takes `default`. `None` when it names none.
pub fn parse_scope_choice(answer: &str, default: InitScope) -> Option<InitScope> {
    match answer.trim().to_ascii_lowercase().as_str() {
        "" => Some(default),
        "1" | "repo" | "repository" => Some(InitScope::Repo),
        "2" | "machine" | "global" => Some(InitScope::Machine),
        "3" | "workspace" | "folder" => Some(InitScope::Workspace),
        _ => None,
    }
}

/// Ask what to set up. `None` at end of input: nothing chosen.
pub fn ask_scope(default: InitScope) -> Option<InitScope> {
    let number = match default {
        InitScope::Repo => 1,
        InitScope::Machine => 2,
        InitScope::Workspace => 3,
    };
    eprintln!("What should visdom set up?");
    eprintln!("  [1] this repository");
    eprintln!("  [2] every session on this machine");
    eprintln!("  [3] this folder of checkouts, recorded to one project (a workspace)");
    loop {
        let answer = ask_line(&format!("Number (default {number}):"))?;
        match parse_scope_choice(&answer, default) {
            Some(scope) => return Some(scope),
            None => eprintln!("Answer 1, 2 or 3."),
        }
    }
}

/// Ask for a line of text; `None` when nothing was typed.
pub fn ask_text(question: &str) -> Option<String> {
    ask_line(question).filter(|answer| !answer.is_empty())
}

/// The mode an answer names: its number in the list, or its name. An empty
/// answer takes the default, hooks. `None` when it names neither.
pub fn parse_mode_choice(answer: &str) -> Option<TracingMode> {
    match answer.trim().to_ascii_lowercase().as_str() {
        "" | "1" | "hooks" => Some(TracingMode::Hooks),
        "2" | "gateway" => Some(TracingMode::Gateway),
        _ => None,
    }
}

/// Ask how sessions should be traced. `None` at end of input: nothing chosen.
pub fn ask_mode() -> Option<TracingMode> {
    loop {
        let answer = ask_line(
            "How should your sessions be traced? [1] hooks  [2] through the AI Gateway  (default 1):",
        )?;
        match parse_mode_choice(&answer) {
            Some(mode) => return Some(mode),
            None => eprintln!("Answer 1 or 2."),
        }
    }
}

/// The entry of a list of `count` an answer names by its number, from 1.
pub fn parse_choice(answer: &str, count: usize) -> Option<usize> {
    let n: usize = answer.trim().parse().ok()?;
    (1..=count).contains(&n).then(|| n - 1)
}

/// Ask for one of `options`. `None` at end of input, or with nothing to
/// choose from.
pub fn ask_choice(question: &str, options: &[String]) -> Option<usize> {
    if options.is_empty() {
        return None;
    }
    eprintln!("{question}");
    for (i, option) in options.iter().enumerate() {
        eprintln!("  [{}] {option}", i + 1);
    }
    loop {
        let answer = ask_line("Number:")?;
        match parse_choice(&answer, options.len()) {
            Some(index) => return Some(index),
            None => eprintln!("Answer a number from 1 to {}.", options.len()),
        }
    }
}

/// What a typed URL answer means.
#[derive(Debug, PartialEq, Eq)]
pub enum UrlAnswer {
    Url(String),
    /// Nothing typed.
    Skipped,
    Invalid,
}

/// A bare host is taken as https; anything that is then not an absolute
/// http(s) URL is invalid.
pub fn parse_url_answer(answer: &str) -> UrlAnswer {
    let answer = answer.trim();
    if answer.is_empty() {
        return UrlAnswer::Skipped;
    }
    if answer.starts_with('-') {
        return UrlAnswer::Invalid;
    }
    let candidate = if answer.contains("://") {
        answer.to_string()
    } else {
        format!("https://{answer}")
    };
    if crate::components::bazaar::is_http_url(&candidate) {
        UrlAnswer::Url(candidate.trim_end_matches('/').to_string())
    } else {
        UrlAnswer::Invalid
    }
}

/// Ask for a URL until one is given or the question is skipped (Enter, or
/// end of input).
pub fn ask_url(question: &str) -> Option<String> {
    loop {
        match parse_url_answer(&ask_line(question)?) {
            UrlAnswer::Url(url) => return Some(url),
            UrlAnswer::Skipped => return None,
            UrlAnswer::Invalid => eprintln!("That is not an http(s) URL."),
        }
    }
}

/// Record `bazaar_url` in the user config at `path`, creating the file if
/// needed and leaving everything else in it as it is.
pub fn save_bazaar_url(path: &Path, url: &str) -> Result<(), String> {
    save_user_setting(path, "bazaar_url", url)
}

/// Record `tracing_mode` in the user config at `path`, the same way.
pub fn save_tracing_mode(path: &Path, mode: TracingMode) -> Result<(), String> {
    save_user_setting(path, "tracing_mode", mode.name())
}

/// Record `key` under `[gateway]` in the user config at `path`, creating the
/// file if needed. A file with no `[gateway]` table gets one at its end and
/// is otherwise kept byte for byte; one that has it is rewritten from its
/// parsed form.
pub fn save_gateway_setting(path: &Path, key: &str, value: &str) -> Result<(), String> {
    let existing = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
    };
    let mut table: toml::Table =
        toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
    let value = toml::Value::String(value.to_string());
    let updated = match table.get_mut("gateway") {
        Some(toml::Value::Table(gateway)) => {
            // The same setting under its other spelling (`claude-code-model`)
            // would make the file name it twice, and then not load at all.
            gateway.remove(&key.replace('_', "-"));
            gateway.insert(key.to_string(), value);
            toml::to_string(&table).map_err(|e| e.to_string())?
        }
        Some(_) => return Err(format!("`gateway` in {} is not a table", path.display())),
        None => {
            let gap = match existing.is_empty() || existing.ends_with("\n\n") {
                true => "",
                false if existing.ends_with('\n') => "\n",
                false => "\n\n",
            };
            format!("{existing}{gap}[gateway]\n{key} = {value}\n")
        }
    };
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)
            .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
    }
    std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
}

/// Set the top-level string `key` in the user config at `path`, creating the
/// file if needed and leaving everything else in it as it is.
fn save_user_setting(path: &Path, key: &str, value: &str) -> Result<(), String> {
    let existing = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
    };
    let mut table: toml::Table =
        toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
    let line = format!("{key} = {}\n", toml::Value::String(value.to_string()));
    let updated = if table.contains_key(key) {
        // Already there (empty, or it would not have been asked for): the
        // file is rewritten from its parsed form.
        table.insert(key.to_string(), toml::Value::String(value.to_string()));
        toml::to_string(&table).map_err(|e| e.to_string())?
    } else {
        // A top-level key must come before the first table: put it first, and
        // keep the rest of the file, comments included, byte for byte.
        format!("{line}{existing}")
    };
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)
            .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
    }
    std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::load_user_config_in;

    #[test]
    fn agent_choice_by_number_name_or_default() {
        assert_eq!(parse_agent_choice(""), Some(Agent::ClaudeCode));
        assert_eq!(parse_agent_choice("1"), Some(Agent::ClaudeCode));
        assert_eq!(parse_agent_choice(" Claude-Code "), Some(Agent::ClaudeCode));
        assert_eq!(parse_agent_choice("2"), Some(Agent::Codex));
        assert_eq!(parse_agent_choice("codex"), Some(Agent::Codex));
        assert_eq!(parse_agent_choice("3"), None);
        assert_eq!(parse_agent_choice("amp"), None);
    }

    #[test]
    fn mode_choice_by_number_name_or_default() {
        assert_eq!(parse_mode_choice(""), Some(TracingMode::Hooks));
        assert_eq!(parse_mode_choice("1"), Some(TracingMode::Hooks));
        assert_eq!(parse_mode_choice(" Gateway "), Some(TracingMode::Gateway));
        assert_eq!(parse_mode_choice("2"), Some(TracingMode::Gateway));
        assert_eq!(parse_mode_choice("3"), None);
        assert_eq!(parse_mode_choice("proxy"), None);
    }

    #[test]
    fn the_mode_is_saved_next_to_the_other_settings() {
        let tmp = tempfile::tempdir().unwrap();
        let path = crate::config::user_config_path_in(tmp.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let before = "agent = \"codex\"\n\n[gateway]\nproject = \"alpha\"\n";
        std::fs::write(&path, before).unwrap();
        save_tracing_mode(&path, TracingMode::Gateway).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            format!("tracing_mode = \"gateway\"\n{before}")
        );
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(user.tracing_mode, Some(TracingMode::Gateway));
        assert_eq!(user.agent, Some(Agent::Codex));
        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
        // Choosing again replaces it.
        save_tracing_mode(&path, TracingMode::Hooks).unwrap();
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(user.tracing_mode, Some(TracingMode::Hooks));
        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
    }

    #[test]
    fn scope_choice_by_number_name_or_default() {
        use InitScope::*;
        assert_eq!(parse_scope_choice("", Machine), Some(Machine));
        assert_eq!(parse_scope_choice("\n", Repo), Some(Repo));
        assert_eq!(parse_scope_choice("1", Machine), Some(Repo));
        assert_eq!(parse_scope_choice(" 2 ", Repo), Some(Machine));
        assert_eq!(parse_scope_choice("global", Repo), Some(Machine));
        assert_eq!(parse_scope_choice("3", Repo), Some(Workspace));
        assert_eq!(parse_scope_choice("Workspace", Repo), Some(Workspace));
        assert_eq!(parse_scope_choice("4", Repo), None);
        assert_eq!(parse_scope_choice("everything", Repo), None);
    }

    #[test]
    fn a_choice_is_a_number_of_the_list() {
        assert_eq!(parse_choice("1", 3), Some(0));
        assert_eq!(parse_choice(" 3\n", 3), Some(2));
        for answer in ["0", "4", "", "alpha", "-1"] {
            assert_eq!(parse_choice(answer, 3), None, "{answer}");
        }
    }

    #[test]
    fn a_gateway_setting_is_saved_without_touching_the_rest() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("visdom").join("config.toml");
        // A new file.
        save_gateway_setting(&path, "project", "alpha").unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "[gateway]\nproject = \"alpha\"\n"
        );
        // A second setting, and the first one replaced.
        save_gateway_setting(&path, "claude_code_model", "claude-sonnet").unwrap();
        save_gateway_setting(&path, "project", "beta").unwrap();
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(user.gateway.project.as_deref(), Some("beta"));
        assert_eq!(
            user.gateway.claude_code_model.as_deref(),
            Some("claude-sonnet")
        );

        // A file with no [gateway] keeps every byte, comments included.
        let before =
            "# mine\ntracing_mode = \"gateway\"\n\n[agents]\ncodex = \"cdx\" # local build";
        std::fs::write(&path, before).unwrap();
        save_gateway_setting(&path, "codex_model", "gpt-general").unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            after,
            format!("{before}\n\n[gateway]\ncodex_model = \"gpt-general\"\n")
        );
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(user.gateway.codex_model.as_deref(), Some("gpt-general"));
        assert_eq!(user.agents.codex.as_deref(), Some("cdx"));

        // The other spelling of a key is replaced, not doubled.
        std::fs::write(&path, "[gateway]\nclaude-code-model = \"\"\n").unwrap();
        save_gateway_setting(&path, "claude_code_model", "claude-sonnet").unwrap();
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(
            user.gateway.claude_code_model.as_deref(),
            Some("claude-sonnet")
        );

        // One that cannot be parsed is left alone.
        std::fs::write(&path, "[gateway\n").unwrap();
        assert!(save_gateway_setting(&path, "project", "alpha").is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[gateway\n");
    }

    #[test]
    fn url_answers() {
        assert_eq!(parse_url_answer("  "), UrlAnswer::Skipped);
        assert_eq!(
            parse_url_answer("https://tv.example.com/"),
            UrlAnswer::Url("https://tv.example.com".to_string())
        );
        assert_eq!(
            parse_url_answer("tv.example.com"),
            UrlAnswer::Url("https://tv.example.com".to_string())
        );
        assert_eq!(
            parse_url_answer("http://localhost:3000/mcp/remote"),
            UrlAnswer::Url("http://localhost:3000/mcp/remote".to_string())
        );
        for bad in ["ftp://x.example.com", "--flag", "two words", "https://"] {
            assert_eq!(parse_url_answer(bad), UrlAnswer::Invalid, "{bad}");
        }
    }

    #[test]
    fn bazaar_url_is_saved_into_a_new_file() {
        let tmp = tempfile::tempdir().unwrap();
        let path = crate::config::user_config_path_in(tmp.path());
        save_bazaar_url(&path, "https://ctx.example.com/mcp/remote").unwrap();
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(
            user.bazaar_url.as_deref(),
            Some("https://ctx.example.com/mcp/remote")
        );
    }

    #[test]
    fn bazaar_url_is_added_without_touching_the_rest() {
        let tmp = tempfile::tempdir().unwrap();
        let path = crate::config::user_config_path_in(tmp.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let before = "# my settings\nagent = \"codex\"\n\n[agents]\n# the nightly build\ncodex = \"/opt/codex\"\n";
        std::fs::write(&path, before).unwrap();
        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            after,
            format!("bazaar_url = \"https://ctx.example.com/mcp\"\n{before}")
        );
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(user.agent, Some(Agent::Codex));
        assert_eq!(
            user.bazaar_url.as_deref(),
            Some("https://ctx.example.com/mcp")
        );
        assert_eq!(
            user.agents.program_for(Agent::Codex).as_deref(),
            Some("/opt/codex")
        );
    }

    #[test]
    fn an_empty_bazaar_url_is_replaced() {
        let tmp = tempfile::tempdir().unwrap();
        let path = crate::config::user_config_path_in(tmp.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "bazaar_url = \"\"\nagent = \"codex\"\n").unwrap();
        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
        let user = load_user_config_in(tmp.path()).unwrap();
        assert_eq!(
            user.bazaar_url.as_deref(),
            Some("https://ctx.example.com/mcp")
        );
        assert_eq!(user.agent, Some(Agent::Codex));
    }

    #[test]
    fn a_config_that_cannot_be_parsed_is_left_alone() {
        let tmp = tempfile::tempdir().unwrap();
        let path = crate::config::user_config_path_in(tmp.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "agent = [broken").unwrap();
        let err = save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap_err();
        assert!(err.contains("cannot parse"), "{err}");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "agent = [broken");
    }
}