mecha-cli 0.1.13

The mecha CLI: an agent harness for local models.
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
//! The `/entity` modal — repairing who is who in the knowledge graph.
//!
//! Tenth modal on the `/outbox` pattern, and it inherits that pattern's
//! shape: **read for display, and every mutation is a `mecha-graph …` child
//! process.** Nothing here reimplements a verb, so a thing the modal can do
//! is a thing a script can do.
//!
//! The gap it closes was found from the other side. Asked in the TUI to fix
//! a daughter's name, the model correctly reported that it could add an
//! alias and stage a fact correction and nothing else — no rename, no way to
//! create a person who has forty facts and no node. That was true of the
//! whole system, not just the tool surface: `merge_nodes` keeps the
//! survivor's name, so the workaround for a bad name needed a node that
//! nothing could create, and the two missing verbs were each other's only
//! workaround.
//!
//! Three decisions:
//!
//! - **The model still cannot do any of this, and that is the point.** The
//!   verbs went onto `mecha-graph` and this modal drives them as a person
//!   drives them — the same reasoning that keeps `kg_accept` off the MCP
//!   surface. A model that reads mail, web pages and Slack must not be able
//!   to rewrite who anyone in the graph *is*: an identity edit is invisible
//!   in a way a fact edit is not, because every fact about the node keeps
//!   reading correctly while pointing somewhere else.
//! - **Synchronous shell-outs.** An entity lookup against the graph measures
//!   7ms, so the `Watch`/detached-job machinery `/docs` needs for OAuth and
//!   `/outbox` needs for MCP startup would be ceremony around something
//!   faster than a keypress. If that ever stops being true this becomes a
//!   `Watch` like its siblings.
//! - **A refusal keeps the page open.** Every collision this can hit is a
//!   *question* — merge these two? did you mean the other node? — and
//!   answering it needs the page you were already reading. So a refusal
//!   lands in the status line and changes nothing else.

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};

use super::{centered, list_height_reserving};

/// One resolved node, flattened for display.
pub struct EntityRow {
    pub id: String,
    pub name: String,
    pub node_type: String,
    pub aliases: Vec<String>,
    pub interactions: Option<i64>,
    pub facts: Vec<String>,
}

/// Which single-line edit is in flight.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum EditKind {
    Rename,
    Alias,
    NewPerson,
}

impl EditKind {
    pub fn title(self) -> &'static str {
        match self {
            EditKind::Rename => " rename to — enter confirms · esc cancels ",
            EditKind::Alias => " add alias — enter confirms · esc cancels ",
            EditKind::NewPerson => " new person, their name — enter confirms · esc cancels ",
        }
    }

    /// The `mecha-graph` verb behind it. One place, so the modal and the
    /// command line cannot drift into meaning different things by the same
    /// key.
    pub fn verb(self) -> &'static str {
        match self {
            EditKind::Rename => "rename",
            EditKind::Alias => "alias",
            EditKind::NewPerson => "new-person",
        }
    }
}

pub struct EntityModal {
    /// The lookup box.
    pub query: String,
    /// What the last lookup returned.
    pub rows: Vec<EntityRow>,
    pub selected: usize,
    /// An edit in flight: its kind and the text typed so far.
    pub edit: Option<(EditKind, String)>,
    pub status: Option<String>,
    /// True before the first lookup, so an empty list can say "type a name"
    /// rather than "no matches" — the two are opposite findings and the
    /// store-reader rule applies to a list as much as to a queue depth.
    pub fresh: bool,
    pub help: bool,
}

impl EntityModal {
    pub fn new() -> Self {
        Self {
            query: String::new(),
            rows: Vec::new(),
            selected: 0,
            edit: None,
            status: None,
            fresh: true,
            help: false,
        }
    }

    pub fn selected_row(&self) -> Option<&EntityRow> {
        self.rows.get(self.selected)
    }

    pub fn move_sel(&mut self, delta: isize) {
        if self.rows.is_empty() {
            return;
        }
        let n = self.rows.len() as isize;
        let next = (self.selected as isize + delta).rem_euclid(n);
        self.selected = next as usize;
    }

    /// Fold a `mecha-graph entity … --json` answer into the list.
    pub fn install(&mut self, json: &str) {
        self.rows = parse_rows(json);
        self.selected = 0;
        self.fresh = false;
        self.status = Some(match self.rows.len() {
            0 => format!(
                "nothing matches {:?} — ctrl-n creates a person by that name",
                self.query
            ),
            1 => "1 match".to_string(),
            n => format!("{n} matches"),
        });
    }

    pub fn draw(&self, frame: &mut Frame) {
        if self.help {
            self.draw_help(frame);
            return;
        }
        let area = frame.area();
        // Two reserved rows: the query line and the status line. The
        // `list_height` rule — an inline clamp here saturates to zero on a
        // four-row terminal and panics on `min > max`.
        let rows = list_height_reserving(self.body_lines() as u16, area.height, 2);
        let box_area = centered(area, area.width.saturating_sub(6).min(110), rows);
        frame.render_widget(Clear, box_area);

        let mut lines: Vec<Line> = Vec::new();
        lines.push(Line::from(vec![
            Span::styled("  search  ", Style::new().fg(Color::DarkGray)),
            Span::styled(
                if self.query.is_empty() {
                    "".to_string()
                } else {
                    self.query.clone()
                },
                Style::new().fg(Color::White).bold(),
            ),
        ]));

        if self.rows.is_empty() {
            lines.push(Line::styled(
                if self.fresh {
                    "  type a name and press enter"
                } else {
                    "  no match"
                },
                Style::new().fg(Color::DarkGray),
            ));
        }
        for (i, row) in self.rows.iter().enumerate() {
            let here = i == self.selected;
            let marker = if here { "" } else { "  " };
            lines.push(Line::from(vec![
                Span::styled(
                    format!("{marker}{:<8} ", row.node_type),
                    Style::new().fg(if here { Color::Cyan } else { Color::DarkGray }),
                ),
                Span::styled(
                    format!("{:<34} ", clip(&row.name, 34)),
                    if here {
                        Style::new().fg(Color::White).bold()
                    } else {
                        Style::new().fg(Color::White)
                    },
                ),
                Span::styled(
                    match row.interactions {
                        Some(n) => format!("{n} interactions"),
                        None => String::new(),
                    },
                    Style::new().fg(Color::DarkGray),
                ),
            ]));
            if here {
                if !row.aliases.is_empty() {
                    lines.push(Line::styled(
                        format!("      aka {}", clip(&row.aliases.join(", "), 88)),
                        Style::new().fg(Color::DarkGray),
                    ));
                }
                // A couple of facts, so the person deciding whether this is
                // the right node can see what is filed under it. Renaming
                // the wrong node is the failure this whole surface exists to
                // avoid, and the id alone does not prevent it.
                for f in row.facts.iter().take(3) {
                    lines.push(Line::styled(
                        format!("      · {}", clip(f, 88)),
                        Style::new().fg(Color::DarkGray),
                    ));
                }
            }
        }

        lines.push(Line::styled(
            match &self.status {
                Some(s) => format!("  {s}"),
                None => String::new(),
            },
            Style::new().fg(Color::Yellow),
        ));

        let title = match &self.edit {
            Some((kind, buf)) => format!("{}  {buf}", kind.title()),
            None => {
                " /entity · enter search · ↑↓ · r rename · a alias · ctrl-n new · ? help · esc "
                    .to_string()
            }
        };
        let border = if self.edit.is_some() {
            Color::Yellow
        } else {
            Color::Cyan
        };
        frame.render_widget(
            Paragraph::new(lines)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(Style::new().fg(border))
                        .title(title),
                )
                .wrap(Wrap { trim: false }),
            box_area,
        );
    }

    fn body_lines(&self) -> usize {
        let mut n = 1 + self.rows.len().max(1);
        if let Some(row) = self.selected_row() {
            if !row.aliases.is_empty() {
                n += 1;
            }
            n += row.facts.len().min(3);
        }
        n
    }

    fn draw_help(&self, frame: &mut Frame) {
        let area = frame.area();
        let text = "\
  /entity — who is who in the knowledge graph

  enter     look the typed name up
  ↑ ↓       move through the matches
  r         rename the selected node
            the old name is kept as an alias, so everything that
            reached it by the old name still does
  a         add an alias to the selected node
  ctrl-n    create a person, prefilled with what you typed
            for someone who has facts and episodes but no node
  ?         this
  esc       back

  Every one of these runs `mecha-graph` as a child process, so
  anything here is available to a script. The model cannot do any
  of it: an identity edit is invisible in a way a fact edit is not,
  because every fact about a node keeps reading correctly while
  pointing somewhere else.

  A name that is already another node's is refused rather than
  guessed at — that is a merge question, and `mecha-graph merge`
  is the verb that answers it.";
        let rows = list_height_reserving(text.lines().count() as u16, area.height, 0);
        let box_area = centered(area, area.width.saturating_sub(6).min(78), rows);
        frame.render_widget(Clear, box_area);
        frame.render_widget(
            Paragraph::new(text)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(Style::new().fg(Color::Cyan))
                        .title(" /entity — keys · esc back "),
                )
                .wrap(Wrap { trim: false }),
            box_area,
        );
    }
}

/// Parse `mecha-graph entity … --json`.
///
/// A shape that cannot be read is an empty list *plus* a status the caller
/// sets — never a panic, and never a silent success. This is display code
/// for a store another program owns, and the ordinary failure is a version
/// skew rather than corruption.
fn parse_rows(json: &str) -> Vec<EntityRow> {
    let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(json)
    else {
        return Vec::new();
    };
    items
        .iter()
        .map(|it| EntityRow {
            id: it["id"].as_str().unwrap_or_default().to_string(),
            name: it["name"].as_str().unwrap_or_default().to_string(),
            node_type: it["node_type"].as_str().unwrap_or("?").to_string(),
            aliases: it["aliases"]
                .as_array()
                .map(|a| {
                    a.iter()
                        .filter_map(|v| v.as_str().map(str::to_string))
                        .collect()
                })
                .unwrap_or_default(),
            interactions: it["interactions"].as_i64(),
            facts: it["facts"]
                .as_array()
                .map(|a| {
                    a.iter()
                        .filter_map(|f| f["statement"].as_str().map(str::to_string))
                        .collect()
                })
                .unwrap_or_default(),
        })
        .collect()
}

fn clip(s: &str, n: usize) -> String {
    if s.chars().count() <= n {
        return s.to_string();
    }
    let mut out: String = s.chars().take(n.saturating_sub(1)).collect();
    out.push('');
    out
}

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

    fn sample() -> &'static str {
        r#"[{"id":"person-1","name":"Josephine B. Conley","node_type":"person",
            "aliases":["josephine","josephine chang"],"interactions":1035,
            "facts":[{"statement":"Josephine is one of Luke's twin daughters."}]}]"#
    }

    #[test]
    fn a_lookup_answer_becomes_rows() {
        let mut m = EntityModal::new();
        m.query = "Josephine".into();
        m.install(sample());
        assert_eq!(m.rows.len(), 1);
        assert_eq!(m.rows[0].id, "person-1");
        assert_eq!(m.rows[0].interactions, Some(1035));
        assert_eq!(m.rows[0].facts.len(), 1);
        assert!(!m.fresh);
    }

    /// "Nothing matches" and "you have not searched yet" are opposite
    /// findings, and a list that rendered them alike would be the
    /// unreadable-store bug one layer up.
    #[test]
    fn an_empty_list_before_and_after_a_search_read_differently() {
        let m = EntityModal::new();
        assert!(m.fresh, "a modal that has not searched is not a no-match");
        let mut m = m;
        m.query = "Nobody".into();
        m.install("[]");
        assert!(!m.fresh);
        assert!(m.status.as_ref().unwrap().contains("nothing matches"));
    }

    /// Display code for another program's store degrades rather than
    /// panicking: version skew is the ordinary failure here.
    #[test]
    fn unreadable_json_is_an_empty_list_not_a_panic() {
        assert!(parse_rows("not json").is_empty());
        assert!(parse_rows("{}").is_empty());
        assert!(parse_rows("[]").is_empty());
        // A row missing every optional field still parses.
        let rows = parse_rows(r#"[{"id":"x"}]"#);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].node_type, "?");
        assert!(rows[0].interactions.is_none());
    }

    #[test]
    fn selection_wraps_and_survives_an_empty_list() {
        let mut m = EntityModal::new();
        m.move_sel(1); // must not panic on an empty list
        assert_eq!(m.selected, 0);
        m.install(sample());
        m.move_sel(1);
        assert_eq!(m.selected, 0, "one row wraps to itself");
        m.move_sel(-1);
        assert_eq!(m.selected, 0);
    }

    /// Each key means exactly one `mecha-graph` verb, defined once.
    #[test]
    fn every_edit_names_its_verb() {
        assert_eq!(EditKind::Rename.verb(), "rename");
        assert_eq!(EditKind::Alias.verb(), "alias");
        assert_eq!(EditKind::NewPerson.verb(), "new-person");
    }

    /// The `list_height` rule: the assertion is the draw itself. A modal
    /// that panics on a shrunken terminal takes the session down, partial
    /// answer and all.
    #[test]
    fn it_draws_at_tiny_sizes() {
        let mut m = EntityModal::new();
        m.install(sample());
        for (w, h) in [(1, 1), (4, 2), (10, 4), (20, 5), (80, 24)] {
            let backend = ratatui::backend::TestBackend::new(w, h);
            let mut term = ratatui::Terminal::new(backend).unwrap();
            term.draw(|f| m.draw(f)).unwrap();
            m.help = true;
            term.draw(|f| m.draw(f)).unwrap();
            m.help = false;
        }
    }
}