ito-core 0.1.29

Core functionality and business logic for Ito
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
//! JSON configuration file CRUD operations.
//!
//! This module provides low-level functions for reading, writing, and
//! manipulating JSON configuration files with dot-delimited path navigation.

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

use crate::errors::{CoreError, CoreResult};
use ito_config::ConfigContext;
use ito_config::load_cascading_project_config;
use ito_config::types::{
    ArchiveMainIntegrationMode, IntegrationMode, MemoryConfig, MemoryOpConfig,
    RepositoryPersistenceMode, WorktreeStrategy,
};

/// Read a JSON config file, returning an empty object if the file doesn't exist.
///
/// # Errors
///
/// Returns [`CoreError::Serde`] if the file contains invalid JSON or is not a JSON object.
pub fn read_json_config(path: &Path) -> CoreResult<serde_json::Value> {
    let Ok(contents) = std::fs::read_to_string(path) else {
        return Ok(serde_json::Value::Object(serde_json::Map::new()));
    };
    let v: serde_json::Value = serde_json::from_str(&contents).map_err(|e| {
        CoreError::serde(format!("Invalid JSON in {}", path.display()), e.to_string())
    })?;
    match v {
        serde_json::Value::Object(_) => Ok(v),
        _ => Err(CoreError::serde(
            format!("Expected JSON object in {}", path.display()),
            "root value is not an object",
        )),
    }
}

/// Write a JSON value to a config file (pretty-printed with trailing newline).
///
/// # Errors
///
/// Returns [`CoreError::Serde`] if serialization fails, or [`CoreError::Io`] if writing fails.
pub fn write_json_config(path: &Path, value: &serde_json::Value) -> CoreResult<()> {
    let mut bytes = serde_json::to_vec_pretty(value)
        .map_err(|e| CoreError::serde("Failed to serialize JSON config", e.to_string()))?;
    bytes.push(b'\n');
    ito_common::io::write_atomic_std(path, bytes)
        .map_err(|e| CoreError::io(format!("Failed to write config to {}", path.display()), e))?;
    Ok(())
}

/// Parse a CLI argument as a JSON value, falling back to a string if parsing fails.
///
/// If `force_string` is true, always returns a JSON string without attempting to parse.
pub fn parse_json_value_arg(raw: &str, force_string: bool) -> serde_json::Value {
    if force_string {
        return serde_json::Value::String(raw.to_string());
    }
    match serde_json::from_str::<serde_json::Value>(raw) {
        Ok(v) => v,
        Err(_) => serde_json::Value::String(raw.to_string()),
    }
}

/// Split a dot-delimited config key path into parts, trimming and filtering empty segments.
pub fn json_split_path(key: &str) -> Vec<&str> {
    let mut out: Vec<&str> = Vec::new();
    for part in key.split('.') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        out.push(part);
    }
    out
}

/// Navigate a JSON object by a slice of path parts, returning the value if found.
pub fn json_get_path<'a>(
    root: &'a serde_json::Value,
    parts: &[&str],
) -> Option<&'a serde_json::Value> {
    let mut cur = root;
    for p in parts {
        let serde_json::Value::Object(map) = cur else {
            return None;
        };
        let next = map.get(*p)?;
        cur = next;
    }
    Some(cur)
}

/// Set a value at a dot-delimited path in a JSON object, creating intermediate objects as needed.
///
/// # Errors
///
/// Returns [`CoreError::Validation`] if the path is empty or if setting the path fails.
#[allow(clippy::match_like_matches_macro)]
pub fn json_set_path(
    root: &mut serde_json::Value,
    parts: &[&str],
    value: serde_json::Value,
) -> CoreResult<()> {
    if parts.is_empty() {
        return Err(CoreError::validation("Invalid empty path"));
    }

    let mut cur = root;
    for (i, key) in parts.iter().enumerate() {
        let is_last = i + 1 == parts.len();

        let is_object = match cur {
            serde_json::Value::Object(_) => true,
            _ => false,
        };
        if !is_object {
            *cur = serde_json::Value::Object(serde_json::Map::new());
        }

        let serde_json::Value::Object(map) = cur else {
            return Err(CoreError::validation("Failed to set path"));
        };

        if is_last {
            map.insert((*key).to_string(), value);
            return Ok(());
        }

        let needs_object = match map.get(*key) {
            Some(serde_json::Value::Object(_)) => false,
            Some(_) => true,
            None => true,
        };
        if needs_object {
            map.insert(
                (*key).to_string(),
                serde_json::Value::Object(serde_json::Map::new()),
            );
        }

        let Some(next) = map.get_mut(*key) else {
            return Err(CoreError::validation("Failed to set path"));
        };
        cur = next;
    }

    Ok(())
}

/// Validate a config value for known keys that require enum values.
///
/// Returns `Ok(())` if the key is not constrained or the value is valid.
/// Returns `Err` with a descriptive message if the value is invalid.
///
/// # Errors
///
/// Returns [`CoreError::Validation`] if the value does not match the allowed enum values.
pub fn validate_config_value(parts: &[&str], value: &serde_json::Value) -> CoreResult<()> {
    let path = parts.join(".");
    match path.as_str() {
        "worktrees.strategy" => {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a string value. Valid values: {}",
                    path,
                    WorktreeStrategy::ALL.join(", ")
                )));
            };
            if WorktreeStrategy::parse_value(s).is_none() {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Valid values: {}",
                    s,
                    path,
                    WorktreeStrategy::ALL.join(", ")
                )));
            }
        }
        "worktrees.apply.integration_mode" => {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a string value. Valid values: {}",
                    path,
                    IntegrationMode::ALL.join(", ")
                )));
            };
            if IntegrationMode::parse_value(s).is_none() {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Valid values: {}",
                    s,
                    path,
                    IntegrationMode::ALL.join(", ")
                )));
            }
        }
        "repository.mode" => {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a string value. Valid values: {}",
                    path,
                    RepositoryPersistenceMode::ALL.join(", ")
                )));
            };
            if RepositoryPersistenceMode::parse_value(s).is_none() {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Valid values: {}",
                    s,
                    path,
                    RepositoryPersistenceMode::ALL.join(", ")
                )));
            }
        }
        "changes.coordination_branch.name" => {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a string value.",
                    path,
                )));
            };
            if !is_valid_branch_name(s) {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Provide a valid git branch name.",
                    s, path,
                )));
            }
        }
        "changes.coordination_branch.sync_interval_seconds" => {
            let Some(n) = value.as_u64() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a positive integer value in seconds.",
                    path,
                )));
            };
            if n == 0 {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Provide a positive integer number of seconds.",
                    n, path,
                )));
            }
        }
        "changes.archive.main_integration_mode" => {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a string value. Valid values: {}",
                    path,
                    ArchiveMainIntegrationMode::ALL.join(", ")
                )));
            };
            if ArchiveMainIntegrationMode::parse_value(s).is_none() {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Valid values: {}",
                    s,
                    path,
                    ArchiveMainIntegrationMode::ALL.join(", ")
                )));
            }
        }
        "audit.mirror.branch" => {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a string value.",
                    path,
                )));
            };
            if !is_valid_branch_name(s) {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Provide a valid git branch name.",
                    s, path,
                )));
            }
        }
        path if matches!(
            parts,
            ["memory", op, "kind"]
                if matches!(*op, "capture" | "search" | "query")
        ) =>
        {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a string value. Valid values: skill, command",
                    path,
                )));
            };
            if !matches!(s, "skill" | "command") {
                return Err(CoreError::validation(format!(
                    "Invalid value '{}' for key '{}'. Valid values: skill, command",
                    s, path,
                )));
            }
        }
        path if matches!(
            parts,
            ["memory", op, "skill"]
                if matches!(*op, "capture" | "search" | "query")
        ) =>
        {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a non-empty string skill id.",
                    path,
                )));
            };
            if s.trim().is_empty() {
                return Err(CoreError::validation(format!(
                    "Invalid value for key '{}'. Provide a non-empty skill id.",
                    path,
                )));
            }
        }
        path if matches!(
            parts,
            ["memory", op, "command"]
                if matches!(*op, "capture" | "search" | "query")
        ) =>
        {
            let Some(s) = value.as_str() else {
                return Err(CoreError::validation(format!(
                    "Key '{}' requires a non-empty string command template.",
                    path,
                )));
            };
            if s.trim().is_empty() {
                return Err(CoreError::validation(format!(
                    "Invalid value for key '{}'. Provide a non-empty command template.",
                    path,
                )));
            }
        }
        _ if matches!(parts, ["memory", op] if matches!(*op, "capture" | "search" | "query")) => {
            let op_name = parts[1];
            return validate_memory_op_value(op_name, value);
        }
        _ if parts == ["memory"] => {
            return validate_memory_section_value(value);
        }
        // Wildcard: config keys are open-ended strings; only enum-constrained
        // keys are validated above. New constrained keys should be added here.
        _ => {}
    }
    Ok(())
}

/// Validate a structurally-set `memory` section value.
///
/// Accepts the leaf values for each operation (`capture`, `search`, `query`).
/// Unknown operation keys are rejected here so that `ito config set memory <json>`
/// surfaces typos like `curate` (instead of `capture`) with a clear message.
fn validate_memory_section_value(value: &serde_json::Value) -> CoreResult<()> {
    let Some(obj) = value.as_object() else {
        return Err(CoreError::validation(
            "Key 'memory' requires an object whose keys are operation names (capture, search, query).",
        ));
    };
    for (key, child) in obj {
        match key.as_str() {
            "capture" | "search" | "query" => validate_memory_op_value(key, child)?,
            other => {
                return Err(CoreError::validation(format!(
                    "Unknown memory operation '{}'. Valid keys: capture, search, query.",
                    other
                )));
            }
        }
    }
    Ok(())
}

/// Validate a structurally-set `memory.<op>` value.
///
/// `op_name` is `capture`, `search`, or `query`.
fn validate_memory_op_value(op_name: &str, value: &serde_json::Value) -> CoreResult<()> {
    let Some(obj) = value.as_object() else {
        return Err(CoreError::validation(format!(
            "Key 'memory.{}' requires an object describing the provider shape.",
            op_name
        )));
    };

    let Some(kind) = obj.get("kind").and_then(|v| v.as_str()) else {
        return Err(CoreError::validation(format!(
            "Key 'memory.{}' must include a string 'kind' field. Valid values: skill, command.",
            op_name
        )));
    };

    match kind {
        "skill" => match obj.get("skill").and_then(|v| v.as_str()) {
            Some(s) if !s.trim().is_empty() => Ok(()),
            _ => Err(CoreError::validation(format!(
                "Key 'memory.{}.skill' is required and must be a non-empty string when kind is 'skill'.",
                op_name
            ))),
        },
        "command" => match obj.get("command").and_then(|v| v.as_str()) {
            Some(s) if !s.trim().is_empty() => Ok(()),
            _ => Err(CoreError::validation(format!(
                "Key 'memory.{}.command' is required and must be a non-empty string when kind is 'command'.",
                op_name
            ))),
        },
        other => Err(CoreError::validation(format!(
            "Invalid 'kind' value '{}' for 'memory.{}'. Valid values: skill, command.",
            other, op_name
        ))),
    }
}

/// Validate a deserialized [`MemoryConfig`].
///
/// Performs structural checks that serde alone cannot enforce — most notably
/// that any operation configured with `kind: "skill"` references a skill id
/// discoverable under one of the supplied search paths.
///
/// `search_paths` SHOULD be the list of skills directories returned by
/// [`known_skills_search_paths`] for the active project.
///
/// # Errors
///
/// Returns [`CoreError::Validation`] for any operation whose skill id does
/// not resolve to a directory containing `SKILL.md` under one of the
/// supplied search paths. Lists the searched paths in the error message.
pub fn validate_memory_config(config: &MemoryConfig, search_paths: &[PathBuf]) -> CoreResult<()> {
    for (op_name, op) in [
        ("capture", &config.capture),
        ("search", &config.search),
        ("query", &config.query),
    ] {
        let Some(MemoryOpConfig::Skill { skill, .. }) = op else {
            continue;
        };

        if skill.trim().is_empty() {
            return Err(CoreError::validation(format!(
                "Key 'memory.{}.skill' must be a non-empty string when kind is 'skill'.",
                op_name
            )));
        }

        if !skill_id_resolves(skill, search_paths) {
            let searched = search_paths
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join(", ");
            return Err(CoreError::validation(format!(
                "memory.{op}: skill id '{skill}' was not found under any of the searched skills directories: [{searched}]. Install the skill or correct the id.",
                op = op_name,
                skill = skill,
                searched = if searched.is_empty() {
                    "(none configured)".to_string()
                } else {
                    searched
                },
            )));
        }
    }
    Ok(())
}

/// Return the conventional skills directories Ito searches when resolving a
/// skill id under [`MemoryOpConfig::Skill`].
///
/// Order is deterministic for stable error messages but does not imply any
/// preference — a skill id matches as soon as any directory contains
/// `<dir>/<skill-id>/SKILL.md` (or the skill id directly under
/// `.agents/skills/<group>/<skill-id>/SKILL.md` for the shared layout used
/// by ByteRover).
pub fn known_skills_search_paths(project_root: &Path) -> Vec<PathBuf> {
    [
        ".agents/skills",
        ".claude/skills",
        ".codex/skills",
        ".opencode/skills",
        ".pi/skills",
        ".github/skills",
    ]
    .into_iter()
    .map(|p| project_root.join(p))
    .collect()
}

/// Returns `true` if `skill_id` resolves to a directory containing
/// `SKILL.md` under any of the supplied search paths.
///
/// Resolution accepts two layouts:
/// - **Flat**: `<search-path>/<skill-id>/SKILL.md` (used by `.claude/skills/`,
///   `.opencode/skills/`, etc.).
/// - **Grouped**: `<search-path>/<group>/<skill-id>/SKILL.md` (used by
///   `.agents/skills/<group>/<skill-id>/SKILL.md` — e.g. the ByteRover hub
///   skills mirrored under `.agents/skills/byterover/`).
pub fn skill_id_resolves(skill_id: &str, search_paths: &[PathBuf]) -> bool {
    for base in search_paths {
        if !base.is_dir() {
            continue;
        }
        // Flat layout.
        if base.join(skill_id).join("SKILL.md").is_file() {
            return true;
        }
        // Grouped layout — one level deeper.
        let Ok(entries) = std::fs::read_dir(base) else {
            continue;
        };
        for entry in entries {
            let Ok(entry) = entry else {
                continue;
            };
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            if path.join(skill_id).join("SKILL.md").is_file() {
                return true;
            }
        }
    }
    false
}

fn is_valid_branch_name(value: &str) -> bool {
    if value.is_empty() || value.starts_with('-') || value.starts_with('/') || value.ends_with('/')
    {
        return false;
    }
    if value.contains("..")
        || value.contains("@{")
        || value.contains("//")
        || value.ends_with('.')
        || value.ends_with(".lock")
    {
        return false;
    }

    for ch in value.chars() {
        if ch.is_ascii_control() || ch == ' ' {
            return false;
        }
        if ch == '~' || ch == '^' || ch == ':' || ch == '?' || ch == '*' || ch == '[' || ch == '\\'
        {
            return false;
        }
    }

    for segment in value.split('/') {
        if segment.is_empty()
            || segment.starts_with('.')
            || segment.ends_with('.')
            || segment.ends_with(".lock")
        {
            return false;
        }
    }

    true
}

/// Validate that a worktree strategy string is one of the supported values.
///
/// Returns `true` if valid, `false` otherwise.
pub fn is_valid_worktree_strategy(s: &str) -> bool {
    WorktreeStrategy::parse_value(s).is_some()
}

/// Validate that an integration mode string is one of the supported values.
///
/// Returns `true` if valid, `false` otherwise.
pub fn is_valid_integration_mode(s: &str) -> bool {
    IntegrationMode::parse_value(s).is_some()
}

/// Validate that a repository persistence mode string is one of the supported values.
///
/// Returns `true` if valid, `false` otherwise.
pub fn is_valid_repository_mode(s: &str) -> bool {
    RepositoryPersistenceMode::parse_value(s).is_some()
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Resolved defaults used when rendering worktree-aware templates.
pub struct WorktreeTemplateDefaults {
    /// Worktree strategy (e.g., `checkout_subdir`).
    pub strategy: String,
    /// Directory name used by the strategy layout.
    pub layout_dir_name: String,
    /// Integration mode for applying changes.
    pub integration_mode: String,
    /// Default branch name.
    pub default_branch: String,
}

/// Resolve effective worktree defaults from cascading project configuration.
///
/// Falls back to built-in defaults when keys are not configured.
pub fn resolve_worktree_template_defaults(
    target_path: &Path,
    ctx: &ConfigContext,
) -> WorktreeTemplateDefaults {
    let ito_path = ito_config::ito_dir::get_ito_path(target_path, ctx);
    let merged = load_cascading_project_config(target_path, &ito_path, ctx).merged;

    let mut defaults = WorktreeTemplateDefaults {
        strategy: "checkout_subdir".to_string(),
        layout_dir_name: "ito-worktrees".to_string(),
        integration_mode: "commit_pr".to_string(),
        default_branch: "main".to_string(),
    };

    if let Some(wt) = merged.get("worktrees") {
        if let Some(v) = wt.get("strategy").and_then(|v| v.as_str())
            && !v.is_empty()
        {
            defaults.strategy = v.to_string();
        }

        if let Some(v) = wt.get("default_branch").and_then(|v| v.as_str())
            && !v.is_empty()
        {
            defaults.default_branch = v.to_string();
        }

        if let Some(layout) = wt.get("layout")
            && let Some(v) = layout.get("dir_name").and_then(|v| v.as_str())
            && !v.is_empty()
        {
            defaults.layout_dir_name = v.to_string();
        }

        if let Some(apply) = wt.get("apply")
            && let Some(v) = apply.get("integration_mode").and_then(|v| v.as_str())
            && !v.is_empty()
        {
            defaults.integration_mode = v.to_string();
        }
    }

    defaults
}

/// Remove a key at a dot-delimited path in a JSON object.
///
/// Returns `true` if a key was removed, `false` if the path didn't exist.
///
/// # Errors
///
/// Returns [`CoreError::Validation`] if the path is empty.
pub fn json_unset_path(root: &mut serde_json::Value, parts: &[&str]) -> CoreResult<bool> {
    if parts.is_empty() {
        return Err(CoreError::validation("Invalid empty path"));
    }

    let mut cur = root;
    for (i, p) in parts.iter().enumerate() {
        let is_last = i + 1 == parts.len();
        let serde_json::Value::Object(map) = cur else {
            return Ok(false);
        };

        if is_last {
            return Ok(map.remove(*p).is_some());
        }

        let Some(next) = map.get_mut(*p) else {
            return Ok(false);
        };
        cur = next;
    }

    Ok(false)
}

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

    #[test]
    fn validate_config_value_accepts_valid_strategy() {
        let parts = ["worktrees", "strategy"];
        let value = json!("checkout_subdir");
        assert!(validate_config_value(&parts, &value).is_ok());

        let value = json!("checkout_siblings");
        assert!(validate_config_value(&parts, &value).is_ok());

        let value = json!("bare_control_siblings");
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn validate_config_value_rejects_invalid_strategy() {
        let parts = ["worktrees", "strategy"];
        let value = json!("custom_layout");
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Invalid value"));
        assert!(msg.contains("custom_layout"));
    }

    #[test]
    fn validate_config_value_rejects_non_string_strategy() {
        let parts = ["worktrees", "strategy"];
        let value = json!(42);
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("requires a string value"));
    }

    #[test]
    fn validate_config_value_accepts_valid_integration_mode() {
        let parts = ["worktrees", "apply", "integration_mode"];
        let value = json!("commit_pr");
        assert!(validate_config_value(&parts, &value).is_ok());

        let value = json!("merge_parent");
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn validate_config_value_accepts_valid_repository_mode() {
        let parts = ["repository", "mode"];
        let value = json!("filesystem");
        assert!(validate_config_value(&parts, &value).is_ok());

        let value = json!("sqlite");
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn validate_config_value_rejects_invalid_repository_mode() {
        let parts = ["repository", "mode"];
        let value = json!("remote");
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Invalid value"));
        assert!(msg.contains("repository.mode"));
    }

    #[test]
    fn validate_config_value_rejects_invalid_integration_mode() {
        let parts = ["worktrees", "apply", "integration_mode"];
        let value = json!("squash_merge");
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Invalid value"));
        assert!(msg.contains("squash_merge"));
    }

    #[test]
    fn validate_config_value_accepts_unknown_keys() {
        let parts = ["worktrees", "enabled"];
        let value = json!(true);
        assert!(validate_config_value(&parts, &value).is_ok());

        let parts = ["some", "other", "key"];
        let value = json!("anything");
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn is_valid_worktree_strategy_checks_correctly() {
        assert!(is_valid_worktree_strategy("checkout_subdir"));
        assert!(is_valid_worktree_strategy("checkout_siblings"));
        assert!(is_valid_worktree_strategy("bare_control_siblings"));
        assert!(!is_valid_worktree_strategy("custom"));
        assert!(!is_valid_worktree_strategy(""));
    }

    #[test]
    fn is_valid_integration_mode_checks_correctly() {
        assert!(is_valid_integration_mode("commit_pr"));
        assert!(is_valid_integration_mode("merge_parent"));
        assert!(!is_valid_integration_mode("squash"));
        assert!(!is_valid_integration_mode(""));
    }

    #[test]
    fn is_valid_repository_mode_checks_correctly() {
        assert!(is_valid_repository_mode("filesystem"));
        assert!(is_valid_repository_mode("sqlite"));
        assert!(!is_valid_repository_mode("remote"));
        assert!(!is_valid_repository_mode(""));
    }

    #[test]
    fn validate_config_value_accepts_valid_coordination_branch_name() {
        let parts = ["changes", "coordination_branch", "name"];
        let value = json!("ito/internal/changes");
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn validate_config_value_rejects_invalid_coordination_branch_name() {
        let parts = ["changes", "coordination_branch", "name"];
        let value = json!("--ito-changes");
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Invalid value"));
        assert!(msg.contains("changes.coordination_branch.name"));
    }

    #[test]
    fn validate_config_value_rejects_lock_suffix_in_path_segment() {
        let parts = ["changes", "coordination_branch", "name"];
        let value = json!("foo.lock/bar");
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Invalid value"));
        assert!(msg.contains("changes.coordination_branch.name"));
    }

    #[test]
    fn validate_config_value_accepts_positive_sync_interval() {
        let parts = ["changes", "coordination_branch", "sync_interval_seconds"];
        let value = json!(120);
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn validate_config_value_rejects_zero_sync_interval() {
        let parts = ["changes", "coordination_branch", "sync_interval_seconds"];
        let value = json!(0);
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("positive integer"));
        assert!(msg.contains("changes.coordination_branch.sync_interval_seconds"));
    }

    #[test]
    fn validate_config_value_accepts_archive_main_integration_mode() {
        let parts = ["changes", "archive", "main_integration_mode"];
        let value = json!("pull_request_auto_merge");
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn validate_config_value_rejects_invalid_archive_main_integration_mode() {
        let parts = ["changes", "archive", "main_integration_mode"];
        let value = json!("always_merge");
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Invalid value"));
        assert!(msg.contains("changes.archive.main_integration_mode"));
    }

    #[test]
    fn validate_config_value_accepts_valid_audit_mirror_branch_name() {
        let parts = ["audit", "mirror", "branch"];
        let value = json!("ito/internal/audit");
        assert!(validate_config_value(&parts, &value).is_ok());
    }

    #[test]
    fn validate_config_value_rejects_invalid_audit_mirror_branch_name() {
        let parts = ["audit", "mirror", "branch"];
        let value = json!("--ito-audit");
        let err = validate_config_value(&parts, &value).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Invalid value"));
        assert!(msg.contains("audit.mirror.branch"));
    }

    #[test]
    fn resolve_worktree_template_defaults_uses_defaults_when_missing() {
        let project = tempfile::tempdir().expect("tempdir should succeed");
        let ctx = ConfigContext {
            project_dir: Some(project.path().to_path_buf()),
            ..Default::default()
        };

        let resolved = resolve_worktree_template_defaults(project.path(), &ctx);
        assert_eq!(
            resolved,
            WorktreeTemplateDefaults {
                strategy: "checkout_subdir".to_string(),
                layout_dir_name: "ito-worktrees".to_string(),
                integration_mode: "commit_pr".to_string(),
                default_branch: "main".to_string(),
            }
        );
    }

    #[test]
    fn resolve_worktree_template_defaults_reads_overrides() {
        let project = tempfile::tempdir().expect("tempdir should succeed");
        let ito_dir = project.path().join(".ito");
        std::fs::create_dir_all(&ito_dir).expect("create .ito should succeed");
        std::fs::write(
            ito_dir.join("config.json"),
            r#"{
  "worktrees": {
    "strategy": "bare_control_siblings",
    "default_branch": "develop",
    "layout": { "dir_name": "wt" },
    "apply": { "integration_mode": "merge_parent" }
  }
}
"#,
        )
        .expect("write config should succeed");

        let ctx = ConfigContext {
            project_dir: Some(project.path().to_path_buf()),
            ..Default::default()
        };

        let resolved = resolve_worktree_template_defaults(project.path(), &ctx);
        assert_eq!(
            resolved,
            WorktreeTemplateDefaults {
                strategy: "bare_control_siblings".to_string(),
                layout_dir_name: "wt".to_string(),
                integration_mode: "merge_parent".to_string(),
                default_branch: "develop".to_string(),
            }
        );
    }

    // ---- memory config validation ------------------------------------------------

    #[test]
    fn validate_config_value_rejects_unknown_memory_kind() {
        let parts = ["memory", "capture", "kind"];
        let value = json!("delegate");
        let err = validate_config_value(&parts, &value).expect_err("expected error");
        let msg = err.to_string();
        assert!(msg.contains("memory.capture.kind"), "msg = {msg}");
        assert!(msg.contains("skill") && msg.contains("command"));
    }

    #[test]
    fn validate_config_value_accepts_valid_memory_kind() {
        for op in ["capture", "search", "query"] {
            let parts = ["memory", op, "kind"];
            for kind in ["skill", "command"] {
                assert!(
                    validate_config_value(&parts, &json!(kind)).is_ok(),
                    "expected memory.{op}.kind = {kind} to validate"
                );
            }
        }
    }

    #[test]
    fn validate_config_value_rejects_empty_memory_skill_id() {
        let parts = ["memory", "search", "skill"];
        let err = validate_config_value(&parts, &json!("   ")).expect_err("expected error");
        assert!(
            err.to_string().contains("memory.search.skill"),
            "msg = {err}"
        );
    }

    #[test]
    fn validate_config_value_rejects_empty_memory_command_template() {
        let parts = ["memory", "query", "command"];
        let err = validate_config_value(&parts, &json!("")).expect_err("expected error");
        assert!(
            err.to_string().contains("memory.query.command"),
            "msg = {err}"
        );
    }

    #[test]
    fn validate_config_value_rejects_unknown_memory_op_key() {
        let parts = ["memory"];
        let value = json!({
            "curate": { "kind": "command", "command": "noop" }
        });
        let err = validate_config_value(&parts, &value).expect_err("expected error");
        let msg = err.to_string();
        assert!(msg.contains("Unknown memory operation"), "msg = {msg}");
        assert!(msg.contains("curate"), "msg = {msg}");
    }

    #[test]
    fn validate_config_value_rejects_memory_op_missing_required_field() {
        let parts = ["memory", "capture"];

        let err = validate_config_value(&parts, &json!({ "kind": "skill" }))
            .expect_err("skill variant requires `skill`");
        assert!(err.to_string().contains("memory.capture.skill"));

        let err = validate_config_value(&parts, &json!({ "kind": "command" }))
            .expect_err("command variant requires `command`");
        assert!(err.to_string().contains("memory.capture.command"));
    }

    #[test]
    fn validate_config_value_rejects_memory_op_unknown_kind() {
        let parts = ["memory", "search"];
        let err = validate_config_value(&parts, &json!({ "kind": "magic", "command": "noop" }))
            .expect_err("expected error");
        let msg = err.to_string();
        assert!(msg.contains("Invalid 'kind' value 'magic'"), "msg = {msg}");
        assert!(msg.contains("memory.search"), "msg = {msg}");
    }

    #[test]
    fn validate_memory_config_passes_when_no_skill_provider() {
        let config = MemoryConfig {
            capture: Some(MemoryOpConfig::Command {
                command: "brv curate \"{context}\"".to_string(),
            }),
            search: None,
            query: None,
        };
        validate_memory_config(&config, &[]).expect("command-only config should validate");
    }

    #[test]
    fn validate_memory_config_passes_when_skill_resolves_in_flat_layout() {
        let tmp = tempfile::TempDir::new().unwrap();
        let skill_dir = tmp.path().join(".claude/skills/my-skill");
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(skill_dir.join("SKILL.md"), "stub").unwrap();

        let config = MemoryConfig {
            capture: Some(MemoryOpConfig::Skill {
                skill: "my-skill".to_string(),
                options: None,
            }),
            search: None,
            query: None,
        };
        let paths = known_skills_search_paths(tmp.path());
        validate_memory_config(&config, &paths).expect("flat skill should resolve");
    }

    #[test]
    fn validate_memory_config_passes_when_skill_resolves_in_grouped_layout() {
        let tmp = tempfile::TempDir::new().unwrap();
        let skill_dir = tmp
            .path()
            .join(".agents/skills/byterover/byterover-explore");
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(skill_dir.join("SKILL.md"), "stub").unwrap();

        let config = MemoryConfig {
            capture: Some(MemoryOpConfig::Skill {
                skill: "byterover-explore".to_string(),
                options: None,
            }),
            search: None,
            query: None,
        };
        let paths = known_skills_search_paths(tmp.path());
        validate_memory_config(&config, &paths)
            .expect("grouped skill (.agents/skills/<group>/<id>) should resolve");
    }

    #[test]
    fn validate_memory_config_rejects_missing_skill() {
        let tmp = tempfile::TempDir::new().unwrap();
        let config = MemoryConfig {
            capture: None,
            search: Some(MemoryOpConfig::Skill {
                skill: "nonexistent".to_string(),
                options: None,
            }),
            query: None,
        };
        let paths = known_skills_search_paths(tmp.path());
        let err = validate_memory_config(&config, &paths)
            .expect_err("missing skill should fail validation");
        let msg = err.to_string();
        assert!(msg.contains("memory.search"), "msg = {msg}");
        assert!(msg.contains("nonexistent"), "msg = {msg}");
        // Searched-paths list should include at least one of the conventional dirs.
        assert!(msg.contains(".agents/skills") || msg.contains(".claude/skills"));
    }

    #[test]
    fn skill_id_resolves_returns_false_when_no_paths_exist() {
        let tmp = tempfile::TempDir::new().unwrap();
        let paths = known_skills_search_paths(tmp.path());
        assert!(!skill_id_resolves("anything", &paths));
    }
}