kaish-kernel 0.16.0

Core kernel for kaish: lexer, parser, interpreter, and runtime
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
//! The statement plan: an AST rendered back to shell text, **unexpanded**.
//!
//! A plan is parse information. It is built after validation and before
//! execution, so `${HOME}` and `$(...)` appear exactly as written — an
//! embedder judges what was asked, not what it resolved to, and the
//! substitution that would resolve them has not run.
//!
//! Two products, one AST walk each: `render_stmt` produces the text, and
//! [`planned_commands`] produces one [`PlannedCommand`] per command the
//! statement contains — control-structure bodies, `if` conditions, and
//! command substitutions included, because every one of them is a command
//! this statement would run.
//!
//! The same walk collects the statement's variables: the names it reads
//! (`free_variables`) and the names it writes (`bound_variables`). A name
//! that is both lands bound, never free.
//!
//! The collection walk also lifts out any literal `--confirm=<key>` the
//! statement's argv carries ([`StatementPlan::presented_keys`]) — the same
//! spellings the rendering redacts. One predicate decides all three of lift,
//! redact, and render, so they cannot disagree about what the statement
//! presented.
//!
//! Redaction is the `--confirm=<key>` flag spelling and nothing else — that
//! spelling carries a confirmation credential, and a credential must never
//! ride into a stored plan. kaish ships no secret detector — a shell cannot
//! define what a secret is — so an embedder that wants more redacts the
//! plans it holds.

use std::collections::BTreeSet;

use kaish_types::plan::{
    Plan, PlannedCommand, PlannedHeredoc, PlannedRedirect, PlannedValue, PLAN_RENDER_LIMIT,
};
use kaish_types::Value;

use super::types::{
    Arg, Assignment, BinaryOp, CaseStmt, Command, Expr, ForLoop, IfStmt, ListElem, Pipeline,
    PipelineStage, RecordKey, Redirect, RedirectKind, Stmt, StringPart, TestExpr, ToolDef, VarPath,
    VarSegment,
    WhileLoop,
};

/// One statement's plan, plus the redemption credentials its argv presented.
pub struct StatementPlan {
    /// What the statement was asked to run, with every credential redacted.
    pub plan: Plan,
    /// Every literal `--confirm=<key>` (or `confirm=<key>`) the statement's
    /// argv carries, in source order.
    ///
    /// **Literal only.** A plan is unexpanded, so `--confirm=${key}` reads as
    /// `${key}` here and nothing is lifted — what the plan cannot see, the
    /// plan cannot leak, and nothing is stripped from the argv that executes.
    pub presented_keys: Vec<String>,
}

/// One statement of a planned program: its [`Plan`] and where it sits among
/// the planned statements.
///
/// `index` is the statement's position in the returned list, so an embedder
/// can name which statement it is talking about.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PlannedStatement {
    /// The statement's position in the returned list, counted from 0 with no
    /// gaps: `plans[i].index == i`, always. Indexing the list by this number
    /// reads the statement it names.
    pub index: usize,
    /// What the statement was asked to run, with every credential redacted.
    pub plan: Plan,
}

/// Plan every statement of `source` without executing anything.
///
/// A plan is parse information: `${HOME}` and `$(...)` appear exactly as
/// written, no substitution has run, and no filesystem has been touched. That
/// is the point — an embedder judges what the statement *asked for*, before
/// anything it names can happen.
///
/// Each plan carries the statement's rendered text, every command it would
/// run (control-structure bodies, `if` conditions, and `$(...)` bodies
/// included), the variables it reads ([`Plan::free_variables`]) and the ones
/// it writes ([`Plan::bound_variables`]). Reading live session state for the
/// free set with [`Kernel::get_var`](crate::Kernel::get_var) closes the loop:
/// plan a statement, look up what it depends on, and decide with the values
/// in hand.
///
/// Every literal `--confirm=<key>` is redacted from the plans and **not
/// returned**: the caller holds `source` and can read its own credentials;
/// this function adds no second copy.
///
/// # Errors
///
/// Returns the parse errors when `source` does not parse. Each error's
/// [`format`](crate::parser::ParseError::format) renders a diagnostic against
/// the source.
pub fn plan_program(
    source: &str,
) -> Result<Vec<PlannedStatement>, Vec<crate::parser::ParseError>> {
    let program = crate::parser::parse(source)?;
    Ok(program
        .statements
        .iter()
        // An empty statement runs nothing and plans nothing. Dropping it
        // BEFORE numbering is what keeps `index` equal to the position in the
        // returned list: numbering first left a gap whenever the source opened
        // with a comment or a blank line, which is most scripts.
        .filter(|stmt| !matches!(stmt, Stmt::Empty))
        .enumerate()
        .map(|(index, stmt)| PlannedStatement {
            index,
            plan: plan_statement(stmt).plan,
        })
        .collect())
}

/// Build the plan for one top-level statement. Every value is
/// [`PlannedValue::Plain`] except a presented confirm key, which the kernel
/// redacts unconditionally.
pub(crate) fn plan_statement(stmt: &Stmt) -> StatementPlan {
    let collected = collect(stmt);
    // Free = read and never written in-statement. A name that is both read
    // and written lands in `bound` — the safe direction: an embedder that
    // skips peeking it loses one lookup; one that peeked it would judge the
    // statement against a value the statement itself replaces.
    let free: Vec<String> = collected
        .reads
        .difference(&collected.binds)
        .cloned()
        .collect();
    let bound: Vec<String> = collected.binds.into_iter().collect();
    StatementPlan {
        plan: Plan::new(
            truncate_rendering(render_stmt(stmt)),
            stmt.kind_name(),
            collected.commands,
        )
        .with_variables(free, bound),
        presented_keys: collected.keys,
    }
}

/// Remove every `--confirm=` (or `confirm=`) token from rendered plan text,
/// whatever it carries.
///
/// An embedder computing a content identity over rendered text (see
/// `PlanDigest` in kaish-types) wants the identity to cover the operation,
/// not any credential presented with it — `rm x` and
/// `rm --confirm=<confirm-key> x` should digest the same.
///
/// Unlike [`redact_keys`], this does not need to know the key: it removes the
/// whole token whether it carries a literal credential, the `<confirm-key>`
/// marker a rendered plan shows, or an unexpanded `${key}` the plan could not
/// lift.
pub fn strip_confirm_tokens(rendered: &str) -> String {
    rendered
        .split_whitespace()
        .filter(|word| {
            !word.starts_with(&format!("--{CONFIRM_KEY}=")) && !word.starts_with(&format!("{CONFIRM_KEY}="))
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Remove every one of `keys` from captured source text — for an embedder
/// storing source alongside plans, so the stored text never carries a
/// credential. The whole `--confirm=<key>` token goes, not just its value,
/// so re-running the stored text cannot re-present a spent key.
pub fn redact_keys(source: &str, keys: &[String]) -> String {
    let mut out = source.to_string();
    for key in keys {
        for spelling in [format!("--{CONFIRM_KEY}={key}"), format!("{CONFIRM_KEY}={key}")] {
            // Take the separating space with the token so the surrounding
            // words stay one space apart; fall back to the bare token for a
            // spelling that opens its line.
            out = out.replace(&format!(" {spelling}"), "");
            out = out.replace(&spelling, "");
        }
    }
    out
}

/// Cut a rendering to [`PLAN_RENDER_LIMIT`] bytes, naming the cut.
///
/// The marker is loud and states the number, because a classifier reading a
/// silently shortened line would judge a statement it cannot see the end of.
/// The structure is not lost with the text — [`Plan::commands`] still names
/// every command.
fn truncate_rendering(rendered: String) -> String {
    if rendered.len() <= PLAN_RENDER_LIMIT {
        return rendered;
    }
    // Back up to a character boundary so the marker lands on valid UTF-8.
    let mut cut = PLAN_RENDER_LIMIT;
    while cut > 0 && !rendered.is_char_boundary(cut) {
        cut -= 1;
    }
    let mut out = rendered[..cut].to_string();
    out.push_str(&format!(
        "… [rendering truncated at {PLAN_RENDER_LIMIT} bytes]"
    ));
    out
}

// ───────────────────────── Command collection ─────────────────────────

/// What one collection walk produces: the statement's commands, the
/// credentials their argv presented, and its variable analysis.
#[derive(Default)]
struct Collected<'a> {
    commands: Vec<PlannedCommand>,
    keys: Vec<String>,
    /// Every variable name the statement reads, anywhere — `${x}`, a
    /// `"${x}"` interpolation, `${#x}`, a `[$k]` dynamic subscript, an
    /// identifier inside `$((…))`. kaish has no `eval` and no indirect
    /// expansion, so this set is complete by construction.
    reads: BTreeSet<String>,
    /// Every name the statement writes or binds — an assignment target, a
    /// `for` variable, an env-prefix name, a tool-def parameter.
    binds: BTreeSet<String>,
    /// Every heredoc target the walk has reached, in the order it reached
    /// them — the order that gives each one the flat
    /// [`PlannedHeredoc::index`] a plan publishes, so a heredoc inside a
    /// loop body is addressable without walking structure.
    ///
    /// Kept here rather than re-derived by a second walk. An address that
    /// resolves to a *different* body than the one it published is the worst
    /// failure this surface can have, and two traversals that have to agree
    /// is how you get one — this walk descends into redirect targets and
    /// interpolated strings, and a resolver written to match would have to
    /// remember to. `heredoc_targets[i]` is the target of the heredoc
    /// published with `index == i`, by construction.
    heredoc_targets: Vec<&'a Expr>,
}

impl<'a> Collected<'a> {
    /// Publish every heredoc one command declares, numbering them in the
    /// order this walk reaches them.
    fn take_heredocs(&mut self, cmd: &'a Command) -> Vec<PlannedHeredoc> {
        cmd.redirects
            .iter()
            .filter_map(|r| match &r.kind {
                RedirectKind::HereDoc(meta) => Some((meta, &r.target)),
                _ => None,
            })
            .map(|(meta, target)| {
                let index = self.heredoc_targets.len();
                self.heredoc_targets.push(target);
                // The body's own reads, not the statement's: an embedder
                // asking what plugs into *this* program wants the answer
                // scoped to it. A literal body reads nothing whatever it
                // contains, because nothing in it expands.
                let free = if meta.literal {
                    Vec::new()
                } else {
                    let mut body_reads = Collected::default();
                    collect_expr(target, false, &mut body_reads);
                    body_reads.reads.into_iter().collect()
                };
                PlannedHeredoc::new(
                    index,
                    meta.delimiter.clone(),
                    meta.literal,
                    meta.strip_tabs,
                    PlannedValue::Plain(meta.body.clone()),
                    meta.body_offset,
                )
                .with_free_variables(free)
            })
            .collect()
    }

    /// Record every read a variable path performs: its root name, plus any
    /// `[$k]` dynamic-subscript variable along the path.
    fn read_path(&mut self, path: &VarPath) {
        for (i, segment) in path.segments.iter().enumerate() {
            match segment {
                VarSegment::Field(name) if i == 0 => {
                    self.reads.insert(name.clone());
                }
                VarSegment::Dynamic(v) => {
                    self.reads.insert(v.clone());
                }
                _ => {}
            }
        }
    }

    /// Record the name an assignment path writes (its root), plus the reads
    /// its dynamic subscripts perform — `x[$k]=v` writes `x` and reads `k`.
    fn bind_path(&mut self, path: &VarPath) {
        if let Some(VarSegment::Field(name)) = path.segments.first() {
            self.binds.insert(name.clone());
        }
        for segment in path.segments.iter().skip(1) {
            if let VarSegment::Dynamic(v) = segment {
                self.reads.insert(v.clone());
            }
        }
    }

    /// Record every identifier in an arithmetic expression as a read.
    /// kaish arithmetic is numbers, variables (bare or `${name}`), and
    /// operators — an identifier token is always a variable.
    fn read_arithmetic(&mut self, expr: &str) {
        let mut name = String::new();
        for c in expr.chars() {
            if c == '_' || c.is_ascii_alphabetic() || (!name.is_empty() && c.is_ascii_digit()) {
                name.push(c);
            } else if !name.is_empty() {
                self.reads.insert(std::mem::take(&mut name));
            }
        }
        if !name.is_empty() {
            self.reads.insert(name);
        }
    }
}

/// Every command the statement contains, in source order, plus any literal
/// redemption key its argv carries.
///
/// A `for` body's commands, an `if` condition's command, and a `$(…)`
/// substitution's commands are all in here: each is a command this statement
/// would run, so each is a `cmd` resource a standing grant has to cover.
fn collect<'a>(stmt: &'a Stmt) -> Collected<'a> {
    let mut out = Collected::default();
    collect_stmt(stmt, false, &mut out);
    out
}

/// Every heredoc target the statement contains, indexed by the flat
/// [`PlannedHeredoc::index`] the plan publishes.
///
/// This is the **same walk** that numbers them, not a second one that agrees
/// with it — `heredoc_targets(stmt)[i]` is the target of the heredoc the plan
/// published with `index == i`, by construction rather than by test.
pub(crate) fn heredoc_targets(stmt: &Stmt) -> Vec<&Expr> {
    collect(stmt).heredoc_targets
}

/// Every command the statement contains, in source order.
pub fn planned_commands(stmt: &Stmt) -> Vec<PlannedCommand> {
    collect(stmt).commands
}

fn collect_stmt<'a>(stmt: &'a Stmt, background: bool, out: &mut Collected<'a>) {
    match stmt {
        Stmt::Assignment(a) => {
            out.bind_path(&a.path);
            collect_expr(&a.value, background, out)
        }
        Stmt::Command(cmd) => collect_command(cmd, background, out),
        Stmt::Pipeline(p) => {
            for stage in &p.stages {
                match stage {
                    PipelineStage::Command(cmd) => {
                        collect_command(cmd, background || p.background, out)
                    }
                    // A compound stage's commands belong to the enclosing
                    // statement, same as a loop body's do.
                    PipelineStage::Compound(stmt) => {
                        collect_stmt(stmt, background || p.background, out)
                    }
                }
            }
        }
        Stmt::If(s) => {
            collect_expr(&s.condition, background, out);
            collect_block(&s.then_branch, background, out);
            if let Some(else_branch) = &s.else_branch {
                collect_block(else_branch, background, out);
            }
        }
        Stmt::For(s) => {
            out.binds.insert(s.variable.clone());
            for item in &s.items {
                collect_expr(item, background, out);
            }
            collect_block(&s.body, background, out);
        }
        Stmt::While(s) => {
            collect_expr(&s.condition, background, out);
            collect_block(&s.body, background, out);
        }
        Stmt::Case(s) => {
            collect_expr(&s.expr, background, out);
            for branch in &s.branches {
                collect_block(&branch.body, background, out);
            }
        }
        Stmt::Return(e) | Stmt::Exit(e) => {
            if let Some(e) = e {
                collect_expr(e, background, out);
            }
        }
        Stmt::ToolDef(def) => {
            for param in &def.params {
                out.binds.insert(param.name.clone());
                if let Some(default) = &param.default {
                    collect_expr(default, background, out);
                }
            }
            collect_block(&def.body, background, out)
        }
        Stmt::Test(t) => collect_test(t, background, out),
        Stmt::AndChain { left, right } | Stmt::OrChain { left, right } => {
            collect_stmt(left, background, out);
            collect_stmt(right, background, out);
        }
        Stmt::EnvScoped { assignments, body } => {
            for a in assignments {
                out.bind_path(&a.path);
                collect_expr(&a.value, background, out);
            }
            collect_stmt(body, background, out);
        }
        Stmt::Break(_) | Stmt::Continue(_) | Stmt::Empty => {}
    }
}

fn collect_block<'a>(stmts: &'a [Stmt], background: bool, out: &mut Collected<'a>) {
    for stmt in stmts {
        collect_stmt(stmt, background, out);
    }
}

fn collect_command<'a>(cmd: &'a Command, background: bool, out: &mut Collected<'a>) {
    let args: Vec<PlannedValue> = cmd.args.iter().map(|arg| plan_arg(arg).1).collect();
    let redirects = cmd
        .redirects
        .iter()
        .map(|r| PlannedRedirect::new(r.kind.to_string(), plan_redirect_target(r)))
        .collect();
    let heredocs = out.take_heredocs(cmd);
    out.commands.push(
        PlannedCommand::new(cmd.name.clone(), args, redirects, background)
            .with_heredocs(heredocs),
    );
    // Lift any literal credential out of the argv on the same pass that
    // redacts it from the rendering — one walk, one truth about what this
    // statement presented.
    for arg in &cmd.args {
        if let Some(key) = presented_key(arg) {
            out.keys.push(key);
        }
    }
    // Substitutions nested inside this command's own arguments and redirect
    // targets are commands too, and they run before it does.
    for arg in &cmd.args {
        match arg {
            Arg::Positional(e) => collect_expr(e, background, out),
            Arg::Named { value, .. } | Arg::WordAssign { value, .. } => {
                collect_expr(value, background, out)
            }
            Arg::ShortFlag(_) | Arg::LongFlag(_) | Arg::DoubleDash => {}
        }
    }
    for redirect in &cmd.redirects {
        collect_expr(&redirect.target, background, out);
    }
}

fn collect_expr<'a>(expr: &'a Expr, background: bool, out: &mut Collected<'a>) {
    match expr {
        Expr::Command(cmd) => collect_command(cmd, background, out),
        Expr::CommandSubst(stmts) => collect_block(stmts, background, out),
        // The negation runs its inner command; the plan must show it.
        Expr::Not(inner) => collect_expr(inner, background, out),
        Expr::BinaryOp { left, right, .. } => {
            collect_expr(left, background, out);
            collect_expr(right, background, out);
        }
        Expr::Interpolated(parts) => collect_parts(parts, background, out),
        Expr::HereDocBody { parts, .. } => {
            for part in parts {
                collect_part(&part.part, background, out);
            }
        }
        Expr::Test(t) => collect_test(t, background, out),
        Expr::VarWithDefault { path, default } => {
            out.read_path(path);
            collect_parts(default, background, out)
        }
        Expr::ListLiteral(elems) => {
            for elem in elems {
                match elem {
                    ListElem::Item(e) | ListElem::Spread(e) => collect_expr(e, background, out),
                }
            }
        }
        Expr::RecordLiteral(entries) => {
            for entry in entries {
                if let RecordKey::Interpolated(parts) = &entry.key {
                    collect_parts(parts, background, out);
                }
                collect_expr(&entry.value, background, out);
            }
        }
        Expr::VarRef(path) | Expr::VarLength(path) => out.read_path(path),
        Expr::Arithmetic(e) => out.read_arithmetic(e),
        // Special forms ($1, $@, $#, $?, $$) are not session variables; an
        // embedder cannot peek them with `get_var`, so they are not listed.
        Expr::Literal(_)
        | Expr::Positional(_)
        | Expr::AllArgs
        | Expr::ArgCount
        | Expr::LastExitCode
        | Expr::CurrentPid
        | Expr::GlobPattern(_) => {}
    }
}

fn collect_parts<'a>(parts: &'a [StringPart], background: bool, out: &mut Collected<'a>) {
    for part in parts {
        collect_part(part, background, out);
    }
}

fn collect_part<'a>(part: &'a StringPart, background: bool, out: &mut Collected<'a>) {
    match part {
        StringPart::CommandSubst(stmts) => collect_block(stmts, background, out),
        StringPart::VarWithDefault { path, default } => {
            out.read_path(path);
            collect_parts(default, background, out)
        }
        StringPart::Var(path) | StringPart::VarLength(path) => out.read_path(path),
        StringPart::Arithmetic(e) => out.read_arithmetic(e),
        // See the identical special-forms note in `collect_expr`.
        StringPart::Literal(_)
        | StringPart::Positional(_)
        | StringPart::AllArgs
        | StringPart::ArgCount
        | StringPart::LastExitCode
        | StringPart::CurrentPid => {}
    }
}

fn collect_test<'a>(test: &'a TestExpr, background: bool, out: &mut Collected<'a>) {
    match test {
        TestExpr::FileTest { path, .. } => collect_expr(path, background, out),
        TestExpr::StringTest { value, .. } => collect_expr(value, background, out),
        TestExpr::Comparison { left, right, .. }
        | TestExpr::In { left, right }
        | TestExpr::NotIn { left, right } => {
            collect_expr(left, background, out);
            collect_expr(right, background, out);
        }
        TestExpr::And { left, right } | TestExpr::Or { left, right } => {
            collect_test(left, background, out);
            collect_test(right, background, out);
        }
        TestExpr::Not { expr } => collect_test(expr, background, out),
    }
}

// ───────────────────────── Rendering ─────────────────────────

/// Render one statement back to shell text, unexpanded.
pub(crate) fn render_stmt(stmt: &Stmt) -> String {
    match stmt {
        Stmt::Assignment(a) => render_assignment(a),
        Stmt::Command(cmd) => render_command(cmd),
        Stmt::Pipeline(p) => render_pipeline(p),
        Stmt::If(s) => render_if(s),
        Stmt::For(s) => render_for(s),
        Stmt::While(s) => render_while(s),
        Stmt::Case(s) => render_case(s),
        Stmt::Break(n) => render_keyword("break", n.map(|n| n.to_string())),
        Stmt::Continue(n) => render_keyword("continue", n.map(|n| n.to_string())),
        Stmt::Return(e) => render_keyword("return", e.as_ref().map(|e| render_expr(e))),
        Stmt::Exit(e) => render_keyword("exit", e.as_ref().map(|e| render_expr(e))),
        Stmt::ToolDef(def) => render_tooldef(def),
        Stmt::Test(t) => format!("[[ {} ]]", render_test(t)),
        Stmt::AndChain { left, right } => {
            format!("{} && {}", render_stmt(left), render_stmt(right))
        }
        Stmt::OrChain { left, right } => {
            format!("{} || {}", render_stmt(left), render_stmt(right))
        }
        Stmt::EnvScoped { assignments, body } => {
            let prefix: Vec<String> = assignments.iter().map(render_assignment).collect();
            format!("{} {}", prefix.join(" "), render_stmt(body))
        }
        Stmt::Empty => String::new(),
    }
}

fn render_keyword(word: &str, operand: Option<String>) -> String {
    match operand {
        Some(operand) => format!("{word} {operand}"),
        None => word.to_string(),
    }
}

fn render_block(stmts: &[Stmt]) -> String {
    stmts
        .iter()
        .filter(|s| !matches!(s, Stmt::Empty))
        .map(render_stmt)
        .collect::<Vec<_>>()
        .join("; ")
}

fn render_assignment(a: &Assignment) -> String {
    let path = render_varpath(&a.path);
    if a.local {
        format!("local {} = {}", path, render_expr(&a.value))
    } else {
        format!("{}={}", path, render_expr(&a.value))
    }
}

/// Render one command: argv0, every argument form, and every redirect.
pub(crate) fn render_command(cmd: &Command) -> String {
    let mut parts = vec![cmd.name.clone()];
    for arg in &cmd.args {
        parts.push(plan_arg(arg).0);
    }
    for redirect in &cmd.redirects {
        parts.push(render_redirect(redirect));
    }
    parts.join(" ")
}

/// The one argument whose value never reaches a plan unredacted:
/// `--confirm=<token>` carries a confirmation credential, and a plan is
/// built to be stored and shown. This is kaish's own, unconditional
/// redaction — possible exactly because the flag spelling is kaish's
/// convention and needs no secret detector to recognize.
const CONFIRM_KEY: &str = "confirm";

/// The [`PlannedValue::Redacted`] `kind` the kernel's confirm-key redaction
/// marks a value with, so an auditor reading `Plan::commands` can tell the
/// kernel's own redaction apart from an embedder's.
const CONFIRM_KEY_KIND: &str = "confirm-key";

/// The literal credential this argument presents, if it is a `confirm`
/// argument carrying one.
///
/// A non-literal value (`--confirm=${key}`, `--confirm=$(cat key)`) yields
/// `None`: the plan is unexpanded, so the value is not knowable here. That
/// costs nothing — what the plan cannot see, it cannot leak, and the argv
/// that executes is untouched.
fn presented_key(arg: &Arg) -> Option<String> {
    let value = match arg {
        Arg::Named { key, value } | Arg::WordAssign { key, value } if key == CONFIRM_KEY => value,
        _ => return None,
    };
    match value {
        Expr::Literal(Value::String(s)) => Some(s.clone()),
        _ => None,
    }
}

/// Plan one argument: its flat text (for [`render_command`]) and its
/// [`PlannedValue`] (for [`PlannedCommand::args`]), derived together so the
/// two representations cannot disagree about what this argument was.
///
/// A `confirm` argument carrying a *literal* is a credential and is redacted
/// unconditionally; every other value's flag/key prefix (if any) stays
/// visible even when its value is redacted, so the plan still shows *that* a
/// value was presented at that flag, never *what*.
fn plan_arg(arg: &Arg) -> (String, PlannedValue) {
    if presented_key(arg).is_some() {
        let value = PlannedValue::redacted(CONFIRM_KEY_KIND, None);
        let text = match arg {
            // `dd` takes its operands as bare `key=value`, so `confirm=<key>`
            // is a second spelling of the same credential.
            Arg::WordAssign { key, .. } => format!("{key}={}", value.display()),
            _ => format!("--{CONFIRM_KEY}={}", value.display()),
        };
        return (text, value);
    }
    let (text, value) = match arg {
        Arg::Positional(e) => {
            let value = PlannedValue::Plain(render_expr(e));
            (value.display(), value)
        }
        Arg::Named { key, value: e } => {
            let value = PlannedValue::Plain(render_expr(e));
            (format!("--{key}={}", value.display()), value)
        }
        Arg::WordAssign { key, value: e } => {
            let value = PlannedValue::Plain(render_expr(e));
            (format!("{key}={}", value.display()), value)
        }
        Arg::ShortFlag(f) => {
            let text = format!("-{f}");
            (text.clone(), PlannedValue::Plain(text))
        }
        Arg::LongFlag(f) => {
            let text = format!("--{f}");
            (text.clone(), PlannedValue::Plain(text))
        }
        Arg::DoubleDash => ("--".to_string(), PlannedValue::Plain("--".to_string())),
    };
    // A redacted `--key=value` loses its `key=` prefix in the *structured*
    // value (`PlannedValue::Redacted` has nowhere to put one) but keeps it
    // in the flat text above; a plain value keeps the full composed text in
    // both, so `PlannedCommand::args` round-trips into `render_command`'s
    // output unless something was actually judged secret.
    let structured = if value.is_redacted() {
        value
    } else {
        PlannedValue::Plain(text.clone())
    };
    (text, structured)
}

/// Plan one redirect's target: rendered unexpanded, always plain — a
/// redirect target is never the kernel's confirm key.
///
/// A heredoc's target is its delimiter word, which is what stands after `<<`
/// in the source. Rendering the *body* here would repeat what
/// [`PlannedCommand::heredocs`] carries structurally, and rendering it from
/// the target expression spells every delimiter `EOF` — the body has lost the
/// word by then.
///
/// [`PlannedCommand::heredocs`]: kaish_types::plan::PlannedCommand::heredocs
fn plan_redirect_target(redirect: &Redirect) -> PlannedValue {
    match &redirect.kind {
        RedirectKind::HereDoc(meta) => {
            let quote = if meta.literal { "'" } else { "" };
            PlannedValue::Plain(format!("{quote}{}{quote}", meta.delimiter))
        }
        _ => PlannedValue::Plain(render_expr(&redirect.target)),
    }
}

fn render_redirect(redirect: &Redirect) -> String {
    // A merge redirect (`2>&1`, `1>&2`) is the whole operator: its target
    // expression is a placeholder, and printing it would invent a filename.
    match &redirect.kind {
        RedirectKind::MergeStderr | RedirectKind::MergeStdout => redirect.kind.to_string(),
        // A heredoc renders back the way it was written — its own delimiter
        // word, its own body. Spelling every delimiter `EOF` would erase the
        // hint the author chose (`PY`, `SQL`) from the one field a classifier
        // reads first.
        RedirectKind::HereDoc(meta) => {
            let dash = if meta.strip_tabs { "-" } else { "" };
            let quote = if meta.literal { "'" } else { "" };
            format!(
                "<<{dash}{quote}{delim}{quote}\n{body}{delim}",
                delim = meta.delimiter,
                body = meta.body,
            )
        }
        _ => format!(
            "{} {}",
            redirect.kind,
            plan_redirect_target(redirect).display()
        ),
    }
}

fn render_pipeline(p: &Pipeline) -> String {
    let body = p
        .stages
        .iter()
        .map(|stage| match stage {
            PipelineStage::Command(cmd) => render_command(cmd),
            PipelineStage::Compound(stmt) => render_stmt(stmt),
        })
        .collect::<Vec<_>>()
        .join(" | ");
    if p.background {
        format!("{body} &")
    } else {
        body
    }
}

fn render_if(s: &IfStmt) -> String {
    let mut out = format!(
        "if {}; then {}",
        render_expr(&s.condition),
        render_block(&s.then_branch)
    );
    if let Some(else_branch) = &s.else_branch {
        let rendered = render_block(else_branch);
        if !rendered.is_empty() {
            out.push_str(&format!("; else {rendered}"));
        }
    }
    out.push_str("; fi");
    out
}

fn render_for(s: &ForLoop) -> String {
    let items: Vec<String> = s.items.iter().map(render_expr).collect();
    format!(
        "for {} in {}; do {}; done",
        s.variable,
        items.join(" "),
        render_block(&s.body)
    )
}

fn render_while(s: &WhileLoop) -> String {
    format!(
        "while {}; do {}; done",
        render_expr(&s.condition),
        render_block(&s.body)
    )
}

fn render_case(s: &CaseStmt) -> String {
    let branches: Vec<String> = s
        .branches
        .iter()
        .map(|b| format!("{}) {} ;;", b.patterns.join("|"), render_block(&b.body)))
        .collect();
    format!("case {} in {} esac", render_expr(&s.expr), branches.join(" "))
}

fn render_tooldef(def: &ToolDef) -> String {
    let params: Vec<String> = def
        .params
        .iter()
        .map(|p| match &p.default {
            Some(default) => format!("{}={}", p.name, render_expr(default)),
            None => p.name.clone(),
        })
        .collect();
    format!(
        "tool {}({}) {{ {} }}",
        def.name,
        params.join(", "),
        render_block(&def.body)
    )
}

/// Render one expression back to shell text, unexpanded: a variable
/// reference stays `${NAME}` and a substitution stays `$(…)`.
pub(crate) fn render_expr(expr: &Expr) -> String {
    match expr {
        Expr::Not(inner) => format!("! {}", render_expr(inner)),
        Expr::Literal(v) => render_literal(v),
        Expr::VarRef(path) => format!("${{{}}}", render_varpath(path)),
        Expr::Interpolated(parts) => format!("\"{}\"", render_parts(parts)),
        Expr::HereDocBody { parts, strip_tabs } => {
            let dash = if *strip_tabs { "-" } else { "" };
            let body: Vec<String> = parts.iter().map(|sp| render_part(&sp.part)).collect();
            format!("<<{dash}EOF\n{}\nEOF", body.join(""))
        }
        Expr::BinaryOp { left, op, right } => {
            let op = match op {
                BinaryOp::And => "&&",
                BinaryOp::Or => "||",
            };
            format!("{} {} {}", render_expr(left), op, render_expr(right))
        }
        Expr::CommandSubst(stmts) => format!("$({})", render_block(stmts)),
        Expr::Test(t) => format!("[[ {} ]]", render_test(t)),
        Expr::Positional(n) => format!("${n}"),
        Expr::AllArgs => "$@".to_string(),
        Expr::ArgCount => "$#".to_string(),
        Expr::VarLength(path) => format!("${{#{}}}", render_varpath(path)),
        Expr::VarWithDefault { path, default } => {
            format!("${{{}:-{}}}", render_varpath(path), render_parts(default))
        }
        Expr::Arithmetic(e) => format!("$(({e}))"),
        Expr::Command(cmd) => render_command(cmd),
        Expr::LastExitCode => "$?".to_string(),
        Expr::CurrentPid => "$$".to_string(),
        Expr::GlobPattern(p) => p.clone(),
        Expr::ListLiteral(elems) => {
            let parts: Vec<String> = elems
                .iter()
                .map(|e| match e {
                    ListElem::Item(e) => render_expr(e),
                    ListElem::Spread(e) => format!("...{}", render_expr(e)),
                })
                .collect();
            format!("[{}]", parts.join(" "))
        }
        Expr::RecordLiteral(entries) => {
            let parts: Vec<String> = entries
                .iter()
                .map(|entry| {
                    let key = match &entry.key {
                        RecordKey::Bare(k) => k.clone(),
                        RecordKey::Quoted(k) => format!("\"{k}\""),
                        RecordKey::Interpolated(parts) => format!("\"{}\"", render_parts(parts)),
                    };
                    format!("{key}: {}", render_expr(&entry.value))
                })
                .collect();
            format!("{{{}}}", parts.join(", "))
        }
    }
}

/// A literal, quoted only where a shell reader would need the quotes.
fn render_literal(value: &Value) -> String {
    match value {
        Value::String(s) => quote_word(s),
        Value::Int(i) => i.to_string(),
        Value::Float(f) => f.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Null => "null".to_string(),
        Value::Json(j) => j.to_string(),
        // Binary reaches a plan only through `execute_argv`, which takes
        // typed values. Naming the length is honest; printing the bytes
        // would put unreadable data in a stored plan.
        Value::Bytes(b) => format!("<bytes len={}>", b.len()),
    }
}

/// Single-quote a word that a shell reader could not take literally.
fn quote_word(s: &str) -> String {
    let needs_quotes = s.is_empty()
        || s.chars()
            .any(|c| c.is_whitespace() || "\"'$`&|;<>(){}[]*?#!~\\".contains(c));
    if !needs_quotes {
        return s.to_string();
    }
    // `'\''` is the one portable way to put a single quote inside a
    // single-quoted word.
    format!("'{}'", s.replace('\'', "'\\''"))
}

fn render_parts(parts: &[StringPart]) -> String {
    parts.iter().map(render_part).collect::<Vec<_>>().join("")
}

fn render_part(part: &StringPart) -> String {
    match part {
        StringPart::Literal(s) => s.replace('\\', "\\\\").replace('"', "\\\""),
        StringPart::Var(path) => format!("${{{}}}", render_varpath(path)),
        StringPart::VarWithDefault { path, default } => {
            format!("${{{}:-{}}}", render_varpath(path), render_parts(default))
        }
        StringPart::VarLength(path) => format!("${{#{}}}", render_varpath(path)),
        StringPart::Positional(n) => format!("${n}"),
        StringPart::AllArgs => "$@".to_string(),
        StringPart::ArgCount => "$#".to_string(),
        StringPart::Arithmetic(e) => format!("$(({e}))"),
        StringPart::CommandSubst(stmts) => format!("$({})", render_block(stmts)),
        StringPart::LastExitCode => "$?".to_string(),
        StringPart::CurrentPid => "$$".to_string(),
    }
}

fn render_test(test: &TestExpr) -> String {
    match test {
        TestExpr::FileTest { op, path } => format!("{} {}", op, render_expr(path)),
        TestExpr::StringTest { op, value } => format!("{} {}", op, render_expr(value)),
        TestExpr::Comparison { left, op, right } => {
            format!("{} {} {}", render_expr(left), op, render_expr(right))
        }
        TestExpr::And { left, right } => {
            format!("{} && {}", render_test(left), render_test(right))
        }
        TestExpr::Or { left, right } => {
            format!("{} || {}", render_test(left), render_test(right))
        }
        TestExpr::Not { expr } => format!("! {}", render_test(expr)),
        TestExpr::In { left, right } => {
            format!("{} in {}", render_expr(left), render_expr(right))
        }
        TestExpr::NotIn { left, right } => {
            format!("{} not in {}", render_expr(left), render_expr(right))
        }
    }
}

/// Render a variable path in its source form: the root name, then bracket
/// subscripts. Never dotted — kaish access is brackets-only.
fn render_varpath(path: &VarPath) -> String {
    let mut out = String::new();
    for (i, segment) in path.segments.iter().enumerate() {
        match segment {
            VarSegment::Field(name) => {
                if i > 0 {
                    out.push('.');
                }
                out.push_str(name);
            }
            VarSegment::Index(idx) => out.push_str(&format!("[{idx}]")),
            VarSegment::Key(k) => out.push_str(&format!("[{k}]")),
            VarSegment::Dynamic(v) => out.push_str(&format!("[${v}]")),
            VarSegment::Slice(a, b) => out.push_str(&format!(
                "[{}:{}]",
                a.map(|n| n.to_string()).unwrap_or_default(),
                b.map(|n| n.to_string()).unwrap_or_default()
            )),
        }
    }
    out
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::parser::parse;

    fn planned_of(source: &str) -> StatementPlan {
        let program = parse(source).expect("the fixture parses");
        let stmt = program
            .statements
            .into_iter()
            .find(|s| !matches!(s, Stmt::Empty))
            .expect("one statement");
        plan_statement(&stmt)
    }

    fn plan_of(source: &str) -> Plan {
        planned_of(source).plan
    }

    #[test]
    fn a_variable_renders_unexpanded() {
        let plan = plan_of("rm -r \"${HOME}/build\"");
        assert!(
            plan.rendered.contains("${HOME}"),
            "the plan must keep the variable as written: {}",
            plan.rendered
        );
    }

    #[test]
    fn a_substitution_renders_unexpanded_and_plans_its_own_command() {
        let plan = plan_of("rm $(cat list.txt)");
        assert!(
            plan.rendered.contains("$(cat list.txt)"),
            "got: {}",
            plan.rendered
        );
        let names: Vec<&str> = plan.commands.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["rm", "cat"], "the substitution runs too");
    }

    #[test]
    fn a_loop_body_belongs_to_the_enclosing_statement() {
        let plan = plan_of("for f in a b; do rm $f; done");
        assert_eq!(plan.statement_kind, "for");
        let names: Vec<&str> = plan.commands.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["rm"]);
        assert!(plan.rendered.starts_with("for f in a b; do rm"));
    }

    #[test]
    fn every_redirect_form_renders() {
        let plan = plan_of("cmd > out.txt 2> err.txt < in.txt");
        let kinds: Vec<&str> = plan.commands[0]
            .redirects
            .iter()
            .map(|r| r.kind.as_str())
            .collect();
        assert_eq!(kinds, vec![">", "2>", "<"]);
        assert_eq!(
            plan.commands[0].redirects[0].target,
            PlannedValue::Plain("out.txt".to_string())
        );
        assert!(plan.rendered.contains("> out.txt"), "got: {}", plan.rendered);
    }

    #[test]
    fn a_redirect_target_stays_unexpanded() {
        let plan = plan_of("echo hi > ${LOG}");
        assert_eq!(
            plan.commands[0].redirects[0].target,
            PlannedValue::Plain("${LOG}".to_string())
        );
    }

    #[test]
    fn a_merge_redirect_renders_as_its_operator_alone() {
        let plan = plan_of("cmd 2>&1");
        assert!(
            plan.rendered.ends_with("2>&1"),
            "a merge redirect has no filename: {}",
            plan.rendered
        );
    }

    #[test]
    fn every_argument_form_renders() {
        let plan = plan_of("tool -v --force --key=value word -- --after");
        let args = &plan.commands[0].args;
        assert_eq!(
            args,
            &vec![
                PlannedValue::Plain("-v".to_string()),
                PlannedValue::Plain("--force".to_string()),
                PlannedValue::Plain("--key=value".to_string()),
                PlannedValue::Plain("word".to_string()),
                PlannedValue::Plain("--".to_string()),
                PlannedValue::Plain("--after".to_string()),
            ]
        );
    }

    #[test]
    fn a_backgrounded_pipeline_marks_every_command() {
        let plan = plan_of("a | b &");
        assert!(plan.commands.iter().all(|c| c.background));
        assert!(plan.rendered.ends_with('&'), "got: {}", plan.rendered);
    }

    #[test]
    fn a_pipeline_renders_every_stage() {
        let plan = plan_of("cat f | grep x | wc -l");
        let names: Vec<&str> = plan.commands.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["cat", "grep", "wc"]);
        assert_eq!(plan.rendered, "cat f | grep x | wc -l");
    }

    #[test]
    fn an_and_chain_plans_both_sides() {
        let plan = plan_of("mkdir d && rm -r d");
        assert_eq!(plan.statement_kind, "and_chain");
        let names: Vec<&str> = plan.commands.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["mkdir", "rm"]);
    }

    #[test]
    fn an_if_plans_its_condition_and_both_branches() {
        let plan = plan_of("if grep -q x f; then echo hit; else echo miss; fi");
        let names: Vec<&str> = plan.commands.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["grep", "echo", "echo"]);
    }

    #[test]
    fn a_quoted_word_keeps_its_spaces_inside_quotes() {
        let plan = plan_of("echo 'two words'");
        assert_eq!(plan.rendered, "echo 'two words'");
    }

    #[test]
    fn an_interpolated_string_keeps_its_variables() {
        let plan = plan_of("echo \"hello ${NAME}\"");
        assert_eq!(plan.rendered, "echo \"hello ${NAME}\"");
    }

    #[test]
    fn a_bracket_path_renders_with_brackets_not_dots() {
        let plan = plan_of("echo ${servers[web]}");
        assert_eq!(plan.rendered, "echo ${servers[web]}");
    }

    #[test]
    fn rendering_truncates_at_the_limit_with_a_loud_marker() {
        let long = "x".repeat(PLAN_RENDER_LIMIT * 2);
        let plan = plan_of(&format!("echo {long}"));
        assert!(
            plan.rendered.contains("[rendering truncated at 8192 bytes]"),
            "expected the marker, got {} bytes ending in {:?}",
            plan.rendered.len(),
            &plan.rendered[plan.rendered.len().saturating_sub(48)..]
        );
        // The structure survives the cut — that is what a classifier reads.
        assert_eq!(plan.commands.len(), 1);
        assert_eq!(plan.commands[0].name, "echo");
    }

    #[test]
    fn a_short_rendering_carries_no_marker() {
        let plan = plan_of("echo hi");
        assert_eq!(plan.rendered, "echo hi");
    }

    // ── The presented credential (spec §A.2, §C.6) ──

    #[test]
    fn a_literal_key_is_lifted_and_redacted() {
        let planned = planned_of("rm --confirm=deadbeef target.txt");
        assert_eq!(planned.presented_keys, vec!["deadbeef".to_string()]);
        assert_eq!(planned.plan.rendered, "rm --confirm=<confirm-key> target.txt");
        assert_eq!(
            planned.plan.commands[0].args,
            vec![
                PlannedValue::redacted("confirm-key", None),
                PlannedValue::Plain("target.txt".to_string()),
            ]
        );
    }

    #[test]
    fn the_bare_word_assign_spelling_is_lifted_too() {
        // `dd` takes its operands as `key=value`, so this is the same
        // credential wearing the other spelling.
        let planned = planned_of("dd if=a of=b confirm=deadbeef");
        assert_eq!(planned.presented_keys, vec!["deadbeef".to_string()]);
        assert!(
            planned.plan.rendered.ends_with("confirm=<confirm-key>"),
            "got: {}",
            planned.plan.rendered
        );
    }

    #[test]
    fn a_variable_carried_key_is_neither_lifted_nor_redacted() {
        // Nothing to lift and nothing to leak: an unexpanded plan never held
        // the value, so it renders as written like any other variable.
        let planned = planned_of("rm --confirm=${key} target.txt");
        assert!(planned.presented_keys.is_empty());
        assert_eq!(planned.plan.rendered, "rm --confirm=${key} target.txt");
    }

    #[test]
    fn a_key_inside_a_loop_body_is_still_lifted() {
        let planned = planned_of("for f in a b; do rm --confirm=deadbeef $f; done");
        assert_eq!(planned.presented_keys, vec!["deadbeef".to_string()]);
    }

    #[test]
    fn redaction_takes_the_whole_token_and_leaves_one_space() {
        let source = "rm --confirm=deadbeef target.txt";
        assert_eq!(
            redact_keys(source, &["deadbeef".to_string()]),
            "rm target.txt"
        );
    }

    #[test]
    fn redaction_leaves_a_source_that_never_presented_a_key_alone() {
        let source = "rm target.txt";
        assert_eq!(redact_keys(source, &[]), source);
        assert_eq!(redact_keys(source, &["deadbeef".to_string()]), source);
    }

    // ── Variable analysis ──

    #[test]
    fn reads_cover_interpolation_length_subscript_and_arithmetic() {
        let plan = plan_of(
            "echo \"${greeting} ${#items} ${servers[$env]}\" $((base + offset))",
        );
        assert_eq!(
            plan.free_variables,
            vec!["base", "env", "greeting", "items", "offset", "servers"],
            "every lexical read is listed, sorted"
        );
        assert!(plan.bound_variables.is_empty());
    }

    #[test]
    fn a_subscripted_assignment_binds_the_root_and_reads_the_subscript() {
        let plan = plan_of("counts[$key]=1");
        assert_eq!(plan.free_variables, vec!["key"]);
        assert_eq!(plan.bound_variables, vec!["counts"]);
    }

    #[test]
    fn an_env_prefix_binds_its_name_for_the_one_command() {
        let plan = plan_of("MODE=fast deploy ${TARGET}");
        assert_eq!(plan.free_variables, vec!["TARGET"]);
        assert_eq!(plan.bound_variables, vec!["MODE"]);
    }

    // ── plan_program: the program-level surface ──

    /// `index` is the position in the returned list, so indexing the list by it
    /// reads the statement it names.
    ///
    /// This used to preserve the gap left by a dropped `Stmt::Empty`, to line
    /// up with `Capture::Statement`'s index. That type was approval-ledger
    /// vocabulary; it was cut in 2481a3f3 and the ledger was deleted whole in
    /// 0c36dba1, before 0.14.0. The correspondence had no remaining consumer,
    /// and what it cost was an off-by-one in every script that opens with a
    /// comment.
    #[test]
    fn plan_program_indexes_are_dense_and_ordered() {
        let source = "echo one\n\n# a comment\necho two && echo three\nX=5";
        let program = parse(source).expect("the fixture parses");
        let expected: Vec<String> = program
            .statements
            .iter()
            .filter(|s| !matches!(s, Stmt::Empty))
            .map(|s| s.kind_name().to_string())
            .collect();
        let plans = plan_program(source).expect("the fixture parses");
        assert_eq!(
            plans.iter().map(|p| p.plan.statement_kind.clone()).collect::<Vec<_>>(),
            expected,
            "every non-empty statement is planned, in source order"
        );
        for (position, planned) in plans.iter().enumerate() {
            assert_eq!(
                planned.index, position,
                "index must be the position in the returned list"
            );
        }
    }

    /// The shape that made the old numbering wrong. A leading comment parses to
    /// a `Stmt::Empty` the plan drops, and numbering before the drop started
    /// every later statement one too high.
    #[test]
    fn a_leading_comment_does_not_shift_the_indexes() {
        let plans = plan_program("# lead\necho a\necho b").expect("parses");
        assert_eq!(plans.len(), 2);
        assert_eq!(plans[0].index, 0, "a leading comment must not shift index");
        assert_eq!(plans[1].index, 1);
    }

    #[test]
    fn plan_program_redacts_a_presented_key_and_returns_no_copy_of_it() {
        // `PlannedStatement` has no key field by design — the caller holds
        // the source. What must hold is that the plan itself is redacted.
        let plans = plan_program("rm --confirm=deadbeef x.txt").expect("parses");
        assert_eq!(plans[0].plan.rendered, "rm --confirm=<confirm-key> x.txt");
    }

    #[test]
    fn plan_program_returns_the_parse_errors_for_a_broken_source() {
        let errors = plan_program("echo 'unclosed").expect_err("must not parse");
        assert!(!errors.is_empty());
    }

    #[test]
    fn redaction_covers_both_spellings_across_a_multi_statement_source() {
        let source = "echo one\ndd if=a confirm=deadbeef\nrm --confirm=deadbeef x";
        let redacted = redact_keys(source, &["deadbeef".to_string()]);
        assert!(!redacted.contains("deadbeef"), "got: {redacted}");
        assert_eq!(redacted, "echo one\ndd if=a\nrm x");
    }
}