zebflow 0.6.1

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
//! Pure parser for the Pipeline DSL command language.
//!
//! `DslFlag.config_key` is the single source of truth for flag→config mapping.
//! Every flag used in DSL must be declared in the node's `dsl_flags`. Undeclared
//! flags are a parse error — no auto-rule, no fallback.

use std::collections::HashMap;

use serde_json::{Value, json};

use crate::pipeline::model::{DslFlag, DslFlagKind, PipelineEdge, PipelineGraph, PipelineNode};
use crate::pipeline::nodes::builtin_node_definitions;

/// Parsed DSL command verb ready for execution.
#[derive(Debug, Clone)]
pub enum DslVerb {
    /// `get <resource> [--path <p>] [--status <s>] [--filter <f>]`
    Get {
        resource: String,
        path: Option<String>,
        filter: Option<String>,
        status: Option<String>,
    },
    /// `describe <kind> <name> [--compact]`
    Describe {
        kind: String,
        name: String,
        compact: bool,
    },
    /// `read <kind> <name>`
    Read { kind: String, name: String },
    /// `write <kind> <name> [body after --]`
    Write {
        kind: String,
        name: String,
        body: Option<String>,
    },
    /// `delete <kind> <name>`
    Delete { kind: String, name: String },
    /// `activate pipeline <file_rel_path>`
    Activate { file_rel_path: String },
    /// `deactivate pipeline <file_rel_path>`
    Deactivate { file_rel_path: String },
    /// `execute pipeline <file_rel_path> [--input <json>]`
    Execute { file_rel_path: String, input: Value },
    /// `register <file_rel_path> [--title <t>] [--description <d>] [--as-json] [| ...]`
    Register {
        file_rel_path: String,
        title: String,
        description: String,
        as_json: bool,
        body: String,
    },
    /// `patch pipeline <file_rel_path> node <id> [flags...]`
    Patch {
        file_rel_path: String,
        node_id: String,
        flags: HashMap<String, Value>,
        body: Option<String>,
    },
    /// `run [--dry-run] [| ...]`
    Run { body: String, dry_run: bool },
    /// `git <subcommand> [args...] [-- <body>]`
    Git {
        subcommand: String,
        args: Vec<String>,
        body: Option<String>,
    },
    /// `node help <kind>`
    NodeHelp { kind: String },
    /// Credential write blocked
    CredentialBlocked { reason: String },
    /// Unknown verb
    Unknown { raw: String },
}

/// Tokenize a DSL string respecting single and double quoted strings.
pub fn tokenize(s: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut in_single = false;
    let mut in_double = false;

    for ch in s.chars() {
        match ch {
            '\'' if !in_double => {
                in_single = !in_single;
            }
            '"' if !in_single => {
                in_double = !in_double;
            }
            ' ' | '\t' | '\n' | '\r' if !in_single && !in_double => {
                if !current.is_empty() {
                    tokens.push(current.clone());
                    current.clear();
                }
            }
            _ => {
                current.push(ch);
            }
        }
    }
    if !current.is_empty() {
        tokens.push(current);
    }
    tokens
}

/// Split DSL string into individual commands.
/// Joins `\` line continuations and splits on `&&`.
pub fn split_commands(dsl: &str) -> Vec<String> {
    let joined = dsl.replace("\\\r\n", "\n").replace("\\\n", "\n");
    joined
        .split("&&")
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

/// Expand short node kind alias to full qualified kind.
pub fn expand_kind(short: &str) -> Option<&'static str> {
    match short {
        "trigger.webhook" | "n.trigger.webhook" => Some("n.trigger.webhook"),
        "trigger.schedule" | "n.trigger.schedule" => Some("n.trigger.schedule"),
        "trigger.manual" | "n.trigger.manual" => Some("n.trigger.manual"),
        "pg.query" | "n.pg.query" => Some("n.pg.query"),
        "sekejap.query" | "n.sekejap.query" => Some("n.sekejap.query"),
        "table.convert" | "n.table.convert" => Some("n.table.convert"),
        "table.query" | "n.table.query" => Some("n.table.query"),
        "script" | "n.script" => Some("n.script"),
        "web.response" | "n.web.response" => Some("n.web.response"),
        "web.static.generate" | "n.web.static.generate" => Some("n.web.static.generate"),
        "web.docs.generate" | "n.web.docs.generate" => Some("n.web.docs.generate"),
        "http.request" | "n.http.request" => Some("n.http.request"),
        "zebtune" | "n.zebtune" => Some("n.zebtune"),
        "logic.if" | "n.logic.if" => Some("n.logic.if"),
        "logic.match" | "n.logic.match" => Some("n.logic.match"),
        "logic.collect" | "n.logic.collect" => Some("n.logic.collect"),
        "logic.foreach" | "n.logic.foreach" => Some("n.logic.foreach"),
        "logic.reduce" | "n.logic.reduce" => Some("n.logic.reduce"),
        "logic.retry" | "n.logic.retry" => Some("n.logic.retry"),
        "trigger.ws" | "n.trigger.ws" => Some("n.trigger.ws"),
        "ws.emit" | "n.ws.emit" => Some("n.ws.emit"),
        "ws.sync_state" | "n.ws.sync_state" => Some("n.ws.sync_state"),
        "auth.token.create" | "n.auth.token.create" => Some("n.auth.token.create"),
        "crypto" | "n.crypto" => Some("n.crypto"),
        "ai.agent" | "n.ai.agent" => Some("n.ai.agent"),
        "ai.tts" | "n.ai.tts" => Some("n.ai.tts"),
        "browser.run" | "n.browser.run" => Some("n.browser.run"),
        "trigger.weberror" | "n.trigger.weberror" => Some("n.trigger.weberror"),
        "trigger.function" | "n.trigger.function" => Some("n.trigger.function"),
        "function.call" | "n.function.call" => Some("n.function.call"),
        "fs.save" | "n.fs.save" => Some("n.fs.save"),
        "fs.compress" | "n.fs.compress" => Some("n.fs.compress"),
        "fs.decompress" | "n.fs.decompress" => Some("n.fs.decompress"),
        "fs.pdf.convert" | "n.fs.pdf.convert" => Some("n.fs.pdf.convert"),
        "fs.thumbnail" | "n.fs.thumbnail" => Some("n.fs.thumbnail"),
        "mem.set" | "n.mem.set" => Some("n.mem.set"),
        "mem.get" | "n.mem.get" => Some("n.mem.get"),
        "mem.del" | "n.mem.del" => Some("n.mem.del"),
        "mem.exists" | "n.mem.exists" => Some("n.mem.exists"),
        "mem.expire" | "n.mem.expire" => Some("n.mem.expire"),
        "mem.incr" | "n.mem.incr" => Some("n.mem.incr"),
        "mem.publish" | "n.mem.publish" => Some("n.mem.publish"),
        "trigger.memsubscribe" | "n.trigger.memsubscribe" => Some("n.trigger.memsubscribe"),
        _ => None,
    }
}

/// Default input/output pins per node kind.
pub fn default_pins(kind: &str) -> (Vec<String>, Vec<String>) {
    match kind {
        "n.trigger.webhook" | "n.trigger.schedule" | "n.trigger.manual" | "n.trigger.function" => {
            (vec![], vec!["out".to_string()])
        }
        "n.pg.query" | "n.sekejap.query" | "n.table.convert" | "n.table.query" | "n.script"
        | "n.http.request" | "n.zebtune" | "n.logic.collect" | "n.ai.tts" => {
            (vec!["in".to_string()], vec!["out".to_string()])
        }
        "n.logic.foreach" => (vec!["in".to_string()], vec!["item".to_string()]),
        "n.logic.reduce" => (vec!["in".to_string()], vec!["out".to_string()]),
        "n.logic.retry" => (
            vec!["in".to_string()],
            vec!["retry".to_string(), "failed".to_string()],
        ),
        "n.logic.if" => (
            vec!["in".to_string()],
            vec!["true".to_string(), "false".to_string()],
        ),
        // n.logic.match: output pins are dynamic (set per-instance from cases config).
        // Return just ["default"] as the fallback; actual pins are set after config is parsed.
        "n.logic.match" => (vec!["in".to_string()], vec!["default".to_string()]),
        "n.web.response" => (vec!["in".to_string()], vec!["out".to_string()]),
        "n.trigger.ws" => (vec![], vec!["out".to_string()]),
        "n.ws.emit" | "n.ws.sync_state" => (vec!["in".to_string()], vec!["out".to_string()]),
        "n.function.call" => (
            vec!["in".to_string()],
            vec!["out".to_string(), "error".to_string()],
        ),
        _ => (vec!["in".to_string()], vec!["out".to_string()]),
    }
}

/// Strips matching outer `"..."` or `'...'` from a string.
/// Returns the byte offset of the first top-level `|` in `raw` (not inside quotes).
/// Used to extract pipe bodies from raw command strings without losing quote context.
fn find_first_pipe_in_raw(raw: &str) -> Option<usize> {
    let mut in_single = false;
    let mut in_double = false;
    for (i, ch) in raw.char_indices() {
        match ch {
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            '|' if !in_single && !in_double => return Some(i),
            _ => {}
        }
    }
    None
}

fn strip_outer_quotes(s: &str) -> &str {
    if s.len() >= 2
        && ((s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')))
    {
        &s[1..s.len() - 1]
    } else {
        s
    }
}

/// Extracts the raw body substring after ` -- ` in a segment string.
/// Strips outer quotes if the entire body is quoted.
fn extract_raw_body_from(raw: &str) -> Option<String> {
    raw.find(" -- ")
        .map(|pos| {
            let after = raw[pos + 4..].trim();
            strip_outer_quotes(after).to_string()
        })
        .filter(|s| !s.is_empty())
}

/// Coerce a DSL flag string value to the appropriate JSON type.
/// "true"/"false" → bool, integer strings → i64, float strings → f64, else string.
fn coerce_scalar_value(s: &str) -> Value {
    match s {
        "true" => json!(true),
        "false" => json!(false),
        _ => {
            if let Ok(n) = s.parse::<i64>() {
                json!(n)
            } else if let Ok(f) = s.parse::<f64>() {
                json!(f)
            } else {
                json!(s)
            }
        }
    }
}

/// Parse flag→config key mapping and body from token list after node kind.
///
/// Every `--flag` must be declared in the node's `dsl_flags`. The `config_key`
/// from the matching `DslFlag` entry is the authoritative destination key.
/// Unknown flags (not declared in `dsl_flags`) are a hard parse error.
pub fn parse_node_config(
    tokens: &[String],
    raw: &str,
    dsl_flags: &[DslFlag],
) -> Result<(Value, Option<String>), String> {
    let mut config = serde_json::Map::new();
    let mut list_modes = HashMap::<String, ListFlagMode>::new();
    let mut body: Option<String> = None;
    let mut i = 0;

    while i < tokens.len() {
        let t = &tokens[i];

        if t == "--" {
            body = extract_raw_body_from(raw);
            break;
        }

        if let Some(key) = t.strip_prefix("--") {
            let flag_str = format!("--{key}");
            let dsl_flag = dsl_flags
                .iter()
                .find(|f| f.flag == flag_str)
                .ok_or_else(|| {
                    format!("unknown flag `--{key}` — not declared in this node's dsl_flags")
                })?;

            match dsl_flag.kind {
                DslFlagKind::Scalar => {
                    let val = tokens.get(i + 1).cloned().unwrap_or_default();
                    config.insert(dsl_flag.config_key.clone(), coerce_scalar_value(&val));
                    i += 2;
                }
                DslFlagKind::CommaSeparatedList | DslFlagKind::RepeatedList => {
                    let val = tokens.get(i + 1).cloned().unwrap_or_default();
                    push_list_flag_value(&mut config, &mut list_modes, dsl_flag, &val)?;
                    i += 2;
                }
                DslFlagKind::Bool => {
                    config.insert(dsl_flag.config_key.clone(), json!(true));
                    i += 1;
                }
                DslFlagKind::KeyValuePairs => {
                    let raw = tokens.get(i + 1).cloned().unwrap_or_default();
                    let (k, v) = if let Some(eq) = raw.find('=') {
                        (raw[..eq].trim().to_string(), raw[eq + 1..].to_string())
                    } else {
                        (raw.trim().to_string(), String::new())
                    };
                    let entry = config
                        .entry(dsl_flag.config_key.clone())
                        .or_insert_with(|| Value::Object(serde_json::Map::new()));
                    if let Value::Object(m) = entry {
                        m.insert(k, json!(v));
                    }
                    i += 2;
                }
            }
        } else {
            i += 1;
        }
    }

    Ok((Value::Object(config), body))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ListFlagMode {
    Compact,
    Repeated,
}

fn push_list_flag_value(
    config: &mut serde_json::Map<String, Value>,
    list_modes: &mut HashMap<String, ListFlagMode>,
    flag: &DslFlag,
    value: &str,
) -> Result<(), String> {
    let has_comma = value.contains(',');
    let next_mode = if has_comma {
        ListFlagMode::Compact
    } else {
        ListFlagMode::Repeated
    };
    let key = flag.config_key.clone();
    if let Some(existing) = list_modes.get(&key) {
        if *existing != next_mode || has_comma {
            return Err(format!(
                "list flag `{}` must use one style per node command: either `{0} a,b,c` or `{0} a {0} b`, not both",
                flag.flag
            ));
        }
    } else {
        list_modes.insert(key.clone(), next_mode);
    }

    let values = if has_comma {
        value
            .split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(|s| json!(s))
            .collect::<Vec<_>>()
    } else if value.trim().is_empty() {
        Vec::new()
    } else {
        vec![json!(value)]
    };

    let entry = config
        .entry(key)
        .or_insert_with(|| Value::Array(Vec::new()));
    if let Value::Array(existing) = entry {
        existing.extend(values);
    }
    Ok(())
}

/// Parse flags for patch operations without DslFlag validation.
/// Used only by `parse_patch` where node kind is not known at parse time.
/// Validation against DslFlags happens later in the executor.
fn parse_flags_for_patch(tokens: &[String], cmd: &str) -> (HashMap<String, Value>, Option<String>) {
    let mut flags: HashMap<String, Value> = HashMap::new();
    let mut body: Option<String> = None;
    let mut i = 0;

    while i < tokens.len() {
        let t = &tokens[i];
        if t == "--" {
            body = extract_raw_body_from(cmd);
            break;
        }
        if let Some(key) = t.strip_prefix("--") {
            let val = tokens.get(i + 1).cloned().unwrap_or_default();
            let config_key = key.replace('-', "_");
            let new_val = coerce_scalar_value(&val);
            // Accumulate repeated flags as an array to preserve all occurrences
            // (e.g. --claim sub=$.id --claim name=$.fullname:public)
            match flags.entry(config_key) {
                std::collections::hash_map::Entry::Occupied(mut e) => match e.get_mut() {
                    Value::Array(arr) => arr.push(new_val),
                    existing => {
                        let prev = existing.clone();
                        *existing = Value::Array(vec![prev, new_val]);
                    }
                },
                std::collections::hash_map::Entry::Vacant(e) => {
                    e.insert(new_val);
                }
            }
            i += 2;
        } else {
            i += 1;
        }
    }

    (flags, body)
}

/// Parse `register <file_rel_path> [--title t] [--description d] [--as-json] <body>`
fn parse_register(tokens: &[String], cmd: &str) -> DslVerb {
    let file_rel_path = tokens.get(1).cloned().unwrap_or_default();
    let mut title = String::new();
    let mut description = String::new();
    let mut as_json = false;
    let mut i = 2;

    while i < tokens.len() {
        match tokens[i].as_str() {
            "--title" => {
                title = tokens.get(i + 1).cloned().unwrap_or_default();
                i += 2;
            }
            "--description" => {
                description = tokens.get(i + 1).cloned().unwrap_or_default();
                i += 2;
            }
            "--as-json" => {
                as_json = true;
                i += 1;
            }
            _ => break,
        }
    }

    // Extract body from raw string to preserve quoted values (e.g. --cron "* * * * *").
    // Pipe mode bodies start with `|`; graph mode bodies start with `[`.
    let body = match find_first_pipe_in_raw(cmd) {
        Some(pos) => cmd[pos..].to_string(),
        None => cmd
            .find('[')
            .map(|pos| cmd[pos..].to_string())
            .unwrap_or_default(),
    };

    DslVerb::Register {
        file_rel_path,
        title,
        description,
        as_json,
        body,
    }
}

/// Parse `patch pipeline <file_rel_path> node <id> [flags] [-- body]`
fn parse_patch(tokens: &[String], cmd: &str) -> DslVerb {
    let file_rel_path = tokens.get(2).cloned().unwrap_or_default();
    let node_id = tokens.get(4).cloned().unwrap_or_default();
    let flag_tokens = if tokens.len() > 5 {
        tokens[5..].to_vec()
    } else {
        vec![]
    };
    let (flags, body) = parse_flags_for_patch(&flag_tokens, cmd);
    DslVerb::Patch {
        file_rel_path,
        node_id,
        flags,
        body,
    }
}

fn extract_flag(tokens: &[String], flag: &str) -> Option<String> {
    let pos = tokens.iter().position(|t| t == flag)?;
    tokens.get(pos + 1).cloned()
}

fn extract_body(tokens: &[String]) -> Option<String> {
    let pos = tokens.iter().position(|t| t == "--")?;
    let rest = tokens[pos + 1..].join(" ");
    if rest.is_empty() { None } else { Some(rest) }
}

/// Parse one command string into a `DslVerb`.
pub fn parse_one_command(cmd: &str) -> DslVerb {
    let tokens = tokenize(cmd);
    if tokens.is_empty() {
        return DslVerb::Unknown {
            raw: cmd.to_string(),
        };
    }

    match tokens[0].to_lowercase().as_str() {
        "get" => {
            let resource = tokens.get(1).cloned().unwrap_or_default().to_lowercase();
            let path = extract_flag(&tokens, "--path");
            let filter = extract_flag(&tokens, "--filter");
            let status = extract_flag(&tokens, "--status");
            DslVerb::Get { resource, path, filter, status }
        }
        "describe" => {
            let kind = tokens.get(1).cloned().unwrap_or_default().to_lowercase();
            let name = tokens.get(2).cloned().unwrap_or_default();
            let compact = tokens.iter().any(|t| t == "--compact");
            DslVerb::Describe { kind, name, compact }
        }
        "read" => {
            let kind = tokens.get(1).cloned().unwrap_or_default().to_lowercase();
            let name = tokens.get(2).cloned().unwrap_or_default();
            DslVerb::Read { kind, name }
        }
        "write" | "create" => {
            let kind = tokens.get(1).cloned().unwrap_or_default().to_lowercase();
            let name = tokens.get(2).cloned().unwrap_or_default();
            let body = extract_body(&tokens);
            DslVerb::Write { kind, name, body }
        }
        "delete" | "rm" | "remove" => {
            let kind = tokens.get(1).cloned().unwrap_or_default().to_lowercase();
            let name = tokens.get(2).cloned().unwrap_or_default();
            DslVerb::Delete { kind, name }
        }
        "activate" => {
            // Accept both "activate <path>" and "activate pipeline <path>"
            let mut idx = 1;
            if tokens.get(1).map(|s| s.as_str()) == Some("pipeline") { idx = 2; }
            let file_rel_path = tokens.get(idx).cloned().unwrap_or_default();
            DslVerb::Activate { file_rel_path }
        }
        "deactivate" => {
            // Accept both "deactivate <path>" and "deactivate pipeline <path>"
            let mut idx = 1;
            if tokens.get(1).map(|s| s.as_str()) == Some("pipeline") { idx = 2; }
            let file_rel_path = tokens.get(idx).cloned().unwrap_or_default();
            DslVerb::Deactivate { file_rel_path }
        }
        "execute" | "exec" => {
            // Accept both "execute <path>" and "execute pipeline <path>"
            let mut idx = 1;
            if tokens.get(1).map(|s| s.as_str()) == Some("pipeline") { idx = 2; }
            let file_rel_path = tokens.get(idx).cloned().unwrap_or_default();
            let input_str = extract_flag(&tokens, "--input").unwrap_or_default();
            let input = serde_json::from_str(&input_str).unwrap_or(json!({}));
            DslVerb::Execute { file_rel_path, input }
        }
        "register" | "reg" => parse_register(&tokens, cmd),
        "patch" => parse_patch(&tokens, cmd),
        "run" => {
            let dry_run = tokens.iter().any(|t| t == "--dry-run");
            // Extract body from raw string to preserve quoted values.
            let body = match find_first_pipe_in_raw(cmd) {
                Some(pos) => cmd[pos..].to_string(),
                None => cmd
                    .find('[')
                    .map(|pos| cmd[pos..].to_string())
                    .unwrap_or_default(),
            };
            DslVerb::Run { body, dry_run }
        }
        "git" => {
            let subcommand = tokens.get(1).cloned().unwrap_or_default().to_lowercase();
            let dash_pos = tokens.iter().position(|t| t == "--");
            let args = if let Some(pos) = dash_pos {
                tokens[2..pos].to_vec()
            } else {
                tokens[2..].to_vec()
            };
            let body = dash_pos.and_then(|pos| {
                let b = tokens[pos + 1..].join(" ");
                if b.is_empty() { None } else { Some(b) }
            });
            DslVerb::Git { subcommand, args, body }
        }
        "node" => {
            let sub = tokens.get(1).cloned().unwrap_or_default().to_lowercase();
            if sub == "help" {
                let kind = tokens.get(2).cloned().unwrap_or_default();
                DslVerb::NodeHelp { kind }
            } else {
                DslVerb::Unknown { raw: cmd.to_string() }
            }
        }
        "credential" | "credentials" | "secret" | "secrets"
        | "set-secret" | "set-credential" | "set-env" => {
            DslVerb::CredentialBlocked {
                reason: "Credential writes are blocked via DSL for security. Use the Credentials UI at /projects/{owner}/{project}/credentials".to_string(),
            }
        }
        _ => DslVerb::Unknown { raw: cmd.to_string() },
    }
}

/// Build a `PipelineGraph` from pipe (`|`) or graph (`[id] ->`) notation.
pub fn build_pipeline_graph(id: &str, body: &str) -> Result<PipelineGraph, String> {
    let body = body.trim();
    if body.is_empty() {
        return Err("Pipeline body is empty".to_string());
    }
    // Detect graph mode: body contains `[` and `] ->` (with space before arrow)
    if body.contains('[') && body.contains("] ->") {
        build_graph_mode(id, body)
    } else {
        build_pipe_mode(id, body)
    }
}

/// Split a pipe-notation body into segments, ignoring `|` inside single/double quotes.
fn split_pipe_segments(body: &str) -> Vec<&str> {
    let mut segments = Vec::new();
    let mut start = 0usize;
    let mut in_single = false;
    let mut in_double = false;

    for (byte_pos, ch) in body.char_indices() {
        match ch {
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            '|' if !in_single && !in_double => {
                let seg = body[start..byte_pos].trim();
                if !seg.is_empty() {
                    segments.push(seg);
                }
                start = byte_pos + ch.len_utf8();
            }
            _ => {}
        }
    }
    let last = body[start..].trim();
    if !last.is_empty() {
        segments.push(last);
    }
    segments
}

/// Build pipeline from graph notation: `[label] node_kind --flags...\n[from] -> [to]`
fn build_graph_mode(id: &str, body: &str) -> Result<PipelineGraph, String> {
    let mut nodes: Vec<PipelineNode> = Vec::new();
    let mut edges: Vec<PipelineEdge> = Vec::new();

    // Join line continuations then split on newlines
    let joined = body.replace("\\\n", " ").replace("\\\r\n", " ");
    let lines: Vec<&str> = joined
        .lines()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();

    for line in &lines {
        if !line.starts_with('[') {
            continue;
        }
        if line.contains("->") {
            // Edge declaration: [from]:pin -> [to]:pin  or  [from] -> [to]
            parse_graph_edge(line, &mut edges)?;
        } else {
            // Node declaration: [label] node_kind --flags...
            parse_graph_node(line, &mut nodes)?;
        }
    }

    // Entry nodes = nodes with no incoming edges
    let to_nodes: std::collections::HashSet<&str> =
        edges.iter().map(|e| e.to_node.as_str()).collect();
    let entry_nodes: Vec<String> = nodes
        .iter()
        .filter(|n| !to_nodes.contains(n.id.as_str()))
        .map(|n| n.id.clone())
        .collect();

    Ok(PipelineGraph {
        kind: "zebflow.pipeline".to_string(),
        version: "0.1".to_string(),
        id: id.to_string(),
        description: None,
        metadata: None,
        entry_nodes,
        nodes,
        edges,
    })
}

#[cfg(test)]
mod tests {
    use crate::pipeline::model::PipelineNode;
    use serde_json::json;

    use super::{
        DslVerb, build_pipeline_graph, node_to_segment_no_body, parse_one_command, split_commands,
    };

    #[test]
    fn logic_match_cases_accept_compact_list_form() {
        let dsl = r#"
[a] trigger.manual
[b] logic.match --expr "$input.type" --cases create,update,delete --default unknown

[a] -> [b]
"#;

        let graph = build_pipeline_graph("parser-match-cases-test", dsl).expect("graph");
        let node = graph
            .nodes
            .iter()
            .find(|node| node.id == "b")
            .expect("match node");

        assert_eq!(
            node.config.get("cases"),
            Some(&json!(["create", "update", "delete"]))
        );
        assert_eq!(
            node.output_pins,
            vec![
                "create".to_string(),
                "update".to_string(),
                "delete".to_string(),
                "unknown".to_string()
            ]
        );
    }

    #[test]
    fn logic_match_cases_accept_repeated_list_form() {
        let dsl = r#"
[a] trigger.manual
[b] logic.match --expr "$input.type" --cases create --cases update --cases delete --default unknown

[a] -> [b]
"#;

        let graph = build_pipeline_graph("parser-match-cases-repeated-test", dsl).expect("graph");
        let node = graph
            .nodes
            .iter()
            .find(|node| node.id == "b")
            .expect("match node");

        assert_eq!(
            node.config.get("cases"),
            Some(&json!(["create", "update", "delete"]))
        );
    }

    #[test]
    fn list_flags_reject_mixed_compact_and_repeated_forms() {
        let dsl = r#"
[a] trigger.manual
[b] logic.match --expr "$input.type" --cases create,update --cases delete --default unknown

[a] -> [b]
"#;

        let err = build_pipeline_graph("parser-match-cases-mixed-test", dsl)
            .expect_err("mixed list syntax must fail");
        assert!(err.contains("must use one style"));
    }

    #[test]
    fn repeated_list_reconstructs_source_binding_objects() {
        let node = PipelineNode {
            id: "b".to_string(),
            kind: "n.table.query".to_string(),
            config: json!({
                "sources": [
                    { "source": "datasets/posts.csv", "alias": "posts" },
                    { "source": "$input.rows", "alias": "rows" }
                ],
                "sql": "select * from posts",
                "to_json": true
            }),
            input_pins: vec!["in".to_string()],
            output_pins: vec!["out".to_string()],
        };

        let segment = node_to_segment_no_body(&node);
        assert!(segment.contains("--from \"datasets/posts.csv as posts\""));
        assert!(segment.contains("--from \"$input.rows as rows\""));
        assert!(segment.contains("--to-json"));
    }

    #[test]
    fn split_commands_preserves_graph_mode_lines_for_run() {
        let dsl = r#"
run \
  [a] trigger.manual \
  [b] script -- "return { ok: true };" \
  [a] -> [b]
"#;

        let commands = split_commands(dsl);
        assert_eq!(commands.len(), 1);

        let verb = parse_one_command(&commands[0]);
        match verb {
            DslVerb::Run { body, dry_run } => {
                assert!(!dry_run);
                let graph = build_pipeline_graph("graph-run-test", &body).expect("graph");
                assert_eq!(graph.nodes.len(), 2);
                assert_eq!(graph.edges.len(), 1);
            }
            other => panic!("expected run verb, got {other:?}"),
        }
    }
}

fn parse_graph_node(line: &str, nodes: &mut Vec<PipelineNode>) -> Result<(), String> {
    let rest = line
        .strip_prefix('[')
        .ok_or("expected '[' at start of node declaration")?;
    let (label, rest) = rest
        .split_once(']')
        .ok_or("expected ']' in node declaration")?;
    let label = label.trim();
    if label.is_empty() {
        return Err("node label must not be empty".to_string());
    }
    let rest = rest.trim();
    let tokens = tokenize(rest);
    if tokens.is_empty() {
        return Err(format!("node '[{label}]' has no kind"));
    }
    let raw_kind = &tokens[0];
    let full_kind =
        expand_kind(raw_kind).ok_or_else(|| format!("Unknown node kind: '{raw_kind}'"))?;
    let (input_pins, mut output_pins) = default_pins(full_kind);
    let all_defs = builtin_node_definitions();
    let dsl_flags = all_defs
        .iter()
        .find(|d| d.kind == full_kind)
        .map(|d| d.dsl_flags.as_slice())
        .unwrap_or(&[]);
    let (mut config, body_val) = parse_node_config(&tokens[1..], rest, dsl_flags)?;
    if let Some(bval) = body_val {
        let body_key = match full_kind {
            "n.pg.query" => "query",
            "n.sekejap.query" => "query",
            "n.table.query" => "sql",
            "n.script" => "source",
            "n.logic.match" | "n.logic.if" => "expression",
            "n.browser.run" => "code",
            _ => "body",
        };
        if let Value::Object(ref mut map) = config {
            map.insert(body_key.to_string(), json!(bval));
        }
    }
    // For logic.match, output pins are dynamic: the declared cases + the default pin.
    if full_kind == "n.logic.match" {
        if let Value::Object(ref map) = config {
            let cases: Vec<String> = map
                .get("cases")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let default_pin = map
                .get("default")
                .and_then(|v| v.as_str())
                .unwrap_or("default")
                .to_string();
            let mut pins = cases;
            if !pins.contains(&default_pin) {
                pins.push(default_pin);
            }
            if !pins.is_empty() {
                output_pins = pins;
            }
        }
    }
    nodes.push(PipelineNode {
        id: label.to_string(),
        kind: full_kind.to_string(),
        input_pins,
        output_pins,
        config,
    });
    Ok(())
}

fn parse_graph_edge(line: &str, edges: &mut Vec<PipelineEdge>) -> Result<(), String> {
    // Format: [from]:pin -> [to]:pin  or  [from] -> [to]
    let arrow_pos = line.find("->").ok_or("expected '->' in edge declaration")?;
    let from_part = line[..arrow_pos].trim();
    let to_part = line[arrow_pos + 2..].trim();

    let (from_node, from_pin) = parse_node_pin_part(from_part, "out")?;
    let (to_node, to_pin) = parse_node_pin_part(to_part, "in")?;

    edges.push(PipelineEdge {
        from_node,
        from_pin,
        to_node,
        to_pin,
    });
    Ok(())
}

/// Parse `[label]` or `[label]:pin` into `(node_id, pin)`. `default_pin` used when no `:pin`.
fn parse_node_pin_part(s: &str, default_pin: &str) -> Result<(String, String), String> {
    let s = s.trim();
    let inner = s
        .strip_prefix('[')
        .ok_or_else(|| format!("expected '[' in edge endpoint: '{s}'"))?;
    let (label, rest) = inner
        .split_once(']')
        .ok_or_else(|| format!("expected ']' in edge endpoint: '{s}'"))?;
    let label = label.trim().to_string();
    let pin = rest
        .trim()
        .strip_prefix(':')
        .map(|p| p.trim().to_string())
        .unwrap_or_else(|| default_pin.to_string());
    Ok((label, pin))
}

// ─── DSL Reconstruction (inverse of build_pipeline_graph) ───────────────────

/// Reconstruct DSL text from a compiled `PipelineGraph`.
///
/// Emits pipe mode (`| node1\n| node2`) for simple linear chains where every
/// edge uses default "out"→"in" pins and no node has more than one in/out edge.
/// Emits graph mode (`[label] kind ...\n[a] -> [b]`) for all other topologies.
pub fn graph_to_dsl(graph: &PipelineGraph) -> String {
    if is_linear_graph(graph) {
        graph_to_pipe_mode(graph)
    } else {
        graph_to_graph_mode(graph)
    }
}

/// True iff the graph is a simple linear chain — no branching, no merging,
/// all edges on default "out"→"in" pins.
fn is_linear_graph(graph: &PipelineGraph) -> bool {
    let mut in_count: HashMap<&str, usize> = HashMap::new();
    let mut out_count: HashMap<&str, usize> = HashMap::new();

    for edge in &graph.edges {
        if edge.from_pin != "out" || edge.to_pin != "in" {
            return false;
        }
        *in_count.entry(edge.to_node.as_str()).or_insert(0) += 1;
        *out_count.entry(edge.from_node.as_str()).or_insert(0) += 1;
    }

    graph.nodes.iter().all(|n| {
        *in_count.get(n.id.as_str()).unwrap_or(&0) <= 1
            && *out_count.get(n.id.as_str()).unwrap_or(&0) <= 1
    })
}

/// Reconstruct the DSL segment for one node: `kind --flag val... -- body`
///
/// Uses `dsl_flags` as the authoritative reverse-mapping (config_key → flag).
/// Fields not declared in `dsl_flags` (e.g. `title`, `params_path`) are omitted.
fn node_to_segment(node: &PipelineNode) -> String {
    let all_defs = builtin_node_definitions();
    let dsl_flags = all_defs
        .iter()
        .find(|d| d.kind == node.kind)
        .map(|d| d.dsl_flags.as_slice())
        .unwrap_or(&[]);

    // Strip "n." prefix for cleaner output; expand_kind accepts both forms.
    let kind = node.kind.strip_prefix("n.").unwrap_or(&node.kind);
    let mut parts = vec![kind.to_string()];

    for flag in dsl_flags {
        let Some(val) = node.config.get(&flag.config_key) else {
            continue;
        };
        match &flag.kind {
            DslFlagKind::Bool => {
                if val.as_bool().unwrap_or(false) {
                    parts.push(flag.flag.clone());
                }
            }
            DslFlagKind::CommaSeparatedList => {
                if let Some(arr) = val.as_array() {
                    let csv = arr
                        .iter()
                        .filter_map(|v| v.as_str())
                        .collect::<Vec<_>>()
                        .join(",");
                    if !csv.is_empty() {
                        parts.push(flag.flag.clone());
                        parts.push(csv);
                    }
                }
            }
            DslFlagKind::RepeatedList => {
                if let Some(arr) = val.as_array() {
                    for item in arr.iter().filter_map(repeated_list_item_to_string) {
                        if item.is_empty() {
                            continue;
                        }
                        parts.push(flag.flag.clone());
                        parts.push(quote_dsl_arg(&item));
                    }
                }
            }
            DslFlagKind::Scalar => {
                let s = match val {
                    Value::String(s) if !s.is_empty() => s.clone(),
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    _ => continue,
                };
                parts.push(flag.flag.clone());
                // Quote values containing spaces.
                parts.push(quote_dsl_arg(&s));
            }
            DslFlagKind::KeyValuePairs => {
                if let Some(map) = val.as_object() {
                    for (k, v) in map {
                        let v_str = match v {
                            Value::String(s) => s.clone(),
                            other => other.to_string(),
                        };
                        parts.push(flag.flag.clone());
                        parts.push(format!("{}={}", k, v_str));
                    }
                }
            }
        }
    }

    // Body (SQL / script source / generic body) — stored under a kind-specific key.
    let body_key = match node.kind.as_str() {
        "n.pg.query" => "query",
        "n.sekejap.query" => "query",
        "n.table.query" => "sql",
        "n.script" => "source",
        "n.logic.match" | "n.logic.if" => "expression",
        _ => "body",
    };
    if let Some(body) = node.config.get(body_key).and_then(|v| v.as_str()) {
        let body = body.trim();
        if !body.is_empty() {
            // Collapse internal newlines so the segment stays on one line.
            let inline: String = body
                .lines()
                .map(str::trim)
                .filter(|l| !l.is_empty())
                .collect::<Vec<_>>()
                .join(" ");
            parts.push("--".to_string());
            parts.push(inline);
        }
    }

    parts.join(" ")
}

/// Like `node_to_segment` but omits the `-- body` portion.
/// Used by compact describe to show flags without long SQL/script bodies.
pub fn node_to_segment_no_body(node: &PipelineNode) -> String {
    let all_defs = builtin_node_definitions();
    let dsl_flags = all_defs
        .iter()
        .find(|d| d.kind == node.kind)
        .map(|d| d.dsl_flags.as_slice())
        .unwrap_or(&[]);

    let kind = node.kind.strip_prefix("n.").unwrap_or(&node.kind);
    let mut parts = vec![kind.to_string()];

    for flag in dsl_flags {
        // Skip body-typed flags (their config_key matches the body key for this node kind)
        let body_key = match node.kind.as_str() {
            "n.pg.query" => "query",
            "n.sekejap.query" => "query",
            "n.table.query" => "sql",
            "n.script" => "source",
            "n.logic.match" | "n.logic.if" => "expression",
            _ => "body",
        };
        if flag.config_key == body_key {
            continue;
        }
        let Some(val) = node.config.get(&flag.config_key) else {
            continue;
        };
        match &flag.kind {
            DslFlagKind::Bool => {
                if val.as_bool().unwrap_or(false) {
                    parts.push(flag.flag.clone());
                }
            }
            DslFlagKind::CommaSeparatedList => {
                if let Some(arr) = val.as_array() {
                    let csv = arr
                        .iter()
                        .filter_map(|v| v.as_str())
                        .collect::<Vec<_>>()
                        .join(",");
                    if !csv.is_empty() {
                        parts.push(flag.flag.clone());
                        parts.push(csv);
                    }
                }
            }
            DslFlagKind::RepeatedList => {
                if let Some(arr) = val.as_array() {
                    for item in arr.iter().filter_map(repeated_list_item_to_string) {
                        if item.is_empty() {
                            continue;
                        }
                        parts.push(flag.flag.clone());
                        parts.push(quote_dsl_arg(&item));
                    }
                }
            }
            DslFlagKind::Scalar => {
                let s = match val {
                    Value::String(s) if !s.is_empty() => s.clone(),
                    Value::Number(n) => n.to_string(),
                    Value::Bool(b) => b.to_string(),
                    _ => continue,
                };
                parts.push(flag.flag.clone());
                parts.push(quote_dsl_arg(&s));
            }
            DslFlagKind::KeyValuePairs => {
                if let Some(map) = val.as_object() {
                    for (k, v) in map {
                        let v_str = match v {
                            Value::String(s) => s.clone(),
                            other => other.to_string(),
                        };
                        parts.push(flag.flag.clone());
                        parts.push(format!("{}={}", k, v_str));
                    }
                }
            }
        }
    }

    parts.join(" ")
}

fn quote_dsl_arg(value: &str) -> String {
    if value.chars().any(char::is_whitespace) || value.contains('"') {
        format!("\"{}\"", value.replace('"', "\\\""))
    } else {
        value.to_string()
    }
}

fn repeated_list_item_to_string(value: &Value) -> Option<String> {
    if let Some(s) = value.as_str() {
        return Some(s.to_string());
    }
    let obj = value.as_object()?;
    let source = obj.get("source").and_then(Value::as_str)?.trim();
    let alias = obj.get("alias").and_then(Value::as_str)?.trim();
    if source.is_empty() || alias.is_empty() {
        return None;
    }
    Some(format!("{source} as {alias}"))
}

fn graph_to_pipe_mode(graph: &PipelineGraph) -> String {
    let node_map: HashMap<&str, &PipelineNode> =
        graph.nodes.iter().map(|n| (n.id.as_str(), n)).collect();
    let next_map: HashMap<&str, &str> = graph
        .edges
        .iter()
        .map(|e| (e.from_node.as_str(), e.to_node.as_str()))
        .collect();

    let mut ordered: Vec<&PipelineNode> = Vec::new();
    if let Some(first_id) = graph.entry_nodes.first() {
        let mut cur = first_id.as_str();
        let mut visited = std::collections::HashSet::new();
        loop {
            if !visited.insert(cur) {
                break; // cycle guard
            }
            if let Some(&node) = node_map.get(cur) {
                ordered.push(node);
            }
            match next_map.get(cur) {
                Some(&next) => cur = next,
                None => break,
            }
        }
    }

    ordered
        .iter()
        .map(|n| format!("| {}", node_to_segment(n)))
        .collect::<Vec<_>>()
        .join("\n")
}

fn graph_to_graph_mode(graph: &PipelineGraph) -> String {
    let mut lines: Vec<String> = Vec::new();

    for node in &graph.nodes {
        lines.push(format!("[{}] {}", node.id, node_to_segment(node)));
    }

    if !graph.edges.is_empty() {
        lines.push(String::new());
        for edge in &graph.edges {
            if edge.from_pin == "out" && edge.to_pin == "in" {
                lines.push(format!("[{}] -> [{}]", edge.from_node, edge.to_node));
            } else {
                lines.push(format!(
                    "[{}]:{} -> [{}]:{}",
                    edge.from_node, edge.from_pin, edge.to_node, edge.to_pin
                ));
            }
        }
    }

    lines.join("\n")
}

// ─── Pipe mode builder ───────────────────────────────────────────────────────

/// Build pipeline from pipe-notation: `trigger.webhook --path /test | pg.query --credential main`
fn build_pipe_mode(id: &str, body: &str) -> Result<PipelineGraph, String> {
    // Strip leading `|` if present
    let body = body.trim_start_matches('|').trim();
    let segments: Vec<&str> = split_pipe_segments(body);

    if segments.is_empty() {
        return Err("No nodes in pipeline body".to_string());
    }

    let mut nodes: Vec<PipelineNode> = Vec::new();
    let mut edges: Vec<PipelineEdge> = Vec::new();

    // Check if first node is a trigger kind
    let first_tokens = tokenize(segments[0]);
    let first_raw_kind = first_tokens.first().map(|s| s.as_str()).unwrap_or("");
    let first_full_kind = expand_kind(first_raw_kind).unwrap_or(first_raw_kind);
    let has_trigger_first = first_full_kind.starts_with("n.trigger.");

    // Auto-prepend trigger.manual if first node is not a trigger
    if !has_trigger_first {
        nodes.push(PipelineNode {
            id: "trigger".to_string(),
            kind: "n.trigger.manual".to_string(),
            input_pins: vec![],
            output_pins: vec!["out".to_string()],
            config: json!({}),
        });
    }

    let all_defs = builtin_node_definitions();

    for (idx, segment) in segments.iter().enumerate() {
        let seg_tokens = tokenize(segment);
        if seg_tokens.is_empty() {
            continue;
        }

        let raw_kind = &seg_tokens[0];
        let full_kind =
            expand_kind(raw_kind).ok_or_else(|| format!("Unknown node kind: '{raw_kind}'"))?;

        let node_id = format!("n{idx}");
        let (input_pins, mut output_pins) = default_pins(full_kind);
        let dsl_flags = all_defs
            .iter()
            .find(|d| d.kind == full_kind)
            .map(|d| d.dsl_flags.as_slice())
            .unwrap_or(&[]);
        let (mut config, body_val) = parse_node_config(&seg_tokens[1..], segment, dsl_flags)?;

        // Set body using kind-appropriate key
        if let Some(bval) = body_val {
            let body_key = match full_kind {
                "n.pg.query" => "query",
                "n.table.query" => "sql",
                "n.script" => "source",
                "n.browser.run" => "code",
                _ => "body",
            };
            if let Value::Object(ref mut map) = config {
                map.insert(body_key.to_string(), json!(bval));
            }
        }

        // For logic.match, output pins are dynamic: the declared cases + the default pin.
        if full_kind == "n.logic.match" {
            if let Value::Object(ref map) = config {
                let cases: Vec<String> = map
                    .get("cases")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect()
                    })
                    .unwrap_or_default();
                let default_pin = map
                    .get("default")
                    .and_then(|v| v.as_str())
                    .unwrap_or("default")
                    .to_string();
                let mut pins = cases;
                if !pins.contains(&default_pin) {
                    pins.push(default_pin);
                }
                if !pins.is_empty() {
                    output_pins = pins;
                }
            }
        }

        // Determine from_node for edge
        let from_node = if idx == 0 {
            if !has_trigger_first {
                // Edge from auto-prepended trigger to first real node
                Some("trigger".to_string())
            } else {
                None // First node is the trigger — no incoming edge
            }
        } else {
            Some(format!("n{}", idx - 1))
        };

        if let Some(from_id) = from_node {
            edges.push(PipelineEdge {
                from_node: from_id,
                from_pin: "out".to_string(),
                to_node: node_id.clone(),
                to_pin: "in".to_string(),
            });
        }

        nodes.push(PipelineNode {
            id: node_id,
            kind: full_kind.to_string(),
            input_pins,
            output_pins,
            config,
        });
    }

    let entry_nodes = nodes
        .first()
        .map(|n| vec![n.id.clone()])
        .unwrap_or_default();

    Ok(PipelineGraph {
        kind: "zebflow.pipeline".to_string(),
        version: "0.1".to_string(),
        id: id.to_string(),
        description: None,
        metadata: None,
        entry_nodes,
        nodes,
        edges,
    })
}