litvc 1.2.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
//! Generic agent profile system — extends the swarm subsystem from SWE-only
//! agents to arbitrary domain agents (CAD designers, EDA engineers, writers,
//! DBAs, reviewers, CI bots, security auditors, etc.).
//!
//! Each agent profile declares capabilities, supported content types, trust
//! domains, and resource limits so Lit can intelligently route work, enforce
//! access policies, and schedule across heterogeneous agent fleets.

use crate::core::find_repo_root;
use crate::errors::LitError;
use crate::response::AgentProfileResponse;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

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

/// Domain classification for agent specialization
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AgentDomain {
    /// Software engineering (code, tests, CI/CD)
    Software,
    /// Mechanical / industrial CAD modeling
    Cad,
    /// Electronic design automation (PCB, schematic, FPGA)
    Eda,
    /// Writing — technical docs, manuscripts, legal prose
    Writer,
    /// Database administration — schema, migration, optimization
    Dba,
    /// Code / design review
    Reviewer,
    /// Continuous integration and deployment
    Ci,
    /// Security auditing and compliance
    Security,
    /// Data science and ML pipelines
    DataScience,
    /// DevOps / infrastructure management
    DevOps,
    /// Quality assurance / test automation
    Qa,
    /// Project management / coordination
    ProjectManagement,
    /// General purpose
    General,
    /// Custom domain
    Custom(String),
}

impl std::fmt::Display for AgentDomain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AgentDomain::Software => write!(f, "software"),
            AgentDomain::Cad => write!(f, "cad"),
            AgentDomain::Eda => write!(f, "eda"),
            AgentDomain::Writer => write!(f, "writer"),
            AgentDomain::Dba => write!(f, "dba"),
            AgentDomain::Reviewer => write!(f, "reviewer"),
            AgentDomain::Ci => write!(f, "ci"),
            AgentDomain::Security => write!(f, "security"),
            AgentDomain::DataScience => write!(f, "data-science"),
            AgentDomain::DevOps => write!(f, "devops"),
            AgentDomain::Qa => write!(f, "qa"),
            AgentDomain::ProjectManagement => write!(f, "project-management"),
            AgentDomain::General => write!(f, "general"),
            AgentDomain::Custom(s) => write!(f, "custom:{}", s),
        }
    }
}

/// Capabilities an agent can advertise
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Capability {
    /// Read files / objects
    Read,
    /// Write / modify files
    Write,
    /// Create new branches
    Branch,
    /// Merge branches
    Merge,
    /// Review and approve
    Review,
    /// Deploy / release
    Deploy,
    /// Run tests
    Test,
    /// Run security scans
    SecurityScan,
    /// Generate diffs / patches
    Diff,
    /// Manage large files (LFS operations)
    Lfs,
    /// Create / manage intents
    Intent,
    /// Converge intents to mainline
    Converge,
    /// Manage content type metadata
    ContentMetadata,
    /// Cross-domain coordination (orchestrate other agents)
    Orchestrate,
    /// Structural diff / merge for binary formats
    StructuralAnalysis,
    /// Schema-aware operations (database agents)
    SchemaManagement,
    /// Custom capability
    Custom(String),
}

impl std::fmt::Display for Capability {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Capability::Read => write!(f, "read"),
            Capability::Write => write!(f, "write"),
            Capability::Branch => write!(f, "branch"),
            Capability::Merge => write!(f, "merge"),
            Capability::Review => write!(f, "review"),
            Capability::Deploy => write!(f, "deploy"),
            Capability::Test => write!(f, "test"),
            Capability::SecurityScan => write!(f, "security-scan"),
            Capability::Diff => write!(f, "diff"),
            Capability::Lfs => write!(f, "lfs"),
            Capability::Intent => write!(f, "intent"),
            Capability::Converge => write!(f, "converge"),
            Capability::ContentMetadata => write!(f, "content-metadata"),
            Capability::Orchestrate => write!(f, "orchestrate"),
            Capability::StructuralAnalysis => write!(f, "structural-analysis"),
            Capability::SchemaManagement => write!(f, "schema-management"),
            Capability::Custom(s) => write!(f, "custom:{}", s),
        }
    }
}

/// Trust level assigned to an agent
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum TrustLevel {
    /// Untrusted — read-only sandbox
    Untrusted = 0,
    /// Limited — can propose changes but not merge
    Limited = 1,
    /// Standard — full read/write within assigned scope
    Standard = 2,
    /// Elevated — can merge, converge, manage intents
    Elevated = 3,
    /// Admin — full control including key management
    Admin = 4,
}

impl std::fmt::Display for TrustLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TrustLevel::Untrusted => write!(f, "untrusted"),
            TrustLevel::Limited => write!(f, "limited"),
            TrustLevel::Standard => write!(f, "standard"),
            TrustLevel::Elevated => write!(f, "elevated"),
            TrustLevel::Admin => write!(f, "admin"),
        }
    }
}

/// Resource constraints for an agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
    /// Maximum file size the agent can write (bytes, 0 = unlimited)
    pub max_file_size: u64,
    /// Maximum total storage the agent can consume (bytes, 0 = unlimited)
    pub max_total_storage: u64,
    /// Maximum number of files the agent can modify per commit
    pub max_files_per_commit: u32,
    /// Maximum number of concurrent leases
    pub max_concurrent_leases: u32,
    /// Maximum branch count the agent can own
    pub max_branches: u32,
    /// Rate limit — max operations per minute (0 = unlimited)
    pub max_ops_per_minute: u32,
    /// Whether the agent can access network (fetch/push/clone)
    pub network_access: bool,
    /// Whether the agent can execute hooks/scripts
    pub hook_execution: bool,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            max_file_size: 100 * 1024 * 1024, // 100 MB
            max_total_storage: 0,             // unlimited
            max_files_per_commit: 1000,
            max_concurrent_leases: 10,
            max_branches: 5,
            max_ops_per_minute: 60,
            network_access: true,
            hook_execution: false,
        }
    }
}

/// A complete agent profile definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentProfile {
    /// Unique profile identifier
    pub profile_id: String,
    /// Human-readable name
    pub name: String,
    /// Domain specialization
    pub domain: AgentDomain,
    /// Capabilities this agent advertises
    pub capabilities: Vec<Capability>,
    /// Content type IDs this agent can work with (empty = all)
    pub supported_content_types: Vec<String>,
    /// Trust level
    pub trust_level: TrustLevel,
    /// Resource limits
    pub resource_limits: ResourceLimits,
    /// Path patterns this agent is allowed to modify (glob patterns, empty = all)
    pub allowed_paths: Vec<String>,
    /// Path patterns this agent is denied from modifying
    pub denied_paths: Vec<String>,
    /// Description
    pub description: String,
    /// Version of the profile schema
    pub version: String,
    /// Registration timestamp
    pub registered_at: String,
    /// Optional parent profile to inherit from
    pub inherits_from: Option<String>,
    /// Arbitrary metadata
    #[serde(default)]
    pub metadata: serde_json::Value,
}

// ── Built-in profiles ───────────────────────────────────────────────────────

fn builtin_profiles() -> Vec<AgentProfile> {
    let now = Utc::now().to_rfc3339();
    vec![
        AgentProfile {
            profile_id: "swe-default".into(),
            name: "Software Engineer".into(),
            domain: AgentDomain::Software,
            capabilities: vec![
                Capability::Read, Capability::Write, Capability::Branch,
                Capability::Merge, Capability::Test, Capability::Diff,
                Capability::Intent, Capability::Converge,
            ],
            supported_content_types: vec![],
            trust_level: TrustLevel::Standard,
            resource_limits: ResourceLimits::default(),
            allowed_paths: vec!["**/*.rs".into(), "**/*.py".into(), "**/*.ts".into(), "**/*.js".into(),
                                "**/*.go".into(), "**/*.java".into(), "**/*.c".into(), "**/*.cpp".into(),
                                "**/*.h".into(), "**/*.toml".into(), "**/*.json".into(), "**/*.yaml".into(),
                                "**/*.yml".into(), "**/*.md".into(), "**/*.txt".into()],
            denied_paths: vec![],
            description: "General-purpose software engineering agent".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({}),
        },
        AgentProfile {
            profile_id: "cad-designer".into(),
            name: "CAD Designer".into(),
            domain: AgentDomain::Cad,
            capabilities: vec![
                Capability::Read, Capability::Write, Capability::Branch,
                Capability::Lfs, Capability::Diff, Capability::Intent,
                Capability::StructuralAnalysis, Capability::ContentMetadata,
            ],
            supported_content_types: vec![
                "cad/step".into(), "cad/stl".into(), "cad/iges".into(), "cad/3mf".into(),
            ],
            trust_level: TrustLevel::Standard,
            resource_limits: ResourceLimits {
                max_file_size: 500 * 1024 * 1024, // 500 MB for CAD
                max_files_per_commit: 50,
                max_concurrent_leases: 5,
                ..Default::default()
            },
            allowed_paths: vec!["**/*.step".into(), "**/*.stp".into(), "**/*.stl".into(),
                                "**/*.igs".into(), "**/*.iges".into(), "**/*.3mf".into(),
                                "**/*.obj".into(), "**/*.dxf".into()],
            denied_paths: vec!["src/**".into()],
            description: "Mechanical/industrial CAD modeling agent with LFS and structural diff support".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({"tools": ["openscad", "freecad", "solidworks"]}),
        },
        AgentProfile {
            profile_id: "eda-engineer".into(),
            name: "EDA Engineer".into(),
            domain: AgentDomain::Eda,
            capabilities: vec![
                Capability::Read, Capability::Write, Capability::Branch,
                Capability::Diff, Capability::Intent, Capability::StructuralAnalysis,
                Capability::ContentMetadata,
            ],
            supported_content_types: vec![
                "eda/kicad-pcb".into(), "eda/kicad-sch".into(), "eda/gerber".into(), "eda/spice".into(),
            ],
            trust_level: TrustLevel::Standard,
            resource_limits: ResourceLimits {
                max_files_per_commit: 100,
                max_concurrent_leases: 8,
                ..Default::default()
            },
            allowed_paths: vec!["**/*.kicad_pcb".into(), "**/*.kicad_sch".into(),
                                "**/*.gbr".into(), "**/*.ger".into(), "**/*.spice".into(),
                                "**/*.lib".into(), "**/*.bom".into()],
            denied_paths: vec![],
            description: "Electronic design automation agent for PCB/schematic/FPGA work".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({"tools": ["kicad", "ltspice", "verilator"]}),
        },
        AgentProfile {
            profile_id: "tech-writer".into(),
            name: "Technical Writer".into(),
            domain: AgentDomain::Writer,
            capabilities: vec![
                Capability::Read, Capability::Write, Capability::Branch,
                Capability::Diff, Capability::Intent, Capability::ContentMetadata,
            ],
            supported_content_types: vec![
                "manuscript/latex".into(), "manuscript/docx".into(),
                "manuscript/typst".into(), "manuscript/asciidoc".into(),
            ],
            trust_level: TrustLevel::Standard,
            resource_limits: ResourceLimits {
                max_file_size: 50 * 1024 * 1024,
                max_files_per_commit: 200,
                ..Default::default()
            },
            allowed_paths: vec!["**/*.md".into(), "**/*.tex".into(), "**/*.typ".into(),
                                "**/*.adoc".into(), "**/*.rst".into(), "**/*.docx".into(),
                                "**/*.txt".into(), "docs/**".into()],
            denied_paths: vec!["src/**".into()],
            description: "Technical writing agent for documentation, manuscripts, and publications".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({"languages": ["en", "de", "fr", "ja"]}),
        },
        AgentProfile {
            profile_id: "dba".into(),
            name: "Database Administrator".into(),
            domain: AgentDomain::Dba,
            capabilities: vec![
                Capability::Read, Capability::Write, Capability::Branch,
                Capability::Diff, Capability::Intent, Capability::SchemaManagement,
                Capability::ContentMetadata,
            ],
            supported_content_types: vec![
                "db/sqlite".into(), "db/csv".into(), "db/parquet".into(), "db/sql-migration".into(),
            ],
            trust_level: TrustLevel::Elevated,
            resource_limits: ResourceLimits {
                max_file_size: 1024 * 1024 * 1024, // 1 GB for databases
                max_files_per_commit: 50,
                ..Default::default()
            },
            allowed_paths: vec!["**/*.sql".into(), "**/*.sqlite".into(), "**/*.db".into(),
                                "**/*.csv".into(), "**/*.parquet".into(), "migrations/**".into()],
            denied_paths: vec![],
            description: "Database administration agent for schema, migration, and data versioning".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({"tools": ["sqlite", "postgres", "duckdb"]}),
        },
        AgentProfile {
            profile_id: "reviewer".into(),
            name: "Code & Design Reviewer".into(),
            domain: AgentDomain::Reviewer,
            capabilities: vec![
                Capability::Read, Capability::Review, Capability::Diff,
                Capability::Converge, Capability::ContentMetadata,
            ],
            supported_content_types: vec![], // reviews all types
            trust_level: TrustLevel::Elevated,
            resource_limits: ResourceLimits {
                max_files_per_commit: 0,
                max_file_size: 0,
                network_access: false,
                ..Default::default()
            },
            allowed_paths: vec![],
            denied_paths: vec![],
            description: "Read-only review agent that can approve and converge but not modify files".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({}),
        },
        AgentProfile {
            profile_id: "ci-bot".into(),
            name: "CI/CD Bot".into(),
            domain: AgentDomain::Ci,
            capabilities: vec![
                Capability::Read, Capability::Test, Capability::Deploy,
                Capability::SecurityScan, Capability::Diff,
            ],
            supported_content_types: vec![],
            trust_level: TrustLevel::Elevated,
            resource_limits: ResourceLimits {
                network_access: true,
                hook_execution: true,
                ..Default::default()
            },
            allowed_paths: vec![],
            denied_paths: vec![],
            description: "CI/CD automation agent for build, test, and deploy pipelines".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({}),
        },
        AgentProfile {
            profile_id: "security-auditor".into(),
            name: "Security Auditor".into(),
            domain: AgentDomain::Security,
            capabilities: vec![
                Capability::Read, Capability::Review, Capability::SecurityScan,
                Capability::Diff,
            ],
            supported_content_types: vec![],
            trust_level: TrustLevel::Elevated,
            resource_limits: ResourceLimits {
                max_file_size: 0,
                max_files_per_commit: 0,
                network_access: false,
                hook_execution: false,
                ..Default::default()
            },
            allowed_paths: vec![],
            denied_paths: vec![],
            description: "Security auditing agent — read-only scanning and compliance verification".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({}),
        },
        AgentProfile {
            profile_id: "data-scientist".into(),
            name: "Data Scientist".into(),
            domain: AgentDomain::DataScience,
            capabilities: vec![
                Capability::Read, Capability::Write, Capability::Branch,
                Capability::Lfs, Capability::Intent, Capability::ContentMetadata,
                Capability::SchemaManagement,
            ],
            supported_content_types: vec![
                "scientific/hdf5".into(), "scientific/jupyter".into(),
                "db/parquet".into(), "db/csv".into(),
            ],
            trust_level: TrustLevel::Standard,
            resource_limits: ResourceLimits {
                max_file_size: 2 * 1024 * 1024 * 1024, // 2 GB for datasets
                max_concurrent_leases: 3,
                ..Default::default()
            },
            allowed_paths: vec!["**/*.ipynb".into(), "**/*.h5".into(), "**/*.hdf5".into(),
                                "**/*.parquet".into(), "**/*.csv".into(), "**/*.py".into(),
                                "data/**".into(), "notebooks/**".into(), "models/**".into()],
            denied_paths: vec![],
            description: "Data science agent for notebooks, datasets, and ML pipeline versioning".into(),
            version: "1.0".into(),
            registered_at: now.clone(),
            inherits_from: None,
            metadata: serde_json::json!({"frameworks": ["pytorch", "tensorflow", "scikit-learn"]}),
        },
        AgentProfile {
            profile_id: "orchestrator".into(),
            name: "Multi-Agent Orchestrator".into(),
            domain: AgentDomain::General,
            capabilities: vec![
                Capability::Read, Capability::Orchestrate, Capability::Intent,
                Capability::Converge, Capability::Review,
            ],
            supported_content_types: vec![],
            trust_level: TrustLevel::Admin,
            resource_limits: ResourceLimits {
                max_files_per_commit: 0,
                max_file_size: 0,
                network_access: true,
                ..Default::default()
            },
            allowed_paths: vec![],
            denied_paths: vec![],
            description: "Meta-agent that orchestrates, coordinates, and routes work across domain-specific agents".into(),
            version: "1.0".into(),
            registered_at: now,
            inherits_from: None,
            metadata: serde_json::json!({}),
        },
    ]
}

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

fn profiles_dir(repo_root: &Path) -> std::path::PathBuf {
    repo_root.join(".lit").join("agent-profiles")
}

fn save_profile(repo_root: &Path, profile: &AgentProfile) -> Result<(), LitError> {
    let dir = profiles_dir(repo_root);
    fs::create_dir_all(&dir).map_err(|e| LitError::io(e.to_string()))?;
    let json = serde_json::to_string_pretty(profile)
        .map_err(|e| LitError::general(format!("Serialize profile: {}", e)))?;
    fs::write(dir.join(format!("{}.json", profile.profile_id)), json)
        .map_err(|e| LitError::io(e.to_string()))?;
    Ok(())
}

fn load_all_profiles(repo_root: &Path) -> Result<Vec<AgentProfile>, LitError> {
    let dir = profiles_dir(repo_root);
    let mut profiles = builtin_profiles();

    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(p) = serde_json::from_str::<AgentProfile>(&json) {
                    profiles.retain(|b| b.profile_id != p.profile_id);
                    profiles.push(p);
                }
            }
        }
    }
    Ok(profiles)
}

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

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

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

    let count = profiles.len();
    let summary: Vec<serde_json::Value> = profiles
        .iter()
        .map(|p| {
            serde_json::json!({
                "profile_id": p.profile_id,
                "name": p.name,
                "domain": p.domain.to_string(),
                "trust_level": p.trust_level.to_string(),
                "capabilities": p.capabilities.iter().map(|c| c.to_string()).collect::<Vec<_>>(),
                "content_types": p.supported_content_types,
            })
        })
        .collect();

    Ok(AgentProfileResponse {
        action: "list".into(),
        profile_id: None,
        message: format!("{} agent profile(s)", count),
        details: Some(serde_json::to_value(&summary).unwrap_or_default()),
    })
}

/// Show a specific agent profile
pub fn execute_show(profile_id: String) -> Result<AgentProfileResponse, LitError> {
    let repo_root = find_repo_root().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let profiles = load_all_profiles(&repo_root)?;

    let profile = profiles
        .iter()
        .find(|p| p.profile_id == profile_id)
        .ok_or_else(|| LitError::general(format!("Agent profile not found: {}", profile_id)))?;

    Ok(AgentProfileResponse {
        action: "show".into(),
        profile_id: Some(profile.profile_id.clone()),
        message: format!(
            "{} ({}, trust={})",
            profile.name, profile.domain, profile.trust_level
        ),
        details: Some(serde_json::to_value(profile).unwrap_or_default()),
    })
}

/// Register a custom agent profile
#[allow(clippy::too_many_arguments)]
pub fn execute_register(
    profile_id: String,
    name: String,
    domain: String,
    capabilities: Vec<String>,
    trust_level: Option<String>,
    content_types: Vec<String>,
    allowed_paths: Vec<String>,
    denied_paths: Vec<String>,
) -> Result<AgentProfileResponse, LitError> {
    let repo_root = find_repo_root()?;

    let domain_enum = match domain.as_str() {
        "software" => AgentDomain::Software,
        "cad" => AgentDomain::Cad,
        "eda" => AgentDomain::Eda,
        "writer" => AgentDomain::Writer,
        "dba" => AgentDomain::Dba,
        "reviewer" => AgentDomain::Reviewer,
        "ci" => AgentDomain::Ci,
        "security" => AgentDomain::Security,
        "data-science" => AgentDomain::DataScience,
        "devops" => AgentDomain::DevOps,
        "qa" => AgentDomain::Qa,
        "project-management" => AgentDomain::ProjectManagement,
        "general" => AgentDomain::General,
        other => AgentDomain::Custom(other.to_string()),
    };

    let caps: Vec<Capability> = capabilities
        .iter()
        .map(|c| match c.as_str() {
            "read" => Capability::Read,
            "write" => Capability::Write,
            "branch" => Capability::Branch,
            "merge" => Capability::Merge,
            "review" => Capability::Review,
            "deploy" => Capability::Deploy,
            "test" => Capability::Test,
            "security-scan" => Capability::SecurityScan,
            "diff" => Capability::Diff,
            "lfs" => Capability::Lfs,
            "intent" => Capability::Intent,
            "converge" => Capability::Converge,
            "content-metadata" => Capability::ContentMetadata,
            "orchestrate" => Capability::Orchestrate,
            "structural-analysis" => Capability::StructuralAnalysis,
            "schema-management" => Capability::SchemaManagement,
            other => Capability::Custom(other.to_string()),
        })
        .collect();

    let trust = match trust_level.as_deref() {
        Some("untrusted") => TrustLevel::Untrusted,
        Some("limited") => TrustLevel::Limited,
        Some("elevated") => TrustLevel::Elevated,
        Some("admin") => TrustLevel::Admin,
        _ => TrustLevel::Standard,
    };

    let profile = AgentProfile {
        profile_id: profile_id.clone(),
        name: name.clone(),
        domain: domain_enum,
        capabilities: caps,
        supported_content_types: content_types,
        trust_level: trust,
        resource_limits: ResourceLimits::default(),
        allowed_paths,
        denied_paths,
        description: format!("Custom agent profile: {}", name),
        version: "1.0".into(),
        registered_at: Utc::now().to_rfc3339(),
        inherits_from: None,
        metadata: serde_json::json!({}),
    };

    save_profile(&repo_root, &profile)?;

    Ok(AgentProfileResponse {
        action: "register".into(),
        profile_id: Some(profile_id),
        message: format!("Agent profile '{}' registered", name),
        details: Some(serde_json::to_value(&profile).unwrap_or_default()),
    })
}

/// List capabilities available for a given domain
pub fn execute_capabilities(domain: Option<String>) -> Result<AgentProfileResponse, LitError> {
    let repo_root = find_repo_root().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let profiles = load_all_profiles(&repo_root)?;

    let filtered: Vec<&AgentProfile> = if let Some(ref d) = domain {
        profiles
            .iter()
            .filter(|p| p.domain.to_string() == *d)
            .collect()
    } else {
        profiles.iter().collect()
    };

    // Aggregate unique capabilities
    let mut all_caps: Vec<String> = filtered
        .iter()
        .flat_map(|p| p.capabilities.iter().map(|c| c.to_string()))
        .collect();
    all_caps.sort();
    all_caps.dedup();

    // Aggregate unique domains
    let mut all_domains: Vec<String> = profiles.iter().map(|p| p.domain.to_string()).collect();
    all_domains.sort();
    all_domains.dedup();

    Ok(AgentProfileResponse {
        action: "capabilities".into(),
        profile_id: None,
        message: format!(
            "{} unique capability/ies across {} domain(s)",
            all_caps.len(),
            all_domains.len()
        ),
        details: Some(serde_json::json!({
            "capabilities": all_caps,
            "domains": all_domains,
            "profiles_by_domain": all_domains.iter().map(|d| {
                let count = profiles.iter().filter(|p| p.domain.to_string() == *d).count();
                serde_json::json!({"domain": d, "profile_count": count})
            }).collect::<Vec<_>>(),
        })),
    })
}

/// Remove a custom agent profile
pub fn execute_remove(profile_id: String) -> Result<AgentProfileResponse, LitError> {
    let repo_root = find_repo_root()?;
    let dir = profiles_dir(&repo_root);
    let path = dir.join(format!("{}.json", profile_id));

    if !path.exists() {
        // Could be a builtin — can't remove builtins
        let builtins = builtin_profiles();
        if builtins.iter().any(|p| p.profile_id == profile_id) {
            return Err(LitError::general(format!(
                "Cannot remove built-in profile: {}",
                profile_id
            )));
        }
        return Err(LitError::general(format!(
            "Agent profile not found: {}",
            profile_id
        )));
    }

    fs::remove_file(&path).map_err(|e| LitError::io(e.to_string()))?;

    Ok(AgentProfileResponse {
        action: "remove".into(),
        profile_id: Some(profile_id.clone()),
        message: format!("Agent profile '{}' removed", profile_id),
        details: None,
    })
}