openjd-sessions 0.7.0

Open Job Description sessions — local job execution runtime
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright by contributors to this project.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

//! Script runners for environment and step actions.

pub mod env_script;
pub mod step_script;

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use openjd_expr::function_library::FunctionLibrary;
use openjd_expr::ExprValue;
use openjd_model::job::Action;
use openjd_model::job::CancelationMode;
use openjd_model::symbol_table::SymbolTable;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::action::ActionMessage;
use crate::action::ActionState;
use crate::action_filter::ActionFilter;
use crate::error::SessionError;
use crate::logging::log_subsection_banner;
use crate::session_user::SessionUser;
use crate::subprocess::{run_subprocess, SubprocessConfig, SubprocessResult};

/// Method for canceling a running action.
///
/// ```
/// use openjd_sessions::CancelMethod;
/// use std::time::Duration;
///
/// let method = CancelMethod::NotifyThenTerminate {
///     terminate_delay: Duration::from_secs(30),
/// };
/// assert!(matches!(method, CancelMethod::NotifyThenTerminate { .. }));
/// ```
#[derive(Debug, Clone)]
pub enum CancelMethod {
    /// Immediately terminate via SIGKILL.
    Terminate,
    /// Send SIGTERM, wait for grace period, then SIGKILL.
    NotifyThenTerminate { terminate_delay: Duration },
}

impl std::fmt::Display for CancelMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Terminate => write!(f, "Terminate"),
            Self::NotifyThenTerminate { terminate_delay } => {
                write!(f, "NotifyThenTerminate({}s)", terminate_delay.as_secs())
            }
        }
    }
}

/// State of a script runner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptRunnerState {
    Ready,
    Running,
    Canceling,
    Canceled,
    Timeout,
    Failed,
    Success,
}

impl std::fmt::Display for ScriptRunnerState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Ready => write!(f, "Ready"),
            Self::Running => write!(f, "Running"),
            Self::Canceling => write!(f, "Canceling"),
            Self::Canceled => write!(f, "Canceled"),
            Self::Timeout => write!(f, "Timeout"),
            Self::Failed => write!(f, "Failed"),
            Self::Success => write!(f, "Success"),
        }
    }
}

/// Shared infrastructure for script runners.
///
/// Both `EnvironmentScriptRunner` and `StepScriptRunner` compose this struct
/// to avoid duplicating constructor, builder, cancel/state, and subprocess
/// execution logic.
pub(crate) struct ScriptRunnerBase {
    pub state: ScriptRunnerState,
    pub cancel_token: CancellationToken,
    pub cancel_request_rx: Option<tokio::sync::watch::Receiver<Option<Duration>>>,
    pub session_id: String,
    pub working_directory: PathBuf,
    pub files_directory: PathBuf,
    pub helpers_directory: Option<PathBuf>,
    pub user: Option<Arc<dyn SessionUser>>,
    pub redactions_enabled: bool,
    pub initial_redacted_values: Vec<String>,
    pub debug_collect_stdout: bool,
    /// Whether to echo `openjd_*` directive lines to the log. See
    /// [`crate::session::SessionConfig::echo_openjd_directives`]. Defaults
    /// to `true` to match the Python reference implementation.
    pub echo_openjd_directives: bool,
    /// Caller-policy caps and evaluation budgets enforced during action
    /// resolution. See [`crate::session::SessionConfig::limits`].
    pub limits: crate::limits::SessionLimits,
    #[cfg(unix)]
    pub helper: Option<crate::cross_user_helper::CrossUserHelper>,
    #[cfg(windows)]
    pub helper: Option<crate::cross_user_helper::CrossUserHelperWin>,
    pub cancel_writer: Option<std::fs::File>,
}

impl ScriptRunnerBase {
    pub fn new(
        session_id: &str,
        working_directory: PathBuf,
        files_directory: PathBuf,
        user: Option<Arc<dyn SessionUser>>,
    ) -> Self {
        Self {
            state: ScriptRunnerState::Ready,
            cancel_token: CancellationToken::new(),
            cancel_request_rx: None,
            session_id: session_id.to_string(),
            working_directory,
            files_directory,
            helpers_directory: None,
            user,
            redactions_enabled: false,
            initial_redacted_values: Vec::new(),
            debug_collect_stdout: false,
            echo_openjd_directives: true,
            limits: crate::limits::SessionLimits::default(),
            helper: None,
            cancel_writer: None,
        }
    }

    /// Run a resolved action as a subprocess, updating runner state.
    #[allow(clippy::too_many_arguments)]
    pub async fn run_action(
        &mut self,
        action: &Action,
        symtab: &SymbolTable,
        library: Option<&FunctionLibrary>,
        env_vars: &HashMap<String, Option<String>>,
        message_tx: mpsc::UnboundedSender<ActionMessage>,
        default_timeout: Option<Duration>,
        default_cancel_period: Duration,
    ) -> Result<SubprocessResult, SessionError> {
        self.state = ScriptRunnerState::Running;
        log_subsection_banner(&self.session_id, "Phase: Running action");
        let args = resolve_action_args(action, symtab, library, &self.limits)?;
        let timeout =
            resolve_action_timeout(action, symtab, library, &self.limits, default_timeout)?;
        let cancel_method = cancel_method_for_action(
            &action.cancelation,
            symtab,
            library,
            &self.limits,
            default_cancel_period,
        )?;
        let config = SubprocessConfig {
            args,
            env_vars: env_vars.clone(),
            working_dir: Some(self.working_directory.clone()),
            timeout,
            user: self.user.clone(),
            cancel_method,
            cancel_request_rx: self.cancel_request_rx.clone(),
            debug_collect_stdout: self.debug_collect_stdout,
        };
        let mut filter = ActionFilter::new(
            &self.session_id,
            self.echo_openjd_directives,
            self.redactions_enabled,
        );
        filter.add_redacted_values(&self.initial_redacted_values);

        if let Some(ref mut helper) = self.helper {
            let result = crate::cross_user_helper::run_via_helper(
                helper,
                &config,
                &mut filter,
                &self.session_id,
                message_tx,
                self.cancel_writer.as_ref(),
            )
            .await?;
            self.state = state_from_action(result.state);
            return Ok(result);
        }

        let result = run_subprocess(
            config,
            &mut filter,
            &self.session_id,
            message_tx,
            self.cancel_token.clone(),
        )
        .await?;

        self.state = state_from_action(result.state);
        Ok(result)
    }
}

fn state_from_action(action_state: ActionState) -> ScriptRunnerState {
    match action_state {
        ActionState::Success => ScriptRunnerState::Success,
        ActionState::Canceled => ScriptRunnerState::Canceled,
        ActionState::Timeout => ScriptRunnerState::Timeout,
        _ => ScriptRunnerState::Failed,
    }
}

/// An action's `<Cancelation>` with every format string resolved — the
/// run-time counterpart of [`CancelationMode`].
///
/// # What is the problem this solves?
///
/// Format strings are normally delay-processed: the parser stores "this is
/// a format string" and the value resolves right before the action runs.
/// But a cancelation's `mode` is the *schema selector* — the parser needs
/// it to know which object shape it is reading — while a forwarded value
/// like `mode: "{{WrappedAction.Cancelation.Mode}}"` (RFC 0008 round-trip
/// forwarding) only exists at run time. The model therefore carries such a
/// mode as [`CancelationMode::DeferredMode`], and *this* type is where the
/// deferred decision finally lands: right before the action launches, when
/// the symbol table has the `WrappedAction.*` values, the mode expression
/// resolves to `"TERMINATE"`, `"NOTIFY_THEN_TERMINATE"`, or null — and a
/// null mode means the whole cancelation object is treated as never
/// declared (the runtime default applies).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EffectiveCancelation {
    /// No `<Cancelation>` declared, or a deferred mode that resolved to
    /// null. Canceled with the runtime default (terminate).
    Undeclared,
    Terminate,
    NotifyThenTerminate {
        /// `None` when the field was omitted or its whole-field expression
        /// resolved to null — the caller applies the positional schema
        /// default (120 for a task's onRun, 30 otherwise).
        notify_period_seconds: Option<i64>,
    },
}

/// Resolve an action's cancelation config against the symbol table,
/// deciding a deferred (format-string) mode and resolving any
/// notifyPeriodInSeconds format string to its numeric value.
pub(crate) fn resolve_effective_cancelation(
    cancelation: &Option<CancelationMode>,
    symtab: &SymbolTable,
    library: Option<&FunctionLibrary>,
    limits: &crate::limits::SessionLimits,
) -> Result<EffectiveCancelation, SessionError> {
    match cancelation {
        None => Ok(EffectiveCancelation::Undeclared),
        Some(CancelationMode::Terminate) => Ok(EffectiveCancelation::Terminate),
        Some(CancelationMode::NotifyThenTerminate {
            notify_period_in_seconds,
        }) => Ok(EffectiveCancelation::NotifyThenTerminate {
            notify_period_seconds: resolve_notify_period_seconds(
                notify_period_in_seconds.as_ref(),
                symtab,
                library,
                limits,
            )?,
        }),
        Some(CancelationMode::DeferredMode {
            mode,
            notify_period_in_seconds,
        }) => {
            // Single whole-field expressions resolve with target type
            // `string?` (Template Schemas §5.3, FEATURE_BUNDLE_1 deferred
            // mode): a null result drops the whole cancelation object.
            let target = openjd_expr::ExprType::union(vec![
                openjd_expr::ExprType::STRING,
                openjd_expr::ExprType::NULLTYPE,
            ]);
            let value = mode
                .resolve_with(
                    symtab,
                    &crate::limits::fs_options(library, limits).with_target_type(&target),
                )
                .map_err(|e| SessionError::FormatString {
                    context: "cancelation mode".into(),
                    reason: e.to_string(),
                })?;
            match value {
                openjd_expr::ExprValue::Null => {
                    // Null mode drops the ENTIRE cancelation object: mode is
                    // the object's required discriminator, so an "omitted"
                    // mode cannot leave a partial object behind. The action
                    // behaves exactly as if no <Cancelation> were declared.
                    Ok(EffectiveCancelation::Undeclared)
                }
                openjd_expr::ExprValue::String(s) if s == "TERMINATE" => {
                    // Post-resolution the object must validate against the
                    // resolved variant's shape: TERMINATE admits no notify
                    // period, so a non-null period is an error.
                    let period = resolve_notify_period_seconds(
                        notify_period_in_seconds.as_ref(),
                        symtab,
                        library,
                        limits,
                    )?;
                    if period.is_some() {
                        return Err(SessionError::FormatString {
                            context: "cancelation mode".into(),
                            reason: "mode resolved to TERMINATE, which does not accept \
                                     notifyPeriodInSeconds"
                                .into(),
                        });
                    }
                    Ok(EffectiveCancelation::Terminate)
                }
                openjd_expr::ExprValue::String(s) if s == "NOTIFY_THEN_TERMINATE" => {
                    Ok(EffectiveCancelation::NotifyThenTerminate {
                        notify_period_seconds: resolve_notify_period_seconds(
                            notify_period_in_seconds.as_ref(),
                            symtab,
                            library,
                            limits,
                        )?,
                    })
                }
                other => Err(SessionError::FormatString {
                    context: "cancelation mode".into(),
                    reason: format!(
                        "must resolve to TERMINATE, NOTIFY_THEN_TERMINATE, or null; got {other:?}"
                    ),
                }),
            }
        }
    }
}

/// Determine the cancel method from an action's cancelation field,
/// resolving format strings (a deferred mode, or a FEATURE_BUNDLE_1
/// notifyPeriodInSeconds) against the symbol table.
pub(crate) fn cancel_method_for_action(
    cancelation: &Option<CancelationMode>,
    symtab: &SymbolTable,
    library: Option<&FunctionLibrary>,
    limits: &crate::limits::SessionLimits,
    default_notify_period: Duration,
) -> Result<CancelMethod, SessionError> {
    Ok(
        match resolve_effective_cancelation(cancelation, symtab, library, limits)? {
            EffectiveCancelation::Undeclared | EffectiveCancelation::Terminate => {
                CancelMethod::Terminate
            }
            EffectiveCancelation::NotifyThenTerminate {
                notify_period_seconds,
            } => CancelMethod::NotifyThenTerminate {
                terminate_delay: notify_period_seconds
                    .map(|n| Duration::from_secs(n as u64))
                    .unwrap_or(default_notify_period),
            },
        },
    )
}

/// Resolve an Action's timeout field to a Duration, falling back to a default.
///
/// A single whole-field expression resolves with target type `int?` per
/// Template Schemas §5 (a `null` result means "not provided", and values
/// like `{{ 120.0 }}` or `{{ '120' }}` coerce to the int they denote). A
/// multi-segment format string concatenates to a string and is parsed as
/// a positive integer.
pub(crate) fn resolve_action_timeout(
    action: &Action,
    symtab: &SymbolTable,
    library: Option<&FunctionLibrary>,
    limits: &crate::limits::SessionLimits,
    default: Option<Duration>,
) -> Result<Option<Duration>, SessionError> {
    match &action.timeout {
        Some(fmt) => {
            let target = openjd_expr::ExprType::union(vec![
                openjd_expr::ExprType::INT,
                openjd_expr::ExprType::NULLTYPE,
            ]);
            let value = fmt
                .resolve_with(
                    symtab,
                    &crate::limits::fs_options(library, limits).with_target_type(&target),
                )
                .map_err(|e| SessionError::FormatString {
                    context: "timeout".into(),
                    reason: e.to_string(),
                })?;
            let secs: u64 = match value {
                // Whole-field expression resolved to null (e.g. forwarding
                // `timeout: "{{WrappedAction.Timeout}}"` when the wrapped
                // action specified no timeout): the field is treated as
                // not provided, so the positional default applies.
                openjd_expr::ExprValue::Null => return Ok(default),
                openjd_expr::ExprValue::Int(n) => {
                    // The `int?` target guarantees an integer, but not a
                    // positive one; reject non-positive values with the
                    // interpolated value, not a Debug rendering.
                    if n <= 0 {
                        return Err(SessionError::FormatString {
                            context: "timeout".into(),
                            reason: format!("timeout must be a positive integer, got '{n}'"),
                        });
                    }
                    n as u64
                }
                // Multi-segment format strings concatenate to a string.
                openjd_expr::ExprValue::String(ref s) => match s.trim().parse::<u64>() {
                    Ok(n) if n > 0 => n,
                    _ => {
                        return Err(SessionError::FormatString {
                            context: "timeout".into(),
                            reason: format!("timeout must be a positive integer, got '{s}'"),
                        })
                    }
                },
                // Unreachable under the `int?` target; kept as a
                // defensive arm for unexpected internal states.
                other => {
                    return Err(SessionError::FormatString {
                        context: "timeout".into(),
                        reason: format!("timeout must be a positive integer, got {other:?}"),
                    })
                }
            };
            Ok(Some(Duration::from_secs(secs)))
        }
        None => Ok(default),
    }
}

/// Resolve an optional `notifyPeriodInSeconds` FormatString into an
/// optional positive integer number of seconds.
///
/// Full FormatString resolution against the supplied symbol table. The
/// field is `int?` under whole-field expression semantics (Template
/// Schemas §5.3.2): `Ok(None)` means the field was omitted or its
/// whole-field expression resolved to null — the caller applies the
/// positional schema default. Zero and negative values are rejected,
/// matching the schema's `<posinteger>` typing.
///
/// Used by both the WRAP_ACTIONS seed path (populating
/// `WrappedAction.Cancelation.NotifyPeriodInSeconds` per RFC 0008) and the
/// enforcement path (`cancel_method_for_action`), so the value a wrap
/// script *sees* is always the value the runtime *enforces*.
pub(crate) fn resolve_notify_period_seconds(
    fs: Option<&openjd_model::FormatString>,
    symtab: &SymbolTable,
    library: Option<&FunctionLibrary>,
    limits: &crate::limits::SessionLimits,
) -> Result<Option<i64>, SessionError> {
    let Some(fs) = fs else {
        return Ok(None);
    };
    // Single whole-field expressions resolve with target type `int?`
    // (Template Schemas §5.3.2); multi-segment strings concatenate and
    // are parsed below.
    let target = openjd_expr::ExprType::union(vec![
        openjd_expr::ExprType::INT,
        openjd_expr::ExprType::NULLTYPE,
    ]);
    let value = fs
        .resolve_with(
            symtab,
            &crate::limits::fs_options(library, limits).with_target_type(&target),
        )
        .map_err(|e| SessionError::FormatString {
            context: "notifyPeriodInSeconds".into(),
            reason: e.to_string(),
        })?;
    let n: i64 = match value {
        // Whole-field expression resolved to null: the field is treated as
        // not provided (schema defaults apply).
        openjd_expr::ExprValue::Null => return Ok(None),
        openjd_expr::ExprValue::Int(n) => n,
        openjd_expr::ExprValue::String(s) => {
            s.trim().parse().map_err(|_| SessionError::FormatString {
                context: "notifyPeriodInSeconds".into(),
                reason: format!("notifyPeriodInSeconds must be a positive integer, got '{s}'"),
            })?
        }
        other => {
            return Err(SessionError::FormatString {
                context: "notifyPeriodInSeconds".into(),
                reason: format!("notifyPeriodInSeconds must be a positive integer, got {other:?}"),
            })
        }
    };
    if n <= 0 {
        return Err(SessionError::FormatString {
            context: "notifyPeriodInSeconds".into(),
            reason: format!("notifyPeriodInSeconds must be positive, got '{n}'"),
        });
    }
    // Mirror the static validator's cap on literal values (Template
    // Schemas §5.3.2 maximum: 600): format-string values could not be
    // checked at parse time, so the resolved value is bounds-checked here.
    if n > 600 {
        return Err(SessionError::FormatString {
            context: "notifyPeriodInSeconds".into(),
            reason: format!("notifyPeriodInSeconds must not exceed 600, got '{n}'"),
        });
    }
    Ok(Some(n))
}

/// Resolve an Action's command and args into a flat argument list.
///
/// When the caller opted into
/// [`SessionLimits::max_resolved_arg_len`](crate::SessionLimits::max_resolved_arg_len),
/// the resolved command and every final argv entry (after null-skip and
/// list-flatten) are checked against it — task execution is the
/// enforcement boundary for §5.1/§5.2, which set no spec maximum but
/// acknowledge the operating system's own limit.
pub(crate) fn resolve_action_args(
    action: &Action,
    symtab: &SymbolTable,
    library: Option<&FunctionLibrary>,
    limits: &crate::limits::SessionLimits,
) -> Result<Vec<String>, SessionError> {
    let opts = crate::limits::fs_options(library, limits);
    let check_len = |context: String, s: &str| -> Result<(), SessionError> {
        if let Some(max_len) = limits.max_resolved_arg_len {
            let n = s.chars().count();
            if n > max_len {
                return Err(SessionError::FormatString {
                    context,
                    reason: format!(
                        "resolved value is {n} characters, exceeding the maximum of {max_len}."
                    ),
                });
            }
        }
        Ok(())
    };
    let command = action
        .command
        .resolve_string_with(symtab, &opts)
        .map_err(|e| SessionError::FormatString {
            context: "command".into(),
            reason: e.to_string(),
        })?;
    check_len("command".into(), &command)?;
    let mut args = vec![command];
    if let Some(arg_fmts) = &action.args {
        for (j, fs) in arg_fmts.iter().enumerate() {
            if let Ok(val) = fs.resolve_with(symtab, &opts) {
                match val {
                    ExprValue::Null => continue,
                    val if val.is_list() => {
                        if let Some(elements) = val.list_elements() {
                            for elem in &elements {
                                let s = elem.to_display_string();
                                check_len(format!("args[{j}]"), &s)?;
                                args.push(s);
                            }
                        }
                        continue;
                    }
                    val => {
                        let s = val.to_display_string();
                        check_len(format!("args[{j}]"), &s)?;
                        args.push(s);
                    }
                }
            } else {
                let s = fs.resolve_string_with(symtab, &opts).map_err(|e| {
                    SessionError::FormatString {
                        context: "argument".into(),
                        reason: e.to_string(),
                    }
                })?;
                check_len(format!("args[{j}]"), &s)?;
                args.push(s);
            }
        }
    }
    Ok(args)
}

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

    #[test]
    fn script_runner_state_display() {
        assert_eq!(ScriptRunnerState::Ready.to_string(), "Ready");
        assert_eq!(ScriptRunnerState::Running.to_string(), "Running");
        assert_eq!(ScriptRunnerState::Canceling.to_string(), "Canceling");
        assert_eq!(ScriptRunnerState::Canceled.to_string(), "Canceled");
        assert_eq!(ScriptRunnerState::Timeout.to_string(), "Timeout");
        assert_eq!(ScriptRunnerState::Failed.to_string(), "Failed");
        assert_eq!(ScriptRunnerState::Success.to_string(), "Success");
    }

    #[test]
    fn cancel_method_display() {
        assert_eq!(CancelMethod::Terminate.to_string(), "Terminate");
        assert_eq!(
            CancelMethod::NotifyThenTerminate {
                terminate_delay: Duration::from_secs(30)
            }
            .to_string(),
            "NotifyThenTerminate(30s)"
        );
    }

    fn fs(s: &str) -> openjd_model::FormatString {
        openjd_model::FormatString::new(s).unwrap()
    }

    fn action_with_timeout(timeout: &str) -> Action {
        Action {
            command: fs("echo"),
            args: None,
            timeout: Some(fs(timeout)),
            cancelation: None,
        }
    }

    #[test]
    fn timeout_nonpositive_int_reports_the_value() {
        // Under the int? target, `{{ 0 }}`, `{{ '0' }}`, and `{{ 0 - 5 }}`
        // all coerce to Int before the positivity check: the error must
        // interpolate the value, not Debug-render the ExprValue.
        let symtab = SymbolTable::default();
        for (expr, shown) in [
            ("{{ 0 }}", "'0'"),
            ("{{ '0' }}", "'0'"),
            ("{{ 0 - 5 }}", "'-5'"),
        ] {
            let err = resolve_action_timeout(
                &action_with_timeout(expr),
                &symtab,
                None,
                &Default::default(),
                None,
            )
            .unwrap_err();
            assert_eq!(
                err.to_string(),
                format!(
                    "Failed to resolve timeout: timeout must be a positive integer, got {shown}"
                ),
                "expr {expr}"
            );
        }
    }

    #[test]
    fn timeout_positive_and_null_resolve() {
        let symtab = SymbolTable::default();
        assert_eq!(
            resolve_action_timeout(
                &action_with_timeout("{{ 90 }}"),
                &symtab,
                None,
                &Default::default(),
                None
            )
            .unwrap(),
            Some(Duration::from_secs(90))
        );
        // Whole-field null: field treated as not provided, default applies.
        assert_eq!(
            resolve_action_timeout(
                &action_with_timeout("{{ null }}"),
                &symtab,
                None,
                &Default::default(),
                Some(Duration::from_secs(30))
            )
            .unwrap(),
            Some(Duration::from_secs(30))
        );
    }

    #[test]
    fn notify_period_resolves_literal_and_bounds() {
        let symtab = SymbolTable::default();
        // In-range values resolve.
        assert_eq!(
            resolve_notify_period_seconds(Some(&fs("45")), &symtab, None, &Default::default())
                .unwrap(),
            Some(45)
        );
        // Omitted field is None.
        assert_eq!(
            resolve_notify_period_seconds(None, &symtab, None, &Default::default()).unwrap(),
            None
        );
        // The Template Schemas §5.3.2 cap applies to resolved values just
        // as the static validator applies it to literals: format-string
        // values could not be checked at parse time.
        let err =
            resolve_notify_period_seconds(Some(&fs("9999")), &symtab, None, &Default::default())
                .unwrap_err();
        assert!(
            err.to_string().contains("must not exceed 600"),
            "expected cap error; got: {err}"
        );
        // Non-positive values are rejected.
        assert!(
            resolve_notify_period_seconds(Some(&fs("0")), &symtab, None, &Default::default())
                .is_err()
        );
    }

    #[test]
    fn notify_period_whole_field_null_is_none() {
        let mut symtab = SymbolTable::default();
        symtab
            .set("X", openjd_expr::ExprValue::Null)
            .expect("symtab");
        assert_eq!(
            resolve_notify_period_seconds(Some(&fs("{{X}}")), &symtab, None, &Default::default())
                .unwrap(),
            None
        );
    }

    // === SessionLimits: resolved-argument cap and budgets (run-time enforcement) ===

    fn action_with_args(command: &str, args: &[&str]) -> Action {
        Action {
            command: fs(command),
            args: Some(args.iter().map(|a| fs(a)).collect()),
            timeout: None,
            cancelation: None,
        }
    }

    fn arg_cap(n: usize) -> crate::limits::SessionLimits {
        crate::limits::SessionLimits {
            max_resolved_arg_len: Some(n),
            ..Default::default()
        }
    }

    #[test]
    fn resolved_command_over_arg_cap_rejected() {
        let symtab = SymbolTable::default();
        let action = action_with_args("{{ 'A' * 200 }}", &[]);
        let err = resolve_action_args(&action, &symtab, None, &arg_cap(100)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "Failed to resolve command: resolved value is 200 characters, exceeding the maximum of 100."
        );
    }

    #[test]
    fn resolved_arg_over_cap_rejected_with_index() {
        let symtab = SymbolTable::default();
        let action = action_with_args("echo", &["ok", "{{ 'A' * 200 }}"]);
        let err = resolve_action_args(&action, &symtab, None, &arg_cap(100)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "Failed to resolve args[1]: resolved value is 200 characters, exceeding the maximum of 100."
        );
    }

    #[test]
    fn flattened_list_arg_elements_each_checked() {
        // A list-valued args element flattens into one argv entry per
        // member (§5.2 / resolve_string_list semantics): the cap applies
        // to each final entry.
        let symtab = SymbolTable::default();
        let action = action_with_args("echo", &["{{ ['A' * 150] * 2 }}"]);
        let err = resolve_action_args(&action, &symtab, None, &arg_cap(100)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "Failed to resolve args[0]: resolved value is 150 characters, exceeding the maximum of 100."
        );
        // Elements under the cap pass even though the list's display
        // form is over it.
        let action = action_with_args("echo", &["{{ ['A' * 90] * 3 }}"]);
        let args = resolve_action_args(&action, &symtab, None, &arg_cap(100)).unwrap();
        assert_eq!(args.len(), 4); // command + 3 flattened entries
    }

    #[test]
    fn args_at_cap_and_uncapped_pass() {
        let symtab = SymbolTable::default();
        let action = action_with_args("echo", &["{{ 'A' * 100 }}"]);
        assert!(resolve_action_args(&action, &symtab, None, &arg_cap(100)).is_ok());
        // §5.1/§5.2 set no spec maximum: no cap by default.
        let action = action_with_args("echo", &["{{ 'A' * 200 }}"]);
        assert!(resolve_action_args(&action, &symtab, None, &Default::default()).is_ok());
    }

    #[test]
    fn arg_cap_measures_characters_not_bytes() {
        // The run-time cap counts Unicode scalar values, matching the
        // validation-side checks: 100 three-byte CJK characters satisfy
        // a 100-character cap (300 UTF-8 bytes), 101 fail it.
        let symtab = SymbolTable::default();
        let action = action_with_args("echo", &[&"\u{4e16}".repeat(100)]);
        assert!(resolve_action_args(&action, &symtab, None, &arg_cap(100)).is_ok());
        let action = action_with_args("echo", &[&"\u{4e16}".repeat(101)]);
        let err = resolve_action_args(&action, &symtab, None, &arg_cap(100)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "Failed to resolve args[0]: resolved value is 101 characters, exceeding the maximum of 100."
        );
    }

    #[test]
    fn session_limits_from_caller_limits_mirrors_runtime_fields() {
        // One policy value drives both stages: the conversion copies the
        // four run-time-relevant fields and ignores the rest.
        let caller = openjd_model::CallerLimits {
            max_resolved_arg_len: Some(1),
            max_resolved_data_len: Some(2),
            max_eval_memory_bytes: Some(3),
            max_eval_operations: Some(4),
            max_step_count: Some(99), // no run-time counterpart
            ..Default::default()
        };
        let session: crate::limits::SessionLimits = (&caller).into();
        assert_eq!(
            session,
            crate::limits::SessionLimits {
                max_resolved_arg_len: Some(1),
                max_resolved_data_len: Some(2),
                max_eval_memory_bytes: Some(3),
                max_eval_operations: Some(4),
            }
        );
    }

    #[test]
    fn arg_evaluation_respects_memory_budget() {
        // The evaluation memory budget (the Expression Language spec's
        // lever against `'A' * N` blowups) bounds argument resolution.
        let symtab = SymbolTable::default();
        let limits = crate::limits::SessionLimits {
            max_eval_memory_bytes: Some(1000),
            ..Default::default()
        };
        let action = action_with_args("echo", &["{{ 'A' * 100000 }}"]);
        let err = resolve_action_args(&action, &symtab, None, &limits).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("exceeded limit (1000 bytes)"),
            "expected memory-budget error; got: {msg}"
        );
    }

    #[test]
    fn arg_evaluation_respects_operation_budget() {
        let symtab = SymbolTable::default();
        let limits = crate::limits::SessionLimits {
            max_eval_operations: Some(50),
            ..Default::default()
        };
        let action = action_with_args("echo", &["{{ sum([1] * 1000) }}"]);
        let err = resolve_action_args(&action, &symtab, None, &limits).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("exceeded limit (50)"),
            "expected operation-budget error; got: {msg}"
        );
    }
}