voro-core 0.2.0

Core logic for Voro: the SQLite store, task state machine, scheduler, and scoring.
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
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
//! Comment-preserving edits to the user's `voro.toml` (DESIGN.md §5). Where
//! [`crate::agent::AgentsConfig`] *reads* the file, this *writes* it: the single
//! helper the TUI Config screen and the `voro viewer` CLI verbs both route
//! through, so the two never diverge on formatting or validation.
//!
//! Edits go through `toml_edit`, which round-trips a document preserving its
//! existing content, whitespace, and comments — only the touched key changes.
//! A missing file is created (with its parent directory); the built-ins mean an
//! absent file is still a working config, so the first edit is what brings the
//! file into existence.

use std::path::Path;

use toml_edit::{DocumentMut, Item, Table, value};

use crate::agent::{VIEWER_PATH_PLACEHOLDER, is_builtin_viewer};
use crate::error::{Error, Result};
use crate::model::Project;

/// The command a viewer gets when none is given: for a built-in name, exactly
/// what that built-in runs, so overriding one starts from what it replaces;
/// for anything else, the editor's own name handed the checkout —
/// `<name> {path}` — which is what nearly every editor CLI wants and is the
/// only part of the answer a new operator has no way to guess.
///
/// It is a *default*, not a rule: `code -n {path}`, a wrapper script, or a
/// `git difftool` line are all still spellable by filling the command in.
pub fn assumed_viewer_cmd(name: &str) -> String {
    let name = name.trim();
    match crate::agent::builtin_viewer_cmd(name) {
        Some(cmd) => cmd.to_string(),
        None => format!("{name} {VIEWER_PATH_PLACEHOLDER}"),
    }
}

/// Add a `[viewers.<name>]` table, refusing an empty name or a name that
/// collides with an existing viewer. An empty command is not a refusal but the
/// common case: it becomes [`assumed_viewer_cmd`], so naming the editor is
/// enough. Existing content and comments in the file are preserved.
pub fn add_viewer(path: &Path, name: &str, cmd: &str) -> Result<()> {
    let name = name.trim();
    let assumed = assumed_viewer_cmd(name);
    let cmd = match cmd.trim() {
        "" => assumed.as_str(),
        cmd => cmd,
    };
    validate_viewer(name, cmd)?;
    let mut doc = load_doc(path)?;
    if viewer_exists(&doc, name) {
        return Err(invalid(format!(
            "a viewer named '{name}' already exists — edit it, or pick another name"
        )));
    }
    set_viewer_cmd(&mut doc, name, cmd)?;
    write_doc(path, &doc)
}

/// Replace an existing viewer's command, refusing an empty command or a name
/// that names no viewer. The rest of the table (and file) is untouched.
pub fn edit_viewer(path: &Path, name: &str, cmd: &str) -> Result<()> {
    let name = name.trim();
    let cmd = cmd.trim();
    if cmd.is_empty() {
        return Err(invalid("viewer command is required".into()));
    }
    let mut doc = load_doc(path)?;
    if !viewer_exists(&doc, name) {
        return Err(missing(name, "edit"));
    }
    set_viewer_cmd(&mut doc, name, cmd)?;
    write_doc(path, &doc)
}

/// Remove the named viewer, returning whether `default_viewer` was cleared
/// because it pointed at the deleted viewer. Refuses a name that names no
/// viewer. The referenced-by-a-project refusal lives at the call site, which
/// has the project list to name the offenders (see [`projects_referencing_viewer`]).
pub fn delete_viewer(path: &Path, name: &str) -> Result<bool> {
    let name = name.trim();
    let mut doc = load_doc(path)?;
    if !viewer_exists(&doc, name) {
        return Err(missing(name, "delete"));
    }
    remove_viewer(&mut doc, name);
    let cleared = default_viewer_matches(&doc, name);
    if cleared {
        doc.remove("default_viewer");
    }
    write_doc(path, &doc)?;
    Ok(cleared)
}

/// Set `default_viewer` to a viewer that resolves — a `[viewers.<name>]` table
/// or a built-in — so the picker can't point the default at a viewer that
/// isn't there.
pub fn set_default_viewer(path: &Path, name: &str) -> Result<()> {
    let name = name.trim();
    let mut doc = load_doc(path)?;
    if !viewer_exists(&doc, name) && !is_builtin_viewer(name) {
        return Err(invalid(format!(
            "no viewer named '{name}' — define it before making it the default"
        )));
    }
    doc["default_viewer"] = value(name);
    write_doc(path, &doc)
}

/// Set `default_agent`. Existence against the built-in + user agent set is the
/// caller's to validate (the built-ins live in code, not the file); the picker
/// only offers configured names, so this just records the choice.
pub fn set_default_agent(path: &Path, name: &str) -> Result<()> {
    let name = name.trim();
    if name.is_empty() {
        return Err(invalid("agent name is required".into()));
    }
    let mut doc = load_doc(path)?;
    doc["default_agent"] = value(name);
    write_doc(path, &doc)
}

/// Set `max_running`, the dispatch WIP cap (DESIGN.md §7), refusing a negative
/// count in the same words [`crate::agent::AgentsConfig::load`] refuses one
/// read from the file. `0` is legal and means what it means there: the queue
/// offers no dispatches at all.
pub fn set_max_running(path: &Path, n: i64) -> Result<()> {
    if n < 0 {
        return Err(invalid(crate::agent::negative_max_running(n)));
    }
    let mut doc = load_doc(path)?;
    doc["max_running"] = value(n);
    write_doc(path, &doc)
}

/// Whether a viewer command lacks the `{path}` placeholder — a warning, not an
/// error (DESIGN.md §5): such a command runs in the checkout's own directory,
/// which is occasionally what a `git difftool -d` wants but usually a mistake.
pub fn missing_path_placeholder(cmd: &str) -> bool {
    !cmd.contains(VIEWER_PATH_PLACEHOLDER)
}

/// The projects that name this viewer, so deleting it can be refused with them
/// named (DESIGN.md §5). A project naming no viewer is not counted — it follows
/// whatever the default resolves to rather than pinning this name.
pub fn projects_referencing_viewer<'a>(projects: &'a [Project], name: &str) -> Vec<&'a Project> {
    projects
        .iter()
        .filter(|p| p.viewer.as_deref() == Some(name))
        .collect()
}

fn validate_viewer(name: &str, cmd: &str) -> Result<()> {
    if name.is_empty() {
        return Err(invalid("viewer name is required".into()));
    }
    // A name is typed as one word — on the command line and as the bare TOML
    // key of its `[viewers.<name>]` table — so refuse one that cannot be.
    if name.chars().any(|c| c.is_whitespace() || c == ':') {
        return Err(invalid(format!(
            "viewer name '{name}' cannot contain spaces or ':'"
        )));
    }
    if cmd.is_empty() {
        return Err(invalid("viewer command is required".into()));
    }
    Ok(())
}

fn invalid(message: String) -> Error {
    Error::Invalid(message)
}

/// The refusal for a name this file does not define. A built-in is not missing
/// but unwritable — it lives in the binary — so it is refused separately, with
/// the override that *is* writable named (DESIGN.md §11a).
fn missing(name: &str, verb: &str) -> Error {
    if is_builtin_viewer(name) {
        return invalid(format!(
            "viewer '{name}' is built into voro, so there is nothing here to {verb} — run \
             `voro viewer add {name} '<cmd>'` to override it with your own"
        ));
    }
    invalid(format!("no viewer named '{name}' to {verb}"))
}

/// Read the file into an editable document, or an empty one when it does not
/// exist yet — the first edit creates the file.
fn load_doc(path: &Path) -> Result<DocumentMut> {
    match std::fs::read_to_string(path) {
        Ok(text) => text
            .parse::<DocumentMut>()
            .map_err(|e| Error::AgentConfigInvalid {
                path: path.to_path_buf(),
                message: e.to_string(),
            }),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(DocumentMut::new()),
        Err(e) => Err(Error::AgentConfigInvalid {
            path: path.to_path_buf(),
            message: e.to_string(),
        }),
    }
}

fn write_doc(path: &Path, doc: &DocumentMut) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| Error::AgentConfigInvalid {
            path: path.to_path_buf(),
            message: e.to_string(),
        })?;
    }
    std::fs::write(path, doc.to_string()).map_err(|e| Error::AgentConfigInvalid {
        path: path.to_path_buf(),
        message: e.to_string(),
    })
}

fn viewer_exists(doc: &DocumentMut, name: &str) -> bool {
    doc.get("viewers")
        .and_then(Item::as_table_like)
        .is_some_and(|t| t.contains_key(name))
}

/// Set `viewers.<name>.cmd`, creating the `[viewers]` table (implicit, so no
/// bare `[viewers]` header is emitted) and the named subtable as needed. An
/// existing named table keeps its formatting and any sibling keys.
fn set_viewer_cmd(doc: &mut DocumentMut, name: &str, cmd: &str) -> Result<()> {
    if doc.get("viewers").is_none() {
        let mut table = Table::new();
        table.set_implicit(true);
        doc.insert("viewers", Item::Table(table));
    }
    let viewers = doc["viewers"].as_table_mut().ok_or_else(|| {
        invalid("`viewers` in voro.toml is not a table — fix it by hand first".into())
    })?;
    // Update an existing subtable in place (keeping its formatting), or insert a
    // fresh `[viewers.<name>]` table. Inserting a whole subtable — rather than a
    // dotted `viewers.<name>.cmd` key — is what keeps `viewers` a header-less
    // implicit parent and renders the new entry as its own `[viewers.<name>]`.
    match viewers.get_mut(name).and_then(Item::as_table_mut) {
        Some(existing) => existing["cmd"] = value(cmd),
        None => {
            let mut table = Table::new();
            table["cmd"] = value(cmd);
            viewers.insert(name, Item::Table(table));
        }
    }
    Ok(())
}

fn remove_viewer(doc: &mut DocumentMut, name: &str) {
    if let Some(viewers) = doc.get_mut("viewers").and_then(Item::as_table_mut) {
        viewers.remove(name);
        if viewers.is_empty() {
            doc.remove("viewers");
        }
    }
}

fn default_viewer_matches(doc: &DocumentMut, name: &str) -> bool {
    doc.get("default_viewer").and_then(Item::as_str) == Some(name)
}

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

    /// A unique scratch path per test, cleaned up by the caller.
    fn scratch(tag: &str) -> std::path::PathBuf {
        tempfile::Builder::new()
            .prefix(&format!("voro-config-edit-{tag}-"))
            .tempdir()
            .unwrap()
            .keep()
    }

    #[test]
    fn add_viewer_creates_the_file_when_missing() {
        let dir = scratch("create");
        let path = dir.join("voro/voro.toml");
        assert!(!path.exists());

        add_viewer(&path, "zed", "zed {path}").unwrap();
        assert!(path.exists());

        let config = AgentsConfig::load(&path).unwrap();
        assert_eq!(config.viewer_cmd(Some("zed")).unwrap(), "zed {path}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn add_viewer_preserves_existing_content_and_comments() {
        let dir = scratch("preserve");
        let path = dir.join("voro.toml");
        std::fs::create_dir_all(&dir).unwrap();
        let original = "\
# my hand-written config
default_agent = \"claude\"

[viewers.difftool]
cmd = \"git -C {path} difftool -d {base}...{branch}\"  # inline note
";
        std::fs::write(&path, original).unwrap();

        add_viewer(&path, "zed", "zed {path}").unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains("# my hand-written config"), "{text}");
        assert!(text.contains("# inline note"), "{text}");
        assert!(text.contains("[viewers.difftool]"), "{text}");
        assert!(text.contains("[viewers.zed]"), "{text}");

        let config = AgentsConfig::load(&path).unwrap();
        assert_eq!(config.viewer_names(), vec!["difftool", "zed"]);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn add_viewer_rejects_duplicates_and_a_bad_name() {
        let dir = scratch("reject");
        let path = dir.join("voro.toml");
        std::fs::create_dir_all(&dir).unwrap();

        add_viewer(&path, "zed", "zed {path}").unwrap();
        let dup = add_viewer(&path, "zed", "zed .").unwrap_err().to_string();
        assert!(dup.contains("already exists"), "{dup}");

        let empty_name = add_viewer(&path, "  ", "zed .").unwrap_err().to_string();
        assert!(empty_name.contains("name is required"), "{empty_name}");

        let bad_name = add_viewer(&path, "a:b", "zed .").unwrap_err().to_string();
        assert!(bad_name.contains("cannot contain"), "{bad_name}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn edit_viewer_updates_the_command() {
        let dir = scratch("edit");
        let path = dir.join("voro.toml");
        std::fs::create_dir_all(&dir).unwrap();

        add_viewer(&path, "zed", "zed {path}").unwrap();
        edit_viewer(&path, "zed", "zed --new {path}").unwrap();
        let config = AgentsConfig::load(&path).unwrap();
        assert_eq!(config.viewer_cmd(Some("zed")).unwrap(), "zed --new {path}");

        let missing = edit_viewer(&path, "nope", "x {path}")
            .unwrap_err()
            .to_string();
        assert!(missing.contains("no viewer named 'nope'"), "{missing}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn delete_viewer_removes_it_and_clears_a_matching_default() {
        let dir = scratch("delete");
        let path = dir.join("voro.toml");
        std::fs::create_dir_all(&dir).unwrap();

        add_viewer(&path, "zed", "zed {path}").unwrap();
        add_viewer(&path, "emacs", "emacsclient {path}").unwrap();
        set_default_viewer(&path, "zed").unwrap();

        // deleting a non-default viewer leaves the default alone
        let cleared = delete_viewer(&path, "emacs").unwrap();
        assert!(!cleared);
        assert_eq!(
            AgentsConfig::load(&path)
                .unwrap()
                .default_viewer_name()
                .as_deref(),
            Some("zed")
        );

        // deleting the default clears default_viewer
        let cleared = delete_viewer(&path, "zed").unwrap();
        assert!(cleared);
        let config = AgentsConfig::load(&path).unwrap();
        assert!(config.viewer_names().is_empty());
        assert!(
            !std::fs::read_to_string(&path)
                .unwrap()
                .contains("default_viewer"),
        );

        let missing = delete_viewer(&path, "emacs").unwrap_err().to_string();
        assert!(missing.contains("no viewer named"), "{missing}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A built-in viewer lives in the binary, so the write helpers cannot touch
    /// it — but they can be told to override it, and it is a legitimate default
    /// with no table of its own.
    #[test]
    fn built_in_viewers_are_unwritable_but_overridable_and_defaultable() {
        let dir = scratch("builtin");
        let path = dir.join("voro.toml");
        std::fs::create_dir_all(&dir).unwrap();

        for message in [
            delete_viewer(&path, "code").unwrap_err().to_string(),
            edit_viewer(&path, "code", "code {path}")
                .unwrap_err()
                .to_string(),
        ] {
            assert!(message.contains("built into voro"), "{message}");
            assert!(message.contains("voro viewer add code"), "{message}");
        }

        // a built-in may be the default without any table defining it
        set_default_viewer(&path, "code").unwrap();
        assert_eq!(
            AgentsConfig::load(&path)
                .unwrap()
                .default_viewer_name()
                .as_deref(),
            Some("code")
        );

        // adding one of its name overrides it, and is then editable
        add_viewer(&path, "code", "code --wait {path}").unwrap();
        assert_eq!(
            AgentsConfig::load(&path)
                .unwrap()
                .viewer_cmd(Some("code"))
                .unwrap(),
            "code --wait {path}"
        );
        edit_viewer(&path, "code", "code -n {path}").unwrap();
        delete_viewer(&path, "code").unwrap();

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// The dispatch cap is written like any other key: comments and the
    /// operator's own content survive it, an absent file is created by it, `0`
    /// is legal, and a negative count is refused in the words the loader uses
    /// (DESIGN.md §5/§7).
    #[test]
    fn set_max_running_writes_the_cap_and_refuses_a_negative_one() {
        let dir = scratch("cap");
        let path = dir.join("voro/voro.toml");
        assert!(!path.exists());

        set_max_running(&path, 3).unwrap();
        assert_eq!(AgentsConfig::load(&path).unwrap().max_running(), 3);
        assert_eq!(
            AgentsConfig::load(&path).unwrap().max_running_from_file(),
            Some(3)
        );

        // rewriting the file leaves what the operator wrote around it alone
        let original = "\
# how many at once
max_running = 3  # was 5

[viewers.zed]
cmd = \"zed {path}\"
";
        std::fs::write(&path, original).unwrap();
        set_max_running(&path, 9).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains("# how many at once"), "{text}");
        assert!(text.contains("[viewers.zed]"), "{text}");
        assert!(text.contains("max_running = 9"), "{text}");
        assert_eq!(AgentsConfig::load(&path).unwrap().max_running(), 9);

        // 0 is a cap, not an absence: the queue offers nothing
        set_max_running(&path, 0).unwrap();
        assert_eq!(AgentsConfig::load(&path).unwrap().max_running(), 0);

        // and the refusal is the loader's own sentence, not a second wording
        let refused = set_max_running(&path, -1).unwrap_err().to_string();
        assert!(refused.contains("cannot be negative"), "{refused}");
        assert_eq!(AgentsConfig::load(&path).unwrap().max_running(), 0);

        let hand_written = dir.join("by-hand.toml");
        std::fs::write(&hand_written, "max_running = -1\n").unwrap();
        let from_file = AgentsConfig::load(&hand_written).unwrap_err().to_string();
        assert!(from_file.contains(&refused), "{from_file} vs {refused}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn set_defaults_validate_and_record() {
        let dir = scratch("defaults");
        let path = dir.join("voro.toml");
        std::fs::create_dir_all(&dir).unwrap();

        add_viewer(&path, "zed", "zed {path}").unwrap();
        set_default_viewer(&path, "zed").unwrap();
        set_default_agent(&path, "codex").unwrap();
        let config = AgentsConfig::load(&path).unwrap();
        assert_eq!(config.default_viewer_name().as_deref(), Some("zed"));
        assert_eq!(config.default_name().as_deref(), Some("codex"));

        let bad = set_default_viewer(&path, "ghost").unwrap_err().to_string();
        assert!(bad.contains("no viewer named 'ghost'"), "{bad}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Naming the editor is enough: the command a new operator has no way to
    /// guess is assumed, and naming a built-in starts from what it replaces
    /// rather than from a worse guess at the same thing.
    #[test]
    fn a_viewer_added_with_no_command_gets_the_obvious_one() {
        let dir = scratch("assumed");
        let path = dir.join("voro.toml");
        std::fs::create_dir_all(&dir).unwrap();

        assert_eq!(assumed_viewer_cmd("emacsclient"), "emacsclient {path}");
        assert_eq!(assumed_viewer_cmd("code"), "code -n {path}");

        add_viewer(&path, "emacsclient", "").unwrap();
        add_viewer(&path, "code", "   ").unwrap();
        let config = AgentsConfig::load(&path).unwrap();
        assert_eq!(
            config.viewer_cmd(Some("emacsclient")).unwrap(),
            "emacsclient {path}"
        );
        // overriding a built-in with a blank command reproduces it, so the
        // table is a starting point to edit rather than a downgrade
        assert_eq!(config.viewer_cmd(Some("code")).unwrap(), "code -n {path}");

        // a name is still required, and an edit still refuses a blank command:
        // there the field is not empty but emptied
        let no_name = add_viewer(&path, "  ", "").unwrap_err().to_string();
        assert!(no_name.contains("name is required"), "{no_name}");
        let blank_edit = edit_viewer(&path, "code", " ").unwrap_err().to_string();
        assert!(blank_edit.contains("command is required"), "{blank_edit}");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn missing_path_placeholder_flags_a_bare_command() {
        assert!(missing_path_placeholder("git difftool -d"));
        assert!(!missing_path_placeholder("zed {path}"));
    }
}