o7 0.1.1

O7 workflow DSL runner
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
//! O7 DSL Parser
//!
//! Consumes a flat token array (from the lexer, with INDENT/DEDENT already
//! injected) and produces an AST of WorkflowDecl nodes.
//! Uses a hand-written recursive descent approach matching the TS parser.

use std::collections::{HashMap, HashSet};

use crate::parser::ast::*;
use crate::parser::errors::ParseError;
use crate::parser::tokens::{Token, TokenType};

/// Whether a token type is a keyword (as opposed to NAME/NUMBER/STRING/etc.).
fn is_keyword_token(ty: &TokenType) -> bool {
    matches!(
        ty,
        TokenType::Version
            | TokenType::Workflow
            | TokenType::Run
            | TokenType::If
            | TokenType::Not
            | TokenType::While
            | TokenType::ParAnd
            | TokenType::Exec
            | TokenType::Harness
            | TokenType::Prompt
            | TokenType::PromptFile
            | TokenType::Args
            | TokenType::FailPolicy
            | TokenType::Match
            | TokenType::Else
    )
}

/// Parser state: wraps the token array and provides peek/advance/expect helpers.
struct Parser {
    tokens: Vec<Token>,
    pos: usize,
    filename: String,
    errors: Vec<ParseError>,
}

impl Parser {
    fn new(tokens: Vec<Token>, filename: &str) -> Self {
        Parser {
            tokens,
            pos: 0,
            filename: filename.to_string(),
            errors: Vec::new(),
        }
    }

    /// Look at the current token without consuming it.
    fn peek(&self) -> &Token {
        self.tokens
            .get(self.pos)
            .unwrap_or_else(|| self.eof_token())
    }

    /// Look ahead by n tokens.
    #[allow(dead_code)]
    fn peek_at(&self, n: usize) -> &Token {
        self.tokens
            .get(self.pos + n)
            .unwrap_or_else(|| self.eof_token())
    }

    /// Consume and return the current token, advancing position.
    fn advance(&mut self) -> Token {
        let tok = self
            .tokens
            .get(self.pos)
            .cloned()
            .unwrap_or_else(|| self.eof_token().clone());
        if self.pos < self.tokens.len() {
            self.pos += 1;
        }
        tok
    }

    /// Check if we're at end of file.
    fn is_at_end(&self) -> bool {
        self.peek().ty == TokenType::Eof
    }

    /// Check if current token is of the given type.
    fn check(&self, ty: &TokenType) -> bool {
        self.peek().ty == *ty
    }

    /// Consume the current token if it matches the given type. Return it or None.
    #[allow(dead_code)]
    fn match_token(&mut self, ty: &TokenType) -> Option<Token> {
        if self.check(ty) {
            Some(self.advance())
        } else {
            None
        }
    }

    /// Consume a token of the expected type, or record an error.
    fn expect(&mut self, ty: &TokenType, error_msg: &str) -> Option<Token> {
        if self.check(ty) {
            Some(self.advance())
        } else {
            let tok = self.peek().clone();
            self.add_error(&tok, error_msg);
            None
        }
    }

    /// Skip NEWLINE tokens.
    fn skip_newlines(&mut self) {
        while self.check(&TokenType::Newline) {
            self.advance();
        }
    }

    /// Consume a single trailing newline if present.
    fn consume_newline(&mut self) {
        if self.check(&TokenType::Newline) {
            self.advance();
        }
    }

    /// Record an error at a given token's location.
    fn add_error(&mut self, at: &Token, message: impl Into<String>) {
        self.errors
            .push(ParseError::new(&self.filename, at.line, at.column, message));
    }

    /// Get a reference to the EOF token (for safety when past end).
    fn eof_token(&self) -> &Token {
        // Try to return the last token if it's an EOF
        if let Some(last) = self.tokens.last() {
            if last.ty == TokenType::Eof {
                return last;
            }
        }
        // Fallback: this should never be reached if the lexer always emits EOF
        // but we need to return a reference, so use a static.
        static FALLBACK_EOF: Token = Token {
            ty: TokenType::Eof,
            value: String::new(),
            line: 1,
            column: 1,
        };
        &FALLBACK_EOF
    }

    /// Try to consume a NAME token. Returns the value, or None if not a name.
    /// Reports an error if the next token is a keyword (reserved word used as name).
    fn expect_name(&mut self, context: &str) -> Option<String> {
        let tok = self.peek().clone();
        if tok.ty == TokenType::Name {
            self.advance();
            return Some(tok.value);
        }
        if is_keyword_token(&tok.ty) {
            self.add_error(
                &tok,
                format!(
                    "reserved keyword \"{}\" cannot be used as {}",
                    tok.value, context
                ),
            );
            return None;
        }
        self.add_error(&tok, format!("expected name for {}", context));
        None
    }
}

/// Parse a token stream into an AST.
pub fn parse(tokens: Vec<Token>, filename: &str) -> ParseResult {
    let mut p = Parser::new(tokens, filename);

    // Skip leading newlines
    p.skip_newlines();

    // Version header validation
    if !parse_version_header(&mut p) {
        return ParseResult::Err { errors: p.errors };
    }

    // Parse top-level declarations (workflows)
    let mut workflows = Vec::new();

    p.skip_newlines();

    while !p.is_at_end() {
        let tok = p.peek().clone();

        match tok.ty {
            TokenType::Workflow => {
                if let Some(wf) = parse_workflow(&mut p) {
                    workflows.push(wf);
                } else {
                    // Skip to next newline to try to recover
                    skip_to_newline(&mut p);
                }
            }
            TokenType::Newline => {
                p.advance();
            }
            TokenType::Dedent => {
                // Stray dedent at top level — just consume
                p.advance();
            }
            _ => {
                p.add_error(
                    &tok,
                    format!("unexpected token \"{}\" at top level", tok.value),
                );
                skip_to_newline(&mut p);
            }
        }
    }

    if !p.errors.is_empty() {
        return ParseResult::Err { errors: p.errors };
    }

    ParseResult::Ok { workflows }
}

/// Parse and validate the version header.
/// Expected: VERSION NUMBER NEWLINE
fn parse_version_header(p: &mut Parser) -> bool {
    let tok = p.peek().clone();

    if tok.ty != TokenType::Version {
        p.add_error(&tok, "missing version header");
        return false;
    }

    p.advance(); // consume VERSION

    let num_tok = p.peek().clone();
    if num_tok.ty != TokenType::Number {
        p.add_error(&num_tok, "expected version number after 'version'");
        return false;
    }
    p.advance(); // consume NUMBER

    if num_tok.value != "1" {
        p.add_error(&num_tok, format!("unrecognized version: {}", num_tok.value));
        return false;
    }

    // Consume newline after version
    p.consume_newline();

    true
}

/// Parse a workflow declaration.
/// Expected: WORKFLOW NAME NEWLINE [INDENT body DEDENT]
fn parse_workflow(p: &mut Parser) -> Option<WorkflowDecl> {
    let kw_tok = p.advance(); // consume WORKFLOW
    let line = kw_tok.line;
    let column = kw_tok.column;

    let name = p.expect_name("workflow name")?;

    // Consume trailing newline
    p.consume_newline();

    // Parse body block (if any)
    let body = parse_block(p);

    Some(WorkflowDecl {
        name,
        body,
        file: p.filename.clone(),
        line,
        column,
    })
}

/// Parse a block: an INDENT, then statements, then DEDENT.
/// Returns the list of statements in the block (empty if no INDENT follows).
fn parse_block(p: &mut Parser) -> Vec<Statement> {
    if !p.check(&TokenType::Indent) {
        return Vec::new();
    }
    p.advance(); // consume INDENT

    let mut statements = Vec::new();

    while !p.is_at_end() && !p.check(&TokenType::Dedent) {
        if p.check(&TokenType::Newline) {
            p.advance();
            continue;
        }

        if let Some(stmt) = parse_statement(p) {
            statements.push(stmt);
        } else {
            // Error recovery: skip to next newline
            skip_to_newline(p);
        }
    }

    if p.check(&TokenType::Dedent) {
        p.advance(); // consume DEDENT
    }

    statements
}

/// Parse a single statement within a block.
fn parse_statement(p: &mut Parser) -> Option<Statement> {
    let tok = p.peek().clone();

    match tok.ty {
        TokenType::Run => parse_run(p).map(Statement::Run),
        TokenType::If => parse_if(p),
        TokenType::While => parse_while(p),
        TokenType::ParAnd => parse_par_and(p).map(Statement::ParAnd),
        TokenType::Exec => parse_exec(p).map(Statement::Exec),
        TokenType::Match => parse_match(p).map(Statement::Match),
        _ => {
            p.add_error(&tok, format!("unexpected token \"{}\" in block", tok.value));
            None
        }
    }
}

/// Parse a run statement.
/// Expected: RUN NAME NEWLINE
fn parse_run(p: &mut Parser) -> Option<RunStatement> {
    let kw_tok = p.advance(); // consume RUN
    let line = kw_tok.line;
    let column = kw_tok.column;

    let name = p.expect_name("run target")?;

    // Consume trailing newline
    p.consume_newline();

    Some(RunStatement {
        workflow_name: name,
        line,
        column,
    })
}

/// Parse a conditional statement (if/if-not or while/while-not).
/// Expected: KEYWORD [NOT] NAME NEWLINE INDENT body DEDENT
fn parse_conditional(
    p: &mut Parser,
    keyword_label: &str,
    make_pos: fn(String, Vec<Statement>, usize, usize) -> Statement,
    make_neg: fn(String, Vec<Statement>, usize, usize) -> Statement,
) -> Option<Statement> {
    let kw_tok = p.advance(); // consume keyword
    let line = kw_tok.line;
    let column = kw_tok.column;

    // Check for "not"
    let is_not = p.check(&TokenType::Not);
    if is_not {
        p.advance(); // consume NOT
    }

    let context = if is_not {
        format!("{} not check name", keyword_label)
    } else {
        format!("{} check name", keyword_label)
    };
    let check_name = p.expect_name(&context)?;

    p.consume_newline();

    let body = parse_block(p);

    if is_not {
        Some(make_neg(check_name, body, line, column))
    } else {
        Some(make_pos(check_name, body, line, column))
    }
}

/// Parse an if or if-not statement.
fn parse_if(p: &mut Parser) -> Option<Statement> {
    parse_conditional(
        p,
        "if",
        |name, body, line, col| {
            Statement::If(IfStatement {
                check_name: name,
                body,
                line,
                column: col,
            })
        },
        |name, body, line, col| {
            Statement::IfNot(IfNotStatement {
                check_name: name,
                body,
                line,
                column: col,
            })
        },
    )
}

/// Parse a while or while-not statement.
fn parse_while(p: &mut Parser) -> Option<Statement> {
    parse_conditional(
        p,
        "while",
        |name, body, line, col| {
            Statement::While(WhileStatement {
                check_name: name,
                body,
                line,
                column: col,
            })
        },
        |name, body, line, col| {
            Statement::WhileNot(WhileNotStatement {
                check_name: name,
                body,
                line,
                column: col,
            })
        },
    )
}

/// Parse a par-and statement.
/// Expected: PAR_AND NAME [FAIL_POLICY COLON NAME] NEWLINE INDENT run-children DEDENT
fn parse_par_and(p: &mut Parser) -> Option<ParAndStatement> {
    let kw_tok = p.advance(); // consume PAR_AND
    let line = kw_tok.line;
    let column = kw_tok.column;

    let join_name = p.expect_name("par-and join workflow name")?;

    let mut fail_policy: Option<FailPolicy> = None;

    // Check for fail-policy on the same line
    if p.check(&TokenType::FailPolicy) {
        p.advance(); // consume FAIL_POLICY

        if p.expect(&TokenType::Colon, "expected ':' after fail-policy")
            .is_none()
        {
            return None;
        }

        let policy_tok = p.peek().clone();
        if policy_tok.ty != TokenType::Name {
            p.add_error(
                &policy_tok,
                "expected fail policy value after 'fail-policy:'",
            );
            return None;
        }
        p.advance();

        match policy_tok.value.as_str() {
            "fail-fast" => fail_policy = Some(FailPolicy::FailFast),
            "wait-then-fail" => fail_policy = Some(FailPolicy::WaitThenFail),
            _ => {
                p.add_error(
                    &policy_tok,
                    format!(
                        "invalid fail policy \"{}\"; expected \"fail-fast\" or \"wait-then-fail\"",
                        policy_tok.value
                    ),
                );
                return None;
            }
        }
    }

    // Consume trailing newline
    p.consume_newline();

    // Parse block — only run statements allowed
    let mut branches: Vec<RunStatement> = Vec::new();

    if p.check(&TokenType::Indent) {
        p.advance(); // consume INDENT

        while !p.is_at_end() && !p.check(&TokenType::Dedent) {
            if p.check(&TokenType::Newline) {
                p.advance();
                continue;
            }

            let tok = p.peek().clone();
            if tok.ty != TokenType::Run {
                p.add_error(
                    &tok,
                    format!(
                        "only \"run\" statements are allowed inside par-and, got \"{}\"",
                        tok.value
                    ),
                );
                skip_to_newline(p);
                continue;
            }

            if let Some(run_stmt) = parse_run(p) {
                branches.push(run_stmt);
            } else {
                skip_to_newline(p);
            }
        }

        if p.check(&TokenType::Dedent) {
            p.advance();
        }
    }

    Some(ParAndStatement {
        join_workflow_name: join_name,
        branches,
        fail_policy,
        line,
        column,
    })
}

/// Parse a field value in an exec block (harness, prompt, prompt_file).
/// Consumes: keyword, colon, and value token. Returns the value string on success.
/// On failure, records error and skips to newline.
fn parse_field_value(p: &mut Parser, field_name: &str) -> Option<String> {
    p.advance(); // consume field keyword
    if p.expect(
        &TokenType::Colon,
        &format!("expected ':' after {}", field_name),
    )
    .is_none()
    {
        skip_to_newline(p);
        return None;
    }
    let val_tok = p.peek().clone();
    if matches!(
        val_tok.ty,
        TokenType::Name | TokenType::Str | TokenType::BareValue
    ) {
        p.advance();
        Some(val_tok.value)
    } else {
        p.add_error(&val_tok, format!("expected value after '{}:'", field_name));
        skip_to_newline(p);
        None
    }
}

/// Parse an exec block.
/// Expected: EXEC NEWLINE INDENT field-lines DEDENT
///
/// Fields:
///   harness: <name>          (required)
///   prompt: <string>         (one of prompt/prompt_file required)
///   prompt_file: <name>      (one of prompt/prompt_file required)
///   args:                    (optional, opens nested block)
///     key: value
fn parse_exec(p: &mut Parser) -> Option<ExecBlock> {
    let kw_tok = p.advance(); // consume EXEC
    let line = kw_tok.line;
    let column = kw_tok.column;

    // Consume trailing newline
    p.consume_newline();

    let mut harness: Option<String> = None;
    let mut prompt: Option<String> = None;
    let mut prompt_file: Option<String> = None;
    let mut args: Option<HashMap<String, String>> = None;

    // Parse block of fields
    if !p.check(&TokenType::Indent) {
        let tok = p.peek().clone();
        p.add_error(&tok, "expected indented block after exec");
        return None;
    }
    p.advance(); // consume INDENT

    while !p.is_at_end() && !p.check(&TokenType::Dedent) {
        if p.check(&TokenType::Newline) {
            p.advance();
            continue;
        }

        let field_tok = p.peek().clone();

        match field_tok.ty {
            TokenType::Harness => {
                if let Some(val) = parse_field_value(p, "harness") {
                    harness = Some(val);
                } else {
                    continue;
                }
            }
            TokenType::PromptFile => {
                if let Some(val) = parse_field_value(p, "prompt_file") {
                    prompt_file = Some(val);
                } else {
                    continue;
                }
            }
            TokenType::Prompt => {
                if let Some(val) = parse_field_value(p, "prompt") {
                    prompt = Some(val);
                } else {
                    continue;
                }
            }
            TokenType::Args => {
                p.advance(); // consume ARGS
                if p.expect(&TokenType::Colon, "expected ':' after args")
                    .is_none()
                {
                    skip_to_newline(p);
                    continue;
                }
                // Check for inline value after args: (not allowed)
                if !p.check(&TokenType::Newline)
                    && !p.check(&TokenType::Indent)
                    && !p.check(&TokenType::Eof)
                    && !p.check(&TokenType::Dedent)
                {
                    let tok = p.peek().clone();
                    p.add_error(&tok, "args must be a nested block, not an inline value");
                    skip_to_newline(p);
                    continue;
                }
                // Consume newline before nested block
                p.consume_newline();
                args = Some(parse_args_block(p));
            }
            _ => {
                p.add_error(
                    &field_tok,
                    format!("unknown exec field \"{}\"", field_tok.value),
                );
                skip_to_newline(p);
                continue;
            }
        }

        // Consume trailing newline after field
        p.consume_newline();
    }

    if p.check(&TokenType::Dedent) {
        p.advance(); // consume DEDENT
    }

    // Validate required fields
    if harness.is_none() {
        p.add_error(&kw_tok, "exec block is missing required field 'harness'");
        return None;
    }

    if prompt.is_some() && prompt_file.is_some() {
        p.add_error(
            &kw_tok,
            "exec block has both 'prompt' and 'prompt_file'; only one is allowed",
        );
        return None;
    }

    if prompt.is_none() && prompt_file.is_none() {
        p.add_error(
            &kw_tok,
            "exec block must have either 'prompt' or 'prompt_file'",
        );
        return None;
    }

    Some(ExecBlock {
        harness: harness.unwrap(),
        prompt,
        prompt_file,
        args,
        line,
        column,
    })
}

/// Parse a nested args block (key: value pairs).
/// Expected: INDENT (NAME COLON value NEWLINE)* DEDENT
fn parse_args_block(p: &mut Parser) -> HashMap<String, String> {
    let mut result = HashMap::new();

    if !p.check(&TokenType::Indent) {
        return result;
    }
    p.advance(); // consume INDENT

    while !p.is_at_end() && !p.check(&TokenType::Dedent) {
        if p.check(&TokenType::Newline) {
            p.advance();
            continue;
        }

        let key_tok = p.peek().clone();
        if key_tok.ty != TokenType::Name {
            p.add_error(
                &key_tok,
                format!("expected argument name, got \"{}\"", key_tok.value),
            );
            skip_to_newline(p);
            continue;
        }
        p.advance(); // consume NAME

        if p.expect(
            &TokenType::Colon,
            &format!("expected ':' after argument name \"{}\"", key_tok.value),
        )
        .is_none()
        {
            skip_to_newline(p);
            continue;
        }

        let val_tok = p.peek().clone();
        if val_tok.ty == TokenType::Name
            || val_tok.ty == TokenType::Str
            || val_tok.ty == TokenType::Number
            || val_tok.ty == TokenType::BareValue
        {
            result.insert(key_tok.value, val_tok.value);
            p.advance();
        } else {
            p.add_error(
                &val_tok,
                format!("expected value for argument \"{}\"", key_tok.value),
            );
            skip_to_newline(p);
            continue;
        }

        // Consume trailing newline
        p.consume_newline();
    }

    if p.check(&TokenType::Dedent) {
        p.advance(); // consume DEDENT
    }

    result
}

/// Parse a match statement.
/// Expected: MATCH NAME NEWLINE INDENT match_arm+ DEDENT
/// match_arm: (NAME | ELSE) ARROW (run_statement NEWLINE | NEWLINE INDENT statement+ DEDENT)
fn parse_match(p: &mut Parser) -> Option<MatchStatement> {
    let kw_tok = p.advance(); // consume MATCH
    let line = kw_tok.line;
    let column = kw_tok.column;

    let check_name = p.expect_name("match check name")?;

    p.consume_newline();

    // Expect indented block of arms
    if !p.check(&TokenType::Indent) {
        let tok = p.peek().clone();
        p.add_error(&tok, "expected indented block of arms after match");
        return None;
    }
    p.advance(); // consume INDENT

    let mut arms: Vec<MatchArm> = Vec::new();
    let mut else_body: Option<Vec<Statement>> = None;
    let mut else_line: Option<usize> = None;
    let mut else_column: Option<usize> = None;
    let mut seen_variants: HashSet<String> = HashSet::new();
    let mut seen_else = false;

    while !p.is_at_end() && !p.check(&TokenType::Dedent) {
        if p.check(&TokenType::Newline) {
            p.advance();
            continue;
        }

        let arm_tok = p.peek().clone();
        let is_else;
        let variant_name: String;

        if arm_tok.ty == TokenType::Else {
            is_else = true;
            variant_name = "else".to_string();
            p.advance(); // consume ELSE
        } else if arm_tok.ty == TokenType::Name {
            is_else = false;
            variant_name = arm_tok.value.clone();
            p.advance(); // consume NAME
        } else if is_keyword_token(&arm_tok.ty) {
            p.add_error(
                &arm_tok,
                format!(
                    "reserved keyword \"{}\" cannot be used as a variant name",
                    arm_tok.value
                ),
            );
            skip_to_newline(p);
            continue;
        } else {
            p.add_error(&arm_tok, "expected variant name or 'else'");
            skip_to_newline(p);
            continue;
        }

        // Check for arm after else
        if seen_else {
            p.add_error(
                &arm_tok,
                "'else' arm must be the last arm in a match statement",
            );
            skip_to_newline(p);
            continue;
        }

        // Check for duplicate variant names
        if !is_else && seen_variants.contains(&variant_name) {
            p.add_error(
                &arm_tok,
                format!("duplicate variant \"{}\" in match arms", variant_name),
            );
            skip_to_newline(p);
            continue;
        }

        // Consume ARROW
        if p.expect(&TokenType::Arrow, "expected '->' after variant name")
            .is_none()
        {
            skip_to_newline(p);
            continue;
        }

        // Determine single-line vs multi-line arm
        let body: Vec<Statement>;
        if p.check(&TokenType::Newline) {
            // Multi-line arm
            p.consume_newline();
            body = parse_block(p);
        } else if p.check(&TokenType::Run) {
            // Single-line arm: RUN NAME
            if let Some(run_stmt) = parse_run(p) {
                body = vec![Statement::Run(run_stmt)];
            } else {
                skip_to_newline(p);
                continue;
            }
        } else {
            let tok = p.peek().clone();
            p.add_error(
                &tok,
                "expected 'run' statement or indented block after '->'",
            );
            skip_to_newline(p);
            continue;
        }

        if is_else {
            seen_else = true;
            else_body = Some(body);
            else_line = Some(arm_tok.line);
            else_column = Some(arm_tok.column);
        } else {
            seen_variants.insert(variant_name.clone());
            arms.push(MatchArm {
                variant: variant_name,
                body,
                line: arm_tok.line,
                column: arm_tok.column,
            });
        }
    }

    if p.check(&TokenType::Dedent) {
        p.advance(); // consume DEDENT
    }

    // Must have at least one arm (variant or else)
    if arms.is_empty() && else_body.is_none() {
        p.add_error(&kw_tok, "match statement must have at least one arm");
        return None;
    }

    Some(MatchStatement {
        check_name,
        arms,
        else_body,
        else_line,
        else_column,
        line,
        column,
    })
}

/// Skip tokens until the next NEWLINE or EOF (error recovery).
fn skip_to_newline(p: &mut Parser) {
    while !p.is_at_end() && !p.check(&TokenType::Newline) && !p.check(&TokenType::Dedent) {
        p.advance();
    }
    p.consume_newline();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::lexer::lex;

    fn parse_source(source: &str) -> ParseResult {
        let lex_result = lex(source, "test.7");
        assert!(
            lex_result.errors.is_empty(),
            "Lex errors: {:?}",
            lex_result.errors
        );
        parse(lex_result.tokens, "test.7")
    }

    /// Parse source and assert success, returning workflow list.
    fn parse_ok(source: &str) -> Vec<WorkflowDecl> {
        let result = parse_source(source);
        assert!(result.is_ok(), "errors: {:?}", result.errors());
        result.workflows().unwrap().clone()
    }

    /// Find a workflow by name in a list.
    fn find_wf<'a>(wfs: &'a [WorkflowDecl], name: &str) -> &'a WorkflowDecl {
        wfs.iter()
            .find(|w| w.name == name)
            .unwrap_or_else(|| panic!("workflow \"{}\" not found", name))
    }

    #[test]
    fn test_parse_minimal_workflow() {
        let wfs = parse_ok("version 1\n\nworkflow main\n  run greet\n");
        assert_eq!(wfs.len(), 1);
        assert_eq!(wfs[0].name, "main");
        assert_eq!(wfs[0].body.len(), 1);
    }

    #[test]
    fn test_parse_missing_version() {
        let result = parse_source("workflow main\n  run greet\n");
        assert!(!result.is_ok());
        assert!(result.errors().unwrap()[0].message.contains("version"));
    }

    #[test]
    fn test_parse_wrong_version() {
        let result = parse_source("version 2\n\nworkflow main\n");
        assert!(!result.is_ok());
        assert!(
            result.errors().unwrap()[0]
                .message
                .contains("unrecognized version")
        );
    }

    #[test]
    fn test_parse_if_not() {
        parse_ok(
            "version 1\nworkflow check\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  if not check\n    run check\n",
        );
    }

    #[test]
    fn test_parse_par_and() {
        let wfs = parse_ok(
            "version 1\nworkflow a\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow b\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow join\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  par-and join\n    run a\n    run b\n",
        );
        let main_wf = find_wf(&wfs, "main");
        assert_eq!(main_wf.body.len(), 1);
        match &main_wf.body[0] {
            Statement::ParAnd(p) => {
                assert_eq!(p.join_workflow_name, "join");
                assert_eq!(p.branches.len(), 2);
            }
            _ => panic!("Expected par-and statement"),
        }
    }

    #[test]
    fn test_parse_exec_with_args() {
        let wfs = parse_ok(
            "version 1\nworkflow main\n  exec\n    harness: claude\n    prompt_file: prompts/foo.md\n    args:\n      mode: implement\n      model: sonnet\n",
        );
        match &wfs[0].body[0] {
            Statement::Exec(e) => {
                assert_eq!(e.harness, "claude");
                assert_eq!(e.prompt_file.as_deref(), Some("prompts/foo.md"));
                let args = e.args.as_ref().unwrap();
                assert_eq!(args.get("mode").unwrap(), "implement");
                assert_eq!(args.get("model").unwrap(), "sonnet");
            }
            _ => panic!("Expected exec statement"),
        }
    }

    #[test]
    fn test_parse_exec_both_prompt_error() {
        let result = parse_source(
            "version 1\nworkflow main\n  exec\n    harness: h\n    prompt: \"x\"\n    prompt_file: foo\n",
        );
        assert!(!result.is_ok());
        assert!(result.errors().unwrap()[0].message.contains("both"));
    }

    #[test]
    fn test_parse_exec_neither_prompt_error() {
        let result = parse_source("version 1\nworkflow main\n  exec\n    harness: h\n");
        assert!(!result.is_ok());
        assert!(
            result.errors().unwrap()[0]
                .message
                .contains("must have either")
        );
    }

    #[test]
    fn test_parse_par_and_non_run_child() {
        let result = parse_source(
            "version 1\nworkflow a\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  par-and a\n    exec\n      harness: h\n      prompt: \"x\"\n",
        );
        assert!(!result.is_ok());
        assert!(result.errors().unwrap()[0].message.contains("only \"run\""));
    }

    #[test]
    fn test_parse_reserved_keyword_as_name() {
        let result =
            parse_source("version 1\nworkflow run\n  exec\n    harness: h\n    prompt: \"x\"\n");
        assert!(!result.is_ok());
        assert!(
            result.errors().unwrap()[0]
                .message
                .contains("reserved keyword")
        );
    }

    #[test]
    fn test_parse_empty_workflow() {
        let wfs = parse_ok("version 1\nworkflow empty\n");
        assert_eq!(wfs.len(), 1);
        assert_eq!(wfs[0].name, "empty");
        assert!(wfs[0].body.is_empty());
    }

    #[test]
    fn test_parse_multiple_workflows() {
        let wfs = parse_ok(
            "version 1\nworkflow a\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow b\n  exec\n    harness: h\n    prompt: \"y\"\n",
        );
        assert_eq!(wfs.len(), 2);
        assert_eq!(wfs[0].name, "a");
        assert_eq!(wfs[1].name, "b");
    }

    #[test]
    fn test_parse_while_loop() {
        let wfs = parse_ok(
            "version 1\nworkflow check\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  while check\n    run check\n",
        );
        match &find_wf(&wfs, "main").body[0] {
            Statement::While(w) => {
                assert_eq!(w.check_name, "check");
                assert_eq!(w.body.len(), 1);
            }
            _ => panic!("Expected while statement"),
        }
    }

    #[test]
    fn test_parse_while_not_loop() {
        let wfs = parse_ok(
            "version 1\nworkflow done\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  while not done\n    run done\n",
        );
        match &find_wf(&wfs, "main").body[0] {
            Statement::WhileNot(w) => {
                assert_eq!(w.check_name, "done");
            }
            _ => panic!("Expected while-not statement"),
        }
    }

    #[test]
    fn test_parse_if_statement() {
        let wfs = parse_ok(
            "version 1\nworkflow check\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  if check\n    run check\n",
        );
        match &find_wf(&wfs, "main").body[0] {
            Statement::If(i) => {
                assert_eq!(i.check_name, "check");
                assert_eq!(i.body.len(), 1);
            }
            _ => panic!("Expected if statement"),
        }
    }

    #[test]
    fn test_parse_exec_with_prompt_string() {
        let wfs = parse_ok(
            "version 1\nworkflow main\n  exec\n    harness: claude\n    prompt: \"hello world\"\n",
        );
        match &wfs[0].body[0] {
            Statement::Exec(e) => {
                assert_eq!(e.harness, "claude");
                assert_eq!(e.prompt.as_deref(), Some("hello world"));
                assert!(e.prompt_file.is_none());
            }
            _ => panic!("Expected exec statement"),
        }
    }

    #[test]
    fn test_parse_par_and_with_fail_policy() {
        let wfs = parse_ok(
            "version 1\nworkflow a\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow join\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  par-and join fail-policy: fail-fast\n    run a\n",
        );
        match &find_wf(&wfs, "main").body[0] {
            Statement::ParAnd(pa) => {
                assert_eq!(pa.fail_policy, Some(FailPolicy::FailFast));
            }
            _ => panic!("Expected par-and statement"),
        }
    }

    #[test]
    fn test_parse_unexpected_token_at_top_level() {
        let result = parse_source("version 1\nrun greet\n");
        assert!(!result.is_ok());
        assert!(
            result.errors().unwrap()[0]
                .message
                .contains("unexpected token")
        );
    }

    #[test]
    fn test_parse_unexpected_token_in_block() {
        let result = parse_source("version 1\nworkflow main\n  version 1\n");
        assert!(!result.is_ok());
        assert!(
            result.errors().unwrap()[0]
                .message
                .contains("unexpected token")
        );
    }

    #[test]
    fn test_parse_namespaced_workflow() {
        let wfs = parse_ok(
            "version 1\nworkflow reviews::security\n  exec\n    harness: h\n    prompt: \"x\"\n",
        );
        assert_eq!(wfs[0].name, "reviews::security");
    }

    #[test]
    fn test_parse_exec_missing_harness() {
        let result = parse_source("version 1\nworkflow main\n  exec\n    prompt: \"x\"\n");
        assert!(!result.is_ok());
        assert!(result.errors().unwrap()[0].message.contains("harness"));
    }

    #[test]
    fn test_parse_workflow_line_column() {
        let wfs = parse_ok("version 1\nworkflow main\n  run greet\n");
        assert_eq!(wfs[0].line, 2);
        assert_eq!(wfs[0].column, 1);
    }

    #[test]
    fn test_parse_run_statement_line_column() {
        let wfs = parse_ok("version 1\nworkflow main\n  run greet\n");
        match &wfs[0].body[0] {
            Statement::Run(r) => {
                assert_eq!(r.line, 3);
                assert_eq!(r.column, 3);
            }
            _ => panic!("Expected run statement"),
        }
    }

    #[test]
    fn test_parse_match_basic() {
        let wfs = parse_ok(
            "version 1\nworkflow check\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  match check\n    small -> run check\n    large -> run check\n",
        );
        let main_wf = find_wf(&wfs, "main");
        match &main_wf.body[0] {
            Statement::Match(m) => {
                assert_eq!(m.check_name, "check");
                assert_eq!(m.arms.len(), 2);
                assert_eq!(m.arms[0].variant, "small");
                assert_eq!(m.arms[1].variant, "large");
                assert!(m.else_body.is_none());
            }
            _ => panic!("Expected match statement"),
        }
    }

    #[test]
    fn test_parse_match_with_else() {
        let wfs = parse_ok(
            "version 1\nworkflow check\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  match check\n    small -> run check\n    else -> run check\n",
        );
        match &find_wf(&wfs, "main").body[0] {
            Statement::Match(m) => {
                assert_eq!(m.arms.len(), 1);
                assert_eq!(m.arms[0].variant, "small");
                assert!(m.else_body.is_some());
                assert_eq!(m.else_body.as_ref().unwrap().len(), 1);
            }
            _ => panic!("Expected match statement"),
        }
    }

    #[test]
    fn test_parse_match_multi_statement_arm() {
        let wfs = parse_ok(
            "version 1\nworkflow a\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  match a\n    big ->\n      run a\n      run a\n    small -> run a\n",
        );
        match &find_wf(&wfs, "main").body[0] {
            Statement::Match(m) => {
                assert_eq!(m.arms[0].variant, "big");
                assert_eq!(m.arms[0].body.len(), 2);
                assert_eq!(m.arms[1].variant, "small");
                assert_eq!(m.arms[1].body.len(), 1);
            }
            _ => panic!("Expected match statement"),
        }
    }

    #[test]
    fn test_parse_match_duplicate_variant_error() {
        let result = parse_source(
            "version 1\nworkflow main\n  match check\n    small -> run check\n    small -> run check\n",
        );
        assert!(!result.is_ok());
        assert!(result.errors().unwrap()[0].message.contains("duplicate"));
    }

    #[test]
    fn test_parse_match_else_not_last_error() {
        let result = parse_source(
            "version 1\nworkflow main\n  match check\n    else -> run check\n    small -> run check\n",
        );
        assert!(!result.is_ok());
        assert!(result.errors().unwrap()[0].message.contains("else"));
    }

    #[test]
    fn test_parse_match_keyword_variant_error() {
        let result =
            parse_source("version 1\nworkflow main\n  match check\n    run -> run check\n");
        assert!(!result.is_ok());
        assert!(
            result.errors().unwrap()[0]
                .message
                .contains("reserved keyword")
        );
    }

    #[test]
    fn test_parse_match_empty_arms_error() {
        // A match with no arms at all should be a parse error
        let result = parse_source("version 1\nworkflow main\n  match check\n");
        assert!(
            !result.is_ok(),
            "expected error for empty match, but got ok"
        );
        let errors = result.errors().unwrap();
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("at least one arm") || e.message.contains("arm")),
            "expected 'at least one arm' error, got: {:?}",
            errors
        );
    }

    #[test]
    fn test_parse_match_serialization_elseBody_absent_when_no_else() {
        use crate::parser::lexer::lex;
        let source = "version 1\nworkflow check\n  exec\n    harness: h\n    prompt: \"x\"\nworkflow main\n  match check\n    small -> run check\n";
        let lex_result = lex(source, "test.7");
        let parse_result = parse(lex_result.tokens, "test.7");
        let wfs = parse_result.workflows().unwrap();
        let stmt = &wfs.iter().find(|w| w.name == "main").unwrap().body[0];
        let json = serde_json::to_string(stmt).unwrap();
        assert!(
            json.contains("\"kind\":\"match\""),
            "missing kind: {}",
            json
        );
        assert!(
            json.contains("\"checkName\":\"check\""),
            "missing checkName: {}",
            json
        );
        assert!(
            !json.contains("elseBody"),
            "elseBody should be absent: {}",
            json
        );
    }
}