litvc 1.0.1

Lit - The agentic-first distributed version control system. A complete Git replacement designed for AI agents first and humans second.
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
//! Content type system — extends Lit from SWE-only VCS to a universal
//! versioning system for CAD, EDA, manuscripts, databases, scientific data,
//! media assets, and arbitrary domain content.
//!
//! Each content type carries diff/merge strategy hints, metadata schemas,
//! and size/storage policies so that Lit can handle domain-specific files
//! without requiring external plugins.

use crate::core::find_repo_root;
use crate::errors::LitError;
use crate::response::ContentTypeResponse;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;

// ── Data types ──────────────────────────────────────────────────────────────

/// How a content type should be diffed
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum DiffStrategy {
    /// Line-based textual diff (source code, markdown, config)
    Text,
    /// Binary diff (delta compression)
    Binary,
    /// Structural diff (JSON/XML/AST tree comparison)
    Structural,
    /// Semantic diff (schema-aware: databases, CAD feature trees)
    Semantic,
    /// No diff — treat as opaque blob, show only size/hash changes
    Opaque,
}

/// How a content type should be merged
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum MergeStrategy {
    /// Standard 3-way text merge
    TextThreeWay,
    /// Take ours or theirs — no automatic merge (binary, CAD)
    ManualResolve,
    /// Schema-aware merge (databases, structured data)
    SchemaAware,
    /// Component-level merge (EDA: merge at schematic block level)
    ComponentLevel,
    /// Append-only merge (logs, audit trails)
    AppendOnly,
    /// Last-writer-wins (media assets, compiled outputs)
    LastWriterWins,
}

/// Storage tier hint
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum StorageTier {
    /// Normal object store (small text files)
    Standard,
    /// LFS — large file storage (binary assets, datasets)
    Lfs,
    /// Chunked — content-defined chunking for large structured files
    Chunked,
    /// External — reference to external storage (S3, GCS, NFS)
    External,
}

/// Domain classification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ContentDomain {
    Software,
    Cad,
    Eda,
    Manuscript,
    Database,
    Scientific,
    Media,
    Geospatial,
    Legal,
    Financial,
    Config,
    Documentation,
    Custom(String),
}

impl std::fmt::Display for ContentDomain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ContentDomain::Software => write!(f, "software"),
            ContentDomain::Cad => write!(f, "cad"),
            ContentDomain::Eda => write!(f, "eda"),
            ContentDomain::Manuscript => write!(f, "manuscript"),
            ContentDomain::Database => write!(f, "database"),
            ContentDomain::Scientific => write!(f, "scientific"),
            ContentDomain::Media => write!(f, "media"),
            ContentDomain::Geospatial => write!(f, "geospatial"),
            ContentDomain::Legal => write!(f, "legal"),
            ContentDomain::Financial => write!(f, "financial"),
            ContentDomain::Config => write!(f, "config"),
            ContentDomain::Documentation => write!(f, "documentation"),
            ContentDomain::Custom(s) => write!(f, "custom:{}", s),
        }
    }
}

/// A registered content type with domain-specific handling policies
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentType {
    /// Unique identifier (e.g. "cad/step", "eda/kicad-pcb", "db/sqlite")
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Domain classification
    pub domain: ContentDomain,
    /// MIME type(s) associated with this content type
    pub mime_types: Vec<String>,
    /// File extensions (without dot) that map to this type
    pub extensions: Vec<String>,
    /// Magic bytes for binary detection (hex-encoded prefixes)
    #[serde(default)]
    pub magic_bytes: Vec<String>,
    /// Recommended diff strategy
    pub diff_strategy: DiffStrategy,
    /// Recommended merge strategy
    pub merge_strategy: MergeStrategy,
    /// Storage tier
    pub storage_tier: StorageTier,
    /// Maximum inline size (bytes) before promoting to LFS
    pub lfs_threshold: Option<u64>,
    /// Metadata schema — JSON Schema fragment describing domain-specific fields
    #[serde(default)]
    pub metadata_schema: Option<serde_json::Value>,
    /// Whether this type supports structural diffing natively
    pub structural_diff: bool,
    /// Whether this type supports component-level locking
    pub component_locking: bool,
    /// Description
    pub description: String,
}

// ── Built-in content types ──────────────────────────────────────────────────

fn builtin_types() -> Vec<ContentType> {
    vec![
        // ── CAD ──
        ContentType {
            id: "cad/step".into(),
            name: "STEP CAD Model".into(),
            domain: ContentDomain::Cad,
            mime_types: vec!["model/step".into()],
            extensions: vec!["step".into(), "stp".into(), "p21".into()],
            magic_bytes: vec!["49534F2D".into()], // "ISO-"
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ManualResolve,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "units": {"type": "string", "enum": ["mm", "in", "m"]},
                    "assembly_count": {"type": "integer"},
                    "bounding_box": {"type": "array", "items": {"type": "number"}}
                }
            })),
            structural_diff: true,
            component_locking: true,
            description: "ISO 10303 STEP geometry exchange format".into(),
        },
        ContentType {
            id: "cad/stl".into(),
            name: "STL Mesh".into(),
            domain: ContentDomain::Cad,
            mime_types: vec!["model/stl".into()],
            extensions: vec!["stl".into()],
            magic_bytes: vec!["736F6C6964".into()], // "solid" (ASCII STL)
            diff_strategy: DiffStrategy::Opaque,
            merge_strategy: MergeStrategy::LastWriterWins,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(512 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "triangle_count": {"type": "integer"},
                    "format": {"type": "string", "enum": ["ascii", "binary"]}
                }
            })),
            structural_diff: false,
            component_locking: false,
            description: "Stereolithography mesh format for 3D printing".into(),
        },
        ContentType {
            id: "cad/iges".into(),
            name: "IGES CAD Model".into(),
            domain: ContentDomain::Cad,
            mime_types: vec!["model/iges".into()],
            extensions: vec!["igs".into(), "iges".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ManualResolve,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(1024 * 1024),
            metadata_schema: None,
            structural_diff: true,
            component_locking: false,
            description: "Initial Graphics Exchange Specification".into(),
        },
        ContentType {
            id: "cad/3mf".into(),
            name: "3MF Model".into(),
            domain: ContentDomain::Cad,
            mime_types: vec![
                "model/3mf".into(),
                "application/vnd.ms-package.3dmanufacturing-3dmodel+xml".into(),
            ],
            extensions: vec!["3mf".into()],
            magic_bytes: vec!["504B0304".into()], // ZIP header
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ComponentLevel,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(1024 * 1024),
            metadata_schema: None,
            structural_diff: true,
            component_locking: true,
            description: "3D Manufacturing Format (ZIP-based XML)".into(),
        },
        // ── EDA ──
        ContentType {
            id: "eda/kicad-pcb".into(),
            name: "KiCad PCB Layout".into(),
            domain: ContentDomain::Eda,
            mime_types: vec!["application/x-kicad-pcb".into()],
            extensions: vec!["kicad_pcb".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ComponentLevel,
            storage_tier: StorageTier::Standard,
            lfs_threshold: Some(50 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "layers": {"type": "integer"},
                    "component_count": {"type": "integer"},
                    "net_count": {"type": "integer"},
                    "board_dimensions": {"type": "object", "properties": {
                        "width_mm": {"type": "number"},
                        "height_mm": {"type": "number"}
                    }}
                }
            })),
            structural_diff: true,
            component_locking: true,
            description: "KiCad PCB layout (S-expression format)".into(),
        },
        ContentType {
            id: "eda/kicad-sch".into(),
            name: "KiCad Schematic".into(),
            domain: ContentDomain::Eda,
            mime_types: vec!["application/x-kicad-schematic".into()],
            extensions: vec!["kicad_sch".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ComponentLevel,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: None,
            structural_diff: true,
            component_locking: true,
            description: "KiCad schematic (S-expression format)".into(),
        },
        ContentType {
            id: "eda/gerber".into(),
            name: "Gerber PCB Fabrication".into(),
            domain: ContentDomain::Eda,
            mime_types: vec!["application/x-gerber".into()],
            extensions: vec![
                "gbr".into(),
                "ger".into(),
                "gtl".into(),
                "gbl".into(),
                "gts".into(),
                "gbs".into(),
            ],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Text,
            merge_strategy: MergeStrategy::LastWriterWins,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "Gerber RS-274X PCB fabrication data".into(),
        },
        ContentType {
            id: "eda/spice".into(),
            name: "SPICE Netlist".into(),
            domain: ContentDomain::Eda,
            mime_types: vec!["text/x-spice".into()],
            extensions: vec!["spice".into(), "sp".into(), "cir".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Text,
            merge_strategy: MergeStrategy::TextThreeWay,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "SPICE circuit simulation netlist".into(),
        },
        // ── Manuscripts ──
        ContentType {
            id: "manuscript/latex".into(),
            name: "LaTeX Document".into(),
            domain: ContentDomain::Manuscript,
            mime_types: vec!["application/x-latex".into(), "text/x-tex".into()],
            extensions: vec!["tex".into(), "latex".into(), "ltx".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Text,
            merge_strategy: MergeStrategy::TextThreeWay,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "document_class": {"type": "string"},
                    "word_count": {"type": "integer"},
                    "bibliography_entries": {"type": "integer"}
                }
            })),
            structural_diff: false,
            component_locking: false,
            description: "LaTeX typesetting source".into(),
        },
        ContentType {
            id: "manuscript/docx".into(),
            name: "Word Document".into(),
            domain: ContentDomain::Manuscript,
            mime_types: vec![
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document".into(),
            ],
            extensions: vec!["docx".into()],
            magic_bytes: vec!["504B0304".into()], // ZIP
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ManualResolve,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(5 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "page_count": {"type": "integer"},
                    "word_count": {"type": "integer"},
                    "author": {"type": "string"},
                    "revision": {"type": "integer"}
                }
            })),
            structural_diff: true,
            component_locking: false,
            description: "Microsoft Word OOXML document".into(),
        },
        ContentType {
            id: "manuscript/typst".into(),
            name: "Typst Document".into(),
            domain: ContentDomain::Manuscript,
            mime_types: vec!["text/x-typst".into()],
            extensions: vec!["typ".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Text,
            merge_strategy: MergeStrategy::TextThreeWay,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "Typst markup language source".into(),
        },
        ContentType {
            id: "manuscript/asciidoc".into(),
            name: "AsciiDoc".into(),
            domain: ContentDomain::Manuscript,
            mime_types: vec!["text/asciidoc".into()],
            extensions: vec!["adoc".into(), "asciidoc".into(), "asc".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Text,
            merge_strategy: MergeStrategy::TextThreeWay,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "AsciiDoc markup language".into(),
        },
        // ── Databases ──
        ContentType {
            id: "db/sqlite".into(),
            name: "SQLite Database".into(),
            domain: ContentDomain::Database,
            mime_types: vec![
                "application/vnd.sqlite3".into(),
                "application/x-sqlite3".into(),
            ],
            extensions: vec!["sqlite".into(), "sqlite3".into(), "db".into()],
            magic_bytes: vec!["53514C69746520666F726D6174".into()], // "SQLite format"
            diff_strategy: DiffStrategy::Semantic,
            merge_strategy: MergeStrategy::SchemaAware,
            storage_tier: StorageTier::Chunked,
            lfs_threshold: Some(10 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "table_count": {"type": "integer"},
                    "row_count": {"type": "integer"},
                    "schema_version": {"type": "string"},
                    "page_size": {"type": "integer"}
                }
            })),
            structural_diff: true,
            component_locking: true,
            description: "SQLite embedded database file".into(),
        },
        ContentType {
            id: "db/csv".into(),
            name: "CSV Data".into(),
            domain: ContentDomain::Database,
            mime_types: vec!["text/csv".into()],
            extensions: vec!["csv".into(), "tsv".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::SchemaAware,
            storage_tier: StorageTier::Standard,
            lfs_threshold: Some(50 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "column_count": {"type": "integer"},
                    "row_count": {"type": "integer"},
                    "delimiter": {"type": "string"},
                    "has_header": {"type": "boolean"}
                }
            })),
            structural_diff: true,
            component_locking: false,
            description: "Comma/tab-separated values".into(),
        },
        ContentType {
            id: "db/parquet".into(),
            name: "Apache Parquet".into(),
            domain: ContentDomain::Database,
            mime_types: vec!["application/x-parquet".into()],
            extensions: vec!["parquet".into()],
            magic_bytes: vec!["50415231".into()], // "PAR1"
            diff_strategy: DiffStrategy::Semantic,
            merge_strategy: MergeStrategy::SchemaAware,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(10 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "row_groups": {"type": "integer"},
                    "row_count": {"type": "integer"},
                    "column_count": {"type": "integer"},
                    "compression": {"type": "string"}
                }
            })),
            structural_diff: true,
            component_locking: false,
            description: "Apache Parquet columnar storage".into(),
        },
        ContentType {
            id: "db/sql-migration".into(),
            name: "SQL Migration".into(),
            domain: ContentDomain::Database,
            mime_types: vec!["application/sql".into()],
            extensions: vec!["sql".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Text,
            merge_strategy: MergeStrategy::AppendOnly,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "direction": {"type": "string", "enum": ["up", "down"]},
                    "version": {"type": "string"},
                    "idempotent": {"type": "boolean"}
                }
            })),
            structural_diff: false,
            component_locking: false,
            description: "SQL database migration script".into(),
        },
        // ── Scientific ──
        ContentType {
            id: "scientific/hdf5".into(),
            name: "HDF5 Dataset".into(),
            domain: ContentDomain::Scientific,
            mime_types: vec!["application/x-hdf5".into()],
            extensions: vec!["h5".into(), "hdf5".into(), "he5".into()],
            magic_bytes: vec!["894844460D0A1A0A".into()],
            diff_strategy: DiffStrategy::Semantic,
            merge_strategy: MergeStrategy::SchemaAware,
            storage_tier: StorageTier::Chunked,
            lfs_threshold: Some(10 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "dataset_count": {"type": "integer"},
                    "total_size": {"type": "integer"},
                    "compression": {"type": "string"}
                }
            })),
            structural_diff: true,
            component_locking: true,
            description: "Hierarchical Data Format 5 for scientific datasets".into(),
        },
        ContentType {
            id: "scientific/fits".into(),
            name: "FITS Astronomical Data".into(),
            domain: ContentDomain::Scientific,
            mime_types: vec!["application/fits".into()],
            extensions: vec!["fits".into(), "fit".into()],
            magic_bytes: vec!["53494D504C45".into()], // "SIMPLE"
            diff_strategy: DiffStrategy::Opaque,
            merge_strategy: MergeStrategy::LastWriterWins,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(5 * 1024 * 1024),
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "Flexible Image Transport System (astronomy)".into(),
        },
        ContentType {
            id: "scientific/jupyter".into(),
            name: "Jupyter Notebook".into(),
            domain: ContentDomain::Scientific,
            mime_types: vec!["application/x-ipynb+json".into()],
            extensions: vec!["ipynb".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ComponentLevel,
            storage_tier: StorageTier::Standard,
            lfs_threshold: Some(50 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "cell_count": {"type": "integer"},
                    "kernel": {"type": "string"},
                    "language": {"type": "string"}
                }
            })),
            structural_diff: true,
            component_locking: true,
            description: "Jupyter/IPython notebook (cell-level versioning)".into(),
        },
        // ── Media ──
        ContentType {
            id: "media/image".into(),
            name: "Image Asset".into(),
            domain: ContentDomain::Media,
            mime_types: vec![
                "image/png".into(),
                "image/jpeg".into(),
                "image/webp".into(),
                "image/tiff".into(),
            ],
            extensions: vec![
                "png".into(),
                "jpg".into(),
                "jpeg".into(),
                "webp".into(),
                "tiff".into(),
                "tif".into(),
                "bmp".into(),
            ],
            magic_bytes: vec!["89504E47".into(), "FFD8FF".into()], // PNG, JPEG
            diff_strategy: DiffStrategy::Opaque,
            merge_strategy: MergeStrategy::LastWriterWins,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(256 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "width": {"type": "integer"},
                    "height": {"type": "integer"},
                    "format": {"type": "string"},
                    "color_space": {"type": "string"}
                }
            })),
            structural_diff: false,
            component_locking: false,
            description: "Raster image asset".into(),
        },
        ContentType {
            id: "media/video".into(),
            name: "Video Asset".into(),
            domain: ContentDomain::Media,
            mime_types: vec![
                "video/mp4".into(),
                "video/webm".into(),
                "video/quicktime".into(),
            ],
            extensions: vec![
                "mp4".into(),
                "webm".into(),
                "mov".into(),
                "mkv".into(),
                "avi".into(),
            ],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Opaque,
            merge_strategy: MergeStrategy::LastWriterWins,
            storage_tier: StorageTier::External,
            lfs_threshold: Some(10 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "duration_seconds": {"type": "number"},
                    "resolution": {"type": "string"},
                    "codec": {"type": "string"}
                }
            })),
            structural_diff: false,
            component_locking: false,
            description: "Video media asset".into(),
        },
        ContentType {
            id: "media/audio".into(),
            name: "Audio Asset".into(),
            domain: ContentDomain::Media,
            mime_types: vec![
                "audio/mpeg".into(),
                "audio/wav".into(),
                "audio/flac".into(),
                "audio/ogg".into(),
            ],
            extensions: vec![
                "mp3".into(),
                "wav".into(),
                "flac".into(),
                "ogg".into(),
                "aac".into(),
            ],
            magic_bytes: vec!["494433".into(), "52494646".into()], // "ID3", "RIFF"
            diff_strategy: DiffStrategy::Opaque,
            merge_strategy: MergeStrategy::LastWriterWins,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(1024 * 1024),
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "Audio media asset".into(),
        },
        // ── Geospatial ──
        ContentType {
            id: "geo/geojson".into(),
            name: "GeoJSON".into(),
            domain: ContentDomain::Geospatial,
            mime_types: vec!["application/geo+json".into()],
            extensions: vec!["geojson".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::ComponentLevel,
            storage_tier: StorageTier::Standard,
            lfs_threshold: Some(50 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "feature_count": {"type": "integer"},
                    "geometry_types": {"type": "array", "items": {"type": "string"}},
                    "crs": {"type": "string"}
                }
            })),
            structural_diff: true,
            component_locking: false,
            description: "RFC 7946 GeoJSON geographic data".into(),
        },
        ContentType {
            id: "geo/shapefile".into(),
            name: "Shapefile".into(),
            domain: ContentDomain::Geospatial,
            mime_types: vec!["application/x-shapefile".into()],
            extensions: vec!["shp".into(), "shx".into(), "dbf".into(), "prj".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Opaque,
            merge_strategy: MergeStrategy::ManualResolve,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(5 * 1024 * 1024),
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "ESRI Shapefile geospatial vector data".into(),
        },
        // ── Legal / Financial ──
        ContentType {
            id: "legal/pdf".into(),
            name: "PDF Document".into(),
            domain: ContentDomain::Legal,
            mime_types: vec!["application/pdf".into()],
            extensions: vec!["pdf".into()],
            magic_bytes: vec!["25504446".into()], // "%PDF"
            diff_strategy: DiffStrategy::Opaque,
            merge_strategy: MergeStrategy::ManualResolve,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "page_count": {"type": "integer"},
                    "signed": {"type": "boolean"},
                    "version": {"type": "string"}
                }
            })),
            structural_diff: false,
            component_locking: false,
            description: "Portable Document Format".into(),
        },
        ContentType {
            id: "financial/xlsx".into(),
            name: "Excel Spreadsheet".into(),
            domain: ContentDomain::Financial,
            mime_types: vec![
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".into(),
            ],
            extensions: vec!["xlsx".into()],
            magic_bytes: vec!["504B0304".into()], // ZIP
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::SchemaAware,
            storage_tier: StorageTier::Lfs,
            lfs_threshold: Some(5 * 1024 * 1024),
            metadata_schema: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "sheet_count": {"type": "integer"},
                    "row_count": {"type": "integer"},
                    "has_macros": {"type": "boolean"}
                }
            })),
            structural_diff: true,
            component_locking: true,
            description: "Microsoft Excel OOXML spreadsheet".into(),
        },
        // ── Config / Infrastructure ──
        ContentType {
            id: "config/terraform".into(),
            name: "Terraform HCL".into(),
            domain: ContentDomain::Config,
            mime_types: vec!["text/x-hcl".into()],
            extensions: vec!["tf".into(), "tfvars".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Text,
            merge_strategy: MergeStrategy::TextThreeWay,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: None,
            structural_diff: false,
            component_locking: false,
            description: "HashiCorp Terraform infrastructure-as-code".into(),
        },
        ContentType {
            id: "config/kubernetes".into(),
            name: "Kubernetes Manifest".into(),
            domain: ContentDomain::Config,
            mime_types: vec!["application/x-yaml".into()],
            extensions: vec!["yaml".into(), "yml".into()],
            magic_bytes: vec![],
            diff_strategy: DiffStrategy::Structural,
            merge_strategy: MergeStrategy::SchemaAware,
            storage_tier: StorageTier::Standard,
            lfs_threshold: None,
            metadata_schema: None,
            structural_diff: true,
            component_locking: false,
            description: "Kubernetes resource manifests (YAML)".into(),
        },
    ]
}

// ── Helpers ─────────────────────────────────────────────────────────────────

fn types_dir(repo_root: &Path) -> std::path::PathBuf {
    repo_root.join(".lit").join("content-types")
}

fn save_type(repo_root: &Path, ct: &ContentType) -> Result<(), LitError> {
    let dir = types_dir(repo_root);
    fs::create_dir_all(&dir)
        .map_err(|e| LitError::io(format!("Create content-types dir: {}", e)))?;
    let safe_id: String = ct.id.replace('/', "_");
    let path = dir.join(format!("{}.json", safe_id));
    let json = serde_json::to_string_pretty(ct)
        .map_err(|e| LitError::general(format!("Serialize content type: {}", e)))?;
    fs::write(&path, json).map_err(|e| LitError::io(format!("Write content type: {}", e)))?;
    Ok(())
}

fn load_all_types(repo_root: &Path) -> Result<Vec<ContentType>, LitError> {
    let dir = types_dir(repo_root);
    let mut types = builtin_types();

    // Overlay custom types from repo
    if dir.exists() {
        for entry in fs::read_dir(&dir).map_err(|e| LitError::io(e.to_string()))? {
            let entry = entry.map_err(|e| LitError::io(e.to_string()))?;
            if entry
                .path()
                .extension()
                .map(|e| e == "json")
                .unwrap_or(false)
            {
                let json =
                    fs::read_to_string(entry.path()).map_err(|e| LitError::io(e.to_string()))?;
                if let Ok(ct) = serde_json::from_str::<ContentType>(&json) {
                    // Custom types override builtins with the same id
                    types.retain(|t| t.id != ct.id);
                    types.push(ct);
                }
            }
        }
    }
    Ok(types)
}

/// Detect content type for a file by extension, then magic bytes
pub fn detect(file_path: &str, first_bytes: Option<&[u8]>) -> Option<ContentType> {
    let ext = file_path
        .rsplit('.')
        .next()
        .map(|e| e.to_lowercase())
        .unwrap_or_default();

    // Try builtins first (avoid needing repo root for detection)
    let all = builtin_types();

    // Extension match
    if let Some(ct) = all.iter().find(|t| t.extensions.contains(&ext)) {
        return Some(ct.clone());
    }

    // Magic bytes match
    if let Some(bytes) = first_bytes {
        let hex: String = bytes
            .iter()
            .take(16)
            .map(|b| format!("{:02X}", b))
            .collect();
        if let Some(ct) = all
            .iter()
            .find(|t| t.magic_bytes.iter().any(|mb| hex.starts_with(mb)))
        {
            return Some(ct.clone());
        }
    }

    None
}

// ── Public API ──────────────────────────────────────────────────────────────

/// List all registered content types, optionally filtered by domain
pub fn execute_list(domain_filter: Option<String>) -> Result<ContentTypeResponse, LitError> {
    let repo_root = find_repo_root().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let mut types = load_all_types(&repo_root)?;

    if let Some(ref domain) = domain_filter {
        types.retain(|t| t.domain.to_string() == *domain);
    }

    let count = types.len();
    Ok(ContentTypeResponse {
        action: "list".into(),
        content_type_id: None,
        message: format!("{} content type(s)", count),
        details: Some(serde_json::to_value(&types).unwrap_or_default()),
    })
}

/// Show a specific content type
pub fn execute_show(type_id: String) -> Result<ContentTypeResponse, LitError> {
    let repo_root = find_repo_root().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let types = load_all_types(&repo_root)?;

    let ct = types
        .iter()
        .find(|t| t.id == type_id)
        .ok_or_else(|| LitError::general(format!("Content type not found: {}", type_id)))?;

    Ok(ContentTypeResponse {
        action: "show".into(),
        content_type_id: Some(ct.id.clone()),
        message: format!("{} ({})", ct.name, ct.domain),
        details: Some(serde_json::to_value(ct).unwrap_or_default()),
    })
}

/// Register a custom content type
pub fn execute_register(
    id: String,
    name: String,
    domain: String,
    extensions: Vec<String>,
    diff_strategy: Option<String>,
    merge_strategy: Option<String>,
    storage_tier: Option<String>,
) -> Result<ContentTypeResponse, LitError> {
    let repo_root = find_repo_root()?;

    let domain_enum = match domain.as_str() {
        "software" => ContentDomain::Software,
        "cad" => ContentDomain::Cad,
        "eda" => ContentDomain::Eda,
        "manuscript" => ContentDomain::Manuscript,
        "database" => ContentDomain::Database,
        "scientific" => ContentDomain::Scientific,
        "media" => ContentDomain::Media,
        "geospatial" => ContentDomain::Geospatial,
        "legal" => ContentDomain::Legal,
        "financial" => ContentDomain::Financial,
        "config" => ContentDomain::Config,
        "documentation" => ContentDomain::Documentation,
        other => ContentDomain::Custom(other.to_string()),
    };

    let diff = match diff_strategy.as_deref() {
        Some("text") => DiffStrategy::Text,
        Some("binary") => DiffStrategy::Binary,
        Some("structural") => DiffStrategy::Structural,
        Some("semantic") => DiffStrategy::Semantic,
        Some("opaque") => DiffStrategy::Opaque,
        _ => DiffStrategy::Binary,
    };

    let merge = match merge_strategy.as_deref() {
        Some("text-three-way") => MergeStrategy::TextThreeWay,
        Some("manual-resolve") => MergeStrategy::ManualResolve,
        Some("schema-aware") => MergeStrategy::SchemaAware,
        Some("component-level") => MergeStrategy::ComponentLevel,
        Some("append-only") => MergeStrategy::AppendOnly,
        Some("last-writer-wins") => MergeStrategy::LastWriterWins,
        _ => MergeStrategy::ManualResolve,
    };

    let tier = match storage_tier.as_deref() {
        Some("standard") => StorageTier::Standard,
        Some("lfs") => StorageTier::Lfs,
        Some("chunked") => StorageTier::Chunked,
        Some("external") => StorageTier::External,
        _ => StorageTier::Lfs,
    };

    let ct = ContentType {
        id: id.clone(),
        name: name.clone(),
        domain: domain_enum,
        mime_types: vec![],
        extensions,
        magic_bytes: vec![],
        diff_strategy: diff,
        merge_strategy: merge,
        storage_tier: tier,
        lfs_threshold: None,
        metadata_schema: None,
        structural_diff: false,
        component_locking: false,
        description: format!("Custom content type: {}", name),
    };

    save_type(&repo_root, &ct)?;

    Ok(ContentTypeResponse {
        action: "register".into(),
        content_type_id: Some(id),
        message: format!("Content type '{}' registered", name),
        details: Some(serde_json::to_value(&ct).unwrap_or_default()),
    })
}

/// Detect the content type(s) of one or more files
pub fn execute_detect(paths: Vec<String>) -> Result<ContentTypeResponse, LitError> {
    let mut results: HashMap<String, serde_json::Value> = HashMap::new();

    for path in &paths {
        let first_bytes = fs::read(path).ok().map(|b| b[..b.len().min(16)].to_vec());
        let detected = detect(path, first_bytes.as_deref());
        results.insert(
            path.clone(),
            match detected {
                Some(ct) => serde_json::to_value(&ct).unwrap_or_default(),
                None => serde_json::json!({"detected": false}),
            },
        );
    }

    Ok(ContentTypeResponse {
        action: "detect".into(),
        content_type_id: None,
        message: format!("Detected types for {} file(s)", paths.len()),
        details: Some(serde_json::to_value(&results).unwrap_or_default()),
    })
}