openlatch-provider 0.2.1

Self-service onboarding CLI + runtime daemon for OpenLatch Editors and Providers
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
//! Manifest v2 — multi-tool composition (`kind: Tool` + `kind: Provider`).
//!
//! The "shim" approach: the v2 loader synthesizes an in-memory v1
//! [`Manifest`] so the existing supervisor / register / publish pipelines
//! consume v2 trees unchanged. v2 validation runs at the boundary
//! (`load_provider_tree`); everything downstream sees v1.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::error::{
    OlError, OL_4273_MANIFEST_UNREADABLE, OL_4320_PROVIDER_SCHEMA_INVALID,
    OL_4321_TOOL_SCHEMA_INVALID, OL_4322_AMBIGUOUS_TOOL_REF, OL_4323_UNRESOLVED_TOOL_REF,
    OL_4324_DUPLICATE_TOOL_REGISTRY, OL_4325_TOOL_PATHS_ZERO_MATCH,
    OL_4326_OVERRIDE_COMMAND_CONFLICT, OL_4327_V1_MANIFEST_REJECTED,
    OL_4328_TOOL_MANIFEST_MULTI_EDITOR,
};
use crate::generated::{
    BindingV2, HealthCheckV2, ManifestEditor, ManifestProviderV2, ManifestToolV2,
    ProcessOverrideV2, ProcessOverrideV2HealthCheck, ProcessV2, ToolItemV2,
};
use crate::manifest::schema;

const MAX_MANIFEST_BYTES: usize = 256 * 1024;

/// Caps `tool_paths` expansion so a pathological glob can't fan out unbounded.
const MAX_TOOL_MANIFESTS: usize = 256;

#[derive(Debug, Clone)]
pub struct ResolvedManifest {
    pub provider: ManifestProviderV2,
    pub provider_path: PathBuf,
    pub tools: BTreeMap<(String, String, String), ResolvedTool>,
    pub bindings: Vec<ResolvedBinding>,
    /// In-memory v1 [`crate::generated::Manifest`] synthesized from the v2
    /// tree. Exposed for downstream v1-shaped consumers (supervisor,
    /// register, publish).
    pub synth: crate::generated::Manifest,
}

impl ResolvedManifest {
    /// cwd anchor for the binding at `idx` — the parent of the tool manifest
    /// it resolved to. Used by the supervisor to resolve relative `cwd`s.
    pub fn binding_dir(&self, idx: usize) -> Option<PathBuf> {
        let b = self.bindings.get(idx)?;
        let key = (
            b.editor_slug.clone(),
            b.tool_slug.clone(),
            b.version.clone(),
        );
        self.tools.get(&key).and_then(|t| {
            t.manifest_path
                .parent()
                .map(Path::to_path_buf)
                .or_else(|| Some(PathBuf::from(".")))
        })
    }
}

#[derive(Debug, Clone)]
pub struct ResolvedTool {
    pub manifest_path: PathBuf,
    pub editor_slug: String,
    pub editor: ManifestEditor,
    pub tool: ToolItemV2,
}

#[derive(Debug, Clone)]
pub struct ResolvedBinding {
    pub editor_slug: String,
    pub tool_slug: String,
    pub version: String,
    pub provider_slug: String,
}

/// Dispatcher input — used by [`crate::manifest::load`] to pick between v1
/// and v2 loaders without committing to a full parse.
pub fn peek_kind(bytes: &[u8]) -> Result<(Option<i64>, Option<String>), OlError> {
    let yaml: serde_yaml::Value = serde_yaml::from_slice(bytes)
        .map_err(|e| OlError::new(OL_4320_PROVIDER_SCHEMA_INVALID, format!("YAML parse: {e}")))?;
    let schema_version = yaml.get("schema_version").and_then(|v| v.as_i64());
    let kind = yaml
        .get("kind")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    Ok((schema_version, kind))
}

/// Load a v2 provider manifest tree (provider + every tool manifest reachable
/// via its `tool_paths:` globs), validate everything, resolve binding refs,
/// merge process overrides, and synthesize a v1 [`crate::generated::Manifest`]
/// for downstream consumption.
pub fn load_provider_tree(provider_path: &Path) -> Result<ResolvedManifest, OlError> {
    let provider_bytes = read_capped(provider_path)?;
    let provider = parse_provider_v2(&provider_bytes, provider_path)?;
    let provider_dir = provider_path
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));

    let mut tool_paths_expanded: Vec<PathBuf> = Vec::new();
    for entry in provider.tool_paths.iter() {
        let pattern: &str = entry.as_str();
        let matched = expand_glob(&provider_dir, pattern)?;
        if matched.is_empty() {
            return Err(OlError::new(
                OL_4325_TOOL_PATHS_ZERO_MATCH,
                format!(
                    "tool_paths entry `{}` expanded to zero matches (relative to `{}`)",
                    pattern,
                    provider_dir.display()
                ),
            )
            .with_suggestion(
                "Check the glob pattern; or remove the entry if no tools live under it.",
            ));
        }
        for p in matched {
            if !tool_paths_expanded.contains(&p) {
                tool_paths_expanded.push(p);
            }
        }
    }
    tool_paths_expanded.sort();
    if tool_paths_expanded.len() > MAX_TOOL_MANIFESTS {
        return Err(OlError::new(
            OL_4325_TOOL_PATHS_ZERO_MATCH,
            format!(
                "tool_paths expanded to {} manifests (cap {}); narrow the glob",
                tool_paths_expanded.len(),
                MAX_TOOL_MANIFESTS
            ),
        ));
    }

    let mut tools: BTreeMap<(String, String, String), ResolvedTool> = BTreeMap::new();
    for path in &tool_paths_expanded {
        let bytes = read_capped(path)?;
        let tool_manifest = parse_tool_v2(&bytes, path)?;
        let editor_slug = tool_manifest.editor.slug.to_string();
        let editor = tool_manifest.editor.clone();
        for item in tool_manifest.tools.into_iter() {
            let tool_slug = item.slug.to_string();
            let version = item.version.to_string();
            let key = (editor_slug.clone(), tool_slug.clone(), version.clone());
            if tools.contains_key(&key) {
                return Err(OlError::new(
                    OL_4324_DUPLICATE_TOOL_REGISTRY,
                    format!(
                        "duplicate tool registry entry `{}/{}@{}` (already loaded; second match in `{}`)",
                        editor_slug,
                        tool_slug,
                        version,
                        path.display()
                    ),
                ));
            }
            tools.insert(
                key,
                ResolvedTool {
                    manifest_path: path.clone(),
                    editor_slug: editor_slug.clone(),
                    editor: editor.clone(),
                    tool: item,
                },
            );
        }
    }

    let mut resolved_bindings: Vec<ResolvedBinding> = Vec::new();
    let mut synth_bindings_json: Vec<serde_json::Value> = Vec::new();
    let mut synth_tools_json: Vec<serde_json::Value> = Vec::new();
    let mut synth_tools_seen: std::collections::BTreeSet<String> =
        std::collections::BTreeSet::new();
    // v1 has a single `editor` block; v2 may have several across tool
    // manifests. The first resolved editor wins — `publish` is per-tool
    // anyway, so the singular v1 view is only used to round-trip the synth
    // through v1 schema validation.
    let mut synth_editor: Option<serde_json::Value> = None;

    for (idx, binding) in provider.bindings.iter().enumerate() {
        if let Some(ovr) = binding.process_override.as_ref() {
            if !ovr.command.is_empty() && !ovr.command_args.is_empty() {
                return Err(OlError::new(
                    OL_4326_OVERRIDE_COMMAND_CONFLICT,
                    format!(
                        "binding #{idx} `{}/{}`: process_override.command and \
                         process_override.command_args are mutually exclusive",
                        binding.tool, binding.provider
                    ),
                ));
            }
        }
        let (editor_slug, tool_slug, version) = resolve_ref(&binding.tool, &tools)?;
        let resolved_tool = tools
            .get(&(editor_slug.clone(), tool_slug.clone(), version.clone()))
            .ok_or_else(|| {
                OlError::new(
                    OL_4323_UNRESOLVED_TOOL_REF,
                    format!(
                        "tool ref `{}` resolved to ({}/{}@{}) but registry has no entry",
                        binding.tool, editor_slug, tool_slug, version
                    ),
                )
            })?;

        let merged_process = merge_process(
            &resolved_tool.tool.process,
            binding.process_override.as_ref(),
        )?;
        synth_bindings_json.push(synthesize_v1_binding(binding, &tool_slug, &merged_process));

        if synth_tools_seen.insert(tool_slug.clone()) {
            synth_tools_json.push(synthesize_v1_tool(&resolved_tool.tool));
        }
        if synth_editor.is_none() {
            synth_editor = Some(serde_json::to_value(&resolved_tool.editor).map_err(|e| {
                OlError::new(
                    OL_4320_PROVIDER_SCHEMA_INVALID,
                    format!("internal: serialize editor for synth: {e}"),
                )
            })?);
        }

        resolved_bindings.push(ResolvedBinding {
            editor_slug,
            tool_slug,
            version,
            provider_slug: binding.provider.clone(),
        });
    }

    // If there were no bindings, fall back to the first loaded tool's editor —
    // gives `register` something to publish even with bindings empty.
    if synth_editor.is_none() {
        if let Some((_, t)) = tools.iter().next() {
            synth_editor = Some(serde_json::to_value(&t.editor).map_err(|e| {
                OlError::new(
                    OL_4320_PROVIDER_SCHEMA_INVALID,
                    format!("internal: serialize fallback editor: {e}"),
                )
            })?);
        } else {
            return Err(OlError::new(
                OL_4320_PROVIDER_SCHEMA_INVALID,
                "provider manifest has no resolvable tools (tool_paths empty and bindings empty)",
            ));
        }
    }

    let synth_providers_json: Vec<serde_json::Value> = provider
        .providers
        .iter()
        .map(|p| serde_json::to_value(p).unwrap_or(serde_json::Value::Null))
        .collect();

    let synth_json = serde_json::json!({
        "schema_version": 1,
        "editor": synth_editor.expect("synth_editor populated above"),
        "tools": synth_tools_json,
        "providers": synth_providers_json,
        "bindings": synth_bindings_json,
    });

    // Defense-in-depth: feed the synthesized v1 through the v1 validator so
    // any shape regression in the shim surfaces here, not at the platform.
    schema::validate(&synth_json).map_err(|e| {
        OlError::new(
            OL_4320_PROVIDER_SCHEMA_INVALID,
            format!(
                "internal: synthesized v1 manifest failed v1 schema validation \
                 (please report): {e}"
            ),
        )
    })?;

    let synth: crate::generated::Manifest = serde_json::from_value(synth_json).map_err(|e| {
        OlError::new(
            OL_4320_PROVIDER_SCHEMA_INVALID,
            format!("internal: synth manifest deserialize failed: {e}"),
        )
    })?;

    Ok(ResolvedManifest {
        provider,
        provider_path: provider_path.to_path_buf(),
        tools,
        bindings: resolved_bindings,
        synth,
    })
}

/// Parse + validate a v2 provider manifest.
pub fn parse_provider_v2(bytes: &[u8], path: &Path) -> Result<ManifestProviderV2, OlError> {
    let yaml: serde_yaml::Value = serde_yaml::from_slice(bytes).map_err(|e| {
        OlError::new(
            OL_4320_PROVIDER_SCHEMA_INVALID,
            format!("`{}`: YAML parse: {e}", path.display()),
        )
    })?;
    let json = serde_json::to_value(&yaml).map_err(|e| {
        OlError::new(
            OL_4320_PROVIDER_SCHEMA_INVALID,
            format!("`{}`: YAML→JSON: {e}", path.display()),
        )
    })?;

    // Discriminator pre-check — give a v1-friendly hint when caller passed a
    // v1 manifest to a v2 entrypoint.
    let kind = json.get("kind").and_then(|v| v.as_str());
    let schema_version = json.get("schema_version").and_then(|v| v.as_i64());
    if kind != Some("Provider") {
        if kind.is_none() && schema_version == Some(1) {
            return Err(OlError::new(
                OL_4327_V1_MANIFEST_REJECTED,
                format!(
                    "`{}` is a v1 manifest; v2 entrypoints require `kind: Provider`",
                    path.display()
                ),
            )
            .with_suggestion(
                "Run `openlatch-provider migrate <v1-file> --out-tool ... --out-provider ...` \
                 to split it into the v2 shape.",
            ));
        }
        return Err(OlError::new(
            OL_4320_PROVIDER_SCHEMA_INVALID,
            format!(
                "`{}`: expected `kind: Provider`, got `kind: {}`",
                path.display(),
                kind.unwrap_or("<missing>")
            ),
        ));
    }

    schema::validate_provider_v2(&json).map_err(|e| {
        OlError::new(
            OL_4320_PROVIDER_SCHEMA_INVALID,
            format!("`{}`: {e}", path.display()),
        )
    })?;

    let parsed: ManifestProviderV2 = serde_json::from_value(json).map_err(|e| {
        OlError::new(
            OL_4320_PROVIDER_SCHEMA_INVALID,
            format!("`{}`: typify deserialize: {e}", path.display()),
        )
    })?;
    Ok(parsed)
}

/// Parse + validate a v2 tool manifest.
pub fn parse_tool_v2(bytes: &[u8], path: &Path) -> Result<ManifestToolV2, OlError> {
    let yaml: serde_yaml::Value = serde_yaml::from_slice(bytes).map_err(|e| {
        OlError::new(
            OL_4321_TOOL_SCHEMA_INVALID,
            format!("`{}`: YAML parse: {e}", path.display()),
        )
    })?;
    let json = serde_json::to_value(&yaml).map_err(|e| {
        OlError::new(
            OL_4321_TOOL_SCHEMA_INVALID,
            format!("`{}`: YAML→JSON: {e}", path.display()),
        )
    })?;

    let kind = json.get("kind").and_then(|v| v.as_str());
    let schema_version = json.get("schema_version").and_then(|v| v.as_i64());
    if kind != Some("Tool") {
        if kind.is_none() && schema_version == Some(1) {
            return Err(OlError::new(
                OL_4327_V1_MANIFEST_REJECTED,
                format!(
                    "`{}` is a v1 manifest; v2 tool entrypoints require `kind: Tool`",
                    path.display()
                ),
            ));
        }
        return Err(OlError::new(
            OL_4321_TOOL_SCHEMA_INVALID,
            format!(
                "`{}`: expected `kind: Tool`, got `kind: {}`",
                path.display(),
                kind.unwrap_or("<missing>")
            ),
        ));
    }

    // Reject multi-editor tool manifests (one editor per tool manifest is the
    // rule per handoff §6.1 / OL-4328). JSON Schema can't catch this because
    // `editor` is already a single object — we enforce in case a future
    // schema relaxation lets multiple slip through.
    if let Some(editor) = json.get("editor") {
        if editor.is_array() {
            return Err(OlError::new(
                OL_4328_TOOL_MANIFEST_MULTI_EDITOR,
                format!(
                    "`{}`: tool manifest declares multiple editors; one editor per tool \
                     manifest is the rule",
                    path.display()
                ),
            ));
        }
    }

    schema::validate_tool_v2(&json).map_err(|e| {
        OlError::new(
            OL_4321_TOOL_SCHEMA_INVALID,
            format!("`{}`: {e}", path.display()),
        )
    })?;

    let parsed: ManifestToolV2 = serde_json::from_value(json).map_err(|e| {
        OlError::new(
            OL_4321_TOOL_SCHEMA_INVALID,
            format!("`{}`: typify deserialize: {e}", path.display()),
        )
    })?;
    Ok(parsed)
}

/// Resolve a binding's `tool:` ref string to `(editor_slug, tool_slug, version)`.
///
/// Accepted forms:
/// - `editor/tool@version` — qualified; exact registry lookup
/// - `tool@version` — editor-implicit; unambiguous lookup across editors
/// - `editor/tool@latest` or `tool@latest` — highest semver among local matches
fn resolve_ref(
    raw: &str,
    tools: &BTreeMap<(String, String, String), ResolvedTool>,
) -> Result<(String, String, String), OlError> {
    let (head, version) = match raw.rsplit_once('@') {
        Some((h, v)) if !h.is_empty() && !v.is_empty() => (h, v),
        _ => {
            return Err(OlError::new(
                OL_4323_UNRESOLVED_TOOL_REF,
                format!(
                    "tool ref `{raw}` is malformed; expected `<editor>/<tool>@<version>` \
                     or `<tool>@<version>`"
                ),
            )
            .with_suggestion("Add `@<semver>` or `@latest`."));
        }
    };

    let (editor_part, tool_part) = match head.split_once('/') {
        Some((e, t)) if !e.is_empty() && !t.is_empty() => (Some(e), t),
        Some(_) => {
            return Err(OlError::new(
                OL_4323_UNRESOLVED_TOOL_REF,
                format!("tool ref `{raw}` has empty editor or tool slug"),
            ));
        }
        None => (None, head),
    };

    let resolve_version = |candidates: &[&(String, String, String)]| -> Result<String, OlError> {
        if version != "latest" {
            // Exact match required.
            for c in candidates {
                if c.2 == version {
                    return Ok(version.to_string());
                }
            }
            Err(OlError::new(
                OL_4323_UNRESOLVED_TOOL_REF,
                format!("tool ref `{raw}`: no local manifest declares version `{version}`"),
            ))
        } else {
            // Highest semver wins.
            let mut best: Option<(semver::Version, String)> = None;
            for c in candidates {
                if let Ok(parsed) = semver::Version::parse(&c.2) {
                    match &best {
                        None => best = Some((parsed, c.2.clone())),
                        Some((b, _)) if parsed > *b => best = Some((parsed, c.2.clone())),
                        _ => {}
                    }
                }
            }
            best.map(|(_, s)| s).ok_or_else(|| {
                OlError::new(
                    OL_4323_UNRESOLVED_TOOL_REF,
                    format!("tool ref `{raw}@latest`: no parseable semver in the local registry"),
                )
            })
        }
    };

    if let Some(editor) = editor_part {
        // Qualified ref.
        let candidates: Vec<&(String, String, String)> = tools
            .keys()
            .filter(|(e, t, _)| e == editor && t == tool_part)
            .collect();
        if candidates.is_empty() {
            return Err(OlError::new(
                OL_4323_UNRESOLVED_TOOL_REF,
                format!(
                    "tool ref `{raw}`: no local manifest declares editor=`{editor}` + tool=`{tool_part}`"
                ),
            ));
        }
        let v = resolve_version(&candidates)?;
        Ok((editor.to_string(), tool_part.to_string(), v))
    } else {
        // Editor-implicit ref — must be unambiguous across editors.
        let candidates: Vec<&(String, String, String)> =
            tools.keys().filter(|(_, t, _)| t == tool_part).collect();
        if candidates.is_empty() {
            return Err(OlError::new(
                OL_4323_UNRESOLVED_TOOL_REF,
                format!("tool ref `{raw}`: no local manifest declares tool=`{tool_part}`"),
            ));
        }
        let mut editors: std::collections::BTreeSet<&str> =
            candidates.iter().map(|(e, _, _)| e.as_str()).collect();
        if editors.len() > 1 {
            let list: Vec<&str> = editors.iter().copied().collect();
            return Err(OlError::new(
                OL_4322_AMBIGUOUS_TOOL_REF,
                format!(
                    "tool ref `{raw}` is editor-implicit but matches multiple editors: {}",
                    list.join(", ")
                ),
            )
            .with_suggestion("Qualify the ref as `<editor>/<tool>@<version>`."));
        }
        let editor = editors.pop_first().unwrap().to_string();
        let v = resolve_version(&candidates)?;
        Ok((editor, tool_part.to_string(), v))
    }
}

/// Merge a tool's default [`ProcessV2`] with a per-binding
/// [`ProcessOverrideV2`] into a serde_json value shaped as v1's
/// `manifest-process.schema.json` (so the synthesized v1 binding round-trips
/// through the existing supervisor pipeline).
///
/// Merge rules (per handoff §6.4):
/// | Field           | Rule                                            |
/// |-----------------|-------------------------------------------------|
/// | `command`       | override replaces if set                        |
/// | `command_args`  | appended to default's command (override-only)   |
/// | `cwd`           | override replaces                               |
/// | `env`           | deep merge; override wins on key conflict       |
/// | `health_check`  | override replaces the whole block               |
/// | `restart`       | override replaces; mapped to v1 `restart_policy`|
fn merge_process(
    default: &ProcessV2,
    over: Option<&ProcessOverrideV2>,
) -> Result<serde_json::Value, OlError> {
    use serde_json::json;

    // 1. command
    let command: Vec<String> = if let Some(o) = over {
        if !o.command.is_empty() {
            o.command.iter().map(|c| c.to_string()).collect()
        } else if !o.command_args.is_empty() {
            let mut base: Vec<String> = default.command.iter().map(|c| c.to_string()).collect();
            base.extend(o.command_args.iter().cloned());
            base
        } else {
            default.command.iter().map(|c| c.to_string()).collect()
        }
    } else {
        default.command.iter().map(|c| c.to_string()).collect()
    };

    // 2. cwd
    let cwd = over
        .and_then(|o| o.cwd.clone())
        .or_else(|| default.cwd.clone());

    // 3. env — deep merge with override winning on key conflict.
    let mut env: std::collections::HashMap<String, String> = default.env.clone();
    if let Some(o) = over {
        for (k, v) in &o.env {
            env.insert(k.clone(), v.clone());
        }
    }

    // 4. health_check — override replaces.
    let hc_value = match over.and_then(|o| o.health_check.as_ref()) {
        Some(ovr_hc) => override_health_check_to_json(ovr_hc),
        None => default_health_check_to_json(&default.health_check),
    };

    // 5. restart — override replaces. v2 shape: `{max_restarts, window_seconds}`.
    // Map to v1 `restart_policy: {max_restarts, window_ms}` so the synthesized
    // binding satisfies the v1 schema.
    let restart_policy = match (
        over.and_then(|o| o.restart.as_ref()),
        default.restart.as_ref(),
    ) {
        (Some(o), _) => Some((o.max_restarts, o.window_seconds)),
        (None, Some(d)) => Some((d.max_restarts, d.window_seconds)),
        _ => None,
    };

    let mut process = serde_json::Map::new();
    process.insert("command".into(), json!(command.iter().collect::<Vec<_>>()));
    if let Some(c) = cwd {
        process.insert("cwd".into(), json!(c));
    }
    if !env.is_empty() {
        process.insert(
            "env".into(),
            serde_json::to_value(&env).unwrap_or_else(|_| json!({})),
        );
    }
    if let Some(v) = default.start_timeout_ms {
        process.insert("start_timeout_ms".into(), json!(v));
    }
    if let Some(v) = default.kill_timeout_ms {
        process.insert("kill_timeout_ms".into(), json!(v));
    }
    process.insert("health_check".into(), hc_value);
    if let Some((max_restarts, window_seconds)) = restart_policy {
        let mut rp = serde_json::Map::new();
        if let Some(n) = max_restarts {
            rp.insert("max_restarts".into(), json!(n.get()));
        }
        if let Some(n) = window_seconds {
            rp.insert("window_ms".into(), json!(n.get() * 1000));
        }
        if !rp.is_empty() {
            process.insert("restart_policy".into(), serde_json::Value::Object(rp));
        }
    }
    // Default to `restart: always` so the v1 supervisor's RestartPolicy enum
    // gets a defined value; v2 has no equivalent enum and the rate-limit
    // window above is the controlling knob.
    process.insert("restart".into(), json!("always"));

    Ok(serde_json::Value::Object(process))
}

/// Build a v1 binding JSON from a v2 binding + the merged process JSON.
/// Fields common to v1 and v2 round-trip via `serde_json::to_value`; the
/// v2-only `process_override` is dropped and replaced with the v1 `process`
/// block (already merged by [`merge_process`]).
fn synthesize_v1_binding(
    v2: &BindingV2,
    tool_slug: &str,
    process_json: &serde_json::Value,
) -> serde_json::Value {
    let mut val = serde_json::to_value(v2).unwrap_or(serde_json::Value::Null);
    if let Some(map) = val.as_object_mut() {
        map.remove("process_override");
        map.insert(
            "tool".into(),
            serde_json::Value::String(tool_slug.to_string()),
        );
        map.insert("process".into(), process_json.clone());
    }
    val
}

/// Build a v1 `tools[]` entry from a v2 `ToolItemV2`. v1 has process on
/// bindings, not tools — strip the v2-only field so v1 schema validation
/// passes.
fn synthesize_v1_tool(item: &ToolItemV2) -> serde_json::Value {
    let mut val = serde_json::to_value(item).unwrap_or(serde_json::Value::Null);
    if let Some(map) = val.as_object_mut() {
        map.remove("process");
    }
    val
}

fn default_health_check_to_json(hc: &HealthCheckV2) -> serde_json::Value {
    use serde_json::json;
    let mut http = serde_json::Map::new();
    http.insert("port".into(), json!(hc.http.port.get()));
    if let Some(path) = hc.http.path.as_ref() {
        http.insert("path".into(), json!(path.to_string()));
    }
    if let Some(v) = hc.http.startup_period_ms {
        http.insert("startup_period_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.startup_timeout_ms {
        http.insert("startup_timeout_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.liveness_period_ms {
        http.insert("liveness_period_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.liveness_timeout_ms {
        http.insert("liveness_timeout_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.liveness_failure_threshold {
        http.insert("liveness_failure_threshold".into(), json!(v.get()));
    }
    json!({ "http": http })
}

fn override_health_check_to_json(hc: &ProcessOverrideV2HealthCheck) -> serde_json::Value {
    use serde_json::json;
    let mut http = serde_json::Map::new();
    http.insert("port".into(), json!(hc.http.port.get()));
    if let Some(path) = hc.http.path.as_ref() {
        http.insert("path".into(), json!(path.to_string()));
    }
    if let Some(v) = hc.http.startup_period_ms {
        http.insert("startup_period_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.startup_timeout_ms {
        http.insert("startup_timeout_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.liveness_period_ms {
        http.insert("liveness_period_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.liveness_timeout_ms {
        http.insert("liveness_timeout_ms".into(), json!(v));
    }
    if let Some(v) = hc.http.liveness_failure_threshold {
        http.insert("liveness_failure_threshold".into(), json!(v.get()));
    }
    json!({ "http": http })
}

fn read_capped(path: &Path) -> Result<Vec<u8>, OlError> {
    let bytes = std::fs::read(path).map_err(|e| {
        OlError::new(
            OL_4273_MANIFEST_UNREADABLE,
            format!("cannot read `{}`: {e}", path.display()),
        )
    })?;
    if bytes.len() > MAX_MANIFEST_BYTES {
        return Err(OlError::new(
            OL_4273_MANIFEST_UNREADABLE,
            format!(
                "`{}` is {} bytes (cap {} KB)",
                path.display(),
                bytes.len(),
                MAX_MANIFEST_BYTES / 1024
            ),
        ));
    }
    Ok(bytes)
}

// ---------------------------------------------------------------------------
// Simple glob expansion
// ---------------------------------------------------------------------------
//
// Supports the patterns sectools actually uses today:
//   - literal paths: `./external/specific-tool/openlatch-tool.yaml`
//   - single-segment wildcard: `./tools/*/openlatch-tool.yaml`
//   - multi-segment wildcard (single `*` per segment): `./a/*/b/*/c.yaml`
//
// Does NOT yet support recursive `**`. If a user needs that we can swap in
// the `globwalk` crate; for v0 the simple expander keeps the dep tree clean.

fn expand_glob(base: &Path, pattern: &str) -> Result<Vec<PathBuf>, OlError> {
    let normalized: PathBuf = if Path::new(pattern).is_absolute() {
        PathBuf::from(pattern)
    } else {
        // Strip leading `./` so split-by-separator doesn't yield an empty head.
        let stripped = pattern.trim_start_matches("./").trim_start_matches(".\\");
        base.join(stripped)
    };

    let parts: Vec<String> = normalized
        .iter()
        .map(|s| s.to_string_lossy().to_string())
        .collect();
    if parts.is_empty() {
        return Ok(Vec::new());
    }

    // Recursive walk, expanding one wildcard segment at a time.
    let mut results: Vec<PathBuf> = vec![PathBuf::new()];
    for part in parts {
        let mut next: Vec<PathBuf> = Vec::new();
        if part == "**" {
            return Err(OlError::new(
                OL_4325_TOOL_PATHS_ZERO_MATCH,
                format!(
                    "recursive `**` in tool_paths glob `{pattern}` is not yet supported \
                     in v2; use single-segment `*` only"
                ),
            ));
        }
        let has_wildcard = part.contains('*') || part.contains('?');
        for prefix in results.drain(..) {
            if has_wildcard {
                let parent = if prefix.as_os_str().is_empty() {
                    PathBuf::from("/")
                } else {
                    prefix.clone()
                };
                let dir_to_list = if prefix.as_os_str().is_empty() {
                    // First segment + wildcard — should not happen in practice
                    // (patterns start with `./` or absolute). Skip.
                    continue;
                } else {
                    parent
                };
                let entries = match std::fs::read_dir(&dir_to_list) {
                    Ok(e) => e,
                    Err(_) => continue, // directory missing → empty expansion
                };
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if glob_match(&part, &name) {
                        next.push(prefix.join(&name));
                    }
                }
            } else {
                next.push(prefix.join(&part));
            }
        }
        results = next;
    }

    // Keep only existing files (drop missing/dirs).
    let mut filtered: Vec<PathBuf> = results.into_iter().filter(|p| p.is_file()).collect();
    filtered.sort();
    Ok(filtered)
}

/// `*` matches any run of characters (including empty); `?` matches one char.
/// Case-sensitive; no character classes.
fn glob_match(pattern: &str, candidate: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let c: Vec<char> = candidate.chars().collect();
    glob_match_inner(&p, &c, 0, 0)
}

fn glob_match_inner(p: &[char], c: &[char], pi: usize, ci: usize) -> bool {
    if pi == p.len() {
        return ci == c.len();
    }
    match p[pi] {
        '*' => {
            // Match 0 or more characters.
            for skip in ci..=c.len() {
                if glob_match_inner(p, c, pi + 1, skip) {
                    return true;
                }
            }
            false
        }
        '?' => {
            if ci < c.len() {
                glob_match_inner(p, c, pi + 1, ci + 1)
            } else {
                false
            }
        }
        ch => {
            if ci < c.len() && c[ci] == ch {
                glob_match_inner(p, c, pi + 1, ci + 1)
            } else {
                false
            }
        }
    }
}

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

    #[test]
    fn glob_match_basics() {
        assert!(glob_match("*.yaml", "openlatch.yaml"));
        assert!(glob_match("openlatch-*.yaml", "openlatch-tool.yaml"));
        assert!(!glob_match("*.yml", "openlatch.yaml"));
        assert!(glob_match("*", "anything"));
        assert!(glob_match("foo?bar", "fooxbar"));
        assert!(!glob_match("foo?bar", "fooxxbar"));
    }

    #[test]
    fn peek_kind_v2_provider() {
        let bytes = br#"
schema_version: 2
kind: Provider
providers: []
bindings: []
"#;
        let (sv, kind) = peek_kind(bytes).unwrap();
        assert_eq!(sv, Some(2));
        assert_eq!(kind.as_deref(), Some("Provider"));
    }

    #[test]
    fn peek_kind_v1_legacy() {
        let bytes = br#"
schema_version: 1
editor:
  slug: x
  display_name: X
"#;
        let (sv, kind) = peek_kind(bytes).unwrap();
        assert_eq!(sv, Some(1));
        assert_eq!(kind, None);
    }

    #[test]
    fn resolve_ref_qualified() {
        let mut tools: BTreeMap<(String, String, String), ResolvedTool> = BTreeMap::new();
        let key = (
            "openlatch".to_string(),
            "coinflip-tool".to_string(),
            "0.1.0".to_string(),
        );
        // We can't easily construct a fake ResolvedTool here without going
        // through the schema parser; resolve_ref only uses the keys map.
        // Insert a placeholder via test-only helper.
        tools.insert(
            key.clone(),
            ResolvedTool {
                manifest_path: PathBuf::from("/dev/null"),
                editor_slug: "openlatch".to_string(),
                editor: serde_json::from_value(serde_json::json!({
                    "slug": "openlatch",
                    "display_name": "OpenLatch"
                }))
                .expect("test editor fixture must deserialize"),
                tool: serde_json::from_value(serde_json::json!({
                    "slug": "coinflip-tool",
                    "version": "0.1.0",
                    "license": "apache-2.0",
                    "description": "x",
                    "hooks_supported": ["pre_tool_use"],
                    "agents_supported": ["claude-code"],
                    "capabilities": [{
                        "threat_category": "pii_outbound",
                        "execution_mode": "sync",
                        "declared_latency_p95_ms": 30,
                        "needs_raw_payload": false
                    }],
                    "process": {
                        "command": ["echo", "hi"],
                        "health_check": { "http": { "port": 8081 } }
                    }
                }))
                .expect("test fixture must deserialize"),
            },
        );
        let r = resolve_ref("openlatch/coinflip-tool@0.1.0", &tools).unwrap();
        assert_eq!(
            r,
            ("openlatch".into(), "coinflip-tool".into(), "0.1.0".into())
        );
    }

    #[test]
    fn resolve_ref_unresolved_errors() {
        let tools: BTreeMap<(String, String, String), ResolvedTool> = BTreeMap::new();
        let err = resolve_ref("openlatch/coinflip-tool@0.1.0", &tools).unwrap_err();
        assert_eq!(err.code.code, "OL-4323");
    }

    #[test]
    fn resolve_ref_malformed_errors() {
        let tools: BTreeMap<(String, String, String), ResolvedTool> = BTreeMap::new();
        let err = resolve_ref("no-version-here", &tools).unwrap_err();
        assert_eq!(err.code.code, "OL-4323");
    }
}