vissue-core 0.9.1

Plain-text issue tracking over per-project orgmode files: model, store, queries, and org projection
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
//! The operation set, read from the Cap'n Proto schema itself.
//!
//! Every verb reaches a caller through three surfaces: the command line, the
//! control socket, and the MCP tool list. Each was declared in its own file in its
//! own idiom, so a verb could exist on one and not the others. That happened
//! repeatedly and nothing caught it: `vote` shipped on the command line alone,
//! `append` had no socket method for as long as the socket existed, and a test
//! asserting `issue/fold` was an unknown method became wrong the day fold got one.
//!
//! The set now lives in `schema/vissue.capnp` and this module reads it. Not a copy
//! of it and not a parser for it: `capnp compile` encodes the constant into the
//! generated `vissue_capnp.rs`, so the bytes this reads are the schema, and a
//! surface is checked against them.
//!
//! No toolchain at build time. `capnp` the compiler is absent from the machines
//! that build this, so the generated file is committed and regenerating it is a
//! maintainer step; what ships is the encoded constant, which the pure-Rust `capnp`
//! runtime reads anywhere.

use crate::vissue_capnp::{OPERATIONS, operation};

/// One verb, named on each surface that carries it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Operation {
    /// Subcommand name, as clap spells it.
    pub cli: String,
    /// Control-socket method, empty when the verb has none.
    pub socket: String,
    /// MCP tool name, empty when the verb is deliberately not a tool.
    pub mcp: String,
    /// Whether the verb changes a file.
    pub mutates: bool,
    /// Whether the verb only makes sense in the process it is typed into.
    pub local: bool,
    /// Other names the command line answers to for this verb.
    pub aliases: Vec<String>,
    /// The operation this verb is a narrower spelling of, empty for the ordinary case.
    pub shorthand_for: String,
    /// Why a surface is empty, when one is.
    pub note: String,
    /// Fields the verb takes, each named per surface.
    pub fields: Vec<Field>,
}

/// One field of one verb, named per surface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Field {
    /// Flag name without dashes, empty when absent or positional.
    pub cli: String,
    /// MCP argument name, empty when the tool does not take it.
    pub tool: String,
    /// Control-socket parameter name, empty when the method does not take it.
    pub socket: String,
    /// Why a surface is empty, or why the names differ.
    pub note: String,
    /// Whether a caller may leave the field out on the wire, whatever the type says.
    pub omittable: bool,
    /// Rust type of the tool argument, empty when the tool does not take it.
    pub tool_type: String,
    /// Rust type of the socket parameter, empty when the method does not take it.
    pub socket_type: String,
}

/// The operation set as the schema states it.
///
/// # Panics
///
/// Panics if the encoded constant cannot be read, which would mean the committed
/// generated file is corrupt rather than that a caller did anything wrong.
#[must_use]
pub fn operations() -> Vec<Operation> {
    let list = OPERATIONS
        .get()
        .expect("the encoded operation set in vissue_capnp.rs is unreadable");
    list.iter().map(read_one).collect()
}

fn read_one(row: operation::Reader<'_>) -> Operation {
    let text = |r: ::capnp::Result<::capnp::text::Reader<'_>>| -> String {
        r.ok()
            .and_then(|t| t.to_str().ok().map(str::to_string))
            .unwrap_or_default()
    };
    let fields = row
        .get_fields()
        .map(|list| {
            list.iter()
                .map(|f| Field {
                    cli: text(f.get_cli()),
                    tool: text(f.get_tool()),
                    socket: text(f.get_socket()),
                    note: text(f.get_note()),
                    omittable: f.get_omittable(),
                    tool_type: text(f.get_tool_type()),
                    socket_type: text(f.get_socket_type()),
                })
                .collect()
        })
        .unwrap_or_default();
    Operation {
        cli: text(row.get_cli()),
        socket: text(row.get_socket()),
        mcp: text(row.get_mcp()),
        mutates: row.get_mutates(),
        local: row.get_local(),
        aliases: row
            .get_aliases()
            .map(|list| {
                list.iter()
                    .filter_map(|a| a.ok().and_then(|t| t.to_str().ok().map(str::to_string)))
                    .collect()
            })
            .unwrap_or_default(),
        shorthand_for: text(row.get_shorthand_for()),
        note: text(row.get_note()),
        fields,
    }
}

/// Verbs the schema records as reaching the socket, mutating or not.
#[must_use]
pub fn socket_methods() -> Vec<String> {
    operations()
        .into_iter()
        .filter(|o| !o.socket.is_empty())
        .map(|o| o.socket)
        .collect()
}

/// Every subcommand the schema knows, including the local-only ones.
#[must_use]
pub fn cli_verbs() -> Vec<String> {
    operations()
        .into_iter()
        .filter(|o| !o.cli.is_empty())
        .flat_map(|o| std::iter::once(o.cli).chain(o.aliases))
        .collect()
}

/// Flags clap puts on every subcommand, which a per-verb row does not repeat.
///
/// # Panics
///
/// Panics if the encoded constant cannot be read, which would mean the committed
/// generated file is corrupt.
#[must_use]
pub fn global_flags() -> Vec<String> {
    crate::vissue_capnp::GLOBAL_FLAGS
        .get()
        .expect("the encoded global flag list is unreadable")
        .iter()
        .filter_map(|f| f.ok().and_then(|t| t.to_str().ok().map(str::to_string)))
        .collect()
}

/// Every mutating verb's socket method, skipping any the schema leaves empty.
#[must_use]
pub fn mutating_socket_methods() -> Vec<String> {
    operations()
        .into_iter()
        .filter(|o| o.mutates && !o.socket.is_empty())
        .map(|o| o.socket)
        .collect()
}

/// Every mutating verb's subcommand.
#[must_use]
pub fn mutating_cli_verbs() -> Vec<String> {
    operations()
        .into_iter()
        .filter(|o| o.mutates && !o.cli.is_empty())
        .map(|o| o.cli)
        .collect()
}

/// Every mutating verb's MCP tool, skipping the ones deliberately absent.
#[must_use]
pub fn mutating_mcp_tools() -> Vec<String> {
    operations()
        .into_iter()
        .filter(|o| o.mutates && !o.mcp.is_empty())
        .map(|o| o.mcp)
        .collect()
}

/// One operation as the schema text states it.
///
/// Everything the encoded constant can drift from without changing a surface
/// name or a field count, which is what made a note-only edit invisible.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaRow {
    /// Subcommand name.
    pub cli: String,
    /// Control-socket method.
    pub socket: String,
    /// MCP tool name.
    pub mcp: String,
    /// The operation's own note.
    pub note: String,
    /// One note per field, in order, empty where a field has none.
    pub field_notes: Vec<String>,
}

/// The schema as its text states it, for comparison with the encoded constant.
///
/// This exists to close a hole in the arrangement rather than to be used at
/// runtime. The constant the checks read is compiled into `vissue_capnp.rs`, which
/// is committed and regenerated by hand. Edit `vissue.capnp`, forget to regenerate,
/// and every check happily validates against the previous schema and passes. The
/// schema would be authoritative in the documentation and not in fact.
///
/// So the text is read too, and a test compares the two. A deliberately small
/// reader for one list of flat records, not a Cap'n Proto parser: it needs to run
/// where `capnp` is not installed, which is everywhere this is built.
///
/// Returns one [`SchemaRow`] per operation.
#[must_use]
pub fn parse_schema_text(text: &str) -> Vec<SchemaRow> {
    let Some(start) = text.find("const operations") else {
        return Vec::new();
    };
    let body = &text[start..];
    let mut out: Vec<SchemaRow> = Vec::new();
    for line in body.lines() {
        let trimmed = line.trim();
        let quoted = |name: &str| -> Option<String> {
            let at = trimmed.find(&format!("{name} = "))?;
            let rest = &trimmed[at..];
            let open = rest.find('"')?;
            let close = rest[open + 1..].find('"')?;
            Some(rest[open + 1..open + 1 + close].to_string())
        };
        // An operation row opens with its three surface names on one line.
        if trimmed.starts_with("( cli = ")
            && trimmed.contains("mutates = ")
            && let (Some(cli), Some(socket), Some(mcp)) =
                (quoted("cli"), quoted("socket"), quoted("mcp"))
        {
            out.push(SchemaRow {
                cli,
                socket,
                mcp,
                note: String::new(),
                field_notes: Vec::new(),
            });
            continue;
        }
        // An operation's note is on its own line under the row it belongs to.
        // It is read because a note-only edit is otherwise invisible: the
        // surfaces and the field count are unchanged, so the comparison passed
        // while the constant still carried the previous prose.
        if trimmed.starts_with("note = ")
            && let (Some(note), Some(last)) = (quoted("note"), out.last_mut())
        {
            last.note = note;
            continue;
        }
        // A field row also opens with `( cli = `, so it is told apart by carrying a
        // `tool =` and no `socket = "issue/`. Its note rides on the same line.
        if trimmed.starts_with("( cli = ")
            && trimmed.contains("tool = ")
            && !trimmed.contains("mutates = ")
            && let Some(last) = out.last_mut()
        {
            last.field_notes.push(quoted("note").unwrap_or_default());
        }
    }
    out
}

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

    fn schema_text() -> String {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schema/vissue.capnp");
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
    }

    /// The committed generated file and the schema text say the same thing.
    ///
    /// Without this the schema is authoritative only in the documentation.
    /// `vissue_capnp.rs` is regenerated by hand, so an edit to the schema that
    /// nobody regenerated leaves every other check validating the previous schema
    /// and passing.
    #[test]
    fn the_generated_constant_matches_the_schema_text() {
        let from_text = parse_schema_text(&schema_text());
        assert!(
            !from_text.is_empty(),
            "no operations parsed from the schema text; the reader and the file have diverged"
        );
        let from_bytes: Vec<SchemaRow> = operations()
            .into_iter()
            .map(|o| SchemaRow {
                cli: o.cli,
                socket: o.socket,
                mcp: o.mcp,
                note: o.note,
                field_notes: o.fields.into_iter().map(|f| f.note).collect(),
            })
            .collect();
        assert_eq!(
            from_text, from_bytes,
            "schema/vissue.capnp and the committed vissue_capnp.rs disagree; \
             regenerate it, see schema/README.md"
        );
    }

    /// The note is prose and the checks are about names, which is how a
    /// note-only edit came to be invisible: the surfaces and the field count
    /// were unchanged, so the constant kept the previous wording and every
    /// check passed. The schema is meant to be authoritative in fact and not
    /// only in the documentation.
    #[test]
    fn a_note_the_schema_states_reaches_the_constant() {
        let ops = operations();
        let backlinks = ops
            .iter()
            .find(|o| o.cli == "backlinks")
            .expect("backlinks is in the operation set");
        assert!(
            backlinks.note.contains("scan every routed tracker"),
            "the command line and tool half of the split is missing: {:?}",
            backlinks.note
        );
        assert!(
            backlinks.note.contains("the layout it was started on"),
            "the socket half of the split is missing: {:?}",
            backlinks.note
        );
    }

    /// The helpers three checks now share, so their own behaviour is pinned rather
    /// than assumed by each caller.

    #[test]
    fn the_schema_constant_reads_back() {
        let ops = operations();
        assert!(
            ops.len() >= 10,
            "the encoded operation set looks truncated: {ops:?}"
        );
        assert!(ops.iter().any(|o| o.cli == "create"));
        assert!(ops.iter().any(|o| o.cli == "vote"), "vote is missing");
    }

    /// Every mutating verb reaches the socket, itself or through the verb it is a
    /// shorthand for. This was false for five verbs at once, and for `append` the
    /// whole time the socket existed.
    ///
    /// A write that has to leave the socket puts a hole in the change stream exactly
    /// where that write was, so the reachability is what matters rather than the
    /// method count: `q` has no method and needs none, because `create` has one and
    /// takes everything `q` takes.
    #[test]
    fn every_mutating_verb_reaches_the_socket() {
        let ops = operations();
        let mut missing = Vec::new();
        for op in ops.iter().filter(|o| o.mutates && o.socket.is_empty()) {
            if op.shorthand_for.is_empty() {
                missing.push(format!("{} reaches no socket method", op.cli));
                continue;
            }
            match ops.iter().find(|o| o.cli == op.shorthand_for) {
                None => missing.push(format!(
                    "{} is a shorthand for {}, which is in no row",
                    op.cli, op.shorthand_for
                )),
                Some(target) if target.socket.is_empty() => missing.push(format!(
                    "{} is a shorthand for {}, which reaches no socket method either",
                    op.cli, op.shorthand_for
                )),
                Some(_) => {}
            }
        }
        assert!(
            missing.is_empty(),
            "these change a file and no socket method can: {missing:?}"
        );
    }

    /// A shorthand takes a subset of the fields of the verb it shortens.
    ///
    /// That subset is what makes the exemption above sound. A shorthand taking a
    /// field its target does not is not a narrower spelling of it, and answering for
    /// it with the target's socket method would drop that field on the floor.
    #[test]
    fn a_shorthand_takes_a_subset_of_what_it_shortens() {
        let ops = operations();
        let mut wrong = Vec::new();
        for op in ops.iter().filter(|o| !o.shorthand_for.is_empty()) {
            let Some(target) = ops.iter().find(|o| o.cli == op.shorthand_for) else {
                continue; // reported by every_mutating_verb_reaches_the_socket
            };
            for field in &op.fields {
                if field.cli.is_empty() {
                    continue;
                }
                if !target.fields.iter().any(|f| f.cli == field.cli) {
                    wrong.push(format!(
                        "{} takes --{} and {} does not",
                        op.cli, field.cli, target.cli
                    ));
                }
            }
        }
        assert!(
            wrong.is_empty(),
            "these shorthands take fields the verb they shorten does not: {wrong:?}"
        );
    }

    /// A shorthand names a verb other than itself, and that verb is not itself a
    /// shorthand. A cycle or a chain would make the reachability argument circular.
    #[test]
    fn a_shorthand_points_at_a_verb_that_stands_on_its_own() {
        let ops = operations();
        let mut wrong = Vec::new();
        for op in ops.iter().filter(|o| !o.shorthand_for.is_empty()) {
            if op.shorthand_for == op.cli {
                wrong.push(format!("{} is a shorthand for itself", op.cli));
            }
            if let Some(target) = ops
                .iter()
                .find(|o| o.cli == op.shorthand_for)
                .filter(|t| !t.shorthand_for.is_empty())
            {
                wrong.push(format!(
                    "{} shortens {}, which shortens {}",
                    op.cli, target.cli, target.shorthand_for
                ));
            }
        }
        assert!(wrong.is_empty(), "{wrong:?}");
    }

    /// A surface left empty says why, so a deliberate omission cannot pass for an
    /// oversight or the other way round.
    #[test]
    fn a_missing_surface_carries_its_reason() {
        for o in operations() {
            if o.socket.is_empty() || o.mcp.is_empty() {
                assert!(
                    !o.note.is_empty(),
                    "{} leaves a surface empty and says nothing about why",
                    o.cli
                );
            }
        }
    }

    /// Names are not blank and not accidentally duplicated.
    #[test]
    fn the_names_are_distinct_and_present() {
        let ops = operations();
        // A row may have no subcommand, when the command line reaches the operation
        // through a flag on another verb: `vissue_org` is `show --org`. It has to
        // reach *some* surface and say why the others are empty, which the note
        // check enforces, so the requirement here is a surface rather than a
        // subcommand.
        for o in &ops {
            assert!(
                !(o.cli.is_empty() && o.socket.is_empty() && o.mcp.is_empty()),
                "an operation reaches no surface at all: {o:?}"
            );
        }
        // Empty is not a name. Two rows without a subcommand are two operations the
        // command line reaches through a flag, not a collision.
        let mut clis: Vec<&str> = ops
            .iter()
            .map(|o| o.cli.as_str())
            .filter(|c| !c.is_empty())
            .collect();
        clis.sort_unstable();
        let before = clis.len();
        clis.dedup();
        assert_eq!(before, clis.len(), "two operations share a subcommand");

        // Two subcommands may answer from one method, and one pair does: `identity`
        // and `whoami` both reach `identity/get`. That is a fact about the surfaces
        // rather than a mistake, so it is allowed when the rows say so. Silence is
        // what is refused, because an undocumented duplicate is the shape a
        // copy-paste error takes.
        let mut by_method: std::collections::BTreeMap<&str, Vec<&Operation>> =
            std::collections::BTreeMap::new();
        for o in &ops {
            if !o.socket.is_empty() {
                by_method.entry(o.socket.as_str()).or_default().push(o);
            }
        }
        for (method, sharers) in by_method {
            if sharers.len() < 2 {
                continue;
            }
            let silent: Vec<&str> = sharers
                .iter()
                .filter(|o| o.note.is_empty())
                .map(|o| o.cli.as_str())
                .collect();
            assert!(
                silent.is_empty(),
                "{method} answers for {silent:?} and none of them says why"
            );
        }
    }
}