Skip to main content

gammaloop_api/
session.rs

1//! Borrowed command-session access to a loaded GammaLoop state.
2//!
3//! [`CliSession`] ties together the domain state, replay history, persistent settings, runtime
4//! defaults, and transient command-block state owned by [`crate::LoadedState`]. It does not own or
5//! automatically persist any of them.
6
7use std::{
8    collections::BTreeMap,
9    io::{self, IsTerminal, Write},
10    ops::ControlFlow,
11};
12
13use color_eyre::{eyre::eyre, Result};
14use colored::Colorize;
15use gammalooprs::integrands::process::ProcessIntegrand;
16use gammalooprs::model::Model;
17use gammalooprs::processes::{
18    GraphSelectionSignatureInventory, ProcessCollection, ProcessDefinition,
19    RaisedCutSignatureInventory,
20};
21use gammalooprs::settings::{global::GenerationSettings, RuntimeSettings};
22use tracing::{info, warn};
23
24use crate::{
25    command_template::contains_placeholder,
26    commands::{
27        run::{
28            prepare_command_histories_with_context, PreparedCommand, PreparedRun, MAX_RUN_DEPTH,
29        },
30        save::SaveState,
31        CommandExecution, Commands, StartCommandsBlock,
32    },
33    completion::{
34        IntegrandDetailCompletionEntry, IrProfileCompletionEntry, ModelVertexCompletionEntry,
35        ProcessCompletionEntry, ProcessKind,
36    },
37    integrand_info::IntegrandKind,
38    render_smart_toml,
39    state::{CommandHistory, CommandsBlock, ProcessRef, RunHistory, State},
40    CLISettings, ReadOnlyStateOrigin,
41};
42
43#[cfg(feature = "cli")]
44use crate::commands::process_settings::{
45    serialize_runtime_named_settings, ProcessSettingsCompletionEntry,
46};
47
48const MAX_DISPLAY_COMMAND_LINES: usize = 5;
49
50fn format_command_block_conflict_message(conflicting_blocks: &[String]) -> String {
51    match conflicting_blocks {
52        [] => String::new(),
53        [single] => format!(
54            "Run card command block '{}' redefines an existing block with different commands",
55            single
56        ),
57        many => format!(
58            "Run card command blocks {} redefine existing blocks with different commands",
59            many.iter()
60                .map(|name| format!("'{}'", name))
61                .collect::<Vec<_>>()
62                .join(", ")
63        ),
64    }
65}
66
67fn prompt_command_block_conflict_override(conflicting_blocks: &[String]) -> Result<bool> {
68    let prompt = format!(
69        "{}. Proceed anyway? (it may break reproducibility of the state from run.toml) [y/n] > ",
70        format_command_block_conflict_message(conflicting_blocks)
71    );
72    let mut stderr = io::stderr();
73    let mut input = String::new();
74    loop {
75        eprint!("{prompt}");
76        stderr.flush()?;
77        input.clear();
78        io::stdin().read_line(&mut input)?;
79        match input.trim().to_ascii_lowercase().as_str() {
80            "y" | "yes" => return Ok(true),
81            "n" | "no" => return Ok(false),
82            _ => {
83                eprintln!("Please answer 'y' or 'n'.");
84            }
85        }
86    }
87}
88
89/// Transient state used while defining a reusable command block.
90///
91/// This is process/session state rather than persisted run history. Most callers should retain the
92/// value inside [`crate::LoadedState`] and access it through [`CliSession`].
93#[derive(Debug, Clone, Default)]
94pub struct CliSessionState {
95    pending_commands_block: Option<PendingCommandsBlock>,
96}
97
98#[derive(Debug, Clone)]
99struct PendingCommandsBlock {
100    name: String,
101    commands: Vec<CommandHistory>,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105enum HistoryMode {
106    Record,
107    Suppress,
108}
109
110/// Mutably borrowed view used to execute GammaLoop commands.
111///
112/// A session updates its caller-owned [`State`], [`RunHistory`], and effective settings in place.
113/// It may also write files according to the selected command. Read-only mode prevents
114/// GammaLoop-managed writes into the active state tree, but does not constrain explicit exports or
115/// external processes such as the `!` shell command.
116pub struct CliSession<'a> {
117    state: &'a mut State,
118    run_history: &'a mut RunHistory,
119    cli_settings: &'a mut CLISettings,
120    default_runtime_settings: &'a mut RuntimeSettings,
121    session_state: &'a mut CliSessionState,
122}
123
124impl<'a> CliSession<'a> {
125    /// Combine the mutable state and settings that participate in command execution.
126    ///
127    /// This constructor does not initialize GammaLoop, load files, replay history, or execute boot
128    /// commands. Prefer [`crate::StateLoadOption::load`] followed by
129    /// [`crate::LoadedState::cli_session`] unless the caller already owns a consistent bundle.
130    pub fn new(
131        state: &'a mut State,
132        run_history: &'a mut RunHistory,
133        cli_settings: &'a mut CLISettings,
134        default_runtime_settings: &'a mut RuntimeSettings,
135        session_state: &'a mut CliSessionState,
136    ) -> Self {
137        Self {
138            state,
139            run_history,
140            cli_settings,
141            default_runtime_settings,
142            session_state,
143        }
144    }
145
146    /// Prepare and execute one command against the borrowed state.
147    ///
148    /// Ordinary successful commands are normalized and appended to the replayable run history;
149    /// command-block definition controls have specialized recording behavior. A command can mutate
150    /// the state and settings or write its requested outputs before returning. Inspect both
151    /// [`CommandExecution::flow`] and [`CommandExecution::output`]: save/quit requests use
152    /// [`ControlFlow::Break`], while only evaluation and integration currently return structured
153    /// output.
154    ///
155    /// Errors include parse/preparation failures, invalid state or settings, unavailable backends,
156    /// numerical command failures, and forbidden writes into a read-only state tree. An error does
157    /// not imply that every command-specific external effect was rolled back.
158    pub fn execute_command(&mut self, command: CommandHistory) -> Result<CommandExecution> {
159        let prepared = PreparedCommand::prepare(command, self.run_history, 1)?;
160        self.execute_prepared(prepared, HistoryMode::Record)
161    }
162
163    /// Reapply the stored session settings and commands without appending duplicate history.
164    ///
165    /// Replay mutates the current state and can perform the same command-specific effects as normal
166    /// execution. Callers must honor a returned [`ControlFlow::Break`] save/quit request.
167    pub fn replay_run_history(&mut self) -> Result<ControlFlow<SaveState>> {
168        self.run_history
169            .apply_session_settings(self.cli_settings, self.default_runtime_settings)?;
170        let prepared = prepare_command_histories_with_context(
171            &self.run_history.commands.clone(),
172            self.run_history,
173            1,
174            "run history",
175        )?;
176        self.execute_prepared_commands(prepared, HistoryMode::Suppress)
177    }
178
179    pub fn apply_boot_run_history(
180        &mut self,
181        boot_run_history: &RunHistory,
182        effective_boot_run_history: &RunHistory,
183        booted_existing_state: bool,
184    ) -> Result<ControlFlow<SaveState>> {
185        let interactive_prompt_available = io::stdin().is_terminal() && io::stdout().is_terminal();
186        self.apply_boot_run_history_with_conflict_resolver(
187            boot_run_history,
188            effective_boot_run_history,
189            booted_existing_state,
190            |conflicting_blocks| {
191                if interactive_prompt_available {
192                    return prompt_command_block_conflict_override(conflicting_blocks);
193                }
194
195                Err(eyre!(
196                    "{}. Cannot continue non-interactively; rerun in an interactive terminal or align the command block definitions.",
197                    format_command_block_conflict_message(conflicting_blocks)
198                ))
199            },
200        )
201    }
202
203    pub fn apply_boot_run_history_with_conflict_resolver<F>(
204        &mut self,
205        boot_run_history: &RunHistory,
206        effective_boot_run_history: &RunHistory,
207        booted_existing_state: bool,
208        mut resolve_conflicts: F,
209    ) -> Result<ControlFlow<SaveState>>
210    where
211        F: FnMut(&[String]) -> Result<bool>,
212    {
213        boot_run_history.validate()?;
214
215        if booted_existing_state
216            && !self
217                .run_history
218                .frozen_boot_settings_match(boot_run_history)
219        {
220            let warning = format!(
221                "Boot card settings differ from the frozen settings stored in {}. This session is forced into --read-only-state. Line up cli_settings.global and default_runtime_settings in the boot card with the frozen settings in run.toml if you want to boot this state without read-only mode.",
222                self.cli_settings.state.folder.join("run.toml").display()
223            );
224            self.cli_settings
225                .session
226                .force_read_only_state(ReadOnlyStateOrigin::BootSettingsMismatch);
227            self.cli_settings
228                .session
229                .startup_warnings
230                .push(warning.clone());
231            warn!("{warning}");
232        }
233        if !booted_existing_state {
234            self.run_history.freeze_boot_settings_from(boot_run_history);
235        }
236
237        let mut merged_history = self.run_history.clone();
238        let conflicting_blocks = merged_history
239            .conflicting_command_block_names(&effective_boot_run_history.command_blocks);
240        let overwrite_conflicting_blocks = if conflicting_blocks.is_empty() {
241            false
242        } else if self.cli_settings.session.read_only_state {
243            if self
244                .cli_settings
245                .session
246                .is_read_only_due_to_boot_settings_mismatch()
247            {
248                let warning = format!(
249                    "{}. The boot card settings differ from the frozen settings stored in {}; this session remains in --read-only-state for reproducibility, but will use the boot card command block definitions for this process only.",
250                    format_command_block_conflict_message(&conflicting_blocks),
251                    self.cli_settings.state.folder.join("run.toml").display()
252                );
253                self.cli_settings
254                    .session
255                    .startup_warnings
256                    .push(warning.clone());
257                warn!("{warning}");
258                true
259            } else {
260                return Err(eyre!(
261                    "{}. Cannot proceed while --read-only-state is enabled.",
262                    format_command_block_conflict_message(&conflicting_blocks)
263                ));
264            }
265        } else if resolve_conflicts(&conflicting_blocks)? {
266            true
267        } else {
268            info!(
269                "{}",
270                "Boot run card application cancelled by user.".yellow()
271            );
272            return Ok(ControlFlow::Break(SaveState::default()));
273        };
274        merged_history.merge_command_blocks_with_overwrite(
275            &effective_boot_run_history.command_blocks,
276            overwrite_conflicting_blocks,
277        )?;
278
279        for block in &effective_boot_run_history.command_blocks {
280            // Reusable blocks may inherit variables through nested runs. Validate
281            // names and recursion without expanding those variables; expansion
282            // uses the actual invocation environment before any command executes.
283            let mut pending = vec![(
284                format!("command block '{}'", block.name),
285                block.commands.clone(),
286                vec![block.name.clone()],
287                2,
288            )];
289            while let Some((context, commands, active_blocks, depth)) = pending.pop() {
290                for (index, command) in commands.into_iter().enumerate() {
291                    let Commands::Run(run) = command.command else {
292                        continue;
293                    };
294                    if depth > MAX_RUN_DEPTH {
295                        return Err(eyre!(
296                            "Maximum nested run depth of {} reached while validating {}",
297                            MAX_RUN_DEPTH,
298                            context
299                        ));
300                    }
301                    let names = run
302                        .selected_block_names()
303                        .iter()
304                        .filter(|name| !contains_placeholder(name))
305                        .cloned()
306                        .collect::<Vec<_>>();
307                    let selected = merged_history
308                        .select_command_blocks(&names)
309                        .map_err(|err| {
310                            eyre!(
311                                "Failed to validate {} command #{}: {}",
312                                context,
313                                index + 1,
314                                err
315                            )
316                        })?;
317                    for nested in selected.into_iter().rev() {
318                        if let Some(start) =
319                            active_blocks.iter().position(|name| *name == nested.name)
320                        {
321                            let mut cycle = active_blocks[start..].to_vec();
322                            cycle.push(nested.name.clone());
323                            return Err(eyre!(
324                                "Command block recursion detected: {}",
325                                cycle.join(" -> ")
326                            ));
327                        }
328                        let mut active = active_blocks.clone();
329                        active.push(nested.name.clone());
330                        pending.push((
331                            format!("command block '{}'", nested.name),
332                            nested.commands,
333                            active,
334                            depth + 1,
335                        ));
336                    }
337                    let inline = run.parse_inline_commands()?;
338                    if !inline.is_empty() {
339                        pending.push((
340                            format!("{} run -c", context),
341                            inline,
342                            active_blocks.clone(),
343                            depth + 1,
344                        ));
345                    }
346                }
347            }
348        }
349
350        let prepared = prepare_command_histories_with_context(
351            &effective_boot_run_history.commands,
352            &merged_history,
353            1,
354            "boot",
355        )?;
356
357        self.run_history.merge_command_blocks_with_overwrite(
358            &effective_boot_run_history.command_blocks,
359            overwrite_conflicting_blocks,
360        )?;
361        effective_boot_run_history
362            .apply_session_settings(self.cli_settings, self.default_runtime_settings)?;
363        self.execute_prepared_commands(prepared, HistoryMode::Record)
364    }
365
366    pub fn has_pending_commands_block(&self) -> bool {
367        self.session_state.pending_commands_block.is_some()
368    }
369
370    pub fn pending_commands_block_name(&self) -> Option<String> {
371        self.session_state
372            .pending_commands_block
373            .as_ref()
374            .map(|pending| pending.name.clone())
375    }
376
377    pub fn prompt_state_label(&self) -> String {
378        self.cli_settings.state.prompt_label()
379    }
380
381    pub fn current_commands_block_names(&self) -> Vec<String> {
382        self.run_history
383            .command_blocks
384            .iter()
385            .map(|block| block.name.clone())
386            .collect()
387    }
388
389    pub fn current_command_block_placeholders(
390        &self,
391    ) -> BTreeMap<String, Vec<crate::command_template::PlaceholderSpec>> {
392        self.run_history
393            .command_blocks
394            .iter()
395            .map(|block| {
396                (
397                    block.name.clone(),
398                    self.run_history
399                        .command_block_placeholder_specs(&block.name)
400                        .into_iter()
401                        .collect(),
402                )
403            })
404            .collect()
405    }
406
407    pub fn current_process_entries(&self) -> Vec<ProcessCompletionEntry> {
408        self.state
409            .process_list
410            .processes
411            .iter()
412            .enumerate()
413            .map(|(id, process)| ProcessCompletionEntry {
414                id,
415                name: process.definition.folder_name.clone(),
416                kind: match &process.collection {
417                    ProcessCollection::Amplitudes(_) => ProcessKind::Amplitude,
418                    ProcessCollection::CrossSections(_) => ProcessKind::CrossSection,
419                },
420                integrand_names: process
421                    .collection
422                    .get_integrand_names()
423                    .into_iter()
424                    .map(str::to_string)
425                    .collect(),
426            })
427            .collect()
428    }
429
430    pub fn current_integrand_detail_entries(&self) -> Vec<IntegrandDetailCompletionEntry> {
431        self.state
432            .process_list
433            .processes
434            .iter()
435            .enumerate()
436            .flat_map(|(process_id, process)| {
437                process
438                    .collection
439                    .get_integrand_names()
440                    .into_iter()
441                    .filter_map(move |integrand_name| {
442                        let integrand_name = integrand_name.to_string();
443                        let info = self
444                            .state
445                            .get_integrand_info(
446                                Some(&ProcessRef::Id(process_id)),
447                                Some(&integrand_name),
448                            )
449                            .ok()?;
450                        let mut master_graph_names = info
451                            .graph_groups
452                            .iter()
453                            .filter_map(|group| {
454                                group
455                                    .graphs
456                                    .iter()
457                                    .find(|graph| graph.is_master)
458                                    .map(|graph| graph.name.clone())
459                            })
460                            .collect::<Vec<_>>();
461                        master_graph_names.sort();
462                        master_graph_names.dedup();
463
464                        let mut categories = vec![
465                            "generation".to_string(),
466                            "orientation".to_string(),
467                            "loop_momentum_basis".to_string(),
468                        ];
469                        if info.kind == IntegrandKind::CrossSection {
470                            categories.push("cuts".to_string());
471                        }
472                        let signature_inventory = integrand_signature_inventory(
473                            &process.collection,
474                            &integrand_name,
475                            &self.state.model,
476                        );
477                        let amplitude_signature_inventory = amplitude_graph_signature_inventory(
478                            &process.collection,
479                            &integrand_name,
480                            &self.state.model,
481                            &process.definition,
482                            &self.cli_settings.global.generation,
483                        );
484                        let raised_cut_signature_inventory = raised_cut_signature_inventory(
485                            &process.collection,
486                            &integrand_name,
487                            &self.state.model,
488                            &process.definition,
489                            &self.cli_settings.global.generation,
490                        );
491
492                        Some(IntegrandDetailCompletionEntry {
493                            process_name: process.definition.folder_name.clone(),
494                            integrand_name,
495                            kind: info.kind,
496                            master_graph_names,
497                            raised_all_signatures: signature_inventory.raised_all,
498                            raised_massive_signatures: signature_inventory.raised_massive,
499                            raised_massless_signatures: signature_inventory.raised_massless,
500                            cycle_signatures: signature_inventory.cycles,
501                            amplitude_raised_all_signatures: amplitude_signature_inventory
502                                .raised_all,
503                            amplitude_raised_massive_signatures: amplitude_signature_inventory
504                                .raised_massive,
505                            amplitude_raised_massless_signatures: amplitude_signature_inventory
506                                .raised_massless,
507                            amplitude_cycle_signatures: amplitude_signature_inventory.cycles,
508                            raised_cut_all_signatures: raised_cut_signature_inventory.all,
509                            raised_cut_massive_signatures: raised_cut_signature_inventory.massive,
510                            raised_cut_massless_signatures: raised_cut_signature_inventory.massless,
511                            categories,
512                        })
513                    })
514                    .collect::<Vec<_>>()
515            })
516            .collect()
517    }
518
519    pub fn current_ir_profile_entries(&self) -> Vec<IrProfileCompletionEntry> {
520        self.state
521            .process_list
522            .processes
523            .iter()
524            .filter_map(|process| {
525                let ProcessCollection::CrossSections(cross_sections) = &process.collection else {
526                    return None;
527                };
528
529                Some(
530                    cross_sections
531                        .iter()
532                        .filter_map(|(integrand_name, cross_section)| {
533                            let ProcessIntegrand::CrossSection(integrand) =
534                                cross_section.integrand.as_ref()?
535                            else {
536                                return None;
537                            };
538                            let completion_entries =
539                                integrand.ir_profile_completion_entries(&self.state.model);
540                            let mut graph_names = completion_entries
541                                .iter()
542                                .map(|(graph_name, _)| graph_name.clone())
543                                .collect::<Vec<_>>();
544                            graph_names.sort();
545                            graph_names.dedup();
546
547                            let mut graph_limit_entries = completion_entries
548                                .into_iter()
549                                .flat_map(|(graph_name, limits)| {
550                                    limits
551                                        .into_iter()
552                                        .map(move |limit| format!("{graph_name} {limit}"))
553                                })
554                                .collect::<Vec<_>>();
555                            graph_limit_entries.sort();
556                            graph_limit_entries.dedup();
557
558                            Some(IrProfileCompletionEntry {
559                                process_name: process.definition.folder_name.clone(),
560                                integrand_name: integrand_name.clone(),
561                                graph_names,
562                                graph_limit_entries,
563                            })
564                        })
565                        .collect::<Vec<_>>(),
566                )
567            })
568            .flatten()
569            .collect()
570    }
571
572    #[cfg(feature = "cli")]
573    pub(crate) fn current_process_settings_entries(&self) -> Vec<ProcessSettingsCompletionEntry> {
574        let mut entries = Vec::new();
575
576        for (process_id, process) in self.state.process_list.processes.iter().enumerate() {
577            for integrand_name in process.collection.get_integrand_names() {
578                let Ok(resolved) = process.get_integrand(integrand_name) else {
579                    continue;
580                };
581                let Some(integrand) = resolved.integrand else {
582                    continue;
583                };
584                let Ok(serialized) = serialize_runtime_named_settings(integrand.get_settings())
585                else {
586                    continue;
587                };
588
589                entries.push(ProcessSettingsCompletionEntry {
590                    process_id,
591                    process_name: process.definition.folder_name.clone(),
592                    integrand_name: integrand_name.to_string(),
593                    quantities: serialized.quantities,
594                    observables: serialized.observables,
595                    selectors: serialized.selectors,
596                });
597            }
598        }
599
600        entries.sort_by(|left, right| {
601            left.process_id
602                .cmp(&right.process_id)
603                .then_with(|| left.integrand_name.cmp(&right.integrand_name))
604        });
605        entries
606    }
607
608    pub fn current_model_parameter_entries(
609        &self,
610    ) -> Vec<crate::completion::ModelParameterCompletionEntry> {
611        let mut entries = self
612            .state
613            .model_parameters
614            .keys()
615            .filter_map(|name| {
616                self.state
617                    .model
618                    .parameter(name.namespaceless_string())
619                    .ok()
620                    .map(
621                        |parameter| crate::completion::ModelParameterCompletionEntry {
622                            name: name.namespaceless_string().to_owned(),
623                            parameter_type: parameter.parameter_type.clone(),
624                        },
625                    )
626            })
627            .collect::<Vec<_>>();
628        entries.sort_by(|left, right| left.name.cmp(&right.name));
629        entries
630    }
631
632    pub fn current_model_particle_names(&self) -> Vec<String> {
633        let mut names = self
634            .state
635            .model
636            .particles()
637            .iter()
638            .map(|particle| particle.name.clone())
639            .collect::<Vec<_>>();
640        names.sort();
641        names.dedup();
642        names
643    }
644
645    pub fn current_model_select_particle_names(&self) -> Vec<String> {
646        let mut names = self
647            .state
648            .model
649            .particles()
650            .iter()
651            .filter(|particle| particle.pdg_code > 0)
652            .map(|particle| particle.name.to_string())
653            .collect::<Vec<_>>();
654        names.sort();
655        names.dedup();
656        names
657    }
658
659    pub fn current_model_coupling_names(&self) -> Vec<String> {
660        let mut names = self
661            .state
662            .model
663            .orders()
664            .iter()
665            .map(|order| order.name.to_string())
666            .collect::<Vec<_>>();
667        names.sort();
668        names.dedup();
669        names
670    }
671
672    pub fn current_model_vertices(&self) -> Vec<ModelVertexCompletionEntry> {
673        let mut entries = self
674            .state
675            .model
676            .vertex_rules()
677            .iter()
678            .map(|vertex_rule| ModelVertexCompletionEntry {
679                name: vertex_rule.name.clone(),
680                particles: vertex_rule
681                    .particles
682                    .iter()
683                    .filter_map(|particle| self.state.model.particle_by_id(*particle).ok())
684                    .map(|particle| particle.name.clone())
685                    .collect(),
686            })
687            .collect::<Vec<_>>();
688        entries.sort_by(|left, right| left.name.cmp(&right.name));
689        entries.dedup_by(|left, right| left.name == right.name);
690        entries
691    }
692
693    pub fn run_history_toml(&self) -> Result<String> {
694        self.run_history
695            .to_toml_string(self.cli_settings.try_strings)
696    }
697
698    pub fn global_settings_toml(&self) -> Result<String> {
699        render_smart_toml(self.cli_settings)
700    }
701
702    pub fn active_command_blocks(&self) -> BTreeMap<String, Vec<String>> {
703        self.run_history
704            .command_blocks
705            .iter()
706            .map(|block| {
707                (
708                    block.name.clone(),
709                    block.commands.iter().map(display_command).collect(),
710                )
711            })
712            .collect()
713    }
714
715    pub fn dismiss_pending_commands_block(&mut self, trigger: &str) -> bool {
716        let Some(pending) = self.session_state.pending_commands_block.take() else {
717            return false;
718        };
719
720        info!(
721            "{} {} {} {}",
722            "Dismissing command block definition".blue(),
723            pending.name.green(),
724            "after".blue(),
725            trigger.green()
726        );
727        true
728    }
729
730    fn execute_prepared_commands(
731        &mut self,
732        commands: Vec<PreparedCommand>,
733        history_mode: HistoryMode,
734    ) -> Result<ControlFlow<SaveState>> {
735        for command in commands {
736            let execution = self.execute_prepared(command, history_mode)?;
737            if let ControlFlow::Break(save_state) = execution.flow {
738                return Ok(ControlFlow::Break(save_state));
739            }
740        }
741        Ok(ControlFlow::Continue(()))
742    }
743
744    fn execute_prepared(
745        &mut self,
746        command: PreparedCommand,
747        history_mode: HistoryMode,
748    ) -> Result<CommandExecution> {
749        match command {
750            PreparedCommand::Plain(command) => self.execute_plain(command, history_mode),
751            PreparedCommand::Run { command, plan } => self.execute_run(command, plan, history_mode),
752        }
753    }
754
755    fn execute_plain(
756        &mut self,
757        command: CommandHistory,
758        history_mode: HistoryMode,
759    ) -> Result<CommandExecution> {
760        if self.session_state.pending_commands_block.is_some() {
761            return self.handle_recording_mode(command);
762        }
763
764        let display_text = display_command(&command);
765        info!("{} {}", "Running command".blue(), display_text.green());
766
767        let record = match &command.command {
768            Commands::StartCommandsBlock(start) => {
769                self.start_commands_block(start.clone())?;
770                false
771            }
772            Commands::FinishCommandsBlock => {
773                self.finish_commands_block()?;
774                false
775            }
776            _ => {
777                let execution = command.command.clone().run(
778                    self.state,
779                    self.run_history,
780                    self.cli_settings,
781                    self.default_runtime_settings,
782                )?;
783                if let ControlFlow::Break(save_state) = execution.flow {
784                    if history_mode == HistoryMode::Record {
785                        self.record_command(&command);
786                    }
787                    return Ok(CommandExecution::break_with(save_state));
788                }
789                let output = execution.output;
790                if history_mode == HistoryMode::Record {
791                    self.record_command(&command);
792                }
793                return Ok(CommandExecution::continue_with(output));
794            }
795        };
796
797        if record {
798            self.record_command(&command);
799        }
800
801        Ok(CommandExecution::continue_without_output())
802    }
803
804    fn execute_run(
805        &mut self,
806        command: CommandHistory,
807        plan: PreparedRun,
808        history_mode: HistoryMode,
809    ) -> Result<CommandExecution> {
810        if self.session_state.pending_commands_block.is_some() {
811            return self.handle_recording_mode(command);
812        }
813
814        if plan.is_empty() {
815            return Ok(CommandExecution::continue_without_output());
816        }
817
818        let display_text = display_command(&command);
819        info!("{} {}", "Running command".blue(), display_text.green());
820
821        for block in plan.blocks {
822            info!("{} {}", "Starting command block".blue(), block.name.green());
823            if let ControlFlow::Break(save_state) =
824                self.execute_prepared_commands(block.commands, HistoryMode::Suppress)?
825            {
826                if history_mode == HistoryMode::Record {
827                    self.record_command(&command);
828                }
829                return Ok(CommandExecution::break_with(save_state));
830            }
831        }
832
833        if !plan.commands.is_empty() {
834            info!(
835                "{} {}",
836                "Starting commands supplied with".blue(),
837                "--commands/-c".green()
838            );
839        }
840
841        if let ControlFlow::Break(save_state) =
842            self.execute_prepared_commands(plan.commands, HistoryMode::Suppress)?
843        {
844            if history_mode == HistoryMode::Record {
845                self.record_command(&command);
846            }
847            return Ok(CommandExecution::break_with(save_state));
848        }
849
850        if history_mode == HistoryMode::Record {
851            self.record_command(&command);
852        }
853
854        Ok(CommandExecution::continue_without_output())
855    }
856
857    fn handle_recording_mode(&mut self, command: CommandHistory) -> Result<CommandExecution> {
858        match command.command.clone() {
859            Commands::StartCommandsBlock(_) => Err(eyre!(
860                "Cannot start a new command block definition before finishing the current one"
861            )),
862            Commands::FinishCommandsBlock => {
863                self.finish_commands_block()?;
864                Ok(CommandExecution::continue_without_output())
865            }
866            Commands::Quit(_) => {
867                self.dismiss_pending_commands_block("quit");
868                Ok(CommandExecution::continue_without_output())
869            }
870            _ => {
871                let stored = normalize_command_history(&command);
872                let pending = self
873                    .session_state
874                    .pending_commands_block
875                    .as_mut()
876                    .expect("recording mode requires a pending block");
877                pending.commands.push(stored);
878                Ok(CommandExecution::continue_without_output())
879            }
880        }
881    }
882
883    fn start_commands_block(&mut self, start: StartCommandsBlock) -> Result<()> {
884        if self.session_state.pending_commands_block.is_some() {
885            return Err(eyre!(
886                "Cannot start a new command block definition before finishing the current one"
887            ));
888        }
889
890        if self.run_history.command_block(&start.name).is_some() {
891            info!(
892                "{} {}",
893                "Overwriting existing command block definition".blue(),
894                start.name.green()
895            );
896        } else {
897            info!(
898                "{} {}",
899                "Defining new command block definition".blue(),
900                start.name.green()
901            );
902        }
903
904        self.session_state.pending_commands_block = Some(PendingCommandsBlock {
905            name: start.name,
906            commands: Vec::new(),
907        });
908        Ok(())
909    }
910
911    fn finish_commands_block(&mut self) -> Result<()> {
912        let Some(pending) = self.session_state.pending_commands_block.take() else {
913            return Err(eyre!(
914                "No command block definition is currently being recorded"
915            ));
916        };
917
918        let block = CommandsBlock {
919            name: pending.name.clone(),
920            commands: pending.commands,
921        };
922
923        if let Some(existing_index) = self
924            .run_history
925            .command_blocks
926            .iter()
927            .position(|existing| existing.name == pending.name)
928        {
929            self.run_history.command_blocks[existing_index] = block;
930        } else {
931            self.run_history.command_blocks.push(block);
932        }
933
934        self.run_history.validate()?;
935        Ok(())
936    }
937
938    fn record_command(&mut self, command: &CommandHistory) {
939        if let Some(normalized) = normalize_persisted_command_history(command) {
940            self.run_history
941                .push_with_raw(normalized.command, normalized.raw_string);
942        }
943    }
944}
945
946fn integrand_signature_inventory(
947    collection: &ProcessCollection,
948    integrand_name: &str,
949    model: &Model,
950) -> GraphSelectionSignatureInventory {
951    match collection {
952        ProcessCollection::Amplitudes(amplitudes) => amplitudes
953            .get(integrand_name)
954            .map(|amplitude| {
955                GraphSelectionSignatureInventory::from_master_graphs(
956                    model,
957                    amplitude.graph_group_structure.iter().map(|group| {
958                        let master_graph_id = group
959                            .into_iter()
960                            .next()
961                            .expect("graph group should contain a master graph");
962                        &amplitude.graphs[master_graph_id].graph
963                    }),
964                )
965            })
966            .unwrap_or_else(GraphSelectionSignatureInventory::empty),
967        ProcessCollection::CrossSections(cross_sections) => cross_sections
968            .get(integrand_name)
969            .map(|cross_section| {
970                GraphSelectionSignatureInventory::from_master_graphs(
971                    model,
972                    cross_section.graph_group_structure.iter().map(|group| {
973                        let master_graph_id = group
974                            .into_iter()
975                            .next()
976                            .expect("graph group should contain a master graph");
977                        &cross_section.supergraphs[master_graph_id].graph
978                    }),
979                )
980            })
981            .unwrap_or_else(GraphSelectionSignatureInventory::empty),
982    }
983}
984
985fn amplitude_graph_signature_inventory(
986    collection: &ProcessCollection,
987    integrand_name: &str,
988    model: &Model,
989    process_definition: &ProcessDefinition,
990    generation_settings: &GenerationSettings,
991) -> GraphSelectionSignatureInventory {
992    let ProcessCollection::CrossSections(cross_sections) = collection else {
993        return GraphSelectionSignatureInventory::empty();
994    };
995    cross_sections
996        .get(integrand_name)
997        .map(|cross_section| {
998            cross_section
999                .amplitude_graph_signature_inventory(model, process_definition, generation_settings)
1000                .unwrap_or_else(|_| GraphSelectionSignatureInventory::empty())
1001        })
1002        .unwrap_or_else(GraphSelectionSignatureInventory::empty)
1003}
1004
1005fn raised_cut_signature_inventory(
1006    collection: &ProcessCollection,
1007    integrand_name: &str,
1008    model: &Model,
1009    process_definition: &ProcessDefinition,
1010    generation_settings: &GenerationSettings,
1011) -> RaisedCutSignatureInventory {
1012    let ProcessCollection::CrossSections(cross_sections) = collection else {
1013        return RaisedCutSignatureInventory::empty();
1014    };
1015    cross_sections
1016        .get(integrand_name)
1017        .map(|cross_section| {
1018            cross_section
1019                .raised_cut_signature_inventory(model, process_definition, generation_settings)
1020                .unwrap_or_else(|_| RaisedCutSignatureInventory::empty())
1021        })
1022        .unwrap_or_else(RaisedCutSignatureInventory::empty)
1023}
1024
1025fn normalize_persisted_command_history(command: &CommandHistory) -> Option<CommandHistory> {
1026    match &command.command {
1027        Commands::Quit(_) | Commands::StartCommandsBlock(_) | Commands::FinishCommandsBlock => None,
1028        Commands::Run(run) => normalize_persisted_run_history(command, run),
1029        _ => Some(normalize_command_history(command)),
1030    }
1031}
1032
1033fn normalize_persisted_run_history(
1034    command: &CommandHistory,
1035    run: &crate::commands::Run,
1036) -> Option<CommandHistory> {
1037    let inline_commands = run
1038        .parse_inline_commands()
1039        .expect("persisted run commands should always have parseable inline commands");
1040    let persisted_inline_commands = inline_commands
1041        .iter()
1042        .filter_map(normalize_persisted_command_history)
1043        .collect::<Vec<_>>();
1044
1045    let persisted_run = crate::commands::Run {
1046        block_names: run.block_names.clone(),
1047        defines: run.defines.clone(),
1048        commands: (!persisted_inline_commands.is_empty()).then(|| {
1049            persisted_inline_commands
1050                .iter()
1051                .map(persisted_command_raw_string)
1052                .collect::<Vec<_>>()
1053                .join("; ")
1054        }),
1055    };
1056
1057    if persisted_run.is_noop() {
1058        return None;
1059    }
1060
1061    if persisted_run == *run {
1062        return Some(normalize_command_history(command));
1063    }
1064
1065    let raw_string = persisted_run.canonical_raw_string();
1066    Some(CommandHistory::new_with_raw(
1067        Commands::Run(persisted_run),
1068        raw_string,
1069    ))
1070}
1071
1072fn persisted_command_raw_string(command: &CommandHistory) -> String {
1073    normalize_command_history(command)
1074        .raw_string()
1075        .expect("persisted inline commands should remain representable as raw strings")
1076        .to_string()
1077}
1078
1079fn normalize_command_history(command: &CommandHistory) -> CommandHistory {
1080    let raw_string = command
1081        .raw_string()
1082        .filter(|raw| raw_round_trips(raw, &command.command))
1083        .map(str::to_string)
1084        .or_else(|| match &command.command {
1085            Commands::Run(run) => Some(run.canonical_raw_string()),
1086            _ => None,
1087        });
1088
1089    CommandHistory {
1090        command: command.command.clone(),
1091        raw_string,
1092    }
1093}
1094
1095fn raw_round_trips(raw: &str, command: &Commands) -> bool {
1096    CommandHistory::from_raw_string(raw)
1097        .map(|parsed| parsed.command == *command)
1098        .unwrap_or(false)
1099}
1100
1101pub(crate) fn display_command(command: &CommandHistory) -> String {
1102    let display = if let Some(raw_string) = normalize_command_history(command).raw_string {
1103        raw_string
1104    } else {
1105        format!("{:?}", command.command)
1106    };
1107
1108    truncate_multiline_display_command(&display)
1109}
1110
1111fn truncate_multiline_display_command(display: &str) -> String {
1112    let lines = display.lines().collect::<Vec<_>>();
1113    if lines.len() <= MAX_DISPLAY_COMMAND_LINES {
1114        return display.to_string();
1115    }
1116
1117    let mut truncated = lines[..MAX_DISPLAY_COMMAND_LINES].join("\n");
1118    truncated.push_str("\n[...]");
1119    truncated
1120}
1121
1122#[cfg(test)]
1123mod tests {
1124    use super::{display_command, MAX_DISPLAY_COMMAND_LINES};
1125    use crate::{commands::run::Run, commands::Commands, state::CommandHistory};
1126
1127    #[test]
1128    fn display_command_preserves_multiline_commands_up_to_line_limit() {
1129        let commands = (1..=MAX_DISPLAY_COMMAND_LINES)
1130            .map(|i| format!("cmd{i}"))
1131            .collect::<Vec<_>>()
1132            .join("\n");
1133        let command = CommandHistory::new(Commands::Run(Run {
1134            block_names: Vec::new(),
1135            defines: Vec::new(),
1136            commands: Some(commands.clone()),
1137        }));
1138
1139        let displayed = display_command(&command);
1140
1141        assert_eq!(displayed.lines().count(), MAX_DISPLAY_COMMAND_LINES);
1142        assert!(displayed.contains(&commands));
1143        assert!(!displayed.contains("[...]"));
1144    }
1145
1146    #[test]
1147    fn display_command_truncates_multiline_commands_beyond_line_limit() {
1148        let command = CommandHistory::new(Commands::Run(Run {
1149            block_names: Vec::new(),
1150            defines: Vec::new(),
1151            commands: Some("cmd1\ncmd2\ncmd3\ncmd4\ncmd5\ncmd6".to_string()),
1152        }));
1153
1154        let displayed = display_command(&command);
1155        let displayed_lines = displayed.lines().collect::<Vec<_>>();
1156
1157        assert_eq!(
1158            displayed_lines,
1159            vec!["run -c 'cmd1", "cmd2", "cmd3", "cmd4", "cmd5", "[...]"]
1160        );
1161    }
1162}