flux-platform 1.0.1

A local-first, AI-native developer automation platform: build, test, package, and deploy from a single .flux file, and make your repository legible to AI agents.
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
//! A small hand-written lexer + recursive-descent parser for `.flux`.
//!
//! The grammar is intentionally small, so a dedicated parser generator (pest,
//! nom) would be more machinery than the language warrants. Keeping it
//! hand-rolled means zero grammar-build steps and precise error messages.
//!
//! ```text
//! config    := item*
//! item      := "project" STRING
//!            | "language" IDENT
//!            | "environment" "{" ("image" STRING)* "}"
//!            | "secret" IDENT
//!            | "deployment" "{" dep_field* "}"
//!            | "runners" "{" pool* "}"
//!            | "policy" name "{" require* "}"
//!            | "pipeline" "{" (exec_field | step | use)* "}"
//! dep_field := "target" IDENT | "replicas" NUM | "image" STRING
//! pool      := "pool" name "{" pool_field* "}"
//! pool_field := requirement_field
//!            | "requirements" "{" requirement_field* "}"
//! requirement_field := "os" name | "gpu" bool | "memory" name
//! require   := "require" ("tests" | "security" | "approvals" NUM)
//! use       := "use" name
//! exec_field := "timeout" duration     ; default limit for steps without one
//!            | "parallel" NUM          ; cap on concurrently running steps
//! step      := "step" IDENT "{" field* "}"
//! field     := "command" STRING
//!            | "tool" IDENT
//!            | "description" STRING
//!            | "cache" IDENT              ; on/off/true/false/yes/no
//!            | "needs" ident_or_list
//!            | "secrets" ident_or_list    ; declared secret names to inject
//!            | "inputs" ident_or_list     ; cache-scoping globs
//!            | "retries" NUM
//!            | "timeout" duration
//!            | "only_if" cond_var ("=="|"!=") STRING
//! duration  := NUM                     ; seconds
//!            | STRING                  ; NUM ("s" | "m" | "h")
//!            | "off"                   ; no limit
//! ident_or_list := item_or_str | "[" (item_or_str ("," item_or_str)*)? "]"
//! item_or_str   := IDENT | STRING
//! name          := IDENT | STRING
//! cond_var      := one of ast::CONDITION_VARS
//! bool          := "true" | "yes" | "on"  ; anything else is false
//! ```
//!
//! A `:` after a field keyword (e.g. `only_if:` or `secrets:`) is accepted and
//! ignored, so the spec's colon style parses too. Commas inside `[ … ]` lists
//! and inside `policy`/`runners`/`requirements` blocks are optional separators.
//!
//! ## Retired keywords
//!
//! Three keywords parsed but did nothing, so they were removed rather than left
//! to imply a feature that was never there:
//!
//! * the step field `env`, which always meant *secret names*, never environment
//!   variables. It is the one with a migration window: it still parses, sets
//!   `secrets`, and raises a [`ParseWarning`]. It will be removed next release,
//!   after which the name is free for real environment variables.
//! * the step field `pool`, which never reached the scheduler. Pools are still
//!   declared with the top-level `runners` block and listed by `flux runners
//!   list`; only the per-step preference is gone.
//! * the top-level `import`, which parsed into a list nothing ever read. `use`
//!   inside `pipeline { … }` is the directive that actually loads a module.
//!
//! `pool` and `import` are hard errors that name their replacement, because a
//! silent no-op is exactly what made them worth removing.

use std::fmt;
use std::time::Duration;

use super::ast::{
    CondOp, Condition, Deployment, Environment, FluxConfig, Policy, RunnerPool, Step, Timeout,
    CONDITION_VARS,
};

/// A parse failure with 1-based line information.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    pub line: usize,
    pub message: String,
}

/// A non-fatal diagnostic raised while parsing, currently only deprecations.
/// The file still parses; the caller decides how loudly to say so.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseWarning {
    pub line: usize,
    pub message: String,
}

impl fmt::Display for ParseWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "line {}: {}", self.line, self.message)
    }
}

impl ParseError {
    fn new(line: usize, message: impl Into<String>) -> Self {
        ParseError {
            line,
            message: message.into(),
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "line {}: {}", self.line, self.message)
    }
}

impl std::error::Error for ParseError {}

// ---------------------------------------------------------------------------
// Lexer
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
enum TokKind {
    Ident,
    Str,
    Num,
    Op, // "==" or "!="
    LBrace,
    RBrace,
    LBracket,
    RBracket,
    Comma,
}

#[derive(Debug, Clone)]
struct Token {
    kind: TokKind,
    text: String,
    line: usize,
}

fn is_ident_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_'
}

fn is_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')
}

fn lex(src: &str) -> Result<Vec<Token>, ParseError> {
    // Windows editors (Notepad, some VS Code configurations) save UTF-8 with a
    // leading byte-order mark. The BOM is an encoding artifact, not content, so
    // drop it — otherwise the first token is U+FEFF, which is not whitespace,
    // and the file fails with an opaque "unexpected character" error.
    let src = src.strip_prefix('\u{feff}').unwrap_or(src);

    let mut tokens = Vec::new();
    let mut line = 1usize;
    let mut chars = src.chars().peekable();

    while let Some(&c) = chars.peek() {
        match c {
            '\n' => {
                line += 1;
                chars.next();
            }
            // A colon is decorative (e.g. `only_if:`); skip it.
            ':' => {
                chars.next();
            }
            c if c.is_whitespace() => {
                chars.next();
            }
            // `#` line comment
            '#' => {
                while let Some(&c) = chars.peek() {
                    if c == '\n' {
                        break;
                    }
                    chars.next();
                }
            }
            // `//` line comment
            '/' => {
                chars.next();
                if chars.peek() == Some(&'/') {
                    while let Some(&c) = chars.peek() {
                        if c == '\n' {
                            break;
                        }
                        chars.next();
                    }
                } else {
                    return Err(ParseError::new(
                        line,
                        "unexpected '/' (did you mean '//' ?)",
                    ));
                }
            }
            '{' => {
                push(&mut tokens, TokKind::LBrace, "{", line);
                chars.next();
            }
            '}' => {
                push(&mut tokens, TokKind::RBrace, "}", line);
                chars.next();
            }
            '[' => {
                push(&mut tokens, TokKind::LBracket, "[", line);
                chars.next();
            }
            ']' => {
                push(&mut tokens, TokKind::RBracket, "]", line);
                chars.next();
            }
            ',' => {
                push(&mut tokens, TokKind::Comma, ",", line);
                chars.next();
            }
            '=' => {
                chars.next();
                if chars.peek() == Some(&'=') {
                    chars.next();
                    push(&mut tokens, TokKind::Op, "==", line);
                } else {
                    return Err(ParseError::new(
                        line,
                        "unexpected '=' (did you mean '==' ?)",
                    ));
                }
            }
            '!' => {
                chars.next();
                if chars.peek() == Some(&'=') {
                    chars.next();
                    push(&mut tokens, TokKind::Op, "!=", line);
                } else {
                    return Err(ParseError::new(
                        line,
                        "unexpected '!' (did you mean '!=' ?)",
                    ));
                }
            }
            '"' => {
                chars.next(); // consume opening quote
                let start_line = line;
                let mut s = String::new();
                loop {
                    match chars.next() {
                        Some('"') => break,
                        Some('\\') => match chars.next() {
                            Some('n') => s.push('\n'),
                            Some('t') => s.push('\t'),
                            Some('"') => s.push('"'),
                            Some('\\') => s.push('\\'),
                            Some(other) => s.push(other),
                            None => return Err(ParseError::new(start_line, "unterminated string")),
                        },
                        Some('\n') => {
                            return Err(ParseError::new(
                                start_line,
                                "newline inside string literal",
                            ))
                        }
                        Some(other) => s.push(other),
                        None => return Err(ParseError::new(start_line, "unterminated string")),
                    }
                }
                push(&mut tokens, TokKind::Str, &s, start_line);
            }
            c if c.is_ascii_digit() => {
                let mut s = String::new();
                while let Some(&c) = chars.peek() {
                    if c.is_ascii_digit() {
                        s.push(c);
                        chars.next();
                    } else {
                        break;
                    }
                }
                push(&mut tokens, TokKind::Num, &s, line);
            }
            c if is_ident_start(c) => {
                let mut s = String::new();
                while let Some(&c) = chars.peek() {
                    if is_ident_char(c) {
                        s.push(c);
                        chars.next();
                    } else {
                        break;
                    }
                }
                push(&mut tokens, TokKind::Ident, &s, line);
            }
            other => {
                return Err(ParseError::new(
                    line,
                    format!("unexpected character '{other}'"),
                ))
            }
        }
    }

    Ok(tokens)
}

fn push(tokens: &mut Vec<Token>, kind: TokKind, text: &str, line: usize) {
    tokens.push(Token {
        kind,
        text: text.to_string(),
        line,
    });
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

struct Parser {
    toks: Vec<Token>,
    pos: usize,
    warnings: Vec<ParseWarning>,
}

impl Parser {
    fn warn(&mut self, line: usize, message: impl Into<String>) {
        self.warnings.push(ParseWarning {
            line,
            message: message.into(),
        });
    }

    fn peek(&self) -> Option<&Token> {
        self.toks.get(self.pos)
    }

    fn next(&mut self) -> Option<Token> {
        let t = self.toks.get(self.pos).cloned();
        if t.is_some() {
            self.pos += 1;
        }
        t
    }

    fn last_line(&self) -> usize {
        self.toks
            .get(self.pos.saturating_sub(1))
            .map(|t| t.line)
            .unwrap_or(0)
    }

    fn expect(&mut self, kind: TokKind, what: &str) -> Result<Token, ParseError> {
        match self.next() {
            Some(t) if t.kind == kind => Ok(t),
            Some(t) => Err(ParseError::new(
                t.line,
                format!("expected {what}, found '{}'", t.text),
            )),
            None => Err(ParseError::new(
                self.last_line(),
                format!("expected {what}, found end of file"),
            )),
        }
    }

    fn expect_lbrace(&mut self) -> Result<(), ParseError> {
        self.expect(TokKind::LBrace, "'{'").map(|_| ())
    }

    fn expect_str(&mut self) -> Result<String, ParseError> {
        self.expect(TokKind::Str, "a quoted string").map(|t| t.text)
    }

    fn expect_ident(&mut self) -> Result<(String, usize), ParseError> {
        self.expect(TokKind::Ident, "an identifier")
            .map(|t| (t.text, t.line))
    }

    fn expect_number(&mut self) -> Result<(u32, usize), ParseError> {
        let t = self.expect(TokKind::Num, "a number")?;
        let n = t
            .text
            .parse::<u32>()
            .map_err(|_| ParseError::new(t.line, format!("'{}' is not a valid number", t.text)))?;
        Ok((n, t.line))
    }

    /// Accept either a quoted string or a bare identifier, returning its text.
    fn expect_str_or_ident(&mut self) -> Result<String, ParseError> {
        match self.next() {
            Some(t) if t.kind == TokKind::Str || t.kind == TokKind::Ident => Ok(t.text),
            Some(t) => Err(ParseError::new(
                t.line,
                format!("expected a name or string, found '{}'", t.text),
            )),
            None => Err(ParseError::new(
                self.last_line(),
                "expected a name or string, found end of file",
            )),
        }
    }
}

/// Parse and discard the warnings.
///
/// Test-only. Every caller that reads a file from disk goes through
/// [`parse_with_warnings`] instead, so a pipeline still riding a deprecated
/// keyword is told about it rather than finding out at removal time.
#[cfg(test)]
pub fn parse(src: &str) -> Result<FluxConfig, ParseError> {
    parse_with_warnings(src).map(|(cfg, _)| cfg)
}

/// Parse `.flux` source text, also returning the deprecation warnings it raised.
/// Callers that read a file from disk should report these so a pipeline riding
/// on a deprecated keyword doesn't discover the removal at upgrade time.
pub fn parse_with_warnings(src: &str) -> Result<(FluxConfig, Vec<ParseWarning>), ParseError> {
    let toks = lex(src)?;
    let mut p = Parser {
        toks,
        pos: 0,
        warnings: Vec::new(),
    };
    let mut cfg = FluxConfig::default();

    while let Some(tok) = p.peek().cloned() {
        if tok.kind != TokKind::Ident {
            return Err(ParseError::new(
                tok.line,
                format!("expected a top-level keyword, found '{}'", tok.text),
            ));
        }
        match tok.text.as_str() {
            "project" => {
                p.next();
                cfg.project = Some(p.expect_str()?);
            }
            "language" => {
                p.next();
                cfg.language = Some(p.expect_ident()?.0);
            }
            "environment" => {
                p.next();
                cfg.environment = Some(parse_environment(&mut p)?);
            }
            "secret" => {
                p.next();
                cfg.secrets.push(p.expect_ident()?.0);
            }
            "deployment" => {
                p.next();
                cfg.deployment = Some(parse_deployment(&mut p)?);
            }
            "import" => {
                return Err(ParseError::new(
                    tok.line,
                    "the top-level 'import' directive was removed: it declared a module but never loaded one. Use `use <name>` inside `pipeline { … }` to splice in modules/<name>.flux",
                ))
            }
            "runners" => {
                p.next();
                cfg.runner_pools = parse_runners(&mut p)?;
            }
            "policy" => {
                p.next();
                cfg.policies.push(parse_policy(&mut p)?);
            }
            "pipeline" => {
                p.next();
                parse_pipeline(&mut p, &mut cfg)?;
            }
            other => {
                return Err(ParseError::new(
                    tok.line,
                    format!(
                        "unknown top-level keyword '{other}' (expected project, language, environment, secret, deployment, runners, policy, or pipeline)"
                    ),
                ))
            }
        }
    }

    Ok((cfg, p.warnings))
}

fn parse_environment(p: &mut Parser) -> Result<Environment, ParseError> {
    p.expect_lbrace()?;
    let mut env = Environment::default();
    loop {
        let tok = match p.peek().cloned() {
            Some(t) => t,
            None => {
                return Err(ParseError::new(
                    p.last_line(),
                    "unclosed 'environment' block",
                ))
            }
        };
        if tok.kind == TokKind::RBrace {
            p.next();
            break;
        }
        let (field, line) = p.expect_ident()?;
        match field.as_str() {
            "image" => env.image = Some(p.expect_str()?),
            other => {
                return Err(ParseError::new(
                    line,
                    format!("unknown environment field '{other}' (expected image)"),
                ))
            }
        }
    }
    Ok(env)
}

fn parse_deployment(p: &mut Parser) -> Result<Deployment, ParseError> {
    p.expect_lbrace()?;
    let mut dep = Deployment::default();
    loop {
        let tok = match p.peek().cloned() {
            Some(t) => t,
            None => {
                return Err(ParseError::new(
                    p.last_line(),
                    "unclosed 'deployment' block",
                ))
            }
        };
        if tok.kind == TokKind::RBrace {
            p.next();
            break;
        }
        let (field, line) = p.expect_ident()?;
        match field.as_str() {
            "target" => dep.target = Some(p.expect_ident()?.0),
            "replicas" => dep.replicas = Some(p.expect_number()?.0),
            "image" => dep.image = Some(p.expect_str()?),
            other => {
                return Err(ParseError::new(
                    line,
                    format!(
                        "unknown deployment field '{other}' (expected target, replicas, or image)"
                    ),
                ))
            }
        }
    }
    Ok(dep)
}

fn parse_pipeline(p: &mut Parser, cfg: &mut FluxConfig) -> Result<(), ParseError> {
    p.expect_lbrace()?;
    loop {
        let tok = match p.peek().cloned() {
            Some(t) => t,
            None => return Err(ParseError::new(p.last_line(), "unclosed 'pipeline' block")),
        };
        if tok.kind == TokKind::RBrace {
            p.next();
            break;
        }
        if tok.kind == TokKind::Ident && tok.text == "step" {
            p.next();
            let step = parse_step(p)?;
            cfg.steps.push(step);
        } else if tok.kind == TokKind::Ident && tok.text == "use" {
            // `use <module>` splices a reusable module's steps into this pipeline.
            p.next();
            cfg.uses.push(p.expect_str_or_ident()?);
        } else if tok.kind == TokKind::Ident && tok.text == "timeout" {
            p.next();
            cfg.execution.timeout = Some(parse_timeout(p)?);
        } else if tok.kind == TokKind::Ident && tok.text == "parallel" {
            p.next();
            cfg.execution.parallel = Some(parse_parallel(p)?);
        } else {
            return Err(ParseError::new(
                tok.line,
                format!(
                    "expected 'step', 'use', 'timeout', 'parallel', or '}}', found '{}'",
                    tok.text
                ),
            ));
        }
    }
    Ok(())
}

fn parse_step(p: &mut Parser) -> Result<Step, ParseError> {
    let (name, _) = p.expect_ident()?;
    let mut step = Step::new(name);
    p.expect_lbrace()?;

    loop {
        let tok = match p.peek().cloned() {
            Some(t) => t,
            None => return Err(ParseError::new(p.last_line(), "unclosed 'step' block")),
        };
        if tok.kind == TokKind::RBrace {
            p.next();
            break;
        }
        if tok.kind != TokKind::Ident {
            return Err(ParseError::new(
                tok.line,
                format!("expected a step field, found '{}'", tok.text),
            ));
        }
        p.next();
        match tok.text.as_str() {
            "command" => step.command = Some(p.expect_str()?),
            "tool" => step.tool = Some(p.expect_ident()?.0),
            "description" => step.description = Some(p.expect_str()?),
            "cache" => {
                let (v, line) = p.expect_ident()?;
                step.cache = match v.as_str() {
                    "on" | "true" | "yes" => true,
                    "off" | "false" | "no" => false,
                    other => {
                        return Err(ParseError::new(
                            line,
                            format!("invalid cache value '{other}' (expected on/off)"),
                        ))
                    }
                };
            }
            "needs" => step.needs = parse_ident_or_list(p)?,
            "secrets" => step.secrets = parse_ident_or_list(p)?,
            // `env` has always meant "secret names"; it is kept for one release
            // so existing pipelines still run, and `flux format` rewrites it.
            "env" => {
                step.secrets = parse_ident_or_list(p)?;
                p.warn(
                    tok.line,
                    format!(
                        "step '{}': the 'env' field is deprecated, rename it to 'secrets'. It will be removed in the next release, freeing 'env' for real environment variables. `flux format` rewrites it for you",
                        step.name
                    ),
                );
            }
            "inputs" => step.inputs = parse_ident_or_list(p)?,
            "pool" => {
                return Err(ParseError::new(
                    tok.line,
                    format!(
                        "the step field 'pool' was removed from step '{}': it never reached the scheduler. Declare pools with the top-level `runners {{ pool … }}` block and see them with `flux runners list`",
                        step.name
                    ),
                ))
            }
            "retries" => step.retries = p.expect_number()?.0,
            "timeout" => step.timeout = Some(parse_timeout(p)?),
            "only_if" => step.only_if = Some(parse_condition(p)?),
            other => {
                return Err(ParseError::new(
                    tok.line,
                    format!(
                        "unknown step field '{other}' (expected command, tool, description, cache, needs, secrets, inputs, retries, timeout, or only_if)"
                    ),
                ))
            }
        }
    }

    if step.command.is_none() && step.tool.is_none() {
        return Err(ParseError::new(
            p.last_line(),
            format!("step '{}' has neither a command nor a tool", step.name),
        ));
    }

    Ok(step)
}

/// Parse either a bare item or a `[a, b, c]` list. Items may be identifiers
/// (e.g. step names) or quoted strings (e.g. glob patterns for `inputs`).
fn parse_ident_or_list(p: &mut Parser) -> Result<Vec<String>, ParseError> {
    match p.peek().cloned() {
        Some(t) if t.kind == TokKind::LBracket => {
            p.next();
            let mut items = Vec::new();
            loop {
                let tok = match p.peek().cloned() {
                    Some(t) => t,
                    None => return Err(ParseError::new(p.last_line(), "unclosed '[' list")),
                };
                if tok.kind == TokKind::RBracket {
                    p.next();
                    break;
                }
                if tok.kind == TokKind::Comma {
                    p.next();
                    continue;
                }
                items.push(p.expect_str_or_ident()?);
            }
            Ok(items)
        }
        Some(t) if t.kind == TokKind::Ident || t.kind == TokKind::Str => {
            Ok(vec![p.expect_str_or_ident()?])
        }
        Some(t) => Err(ParseError::new(
            t.line,
            format!("expected an item or '[', found '{}'", t.text),
        )),
        None => Err(ParseError::new(p.last_line(), "expected an item or '['")),
    }
}

/// Units accepted inside a quoted duration, longest suffix first so `"90s"`
/// isn't mistaken for a bare number.
const DURATION_UNITS: &[(&str, u64)] = &[("h", 3600), ("m", 60), ("s", 1)];

/// Parse a `timeout` value in any of its three forms: a bare number of seconds,
/// a quoted `"<n><unit>"`, or the bare word `off`.
///
/// A bare `10m` is rejected with the quoted spelling rather than silently read
/// as `10` seconds followed by a stray field: the lexer splits it into a number
/// and an identifier, and a timeout that is 60x shorter than written is exactly
/// the kind of quiet wrongness this language avoids elsewhere.
fn parse_timeout(p: &mut Parser) -> Result<Timeout, ParseError> {
    match p.peek().cloned() {
        Some(t) if t.kind == TokKind::Num => {
            let (secs, line) = p.expect_number()?;
            if let Some(unit) = p.peek().filter(|n| {
                n.kind == TokKind::Ident && DURATION_UNITS.iter().any(|(u, _)| *u == n.text)
            }) {
                return Err(ParseError::new(
                    unit.line,
                    format!(
                        "a timeout with a unit must be quoted: write `timeout \"{secs}{}\"`",
                        unit.text
                    ),
                ));
            }
            if secs == 0 {
                return Err(ParseError::new(line, zero_timeout_message()));
            }
            Ok(Timeout::After(Duration::from_secs(secs as u64)))
        }
        Some(t) if t.kind == TokKind::Str => {
            p.next();
            let secs = parse_duration_literal(&t.text).ok_or_else(|| {
                ParseError::new(
                    t.line,
                    format!(
                        "invalid timeout '{}' (expected a number and one of s, m, h, e.g. \"90s\", \"10m\", \"2h\")",
                        t.text
                    ),
                )
            })?;
            if secs == 0 {
                return Err(ParseError::new(t.line, zero_timeout_message()));
            }
            Ok(Timeout::After(Duration::from_secs(secs)))
        }
        Some(t) if t.kind == TokKind::Ident => {
            let (word, line) = p.expect_ident()?;
            match word.as_str() {
                "off" | "none" => Ok(Timeout::Off),
                other => Err(ParseError::new(
                    line,
                    format!(
                        "invalid timeout '{other}' (expected a number of seconds, a quoted duration like \"10m\", or 'off')"
                    ),
                )),
            }
        }
        Some(t) => Err(ParseError::new(
            t.line,
            format!("expected a timeout value, found '{}'", t.text),
        )),
        None => Err(ParseError::new(
            p.last_line(),
            "expected a timeout value, found end of file",
        )),
    }
}

fn zero_timeout_message() -> String {
    "a timeout of 0 would kill the command immediately; write `timeout off` to run it unbounded"
        .to_string()
}

/// Parse `"<number><unit>"` into whole seconds. `None` when it isn't one.
fn parse_duration_literal(text: &str) -> Option<u64> {
    let text = text.trim();
    let (unit, secs_per) = DURATION_UNITS
        .iter()
        .find(|(u, _)| text.len() > u.len() && text.ends_with(u))?;
    let digits = &text[..text.len() - unit.len()];
    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
        return None;
    }
    digits.parse::<u64>().ok()?.checked_mul(*secs_per)
}

/// Parse a `parallel N` value. Zero is rejected: it reads like "no limit" but
/// would mean "no workers", and there is no honest way to run a pipeline with
/// nothing running it.
fn parse_parallel(p: &mut Parser) -> Result<u32, ParseError> {
    let (n, line) = p.expect_number()?;
    if n == 0 {
        return Err(ParseError::new(
            line,
            "parallel must be at least 1 (it caps concurrent steps; it cannot disable them)",
        ));
    }
    Ok(n)
}

/// Parse a `runners { pool "name" { requirements { ... } } ... }` block.
fn parse_runners(p: &mut Parser) -> Result<Vec<RunnerPool>, ParseError> {
    p.expect_lbrace()?;
    let mut pools = Vec::new();
    loop {
        let tok = match p.peek().cloned() {
            Some(t) => t,
            None => return Err(ParseError::new(p.last_line(), "unclosed 'runners' block")),
        };
        if tok.kind == TokKind::RBrace {
            p.next();
            break;
        }
        let (kw, line) = p.expect_ident()?;
        if kw != "pool" {
            return Err(ParseError::new(
                line,
                format!("expected 'pool' or '}}', found '{kw}'"),
            ));
        }
        let name = p.expect_str_or_ident()?;
        let mut pool = RunnerPool {
            name,
            ..RunnerPool::default()
        };
        p.expect_lbrace()?;
        loop {
            let tok = match p.peek().cloned() {
                Some(t) => t,
                None => return Err(ParseError::new(p.last_line(), "unclosed 'pool' block")),
            };
            if tok.kind == TokKind::RBrace {
                p.next();
                break;
            }
            if tok.kind == TokKind::Comma {
                p.next();
                continue;
            }
            let (field, fline) = p.expect_ident()?;
            match field.as_str() {
                "requirements" => parse_requirements(p, &mut pool)?,
                "os" => pool.os = Some(p.expect_str_or_ident()?),
                "gpu" => pool.gpu = Some(parse_bool(p)?),
                "memory" => pool.memory = Some(p.expect_str_or_ident()?),
                other => {
                    return Err(ParseError::new(
                        fline,
                        format!(
                        "unknown pool field '{other}' (expected requirements, os, gpu, or memory)"
                    ),
                    ))
                }
            }
        }
        pools.push(pool);
    }
    Ok(pools)
}

fn parse_requirements(p: &mut Parser, pool: &mut RunnerPool) -> Result<(), ParseError> {
    p.expect_lbrace()?;
    loop {
        let tok = match p.peek().cloned() {
            Some(t) => t,
            None => {
                return Err(ParseError::new(
                    p.last_line(),
                    "unclosed 'requirements' block",
                ))
            }
        };
        if tok.kind == TokKind::RBrace {
            p.next();
            break;
        }
        if tok.kind == TokKind::Comma {
            p.next();
            continue;
        }
        let (field, line) = p.expect_ident()?;
        match field.as_str() {
            "gpu" => pool.gpu = Some(parse_bool(p)?),
            "memory" => pool.memory = Some(p.expect_str_or_ident()?),
            "os" => pool.os = Some(p.expect_str_or_ident()?),
            other => {
                return Err(ParseError::new(
                    line,
                    format!("unknown requirement '{other}' (expected gpu, memory, or os)"),
                ))
            }
        }
    }
    Ok(())
}

fn parse_bool(p: &mut Parser) -> Result<bool, ParseError> {
    let v = p.expect_str_or_ident()?;
    Ok(matches!(v.as_str(), "true" | "yes" | "on"))
}

/// Parse `policy <name> { require tests, require security, require approvals N }`.
fn parse_policy(p: &mut Parser) -> Result<Policy, ParseError> {
    let name = p.expect_str_or_ident()?;
    let mut policy = Policy {
        name,
        ..Policy::default()
    };
    p.expect_lbrace()?;
    loop {
        let tok = match p.peek().cloned() {
            Some(t) => t,
            None => return Err(ParseError::new(p.last_line(), "unclosed 'policy' block")),
        };
        if tok.kind == TokKind::RBrace {
            p.next();
            break;
        }
        if tok.kind == TokKind::Comma {
            p.next();
            continue;
        }
        let (kw, line) = p.expect_ident()?;
        if kw != "require" {
            return Err(ParseError::new(
                line,
                format!("expected 'require' in policy, found '{kw}'"),
            ));
        }
        let (what, wline) = p.expect_ident()?;
        match what.as_str() {
            "tests" => policy.require_tests = true,
            "security" => policy.require_security = true,
            "approvals" => policy.require_approvals = p.expect_number()?.0,
            other => {
                return Err(ParseError::new(
                    wline,
                    format!(
                    "unknown policy requirement '{other}' (expected tests, security, or approvals)"
                ),
                ))
            }
        }
    }
    Ok(policy)
}

/// Parse a condition: `cond_var ("==" | "!=") STRING`.
///
/// The variable is checked against [`CONDITION_VARS`] here rather than left to
/// evaluation time. An unbound name would compare equal to `""` and quietly
/// skip (or quietly always run) the step, which is the worst possible failure
/// mode for a typo in a deploy guard.
fn parse_condition(p: &mut Parser) -> Result<Condition, ParseError> {
    let (var, line) = p.expect_ident()?;
    if !CONDITION_VARS.contains(&var.as_str()) {
        return Err(ParseError::new(
            line,
            format!(
                "unknown only_if variable '{var}' (expected {})",
                CONDITION_VARS.join(", ")
            ),
        ));
    }
    let op_tok = p.expect(TokKind::Op, "'==' or '!='")?;
    let op = match op_tok.text.as_str() {
        "==" => CondOp::Eq,
        "!=" => CondOp::Ne,
        _ => unreachable!("lexer only emits == or !="),
    };
    let value = p.expect_str()?;
    Ok(Condition { var, op, value })
}

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

    #[test]
    fn parses_the_reference_example() {
        let src = r#"
            project "my-app"
            language rust

            pipeline {
                step dependencies { command "cargo fetch" }
                step build        { command "cargo build --release" }
                step test         { command "cargo test" }
            }
        "#;
        let cfg = parse(src).expect("should parse");
        assert_eq!(cfg.project.as_deref(), Some("my-app"));
        assert_eq!(cfg.language.as_deref(), Some("rust"));
        assert_eq!(cfg.steps.len(), 3);
        assert_eq!(cfg.steps[1].name, "build");
        assert_eq!(
            cfg.steps[1].command.as_deref(),
            Some("cargo build --release")
        );
        assert!(cfg.steps[1].cache);
    }

    /// A `.flux` file saved as "UTF-8 with BOM" (the Windows editor default)
    /// must parse exactly like the same file without one.
    #[test]
    fn parses_a_file_with_a_utf8_bom() {
        let body = "project \"my-app\"\nlanguage rust\npipeline {\n  step build { command \"cargo build\" }\n}\n";
        let with_bom = format!("\u{feff}{body}");

        // The fixture really does start with the BOM bytes EF BB BF.
        assert_eq!(&with_bom.as_bytes()[..3], &[0xEF, 0xBB, 0xBF]);

        let cfg = parse(&with_bom).expect("a BOM-prefixed file should parse");
        assert_eq!(cfg.project.as_deref(), Some("my-app"));
        assert_eq!(cfg.language.as_deref(), Some("rust"));
        assert_eq!(cfg.steps.len(), 1);
        assert_eq!(cfg.steps[0].name, "build");

        // Identical to the same source without the BOM.
        let plain = parse(body).unwrap();
        assert_eq!(cfg.project, plain.project);
        assert_eq!(cfg.steps.len(), plain.steps.len());
    }

    /// Only a *leading* BOM is an encoding artifact; one in the middle of the
    /// file is genuinely bogus and should still be rejected.
    #[test]
    fn a_bom_in_the_middle_is_still_an_error() {
        let src = "project \"my-app\"\n\u{feff}language rust\n";
        assert!(parse(src).is_err());
    }

    #[test]
    fn parses_tool_hooks_and_cache_flag() {
        let src = r#"
            project "svc"
            language node
            pipeline {
                step build { command "npm run build" cache off }
                step security { tool scanner }
            }
        "#;
        let cfg = parse(src).unwrap();
        assert!(!cfg.steps[0].cache);
        assert_eq!(cfg.steps[1].tool.as_deref(), Some("scanner"));
        assert!(cfg.steps[1].is_hook());
    }

    #[test]
    fn supports_comments() {
        let src = "# a comment\nproject \"x\" // trailing\nlanguage python\n";
        let cfg = parse(src).unwrap();
        assert_eq!(cfg.project.as_deref(), Some("x"));
        assert_eq!(cfg.language.as_deref(), Some("python"));
    }

    #[test]
    fn reports_unknown_keyword_with_line() {
        let err = parse("\nbogus \"x\"\n").unwrap_err();
        assert_eq!(err.line, 2);
    }

    #[test]
    fn rejects_empty_step() {
        let err = parse("pipeline { step build { } }").unwrap_err();
        assert!(err.message.contains("neither a command nor a tool"));
    }

    #[test]
    fn parses_needs_list_and_single() {
        let src = r#"
            pipeline {
                step frontend { command "npm build" }
                step backend  { command "cargo build" }
                step tests {
                    needs [ frontend, backend ]
                    command "./run-tests"
                }
                step package {
                    needs tests
                    command "docker build ."
                }
            }
        "#;
        let cfg = parse(src).unwrap();
        let tests = cfg.steps.iter().find(|s| s.name == "tests").unwrap();
        assert_eq!(tests.needs, vec!["frontend", "backend"]);
        let package = cfg.steps.iter().find(|s| s.name == "package").unwrap();
        assert_eq!(package.needs, vec!["tests"]);
    }

    #[test]
    fn parses_only_if_retries_and_secrets() {
        let src = r#"
            secret DATABASE_URL
            pipeline {
                step deploy {
                    command "./deploy"
                    only_if: branch == "main"
                    retries 3
                    secrets: [ DATABASE_URL ]
                }
            }
        "#;
        let (cfg, warnings) = parse_with_warnings(src).unwrap();
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(cfg.secrets, vec!["DATABASE_URL"]);
        let deploy = &cfg.steps[0];
        assert_eq!(deploy.retries, 3);
        assert_eq!(deploy.secrets, vec!["DATABASE_URL"]);
        let cond = deploy.only_if.as_ref().unwrap();
        assert_eq!(cond.var, "branch");
        assert_eq!(cond.op, CondOp::Eq);
        assert_eq!(cond.value, "main");
    }

    /// `env` keeps working for one release, sets `secrets`, and says so once.
    #[test]
    fn env_is_a_deprecated_alias_for_secrets() {
        let src = r#"
            pipeline {
                step deploy {
                    command "./deploy"
                    env [ TOKEN ]
                }
            }
        "#;
        let (cfg, warnings) = parse_with_warnings(src).unwrap();
        assert_eq!(cfg.steps[0].secrets, vec!["TOKEN"]);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert_eq!(warnings[0].line, 5, "the warning must point at the field");
        assert!(warnings[0].message.contains("'env' field is deprecated"));
        assert!(warnings[0].message.contains("secrets"));
    }

    /// The two removed keywords fail with a message that names the replacement,
    /// rather than the generic "unknown field" list.
    #[test]
    fn removed_keywords_report_their_replacement() {
        let src = "pipeline { step build { command \"x\" pool \"gpu\" } }";
        let pool_err = parse(src).unwrap_err();
        assert!(
            pool_err.message.contains("'pool' was removed"),
            "{pool_err}"
        );
        assert!(pool_err.message.contains("runners"), "{pool_err}");

        let imp_err = parse("import shared-ci\n").unwrap_err();
        assert!(imp_err.message.contains("was removed"), "{imp_err}");
        assert!(imp_err.message.contains("use <name>"), "{imp_err}");
        assert_eq!(imp_err.line, 1);
    }

    /// A misspelled condition variable must fail at parse time. Evaluating it
    /// as the empty string would silently skip the step.
    #[test]
    fn only_if_rejects_variables_outside_the_namespace() {
        let src = "pipeline { step d { command \"x\" only_if brunch == \"main\" } }";
        let err = parse(src).unwrap_err();
        assert!(err.message.contains("unknown only_if variable"), "{err}");
        for var in CONDITION_VARS {
            assert!(err.message.contains(var), "{err} should list '{var}'");
        }
    }

    /// Every documented condition variable parses, with both operators.
    #[test]
    fn only_if_accepts_the_whole_documented_namespace() {
        for var in CONDITION_VARS {
            for op in ["==", "!="] {
                let src =
                    format!("pipeline {{ step d {{ command \"x\" only_if {var} {op} \"v\" }} }}");
                let cfg = parse(&src).unwrap_or_else(|e| panic!("{var} {op}: {e}"));
                assert_eq!(cfg.steps[0].only_if.as_ref().unwrap().var, *var);
            }
        }
    }

    /// The top-level `runners`/`policy` items and the `inputs` step field are
    /// part of the documented grammar but were only exercised end-to-end; this
    /// pins them at the parser level.
    #[test]
    fn parses_runner_pools_policies_and_step_scoping() {
        let src = r#"
            runners {
                pool "gpu-builders" {
                    requirements { gpu true, memory "32gb" }
                }
                pool linux { os linux }
            }
            policy production {
                require tests
                require security
                require approvals 2
            }
            pipeline {
                use rust-library
                step build {
                    command "cargo build --release"
                    inputs [ "src/**", "Cargo.toml" ]
                }
            }
        "#;
        let cfg = parse(src).unwrap();
        assert_eq!(cfg.uses, vec!["rust-library"]);

        assert_eq!(cfg.runner_pools.len(), 2);
        let gpu = &cfg.runner_pools[0];
        assert_eq!(gpu.name, "gpu-builders");
        assert_eq!(gpu.gpu, Some(true));
        assert_eq!(gpu.memory.as_deref(), Some("32gb"));
        assert_eq!(cfg.runner_pools[1].os.as_deref(), Some("linux"));

        assert_eq!(cfg.policies.len(), 1);
        let policy = &cfg.policies[0];
        assert_eq!(policy.name, "production");
        assert!(policy.require_tests);
        assert!(policy.require_security);
        assert_eq!(policy.require_approvals, 2);

        let build = &cfg.steps[0];
        assert_eq!(build.inputs, vec!["src/**", "Cargo.toml"]);
    }

    /// All three spellings of a step timeout, and the round-trip back to source.
    #[test]
    fn parses_every_timeout_form() {
        let src = r#"
            pipeline {
                step seconds { command "x" timeout 90 }
                step minutes { command "x" timeout "10m" }
                step hours   { command "x" timeout "2h" }
                step unbound { command "x" timeout off }
                step inherit { command "x" }
            }
        "#;
        let cfg = parse(src).unwrap();
        let by = |name: &str| cfg.steps.iter().find(|s| s.name == name).unwrap().timeout;
        assert_eq!(by("seconds"), Some(Timeout::After(Duration::from_secs(90))));
        assert_eq!(
            by("minutes"),
            Some(Timeout::After(Duration::from_secs(600)))
        );
        assert_eq!(by("hours"), Some(Timeout::After(Duration::from_secs(7200))));
        assert_eq!(by("unbound"), Some(Timeout::Off));
        assert_eq!(by("inherit"), None, "an absent field must stay absent");

        // `flux format` writes these back, so the rendering has to re-parse.
        assert_eq!(by("seconds").unwrap().describe(), "\"90s\"");
        assert_eq!(by("minutes").unwrap().describe(), "\"10m\"");
        assert_eq!(by("hours").unwrap().describe(), "\"2h\"");
        assert_eq!(by("unbound").unwrap().describe(), "off");
    }

    /// A bare `10m` lexes as a number and an identifier. Reading it as ten
    /// seconds would be sixty times wrong and silent, so it is an error that
    /// spells out the fix.
    #[test]
    fn an_unquoted_duration_is_rejected_with_the_quoted_spelling() {
        let err = parse("pipeline { step a { command \"x\" timeout 10m } }").unwrap_err();
        assert!(err.message.contains("must be quoted"), "{err}");
        assert!(err.message.contains("timeout \"10m\""), "{err}");
    }

    #[test]
    fn rejects_meaningless_timeout_and_parallel_values() {
        for src in [
            "pipeline { step a { command \"x\" timeout 0 } }",
            "pipeline { step a { command \"x\" timeout \"0m\" } }",
        ] {
            let err = parse(src).unwrap_err();
            assert!(err.message.contains("timeout off"), "{err}");
        }

        let err = parse("pipeline { step a { command \"x\" timeout \"soon\" } }").unwrap_err();
        assert!(err.message.contains("invalid timeout"), "{err}");

        let err = parse("pipeline { parallel 0 step a { command \"x\" } }").unwrap_err();
        assert!(err.message.contains("at least 1"), "{err}");
    }

    #[test]
    fn parses_pipeline_execution_settings() {
        let src = r#"
            pipeline {
                timeout "5m"
                parallel 3
                step build { command "cargo build" }
            }
        "#;
        let cfg = parse(src).unwrap();
        assert_eq!(
            cfg.execution.timeout,
            Some(Timeout::After(Duration::from_secs(300)))
        );
        assert_eq!(cfg.execution.parallel, Some(3));
        assert_eq!(cfg.steps.len(), 1);

        // Nothing declared stays nothing declared, so the engine can tell the
        // difference between an author's choice and its own default.
        let bare = parse("pipeline { step build { command \"x\" } }").unwrap();
        assert_eq!(bare.execution, Default::default());
    }

    /// The pipeline block's own fields must not be mistaken for step names, and
    /// an unknown one should list what is allowed there.
    #[test]
    fn unknown_pipeline_field_lists_the_alternatives() {
        let err = parse("pipeline { workers 4 }").unwrap_err();
        for expected in ["step", "use", "timeout", "parallel"] {
            assert!(
                err.message.contains(expected),
                "{err} should list {expected}"
            );
        }
    }

    #[test]
    fn parses_environment_and_deployment() {
        let src = r#"
            environment { image "rust:latest" }
            deployment { target kubernetes replicas 3 }
            pipeline { step build { command "cargo build" } }
        "#;
        let cfg = parse(src).unwrap();
        assert_eq!(
            cfg.environment.unwrap().image.as_deref(),
            Some("rust:latest")
        );
        let dep = cfg.deployment.unwrap();
        assert_eq!(dep.target.as_deref(), Some("kubernetes"));
        assert_eq!(dep.replicas, Some(3));
    }
}