Skip to main content

lean_ctx/tools/
ctx_pack.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::path::Path;
3
4use serde::Serialize;
5
6use crate::core::artifacts::ResolvedArtifact;
7use crate::core::tokens::count_tokens;
8
9const DEFAULT_IMPACT_DEPTH: usize = 3;
10const MAX_CHANGED_FILES_SHOWN: usize = 200;
11const MAX_DIFF_BYTES: usize = 1_048_576; // 1 MiB
12
13#[derive(Debug, Clone, Serialize)]
14struct ChangedFile {
15    path: String,
16    status: String,
17    #[serde(skip_serializing_if = "Option::is_none")]
18    old_path: Option<String>,
19}
20
21#[derive(Debug, Clone, Serialize)]
22struct ImpactEntry {
23    file: String,
24    affected_files: Vec<String>,
25}
26
27#[derive(Debug, Serialize)]
28struct PrPackJson {
29    kind: &'static str,
30    project_root: String,
31    base: String,
32    impact_depth: usize,
33    changed_files: Vec<ChangedFile>,
34    related_tests: Vec<String>,
35    impacts: Vec<ImpactEntry>,
36    context_artifacts: Vec<ResolvedArtifact>,
37    warnings: Vec<String>,
38    tokens: u64,
39}
40
41pub fn handle(
42    action: &str,
43    project_root: &str,
44    base: Option<&str>,
45    format: Option<&str>,
46    depth: Option<usize>,
47    diff: Option<&str>,
48) -> String {
49    match action {
50        "pr" => handle_pr(project_root, base, format, depth, diff),
51        _ => "Unknown action. Use: pr, create, list, info, remove, install, export, import, auto_load, summary".to_string(),
52    }
53}
54
55#[allow(clippy::too_many_arguments)]
56pub fn handle_create(
57    project_root: &str,
58    name: &str,
59    version: Option<&str>,
60    description: Option<&str>,
61    author: Option<&str>,
62    tags: Option<&[String]>,
63    layers: Option<&[String]>,
64    level: Option<u32>,
65    scope: Option<&str>,
66) -> String {
67    let version = version.unwrap_or("1.0.0");
68    let description = description.unwrap_or("");
69    let level = level.unwrap_or(1).clamp(1, 3);
70
71    let requested_layers: Vec<&str> = layers.map_or_else(
72        || vec!["knowledge", "graph", "session", "gotchas"],
73        |l| l.iter().map(String::as_str).collect(),
74    );
75
76    let mut builder = crate::core::context_package::PackageBuilder::new(name, version)
77        .description(description)
78        .tags(tags.unwrap_or(&[]).to_vec())
79        .level(level);
80
81    if let Some(a) = author {
82        builder = builder.author(a);
83    }
84    if let Some(s) = scope {
85        builder = builder.scope(s);
86    }
87
88    let phash = crate::core::project_hash::hash_project_root(project_root);
89    builder = builder.project_hash(&phash);
90
91    if level >= 2 {
92        builder.build_context_graph(project_root);
93    }
94
95    if requested_layers.contains(&"knowledge") || requested_layers.contains(&"patterns") {
96        builder = builder.add_knowledge_from_project(project_root);
97    }
98    if requested_layers.contains(&"patterns") {
99        builder = builder.add_patterns_from_project(project_root);
100    }
101    if requested_layers.contains(&"graph") {
102        builder = builder.add_graph_from_project(project_root);
103    }
104    if requested_layers.contains(&"session")
105        && let Some(session) = crate::core::session::SessionState::load_latest()
106    {
107        builder = builder.add_session(&session);
108    }
109    if requested_layers.contains(&"gotchas") {
110        builder = builder.add_gotchas_from_project(project_root);
111    }
112
113    match builder.build() {
114        Ok((manifest, content)) => {
115            let registry = match crate::core::context_package::LocalRegistry::open() {
116                Ok(r) => r,
117                Err(e) => return format!("ERROR: cannot open registry: {e}"),
118            };
119
120            match registry.install(&manifest, &content) {
121                Ok(dir) => {
122                    let layers_str = manifest
123                        .layers
124                        .iter()
125                        .map(crate::core::context_package::PackageLayer::as_str)
126                        .collect::<Vec<_>>()
127                        .join(", ");
128                    format!(
129                        "Package created:\n  Name: {}\n  Version: {}\n  Level: {}\n  Layers: {}\n  Knowledge facts: {}\n  Graph nodes: {}\n  Patterns: {}\n  Gotchas: {}\n  Size: {} bytes\n  Stored: {}",
130                        manifest.name,
131                        manifest.version,
132                        manifest.conformance_level.unwrap_or(1),
133                        layers_str,
134                        manifest.stats.knowledge_facts,
135                        manifest.stats.graph_nodes,
136                        manifest.stats.pattern_count,
137                        manifest.stats.gotcha_count,
138                        manifest.integrity.byte_size,
139                        dir.display()
140                    )
141                }
142                Err(e) => format!("ERROR: install failed: {e}"),
143            }
144        }
145        Err(e) => format!("ERROR: build failed: {e}"),
146    }
147}
148
149pub fn handle_list() -> String {
150    let registry = match crate::core::context_package::LocalRegistry::open() {
151        Ok(r) => r,
152        Err(e) => return format!("ERROR: {e}"),
153    };
154
155    match registry.list() {
156        Ok(entries) => {
157            if entries.is_empty() {
158                return "No packages installed.".to_string();
159            }
160            let mut out = String::new();
161            out.push_str(&format!("{} package(s):\n", entries.len()));
162            for e in &entries {
163                out.push_str(&format!(
164                    "- {} v{} [{}] ({} bytes){}\n",
165                    e.name,
166                    e.version,
167                    e.layers.join(", "),
168                    e.byte_size,
169                    if e.auto_load { " [auto-load]" } else { "" }
170                ));
171            }
172            out
173        }
174        Err(e) => format!("ERROR: {e}"),
175    }
176}
177
178pub fn handle_info(name: &str, version: Option<&str>) -> String {
179    let registry = match crate::core::context_package::LocalRegistry::open() {
180        Ok(r) => r,
181        Err(e) => return format!("ERROR: {e}"),
182    };
183
184    let resolved_ver;
185    let ver = if let Some(v) = version {
186        v
187    } else {
188        resolved_ver = registry
189            .list()
190            .ok()
191            .and_then(|entries| {
192                entries
193                    .iter()
194                    .filter(|e| e.name == name)
195                    .max_by(|a, b| a.installed_at.cmp(&b.installed_at))
196                    .map(|e| e.version.clone())
197            })
198            .unwrap_or_default();
199        &resolved_ver
200    };
201
202    match registry.load_package(name, ver) {
203        Ok((manifest, content)) => {
204            let layers_str = manifest
205                .layers
206                .iter()
207                .map(crate::core::context_package::PackageLayer::as_str)
208                .collect::<Vec<_>>()
209                .join(", ");
210            let mut out = format!(
211                "Package: {} v{}\nSchema: v{}\nLevel: {}\nLayers: {}\nDescription: {}\n",
212                manifest.name,
213                manifest.version,
214                manifest.schema_version,
215                manifest.conformance_level.unwrap_or(1),
216                layers_str,
217                manifest.description,
218            );
219            if let Some(ref a) = manifest.author {
220                out.push_str(&format!("Author: {a}\n"));
221            }
222            if let Some(ref s) = manifest.scope {
223                out.push_str(&format!("Scope: {s}\n"));
224            }
225            if !manifest.tags.is_empty() {
226                out.push_str(&format!("Tags: {}\n", manifest.tags.join(", ")));
227            }
228            out.push_str(&format!(
229                "Created: {}\nStats:\n  Knowledge facts: {}\n  Graph nodes: {}\n  Graph edges: {}\n  Patterns: {}\n  Gotchas: {}\n  Compression: {:.1}%\n  Est. tokens: ~{}\nIntegrity:\n  SHA256: {}\n  Size: {} bytes\n",
230                manifest.created_at.format("%Y-%m-%d %H:%M UTC"),
231                manifest.stats.knowledge_facts,
232                manifest.stats.graph_nodes,
233                manifest.stats.graph_edges,
234                manifest.stats.pattern_count,
235                manifest.stats.gotcha_count,
236                manifest.stats.compression_ratio * 100.0,
237                content.estimated_token_count(),
238                manifest.integrity.sha256,
239                manifest.integrity.byte_size,
240            ));
241            out
242        }
243        Err(e) => format!("ERROR: {e}"),
244    }
245}
246
247pub fn handle_remove(name: &str, version: Option<&str>) -> String {
248    let registry = match crate::core::context_package::LocalRegistry::open() {
249        Ok(r) => r,
250        Err(e) => return format!("ERROR: {e}"),
251    };
252
253    match registry.remove(name, version) {
254        Ok(0) => format!("No matching package found: {name}"),
255        Ok(n) => format!("Removed {n} package(s)."),
256        Err(e) => format!("ERROR: {e}"),
257    }
258}
259
260pub fn handle_install(name: &str, version: Option<&str>, project_root: &str) -> String {
261    let registry = match crate::core::context_package::LocalRegistry::open() {
262        Ok(r) => r,
263        Err(e) => return format!("ERROR: {e}"),
264    };
265
266    let resolved_ver;
267    let ver = if let Some(v) = version {
268        v
269    } else {
270        resolved_ver = registry
271            .list()
272            .ok()
273            .and_then(|entries| {
274                entries
275                    .iter()
276                    .filter(|e| e.name == name)
277                    .max_by(|a, b| a.installed_at.cmp(&b.installed_at))
278                    .map(|e| e.version.clone())
279            })
280            .unwrap_or_default();
281        &resolved_ver
282    };
283
284    match registry.load_package(name, ver) {
285        Ok((manifest, content)) => {
286            match crate::core::context_package::load_package(&manifest, &content, project_root) {
287                Ok(report) => format!("{report}\nPackage applied successfully."),
288                Err(e) => format!("ERROR: load failed: {e}"),
289            }
290        }
291        Err(e) => format!("ERROR: {e}"),
292    }
293}
294
295pub fn handle_export(name: &str, version: Option<&str>, output: Option<&str>) -> String {
296    let registry = match crate::core::context_package::LocalRegistry::open() {
297        Ok(r) => r,
298        Err(e) => return format!("ERROR: {e}"),
299    };
300
301    let resolved_ver;
302    let ver = if let Some(v) = version {
303        v
304    } else {
305        resolved_ver = registry
306            .list()
307            .ok()
308            .and_then(|entries| {
309                entries
310                    .iter()
311                    .filter(|e| e.name == name)
312                    .max_by(|a, b| a.installed_at.cmp(&b.installed_at))
313                    .map(|e| e.version.clone())
314            })
315            .unwrap_or_default();
316        &resolved_ver
317    };
318
319    let out_path = output.map_or_else(
320        || crate::core::contracts::default_package_filename(name, ver),
321        ToString::to_string,
322    );
323
324    match registry.export_to_file(name, ver, &std::path::PathBuf::from(&out_path)) {
325        Ok(bytes) => format!("Exported: {out_path} ({bytes} bytes)"),
326        Err(e) => format!("ERROR: {e}"),
327    }
328}
329
330pub fn handle_import(file_path: &str, apply: bool, project_root: &str) -> String {
331    let registry = match crate::core::context_package::LocalRegistry::open() {
332        Ok(r) => r,
333        Err(e) => return format!("ERROR: {e}"),
334    };
335
336    match registry.import_from_file(std::path::Path::new(file_path)) {
337        Ok(manifest) => {
338            let layers_str = manifest
339                .layers
340                .iter()
341                .map(crate::core::context_package::PackageLayer::as_str)
342                .collect::<Vec<_>>()
343                .join(", ");
344            let mut out = format!(
345                "Imported: {} v{}\n  Layers: {}\n  Size: {} bytes\n",
346                manifest.name, manifest.version, layers_str, manifest.integrity.byte_size,
347            );
348            if apply {
349                match crate::core::context_package::LocalRegistry::open() {
350                    Ok(reg) => match reg.load_package(&manifest.name, &manifest.version) {
351                        Ok((m, c)) => {
352                            match crate::core::context_package::load_package(&m, &c, project_root) {
353                                Ok(report) => {
354                                    out.push_str(&format!("{report}\nPackage applied."));
355                                }
356                                Err(e) => out.push_str(&format!("ERROR applying: {e}")),
357                            }
358                        }
359                        Err(e) => out.push_str(&format!("ERROR loading: {e}")),
360                    },
361                    Err(e) => out.push_str(&format!("ERROR: {e}")),
362                }
363            }
364            out
365        }
366        Err(e) => format!("ERROR: import failed: {e}"),
367    }
368}
369
370pub fn handle_auto_load(name: Option<&str>, version: Option<&str>, enable: bool) -> String {
371    let registry = match crate::core::context_package::LocalRegistry::open() {
372        Ok(r) => r,
373        Err(e) => return format!("ERROR: {e}"),
374    };
375
376    let Some(name) = name else {
377        return match registry.auto_load_packages() {
378            Ok(entries) => {
379                if entries.is_empty() {
380                    "No packages set for auto-load.".to_string()
381                } else {
382                    let mut out = "Auto-load packages:\n".to_string();
383                    for e in &entries {
384                        out.push_str(&format!("- {} v{}\n", e.name, e.version));
385                    }
386                    out
387                }
388            }
389            Err(e) => format!("ERROR: {e}"),
390        };
391    };
392
393    let resolved_ver;
394    let ver = if let Some(v) = version {
395        v
396    } else {
397        resolved_ver = registry
398            .list()
399            .ok()
400            .and_then(|entries| {
401                entries
402                    .iter()
403                    .filter(|e| e.name == name)
404                    .max_by(|a, b| a.installed_at.cmp(&b.installed_at))
405                    .map(|e| e.version.clone())
406            })
407            .unwrap_or_default();
408        &resolved_ver
409    };
410
411    match registry.set_auto_load(name, ver, enable) {
412        Ok(()) => {
413            if enable {
414                format!("Auto-load enabled for {name}@{ver}")
415            } else {
416                format!("Auto-load disabled for {name}@{ver}")
417            }
418        }
419        Err(e) => format!("ERROR: {e}"),
420    }
421}
422
423pub fn handle_summary(project_root: &str) -> String {
424    let phash = crate::core::project_hash::hash_project_root(project_root);
425
426    let registry = match crate::core::context_package::LocalRegistry::open() {
427        Ok(r) => r,
428        Err(e) => return format!("ERROR: {e}"),
429    };
430
431    let entries = registry.list().unwrap_or_default();
432    let matching: Vec<_> = entries.iter().collect();
433
434    let mut out = format!("Project: {project_root}\nProject hash: {phash}\n");
435    out.push_str(&format!("Installed packages: {}\n", matching.len()));
436
437    if !matching.is_empty() {
438        out.push_str("\nPackages:\n");
439        for e in &matching {
440            out.push_str(&format!(
441                "- {} v{} [{}]{}\n",
442                e.name,
443                e.version,
444                e.layers.join(", "),
445                if e.auto_load { " [auto-load]" } else { "" }
446            ));
447        }
448    }
449
450    let auto_count = matching.iter().filter(|e| e.auto_load).count();
451    out.push_str(&format!("Auto-load: {auto_count} package(s)\n"));
452    out
453}
454
455fn handle_pr(
456    project_root: &str,
457    base: Option<&str>,
458    format: Option<&str>,
459    depth: Option<usize>,
460    diff: Option<&str>,
461) -> String {
462    let root = project_root.to_string();
463    let base = base.map_or_else(
464        || detect_default_base(&root).unwrap_or_else(|| "HEAD~1".to_string()),
465        ToString::to_string,
466    );
467    let impact_depth = depth.unwrap_or(DEFAULT_IMPACT_DEPTH).max(1);
468
469    let mut warnings: Vec<String> = Vec::new();
470    let mut changed = if let Some(d) = diff {
471        if d.len() > MAX_DIFF_BYTES {
472            warnings.push(format!(
473                "Diff input too large ({} bytes, limit {MAX_DIFF_BYTES}). Truncating at char boundary.",
474                d.len()
475            ));
476            let mut boundary = MAX_DIFF_BYTES;
477            while boundary > 0 && !d.is_char_boundary(boundary) {
478                boundary -= 1;
479            }
480            let truncated = &d[..boundary];
481            parse_changes_from_input(truncated)
482        } else {
483            parse_changes_from_input(d)
484        }
485    } else {
486        git_diff_name_status(&root, &base, &mut warnings)
487    };
488
489    if changed.len() > MAX_CHANGED_FILES_SHOWN {
490        warnings.push(format!(
491            "Too many changed files ({}). Truncating to {MAX_CHANGED_FILES_SHOWN}.",
492            changed.len()
493        ));
494        changed.truncate(MAX_CHANGED_FILES_SHOWN);
495    }
496
497    let related_tests = collect_related_tests(&changed, &root);
498    let impacts = collect_impacts(&changed, &root, impact_depth);
499    let context_artifacts = collect_relevant_artifacts(&changed, &root, &mut warnings);
500
501    let format = format.unwrap_or("markdown");
502    match format {
503        "json" => {
504            let mut json = PrPackJson {
505                kind: "leanctx.pr_pack",
506                project_root: root,
507                base,
508                impact_depth,
509                changed_files: changed,
510                related_tests,
511                impacts,
512                context_artifacts,
513                warnings,
514                tokens: 0,
515            };
516            match serde_json::to_string_pretty(&json) {
517                Ok(s) => {
518                    json.tokens = count_tokens(&s) as u64;
519                    serde_json::to_string_pretty(&json).unwrap()
520                }
521                Err(e) => format!("{{\"error\": \"serialization failed: {e}\"}}"),
522            }
523        }
524        _ => format_markdown(
525            project_root,
526            &base,
527            impact_depth,
528            &changed,
529            &related_tests,
530            &impacts,
531            &context_artifacts,
532            &warnings,
533        ),
534    }
535}
536
537fn format_markdown(
538    project_root: &str,
539    base: &str,
540    impact_depth: usize,
541    changed: &[ChangedFile],
542    related_tests: &[String],
543    impacts: &[ImpactEntry],
544    artifacts: &[ResolvedArtifact],
545    warnings: &[String],
546) -> String {
547    let mut out = String::new();
548    out.push_str("# PR Context Pack\n\n");
549    out.push_str(&format!("- Project root: `{project_root}`\n"));
550    out.push_str(&format!("- Base: `{base}`\n"));
551    out.push_str(&format!("- Impact depth: `{impact_depth}`\n\n"));
552
553    if !warnings.is_empty() {
554        out.push_str("## Warnings\n");
555        for w in warnings {
556            out.push_str(&format!("- {w}\n"));
557        }
558        out.push('\n');
559    }
560
561    out.push_str("## Changed files\n");
562    for c in changed {
563        match &c.old_path {
564            Some(old) => out.push_str(&format!("- `{}` ({}) ← `{old}`\n", c.path, c.status)),
565            None => out.push_str(&format!("- `{}` ({})\n", c.path, c.status)),
566        }
567    }
568    out.push('\n');
569
570    if !artifacts.is_empty() {
571        out.push_str("## Context artifacts\n");
572        for a in artifacts {
573            let kind = if a.is_dir { "dir" } else { "file" };
574            let exists = if a.exists { "exists" } else { "missing" };
575            out.push_str(&format!(
576                "- `{}` ({kind}, {exists}) — {}\n",
577                a.path, a.description
578            ));
579        }
580        out.push('\n');
581    }
582
583    if !related_tests.is_empty() {
584        out.push_str("## Related tests\n");
585        for t in related_tests {
586            out.push_str(&format!("- `{t}`\n"));
587        }
588        out.push('\n');
589    }
590
591    if !impacts.is_empty() {
592        out.push_str("## Impact (property graph)\n");
593        for imp in impacts {
594            out.push_str(&format!(
595                "- `{}`: {} affected files\n",
596                imp.file,
597                imp.affected_files.len()
598            ));
599            for f in imp.affected_files.iter().take(30) {
600                out.push_str(&format!("  - `{f}`\n"));
601            }
602            if imp.affected_files.len() > 30 {
603                out.push_str("  - ...\n");
604            }
605        }
606        out.push('\n');
607    }
608
609    let tokens = count_tokens(&out);
610    out.push_str(&format!("[ctx_pack pr: {tokens} tok]\n"));
611    out
612}
613
614fn collect_related_tests(changed: &[ChangedFile], project_root: &str) -> Vec<String> {
615    let mut all: BTreeSet<String> = BTreeSet::new();
616    for c in changed {
617        for t in crate::tools::ctx_review::find_related_tests(&c.path, project_root) {
618            all.insert(t);
619        }
620    }
621    all.into_iter().collect()
622}
623
624fn collect_impacts(changed: &[ChangedFile], project_root: &str, depth: usize) -> Vec<ImpactEntry> {
625    let mut out = Vec::new();
626    for c in changed {
627        if c.status == "D" {
628            continue;
629        }
630        let raw = crate::tools::ctx_impact::handle(
631            "analyze",
632            Some(&c.path),
633            project_root,
634            Some(depth),
635            None,
636        );
637        let affected = parse_ctx_impact_output(&raw);
638        out.push(ImpactEntry {
639            file: c.path.clone(),
640            affected_files: affected,
641        });
642    }
643    out
644}
645
646fn parse_ctx_impact_output(raw: &str) -> Vec<String> {
647    let mut out: Vec<String> = Vec::new();
648    for line in raw.lines() {
649        let l = line.trim_end();
650        if let Some(rest) = l.strip_prefix("  ") {
651            let item = rest.trim().to_string();
652            if item.starts_with("...") {
653                continue;
654            }
655            if !item.is_empty() {
656                out.push(item);
657            }
658        }
659    }
660    out.sort();
661    out.dedup();
662    out
663}
664
665fn collect_relevant_artifacts(
666    changed: &[ChangedFile],
667    project_root: &str,
668    warnings: &mut Vec<String>,
669) -> Vec<ResolvedArtifact> {
670    let root = Path::new(project_root);
671    let resolved = crate::core::artifacts::load_resolved(root);
672    warnings.extend(resolved.warnings);
673
674    let mut out: Vec<ResolvedArtifact> = Vec::new();
675    for a in resolved.artifacts {
676        if !a.exists {
677            continue;
678        }
679        if is_artifact_relevant(&a, changed) {
680            out.push(a);
681        }
682    }
683    out.sort_by(|a, b| a.path.cmp(&b.path).then_with(|| a.name.cmp(&b.name)));
684    out
685}
686
687fn is_artifact_relevant(a: &ResolvedArtifact, changed: &[ChangedFile]) -> bool {
688    if a.path.is_empty() {
689        return false;
690    }
691    if a.is_dir {
692        let prefix = if a.path.ends_with('/') {
693            a.path.clone()
694        } else {
695            format!("{}/", a.path)
696        };
697        return changed.iter().any(|c| c.path.starts_with(&prefix));
698    }
699    changed.iter().any(|c| c.path == a.path)
700}
701
702fn parse_changes_from_input(input: &str) -> Vec<ChangedFile> {
703    if input.contains("diff --git") || input.contains("\n+++ ") {
704        let paths = parse_unified_diff_paths(input);
705        let mut out = Vec::new();
706        for p in paths {
707            out.push(ChangedFile {
708                path: p,
709                status: "M".to_string(),
710                old_path: None,
711            });
712        }
713        return dedup_changes(out);
714    }
715
716    let mut out = Vec::new();
717    for line in input.lines() {
718        let trimmed = line.trim();
719        if trimmed.is_empty() {
720            continue;
721        }
722        let parts: Vec<&str> = trimmed.split_whitespace().collect();
723        if parts.len() >= 2 {
724            let status = parts[0].to_string();
725            if status.starts_with('R') && parts.len() >= 3 {
726                out.push(ChangedFile {
727                    path: parts[2].to_string(),
728                    status: "R".to_string(),
729                    old_path: Some(parts[1].to_string()),
730                });
731            } else {
732                out.push(ChangedFile {
733                    path: parts[1].to_string(),
734                    status: status.chars().next().unwrap_or('M').to_string(),
735                    old_path: None,
736                });
737            }
738        } else {
739            out.push(ChangedFile {
740                path: trimmed.to_string(),
741                status: "M".to_string(),
742                old_path: None,
743            });
744        }
745    }
746    dedup_changes(out)
747}
748
749fn parse_unified_diff_paths(diff: &str) -> Vec<String> {
750    let mut out: BTreeSet<String> = BTreeSet::new();
751    for line in diff.lines() {
752        if let Some(rest) = line.strip_prefix("+++ b/") {
753            let p = rest.trim();
754            if !p.is_empty() && p != "/dev/null" {
755                out.insert(p.to_string());
756            }
757        }
758        if let Some(rest) = line.strip_prefix("--- a/") {
759            let p = rest.trim();
760            if !p.is_empty() && p != "/dev/null" {
761                out.insert(p.to_string());
762            }
763        }
764    }
765    out.into_iter().collect()
766}
767
768fn git_diff_name_status(
769    project_root: &str,
770    base: &str,
771    warnings: &mut Vec<String>,
772) -> Vec<ChangedFile> {
773    let out = std::process::Command::new("git")
774        .args(["diff", "--name-status", &format!("{base}...HEAD")])
775        .current_dir(project_root)
776        .stdout(std::process::Stdio::piped())
777        .stderr(std::process::Stdio::piped())
778        .output();
779    let Ok(o) = out else {
780        warnings.push("Failed to execute git diff".to_string());
781        return Vec::new();
782    };
783    if !o.status.success() {
784        let stderr = String::from_utf8_lossy(&o.stderr);
785        warnings.push(format!("git diff failed: {}", stderr.trim()));
786        return Vec::new();
787    }
788    let s = String::from_utf8_lossy(&o.stdout);
789    parse_changes_from_input(&s)
790}
791
792fn detect_default_base(project_root: &str) -> Option<String> {
793    for cand in ["origin/main", "origin/master", "main", "master"] {
794        let ok = std::process::Command::new("git")
795            .args(["rev-parse", "--verify", cand])
796            .current_dir(project_root)
797            .stdout(std::process::Stdio::null())
798            .stderr(std::process::Stdio::null())
799            .status()
800            .is_ok_and(|s| s.success());
801        if ok {
802            return Some(cand.to_string());
803        }
804    }
805    None
806}
807
808fn dedup_changes(changes: Vec<ChangedFile>) -> Vec<ChangedFile> {
809    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
810    let mut out: Vec<ChangedFile> = Vec::new();
811    for c in changes {
812        let key = c.path.clone();
813        if let Some(&i) = seen.get(&key) {
814            out[i] = c;
815        } else {
816            seen.insert(key, out.len());
817            out.push(c);
818        }
819    }
820    out
821}