nu-protocol 0.115.0

Nushell's internal protocols, including its abstract syntax tree
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
use crate::{
    Config, ENV_VARIABLE_ID, IntoValue, LAST_VARIABLE_ID, NU_VARIABLE_ID, OutDest, PipelineData,
    PipelineMetadata, ShellError, Span, Value, VarId,
    ast::PathMember,
    engine::{
        ArgumentStack, DEFAULT_OVERLAY_NAME, EngineState, EnvName, ErrorHandlerStack, Redirection,
        ScopeBindings, StackCallArgGuard, StackCollectValueGuard, StackIoGuard, StackOutDest,
        StackWithInvocation,
    },
    ir::ScopeRegion,
    record, report_shell_warning,
    shell_error::generic::GenericError,
    truncate_value_to_budget,
};
use std::{
    collections::{HashMap, HashSet},
    fs::File,
    path::{Component, MAIN_SEPARATOR},
    sync::{Arc, Mutex},
};

/// Shared interactive last-result (`$ans`) storage.
///
/// Held in an [`Arc`] so REPL child stacks from [`Stack::with_parent`] see the same
/// payload and can clear `warn_pending` without mutating an immutable parent frame.
///
/// When [`Self::present`] is true, reading `$ans` yields a record with
/// `exit_code`, `duration`, and `command`. The `last` field is included only when a
/// payload is stored. When false (never snapshotted after a user command), `$ans`
/// is `nothing`.
#[derive(Debug, Default)]
struct LastResultSlot {
    /// Whether `$ans` should resolve to a record (vs `nothing`).
    present: bool,
    /// Pipeline payload for the `last` field (`None` when payload capture is off).
    last: Option<Value>,
    /// Pipeline metadata for replaying `last` (e.g. `ls` path_columns / colors).
    metadata: Option<PipelineMetadata>,
    truncated: bool,
    /// Exit code of the last REPL line (mirrors `$env.LAST_EXIT_CODE`).
    exit_code: i64,
    /// Duration of the last REPL line in nanoseconds (Nushell `Duration` value).
    duration_ns: i64,
    /// Exact REPL source of the last user line (same buffer reedline stores in history).
    command: String,
    /// Set when a store was truncated; moved to `warn_deferred` on first access.
    warn_pending: bool,
    /// Set when `$ans` was accessed after a truncated store; reported after output prints.
    warn_deferred: bool,
}

/// Environment variables per overlay
pub type EnvVars = HashMap<String, HashMap<EnvName, Value>>;

/// A runtime value stack used during evaluation
///
/// A note on implementation:
///
/// We previously set up the stack in a traditional way, where stack frames had parents which would
/// represent other frames that you might return to when exiting a function.
///
/// While experimenting with blocks, we found that we needed to have closure captures of variables
/// seen outside of the blocks, so that they blocks could be run in a way that was both thread-safe
/// and followed the restrictions for closures applied to iterators. The end result left us with
/// closure-captured single stack frames that blocks could see.
///
/// Blocks make up the only scope and stack definition abstraction in Nushell. As a result, we were
/// creating closure captures at any point we wanted to have a Block value we could safely evaluate
/// in any context. This meant that the parents were going largely unused, with captured variables
/// taking their place. The end result is this, where we no longer have separate frames, but instead
/// use the Stack as a way of representing the local and closure-captured state.
#[derive(Debug, Clone)]
pub struct Stack {
    /// Variables
    pub vars: Vec<(VarId, Value)>,
    /// Environment variables arranged as a stack to be able to recover values from parent scopes
    pub env_vars: Vec<Arc<EnvVars>>,
    /// Tells which environment variables from engine state are hidden, per overlay.
    pub env_hidden: Arc<HashMap<String, HashSet<EnvName>>>,
    /// Tracks env vars hidden in this stack context to report repeated `hide-env` calls.
    ///
    /// This is separate from `env_hidden`: `env_hidden` controls runtime visibility for engine
    /// state values, while `env_hide_history` preserves command semantics for repeated hides.
    pub env_hide_history: Arc<HashMap<String, HashSet<EnvName>>>,
    /// List of active overlays
    pub active_overlays: Vec<String>,
    /// Argument stack for IR evaluation
    pub arguments: ArgumentStack,
    /// Error handler stack for IR evaluation
    pub error_handlers: ErrorHandlerStack,
    /// Finally handler stack for IR evaluation
    pub finally_run_handlers: ErrorHandlerStack,
    pub recursion_count: u64,
    pub parent_stack: Option<Arc<Stack>>,
    /// Variables that have been deleted (this is used to hide values from parent stack lookups)
    pub parent_deletions: Vec<VarId>,
    /// Variables deleted in this stack
    pub deletions: Vec<VarId>,
    /// Locally updated config. Use [`.get_config()`](Self::get_config) to access correctly.
    pub config: Option<Arc<Config>>,
    pub(crate) out_dest: StackOutDest,
    /// When `true`, external processes spawned with `PipelineData::Empty` input
    /// receive `/dev/null` for stdin instead of inheriting the terminal.
    pub suppress_stdin: bool,
    /// Active block-local scope bindings (commands/modules), outer → inner.
    ///
    /// Pushed when evaluating a whole block via `eval_ir_block` (closures, custom commands).
    /// Used by `scope` together with [`Self::ir_scope_regions`].
    pub active_scope_bindings: Vec<Arc<ScopeBindings>>,
    /// Scope regions of the IR block currently being evaluated (inlined keyword bodies).
    pub ir_scope_regions: Vec<ScopeRegion>,
    /// Current program counter while evaluating IR (for matching [`Self::ir_scope_regions`]).
    pub ir_instruction_index: Option<usize>,
    /// Interactive last-result payload for [`LAST_VARIABLE_ID`] (e.g. `$ans`).
    ///
    /// Shared across parent/child stacks so REPL iterations (which use
    /// [`Stack::with_parent`]) can store and clear truncation warnings correctly.
    last_result: Arc<Mutex<LastResultSlot>>,
}

impl Default for Stack {
    fn default() -> Self {
        Self::new()
    }
}

impl Stack {
    /// Create a new stack.
    ///
    /// stdout and stderr will be set to [`OutDest::Inherit`]. So, if the last command is an external command,
    /// then its output will be forwarded to the terminal/stdio streams.
    ///
    /// Use [`Stack::collect_value`] afterwards if you need to evaluate an expression to a [`Value`]
    /// (as opposed to a [`PipelineData`](crate::PipelineData)).
    pub fn new() -> Self {
        Self {
            vars: Vec::new(),
            env_vars: Vec::new(),
            env_hidden: Arc::new(HashMap::new()),
            env_hide_history: Arc::new(HashMap::new()),
            active_overlays: vec![DEFAULT_OVERLAY_NAME.to_string()],
            arguments: ArgumentStack::new(),
            error_handlers: ErrorHandlerStack::new(),
            finally_run_handlers: ErrorHandlerStack::new(),
            recursion_count: 0,
            parent_stack: None,
            parent_deletions: vec![],
            deletions: vec![],
            config: None,
            out_dest: StackOutDest::new(),
            suppress_stdin: false,
            active_scope_bindings: vec![],
            ir_scope_regions: vec![],
            ir_instruction_index: None,
            last_result: Arc::new(Mutex::new(LastResultSlot::default())),
        }
    }

    /// Create a new child stack from a parent.
    ///
    /// Changes from this child can be merged back into the parent with
    /// [`Stack::with_changes_from_child`]
    pub fn with_parent(parent: Arc<Stack>) -> Stack {
        Stack {
            // here we are still cloning environment variable-related information
            env_vars: parent.env_vars.clone(),
            env_hidden: parent.env_hidden.clone(),
            env_hide_history: parent.env_hide_history.clone(),
            active_overlays: parent.active_overlays.clone(),
            arguments: ArgumentStack::new(),
            error_handlers: ErrorHandlerStack::new(),
            finally_run_handlers: ErrorHandlerStack::new(),
            recursion_count: parent.recursion_count,
            vars: vec![],
            parent_deletions: vec![],
            deletions: vec![],
            config: parent.config.clone(),
            out_dest: parent.out_dest.clone(),
            suppress_stdin: parent.suppress_stdin,
            // Child inherits outer block bindings so nested `scope` still sees them.
            active_scope_bindings: parent.active_scope_bindings.clone(),
            // Nested IR evaluation installs its own regions/pc.
            ir_scope_regions: vec![],
            ir_instruction_index: None,
            // Share last-result with the parent (REPL uses with_parent every iteration).
            last_result: parent.last_result.clone(),
            parent_stack: Some(parent),
        }
    }

    /// Push block-local scope bindings for the duration of evaluating a whole block.
    pub fn push_scope_bindings(&mut self, bindings: Arc<ScopeBindings>) {
        self.active_scope_bindings.push(bindings);
    }

    /// Pop the most recently pushed whole-block scope bindings.
    pub fn pop_scope_bindings(&mut self) {
        let popped = self.active_scope_bindings.pop();
        debug_assert!(
            popped.is_some(),
            "pop_scope_bindings with empty active_scope_bindings (unbalanced push/pop)"
        );
    }

    /// Take an [`Arc`] parent, and a child, and apply all the changes from a child back to the parent.
    ///
    /// Here it is assumed that `child` was created by a call to [`Stack::with_parent`] with `parent`.
    ///
    /// For this to be performant and not clone `parent`, `child` should be the only other
    /// referencer of `parent`.
    pub fn with_changes_from_child(parent: Arc<Stack>, child: Stack) -> Stack {
        // we're going to drop the link to the parent stack on our new stack
        // so that we can unwrap the Arc as a unique reference
        drop(child.parent_stack);
        let mut unique_stack = Arc::unwrap_or_clone(parent);

        unique_stack
            .vars
            .retain(|(var, _)| !child.parent_deletions.contains(var));
        for (var, value) in child.vars {
            unique_stack.add_var(var, value);
        }
        unique_stack.env_vars = child.env_vars;
        unique_stack.env_hidden = child.env_hidden;
        unique_stack.env_hide_history = child.env_hide_history;
        unique_stack.active_overlays = child.active_overlays;
        unique_stack.config = child.config;
        // last_result is Arc-shared with the child; no merge needed.
        unique_stack
    }

    pub fn with_env(
        &mut self,
        env_vars: &[Arc<EnvVars>],
        env_hidden: &Arc<HashMap<String, HashSet<EnvName>>>,
    ) {
        // Do not clone the environment if it hasn't changed
        if self.env_vars.iter().any(|scope| !scope.is_empty()) {
            env_vars.clone_into(&mut self.env_vars);
        }

        if !self.env_hidden.is_empty() {
            self.env_hidden.clone_from(env_hidden);
        }
    }

    /// Lookup a variable, returning None if it is not present
    fn lookup_var(&self, var_id: VarId) -> Option<Value> {
        if var_id == LAST_VARIABLE_ID {
            return self.assemble_ans_record(Span::unknown());
        }

        for (id, val) in &self.vars {
            if var_id == *id {
                return Some(val.clone());
            }
        }

        if let Some(stack) = &self.parent_stack
            && !self.parent_deletions.contains(&var_id)
        {
            return stack.lookup_var(var_id);
        }
        None
    }

    fn with_last_result_slot<R>(&self, f: impl FnOnce(&LastResultSlot) -> R) -> R {
        match self.last_result.lock() {
            Ok(slot) => f(&slot),
            // Poison is rare; recover so `$ans` / capture do not hard-panic the REPL.
            Err(poisoned) => f(&poisoned.into_inner()),
        }
    }

    fn with_last_result_slot_mut<R>(&self, f: impl FnOnce(&mut LastResultSlot) -> R) -> R {
        match self.last_result.lock() {
            Ok(mut slot) => f(&mut slot),
            Err(poisoned) => {
                let mut slot = poisoned.into_inner();
                // Drop potentially inconsistent state after a panic while locked.
                *slot = LastResultSlot::default();
                f(&mut slot)
            }
        }
    }

    /// Build the `$ans` record when the slot is present; otherwise `None` (→ `nothing`).
    ///
    /// Omits the `last` field entirely when no payload is stored (e.g. budget is `0`),
    /// so `$ans` is `{ exit_code, duration, command }` only. `command` is always included
    /// once the slot is present.
    fn assemble_ans_record(&self, span: Span) -> Option<Value> {
        self.with_last_result_slot(|slot| {
            if !slot.present {
                return None;
            }
            Some(match &slot.last {
                Some(last) => Value::record(
                    record! {
                        "last" => last.clone().with_span(span),
                        "exit_code" => Value::int(slot.exit_code, span),
                        "duration" => Value::duration(slot.duration_ns, span),
                        "command" => Value::string(slot.command.clone(), span),
                    },
                    span,
                ),
                None => Value::record(
                    record! {
                        "exit_code" => Value::int(slot.exit_code, span),
                        "duration" => Value::duration(slot.duration_ns, span),
                        "command" => Value::string(slot.command.clone(), span),
                    },
                    span,
                ),
            })
        })
    }

    /// Drop the entire `$ans` slot (full clear).
    pub fn clear_last_result(&mut self) {
        self.with_last_result_slot_mut(|slot| {
            if let Some(old) = slot.last.take() {
                drop(old);
            }
            *slot = LastResultSlot::default();
        });
    }

    /// Drop only `$ans.last` and its metadata/truncation flags, freeing payload memory.
    ///
    /// Leaves `present`, `exit_code`, `duration`, and `command` unchanged so a budget of
    /// `0` can still expose timing/exit status/source without retaining the pipeline value.
    pub fn clear_last_result_payload(&mut self) {
        self.with_last_result_slot_mut(|slot| {
            if let Some(old) = slot.last.take() {
                drop(old);
            }
            slot.metadata = None;
            slot.truncated = false;
            slot.warn_pending = false;
            slot.warn_deferred = false;
        });
    }

    /// Store `value` as `$ans.last`, enforcing `budget` via truncation.
    ///
    /// When `budget == 0`, payload capture is disabled (clears `.last` only; exit code,
    /// duration, and `command` stay). Preserves pipeline `metadata` (e.g. `path_columns` used for
    /// `ls` coloring) so replaying `$ans.last` can match the original display.
    pub fn set_last_result(
        &mut self,
        value: Value,
        metadata: Option<PipelineMetadata>,
        budget: usize,
    ) {
        if budget == 0 {
            self.clear_last_result_payload();
            return;
        }

        let (stored, truncated) = truncate_value_to_budget(value, budget);
        self.store_last_result_raw(stored, metadata, truncated);
    }

    /// Install an already-budgeted `$ans.last` value (caller handled truncation).
    ///
    /// Marks `$ans` present. Does not reset `exit_code` / `duration` / `command` (those are
    /// updated by [`Self::snapshot_ans_repl_metadata`] at end of each REPL line).
    pub fn store_last_result_raw(
        &mut self,
        value: Value,
        metadata: Option<PipelineMetadata>,
        truncated: bool,
    ) {
        self.with_last_result_slot_mut(|slot| {
            if let Some(old) = slot.last.replace(value) {
                drop(old);
            }
            slot.metadata = metadata;
            slot.truncated = truncated;
            slot.warn_pending = truncated;
            // Fresh store replaces any not-yet-shown deferred warning.
            slot.warn_deferred = false;
            slot.present = true;
        });
    }

    /// After a REPL user command finishes: refresh `$ans.exit_code`, `$ans.duration`,
    /// and `$ans.command`.
    ///
    /// `command` is the exact reedline buffer for this line (same text history stores).
    /// Always marks `$ans` present so every user-typed line gets exit code, duration,
    /// and source (empty Enter / auto-cd do not call this). When `budget == 0`, also
    /// drops `$ans.last` (and its memory) so the record is `{ exit_code, duration, command }`
    /// without a `last` field. When budget is positive, any `.last` already stored this
    /// line (or earlier) is kept.
    pub fn snapshot_ans_repl_metadata(
        &mut self,
        engine_state: &EngineState,
        duration: std::time::Duration,
        command: impl Into<String>,
    ) {
        let budget = self.get_config(engine_state).max_last_result_size_bytes();
        let exit_code = self
            .get_env_var(engine_state, "LAST_EXIT_CODE")
            .and_then(|v| v.as_int().ok())
            .unwrap_or(0);
        let duration_ns = i64::try_from(duration.as_nanos()).unwrap_or(i64::MAX);
        let command = command.into();

        if budget == 0 {
            // Payload off: free `.last` memory before refreshing metadata.
            self.clear_last_result_payload();
        }

        self.with_last_result_slot_mut(|slot| {
            slot.exit_code = exit_code;
            slot.duration_ns = duration_ns;
            slot.command = command;
            slot.present = true;
        });
    }

    /// Pipeline metadata associated with the stored `$ans.last`, if any.
    pub fn last_result_metadata(&self) -> Option<PipelineMetadata> {
        self.with_last_result_slot(|slot| slot.metadata.clone())
    }

    /// Estimated memory size of the stored `$ans.last` payload (`0` if unset).
    pub fn last_result_memory_size(&self) -> usize {
        self.with_last_result_slot(|slot| slot.last.as_ref().map(|v| v.memory_size()).unwrap_or(0))
    }

    /// Marker key in [`PipelineMetadata::custom`] identifying pipeline data loaded from `$ans`.
    ///
    /// Used so IR cell-path follow only reattaches last-result metadata for `$ans.last`,
    /// not every unrelated record field named `last`.
    pub const ANS_LAST_RESULT_METADATA_KEY: &str = "ans_last_result";

    /// Build [`PipelineData`] for `$ans`, restoring stored pipeline metadata on the record
    /// so `$ans.last` cell-path access can reattach it (see IR `FollowCellPath`).
    pub fn last_result_pipeline_data(&self, span: Span) -> PipelineData {
        let mut metadata = self.last_result_metadata().unwrap_or_default();
        // Mark so FollowCellPath can reattach payload metadata only for `$ans.*`.
        metadata
            .custom
            .insert(Self::ANS_LAST_RESULT_METADATA_KEY, Value::bool(true, span));
        let value = self
            .assemble_ans_record(span)
            .unwrap_or_else(|| Value::nothing(span));
        PipelineData::value(value, Some(metadata))
    }

    /// Whether the currently stored `$ans.last` was truncated.
    pub fn last_result_was_truncated(&self) -> bool {
        self.with_last_result_slot(|slot| slot.truncated)
    }

    /// On `$ans` access after a truncated store: schedule a warning for after output prints.
    ///
    /// Does not print anything. Call [`Self::take_last_result_warn_deferred`] after display
    /// so the truncated value is shown first, then the warning.
    pub fn defer_last_result_truncation_warning(&self) {
        self.with_last_result_slot_mut(|slot| {
            if slot.warn_pending {
                slot.warn_pending = false;
                slot.warn_deferred = true;
            }
        });
    }

    /// Whether a truncation warning is waiting to be shown after print (does not clear).
    pub fn last_result_warn_pending(&self) -> bool {
        self.with_last_result_slot(|slot| slot.warn_pending)
    }

    /// Take the deferred truncation warning flag (clears it).
    ///
    /// Returns `true` once after a truncated `$ans` was accessed; intended to be called
    /// after the pipeline has been printed so the warning appears below the data.
    pub fn take_last_result_warn_deferred(&self) -> bool {
        self.with_last_result_slot_mut(|slot| std::mem::take(&mut slot.warn_deferred))
    }

    /// Report a deferred last-result truncation warning, if any.
    ///
    /// Prefer calling this after printing so output is not scrolled away by the warning.
    pub fn flush_last_result_truncation_warning(&self, engine_state: &EngineState, span: Span) {
        if !self.take_last_result_warn_deferred() {
            return;
        }
        let limit_bytes = self.get_config(engine_state).max_last_result_size_bytes();
        report_shell_warning(
            Some(self),
            engine_state,
            &crate::ShellWarning::LastResultTruncated {
                span,
                limit_bytes,
                help: Some(format!(
                    "Increase $env.config.max_last_result_size or use a smaller command result. Variable name is `${}`.",
                    crate::LAST_RESULT_VAR_NAME
                )),
                // EveryUse: once-per-access is handled by warn_pending/warn_deferred flags.
                report_mode: crate::ReportMode::EveryUse,
            },
        );
    }

    /// Lookup a variable, erroring if it is not found
    ///
    /// The passed-in span will be used to tag the value
    pub fn get_var(&self, var_id: VarId, span: Span) -> Result<Value, ShellError> {
        match self.lookup_var(var_id) {
            Some(v) => Ok(v.with_span(span)),
            // Unset last-result behaves like `nothing` rather than a missing variable.
            None if var_id == LAST_VARIABLE_ID => Ok(Value::nothing(span)),
            None => Err(ShellError::VariableNotFoundAtRuntime { span }),
        }
    }

    /// Lookup a variable, erroring if it is not found
    ///
    /// While the passed-in span will be used for errors, the returned value
    /// has the span from where it was originally defined
    pub fn get_var_with_origin(&self, var_id: VarId, span: Span) -> Result<Value, ShellError> {
        match self.lookup_var(var_id) {
            Some(v) => Ok(v),
            None => {
                if var_id == NU_VARIABLE_ID || var_id == ENV_VARIABLE_ID {
                    return Err(ShellError::Generic(GenericError::new(
                        "Built-in variables `$env` and `$nu` have no metadata",
                        "no metadata available",
                        span,
                    )));
                }
                Err(ShellError::VariableNotFoundAtRuntime { span })
            }
        }
    }

    /// Get the local config if set, otherwise the config from the engine state.
    ///
    /// This is the canonical way to get [`Config`] when [`Stack`] is available.
    pub fn get_config(&self, engine_state: &EngineState) -> Arc<Config> {
        self.config
            .clone()
            .unwrap_or_else(|| engine_state.config.clone())
    }

    /// Update the local config with the config stored in the `config` environment variable. Run
    /// this after assigning to `$env.config`.
    ///
    /// The config will be updated with successfully parsed values even if an error occurs.
    pub fn update_config(&mut self, engine_state: &EngineState) -> Result<(), ShellError> {
        if let Some(value) = self.get_env_var(engine_state, "config") {
            let old = self.get_config(engine_state);
            let mut config = (*old).clone();
            let result = config.update_from_value_with_options(
                &old,
                value,
                engine_state.history_locked_after_startup,
            );
            // The config value is modified by the update, so we should add it again
            self.add_env_var("config".into(), config.clone().into_value(value.span()));
            self.config = Some(config.into());
            if let Some(warning) = result? {
                report_shell_warning(Some(self), engine_state, &warning);
            }
        } else {
            self.config = None;
        }
        Ok(())
    }

    pub fn add_var(&mut self, var_id: VarId, value: Value) {
        //self.vars.insert(var_id, value);
        for (id, val) in &mut self.vars {
            if *id == var_id {
                *val = value;
                return;
            }
        }
        self.vars.push((var_id, value));
    }

    /// Return a mutable reference to a variable's value for in-place mutation.
    ///
    /// Looks up the variable in the current stack frame first. If not found, pulls it
    /// from the parent chain into the current frame (cloning it once). This enables
    /// zero-clone mutation for local `mut` variables: use `get_var_mut` + mutate instead
    /// of `lookup_var` (clone) + mutate + `add_var` (move back).
    pub fn get_var_mut(&mut self, var_id: VarId) -> Option<&mut Value> {
        // Use index-based access to avoid conflicting mutable borrows
        if let Some(pos) = self.vars.iter().position(|(id, _)| var_id == *id) {
            return Some(&mut self.vars[pos].1);
        }
        // Check parent chain
        if let Some(parent) = &self.parent_stack
            && !self.parent_deletions.contains(&var_id)
        {
            let value = parent.lookup_var(var_id)?;
            self.vars.push((var_id, value));
            return self.vars.last_mut().map(|(_, val)| val);
        }
        None
    }

    /// Upsert a cell path on a variable in place (shared by AST and IR assignment paths).
    ///
    /// Errors with [`ShellError::VariableNotFoundAtRuntime`] if the variable is not on
    /// this stack or its parent chain.
    pub fn upsert_var_cell_path(
        &mut self,
        var_id: VarId,
        members: &[PathMember],
        new_value: Value,
        span: Span,
    ) -> Result<(), ShellError> {
        let value = self
            .get_var_mut(var_id)
            .ok_or(ShellError::VariableNotFoundAtRuntime { span })?;
        value.upsert_data_at_cell_path(members, new_value)
    }

    pub fn remove_var(&mut self, var_id: VarId) {
        for (idx, (id, _)) in self.vars.iter().enumerate() {
            if *id == var_id {
                self.vars.remove(idx);
                break;
            }
        }
        // even if we did have it in the original layer, we need to make sure to remove it here
        // as well (since the previous update might have simply hid the parent value)
        if self.parent_stack.is_some() {
            self.parent_deletions.push(var_id);
        }
        self.deletions.push(var_id);
    }

    pub fn add_env_var(&mut self, var: String, value: Value) {
        if let Some(last_overlay) = self.active_overlays.last().cloned() {
            let env_name = EnvName::from(var);
            self.clear_env_var_marks_in_active_overlay(&last_overlay, &env_name);

            if let Some(scope) = self.env_vars.last_mut() {
                let scope = Arc::make_mut(scope);
                if let Some(env_vars) = scope.get_mut(&last_overlay) {
                    env_vars.insert(env_name, value);
                } else {
                    scope.insert(last_overlay, [(env_name, value)].into_iter().collect());
                }
            } else {
                self.env_vars.push(Arc::new(
                    [(last_overlay, [(env_name, value)].into_iter().collect())]
                        .into_iter()
                        .collect(),
                ));
            }
        } else {
            // TODO: Remove panic
            panic!("internal error: no active overlay");
        }
    }

    fn clear_env_var_marks_in_active_overlay(&mut self, overlay: &str, env_name: &EnvName) {
        if let Some(env_hidden) = Arc::make_mut(&mut self.env_hidden).get_mut(overlay) {
            // Re-assigning re-activates a previously hidden env var in this overlay.
            env_hidden.remove(env_name);
        }

        if let Some(hide_history) = Arc::make_mut(&mut self.env_hide_history).get_mut(overlay) {
            hide_history.remove(env_name);
        }
    }

    pub fn set_last_exit_code(&mut self, code: i32, span: Span) {
        self.add_env_var("LAST_EXIT_CODE".into(), Value::int(code.into(), span));
    }

    pub fn set_last_error(&mut self, error: &ShellError) {
        if let Some(code) = error.external_exit_code() {
            self.set_last_exit_code(code.item, code.span);
        } else if let Some(code) = error.exit_code() {
            self.set_last_exit_code(code, Span::unknown());
        }
    }

    pub fn last_overlay_name(&self) -> Result<String, ShellError> {
        self.active_overlays
            .last()
            .cloned()
            .ok_or_else(|| ShellError::NushellFailed {
                msg: "No active overlay".into(),
            })
    }

    /// Like [`captures_to_stack_preserve_out_dest`], but sets the new scope up to collect output into a Value.
    pub fn captures_to_stack(&self, captures: Vec<(VarId, Value)>) -> Stack {
        self.captures_to_stack_preserve_out_dest(captures)
            .collect_value()
    }

    /// Creates a derived stack for a new scope, with the given captures.
    ///
    /// The caller is retained as [`Self::parent_stack`] so outer variables remain visible to
    /// `scope variables` (and other stack lookups that walk parents). Captured values are still
    /// copied onto this stack for isolation of the closure’s own locals.
    pub fn captures_to_stack_preserve_out_dest(&self, captures: Vec<(VarId, Value)>) -> Stack {
        let mut env_vars = self.env_vars.clone();
        env_vars.push(Arc::new(HashMap::new()));

        Stack {
            vars: captures,
            env_vars,
            env_hidden: self.env_hidden.clone(),
            env_hide_history: self.env_hide_history.clone(),
            active_overlays: self.active_overlays.clone(),
            arguments: ArgumentStack::new(),
            error_handlers: ErrorHandlerStack::new(),
            finally_run_handlers: ErrorHandlerStack::new(),
            recursion_count: self.recursion_count,
            // Keep the caller as parent so global/outer locals stay nameable for `scope`
            // (values are still resolved via the parent chain when not captured).
            parent_stack: Some(Arc::new(self.clone())),
            parent_deletions: vec![],
            deletions: vec![],
            config: self.config.clone(),
            out_dest: self.out_dest.clone(),
            suppress_stdin: self.suppress_stdin,
            // Inherit caller block bindings so nested closures still see outer local defs.
            active_scope_bindings: self.active_scope_bindings.clone(),
            ir_scope_regions: vec![],
            ir_instruction_index: None,
            // Share last-result so closures can still read `$ans`.
            last_result: self.last_result.clone(),
        }
    }

    pub fn gather_captures(&self, engine_state: &EngineState, captures: &[(VarId, Span)]) -> Stack {
        let mut vars = Vec::with_capacity(captures.len());

        let fake_span = Span::new(0, 0);

        for (capture, _) in captures {
            // Note: this assumes we have calculated captures correctly and that commands
            // that take in a var decl will manually set this into scope when running the blocks
            if let Ok(value) = self.get_var(*capture, fake_span) {
                vars.push((*capture, value));
            } else if let Some(const_val) = &engine_state.get_var(*capture).const_val {
                vars.push((*capture, const_val.clone()));
            }
        }

        let mut env_vars = self.env_vars.clone();
        env_vars.push(Arc::new(HashMap::new()));

        Stack {
            vars,
            env_vars,
            env_hidden: self.env_hidden.clone(),
            env_hide_history: self.env_hide_history.clone(),
            active_overlays: self.active_overlays.clone(),
            arguments: ArgumentStack::new(),
            error_handlers: ErrorHandlerStack::new(),
            finally_run_handlers: ErrorHandlerStack::new(),
            recursion_count: self.recursion_count,
            parent_stack: Some(Arc::new(self.clone())),
            parent_deletions: vec![],
            deletions: vec![],
            config: self.config.clone(),
            out_dest: self.out_dest.clone(),
            suppress_stdin: self.suppress_stdin,
            // Inherit caller block bindings so nested closures still see outer local defs.
            active_scope_bindings: self.active_scope_bindings.clone(),
            ir_scope_regions: vec![],
            ir_instruction_index: None,
            // Share last-result so closures can still read `$ans`.
            last_result: self.last_result.clone(),
        }
    }

    /// Flatten the env var scope frames into one frame
    pub fn get_env_vars(&self, engine_state: &EngineState) -> HashMap<String, Value> {
        let mut result = HashMap::new();

        for active_overlay in self.active_overlays.iter() {
            if let Some(env_vars) = engine_state.env_vars.get(active_overlay) {
                result.extend(
                    env_vars
                        .iter()
                        .filter(|(k, _)| {
                            if let Some(env_hidden) = self.env_hidden.get(active_overlay) {
                                !env_hidden.contains(*k)
                            } else {
                                // nothing has been hidden in this overlay
                                true
                            }
                        })
                        .map(|(k, v)| (k.as_str().to_string(), v.clone()))
                        .collect::<HashMap<String, Value>>(),
                );
            }
        }

        result.extend(self.get_stack_env_vars());

        result
    }

    /// Get flattened environment variables only from the stack
    pub fn get_stack_env_vars(&self) -> HashMap<String, Value> {
        let mut result = HashMap::new();

        for scope in &self.env_vars {
            for active_overlay in self.active_overlays.iter() {
                if let Some(env_vars) = scope.get(active_overlay) {
                    result.extend(
                        env_vars
                            .iter()
                            .map(|(k, v)| (k.as_str().to_string(), v.clone())),
                    );
                }
            }
        }

        result
    }

    /// Get flattened environment variables only from the stack and one overlay
    pub fn get_stack_overlay_env_vars(&self, overlay_name: &str) -> HashMap<String, Value> {
        let mut result = HashMap::new();

        for scope in &self.env_vars {
            if let Some(active_overlay) = self.active_overlays.iter().find(|n| n == &overlay_name)
                && let Some(env_vars) = scope.get(active_overlay)
            {
                result.extend(
                    env_vars
                        .iter()
                        .map(|(k, v)| (k.as_str().to_string(), v.clone())),
                );
            }
        }

        result
    }

    /// Get hidden envs, but without envs defined previously in `excluded_overlay_name`.
    pub fn get_hidden_env_vars(
        &self,
        excluded_overlay_name: &str,
        engine_state: &EngineState,
    ) -> HashMap<String, Value> {
        let mut result = HashMap::new();

        for overlay_name in self.active_overlays.iter().rev() {
            if overlay_name == excluded_overlay_name {
                continue;
            }
            if let Some(env_names) = self.env_hidden.get(overlay_name) {
                for n in env_names {
                    if result.contains_key(n.as_str()) {
                        continue;
                    }
                    // get env value.
                    if let Some(Some(v)) = engine_state
                        .env_vars
                        .get(overlay_name)
                        .map(|env_vars| env_vars.get(n))
                    {
                        result.insert(n.as_str().to_string(), v.clone());
                    }
                }
            }
        }
        result
    }

    /// Same as get_env_vars, but returns only the names as a HashSet
    pub fn get_env_var_names(&self, engine_state: &EngineState) -> HashSet<String> {
        let mut result = HashSet::new();

        for active_overlay in self.active_overlays.iter() {
            if let Some(env_vars) = engine_state.env_vars.get(active_overlay) {
                result.extend(
                    env_vars
                        .keys()
                        .filter(|k| {
                            if let Some(env_hidden) = self.env_hidden.get(active_overlay) {
                                !env_hidden.contains(*k)
                            } else {
                                // nothing has been hidden in this overlay
                                true
                            }
                        })
                        .map(|k| k.as_str().to_string())
                        .collect::<HashSet<String>>(),
                );
            }
        }

        for scope in &self.env_vars {
            for active_overlay in self.active_overlays.iter() {
                if let Some(env_vars) = scope.get(active_overlay) {
                    result.extend(
                        env_vars
                            .keys()
                            .map(|k| k.as_str().to_string())
                            .collect::<HashSet<String>>(),
                    );
                }
            }
        }

        result
    }

    pub fn get_env_var<'a>(
        &'a self,
        engine_state: &'a EngineState,
        name: &str,
    ) -> Option<&'a Value> {
        let env_name = EnvName::from(name);

        for scope in self.env_vars.iter().rev() {
            for active_overlay in self.active_overlays.iter().rev() {
                if let Some(env_vars) = scope.get(active_overlay)
                    && let Some(v) = env_vars.get(&env_name)
                {
                    return Some(v);
                }
            }
        }

        for active_overlay in self.active_overlays.iter().rev() {
            if !self.is_env_hidden_in_overlay(active_overlay, &env_name)
                && let Some(env_vars) = engine_state.env_vars.get(active_overlay)
                && let Some(v) = env_vars.get(&env_name)
            {
                return Some(v);
            }
        }
        None
    }

    pub fn has_env_var(&self, engine_state: &EngineState, name: &str) -> bool {
        let env_name = EnvName::from(name);

        for scope in self.env_vars.iter().rev() {
            for active_overlay in self.active_overlays.iter().rev() {
                if let Some(env_vars) = scope.get(active_overlay)
                    && env_vars.contains_key(&env_name)
                {
                    return true;
                }
            }
        }

        for active_overlay in self.active_overlays.iter().rev() {
            if !self.is_env_hidden_in_overlay(active_overlay, &env_name)
                && let Some(env_vars) = engine_state.env_vars.get(active_overlay)
                && env_vars.contains_key(&env_name)
            {
                return true;
            }
        }

        false
    }

    /// Removes `name` from the stack. If it was not on the stack and lives in `engine_state`,
    /// marks it hidden in `env_hidden`. Returns `true` if the variable was found and removed.
    ///
    /// Use this for temporary bookkeeping removals (e.g. `FILE_PWD`, canary variables) where
    /// the goal is to clean up a stack-level value without necessarily hiding the engine-state
    /// baseline. Use [`Self::hide_env_var`] when the intent is to make the variable invisible
    /// to subsequent lookups (e.g. `hide-env`).
    pub fn remove_env_var(&mut self, engine_state: &EngineState, name: &str) -> bool {
        let env_name = EnvName::from(name);

        self.remove_env_var_from_stack(&env_name)
            || self.hide_engine_state_env_var(engine_state, &env_name)
    }

    /// Removes `env_name` from all stack scopes and returns `true` if it was found.
    /// Does not affect `env_hidden`; use [`Self::hide_env_var`] for full hiding semantics.
    fn remove_env_var_from_stack(&mut self, env_name: &EnvName) -> bool {
        self.env_vars
            .iter_mut()
            .rev()
            .map(Arc::make_mut)
            .find_map(|scope| {
                self.active_overlays
                    .iter()
                    .rev()
                    .find_map(|active_overlay| scope.get_mut(active_overlay)?.remove(env_name))
            })
            .is_some()
    }

    /// Marks `env_name` as hidden in `env_hidden` for the active overlay where it exists in
    /// `engine_state`.
    ///
    /// Returns `true` only when the baseline variable exists and was newly hidden.
    fn hide_engine_state_env_var(
        &mut self,
        engine_state: &EngineState,
        env_name: &EnvName,
    ) -> bool {
        let overlay_containing_env_var = self.active_overlays.iter().rev().find(|active_overlay| {
            engine_state
                .env_vars
                .get(active_overlay.as_str())
                .is_some_and(|env_vars| env_vars.contains_key(env_name))
        });

        let Some(overlay_containing_env_var) = overlay_containing_env_var else {
            return false;
        };

        let env_hidden = Arc::make_mut(&mut self.env_hidden);

        if env_hidden
            .get(overlay_containing_env_var.as_str())
            .is_some_and(|hidden_vars| hidden_vars.contains(env_name))
        {
            return false;
        }

        env_hidden
            .entry(overlay_containing_env_var.clone())
            .or_default()
            .insert(env_name.clone());
        true
    }

    /// Records that `env_name` has been hidden in the active overlay and returns `false` if it
    /// was already recorded as hidden there.
    fn record_env_var_hide_in_active_overlay(&mut self, env_name: &EnvName) -> bool {
        let Some(active_overlay) = self.active_overlays.last().cloned() else {
            return false;
        };

        Arc::make_mut(&mut self.env_hide_history)
            .entry(active_overlay)
            .or_default()
            .insert(env_name.clone())
    }

    fn is_env_var_hide_recorded(&self, env_name: &EnvName) -> bool {
        self.active_overlays
            .iter()
            .rev()
            .filter_map(|overlay| self.env_hide_history.get(overlay))
            .any(|hidden_vars| hidden_vars.contains(env_name))
    }

    fn is_env_hidden_in_overlay(&self, overlay: &str, env_name: &EnvName) -> bool {
        self.env_hidden
            .get(overlay)
            .is_some_and(|hidden_vars| hidden_vars.contains(env_name))
    }

    /// Returns `true` if `name` was hidden in this stack context (e.g. by `hide-env`), either by
    /// masking an `engine_state` baseline value or by removing a stack-level value.
    ///
    /// A variable that was re-added after being hidden is still reported as hidden here, so only
    /// use this after a failed lookup to distinguish "hidden" from "never set".
    pub fn is_env_var_hidden(&self, name: &str) -> bool {
        let env_name = EnvName::from(name);

        self.active_overlays
            .iter()
            .rev()
            .any(|overlay| self.is_env_hidden_in_overlay(overlay, &env_name))
            || self.is_env_var_hide_recorded(&env_name)
    }

    /// Hides `name` so it is no longer visible to subsequent lookups. Removes it from the stack
    /// and, if no stack shadowing remains, also marks the `engine_state` baseline as hidden in
    /// `env_hidden`. Returns `true` if the variable was found.
    ///
    /// This is the correct method for `hide-env` and `redirect_env`; it ensures that a variable
    /// set in engine_state (from a previous REPL merge) cannot be seen after hiding even when a
    /// stack-level override (e.g. an empty-string assignment) was present at hide time.
    pub fn hide_env_var(&mut self, engine_state: &EngineState, name: &str) -> bool {
        let env_name = EnvName::from(name);

        // Re-hiding the same env var in the same scope should report not found.
        if self.is_env_var_hide_recorded(&env_name) {
            return false;
        }

        if self.remove_env_var_from_stack(&env_name) {
            self.record_env_var_hide_in_active_overlay(&env_name);

            if !self.has_env_var_in_stack(&env_name) {
                self.hide_engine_state_env_var(engine_state, &env_name);
            }
            return true;
        }

        if self.hide_engine_state_env_var(engine_state, &env_name) {
            self.record_env_var_hide_in_active_overlay(&env_name);
            return true;
        }

        false
    }

    /// Returns `true` if `name` exists in any stack scope (without consulting `engine_state`).
    fn has_env_var_in_stack(&self, name: &EnvName) -> bool {
        self.env_vars.iter().rev().any(|scope| {
            self.active_overlays
                .iter()
                .rev()
                .filter_map(|active_overlay| scope.get(active_overlay))
                .any(|env_vars| env_vars.contains_key(name))
        })
    }

    pub fn has_env_overlay(&self, name: &str, engine_state: &EngineState) -> bool {
        for scope in self.env_vars.iter().rev() {
            if scope.contains_key(name) {
                return true;
            }
        }

        engine_state.env_vars.contains_key(name)
    }

    pub fn is_overlay_active(&self, name: &str) -> bool {
        self.active_overlays.iter().any(|n| n == name)
    }

    pub fn add_overlay(&mut self, name: String) {
        self.active_overlays.retain(|o| o != &name);
        self.active_overlays.push(name);
    }

    pub fn remove_overlay(&mut self, name: &str) {
        self.active_overlays.retain(|o| o != name);
    }

    /// Returns the [`OutDest`] to use for the current command's stdout.
    ///
    /// This will be the pipe redirection if one is set,
    /// otherwise it will be the current file redirection,
    /// otherwise it will be the process's stdout indicated by [`OutDest::Inherit`].
    pub fn stdout(&self) -> &OutDest {
        self.out_dest.stdout()
    }

    /// Returns the [`OutDest`] to use for the current command's stderr.
    ///
    /// This will be the pipe redirection if one is set,
    /// otherwise it will be the current file redirection,
    /// otherwise it will be the process's stderr indicated by [`OutDest::Inherit`].
    pub fn stderr(&self) -> &OutDest {
        self.out_dest.stderr()
    }

    /// Returns the [`OutDest`] of the pipe redirection applied to the current command's stdout.
    pub fn pipe_stdout(&self) -> Option<&OutDest> {
        self.out_dest.pipe_stdout.as_ref()
    }

    /// Returns the [`OutDest`] of the pipe redirection applied to the current command's stderr.
    pub fn pipe_stderr(&self) -> Option<&OutDest> {
        self.out_dest.pipe_stderr.as_ref()
    }

    /// Returns the stdout destination of the innermost active custom-command invocation, if any.
    ///
    /// This is the destination of that command's *return value*. It stays stable even when
    /// intermediate expressions temporarily set [`OutDest::Value`] (e.g. `if (…)`), so callers
    /// can answer "where does *this command* go?" from anywhere in the body.
    ///
    /// See also [`Self::is_stdout_redirected`] and [`StackWithInvocation`].
    pub fn invocation_stdout(&self) -> Option<&OutDest> {
        self.out_dest.invocation_stdout.last()
    }

    /// Whether the current custom command's return value is redirected away from display.
    ///
    /// Uses the active [`Self::invocation_stdout`] frame when inside a custom command so the
    /// answer is stable across nested `if` / `let` collection. Outside a custom command, falls
    /// back to [`Self::stdout`].
    ///
    /// Semantics match [`OutDest::is_redirected`] (only [`OutDest::Print`] is not redirected).
    /// This is the engine-side helper behind the `is-redirected` command.
    #[must_use]
    pub fn is_stdout_redirected(&self) -> bool {
        self.invocation_stdout()
            .unwrap_or_else(|| self.stdout())
            .is_redirected()
    }

    /// Wrap this stack with an invocation-stdout frame for a custom command about to run.
    ///
    /// Push the destination of the call's *return value* (typically
    /// `caller_stack.stdout().clone()` after redirections are applied). The frame is popped when
    /// the returned [`StackWithInvocation`] is dropped.
    ///
    /// # Why a separate frame?
    ///
    /// Intermediate evaluation sets [`OutDest::Value`] via [`Self::start_collect_value`]. Without
    /// an invocation frame, queries like `is-redirected` inside `if (…)` would always see
    /// `Value` and report redirected—even when the enclosing custom command's result is printed.
    pub fn with_invocation_stdout(self, dest: OutDest) -> StackWithInvocation {
        StackWithInvocation::new(self, dest)
    }

    /// Temporarily set the pipe stdout redirection to [`OutDest::Value`].
    ///
    /// This is used before evaluating an expression into a `Value`.
    pub fn start_collect_value(&mut self) -> StackCollectValueGuard<'_> {
        StackCollectValueGuard::new(self)
    }

    /// Temporarily use the output redirections in the parent scope.
    ///
    /// This is used before evaluating an argument to a call.
    pub fn use_call_arg_out_dest(&mut self) -> StackCallArgGuard<'_> {
        StackCallArgGuard::new(self)
    }

    /// Temporarily apply redirections to stdout and/or stderr.
    pub fn push_redirection(
        &mut self,
        stdout: Option<Redirection>,
        stderr: Option<Redirection>,
    ) -> StackIoGuard<'_> {
        StackIoGuard::new(self, stdout, stderr)
    }

    /// Mark stdout for the last command as [`OutDest::Value`].
    ///
    /// This will irreversibly alter the output redirections, and so it only makes sense to use this on an owned `Stack`
    /// (which is why this function does not take `&mut self`).
    ///
    /// See [`Stack::start_collect_value`] which can temporarily set stdout as [`OutDest::Value`] for a mutable `Stack` reference.
    pub fn collect_value(mut self) -> Self {
        self.out_dest.pipe_stdout = Some(OutDest::Value);
        self.out_dest.pipe_stderr = None;
        self
    }

    /// Mark both stdout and stderr for the last command as [`OutDest::Value`].
    ///
    /// This captures all output (stdout and stderr) instead of letting it inherit
    /// to the process's terminal. Useful for programmatic contexts like MCP servers
    /// where all output must be captured and returned.
    ///
    /// This will irreversibly alter the output redirections, and so it only makes sense to use this on an owned `Stack`
    /// (which is why this function does not take `&mut self`).
    pub fn capture_all(mut self) -> Self {
        self.out_dest.pipe_stdout = Some(OutDest::Value);
        self.out_dest.pipe_stderr = Some(OutDest::Value);
        self
    }

    /// Clears any pipe and file redirections and resets stdout and stderr to [`OutDest::Inherit`].
    ///
    /// This will irreversibly reset the output redirections, and so it only makes sense to use this on an owned `Stack`
    /// (which is why this function does not take `&mut self`).
    pub fn reset_out_dest(mut self) -> Self {
        self.out_dest = StackOutDest::new();
        self
    }

    /// Redirects stdout and stderr to [`OutDest::Null`], discarding all output.
    ///
    /// Use this for background evaluation tasks (e.g., completion) that must
    /// never write to the terminal while reedline owns it.
    pub fn suppress_output(mut self) -> Self {
        self.out_dest.stdout = OutDest::Null;
        self.out_dest.stderr = OutDest::Null;
        self
    }

    /// Causes external processes spawned with empty input to receive
    /// `/dev/null` for stdin instead of inheriting the terminal.
    ///
    /// Use this together with [`suppress_output`](Self::suppress_output) for
    /// background tasks (e.g. completion threads).  Without it, subprocesses
    /// spawned by closure-based completers (carapace, fish_complete, etc.)
    /// inherit the live terminal fd and can race with reedline's reads,
    /// causing `Input/output error` (EIO).
    pub fn suppress_stdin(mut self) -> Self {
        self.suppress_stdin = true;
        self
    }

    /// Clears any pipe redirections, keeping the current stdout and stderr.
    ///
    /// This will irreversibly reset some of the output redirections, and so it only makes sense to use this on an owned `Stack`
    /// (which is why this function does not take `&mut self`).
    pub fn reset_pipes(mut self) -> Self {
        self.out_dest.pipe_stdout = None;
        self.out_dest.pipe_stderr = None;
        self
    }

    /// Replaces the default stdout of the stack with a given file.
    ///
    /// This method configures the default stdout to redirect to a specified file.
    /// It is primarily useful for applications using `nu` as a language, where the stdout of
    /// external commands that are not explicitly piped can be redirected to a file.
    ///
    /// # Using Pipes
    ///
    /// For use in third-party applications pipes might be very useful as they allow using the
    /// stdout of external commands for different uses.
    /// For example the [`os_pipe`](https://docs.rs/os_pipe) crate provides an elegant way to
    /// access the stdout.
    ///
    /// ```
    /// # use std::{fs::File, io::{self, Read}, thread, error};
    /// # use nu_protocol::engine::Stack;
    /// #
    /// let (mut reader, writer) = os_pipe::pipe().unwrap();
    /// // Use a thread to avoid blocking the execution of the called command.
    /// let reader = thread::spawn(move || {
    ///     let mut buf: Vec<u8> = Vec::new();
    ///     reader.read_to_end(&mut buf)?;
    ///     Ok::<_, io::Error>(buf)
    /// });
    ///
    /// #[cfg(windows)]
    /// let file = std::os::windows::io::OwnedHandle::from(writer).into();
    /// #[cfg(unix)]
    /// let file = std::os::unix::io::OwnedFd::from(writer).into();
    ///
    /// let stack = Stack::new().stdout_file(file);
    ///
    /// // Execute some nu code.
    ///
    /// drop(stack); // drop the stack so that the writer will be dropped too
    /// let buf = reader.join().unwrap().unwrap();
    /// // Do with your buffer whatever you want.
    /// ```
    pub fn stdout_file(mut self, file: File) -> Self {
        self.out_dest.stdout = OutDest::File(Arc::new(file));
        self
    }

    /// Replaces the default stderr of the stack with a given file.
    ///
    /// For more info, see [`stdout_file`](Self::stdout_file).
    pub fn stderr_file(mut self, file: File) -> Self {
        self.out_dest.stderr = OutDest::File(Arc::new(file));
        self
    }

    /// Set the PWD environment variable to `path`.
    ///
    /// This method accepts `path` with trailing slashes, but they're removed
    /// before writing the value into PWD.
    pub fn set_cwd(&mut self, path: impl AsRef<std::path::Path>) -> Result<(), ShellError> {
        // Helper function to create a simple generic error.
        // Its messages are not especially helpful, but these errors don't occur often, so it's probably fine.
        fn error(msg: &str) -> Result<(), ShellError> {
            Err(ShellError::Generic(GenericError::new_internal(
                msg.to_string(),
                "",
            )))
        }

        let path = path.as_ref();

        if !path.is_absolute() {
            if let Some(Component::Prefix(_)) = path.components().next() {
                return Err(ShellError::Generic(
                    GenericError::new_internal("Cannot set $env.PWD to a prefix-only path", "")
                        .with_help(format!(
                            "Try to use {}{MAIN_SEPARATOR} instead",
                            path.display()
                        )),
                ));
            }

            error("Cannot set $env.PWD to a non-absolute path")
        } else if !path.exists() {
            error("Cannot set $env.PWD to a non-existent directory")
        } else if !path.is_dir() {
            error("Cannot set $env.PWD to a non-directory")
        } else {
            // Strip trailing slashes, if any.
            let path = nu_path::strip_trailing_slash(path);
            let value = Value::string(path.to_string_lossy(), Span::unknown());
            self.add_env_var("PWD".into(), value);
            Ok(())
        }
    }
}

#[cfg(test)]
mod test {
    use std::sync::Arc;

    use crate::{Span, Value, VarId, engine::EngineState};

    use super::Stack;

    #[test]
    fn test_children_see_inner_values() {
        let mut original = Stack::new();
        original.add_var(VarId::new(0), Value::test_string("hello"));

        let cloned = Stack::with_parent(Arc::new(original));
        assert_eq!(
            cloned.get_var(VarId::new(0), Span::test_data()),
            Ok(Value::test_string("hello"))
        );
    }

    #[test]
    fn test_children_dont_see_deleted_values() {
        let mut original = Stack::new();
        original.add_var(VarId::new(0), Value::test_string("hello"));

        let mut cloned = Stack::with_parent(Arc::new(original));
        cloned.remove_var(VarId::new(0));

        assert_eq!(
            cloned.get_var(VarId::new(0), Span::test_data()),
            Err(crate::ShellError::VariableNotFoundAtRuntime {
                span: Span::test_data()
            })
        );
    }

    #[test]
    fn test_children_changes_override_parent() {
        let mut original = Stack::new();
        original.add_var(VarId::new(0), Value::test_string("hello"));

        let mut cloned = Stack::with_parent(Arc::new(original));
        cloned.add_var(VarId::new(0), Value::test_string("there"));
        assert_eq!(
            cloned.get_var(VarId::new(0), Span::test_data()),
            Ok(Value::test_string("there"))
        );

        cloned.remove_var(VarId::new(0));
        // the underlying value shouldn't magically re-appear
        assert_eq!(
            cloned.get_var(VarId::new(0), Span::test_data()),
            Err(crate::ShellError::VariableNotFoundAtRuntime {
                span: Span::test_data()
            })
        );
    }
    #[test]
    fn test_children_changes_persist_in_offspring() {
        let mut original = Stack::new();
        original.add_var(VarId::new(0), Value::test_string("hello"));

        let mut cloned = Stack::with_parent(Arc::new(original));
        cloned.add_var(VarId::new(1), Value::test_string("there"));

        cloned.remove_var(VarId::new(0));
        let cloned = Stack::with_parent(Arc::new(cloned));

        assert_eq!(
            cloned.get_var(VarId::new(0), Span::test_data()),
            Err(crate::ShellError::VariableNotFoundAtRuntime {
                span: Span::test_data()
            })
        );

        assert_eq!(
            cloned.get_var(VarId::new(1), Span::test_data()),
            Ok(Value::test_string("there"))
        );
    }

    #[test]
    fn test_merging_children_back_to_parent() {
        let mut original = Stack::new();
        let engine_state = EngineState::new();
        original.add_var(VarId::new(0), Value::test_string("hello"));

        let original_arc = Arc::new(original);
        let mut cloned = Stack::with_parent(original_arc.clone());
        cloned.add_var(VarId::new(1), Value::test_string("there"));

        cloned.remove_var(VarId::new(0));

        cloned.add_env_var(
            "ADDED_IN_CHILD".to_string(),
            Value::test_string("New Env Var"),
        );

        let original = Stack::with_changes_from_child(original_arc, cloned);

        assert_eq!(
            original.get_var(VarId::new(0), Span::test_data()),
            Err(crate::ShellError::VariableNotFoundAtRuntime {
                span: Span::test_data()
            })
        );

        assert_eq!(
            original.get_var(VarId::new(1), Span::test_data()),
            Ok(Value::test_string("there"))
        );

        assert_eq!(
            original
                .get_env_var(&engine_state, "ADDED_IN_CHILD")
                .cloned(),
            Some(Value::test_string("New Env Var")),
        );
    }

    #[test]
    fn test_get_var_mut_local_in_place() {
        use crate::ast::PathMember;
        use crate::casing::Casing;
        use crate::record;

        let mut stack = Stack::new();
        let var_id = VarId::new(0);
        stack.add_var(
            var_id,
            Value::test_record(record! { "a" => Value::test_int(1) }),
        );

        let path = vec![PathMember::test_string("a", false, Casing::Sensitive)];
        stack
            .upsert_var_cell_path(var_id, &path, Value::test_int(2), Span::test_data())
            .expect("upsert should succeed");

        assert_eq!(
            stack.get_var(var_id, Span::test_data()),
            Ok(Value::test_record(record! { "a" => Value::test_int(2) }))
        );
        // Still a single local binding (no extra shadow entries).
        assert_eq!(stack.vars.len(), 1);
    }

    #[test]
    fn test_get_var_mut_pulls_from_parent() {
        use crate::ast::PathMember;
        use crate::casing::Casing;
        use crate::record;

        let mut parent = Stack::new();
        let var_id = VarId::new(0);
        parent.add_var(
            var_id,
            Value::test_record(record! { "a" => Value::test_int(1) }),
        );

        let mut child = Stack::with_parent(Arc::new(parent));
        assert!(child.vars.is_empty());

        let path = vec![PathMember::test_string("a", false, Casing::Sensitive)];
        child
            .upsert_var_cell_path(var_id, &path, Value::test_int(9), Span::test_data())
            .expect("upsert should succeed");

        // Value was pulled into the child frame, then mutated.
        assert_eq!(child.vars.len(), 1);
        assert_eq!(
            child.get_var(var_id, Span::test_data()),
            Ok(Value::test_record(record! { "a" => Value::test_int(9) }))
        );

        // Second mutation hits the local copy.
        child
            .upsert_var_cell_path(var_id, &path, Value::test_int(10), Span::test_data())
            .expect("second upsert should succeed");
        assert_eq!(child.vars.len(), 1);
        assert_eq!(
            child.get_var(var_id, Span::test_data()),
            Ok(Value::test_record(record! { "a" => Value::test_int(10) }))
        );
    }

    #[test]
    fn test_upsert_var_cell_path_missing_and_deleted() {
        use crate::ast::PathMember;
        use crate::casing::Casing;

        let mut stack = Stack::new();
        let var_id = VarId::new(0);
        let path = vec![PathMember::test_string("a", false, Casing::Sensitive)];

        assert!(matches!(
            stack.upsert_var_cell_path(var_id, &path, Value::test_int(1), Span::test_data()),
            Err(crate::ShellError::VariableNotFoundAtRuntime { .. })
        ));

        let mut parent = Stack::new();
        parent.add_var(var_id, Value::test_int(1));
        let mut child = Stack::with_parent(Arc::new(parent));
        child.remove_var(var_id);

        assert!(matches!(
            child.upsert_var_cell_path(var_id, &path, Value::test_int(2), Span::test_data()),
            Err(crate::ShellError::VariableNotFoundAtRuntime { .. })
        ));
        assert!(child.get_var_mut(var_id).is_none());
    }
}