tmprl-core 0.1.0

Pure domain logic for tmprl: modes, keymap, command registry
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Things that change a cluster, and the confirmation that stands in front of them.
//!
//! Everything up to now has been a reader. These are the operations that cannot be undone by
//! pressing `R`, so the design in `docs/ARCHITECTURE.md` §9 puts one confirmation in front of
//! every one of them, and that confirmation shows **the equivalent `temporal` CLI command**.
//!
//! That last part is the load-bearing bit. It teaches the CLI, it makes the action auditable
//! at a glance, you can read exactly what is about to happen rather than trusting a verb,
//! and it gives an escape hatch to anyone who would rather run it themselves. Which means the
//! rendered command has to be *correct*: someone will copy it and run it. The flags here are
//! checked against `temporal workflow --help`, and the quoting is tested.

use crate::timerange::{Overlap, TimeRange, to_rfc3339};

/// A change to a cluster, fully specified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Mutation {
    Cancel {
        namespace: String,
        workflow_id: String,
        run_id: String,
    },
    Terminate {
        namespace: String,
        workflow_id: String,
        run_id: String,
        reason: String,
    },
    Signal {
        namespace: String,
        workflow_id: String,
        run_id: String,
        name: String,
        /// JSON, as typed. `None` sends no input at all, which is not the same as `null`.
        input: Option<String>,
    },
    Delete {
        namespace: String,
        workflow_id: String,
        run_id: String,
    },
    /// Rewind to a completed workflow task and replay forward from there. The event id is
    /// already resolved to a valid reset point. See `history::reset_point`.
    Reset {
        namespace: String,
        workflow_id: String,
        run_id: String,
        event_id: i64,
        reason: String,
    },
    /// Send an update and wait for its outcome. Unlike a signal, an update can be rejected
    /// by the workflow and reports back.
    Update {
        namespace: String,
        workflow_id: String,
        run_id: String,
        name: String,
        input: Option<String>,
    },
    /// Pause or resume a schedule. `paused` is the state being moved *to*.
    PauseSchedule {
        namespace: String,
        schedule_id: String,
        paused: bool,
    },
    /// Run a scheduled workflow now, without waiting for its next time.
    TriggerSchedule {
        namespace: String,
        schedule_id: String,
    },
    DeleteSchedule {
        namespace: String,
        schedule_id: String,
    },
    /// Create a schedule. `spec` is passed to the server as a cron string, which also
    /// accepts `@every 1h`.
    CreateSchedule {
        namespace: String,
        schedule_id: String,
        workflow_id: String,
        workflow_type: String,
        task_queue: String,
        spec: String,
        input: Option<String>,
    },
    /// Replay every action the schedule would have taken over a past window.
    BackfillSchedule {
        namespace: String,
        schedule_id: String,
        range: TimeRange,
        overlap: Overlap,
    },
}

/// The three schedule operations act on a schedule id rather than an execution, so they do
/// not share the workflow accessors.
impl Mutation {
    /// The schedule this acts on, if it is a schedule operation at all.
    pub fn schedule_id(&self) -> Option<&str> {
        match self {
            Mutation::PauseSchedule { schedule_id, .. }
            | Mutation::TriggerSchedule { schedule_id, .. }
            | Mutation::DeleteSchedule { schedule_id, .. }
            | Mutation::BackfillSchedule { schedule_id, .. }
            | Mutation::CreateSchedule { schedule_id, .. } => Some(schedule_id),
            _ => None,
        }
    }
}

impl Mutation {
    /// What the confirmation calls it.
    pub fn verb(&self) -> &'static str {
        match self {
            Mutation::Cancel { .. } => "Cancel",
            Mutation::Terminate { .. } => "Terminate",
            Mutation::Signal { .. } => "Signal",
            Mutation::Delete { .. } => "Delete",
            Mutation::Reset { .. } => "Reset",
            Mutation::Update { .. } => "Update",
            Mutation::PauseSchedule { paused: true, .. } => "Pause",
            Mutation::PauseSchedule { paused: false, .. } => "Resume",
            Mutation::TriggerSchedule { .. } => "Trigger",
            Mutation::DeleteSchedule { .. } => "Delete schedule",
            Mutation::BackfillSchedule { .. } => "Backfill",
            Mutation::CreateSchedule { .. } => "Create schedule",
        }
    }

    /// How to say it happened. Spelled out rather than derived: "cancel" + "d" is "canceld",
    /// and a status line that cannot spell does not inspire confidence in what it just did.
    pub fn past_tense(&self) -> &'static str {
        match self {
            Mutation::Cancel { .. } => "cancelled",
            Mutation::Terminate { .. } => "terminated",
            Mutation::Signal { .. } => "signalled",
            Mutation::Delete { .. } => "deleted",
            Mutation::Reset { .. } => "reset",
            Mutation::Update { .. } => "updated",
            Mutation::PauseSchedule { paused: true, .. } => "paused",
            Mutation::PauseSchedule { paused: false, .. } => "resumed",
            Mutation::TriggerSchedule { .. } => "triggered",
            Mutation::DeleteSchedule { .. } => "deleted",
            Mutation::BackfillSchedule { .. } => "backfilled",
            Mutation::CreateSchedule { .. } => "created",
        }
    }

    /// What a batch of this is a batch *of*, for the heading over a count.
    pub fn subject_plural(&self) -> &'static str {
        match self {
            Mutation::Cancel { .. }
            | Mutation::Terminate { .. }
            | Mutation::Signal { .. }
            | Mutation::Delete { .. }
            | Mutation::Reset { .. }
            | Mutation::Update { .. } => "workflows",
            Mutation::PauseSchedule { .. }
            | Mutation::TriggerSchedule { .. }
            | Mutation::DeleteSchedule { .. }
            | Mutation::BackfillSchedule { .. }
            | Mutation::CreateSchedule { .. } => "schedules",
        }
    }

    pub fn namespace(&self) -> &str {
        match self {
            Mutation::Cancel { namespace, .. }
            | Mutation::Terminate { namespace, .. }
            | Mutation::Signal { namespace, .. }
            | Mutation::Delete { namespace, .. }
            | Mutation::Reset { namespace, .. }
            | Mutation::Update { namespace, .. }
            | Mutation::PauseSchedule { namespace, .. }
            | Mutation::TriggerSchedule { namespace, .. }
            | Mutation::DeleteSchedule { namespace, .. }
            | Mutation::BackfillSchedule { namespace, .. }
            | Mutation::CreateSchedule { namespace, .. } => namespace,
        }
    }

    pub fn workflow_id(&self) -> &str {
        match self {
            Mutation::Cancel { workflow_id, .. }
            | Mutation::Terminate { workflow_id, .. }
            | Mutation::Signal { workflow_id, .. }
            | Mutation::Delete { workflow_id, .. }
            | Mutation::Reset { workflow_id, .. }
            | Mutation::Update { workflow_id, .. } => workflow_id,
            // Schedule operations have no execution; the id is the schedule's.
            Mutation::PauseSchedule { schedule_id, .. }
            | Mutation::TriggerSchedule { schedule_id, .. }
            | Mutation::DeleteSchedule { schedule_id, .. }
            | Mutation::BackfillSchedule { schedule_id, .. }
            | Mutation::CreateSchedule { schedule_id, .. } => schedule_id,
        }
    }

    pub fn run_id(&self) -> &str {
        match self {
            Mutation::Cancel { run_id, .. }
            | Mutation::Terminate { run_id, .. }
            | Mutation::Signal { run_id, .. }
            | Mutation::Delete { run_id, .. }
            | Mutation::Reset { run_id, .. }
            | Mutation::Update { run_id, .. } => run_id,
            Mutation::PauseSchedule { .. }
            | Mutation::TriggerSchedule { .. }
            | Mutation::DeleteSchedule { .. }
            | Mutation::BackfillSchedule { .. }
            | Mutation::CreateSchedule { .. } => "",
        }
    }

    /// Whether the workflow does not survive it.
    ///
    /// A signal is a change but not a loss; a delete removes the history itself and cannot be
    /// walked back even by starting the workflow again.
    pub fn is_destructive(&self) -> bool {
        // A reset abandons everything after the reset point, so it loses work even though
        // the workflow survives. An update, like a signal, only adds to it. Pausing and
        // triggering a schedule are reversible by doing the opposite.
        !matches!(
            self,
            Mutation::Signal { .. }
                | Mutation::Update { .. }
                | Mutation::PauseSchedule { .. }
                | Mutation::TriggerSchedule { .. }
                | Mutation::BackfillSchedule { .. }
                | Mutation::CreateSchedule { .. }
        )
    }

    /// Whether it destroys the record as well as the run. Only `delete` does, which is why it
    /// is the one that asks for more than a keypress.
    pub fn destroys_history(&self) -> bool {
        matches!(
            self,
            Mutation::Delete { .. } | Mutation::DeleteSchedule { .. }
        )
    }

    /// The equivalent `temporal` command, ready to paste into a shell.
    ///
    /// Flags follow `temporal workflow --help`: `-w/--workflow-id`, `-r/--run-id`,
    /// `-n/--namespace`, `--reason`, `--name`, `--input`. The long forms are used because
    /// this is meant to be read as much as run.
    pub fn cli(&self) -> String {
        let base = |verb: &str, m: &Mutation| {
            format!(
                "temporal workflow {verb} --namespace {} --workflow-id {} --run-id {}",
                shell_quote(m.namespace()),
                shell_quote(m.workflow_id()),
                shell_quote(m.run_id()),
            )
        };
        match self {
            Mutation::Cancel { .. } => base("cancel", self),
            Mutation::Delete { .. } => base("delete", self),
            Mutation::Terminate { reason, .. } => {
                format!(
                    "{} --reason {}",
                    base("terminate", self),
                    shell_quote(reason)
                )
            }
            Mutation::Signal { name, input, .. } => {
                let mut out = format!("{} --name {}", base("signal", self), shell_quote(name));
                if let Some(input) = input {
                    out.push_str(&format!(" --input {}", shell_quote(input)));
                }
                out
            }
            Mutation::Reset {
                event_id, reason, ..
            } => format!(
                "{} --event-id {event_id} --reason {}",
                base("reset", self),
                shell_quote(reason)
            ),
            // `update execute` rather than `update start`: tmprl waits for the outcome, and
            // the command shown should be the one that behaves the same way.
            Mutation::Update { name, input, .. } => {
                let mut out = format!(
                    "temporal workflow update execute --namespace {} --workflow-id {} \
                     --run-id {} --name {}",
                    shell_quote(self.namespace()),
                    shell_quote(self.workflow_id()),
                    shell_quote(self.run_id()),
                    shell_quote(name)
                );
                if let Some(input) = input {
                    out.push_str(&format!(" --input {}", shell_quote(input)));
                }
                out
            }
            Mutation::PauseSchedule {
                namespace,
                schedule_id,
                paused,
            } => format!(
                "temporal schedule toggle --namespace {} --schedule-id {} {}",
                shell_quote(namespace),
                shell_quote(schedule_id),
                if *paused { "--pause" } else { "--unpause" }
            ),
            Mutation::TriggerSchedule {
                namespace,
                schedule_id,
            } => format!(
                "temporal schedule trigger --namespace {} --schedule-id {}",
                shell_quote(namespace),
                shell_quote(schedule_id)
            ),
            Mutation::DeleteSchedule {
                namespace,
                schedule_id,
            } => format!(
                "temporal schedule delete --namespace {} --schedule-id {}",
                shell_quote(namespace),
                shell_quote(schedule_id)
            ),
            Mutation::CreateSchedule {
                namespace,
                schedule_id,
                workflow_id,
                workflow_type,
                task_queue,
                spec,
                input,
            } => {
                let mut out = format!(
                    "temporal schedule create --namespace {} --schedule-id {} \
                     --workflow-id {} --type {} --task-queue {} --cron {}",
                    shell_quote(namespace),
                    shell_quote(schedule_id),
                    shell_quote(workflow_id),
                    shell_quote(workflow_type),
                    shell_quote(task_queue),
                    shell_quote(spec)
                );
                if let Some(input) = input {
                    out.push_str(&format!(" --input {}", shell_quote(input)));
                }
                out
            }
            Mutation::BackfillSchedule {
                namespace,
                schedule_id,
                range,
                overlap,
            } => format!(
                "temporal schedule backfill --namespace {} --schedule-id {} \
                 --start-time {} --end-time {} --overlap-policy {}",
                shell_quote(namespace),
                shell_quote(schedule_id),
                to_rfc3339(range.start_ms),
                to_rfc3339(range.end_ms),
                overlap.name()
            ),
        }
    }

    /// One line for `~/.local/state/tmprl/audit.jsonl`.
    ///
    /// The CLI equivalent is recorded alongside the fields, so the log answers "what was
    /// actually done" without the reader having to reconstruct it from parts.
    pub fn audit_line(&self, at_epoch_millis: i64, target: Target<'_>, outcome: &str) -> String {
        let mut out = String::from("{");
        out.push_str(&format!(r#""at":{at_epoch_millis},"#));
        out.push_str(&format!(r#""action":{},"#, json_string(self.verb())));
        out.push_str(&format!(r#""profile":{},"#, json_string(target.profile)));
        out.push_str(&format!(r#""address":{},"#, json_string(target.address)));
        out.push_str(&format!(
            r#""namespace":{},"#,
            json_string(self.namespace())
        ));
        out.push_str(&format!(
            r#""workflowId":{},"#,
            json_string(self.workflow_id())
        ));
        out.push_str(&format!(r#""runId":{},"#, json_string(self.run_id())));
        out.push_str(&format!(r#""outcome":{},"#, json_string(outcome)));
        out.push_str(&format!(r#""command":{}"#, json_string(&self.cli())));
        out.push('}');
        out
    }
}

/// Which cluster a mutation was sent to.
///
/// Namespace names repeat across environments, so a namespace alone cannot answer "was
/// this SIT or production". Profile and address together can.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Target<'a> {
    pub profile: &'a str,
    pub address: &'a str,
}

/// What a confirmation is waiting for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Confirm {
    /// Every mutation this confirmation covers, in the order they will run. One for an
    /// ordinary action, one per selected row for a batch.
    pub mutations: Vec<Mutation>,
    /// When set, the reader must type this exactly before the action is allowed. Reserved for
    /// the operations where a single keypress is too cheap for what it does.
    pub typed_word: Option<String>,
    /// What they have typed so far.
    pub entered: String,
}

impl Confirm {
    pub fn new(mutation: Mutation) -> Self {
        Self::batch(vec![mutation])
    }

    /// A confirmation over several rows.
    ///
    /// The word owed scales with what is at stake: destroying histories always costs the
    /// word, and a destructive batch costs the count, because one keypress is too cheap to
    /// end a dozen workflows at once.
    pub fn batch(mutations: Vec<Mutation>) -> Self {
        let typed_word = if mutations.iter().any(Mutation::destroys_history) {
            Some("delete".to_string())
        } else if mutations.len() > 1 && mutations.iter().any(Mutation::is_destructive) {
            Some(mutations.len().to_string())
        } else {
            None
        };
        Self {
            mutations,
            typed_word,
            entered: String::new(),
        }
    }

    /// The mutation that stands for the set: the first, which every other one matches in
    /// verb and namespace because a batch is one action over many rows.
    pub fn first(&self) -> &Mutation {
        &self.mutations[0]
    }

    pub fn len(&self) -> usize {
        self.mutations.len()
    }

    pub fn is_empty(&self) -> bool {
        self.mutations.is_empty()
    }

    /// Whether this covers more than one row, which is what the heading has to say.
    pub fn is_batch(&self) -> bool {
        self.mutations.len() > 1
    }

    /// Whether pressing Enter now would go ahead.
    pub fn is_satisfied(&self) -> bool {
        match &self.typed_word {
            None => true,
            Some(word) => self.entered.trim() == word,
        }
    }

    /// Why a word is owed at all.
    ///
    /// The renderer must not infer this from the word: "delete" is owed because a history is
    /// about to stop existing, a count is owed because one keypress is too cheap for the
    /// number of rows, and telling a reader that terminating destroys a history would be a
    /// lie in the one place that has to be exact.
    pub fn caution(&self) -> Option<String> {
        self.typed_word.as_ref()?;
        Some(if self.first().destroys_history() {
            "this destroys the history itself.".to_string()
        } else {
            format!(
                "this covers {} {}.",
                self.len(),
                self.first().subject_plural()
            )
        })
    }

    /// What to tell the reader they still owe.
    pub fn prompt(&self) -> String {
        match &self.typed_word {
            None => "⏎ to confirm   Esc to cancel".into(),
            Some(word) if self.is_satisfied() => "⏎ to confirm   Esc to cancel".into(),
            Some(word) => format!("type `{word}` to confirm   Esc to cancel"),
        }
    }
}

/// Quote a value for a POSIX shell.
///
/// Single quotes, with the one escape a single-quoted string needs. This matters more than it
/// looks: the rendered command is meant to be copied and run, and a workflow id can contain
/// spaces, quotes or a `;`. A command that is *almost* right is worse than none.
pub fn shell_quote(s: &str) -> String {
    if !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_./:@".contains(c))
    {
        return s.to_string();
    }
    format!("'{}'", s.replace('\'', r"'\''"))
}

fn json_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

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

    fn terminate(reason: &str) -> Mutation {
        Mutation::Terminate {
            namespace: "default".into(),
            workflow_id: "order-1".into(),
            run_id: "run-abc".into(),
            reason: reason.into(),
        }
    }

    #[test]
    fn the_caution_says_why_the_word_is_owed_rather_than_assuming_delete() {
        // Telling a reader that terminating destroys a history would be a lie in the one
        // place that has to be exact.
        let wf = |id: &str| Mutation::Terminate {
            namespace: "default".into(),
            workflow_id: id.into(),
            run_id: "r".into(),
            reason: "r".into(),
        };
        let batch = Confirm::batch(vec![wf("a"), wf("b"), wf("c")]);
        assert_eq!(batch.typed_word.as_deref(), Some("3"));
        assert_eq!(batch.caution().as_deref(), Some("this covers 3 workflows."));

        let del = Confirm::new(Mutation::Delete {
            namespace: "default".into(),
            workflow_id: "a".into(),
            run_id: "r".into(),
        });
        assert_eq!(del.typed_word.as_deref(), Some("delete"));
        assert_eq!(
            del.caution().as_deref(),
            Some("this destroys the history itself.")
        );

        assert_eq!(
            Confirm::new(wf("a")).caution(),
            None,
            "one row owes nothing"
        );
    }

    #[test]
    fn a_backfill_renders_the_cli_with_rfc3339_bounds() {
        // Someone will copy this line and run it, so the times have to be in the format
        // `temporal schedule backfill` accepts, not the millis tmprl holds internally.
        let m = Mutation::BackfillSchedule {
            namespace: "default".into(),
            schedule_id: "nightly recon".into(),
            range: TimeRange {
                start_ms: 1_788_566_400_000,
                end_ms: 1_788_652_800_000,
            },
            overlap: Overlap::BufferAll,
        };
        assert_eq!(
            m.cli(),
            "temporal schedule backfill --namespace default --schedule-id 'nightly recon' \
             --start-time 2026-09-05T00:00:00Z --end-time 2026-09-06T00:00:00Z \
             --overlap-policy BufferAll"
        );
        assert_eq!(m.verb(), "Backfill");
        assert_eq!(m.past_tense(), "backfilled");
        assert_eq!(m.schedule_id(), Some("nightly recon"));
        assert!(!m.is_destructive(), "it starts runs, it destroys nothing");
    }

    #[test]
    fn a_terminate_renders_the_command_that_would_do_it() {
        assert_eq!(
            terminate("stuck").cli(),
            "temporal workflow terminate --namespace default --workflow-id order-1 \
             --run-id run-abc --reason stuck"
        );
    }

    #[test]
    fn a_cancel_and_a_delete_carry_no_reason() {
        let cancel = Mutation::Cancel {
            namespace: "payments".into(),
            workflow_id: "charge-9".into(),
            run_id: "r1".into(),
        };
        assert_eq!(
            cancel.cli(),
            "temporal workflow cancel --namespace payments --workflow-id charge-9 --run-id r1"
        );
        let delete = Mutation::Delete {
            namespace: "payments".into(),
            workflow_id: "charge-9".into(),
            run_id: "r1".into(),
        };
        assert!(delete.cli().starts_with("temporal workflow delete "));
    }

    #[test]
    fn a_signal_without_input_does_not_pass_an_empty_one() {
        // `--input ''` is a JSON parse error, not "no input".
        let signal = Mutation::Signal {
            namespace: "default".into(),
            workflow_id: "w".into(),
            run_id: "r".into(),
            name: "ping".into(),
            input: None,
        };
        assert!(!signal.cli().contains("--input"));

        let with_input = Mutation::Signal {
            namespace: "default".into(),
            workflow_id: "w".into(),
            run_id: "r".into(),
            name: "ping".into(),
            input: Some(r#"{"a":1}"#.into()),
        };
        assert!(with_input.cli().ends_with(r#"--input '{"a":1}'"#));
    }

    #[test]
    fn values_that_would_break_a_shell_are_quoted() {
        // Someone will copy this and run it. A workflow id with a space or a semicolon must
        // not turn into two commands.
        let m = Mutation::Terminate {
            namespace: "default".into(),
            workflow_id: "order 1; rm -rf /".into(),
            run_id: "r".into(),
            reason: "it's stuck".into(),
        };
        let cli = m.cli();
        assert!(cli.contains("'order 1; rm -rf /'"), "got {cli}");
        // The one escape a single-quoted shell string needs.
        assert!(cli.contains(r"'it'\''s stuck'"), "got {cli}");
    }

    #[test]
    fn plain_values_are_not_quoted_needlessly() {
        // The command is meant to be read as much as run.
        assert_eq!(shell_quote("order-1"), "order-1");
        assert_eq!(shell_quote("ns.with.dots"), "ns.with.dots");
        assert_eq!(shell_quote(""), "''", "an empty value still needs quotes");
        assert_eq!(shell_quote("has space"), "'has space'");
    }

    #[test]
    fn a_reset_names_the_event_it_goes_back_to() {
        let m = Mutation::Reset {
            namespace: "default".into(),
            workflow_id: "order-1".into(),
            run_id: "r".into(),
            event_id: 9,
            reason: "bad deploy".into(),
        };
        assert_eq!(
            m.cli(),
            "temporal workflow reset --namespace default --workflow-id order-1 --run-id r \
             --event-id 9 --reason 'bad deploy'"
        );
        // A reset abandons everything after the point, so it loses work even though the
        // workflow survives.
        assert!(m.is_destructive());
        assert!(!m.destroys_history(), "the history is still there");
        assert_eq!(Confirm::new(m).typed_word, None);
    }

    #[test]
    fn an_update_uses_execute_because_tmprl_waits_for_the_outcome() {
        // `update start` returns once accepted; `update execute` waits. The command shown
        // should behave the way tmprl does.
        let m = Mutation::Update {
            namespace: "default".into(),
            workflow_id: "w".into(),
            run_id: "r".into(),
            name: "setLimit".into(),
            input: Some("50".into()),
        };
        let cli = m.cli();
        assert!(
            cli.starts_with("temporal workflow update execute "),
            "{cli}"
        );
        assert!(cli.ends_with("--name setLimit --input 50"), "{cli}");
        // Like a signal, an update adds to a workflow rather than ending it.
        assert!(!m.is_destructive());
    }

    #[test]
    fn an_update_without_input_passes_none() {
        let m = Mutation::Update {
            namespace: "d".into(),
            workflow_id: "w".into(),
            run_id: "r".into(),
            name: "ping".into(),
            input: None,
        };
        assert!(!m.cli().contains("--input"));
    }

    #[test]
    fn every_verb_has_a_past_tense_that_is_a_word() {
        // "cancel" + "d" is "canceld".
        for (m, expected) in [
            (
                Mutation::Cancel {
                    namespace: "d".into(),
                    workflow_id: "w".into(),
                    run_id: "r".into(),
                },
                "cancelled",
            ),
            (terminate("x"), "terminated"),
            (
                Mutation::Reset {
                    namespace: "d".into(),
                    workflow_id: "w".into(),
                    run_id: "r".into(),
                    event_id: 1,
                    reason: "x".into(),
                },
                "reset",
            ),
        ] {
            assert_eq!(m.past_tense(), expected);
        }
    }

    #[test]
    fn pausing_a_schedule_renders_the_toggle_command() {
        // The CLI has no `pause` subcommand: it is `toggle --pause`.
        let m = Mutation::PauseSchedule {
            namespace: "payments".into(),
            schedule_id: "nightly".into(),
            paused: true,
        };
        assert_eq!(
            m.cli(),
            "temporal schedule toggle --namespace payments --schedule-id nightly --pause"
        );
        assert_eq!(m.verb(), "Pause");
        assert_eq!(m.past_tense(), "paused");
        assert!(!m.is_destructive(), "unpausing puts it back");

        let resumed = Mutation::PauseSchedule {
            namespace: "payments".into(),
            schedule_id: "nightly".into(),
            paused: false,
        };
        assert!(resumed.cli().ends_with("--unpause"));
        assert_eq!(resumed.verb(), "Resume");
    }

    #[test]
    fn triggering_is_reversible_but_deleting_a_schedule_is_not() {
        let trigger = Mutation::TriggerSchedule {
            namespace: "d".into(),
            schedule_id: "s".into(),
        };
        assert!(!trigger.is_destructive());
        assert_eq!(
            trigger.cli(),
            "temporal schedule trigger --namespace d --schedule-id s"
        );

        let delete = Mutation::DeleteSchedule {
            namespace: "d".into(),
            schedule_id: "s".into(),
        };
        assert!(delete.is_destructive());
        assert!(delete.destroys_history(), "the schedule is gone for good");
        assert_eq!(Confirm::new(delete).typed_word.as_deref(), Some("delete"));
    }

    #[test]
    fn a_schedule_operation_reports_its_id_and_has_no_run() {
        let m = Mutation::TriggerSchedule {
            namespace: "d".into(),
            schedule_id: "nightly".into(),
        };
        assert_eq!(m.schedule_id(), Some("nightly"));
        assert_eq!(m.workflow_id(), "nightly", "the id column shows it");
        assert_eq!(m.run_id(), "", "a schedule has no execution");
        assert_eq!(terminate("x").schedule_id(), None);
    }

    #[test]
    fn a_signal_is_a_change_but_not_a_loss() {
        let signal = Mutation::Signal {
            namespace: "d".into(),
            workflow_id: "w".into(),
            run_id: "r".into(),
            name: "n".into(),
            input: None,
        };
        assert!(!signal.is_destructive());
        assert!(terminate("x").is_destructive());
    }

    #[test]
    fn only_delete_destroys_the_history_and_only_it_asks_for_a_word() {
        let delete = Mutation::Delete {
            namespace: "d".into(),
            workflow_id: "w".into(),
            run_id: "r".into(),
        };
        assert!(delete.destroys_history());
        assert!(!terminate("x").destroys_history());

        let mut confirm = Confirm::new(delete);
        assert_eq!(confirm.typed_word.as_deref(), Some("delete"));
        assert!(!confirm.is_satisfied(), "a keypress is too cheap for this");
        assert!(confirm.prompt().contains("type `delete`"));

        confirm.entered = "delet".into();
        assert!(!confirm.is_satisfied(), "nearly is not the same as typed");
        confirm.entered = "delete".into();
        assert!(confirm.is_satisfied());
        assert!(confirm.prompt().contains(""));
    }

    #[test]
    fn everything_else_needs_one_confirmation_and_no_typing() {
        let confirm = Confirm::new(terminate("stuck"));
        assert_eq!(confirm.typed_word, None);
        assert!(confirm.is_satisfied());
        assert!(confirm.prompt().contains("⏎ to confirm"));
    }

    /// The cluster the test mutations are sent to.
    fn sit() -> Target<'static> {
        Target {
            profile: "sit",
            address: "http://temporal-sit.internal:7233",
        }
    }

    #[test]
    fn an_audit_line_records_what_was_done_and_how_it_ended() {
        let line = terminate("stuck").audit_line(1_700_000_000_000, sit(), "ok");
        assert!(line.contains(r#""action":"Terminate""#), "{line}");
        assert!(line.contains(r#""workflowId":"order-1""#), "{line}");
        assert!(line.contains(r#""outcome":"ok""#), "{line}");
        assert!(line.contains(r#""at":1700000000000"#), "{line}");
        // The command goes in too, so the log answers "what happened" on its own.
        assert!(line.contains("temporal workflow terminate"), "{line}");
        // And it is one line, because the file is JSONL.
        assert!(!line.contains('\n'));
    }

    #[test]
    fn an_audit_line_escapes_what_it_quotes() {
        let m = Mutation::Terminate {
            namespace: "d".into(),
            workflow_id: "has \"quotes\" and\nnewline".into(),
            run_id: "r".into(),
            reason: "x".into(),
        };
        let line = m.audit_line(0, sit(), "failed");
        assert!(
            !line.contains('\n'),
            "a JSONL line cannot contain a newline"
        );
        assert!(line.contains(r#"\"quotes\""#), "{line}");
    }

    #[test]
    fn a_failed_mutation_is_still_recorded() {
        // The log is what was attempted, not only what succeeded.
        let line = terminate("x").audit_line(1, sit(), "failed: permission denied");
        assert!(line.contains("permission denied"), "{line}");
    }

    #[test]
    fn an_audit_line_records_which_cluster_was_hit() {
        // Two environments sharing a namespace name produce lines that differ only here,
        // which is the whole reason the target is recorded.
        let line = terminate("stuck").audit_line(1, sit(), "ok");
        assert!(line.contains(r#""profile":"sit""#), "{line}");
        assert!(
            line.contains(r#""address":"http://temporal-sit.internal:7233""#),
            "{line}"
        );

        let prod = Target {
            profile: "prod",
            address: "http://temporal.internal:7233",
        };
        let other = terminate("stuck").audit_line(1, prod, "ok");
        assert_ne!(
            line, other,
            "the same namespace on two clusters must differ"
        );
    }
}