zacor 0.1.0

Package manager and dispatcher for zr — install, manage, and run modular CLI packages
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
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
use crate::config;
use crate::error::*;
use crate::package_definition::{
    ArgType, ArgumentDefinition, CommandDefinition, OutputDeclaration, OutputType,
    PackageDefinition,
};
use crate::paths;
use crate::receipt::{self, Receipt};
use clap::ArgAction;
use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, BufWriter, IsTerminal, Write};
use std::net::TcpStream;
use std::path::Path;
use std::process::{self, Command, Stdio};
use std::sync::{Arc, Mutex};
use zacor_package::protocol::{self as proto, Message};

/// A resolved package ready for dispatch.
pub struct ResolvedPackage {
    pub receipt: Receipt,
    pub definition: PackageDefinition,
    pub version: String,
}


// ─── Resolve Phase ───────────────────────────────────────────────────

fn resolve(home: &Path, name: &str) -> Result<ResolvedPackage> {
    let receipt = receipt::read(home, name)?
        .ok_or_else(|| anyhow!("package '{}' not found\nhint: install it with `zacor install <source>`", name))?;

    if !receipt.active {
        bail!("package '{}' is disabled\nhint: run `zacor enable {}`", name, name);
    }

    let version = receipt.current.clone();
    let def_path = paths::definition_path(home, name, &version);

    if !def_path.exists() {
        bail!(
            "package.yaml for '{}' v{} not found in store\nhint: reinstall with `zacor install <source>`",
            name, version
        );
    }

    let definition = crate::package_definition::parse_file(&def_path)
        .with_context(|| format!("corrupt package.yaml for '{}' v{}\nhint: reinstall with `zacor install <source>`", name, version))?;

    Ok(ResolvedPackage {
        receipt,
        definition,
        version,
    })
}

// ─── Clap Command Builder ───────────────────────────────────────────

/// Build a `clap::Command` from a `PackageDefinition`, mapping commands,
/// args, and the `default` command convention to clap's builder API.
pub fn build_clap_command(def: &PackageDefinition) -> clap::Command {
    let mut cmd = clap::Command::new(def.name.clone())
        .version(def.version.clone())
        .disable_help_subcommand(true);

    if let Some(ref desc) = def.description {
        cmd = cmd.about(desc.clone());
    }

    let has_default = def.commands.contains_key("default");
    let named: Vec<(&String, &CommandDefinition)> = def
        .commands
        .iter()
        .filter(|(k, _)| k.as_str() != "default")
        .collect();
    let has_named = !named.is_empty();

    match (has_default, has_named) {
        (true, false) => {
            // Single default: hoist args to root, no subcommand layer
            let default_cmd = &def.commands["default"];
            if def.description.is_none()
                && let Some(ref desc) = default_cmd.description
            {
                cmd = cmd.about(desc.clone());
            }
            let has_rest = default_cmd.args.values().any(|a| a.rest);
            for (name, arg_def) in &default_cmd.args {
                cmd = cmd.arg(build_arg(name, arg_def));
            }
            if has_rest {
                cmd = cmd.trailing_var_arg(true);
            }
        }
        (true, true) => {
            // Default + named: hoist default args, named become subcommands
            let default_cmd = &def.commands["default"];
            let has_rest = default_cmd.args.values().any(|a| a.rest);
            for (name, arg_def) in &default_cmd.args {
                cmd = cmd.arg(build_arg(name, arg_def));
            }
            if has_rest {
                cmd = cmd.trailing_var_arg(true);
            }
            cmd = cmd.subcommand_required(false);
            for (name, cmd_def) in &named {
                cmd = cmd.subcommand(build_subcommand(name, cmd_def));
            }
        }
        (false, _) => {
            // Named only: subcommand required
            cmd = cmd.subcommand_required(true);
            for (name, cmd_def) in &named {
                cmd = cmd.subcommand(build_subcommand(name, cmd_def));
            }
        }
    }

    cmd
}

/// Build a clap subcommand from a `CommandDefinition`, recursively
/// mapping nested commands.
fn build_subcommand(name: &str, def: &CommandDefinition) -> clap::Command {
    let mut cmd = clap::Command::new(name.to_string());

    if let Some(ref desc) = def.description {
        cmd = cmd.about(desc.clone());
    }

    let has_rest = def.args.values().any(|a| a.rest);
    for (arg_name, arg_def) in &def.args {
        cmd = cmd.arg(build_arg(arg_name, arg_def));
    }
    if has_rest {
        cmd = cmd.trailing_var_arg(true);
    }

    for (sub_name, sub_def) in &def.commands {
        cmd = cmd.subcommand(build_subcommand(sub_name, sub_def));
    }

    if !def.commands.is_empty() {
        cmd = cmd.subcommand_required(true);
    }

    cmd
}

/// Build a `clap::Arg` from an `ArgumentDefinition`, mapping ArgType
/// to clap value parsers and handling flag vs positional.
fn build_arg(name: &str, def: &ArgumentDefinition) -> clap::Arg {
    let mut arg = clap::Arg::new(name.to_string());

    // Flag vs positional — bools always become --flags
    if let Some(ref flag) = def.flag {
        arg = arg.long(flag.clone());
    } else if def.arg_type == ArgType::Bool {
        arg = arg.long(name.to_string());
    }

    // Type mapping
    match def.arg_type {
        ArgType::Bool => {
            arg = arg.action(ArgAction::SetTrue);
        }
        ArgType::Number | ArgType::Integer => {
            arg = arg.value_parser(parse_number);
        }
        ArgType::Path => {
            arg = arg.value_hint(clap::ValueHint::AnyPath);
        }
        ArgType::Choice => {
            if let Some(ref values) = def.values {
                arg = arg.value_parser(
                    clap::builder::PossibleValuesParser::new(values.clone()),
                );
            }
        }
        ArgType::String => {}
    }

    // Rest arg: consume all remaining tokens
    if def.rest {
        arg = arg.num_args(0..);
    }

    // Required (only non-Bool args without defaults)
    if def.arg_type != ArgType::Bool && def.required && def.default.is_none() {
        arg = arg.required(true);
    }

    // Default value (for required args with defaults — inserted at flag priority)
    if def.required
        && let Some(ref default) = def.default
    {
        arg = arg.default_value(config::yaml_value_to_string(default));
    }

    arg
}

fn parse_number(s: &str) -> std::result::Result<String, String> {
    s.parse::<f64>()
        .map_err(|_| format!("'{}' is not a valid number", s))?;
    Ok(s.to_string())
}

// ─── Clap Parsing ───────────────────────────────────────────────────

/// Parse CLI args using a clap Command built from a PackageDefinition.
/// Returns (command_path, parsed_flags) where command_path is like
/// "default", "transcribe", or "transcribe.batch".
fn clap_parse(
    cmd: clap::Command,
    pkg_name: &str,
    args: &[String],
    def: &PackageDefinition,
) -> std::result::Result<(String, BTreeMap<String, String>), clap::Error> {
    let mut full_args = vec![pkg_name.to_string()];
    full_args.extend_from_slice(args);

    let matches = cmd.try_get_matches_from(full_args)?;

    // Check for subcommand match
    if let Some((sub_name, sub_matches)) = matches.subcommand()
        && let Some(cmd_def) = def.commands.get(sub_name)
    {
        let (sub_path, flags) = extract_from_command(sub_matches, cmd_def);
        let path = if sub_path.is_empty() {
            sub_name.to_string()
        } else {
            format!("{}.{}", sub_name, sub_path)
        };
        return Ok((path, flags));
    }

    // No subcommand matched — use default command
    if let Some(default_cmd) = def.commands.get("default") {
        let flags = extract_args(&matches, &default_cmd.args);
        return Ok(("default".to_string(), flags));
    }

    // Should not reach here (clap would have errored for named-only)
    Ok(("default".to_string(), BTreeMap::new()))
}

/// Recursively extract the deepest matched subcommand and its args.
fn extract_from_command(
    matches: &clap::ArgMatches,
    cmd_def: &CommandDefinition,
) -> (String, BTreeMap<String, String>) {
    if let Some((sub_name, sub_matches)) = matches.subcommand()
        && let Some(sub_cmd_def) = cmd_def.commands.get(sub_name)
    {
        let (sub_path, flags) = extract_from_command(sub_matches, sub_cmd_def);
        let path = if sub_path.is_empty() {
            sub_name.to_string()
        } else {
            format!("{}.{}", sub_name, sub_path)
        };
        return (path, flags);
    }

    let flags = extract_args(matches, &cmd_def.args);
    (String::new(), flags)
}

/// Extract arg values from clap matches using the argument definitions.
fn extract_args(
    matches: &clap::ArgMatches,
    arg_defs: &BTreeMap<String, ArgumentDefinition>,
) -> BTreeMap<String, String> {
    let mut flags = BTreeMap::new();
    for (name, def) in arg_defs {
        if def.arg_type == ArgType::Bool {
            if matches.get_flag(name) {
                flags.insert(name.clone(), "true".to_string());
            }
        } else if def.rest {
            if let Some(vals) = matches.get_many::<String>(name) {
                let joined: String = vals.cloned().collect::<Vec<_>>().join(" ");
                if !joined.is_empty() {
                    flags.insert(name.clone(), joined);
                }
            }
        } else if let Some(val) = matches.get_one::<String>(name) {
            flags.insert(name.clone(), val.clone());
        }
    }
    flags
}

/// Look up a CommandDefinition by dot-separated path (e.g., "transcribe.batch").
fn find_command<'a>(
    commands: &'a BTreeMap<String, CommandDefinition>,
    path: &str,
) -> Result<&'a CommandDefinition> {
    let parts: Vec<&str> = path.split('.').collect();
    let mut current = commands;
    let mut cmd = None;
    for part in &parts {
        match current.get(*part) {
            Some(c) => {
                cmd = Some(c);
                current = &c.commands;
            }
            None => bail!("command '{}' not found", path),
        }
    }
    cmd.ok_or_else(|| anyhow!("empty command path"))
}

// ─── Build Env Vars ──────────────────────────────────────────────────
// Env var building and placeholder resolution are in crate::execute.

// ─── Execute Phase ───────────────────────────────────────────────────

/// Resolve the effective execution mode: receipt mode > execution.default > "command".
fn resolve_mode(resolved: &ResolvedPackage) -> receipt::Mode {
    // 1. Receipt mode takes priority
    if let Some(mode) = resolved.receipt.mode {
        return mode;
    }
    // 2. execution.default from package.yaml
    if let Some(ref exec) = resolved.definition.execution {
        if let Some(ref default) = exec.default {
            if let Ok(mode) = default.parse::<receipt::Mode>() {
                return mode;
            }
        }
    }
    // 3. Fallback to command
    receipt::Mode::Command
}

#[allow(clippy::too_many_arguments)]
fn execute(
    home: &Path,
    resolved: &ResolvedPackage,
    env_vars: &BTreeMap<String, String>,
    placeholders: &BTreeMap<String, String>,
    command_path: &str,
    command: &CommandDefinition,
    parsed_flags: &BTreeMap<String, String>,
    raw_json: bool,
    force_text: bool,
) -> Result<i32> {
    // Protocol packages use the new module protocol
    if resolved.definition.protocol {
        let mode = resolve_mode(resolved);
        if mode == receipt::Mode::Service && resolved.definition.service.is_some() {
            return execute_service(home, resolved, command_path, command, parsed_flags, raw_json, force_text);
        }
        return execute_protocol(home, resolved, command_path, command, parsed_flags, raw_json, force_text, env_vars);
    }

    // Legacy path: env vars + raw stdout
    execute_command(home, resolved, env_vars, placeholders, command, raw_json, force_text)
}

// ─── Shared Protocol Session ─────────────────────────────────────────

/// Send a protocol message to a shared writer.
fn send_message(
    writer: &Arc<Mutex<BufWriter<Box<dyn Write + Send>>>>,
    msg: &Message,
) -> Result<()> {
    let json = serde_json::to_string(msg).context("failed to serialize protocol message")?;
    let mut w = writer.lock().unwrap();
    writeln!(w, "{}", json).context("failed to write to module")?;
    w.flush().context("failed to flush module writer")
}

/// Forward the dispatcher's stdin as INPUT messages to the module.
/// Uses line-by-line reading to avoid splitting multi-byte UTF-8 sequences
/// at buffer boundaries. Correct for text and jsonl input types.
fn forward_stdin_as_input(writer: Arc<Mutex<BufWriter<Box<dyn Write + Send>>>>) {
    let stdin = std::io::stdin();
    let mut reader = BufReader::new(stdin.lock());
    let mut line = String::new();
    loop {
        line.clear();
        match reader.read_line(&mut line) {
            Ok(0) => break,       // EOF
            Ok(_) => {}
            Err(_) => break,
        }
        let msg = Message::Input(proto::Input {
            data: line.clone(),
            eof: false,
        });
        if send_message(&writer, &msg).is_err() {
            break;
        }
    }
    let eof = Message::Input(proto::Input {
        data: String::new(),
        eof: true,
    });
    let _ = send_message(&writer, &eof);
}

/// Run a protocol session over generic reader/writer.
/// Used by both command-mode (child stdio) and service-mode (TCP) dispatch.
pub(crate) fn run_protocol_session(
    reader: impl BufRead,
    writer: impl Write + Send + 'static,
    invoke_msg: &Message,
    command: &CommandDefinition,
    raw_json: bool,
    force_text: bool,
) -> Result<i32> {
    let has_input = match invoke_msg {
        Message::Invoke(inv) => inv.input,
        _ => false,
    };

    // Shared writer for module (input thread + capability responses)
    let module_writer: Arc<Mutex<BufWriter<Box<dyn Write + Send>>>> =
        Arc::new(Mutex::new(BufWriter::new(Box::new(writer))));
    send_message(&module_writer, invoke_msg)?;

    // Forward stdin as INPUT messages if the command declares input and stdin is piped
    if has_input {
        let w = module_writer.clone();
        std::thread::Builder::new()
            .name("zr-input-fwd".into())
            .spawn(move || forward_stdin_as_input(w))
            .context("failed to spawn input forwarding thread")?;
    }

    // Protocol message loop
    let is_tty = std::io::stdout().is_terminal();
    let render = !raw_json && command.output.is_some() && (force_text || is_tty);
    let streaming = command.output.as_ref().is_some_and(|o| o.stream);

    let mut records: Vec<serde_json::Value> = Vec::new();
    let mut exit_code: Option<i32> = None;
    let mut streaming_started = false;

    // Set up stdout for rendering/output
    let stdout_handle = std::io::stdout();
    let mut stdout_writer = BufWriter::new(stdout_handle.lock());

    for line in reader.lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => break,
        };
        if line.is_empty() {
            continue;
        }

        let msg: Message = match serde_json::from_str(&line) {
            Ok(m) => m,
            Err(_) => continue, // Ignore unknown message types per spec
        };

        match msg {
            Message::Output(output) => {
                if render && streaming {
                    // Streaming render: emit each row as it arrives
                    if !streaming_started {
                        if let Some(output_decl) = &command.output {
                            crate::render::render_streaming_header(output_decl, &mut stdout_writer);
                        }
                        streaming_started = true;
                    }
                    if let Some(output_decl) = &command.output {
                        crate::render::render_streaming_row(
                            &output.record,
                            output_decl,
                            &mut stdout_writer,
                        );
                    }
                } else if render {
                    // Batch: collect for render at end
                    records.push(output.record);
                } else {
                    // Raw JSONL (piped or --json): output just the record payload
                    let json = serde_json::to_string(&output.record)
                        .unwrap_or_default();
                    let _ = writeln!(stdout_writer, "{}", json);
                    let _ = stdout_writer.flush();
                }
            }
            Message::Progress(progress) => {
                if is_tty {
                    render_progress(progress.fraction);
                }
            }
            Message::CapabilityReq(req) => {
                let res = crate::capability_provider::handle(&req);
                if send_message(&module_writer, &Message::CapabilityRes(res)).is_err() {
                    break;
                }
            }
            Message::Done(done) => {
                if let Some(ref error) = done.error {
                    eprintln!("error: {}", error);
                }
                exit_code = Some(done.exit_code);
                break;
            }
            _ => {} // Ignore unexpected messages
        }
    }

    // Clear progress line if we rendered any
    if is_tty {
        eprint!("\r\x1b[K");
    }

    // Batch render collected records
    if render && !streaming && !records.is_empty() {
        if let Some(output_decl) = &command.output {
            match output_decl.resolved_output_type() {
                OutputType::Text => {
                    crate::render::render_text(&records, output_decl, &mut stdout_writer);
                }
                OutputType::Record => {
                    if let Some(record) = records.first() {
                        crate::render::render_record(record, output_decl, &mut stdout_writer);
                    }
                }
                OutputType::Table => {
                    crate::render::render_table(&records, output_decl, &mut stdout_writer);
                }
            }
        }
    }
    let _ = stdout_writer.flush();

    Ok(exit_code.unwrap_or(1))
}

// ─── Service Dispatch ────────────────────────────────────────────────

fn execute_service(
    home: &Path,
    resolved: &ResolvedPackage,
    command_path: &str,
    command: &CommandDefinition,
    parsed_flags: &BTreeMap<String, String>,
    raw_json: bool,
    force_text: bool,
) -> Result<i32> {
    let service = resolved.definition.service.as_ref().unwrap();
    let port = service.port.ok_or_else(|| {
        anyhow!(
            "service package '{}' must declare a port in service.port",
            resolved.definition.name
        )
    })?;

    // Ensure the service is running (starts daemon + service if needed)
    ensure_service_running(home, &resolved.definition.name, port)?;

    // Connect to the running service via TCP
    let stream = TcpStream::connect(format!("127.0.0.1:{}", port))
        .with_context(|| format!("failed to connect to service '{}' on port {}", resolved.definition.name, port))?;
    let reader = BufReader::new(stream.try_clone().context("failed to clone TCP stream")?);

    // Build INVOKE message
    let has_input = command.input.is_some();
    let invoke_msg = Message::Invoke(proto::Invoke::from_str_args(
        command_path,
        parsed_flags,
        has_input,
    ));

    // Run protocol session over TCP
    run_protocol_session(reader, stream, &invoke_msg, command, raw_json, force_text)
}

/// Ensure a service is running by contacting the daemon.
/// Starts the daemon lazily if it is not running.
fn ensure_service_running(home: &Path, name: &str, port: u16) -> Result<()> {
    // Try connecting to the service directly first (fast path)
    if TcpStream::connect(format!("127.0.0.1:{}", port)).is_ok() {
        return Ok(());
    }

    // Contact daemon, start it lazily if needed
    let client = crate::daemon_client::connect_or_start_daemon(home)?;

    // Ask daemon to start the service
    let response = crate::daemon_client::start_service(&client, name)?;
    if !response.ok {
        bail!(
            "failed to start service '{}': {}",
            name,
            response.error.unwrap_or_else(|| "unknown error".into())
        );
    }

    Ok(())
}

// ─── Protocol Dispatch ───────────────────────────────────────────────

fn execute_protocol(
    home: &Path,
    resolved: &ResolvedPackage,
    command_path: &str,
    command: &CommandDefinition,
    parsed_flags: &BTreeMap<String, String>,
    raw_json: bool,
    force_text: bool,
    env_vars: &BTreeMap<String, String>,
) -> Result<i32> {
    let binary_name = resolved.definition.binary.as_ref().ok_or_else(|| {
        anyhow!(
            "protocol package '{}' must have a binary",
            resolved.definition.name
        )
    })?;
    let bin_path = paths::store_binary_path(
        home,
        &resolved.definition.name,
        &resolved.version,
        binary_name,
    );
    if !bin_path.exists() {
        bail!(
            "binary '{}' not found for '{}' v{}\nhint: reinstall with `zacor install <source>`",
            binary_name,
            resolved.definition.name,
            resolved.version
        );
    }

    // Set up Job Object on Windows so child dies when zr exits
    #[cfg(windows)]
    let _job = crate::job_object::JobObject::setup().ok();

    // Spawn module with piped stdin/stdout, inherited stderr
    let mut child = Command::new(&bin_path)
        .envs(env_vars)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .with_context(|| {
            format!(
                "failed to spawn package '{}'",
                resolved.definition.name
            )
        })?;

    #[cfg(windows)]
    if let Some(ref job) = _job {
        let _ = job.assign(&child);
    }

    let child_stdin = child.stdin.take().unwrap();
    let child_stdout = child.stdout.take().unwrap();

    // Build INVOKE message
    let has_input = command.input.is_some();
    let invoke_msg = Message::Invoke(proto::Invoke::from_str_args(
        command_path,
        parsed_flags,
        has_input,
    ));

    // Run protocol session over child stdio
    let reader = BufReader::new(child_stdout);
    let result = run_protocol_session(reader, child_stdin, &invoke_msg, command, raw_json, force_text);

    // If session ended without a DONE (e.g. crash), use process exit code
    let _ = child.wait();
    result
}

/// Render a progress bar on stderr (in-place update).
fn render_progress(fraction: f64) {
    let clamped = fraction.clamp(0.0, 1.0);
    let pct = (clamped * 100.0) as u32;
    let filled = (clamped * 20.0) as usize;
    let bar: String = "".repeat(filled) + &"".repeat(20 - filled);
    eprint!("\r{} {:>3}%", bar, pct);
}

// ─── Legacy Helpers ──────────────────────────────────────────────────

fn should_render(output: &Option<OutputDeclaration>, raw_json: bool, force_text: bool) -> bool {
    !raw_json && output.is_some() && (force_text || std::io::stdout().is_terminal())
}

fn execute_command(
    home: &Path,
    resolved: &ResolvedPackage,
    env_vars: &BTreeMap<String, String>,
    placeholders: &BTreeMap<String, String>,
    command: &CommandDefinition,
    raw_json: bool,
    force_text: bool,
) -> Result<i32> {
    let render = should_render(&command.output, raw_json, force_text);

    if let Some(ref binary_name) = resolved.definition.binary {
        // Binary package: exec with env vars and empty argv
        let bin_path = paths::store_binary_path(
            home,
            &resolved.definition.name,
            &resolved.version,
            binary_name,
        );
        if !bin_path.exists() {
            bail!(
                "binary '{}' not found for '{}' v{}\nhint: reinstall with `zacor install <source>`",
                binary_name, resolved.definition.name, resolved.version
            );
        }
        let output_decl = if render { command.output.as_ref() } else { None };
        exec_binary(&bin_path, &resolved.definition.name, env_vars, output_decl)
    } else if let Some(ref invoke) = command.invoke {
        crate::execute::exec_invoke(invoke, env_vars, placeholders)
    } else {
        bail!(
            "package '{}' has no binary and no invoke template for this command",
            resolved.definition.name
        );
    }
}

fn exec_binary(
    bin: &Path,
    name: &str,
    env_vars: &BTreeMap<String, String>,
    output: Option<&OutputDeclaration>,
) -> Result<i32> {
    #[cfg(unix)]
    if output.is_none() {
        use std::os::unix::process::CommandExt;
        let err = Command::new(bin)
            .envs(env_vars)
            .stdin(process::Stdio::inherit())
            .stdout(process::Stdio::inherit())
            .stderr(process::Stdio::inherit())
            .exec();
        return Err(anyhow!(err).context(format!("failed to exec package '{}'", name)));
    }

    #[cfg(windows)]
    let _job = match crate::job_object::JobObject::setup() {
        Ok(job) => Some(job),
        Err(e) => {
            eprintln!("warning: failed to create Job Object: {:#}", e);
            None
        }
    };

    let stdout_cfg = if output.is_some() {
        process::Stdio::piped()
    } else {
        process::Stdio::inherit()
    };

    let mut child = Command::new(bin)
        .envs(env_vars)
        .stdin(process::Stdio::inherit())
        .stdout(stdout_cfg)
        .stderr(process::Stdio::inherit())
        .spawn()
        .with_context(|| format!("failed to execute package '{}'", name))?;

    #[cfg(windows)]
    if let Some(ref job) = _job
        && let Err(e) = job.assign(&child)
    {
        eprintln!("warning: failed to assign process to Job Object: {:#}", e);
    }

    if let Some(output_decl) = output
        && let Some(child_stdout) = child.stdout.take()
    {
        let reader = BufReader::new(child_stdout);
        let stdout = std::io::stdout();
        let writer = std::io::BufWriter::new(stdout.lock());
        crate::render::render_jsonl(reader, output_decl, writer);
    }

    let status = child
        .wait()
        .with_context(|| format!("failed to wait for package '{}'", name))?;
    Ok(status.code().unwrap_or(1))
}

// ─── Public Entry Point ──────────────────────────────────────────────

pub fn run(home: &Path, name: &str, args: &[String], raw_json: bool, force_text: bool) -> Result<i32> {
    let resolved = resolve(home, name)?;

    // Build clap command from package definition
    let cmd = build_clap_command(&resolved.definition);

    // Parse with clap
    let (command_path, parsed_flags) = match clap_parse(cmd, name, args, &resolved.definition) {
        Ok(result) => result,
        Err(e) => {
            if e.use_stderr() {
                eprint!("{}", e);
                return Ok(2);
            } else {
                print!("{}", e);
                return Ok(0);
            }
        }
    };

    // Find the command definition
    let command = find_command(&resolved.definition.commands, &command_path)?;

    // Discover project root
    let cwd = std::env::current_dir().ok();
    let project_root = match cwd {
        Some(ref c) => paths::discover_project_root(c, home),
        None => None,
    };

    // Read project config if available
    let project_config = project_root.as_ref().and_then(|root| {
        config::read_project(root).ok()
    });

    // Build env vars and placeholder map
    let global_config = config::read_global(home).unwrap_or_default();
    let (env_vars, placeholders) = crate::execute::build_env_vars(
        home,
        &resolved.definition.name,
        &command_path,
        &resolved.version,
        &parsed_flags,
        command,
        &resolved.receipt,
        &global_config,
        &resolved.definition.config,
        project_root.as_deref(),
        resolved.definition.project_data,
        project_config.as_ref(),
        cwd.as_deref(),
    );

    // Execute
    execute(home, &resolved, &env_vars, &placeholders, &command_path, command, &parsed_flags, raw_json, force_text)
}

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

    #[test]
    fn test_dispatch_missing_package() {
        let home = test_util::temp_home("dispatch");
        let result = run(home.path(), "nonexistent", &[], false, false);
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(err.contains("not found"), "got: {}", err);
    }

    #[test]
    fn test_dispatch_disabled_package() {
        let home = test_util::temp_home("dispatch");
        let mut r = receipt::Receipt::new(
            "1.0.0".to_string(),
            receipt::SourceRecord::Local {
                path: "/tmp/mymod".to_string(),
            },
        );
        r.active = false;
        receipt::write(home.path(), "mymod", &r).unwrap();

        let result = run(home.path(), "mymod", &[], false, false);
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(err.contains("disabled"), "got: {}", err);
        assert!(err.contains("zacor enable"), "got: {}", err);
    }

    #[test]
    fn test_dispatch_corrupt_definition() {
        let home = test_util::temp_home("dispatch");
        receipt::write(
            home.path(),
            "broken",
            &receipt::Receipt::new(
                "1.0.0".to_string(),
                receipt::SourceRecord::Local {
                    path: "/tmp/broken".to_string(),
                },
            ),
        )
        .unwrap();
        // No package.yaml in store
        let result = run(home.path(), "broken", &[], false, false);
        assert!(result.is_err());
        let err = format!("{:#}", result.unwrap_err());
        assert!(err.contains("not found in store") || err.contains("reinstall"), "got: {}", err);
    }

    // ─── build_clap_command tests ────────────────────────────────────

    #[test]
    fn test_build_clap_single_default() {
        let yaml = r#"
name: echo
version: "0.2.0"
description: "Echo text"
commands:
  default:
    description: Echo text
    args:
      text:
        type: string
        required: true
"#;
        let def = crate::package_definition::parse(yaml).unwrap();
        let cmd = build_clap_command(&def);

        // Should accept positional arg, no "default" subcommand
        let matches = cmd.try_get_matches_from(["echo", "hello"]).unwrap();
        assert_eq!(matches.get_one::<String>("text").unwrap(), "hello");
        assert!(matches.subcommand().is_none());
    }

    #[test]
    fn test_build_clap_default_plus_named() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
commands:
  default:
    args:
      text:
        type: string
  transcribe:
    description: Transcribe audio
    args:
      file:
        type: path
        required: true
"#;
        let def = crate::package_definition::parse(yaml).unwrap();

        // No subcommand: uses default's args
        let cmd = build_clap_command(&def);
        let matches = cmd.try_get_matches_from(["my-pkg", "hello"]).unwrap();
        assert!(matches.subcommand().is_none());
        assert_eq!(matches.get_one::<String>("text").unwrap(), "hello");

        // Named subcommand works
        let cmd = build_clap_command(&def);
        let matches = cmd
            .try_get_matches_from(["my-pkg", "transcribe", "file.mp3"])
            .unwrap();
        let (name, sub) = matches.subcommand().unwrap();
        assert_eq!(name, "transcribe");
        assert_eq!(sub.get_one::<String>("file").unwrap(), "file.mp3");
    }

    #[test]
    fn test_build_clap_named_only() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
commands:
  transcribe:
    description: Transcribe audio
  translate:
    description: Translate text
"#;
        let def = crate::package_definition::parse(yaml).unwrap();
        let cmd = build_clap_command(&def);

        // No subcommand should error
        let result = cmd.try_get_matches_from(["my-pkg"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_clap_nested_commands() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
commands:
  transcribe:
    description: Transcribe audio
    commands:
      batch:
        description: Batch transcribe
        args:
          files:
            type: string
            required: true
"#;
        let def = crate::package_definition::parse(yaml).unwrap();
        let cmd = build_clap_command(&def);

        let matches = cmd
            .try_get_matches_from(["my-pkg", "transcribe", "batch", "*.mp3"])
            .unwrap();
        let (name, sub) = matches.subcommand().unwrap();
        assert_eq!(name, "transcribe");
        let (nested_name, nested_sub) = sub.subcommand().unwrap();
        assert_eq!(nested_name, "batch");
        assert_eq!(nested_sub.get_one::<String>("files").unwrap(), "*.mp3");
    }

    #[test]
    fn test_build_clap_arg_types() {
        let yaml = r#"
name: test
version: "1.0.0"
commands:
  default:
    args:
      input:
        type: string
        required: true
      count:
        type: number
        flag: count
      verbose:
        type: bool
        flag: verbose
      file:
        type: path
        flag: file
      format:
        type: choice
        flag: format
        values: [json, csv, text]
"#;
        let def = crate::package_definition::parse(yaml).unwrap();

        // Number validation rejects non-numeric
        let cmd = build_clap_command(&def);
        let result = cmd.try_get_matches_from(["test", "hello", "--count", "abc"]);
        assert!(result.is_err());

        // Choice validation rejects invalid value
        let cmd = build_clap_command(&def);
        let result = cmd.try_get_matches_from(["test", "hello", "--format", "invalid"]);
        assert!(result.is_err());

        // Valid args parse correctly
        let cmd = build_clap_command(&def);
        let matches = cmd
            .try_get_matches_from([
                "test", "hello", "--count", "42", "--verbose", "--file", "/path", "--format", "json",
            ])
            .unwrap();
        assert_eq!(matches.get_one::<String>("input").unwrap(), "hello");
        assert_eq!(matches.get_one::<String>("count").unwrap(), "42");
        assert!(matches.get_flag("verbose"));
        assert_eq!(matches.get_one::<String>("file").unwrap(), "/path");
        assert_eq!(matches.get_one::<String>("format").unwrap(), "json");
    }

    #[test]
    fn test_build_clap_flag_vs_positional() {
        let yaml = r#"
name: test
version: "1.0.0"
commands:
  default:
    args:
      text:
        type: string
        required: true
      model:
        type: choice
        flag: model
        values: [base, large]
"#;
        let def = crate::package_definition::parse(yaml).unwrap();

        // Positional + flag
        let cmd = build_clap_command(&def);
        let matches = cmd
            .try_get_matches_from(["test", "hello", "--model", "large"])
            .unwrap();
        assert_eq!(matches.get_one::<String>("text").unwrap(), "hello");
        assert_eq!(matches.get_one::<String>("model").unwrap(), "large");

        // Flag before positional
        let cmd = build_clap_command(&def);
        let matches = cmd
            .try_get_matches_from(["test", "--model", "base", "hello"])
            .unwrap();
        assert_eq!(matches.get_one::<String>("text").unwrap(), "hello");
        assert_eq!(matches.get_one::<String>("model").unwrap(), "base");
    }

    // ─── clap_parse tests ────────────────────────────────────────────

    #[test]
    fn test_clap_parse_default_command() {
        let yaml = r#"
name: echo
version: "0.2.0"
commands:
  default:
    args:
      text:
        type: string
        required: true
"#;
        let def = crate::package_definition::parse(yaml).unwrap();
        let cmd = build_clap_command(&def);
        let (path, flags) = clap_parse(cmd, "echo", &["hello".to_string()], &def).unwrap();
        assert_eq!(path, "default");
        assert_eq!(flags["text"], "hello");
    }

    #[test]
    fn test_clap_parse_named_command() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
commands:
  transcribe:
    description: Transcribe audio
    args:
      file:
        type: path
        required: true
  translate:
    description: Translate text
"#;
        let def = crate::package_definition::parse(yaml).unwrap();
        let cmd = build_clap_command(&def);
        let (path, flags) =
            clap_parse(cmd, "my-pkg", &["transcribe".to_string(), "file.mp3".to_string()], &def)
                .unwrap();
        assert_eq!(path, "transcribe");
        assert_eq!(flags["file"], "file.mp3");
    }

    #[test]
    fn test_clap_parse_nested_command() {
        let yaml = r#"
name: my-pkg
version: "1.0.0"
commands:
  transcribe:
    description: Transcribe
    commands:
      batch:
        description: Batch
        args:
          files:
            type: string
            required: true
"#;
        let def = crate::package_definition::parse(yaml).unwrap();
        let cmd = build_clap_command(&def);
        let (path, flags) = clap_parse(
            cmd,
            "my-pkg",
            &["transcribe".to_string(), "batch".to_string(), "*.mp3".to_string()],
            &def,
        )
        .unwrap();
        assert_eq!(path, "transcribe.batch");
        assert_eq!(flags["files"], "*.mp3");
    }

    #[test]
    fn test_clap_parse_bool_flag() {
        let yaml = r#"
name: test
version: "1.0.0"
commands:
  default:
    args:
      verbose:
        type: bool
        flag: verbose
"#;
        let def = crate::package_definition::parse(yaml).unwrap();

        // With flag
        let cmd = build_clap_command(&def);
        let (_, flags) = clap_parse(cmd, "test", &["--verbose".to_string()], &def).unwrap();
        assert_eq!(flags["verbose"], "true");

        // Without flag
        let cmd = build_clap_command(&def);
        let (_, flags) = clap_parse(cmd, "test", &[], &def).unwrap();
        assert!(!flags.contains_key("verbose"));
    }

    #[test]
    fn test_clap_parse_unknown_flag_error() {
        let yaml = r#"
name: echo
version: "0.2.0"
commands:
  default:
    args:
      text:
        type: string
"#;
        let def = crate::package_definition::parse(yaml).unwrap();
        let cmd = build_clap_command(&def);
        let result = clap_parse(cmd, "echo", &["--unknown".to_string(), "hello".to_string()], &def);
        assert!(result.is_err());
    }

    #[test]
    fn test_bool_auto_flags() {
        let yaml = r#"
name: test
version: "1.0.0"
commands:
  default:
    args:
      changes:
        type: bool
      drafts:
        type: bool
"#;
        let def = crate::package_definition::parse(yaml).unwrap();

        // Bools without explicit flag: become --flags automatically
        let cmd = build_clap_command(&def);
        let (_, flags) = clap_parse(cmd, "test", &["--changes".to_string()], &def).unwrap();
        assert_eq!(flags["changes"], "true");
        assert!(!flags.contains_key("drafts"));

        // Both flags
        let cmd = build_clap_command(&def);
        let (_, flags) = clap_parse(cmd, "test", &["--changes".to_string(), "--drafts".to_string()], &def).unwrap();
        assert_eq!(flags["changes"], "true");
        assert_eq!(flags["drafts"], "true");

        // No flags
        let cmd = build_clap_command(&def);
        let (_, flags) = clap_parse(cmd, "test", &[], &def).unwrap();
        assert!(!flags.contains_key("changes"));
        assert!(!flags.contains_key("drafts"));
    }

    // ─── find_command tests ──────────────────────────────────────────

    #[test]
    fn test_find_command_default() {
        let mut commands = BTreeMap::new();
        commands.insert("default".to_string(), CommandDefinition::default());
        let cmd = find_command(&commands, "default").unwrap();
        assert!(cmd.args.is_empty());
    }

    #[test]
    fn test_find_command_nested() {
        let mut inner = BTreeMap::new();
        inner.insert("batch".to_string(), CommandDefinition::default());
        let mut commands = BTreeMap::new();
        commands.insert(
            "transcribe".to_string(),
            CommandDefinition {
                commands: inner,
                ..Default::default()
            },
        );
        let cmd = find_command(&commands, "transcribe.batch").unwrap();
        assert!(cmd.args.is_empty());
    }

    #[test]
    fn test_find_command_not_found() {
        let commands = BTreeMap::new();
        let result = find_command(&commands, "nonexistent");
        assert!(result.is_err());
    }

    // ─── mode resolution tests ──────────────────────────────────────

    fn make_resolved(
        mode: Option<receipt::Mode>,
        exec_default: Option<&str>,
        service: bool,
    ) -> ResolvedPackage {
        let mut r = receipt::Receipt::new(
            "1.0.0".to_string(),
            receipt::SourceRecord::Local {
                path: "/tmp/test".to_string(),
            },
        );
        r.mode = mode;

        let mut def = crate::package_definition::parse(
            r#"
name: test
version: "1.0.0"
protocol: true
commands:
  default:
    description: test
"#,
        )
        .unwrap();

        if let Some(default) = exec_default {
            def.execution = Some(crate::package_definition::ExecutionSection {
                default: Some(default.to_string()),
            });
        }
        if service {
            def.service = Some(crate::package_definition::ServiceSection {
                start: "test".into(),
                port: Some(9999),
                health: None,
                startup: None,
            });
        }

        ResolvedPackage {
            receipt: r,
            definition: def,
            version: "1.0.0".to_string(),
        }
    }

    #[test]
    fn test_mode_resolution_receipt_overrides_definition() {
        let resolved = make_resolved(Some(receipt::Mode::Service), Some("command"), true);
        assert_eq!(resolve_mode(&resolved), receipt::Mode::Service);
    }

    #[test]
    fn test_mode_resolution_definition_default() {
        let resolved = make_resolved(None, Some("service"), true);
        assert_eq!(resolve_mode(&resolved), receipt::Mode::Service);
    }

    #[test]
    fn test_mode_resolution_fallback_to_command() {
        let resolved = make_resolved(None, None, false);
        assert_eq!(resolve_mode(&resolved), receipt::Mode::Command);
    }

    #[test]
    fn test_mode_resolution_receipt_command_overrides_service_default() {
        let resolved = make_resolved(Some(receipt::Mode::Command), Some("service"), true);
        assert_eq!(resolve_mode(&resolved), receipt::Mode::Command);
    }

    // ─── --text flag tests ──────────────────────────────────────────

    #[test]
    fn test_should_render_force_text() {
        let output = Some(OutputDeclaration {
            output_type: Some(OutputType::Table),
            cardinality: None,
            display: None,
            schema: None,
            field: None,
            stream: false,
        });
        // force_text=true overrides non-TTY
        assert!(should_render(&output, false, true));
        // raw_json still wins over force_text
        assert!(!should_render(&output, true, true));
        // no output declaration → no render
        assert!(!should_render(&None, false, true));
    }

    #[test]
    fn test_text_and_json_conflict() {
        use clap::{CommandFactory, Parser};
        #[derive(Parser)]
        struct TestCli {
            #[arg(long, conflicts_with = "text")]
            json: bool,
            #[arg(long, conflicts_with = "json")]
            text: bool,
        }
        // --text alone is fine
        assert!(TestCli::command().try_get_matches_from(["test", "--text"]).is_ok());
        // --json alone is fine
        assert!(TestCli::command().try_get_matches_from(["test", "--json"]).is_ok());
        // both together is an error
        assert!(TestCli::command().try_get_matches_from(["test", "--text", "--json"]).is_err());
    }
}