zebflow 0.8.3

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
//! Pipeline DSL executor — executes parsed verbs using platform services.

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

use serde_json::{Value, json};

use super::parser::{
    DslVerb, build_pipeline_graph_with_definitions, parse_one_command, split_commands,
};
use super::{DslLine, DslOutput};
use crate::platform::services::PlatformService;

/// Executor for Pipeline DSL commands.
pub struct DslExecutor {
    platform: Arc<PlatformService>,
    owner: String,
    project: String,
}

impl DslExecutor {
    pub fn new(platform: Arc<PlatformService>, owner: &str, project: &str) -> Self {
        Self {
            platform,
            owner: owner.to_string(),
            project: project.to_string(),
        }
    }

    fn node_definitions(&self) -> Vec<crate::pipeline::NodeDefinition> {
        self.platform
            .node_registry
            .merged_definitions(&self.owner, &self.project)
    }

    /// Execute a run body with an optional initial JSON payload.
    pub async fn execute_run_with_input(
        &self,
        body: &str,
        input: Option<serde_json::Value>,
    ) -> DslOutput {
        self.cmd_run(body, false, input).await
    }

    /// Execute a full DSL string (may contain multiple `&&`-chained commands).
    pub async fn execute_dsl(&self, dsl: &str) -> DslOutput {
        let commands = split_commands(dsl);
        if commands.is_empty() {
            return DslOutput::err("Empty command");
        }
        let mut parsed = Vec::new();
        for cmd in commands {
            let cmd = cmd.trim();
            if cmd.is_empty() {
                continue;
            }
            let verb = parse_one_command(cmd);
            if let DslVerb::Unknown { raw } = &verb {
                let verb_word = raw.split_whitespace().next().unwrap_or("?");
                return DslOutput::err(format!(
                    "Unknown command: '{}'. Type help for available commands.",
                    verb_word
                ));
            }
            parsed.push(verb);
        }

        let mut combined = DslOutput::new_ok();
        for verb in parsed {
            let result = self.execute_verb(verb).await;
            if !result.ok {
                combined.ok = false;
            }
            combined.extend(result.lines);
        }
        combined
    }

    async fn execute_verb(&self, verb: DslVerb) -> DslOutput {
        match verb {
            DslVerb::Get {
                resource,
                path,
                filter,
                status,
            } => {
                self.cmd_get(
                    &resource,
                    path.as_deref(),
                    filter.as_deref(),
                    status.as_deref(),
                )
                .await
            }
            DslVerb::Describe {
                kind,
                name,
                compact,
            } => self.cmd_describe(&kind, &name, compact).await,
            DslVerb::Read { kind, name } => self.cmd_describe(&kind, &name, false).await,
            DslVerb::Activate { file_rel_path } => self.cmd_activate(&file_rel_path).await,
            DslVerb::Deactivate { file_rel_path } => self.cmd_deactivate(&file_rel_path).await,
            DslVerb::Execute {
                file_rel_path,
                input,
            } => self.cmd_execute(&file_rel_path, input).await,
            DslVerb::Register {
                file_rel_path,
                title,
                description,
                as_json,
                body,
            } => {
                self.cmd_register(&file_rel_path, &title, &description, as_json, &body)
                    .await
            }
            DslVerb::Patch {
                file_rel_path,
                node_id,
                flags,
                body,
            } => {
                self.cmd_patch(&file_rel_path, &node_id, flags, body.as_deref())
                    .await
            }
            DslVerb::Run { body, dry_run } => self.cmd_run(&body, dry_run, None).await,
            DslVerb::Delete { kind, name } => self.cmd_delete(&kind, &name).await,
            DslVerb::Git {
                subcommand,
                args,
                body,
            } => self.cmd_git(&subcommand, args, body.as_deref()).await,
            DslVerb::NodeHelp { kind } => self.cmd_node_help(&kind),
            DslVerb::CredentialBlocked { reason } => self.cmd_credential_blocked(&reason),
            DslVerb::Write { .. } => DslOutput::err("write/create is not yet implemented via DSL"),
            DslVerb::Unknown { raw } => {
                let verb_word = raw.split_whitespace().next().unwrap_or("?");
                DslOutput::err(format!(
                    "Unknown command: '{}'. Type help for available commands.",
                    verb_word
                ))
            }
        }
    }

    async fn cmd_get(
        &self,
        resource: &str,
        _path: Option<&str>,
        _filter: Option<&str>,
        _status: Option<&str>,
    ) -> DslOutput {
        match resource {
            "pipelines" | "pipeline" => {
                match self
                    .platform
                    .projects
                    .list_pipeline_meta_rows(&self.owner, &self.project)
                {
                    Ok(rows) => {
                        let mut out = DslOutput::new_ok();
                        if rows.is_empty() {
                            out.push(DslLine::muted("(no pipelines)"));
                            return out;
                        }
                        out.push(DslLine::muted(format!(
                            "{:<26} {:<12} {:<8} {}",
                            "NAME", "TRIGGER", "STATUS", "PATH"
                        )));
                        out.push(DslLine::muted(format!(
                            "{:-<26} {:-<12} {:-<8} {}",
                            "", "", "", "----"
                        )));
                        for m in &rows {
                            let name = truncate(&m.name, 26);
                            let trigger = truncate(&m.trigger_kind, 12);
                            let status = if m.active_hash.is_some() {
                                "active"
                            } else {
                                "draft"
                            };
                            out.push(DslLine::info(format!(
                                "{:<26} {:<12} {:<8} {}",
                                name, trigger, status, m.virtual_path
                            )));
                        }
                        out
                    }
                    Err(e) => DslOutput::err(format!("Error: {}", e.message)),
                }
            }
            "nodes" | "node" => {
                let defs = crate::pipeline::nodes::builtin_node_definitions();
                let mut out = DslOutput::new_ok();
                out.push(DslLine::muted(format!("{:<30} {}", "KIND", "DESCRIPTION")));
                out.push(DslLine::muted(format!("{:-<30} {}", "", "------------")));
                for def in &defs {
                    out.push(DslLine::info(format!(
                        "{:<30} {}",
                        def.kind,
                        truncate(&def.description, 60)
                    )));
                }
                out
            }
            "connections" | "connection" => {
                match self
                    .platform
                    .db_connections
                    .list_project_connections(&self.owner, &self.project)
                {
                    Ok(conns) => {
                        let mut out = DslOutput::new_ok();
                        if conns.is_empty() {
                            out.push(DslLine::muted("(no connections)"));
                            return out;
                        }
                        out.push(DslLine::muted(format!(
                            "{:<24} {:<16} {}",
                            "SLUG", "KIND", "LABEL"
                        )));
                        for c in &conns {
                            out.push(DslLine::info(format!(
                                "{:<24} {:<16} {}",
                                c.connection_slug, c.database_kind, c.connection_label
                            )));
                        }
                        out
                    }
                    Err(e) => DslOutput::err(format!("Error: {}", e.message)),
                }
            }
            "credentials" | "credential" => {
                match self
                    .platform
                    .credentials
                    .list_project_credentials(&self.owner, &self.project)
                {
                    Ok(creds) => {
                        let mut out = DslOutput::new_ok();
                        if creds.is_empty() {
                            out.push(DslLine::muted("(no credentials)"));
                            return out;
                        }
                        for c in &creds {
                            out.push(DslLine::info(format!("{} ({})", c.credential_id, c.kind)));
                        }
                        out
                    }
                    Err(e) => DslOutput::err(format!("Error: {}", e.message)),
                }
            }
            "templates" | "template" => {
                match self
                    .platform
                    .projects
                    .list_template_workspace(&self.owner, &self.project)
                {
                    Ok(ws) => {
                        let mut out = DslOutput::new_ok();
                        if ws.items.is_empty() {
                            out.push(DslLine::muted("(no templates)"));
                            return out;
                        }
                        for item in &ws.items {
                            if item.kind == "file" {
                                out.push(DslLine::info(item.rel_path.clone()));
                            }
                        }
                        out
                    }
                    Err(e) => DslOutput::err(format!("Error: {}", e.message)),
                }
            }
            "docs" | "doc" => {
                match self
                    .platform
                    .projects
                    .list_project_docs(&self.owner, &self.project)
                {
                    Ok(docs) => {
                        let mut out = DslOutput::new_ok();
                        if docs.is_empty() {
                            out.push(DslLine::muted("(no docs)"));
                            return out;
                        }
                        for d in &docs {
                            out.push(DslLine::info(d.path.clone()));
                        }
                        out
                    }
                    Err(e) => DslOutput::err(format!("Error: {}", e.message)),
                }
            }
            other => DslOutput::err(format!(
                "get: unknown resource '{}'. Try: pipelines, nodes, connections, credentials, templates, docs",
                other
            )),
        }
    }

    async fn cmd_describe(&self, kind: &str, name: &str, compact: bool) -> DslOutput {
        match kind {
            "pipeline" | "pipelines" => self.describe_pipeline(name, compact).await,
            "connection" | "connections" => self.describe_connection(name).await,
            "node" | "nodes" => self.describe_node(name),
            other => DslOutput::err(format!(
                "describe: unknown kind '{}'. Try: pipeline, connection, node",
                other
            )),
        }
    }

    async fn describe_pipeline(&self, file_rel_path: &str, compact: bool) -> DslOutput {
        let Some(meta) = (match self.platform.projects.get_pipeline_meta_by_file_id(
            &self.owner,
            &self.project,
            file_rel_path,
        ) {
            Ok(m) => m,
            Err(e) => return DslOutput::err(format!("Error: {}", e.message)),
        }) else {
            return DslOutput::err(format!("Pipeline '{file_rel_path}' not found"));
        };

        let mut out = DslOutput::new_ok();
        let status = if meta
            .active_hash
            .as_deref()
            .map(|h| !h.is_empty() && h == meta.hash)
            .unwrap_or(false)
        {
            "active"
        } else {
            "draft"
        };
        let hash_short = meta.hash.chars().take(8).collect::<String>();

        let hits = self
            .platform
            .pipeline_hits
            .get(&self.owner, &self.project, &meta.file_rel_path);

        if compact {
            // Compact header: single line
            out.push(DslLine::info(format!(
                "{}  [{}]  hash:{}  hits:{}/{}",
                meta.file_rel_path, status, hash_short, hits.success_count, hits.failed_count
            )));
        } else {
            out.push(DslLine::info(format!("pipeline: {}", meta.file_rel_path)));
            out.push(DslLine::info(format!(
                "status: {}  hash: {}  hits: {} ok / {} failed",
                status, hash_short, hits.success_count, hits.failed_count
            )));
        }

        // Reconstruct DSL from the stored graph
        if let Ok(source) = self.platform.projects.read_pipeline_source(
            &self.owner,
            &self.project,
            &meta.file_rel_path,
        ) {
            if let Ok(graph) = serde_json::from_str::<crate::pipeline::PipelineGraph>(&source) {
                if compact {
                    // Compact: one line per node, no body content
                    for node in &graph.nodes {
                        let seg = crate::platform::shell::parser::node_to_segment_no_body(node);
                        out.push(DslLine::info(format!("  {:6}  {}", node.id, seg)));
                    }
                } else {
                    let dsl = crate::platform::shell::parser::graph_to_dsl(&graph);
                    out.push(DslLine::blank());
                    for line in dsl.lines() {
                        out.push(DslLine::info(line.to_string()));
                    }

                    // Node id reference for pipeline_patch
                    if !graph.nodes.is_empty() {
                        let ids = graph
                            .nodes
                            .iter()
                            .map(|n| {
                                format!(
                                    "{}({})",
                                    n.id,
                                    n.kind.strip_prefix("n.").unwrap_or(&n.kind)
                                )
                            })
                            .collect::<Vec<_>>()
                            .join("  ");
                        out.push(DslLine::blank());
                        out.push(DslLine::muted(format!("node ids (for patch): {}", ids)));
                    }
                }
            }
        }

        out
    }

    async fn describe_connection(&self, name: &str) -> DslOutput {
        let conns = match self
            .platform
            .db_connections
            .list_project_connections(&self.owner, &self.project)
        {
            Ok(c) => c,
            Err(e) => return DslOutput::err(format!("Error: {}", e.message)),
        };
        let Some(conn) = conns.iter().find(|c| c.connection_slug == name) else {
            return DslOutput::err(format!("Connection '{name}' not found"));
        };

        let mut out = DslOutput::new_ok();
        out.push(DslLine::info(format!(
            "connection: {}  kind: {}  label: {}",
            conn.connection_slug, conn.database_kind, conn.connection_label
        )));
        if let Some(cred_id) = &conn.credential_id {
            out.push(DslLine::muted(format!("  credential: {}", cred_id)));
        }
        out
    }

    fn describe_node(&self, kind: &str) -> DslOutput {
        let defs = crate::pipeline::nodes::builtin_node_definitions();
        let full_kind = crate::platform::shell::parser::expand_kind(kind).unwrap_or(kind);
        let Some(def) = defs.iter().find(|d| d.kind == full_kind) else {
            return DslOutput::err(format!(
                "Node kind '{kind}' not found. Use 'get nodes' for list."
            ));
        };

        let mut out = DslOutput::new_ok();
        out.push(DslLine::info(format!(
            "kind: {}  — {}",
            def.kind, def.description
        )));
        out.push(DslLine::muted(format!(
            "  inputs: {}  outputs: {}",
            def.input_pins.join(", "),
            def.output_pins.join(", ")
        )));
        out
    }

    async fn cmd_register(
        &self,
        file_rel_path: &str,
        title: &str,
        description: &str,
        as_json: bool,
        body: &str,
    ) -> DslOutput {
        if file_rel_path.is_empty() {
            return DslOutput::err(
                "register: pipeline file_rel_path is required (e.g. pipelines/api/my-pipe)",
            );
        }
        if body.is_empty() {
            return DslOutput::err(
                "register: pipeline body is required. \
                 Example: register pipelines/api/my-pipe | trigger.webhook --path /api | pg.query --credential main-db",
            );
        }

        let name = crate::platform::services::project::name_from_file_rel_path(file_rel_path);
        let node_definitions = self.node_definitions();
        let graph_source = if as_json {
            body.to_string()
        } else {
            match build_pipeline_graph_with_definitions(&name, body, &node_definitions) {
                Ok(mut graph) => {
                    if !description.trim().is_empty() {
                        graph.description = Some(description.trim().to_string());
                    }
                    match serde_json::to_string_pretty(&graph) {
                        Ok(s) => s,
                        Err(e) => return DslOutput::err(format!("Serialize error: {e}")),
                    }
                }
                Err(e) => return DslOutput::err(format!("Parse error: {e}")),
            }
        };

        // Validate JSON
        let graph: crate::pipeline::PipelineGraph = match serde_json::from_str(&graph_source) {
            Ok(g) => g,
            Err(e) => return DslOutput::err(format!("Invalid pipeline JSON: {e}")),
        };

        // Webhook conflict check: reject if any active pipeline already owns the same path.
        let self_file_rel_path = self
            .platform
            .projects
            .get_pipeline_meta_by_file_id(&self.owner, &self.project, file_rel_path)
            .ok()
            .flatten()
            .map(|m| m.file_rel_path)
            .unwrap_or_default();

        match self.platform.projects.check_webhook_path_conflict(
            &self.owner,
            &self.project,
            &graph,
            &self_file_rel_path,
        ) {
            Ok(conflicts) if !conflicts.is_empty() => {
                let c = &conflicts[0];
                return DslOutput::err(format!(
                    "Webhook conflict: {} {} is already registered by pipeline '{}' ({})",
                    c.method, c.path, c.pipeline_name, c.file_rel_path
                ));
            }
            Ok(_) => {}
            Err(err) => return DslOutput::err(format!("Webhook validation failed: {err}")),
        }

        let trigger_kind = graph
            .nodes
            .first()
            .map(|n| {
                if n.kind.contains("webhook") {
                    "webhook"
                } else if n.kind.contains("schedule") {
                    "schedule"
                } else if n.kind.contains("function") {
                    "function"
                } else {
                    "manual"
                }
            })
            .unwrap_or("manual");

        let display_title = if title.is_empty() { &name } else { title };
        // --description flag takes precedence; fall back to description embedded in graph JSON
        let effective_description = if !description.trim().is_empty() {
            description.trim().to_string()
        } else {
            graph.description.as_deref().unwrap_or("").to_string()
        };

        match self.platform.projects.upsert_pipeline_definition(
            &self.owner,
            &self.project,
            file_rel_path,
            display_title,
            &effective_description,
            trigger_kind,
            &graph_source,
        ) {
            Ok(meta) => {
                let mut out = DslOutput::new_ok();
                out.push(DslLine::success(format!(
                    "Pipeline '{}' registered ({} nodes). Use 'activate pipeline {}' to make it live.",
                    meta.file_rel_path,
                    graph.nodes.len(),
                    meta.file_rel_path
                )));
                // Emit non-fatal warnings for unknown config keys (likely flag typos).
                for w in validate_graph_flags(&graph, &node_definitions) {
                    out.push(DslLine::muted(format!("⚠ {}", w)));
                }
                out
            }
            Err(e) => DslOutput::err(format!("Error: {}", e.message)),
        }
    }

    async fn cmd_patch(
        &self,
        file_rel_path: &str,
        node_id: &str,
        flags: HashMap<String, Value>,
        body: Option<&str>,
    ) -> DslOutput {
        if file_rel_path.is_empty() || node_id.is_empty() {
            return DslOutput::err(
                "patch: usage: patch pipeline <file_rel_path> node <id> [--flag value...]",
            );
        }

        let meta = match self.platform.projects.get_pipeline_meta_by_file_id(
            &self.owner,
            &self.project,
            file_rel_path,
        ) {
            Ok(Some(m)) => m,
            Ok(None) => return DslOutput::err(format!("Pipeline '{file_rel_path}' not found")),
            Err(e) => return DslOutput::err(format!("Error: {}", e.message)),
        };

        let source = match self.platform.projects.read_pipeline_source(
            &self.owner,
            &self.project,
            &meta.file_rel_path,
        ) {
            Ok(s) => s,
            Err(e) => return DslOutput::err(format!("Error reading pipeline: {}", e.message)),
        };

        let mut graph: crate::pipeline::PipelineGraph = match serde_json::from_str(&source) {
            Ok(g) => g,
            Err(e) => return DslOutput::err(format!("Parse error: {e}")),
        };

        // Find node index: first try exact ID, then kind-based addressing
        let node_idx = if let Some(i) = graph.nodes.iter().position(|n| n.id == node_id) {
            i
        } else {
            let (kind_ref, explicit_idx) = parse_node_kind_ref(node_id);
            let norm_ref = kind_ref.strip_prefix("n.").unwrap_or(&kind_ref);
            let candidates: Vec<usize> = graph
                .nodes
                .iter()
                .enumerate()
                .filter(|(_, n)| n.kind.strip_prefix("n.").unwrap_or(&n.kind) == norm_ref)
                .map(|(i, _)| i)
                .collect();
            match (candidates.len(), explicit_idx) {
                (0, _) => {
                    return DslOutput::err(format!(
                        "Node '{node_id}' not found in pipeline '{file_rel_path}'"
                    ));
                }
                (1, None) | (1, Some(0)) => candidates[0],
                (_, Some(idx)) if idx < candidates.len() => candidates[idx],
                (_, Some(idx)) => {
                    return DslOutput::err(format!(
                        "Kind '{kind_ref}' has {} node(s) — index {idx} is out of range",
                        candidates.len()
                    ));
                }
                (n, None) => {
                    return DslOutput::err(format!(
                        "Kind '{kind_ref}' matches {n} nodes — use {kind_ref}[0], {kind_ref}[1], etc. to specify which"
                    ));
                }
            }
        };
        let node = &mut graph.nodes[node_idx];
        let node_kind = node.kind.clone();

        // Build raw_flag_key → config_key maps for all DSL flag kinds so that flags like
        // --credential (raw key "credential") correctly write to config_key "credential_id",
        // --claim → "claims" (KeyValuePairs), --roles → ["a","b"] (CommaSeparatedList), etc.
        let (kv_config_keys, comma_list_config_keys, scalar_config_keys): (
            std::collections::HashMap<String, String>,
            std::collections::HashMap<String, String>,
            std::collections::HashMap<String, String>,
        ) = {
            let defs = crate::pipeline::nodes::builtin_node_definitions();
            let node_def = defs.iter().find(|d| d.kind == node_kind);
            let flag_key = |f: &crate::pipeline::model::DslFlag| {
                f.flag.trim_start_matches("--").replace('-', "_")
            };
            let kv = node_def
                .map(|d| {
                    d.dsl_flags
                        .iter()
                        .filter(|f| f.kind == crate::pipeline::model::DslFlagKind::KeyValuePairs)
                        .map(|f| (flag_key(f), f.config_key.clone()))
                        .collect()
                })
                .unwrap_or_default();
            let csv = node_def
                .map(|d| {
                    d.dsl_flags
                        .iter()
                        .filter(|f| {
                            matches!(
                                f.kind,
                                crate::pipeline::model::DslFlagKind::CommaSeparatedList
                                    | crate::pipeline::model::DslFlagKind::RepeatedList
                            )
                        })
                        .map(|f| (flag_key(f), f.config_key.clone()))
                        .collect()
                })
                .unwrap_or_default();
            // Scalar and Bool flags: flag name may differ from config key (e.g. --credential → credential_id).
            let scalar = node_def
                .map(|d| {
                    d.dsl_flags
                        .iter()
                        .filter(|f| {
                            matches!(
                                f.kind,
                                crate::pipeline::model::DslFlagKind::Scalar
                                    | crate::pipeline::model::DslFlagKind::Bool
                            )
                        })
                        .map(|f| (flag_key(f), f.config_key.clone()))
                        .collect()
                })
                .unwrap_or_default();
            (kv, csv, scalar)
        };

        if let Value::Object(ref mut cfg) = node.config {
            for (k, v) in &flags {
                if let Some(config_key) = kv_config_keys.get(k) {
                    // KeyValuePairs: parse each "key=value" string and merge into the map.
                    // v may be a single string or an array (when flag repeated multiple times).
                    let items: Vec<&str> = match v {
                        Value::Array(arr) => arr.iter().filter_map(|x| x.as_str()).collect(),
                        Value::String(s) => vec![s.as_str()],
                        _ => vec![],
                    };
                    let entry = cfg
                        .entry(config_key.clone())
                        .or_insert_with(|| Value::Object(serde_json::Map::new()));
                    if let Value::Object(m) = entry {
                        for pair in items {
                            let (pk, pv) = if let Some(eq) = pair.find('=') {
                                (&pair[..eq], &pair[eq + 1..])
                            } else {
                                (pair, "")
                            };
                            m.insert(pk.to_string(), json!(pv));
                        }
                    }
                } else if let Some(config_key) = comma_list_config_keys.get(k) {
                    // CommaSeparatedList: split "a,b,c" → ["a","b","c"].
                    // parse_flags_for_patch stored it as a raw string via coerce_scalar_value.
                    let csv = match v {
                        Value::String(s) => s.as_str(),
                        _ => {
                            // Already an array (or unexpected type) — store as-is.
                            cfg.insert(config_key.clone(), v.clone());
                            continue;
                        }
                    };
                    let arr: Vec<Value> = csv.split(',').map(|s| json!(s.trim())).collect();
                    cfg.insert(config_key.clone(), Value::Array(arr));
                } else {
                    // Scalar/Bool: map flag key → config_key (e.g. "credential" → "credential_id").
                    // Fall back to the raw key for unknown/custom config keys.
                    let config_key = scalar_config_keys
                        .get(k)
                        .cloned()
                        .unwrap_or_else(|| k.clone());
                    cfg.insert(config_key, v.clone());
                }
            }
            if let Some(body_val) = body {
                let body_key = if node.kind.contains("pg.query") {
                    "query"
                } else if node.kind.contains("script") {
                    "source"
                } else {
                    "body"
                };
                cfg.insert(body_key.to_string(), json!(body_val));
            }
        }

        let new_source = match serde_json::to_string_pretty(&graph) {
            Ok(s) => s,
            Err(e) => return DslOutput::err(format!("Serialize error: {e}")),
        };

        let trigger_kind = graph
            .nodes
            .first()
            .map(|n| {
                if n.kind.contains("webhook") {
                    "webhook"
                } else if n.kind.contains("schedule") {
                    "schedule"
                } else if n.kind.contains("function") {
                    "function"
                } else {
                    "manual"
                }
            })
            .unwrap_or("manual");

        match self.platform.projects.upsert_pipeline_definition(
            &self.owner,
            &self.project,
            &meta.file_rel_path,
            &meta.title,
            &meta.description,
            trigger_kind,
            &new_source,
        ) {
            Ok(_) => {
                let mut out = DslOutput::new_ok();
                out.push(DslLine::success(format!(
                    "Node '{node_id}' in pipeline '{file_rel_path}' updated."
                )));
                out
            }
            Err(e) => DslOutput::err(format!("Error: {}", e.message)),
        }
    }

    async fn cmd_activate(&self, file_rel_path: &str) -> DslOutput {
        if file_rel_path.is_empty() {
            return DslOutput::err("activate: pipeline file_rel_path is required");
        }

        match self.platform.projects.activate_pipeline_definition(
            &self.owner,
            &self.project,
            file_rel_path,
        ) {
            Ok(meta) => {
                let _ = self.platform.pipeline_runtime.refresh_pipeline(
                    &self.owner,
                    &self.project,
                    file_rel_path,
                );
                let mut out = DslOutput::new_ok();
                out.push(DslLine::success(format!(
                    "Pipeline '{}' activated.",
                    meta.file_rel_path
                )));
                out
            }
            Err(e) => DslOutput::err(format!("Error: {}", e.message)),
        }
    }

    async fn cmd_deactivate(&self, file_rel_path: &str) -> DslOutput {
        if file_rel_path.is_empty() {
            return DslOutput::err("deactivate: pipeline file_rel_path is required");
        }

        match self.platform.projects.deactivate_pipeline_definition(
            &self.owner,
            &self.project,
            file_rel_path,
        ) {
            Ok(meta) => {
                let _ = self.platform.pipeline_runtime.refresh_pipeline(
                    &self.owner,
                    &self.project,
                    file_rel_path,
                );
                let mut out = DslOutput::new_ok();
                out.push(DslLine::success(format!(
                    "Pipeline '{}' deactivated.",
                    meta.file_rel_path
                )));
                out
            }
            Err(e) => DslOutput::err(format!("Error: {}", e.message)),
        }
    }

    async fn cmd_execute(&self, file_rel_path: &str, input: Value) -> DslOutput {
        if file_rel_path.is_empty() {
            return DslOutput::err("execute: pipeline file_rel_path is required");
        }

        let meta = match self.platform.projects.get_pipeline_meta_by_file_id(
            &self.owner,
            &self.project,
            file_rel_path,
        ) {
            Ok(Some(m)) => m,
            Ok(None) => return DslOutput::err(format!("Pipeline '{file_rel_path}' not found")),
            Err(e) => return DslOutput::err(format!("Error: {}", e.message)),
        };
        if meta.active_hash.is_none() {
            return DslOutput::err(format!(
                "Pipeline '{file_rel_path}' is not active. Use 'activate pipeline {file_rel_path}' first."
            ));
        }

        let source = match self.platform.projects.read_active_pipeline_source(
            &self.owner,
            &self.project,
            &meta,
        ) {
            Ok(s) => s,
            Err(e) => return DslOutput::err(format!("Error: {}", e.message)),
        };

        let graph: crate::pipeline::PipelineGraph = match serde_json::from_str(&source) {
            Ok(g) => g,
            Err(e) => return DslOutput::err(format!("Parse error: {e}")),
        };

        let ctx = crate::pipeline::PipelineContext {
            owner: self.owner.clone(),
            project: self.project.clone(),
            pipeline: graph.id.clone(),
            request_id: format!(
                "dsl-exec-{}",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis()
            ),
            route: Default::default(),
            input,
            trigger: None,
            placeholder: None,
        };

        let engine = crate::pipeline::BasicPipelineEngine::new(
            Arc::new(crate::language::DenoSandboxEngine::default()),
            crate::rwe::resolve_engine_or_default(None),
            Some(self.platform.credentials.clone()),
        )
        .with_platform(self.platform.clone())
        .with_ws_hub(self.platform.ws_hub.clone())
        .with_state_bus(self.platform.state_bus.clone())
        .with_data_root(self.platform.config.data_root.clone())
        .with_template_root(
            self.platform
                .projects
                .get_project_template_root(&self.owner, &self.project)
                .ok(),
        );

        use crate::pipeline::PipelineEngine;
        match engine.execute_async(&graph, &ctx).await {
            Ok(output) => {
                self.platform.pipeline_hits.record_success(
                    &self.owner,
                    &self.project,
                    &meta.file_rel_path,
                );
                let mut out = DslOutput::new_ok();
                out.push(DslLine::success(format!(
                    "Pipeline '{}' executed.",
                    meta.file_rel_path
                )));
                let result_str = serde_json::to_string_pretty(&output.value)
                    .unwrap_or_else(|_| output.value.to_string());
                for line in result_str.lines().take(20) {
                    out.push(DslLine::info(line.to_string()));
                }
                if !output.node_trace.is_empty() {
                    let total_ms: u64 = output.node_trace.iter().map(|e| e.duration_ms).sum();
                    out.push(DslLine::muted(format!(
                        "--- node trace ({} nodes, {}ms total) ---",
                        output.node_trace.len(),
                        total_ms
                    )));
                    for entry in &output.node_trace {
                        let marker = if entry.error.is_none() { "✓" } else { "✗" };
                        let err_part = entry
                            .error
                            .as_deref()
                            .map(|e| format!("  → {}", e))
                            .unwrap_or_default();
                        out.push(DslLine::info(format!(
                            "  {}  {}  ({})  {}ms{}",
                            marker, entry.node_id, entry.node_kind, entry.duration_ms, err_part
                        )));
                    }
                }
                out
            }
            Err(e) => {
                self.platform.pipeline_hits.record_failure(
                    &self.owner,
                    &self.project,
                    &meta.file_rel_path,
                    "dsl.execute",
                    e.code,
                    &e.message,
                );
                let node_ctx = match (&e.node_id, &e.node_kind) {
                    (Some(id), Some(kind)) => format!(" [node {} ({})]", id, kind),
                    _ => String::new(),
                };
                DslOutput::err(format!(
                    "Execution error: {} — {}{}",
                    e.code, e.message, node_ctx
                ))
            }
        }
    }

    async fn cmd_run(
        &self,
        body: &str,
        dry_run: bool,
        initial_input: Option<serde_json::Value>,
    ) -> DslOutput {
        if body.is_empty() {
            return DslOutput::err(
                "run: pipeline body is required. Example: run | trigger.manual | script -- return { ok: true };",
            );
        }

        let node_definitions = self.node_definitions();
        match build_pipeline_graph_with_definitions("ephemeral", body, &node_definitions) {
            Ok(graph) => {
                if dry_run {
                    let mut out = DslOutput::new_ok();
                    out.push(DslLine::info("Dry run — parsed pipeline graph:"));
                    match serde_json::to_string_pretty(&graph) {
                        Ok(s) => {
                            for line in s.lines() {
                                out.push(DslLine::muted(line.to_string()));
                            }
                        }
                        Err(e) => out.push(DslLine::error(format!("Serialize error: {e}"))),
                    }
                    return out;
                }

                let ctx = crate::pipeline::PipelineContext {
                    owner: self.owner.clone(),
                    project: self.project.clone(),
                    pipeline: graph.id.clone(),
                    request_id: format!(
                        "dsl-run-{}",
                        std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_millis()
                    ),
                    route: Default::default(),
                    input: initial_input.unwrap_or_else(|| json!({})),
                    trigger: None,
                    placeholder: None,
                };

                let engine = crate::pipeline::BasicPipelineEngine::new(
                    Arc::new(crate::language::DenoSandboxEngine::default()),
                    crate::rwe::resolve_engine_or_default(None),
                    Some(self.platform.credentials.clone()),
                )
                .with_platform(self.platform.clone())
                .with_ws_hub(self.platform.ws_hub.clone())
                .with_state_bus(self.platform.state_bus.clone())
                .with_data_root(self.platform.config.data_root.clone())
                .with_template_root(
                    self.platform
                        .projects
                        .get_project_template_root(&self.owner, &self.project)
                        .ok(),
                );

                use crate::pipeline::PipelineEngine;
                match engine.execute_async(&graph, &ctx).await {
                    Ok(output) => {
                        let mut out = DslOutput::new_ok();
                        out.push(DslLine::success(format!(
                            "Ephemeral pipeline executed ({} nodes).",
                            graph.nodes.len()
                        )));
                        let result_str = serde_json::to_string_pretty(&output.value)
                            .unwrap_or_else(|_| output.value.to_string());
                        for line in result_str.lines().take(20) {
                            out.push(DslLine::info(line.to_string()));
                        }
                        if !output.node_trace.is_empty() {
                            let total_ms: u64 =
                                output.node_trace.iter().map(|e| e.duration_ms).sum();
                            out.push(DslLine::muted(format!(
                                "--- node trace ({} nodes, {}ms total) ---",
                                output.node_trace.len(),
                                total_ms
                            )));
                            for entry in &output.node_trace {
                                let marker = if entry.error.is_none() { "✓" } else { "✗" };
                                let err_part = entry
                                    .error
                                    .as_deref()
                                    .map(|e| format!("  → {}", e))
                                    .unwrap_or_default();
                                out.push(DslLine::info(format!(
                                    "  {}  {}  ({})  {}ms{}",
                                    marker,
                                    entry.node_id,
                                    entry.node_kind,
                                    entry.duration_ms,
                                    err_part
                                )));
                            }
                        }
                        out
                    }
                    Err(e) => {
                        let node_ctx = match (&e.node_id, &e.node_kind) {
                            (Some(id), Some(kind)) => format!(" [node {} ({})]", id, kind),
                            _ => String::new(),
                        };
                        DslOutput::err(format!("Run error: {} — {}{}", e.code, e.message, node_ctx))
                    }
                }
            }
            Err(e) => DslOutput::err(format!("Parse error: {e}")),
        }
    }

    async fn cmd_delete(&self, kind: &str, name: &str) -> DslOutput {
        DslOutput::err(format!(
            "delete: not supported via DSL for safety. \
             Use the UI to delete {} '{}'. \
             You can use 'deactivate pipeline {}' to take it offline.",
            kind, name, name
        ))
    }

    async fn cmd_git(&self, subcommand: &str, args: Vec<String>, body: Option<&str>) -> DslOutput {
        let allowed = ["status", "log", "diff", "add", "commit"];
        if !allowed.contains(&subcommand) {
            return DslOutput::err(format!(
                "git: '{}' is not allowed. Allowed subcommands: status, log, diff, add, commit",
                subcommand
            ));
        }

        let layout = match self
            .platform
            .file
            .ensure_project_layout(&self.owner, &self.project)
        {
            Ok(l) => l,
            Err(e) => return DslOutput::err(format!("Error: {}", e.message)),
        };

        let mut cmd = std::process::Command::new("git");

        // On commit: inject committer identity from user profile.
        // git global options (-c) must come BEFORE the subcommand.
        if subcommand == "commit" {
            // Fetch stored git identity (best-effort; fall back to owner slug).
            let (git_name, git_email) = self
                .platform
                .users
                .get_user(&self.owner)
                .ok()
                .flatten()
                .map(|u| {
                    let name = if u.git_name.is_empty() {
                        u.owner.clone()
                    } else {
                        u.git_name
                    };
                    let email = if u.git_email.is_empty() {
                        format!("{}@zebflow.local", u.owner)
                    } else {
                        u.git_email
                    };
                    (name, email)
                })
                .unwrap_or_else(|| (self.owner.clone(), format!("{}@zebflow.local", self.owner)));

            // -c flags before subcommand (git global options).
            cmd.arg("-c").arg(format!("user.name={git_name}"));
            cmd.arg("-c").arg(format!("user.email={git_email}"));
        }

        cmd.arg(subcommand);

        if subcommand == "commit" {
            // Filter out any -c user.name / -c user.email the LLM may have injected.
            let mut skip_next = false;
            for arg in &args {
                if skip_next {
                    skip_next = false;
                    continue;
                }
                if arg == "-c" {
                    skip_next = true;
                    continue;
                }
                if arg.starts_with("user.name=") || arg.starts_with("user.email=") {
                    continue;
                }
                cmd.arg(arg);
            }
        } else {
            for arg in &args {
                cmd.arg(arg);
            }
        }

        // For commit with body: use body as commit message.
        // Strip any Co-authored-by lines injected by AI agents before committing.
        if subcommand == "commit" {
            if let Some(msg) = body {
                let cleaned: String = msg
                    .lines()
                    .filter(|l| !l.trim_start().to_lowercase().starts_with("co-authored-by:"))
                    .collect::<Vec<_>>()
                    .join("\n")
                    .trim_end()
                    .to_string();
                cmd.arg("-m").arg(cleaned);
            }
        }

        cmd.current_dir(&layout.repo_dir);

        match cmd.output() {
            Ok(output) => {
                let mut out = DslOutput::new_ok();
                let stdout = String::from_utf8_lossy(&output.stdout);
                let stderr = String::from_utf8_lossy(&output.stderr);

                for line in stdout.lines() {
                    out.push(DslLine::info(line.to_string()));
                }
                if !stderr.is_empty() {
                    for line in stderr.lines() {
                        out.push(DslLine::muted(line.to_string()));
                    }
                }
                if stdout.is_empty() && stderr.is_empty() {
                    out.push(DslLine::muted("(no output)"));
                }
                if !output.status.success() {
                    out.ok = false;
                }
                out
            }
            Err(e) => DslOutput::err(format!("git error: {e}")),
        }
    }

    fn cmd_node_help(&self, kind: &str) -> DslOutput {
        if kind.is_empty() {
            return DslOutput::err(
                "node help: kind is required. Example: node help trigger.webhook",
            );
        }
        self.describe_node(kind)
    }

    fn cmd_credential_blocked(&self, reason: &str) -> DslOutput {
        let mut out = DslOutput::new_ok();
        out.push(DslLine::error(reason.to_string()));
        out.push(DslLine::muted(
            "Use the Credentials UI at /projects/{owner}/{project}/credentials to manage secrets.",
        ));
        out
    }
}

/// Parse a node kind reference with optional index suffix.
/// "pg.query" → ("pg.query", None)
/// "pg.query[1]" → ("pg.query", Some(1))
fn parse_node_kind_ref(s: &str) -> (String, Option<usize>) {
    if let Some(bracket_pos) = s.rfind('[') {
        if s.ends_with(']') {
            let kind = s[..bracket_pos].to_string();
            let idx_str = &s[bracket_pos + 1..s.len() - 1];
            if let Ok(idx) = idx_str.parse::<usize>() {
                return (kind, Some(idx));
            }
        }
    }
    (s.to_string(), None)
}

fn truncate(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        format!("{}…", &s[..max.saturating_sub(1)])
    }
}

/// Config keys that are valid on any node and should not trigger unknown-key warnings.
const GLOBAL_CONFIG_KEYS: &[&str] = &[
    "title",
    "path",
    "method",
    "route",
    "credential_id",
    "sql",
    "query",
    "source",
    "body",
    "markup",
    "template_path",
    "template_id",
    "credential_id_expr",
    "query_expr",
    "params_path",
    "params_expr",
    "room",
    "event",
    "ui",
];

/// Validate node config keys against declared DSL flags for each node kind.
/// Returns a list of warning strings for unknown config keys (likely typos).
fn validate_graph_flags(
    graph: &crate::pipeline::PipelineGraph,
    definitions: &[crate::pipeline::NodeDefinition],
) -> Vec<String> {
    let defs: HashMap<String, &crate::pipeline::NodeDefinition> =
        definitions.iter().map(|d| (d.kind.clone(), d)).collect();
    let mut warnings = vec![];
    for node in &graph.nodes {
        let Some(def) = defs.get(&node.kind) else {
            continue;
        };
        // Only check nodes that have declared flags; skip nodes with empty flag list.
        if def.dsl_flags.is_empty() {
            continue;
        }
        let known_keys: HashSet<&str> = def
            .dsl_flags
            .iter()
            .map(|f| f.config_key.as_str())
            .collect();

        let global_keys: HashSet<&str> = GLOBAL_CONFIG_KEYS.iter().copied().collect();

        if let Some(obj) = node.config.as_object() {
            for key in obj.keys() {
                if global_keys.contains(key.as_str()) {
                    continue;
                }
                if !known_keys.contains(key.as_str()) {
                    warnings.push(format!(
                        "node {} ({}): unknown config key '{}' — check flag spelling. Known: {}",
                        node.id,
                        node.kind,
                        key,
                        known_keys.iter().cloned().collect::<Vec<_>>().join(", ")
                    ));
                }
            }
        }
    }
    warnings
}

#[allow(dead_code)]
fn summarize_config(config: &Value) -> String {
    let Some(map) = config.as_object() else {
        return String::new();
    };
    let parts: Vec<String> = map
        .iter()
        .take(3)
        .map(|(k, v)| {
            let val_str = match v {
                Value::String(s) => {
                    if s.len() > 30 {
                        format!("{}…", &s[..29])
                    } else {
                        s.clone()
                    }
                }
                other => other.to_string(),
            };
            format!("{}={}", k, val_str)
        })
        .collect();
    parts.join(" ")
}