argonauts-app 0.1.0

Argonauts Code's app controller and run host: the conversation, routing, choosing Captain or crew, and the run host each run has.
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
//! The app choices' table in one place: each kind's options, keys, and actions, and what Esc
//! (`SetAside`) means for it.

use argonauts_core::app::{AppChoice, ChoiceKind};
use argonauts_core::events::approval::{AnswerAction, AnswerOption, FreeText};
use argonauts_core::names::ChoiceId;
use argonauts_core::settings::SettingScope;

pub(crate) use argonauts_core::app::NOT_CHANGED;
pub(crate) const JUST_ASKING: &str = "Start work on it? ยท no, just asking";

/// What Esc on an app choice does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OnSetAside {
    /// Stays waiting, like a run's question.
    SetAside,
    /// Closes with "Not changed.".
    NotChanged,
    /// The files stay untrusted, and the question comes back at the next start.
    NotNow,
    /// Offered again when the next run starts.
    NextRun,
    /// Takes the recommended answers for this step and the rest of the setup.
    Recommended,
    /// Closes and nothing changes. The TUI builds these, so the controller never sees one.
    Cancel,
    /// Closes with "Just this request.": what the request asked holds for its run alone.
    JustThisRequest,
    /// Answers No.
    No,
    /// Closes saying nothing ran: a dry run was all it showed.
    NothingRan,
    /// Closes, and the run that waited on the answer doesn't start.
    NotStarted,
}

pub(crate) fn on_set_aside(kind: ChoiceKind) -> OnSetAside {
    match kind {
        ChoiceKind::StartWork | ChoiceKind::RefusedCommands => OnSetAside::SetAside,
        ChoiceKind::Permission | ChoiceKind::GoAhead | ChoiceKind::Fallback => OnSetAside::No,
        ChoiceKind::RewindTurn | ChoiceKind::Git | ChoiceKind::Templates => OnSetAside::NotChanged,
        ChoiceKind::TryWorkflow => OnSetAside::NothingRan,
        ChoiceKind::ConfirmTakeOver | ChoiceKind::ConfirmRewind => OnSetAside::Cancel,
        ChoiceKind::SettingScope | ChoiceKind::ConfirmSafetySetting => OnSetAside::NotChanged,
        ChoiceKind::TrustProject | ChoiceKind::ConfirmConnect => OnSetAside::NotNow,
        ChoiceKind::DetectedChecks => OnSetAside::NextRun,
        ChoiceKind::TermsNote | ChoiceKind::Init => OnSetAside::Recommended,
        ChoiceKind::KeepInstructions => OnSetAside::JustThisRequest,
        ChoiceKind::Setup => OnSetAside::NotChanged,
        ChoiceKind::NeededUpdate => OnSetAside::NotStarted,
        ChoiceKind::RenamedSettings => OnSetAside::NotChanged,
    }
}

/// The fixed options of each kind, in order. `SettingScope` recommends the command's default
/// through [`scope_options`], and `Init` steps build theirs with [`init_options`].
pub(crate) fn options(kind: ChoiceKind) -> Vec<AnswerOption> {
    match kind {
        ChoiceKind::StartWork => vec![
            option('s', "Captain", choose("captain"), false),
            option('c', "Crew run", choose("crew"), false),
            option('n', "No, just asking", choose("no"), false),
        ],
        ChoiceKind::ConfirmTakeOver => vec![option('t', "Take over", AnswerAction::TakeOver, true)],
        ChoiceKind::SettingScope => scope_options(SettingScope::ProjectLocal),
        ChoiceKind::ConfirmSafetySetting => vec![
            option('y', "Change it", AnswerAction::Approve, false),
            option('n', "Keep it as it is", AnswerAction::Cancel, false),
        ],
        ChoiceKind::TrustProject => vec![
            option('y', "Trust them", AnswerAction::Approve, false),
            option('n', "Not now", AnswerAction::Cancel, false),
            option('d', "Show the file", AnswerAction::ShowDiff, false),
        ],
        ChoiceKind::DetectedChecks => vec![
            option('y', "Use these", AnswerAction::Approve, true),
            option('e', "Edit them", AnswerAction::ApproveWithEdits, false),
            option('n', "Skip", AnswerAction::Cancel, false),
        ],
        ChoiceKind::TermsNote => vec![option('c', "Continue", AnswerAction::Approve, true)],
        ChoiceKind::ConfirmRewind => vec![
            option('y', "Rewind", AnswerAction::Approve, false),
            option('d', "Show the diff", AnswerAction::ShowDiff, false),
        ],
        ChoiceKind::ConfirmConnect => vec![
            option('y', "Write it", AnswerAction::Approve, false),
            option('n', "Not now", AnswerAction::Cancel, false),
        ],
        ChoiceKind::KeepInstructions => keep_options(),
        ChoiceKind::RefusedCommands => vec![
            option('y', "Yes, and continue", choose("continue"), true),
            option('n', "No", choose("no"), false),
        ],
        ChoiceKind::GoAhead => vec![
            option('y', "Yes, go ahead", choose("yes"), true),
            option('n', "No, keep planning", choose("no"), false),
        ],
        ChoiceKind::RenamedSettings => vec![
            option('r', "Rename them", AnswerAction::Approve, false),
            option('l', "Leave them", AnswerAction::Cancel, false),
        ],
        // A preview's answer is No unless you say otherwise.
        ChoiceKind::TryWorkflow => vec![
            option('y', "Yes, run it", AnswerAction::Approve, false),
            option('n', "No", choose("no"), true),
        ],
        // Built for each question: they name the CLI, the command, and the turns.
        ChoiceKind::Init
        | ChoiceKind::Permission
        | ChoiceKind::RewindTurn
        | ChoiceKind::Fallback
        | ChoiceKind::Setup
        | ChoiceKind::Git
        | ChoiceKind::Templates
        | ChoiceKind::NeededUpdate => Vec::new(),
    }
}

/// Where a request's "from now on" is kept, yours first, and the request alone last.
pub(crate) fn keep_options() -> Vec<AnswerOption> {
    let mut options: Vec<AnswerOption> = [
        ('m', SettingScope::ProjectLocal),
        ('p', SettingScope::Project),
        ('e', SettingScope::Global),
    ]
    .into_iter()
    .map(|(key, scope)| {
        option(
            key,
            scope_label(scope),
            choose(scope_value(scope)),
            scope == SettingScope::ProjectLocal,
        )
    })
    .collect();
    options.push(option(
        'r',
        "Just this request",
        choose(JUST_THIS_REQUEST),
        false,
    ));
    options
}

/// Where the crew your words set is kept: the request alone first, then this
/// conversation, which writes nothing either, then the repository's shared settings.
pub(crate) fn keep_crew_options() -> Vec<AnswerOption> {
    let mut save = option(
        'p',
        "Save for this repository",
        choose(scope_value(SettingScope::Project)),
        false,
    );
    save.detail = Some("writes [crew] in .argonauts/config.toml".to_owned());
    vec![
        option('r', "Just this request", choose(JUST_THIS_REQUEST), true),
        option(
            's',
            "This conversation",
            choose(scope_value(SettingScope::Session)),
            false,
        ),
        save,
    ]
}

/// The `Choose` value of a dry run's Edit it.
pub(crate) const EDIT_IT: &str = "edit";

/// The `Choose` value that keeps nothing past the request.
pub(crate) const JUST_THIS_REQUEST: &str = "request";

/// Just this session `s`, This project, just me `m`, This project, shared `p`, Everywhere `e`.
pub(crate) fn scope_options(recommended: SettingScope) -> Vec<AnswerOption> {
    [
        ('s', SettingScope::Session),
        ('m', SettingScope::ProjectLocal),
        ('p', SettingScope::Project),
        ('e', SettingScope::Global),
    ]
    .into_iter()
    .map(|(key, scope)| {
        option(
            key,
            scope_label(scope),
            choose(scope_value(scope)),
            scope == recommended,
        )
    })
    .collect()
}

pub(crate) fn scope_label(scope: SettingScope) -> &'static str {
    match scope {
        SettingScope::Session => "Just this session",
        SettingScope::ProjectLocal => "This project, just me",
        SettingScope::Project => "This project, shared",
        SettingScope::Global => "Everywhere",
    }
}

/// The `Choose` value for a scope, its serde name.
pub(crate) fn scope_value(scope: SettingScope) -> &'static str {
    match scope {
        SettingScope::Session => "session",
        SettingScope::ProjectLocal => "project_local",
        SettingScope::Project => "project",
        SettingScope::Global => "global",
    }
}

pub(crate) fn scope_from_value(value: &str) -> Option<SettingScope> {
    [
        SettingScope::Session,
        SettingScope::ProjectLocal,
        SettingScope::Project,
        SettingScope::Global,
    ]
    .into_iter()
    .find(|scope| scope_value(*scope) == value)
}

/// One answer of a guided-setup step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct InitAnswer {
    pub label: String,
    /// What `Choose` carries back.
    pub value: String,
    pub detail: Option<String>,
}

/// `a`, `b`, `c` โ€ฆ in order, the first recommended. A step with nothing to choose gets
/// Continue `c`.
pub(crate) fn init_options(answers: &[InitAnswer]) -> Vec<AnswerOption> {
    if answers.is_empty() {
        return options(ChoiceKind::TermsNote);
    }
    answers
        .iter()
        .zip('a'..='z')
        .enumerate()
        .map(|(index, (answer, key))| AnswerOption {
            key,
            label: answer.label.clone(),
            action: choose(&answer.value),
            recommended: index == 0,
            detail: answer.detail.clone(),
        })
        .collect()
}

pub(crate) fn app_choice(
    id: ChoiceId,
    kind: ChoiceKind,
    title: impl Into<String>,
    body: Vec<String>,
    options: Vec<AnswerOption>,
) -> AppChoice {
    let free_text = match kind {
        ChoiceKind::DetectedChecks => FreeText::Edits,
        _ => FreeText::None,
    };
    AppChoice {
        id,
        kind,
        title: title.into(),
        body,
        options,
        free_text,
        bell: false,
    }
}

pub(crate) fn option(
    key: char,
    label: &str,
    action: AnswerAction,
    recommended: bool,
) -> AnswerOption {
    AnswerOption {
        key,
        label: label.to_owned(),
        action,
        recommended,
        detail: None,
    }
}

pub(crate) fn choose(value: &str) -> AnswerAction {
    AnswerAction::Choose {
        value: value.to_owned(),
    }
}

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

    const SCOPES: [SettingScope; 4] = [
        SettingScope::Session,
        SettingScope::ProjectLocal,
        SettingScope::Project,
        SettingScope::Global,
    ];

    /// An option's key, label, and action.
    type Shape<'a> = (char, &'a str, AnswerAction);

    fn shape(options: &[AnswerOption]) -> Vec<Shape<'_>> {
        options
            .iter()
            .map(|option| (option.key, option.label.as_str(), option.action.clone()))
            .collect()
    }

    #[test]
    fn app_choice_options_follow_the_table() {
        use AnswerAction::{Approve, ApproveWithEdits, Cancel, ShowDiff, TakeOver};
        let table: Vec<(ChoiceKind, Vec<Shape>, OnSetAside)> = vec![
            (
                ChoiceKind::StartWork,
                vec![
                    ('s', "Captain", choose("captain")),
                    ('c', "Crew run", choose("crew")),
                    ('n', "No, just asking", choose("no")),
                ],
                OnSetAside::SetAside,
            ),
            (
                ChoiceKind::ConfirmTakeOver,
                vec![('t', "Take over", TakeOver)],
                OnSetAside::Cancel,
            ),
            (
                ChoiceKind::SettingScope,
                vec![
                    ('s', "Just this session", choose("session")),
                    ('m', "This project, just me", choose("project_local")),
                    ('p', "This project, shared", choose("project")),
                    ('e', "Everywhere", choose("global")),
                ],
                OnSetAside::NotChanged,
            ),
            (
                ChoiceKind::ConfirmSafetySetting,
                vec![
                    ('y', "Change it", Approve),
                    ('n', "Keep it as it is", Cancel),
                ],
                OnSetAside::NotChanged,
            ),
            (
                ChoiceKind::TrustProject,
                vec![
                    ('y', "Trust them", Approve),
                    ('n', "Not now", Cancel),
                    ('d', "Show the file", ShowDiff),
                ],
                OnSetAside::NotNow,
            ),
            (
                ChoiceKind::DetectedChecks,
                vec![
                    ('y', "Use these", Approve),
                    ('e', "Edit them", ApproveWithEdits),
                    ('n', "Skip", Cancel),
                ],
                OnSetAside::NextRun,
            ),
            (
                ChoiceKind::TermsNote,
                vec![('c', "Continue", Approve)],
                OnSetAside::Recommended,
            ),
            (
                ChoiceKind::ConfirmRewind,
                vec![('y', "Rewind", Approve), ('d', "Show the diff", ShowDiff)],
                OnSetAside::Cancel,
            ),
            (
                ChoiceKind::ConfirmConnect,
                vec![('y', "Write it", Approve), ('n', "Not now", Cancel)],
                OnSetAside::NotNow,
            ),
            (ChoiceKind::Init, Vec::new(), OnSetAside::Recommended),
            (
                ChoiceKind::KeepInstructions,
                vec![
                    ('m', "This project, just me", choose("project_local")),
                    ('p', "This project, shared", choose("project")),
                    ('e', "Everywhere", choose("global")),
                    ('r', "Just this request", choose("request")),
                ],
                OnSetAside::JustThisRequest,
            ),
            (ChoiceKind::Permission, Vec::new(), OnSetAside::No),
            (
                ChoiceKind::RefusedCommands,
                vec![
                    ('y', "Yes, and continue", choose("continue")),
                    ('n', "No", choose("no")),
                ],
                OnSetAside::SetAside,
            ),
            (ChoiceKind::RewindTurn, Vec::new(), OnSetAside::NotChanged),
            (
                ChoiceKind::GoAhead,
                vec![
                    ('y', "Yes, go ahead", choose("yes")),
                    ('n', "No, keep planning", choose("no")),
                ],
                OnSetAside::No,
            ),
            (ChoiceKind::Fallback, Vec::new(), OnSetAside::No),
            (
                ChoiceKind::TryWorkflow,
                vec![('y', "Yes, run it", Approve), ('n', "No", choose("no"))],
                OnSetAside::NothingRan,
            ),
            (ChoiceKind::Setup, Vec::new(), OnSetAside::NotChanged),
            (ChoiceKind::Git, Vec::new(), OnSetAside::NotChanged),
            (ChoiceKind::Templates, Vec::new(), OnSetAside::NotChanged),
            (ChoiceKind::NeededUpdate, Vec::new(), OnSetAside::NotStarted),
            (
                ChoiceKind::RenamedSettings,
                vec![
                    ('r', "Rename them", AnswerAction::Approve),
                    ('l', "Leave them", AnswerAction::Cancel),
                ],
                OnSetAside::NotChanged,
            ),
        ];
        for (kind, expected, esc) in &table {
            assert_eq!(shape(&options(*kind)), *expected, "{kind:?}");
            assert_eq!(on_set_aside(*kind), *esc, "{kind:?}");
            let choice = app_choice(
                ChoiceId::numbered(1),
                *kind,
                "t",
                Vec::new(),
                options(*kind),
            );
            let free_text = match kind {
                ChoiceKind::DetectedChecks => FreeText::Edits,
                _ => FreeText::None,
            };
            assert_eq!(choice.free_text, free_text, "{kind:?}");
        }
        // Every kind is in the table once.
        let kinds: std::collections::HashSet<ChoiceKind> =
            table.iter().map(|(kind, ..)| *kind).collect();
        assert_eq!(kinds.len(), table.len());
        for kind in kinds {
            match kind {
                ChoiceKind::StartWork
                | ChoiceKind::ConfirmTakeOver
                | ChoiceKind::SettingScope
                | ChoiceKind::ConfirmSafetySetting
                | ChoiceKind::TermsNote
                | ChoiceKind::Init
                | ChoiceKind::DetectedChecks
                | ChoiceKind::TrustProject
                | ChoiceKind::ConfirmRewind
                | ChoiceKind::ConfirmConnect
                | ChoiceKind::KeepInstructions
                | ChoiceKind::Permission
                | ChoiceKind::RefusedCommands
                | ChoiceKind::RewindTurn
                | ChoiceKind::GoAhead
                | ChoiceKind::Fallback
                | ChoiceKind::TryWorkflow
                | ChoiceKind::Setup
                | ChoiceKind::Git
                | ChoiceKind::Templates
                | ChoiceKind::NeededUpdate
                | ChoiceKind::RenamedSettings => {}
            }
        }

        // The scope question recommends the command's default, and only that.
        for scope in SCOPES {
            let options = scope_options(scope);
            let picked: Vec<AnswerAction> = options
                .iter()
                .filter(|option| option.recommended)
                .map(|option| option.action.clone())
                .collect();
            assert_eq!(picked, vec![choose(scope_value(scope))]);
            assert_eq!(scope_from_value(scope_value(scope)), Some(scope));
            let serde_name = serde_json::to_value(scope).unwrap();
            assert_eq!(serde_name, scope_value(scope));
        }
        assert_eq!(scope_from_value("somewhere"), None);

        // A setup step: a, b, c in order, the first recommended; nothing to pick is Continue.
        let answers = ["one", "two", "three"].map(|value| InitAnswer {
            label: value.to_owned(),
            value: value.to_owned(),
            detail: None,
        });
        let steps = init_options(&answers);
        let keys: Vec<(char, bool)> = steps
            .iter()
            .map(|option| (option.key, option.recommended))
            .collect();
        assert_eq!(keys, vec![('a', true), ('b', false), ('c', false)]);
        assert_eq!(steps[1].action, choose("two"));
        assert_eq!(shape(&init_options(&[])), vec![('c', "Continue", Approve)]);
    }
}