loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
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
//! Output formatters for refactor plans (markdown, JSON, shell script).
//!
//! VibeCrafted with AI Agents (c)2026 Loctree Team

use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::Path;

use super::{RefactorPlan, RiskLevel, Shim};

// ============================================================================
// Markdown Output
// ============================================================================

/// Output refactor plan as markdown.
pub fn output_as_markdown(plan: &RefactorPlan, path: &Path) -> io::Result<()> {
    let content = format_as_markdown(plan);
    fs::write(path, content)
}

/// Format refactor plan as markdown string.
pub fn format_as_markdown(plan: &RefactorPlan) -> String {
    let mut md = String::new();

    // Header
    md.push_str(&format!("# Refactor Plan: {}\n\n", plan.target));

    // Summary
    md.push_str("## Summary\n\n");
    md.push_str(&format!(
        "- **Files analyzed:** {}\n",
        plan.stats.total_files
    ));
    md.push_str(&format!(
        "- **Files to move:** {}\n",
        plan.stats.files_to_move
    ));
    md.push_str(&format!(
        "- **Shims needed:** {}\n",
        plan.stats.shims_needed
    ));

    // Risk breakdown
    md.push_str("- **Risk breakdown:** ");
    let risk_parts: Vec<String> = plan
        .stats
        .by_risk
        .iter()
        .map(|(k, v)| format!("{} {}", v, k))
        .collect();
    md.push_str(&risk_parts.join(", "));
    md.push_str("\n\n");

    // Layer Distribution
    md.push_str("## Layer Distribution\n\n");
    md.push_str("### Before\n");
    for (layer, count) in &plan.stats.layer_before {
        let bar = "".repeat((*count).min(20));
        md.push_str(&format!("- {}: {} {}\n", layer, bar, count));
    }
    md.push_str("\n### After\n");
    for (layer, count) in &plan.stats.layer_after {
        let bar = "".repeat((*count).min(20));
        md.push_str(&format!("- {}: {} {}\n", layer, bar, count));
    }
    md.push('\n');

    // Cyclic Dependencies Warning
    if !plan.cyclic_groups.is_empty() {
        md.push_str("## ⚠️ Cyclic Dependencies\n\n");
        md.push_str("The following groups of files have circular imports. Move these together or break the cycle first:\n\n");
        for (i, group) in plan.cyclic_groups.iter().enumerate() {
            md.push_str(&format!("**Cycle {}:**\n", i + 1));
            for file in group {
                md.push_str(&format!("- `{}`\n", file));
            }
            md.push('\n');
        }
    }

    // Phases
    for phase in &plan.phases {
        let risk_emoji = match phase.risk {
            RiskLevel::Low => "🟢",
            RiskLevel::Medium => "🟡",
            RiskLevel::High => "🔴",
        };

        md.push_str(&format!("## {} {}\n\n", risk_emoji, phase.name));
        md.push_str(&format!("{} file(s)\n\n", phase.moves.len()));

        // Moves table
        md.push_str("| File | From | To | LOC | Consumers | Reason |\n");
        md.push_str("|------|------|----|----|-----------|--------|\n");

        for mv in &phase.moves {
            md.push_str(&format!(
                "| `{}` | {} | {} | {} | {} | {} |\n",
                Path::new(&mv.source)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(&mv.source),
                mv.current_layer.display_name(),
                mv.target_layer.display_name(),
                mv.loc,
                mv.direct_consumers,
                mv.reason
            ));
        }
        md.push('\n');

        // Git commands
        md.push_str("**Commands:**\n\n```bash\n");
        md.push_str(&phase.git_script);
        md.push_str("\n```\n\n");
    }

    // Shimming Strategy
    if !plan.shims.is_empty() {
        md.push_str("## Shimming Strategy\n\n");
        md.push_str("Create re-export shims for heavily-imported files to maintain backward compatibility:\n\n");

        for shim in &plan.shims {
            md.push_str(&format!(
                "### `{}` ({} importers)\n\n",
                shim.old_path, shim.importer_count
            ));
            md.push_str("```\n");
            md.push_str(&shim.code);
            md.push_str("\n```\n\n");
        }
    }

    // Footer
    md.push_str("---\n\n");
    md.push_str("*Generated by loctree • VibeCrafted with AI Agents (c)2026 Loctree Team*\n");

    md
}

/// Output multiple refactor plans as a single markdown file.
pub fn output_bundle_as_markdown(plans: &[RefactorPlan], path: &Path) -> io::Result<()> {
    let content = format_bundle_as_markdown(plans);
    fs::write(path, content)
}

/// Format multiple refactor plans as a single markdown string.
pub fn format_bundle_as_markdown(plans: &[RefactorPlan]) -> String {
    let mut md = String::new();
    for (idx, plan) in plans.iter().enumerate() {
        if idx > 0 {
            md.push_str("\n\n---\n\n");
        }
        md.push_str(&format_as_markdown(plan));
    }
    md
}

// ============================================================================
// JSON Output
// ============================================================================

/// Output refactor plan as JSON.
pub fn output_as_json(plan: &RefactorPlan, path: &Path) -> io::Result<()> {
    let json = serde_json::to_string_pretty(plan)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    fs::write(path, json)
}

/// Format refactor plan as JSON string.
pub fn format_as_json(plan: &RefactorPlan) -> String {
    serde_json::to_string_pretty(plan).unwrap_or_else(|_| "{}".to_string())
}

/// Output multiple refactor plans as JSON.
pub fn output_bundle_as_json(plans: &[RefactorPlan], path: &Path) -> io::Result<()> {
    let json = serde_json::to_string_pretty(plans)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    fs::write(path, json)
}

/// Format multiple refactor plans as JSON string.
pub fn format_bundle_as_json(plans: &[RefactorPlan]) -> String {
    serde_json::to_string_pretty(plans).unwrap_or_else(|_| "[]".to_string())
}

// ============================================================================
// Shell Script Output
// ============================================================================

/// Output refactor plan as executable shell script.
pub fn output_as_script(plan: &RefactorPlan, path: &Path) -> io::Result<()> {
    let content = format_as_script(plan);
    fs::write(path, content)?;

    // Make executable on Unix
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(path, perms)?;
    }

    Ok(())
}

/// Format refactor plan as shell script string.
pub fn format_as_script(plan: &RefactorPlan) -> String {
    let mut script = String::new();

    // Shebang and header
    script.push_str("#!/bin/bash\n");
    script.push_str("# Refactor Plan - Generated by loctree\n");
    script.push_str(&format!("# Target: {}\n", plan.target));
    script.push_str(&format!(
        "# Generated: {}\n",
        chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
    ));
    script.push_str("#\n");
    script.push_str("# VibeCrafted with AI Agents (c)2026 Loctree Team\n");
    script.push_str("#\n");
    script.push_str("# Usage:\n");
    script.push_str("#   ./refactor.sh         # Execute all phases\n");
    script.push_str("#   ./refactor.sh --dry   # Show commands without executing\n");
    script.push_str("#   ./refactor.sh 1       # Execute only phase 1\n");
    script.push('\n');

    // Safety settings
    script.push_str("set -e  # Exit on error\n");
    script.push_str("set -u  # Error on undefined variables\n");
    script.push('\n');

    // Color definitions
    script.push_str("# Colors\n");
    script.push_str("RED='\\033[0;31m'\n");
    script.push_str("GREEN='\\033[0;32m'\n");
    script.push_str("YELLOW='\\033[0;33m'\n");
    script.push_str("NC='\\033[0m' # No Color\n");
    script.push('\n');

    // Dry run flag
    script.push_str("DRY_RUN=false\n");
    script.push_str("PHASE_FILTER=\"\"\n");
    script.push('\n');
    script.push_str("# Parse arguments\n");
    script.push_str("for arg in \"$@\"; do\n");
    script.push_str("    case $arg in\n");
    script.push_str("        --dry)\n");
    script.push_str("            DRY_RUN=true\n");
    script.push_str("            ;;\n");
    script.push_str("        [0-9]*)\n");
    script.push_str("            PHASE_FILTER=\"$arg\"\n");
    script.push_str("            ;;\n");
    script.push_str("    esac\n");
    script.push_str("done\n");
    script.push('\n');

    // Run function
    script.push_str("run() {\n");
    script.push_str("    if [ \"$DRY_RUN\" = true ]; then\n");
    script.push_str("        echo \"[DRY] $*\"\n");
    script.push_str("    else\n");
    script.push_str("        echo \"[RUN] $*\"\n");
    script.push_str("        \"$@\"\n");
    script.push_str("    fi\n");
    script.push_str("}\n");
    script.push('\n');

    // Phase functions
    for (i, phase) in plan.phases.iter().enumerate() {
        let phase_num = i + 1;
        let risk_color = match phase.risk {
            RiskLevel::Low => "GREEN",
            RiskLevel::Medium => "YELLOW",
            RiskLevel::High => "RED",
        };

        script.push_str(&format!("phase_{} () {{\n", phase_num));
        script.push_str(&format!(
            "    echo -e \"${{{}}}=== {} ===${{NC}}\"\n",
            risk_color, phase.name
        ));
        script.push_str(&format!(
            "    echo \"Moving {} files...\"\n",
            phase.moves.len()
        ));
        script.push('\n');

        for mv in &phase.moves {
            // Create parent directory
            if let Some(parent) = Path::new(&mv.target).parent() {
                script.push_str(&format!("    run mkdir -p \"{}\"\n", parent.display()));
            }
            // Move file
            script.push_str(&format!(
                "    run git mv \"{}\" \"{}\"\n",
                mv.source, mv.target
            ));
        }

        script.push('\n');
        script.push_str(&format!(
            "    echo -e \"${{GREEN}}✓ Phase {} complete${{NC}}\"\n",
            phase_num
        ));
        script.push_str("}\n\n");
    }

    // Shim creation function
    if !plan.shims.is_empty() {
        script.push_str("create_shims() {\n");
        script.push_str("    echo \"=== Creating Shims ===\"\n");

        for shim in &plan.shims {
            // Escape the shim code for heredoc
            let escaped_code = shim.code.replace('$', "\\$").replace('`', "\\`");
            script.push_str(&format!("\n    cat > \"{}\" <<'SHIMEOF'\n", shim.old_path));
            script.push_str(&escaped_code);
            script.push_str("\nSHIMEOF\n");
        }

        script.push_str("\n    echo -e \"${GREEN}✓ Shims created${NC}\"\n");
        script.push_str("}\n\n");
    }

    // Main execution
    script.push_str("# Main execution\n");
    script.push_str("echo \"Refactor Plan Execution\"\n");
    script.push_str(&format!("echo \"Target: {}\"\n", plan.target));
    script.push_str(&format!("echo \"Phases: {}\"\n", plan.phases.len()));
    script.push_str("echo \"\"\n");
    script.push('\n');

    // Execute phases
    for (i, _) in plan.phases.iter().enumerate() {
        let phase_num = i + 1;
        script.push_str(&format!(
            "if [ -z \"$PHASE_FILTER\" ] || [ \"$PHASE_FILTER\" = \"{}\" ]; then\n",
            phase_num
        ));
        script.push_str(&format!("    phase_{}\n", phase_num));
        script.push_str("fi\n\n");
    }

    // Create shims at the end
    if !plan.shims.is_empty() {
        script.push_str("if [ -z \"$PHASE_FILTER\" ]; then\n");
        script.push_str("    create_shims\n");
        script.push_str("fi\n\n");
    }

    // Summary
    script.push_str("echo \"\"\n");
    script.push_str("echo -e \"${GREEN}=== Refactoring Complete ===${NC}\"\n");
    script.push_str("echo \"Run 'git status' to review changes\"\n");
    script.push_str("echo \"Run 'loct health' to verify structure\"\n");

    script
}

/// Output multiple refactor plans as a single executable shell script.
pub fn output_bundle_as_script(plans: &[RefactorPlan], path: &Path) -> io::Result<()> {
    let content = format_bundle_as_script(plans);
    fs::write(path, content)?;

    // Make executable on Unix
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(path, perms)?;
    }

    Ok(())
}

/// Format multiple refactor plans as a single shell script string.
pub fn format_bundle_as_script(plans: &[RefactorPlan]) -> String {
    let mut script = String::new();

    // Shebang and header
    script.push_str("#!/bin/bash\n");
    script.push_str("# Refactor Plan (multi-target) - Generated by loctree\n");
    script.push_str("# Targets:\n");
    for plan in plans {
        script.push_str(&format!("#   - {}\n", plan.target));
    }
    script.push_str(&format!(
        "# Generated: {}\n",
        chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
    ));
    script.push_str("#\n");
    script.push_str("# VibeCrafted with AI Agents (c)2026 Loctree Team\n");
    script.push_str("#\n");
    script.push_str("# Usage:\n");
    script.push_str("#   ./refactor.sh         # Execute all phases\n");
    script.push_str("#   ./refactor.sh --dry   # Show commands without executing\n");
    script.push_str("#   ./refactor.sh 1       # Execute only phase 1\n");
    script.push('\n');

    // Safety settings
    script.push_str("set -e  # Exit on error\n");
    script.push_str("set -u  # Error on undefined variables\n");
    script.push('\n');

    // Color definitions
    script.push_str("# Colors\n");
    script.push_str("RED='\\033[0;31m'\n");
    script.push_str("GREEN='\\033[0;32m'\n");
    script.push_str("YELLOW='\\033[0;33m'\n");
    script.push_str("NC='\\033[0m' # No Color\n");
    script.push('\n');

    // Dry run flag
    script.push_str("DRY_RUN=false\n");
    script.push_str("PHASE_FILTER=\"\"\n");
    script.push('\n');
    script.push_str("# Parse arguments\n");
    script.push_str("for arg in \"$@\"; do\n");
    script.push_str("    case $arg in\n");
    script.push_str("        --dry)\n");
    script.push_str("            DRY_RUN=true\n");
    script.push_str("            ;;\n");
    script.push_str("        [0-9]*)\n");
    script.push_str("            PHASE_FILTER=\"$arg\"\n");
    script.push_str("            ;;\n");
    script.push_str("    esac\n");
    script.push_str("done\n");
    script.push('\n');

    // Run function
    script.push_str("run() {\n");
    script.push_str("    if [ \"$DRY_RUN\" = true ]; then\n");
    script.push_str("        echo \"[DRY] $*\"\n");
    script.push_str("    else\n");
    script.push_str("        echo \"[RUN] $*\"\n");
    script.push_str("        \"$@\"\n");
    script.push_str("    fi\n");
    script.push_str("}\n");
    script.push('\n');

    // Phase functions (flatten across plans)
    let mut phase_num = 1usize;
    for plan in plans {
        for phase in &plan.phases {
            let risk_color = match phase.risk {
                RiskLevel::Low => "GREEN",
                RiskLevel::Medium => "YELLOW",
                RiskLevel::High => "RED",
            };

            script.push_str(&format!("phase_{} () {{\n", phase_num));
            script.push_str(&format!(
                "    echo -e \"${{{}}}=== [{}] {} ===${{NC}}\"\n",
                risk_color, plan.target, phase.name
            ));
            script.push_str(&format!(
                "    echo \"Moving {} files...\"\n",
                phase.moves.len()
            ));
            script.push('\n');

            for mv in &phase.moves {
                // Create parent directory
                if let Some(parent) = Path::new(&mv.target).parent() {
                    script.push_str(&format!("    run mkdir -p \"{}\"\n", parent.display()));
                }
                // Move file
                script.push_str(&format!(
                    "    run git mv \"{}\" \"{}\"\n",
                    mv.source, mv.target
                ));
            }

            script.push('\n');
            script.push_str(&format!(
                "    echo -e \"${{GREEN}}✓ Phase {} complete${{NC}}\"\n",
                phase_num
            ));
            script.push_str("}\n\n");

            phase_num += 1;
        }
    }

    let total_phases = phase_num.saturating_sub(1);

    // Shim creation function
    let mut shims: HashMap<String, Shim> = HashMap::new();
    for plan in plans {
        for shim in &plan.shims {
            shims
                .entry(shim.old_path.clone())
                .or_insert_with(|| shim.clone());
        }
    }

    if !shims.is_empty() {
        script.push_str("create_shims() {\n");
        script.push_str("    echo \"=== Creating Shims ===\"\n");

        let mut keys: Vec<String> = shims.keys().cloned().collect();
        keys.sort();
        for key in keys {
            if let Some(shim) = shims.get(&key) {
                // Escape the shim code for heredoc
                let escaped_code = shim.code.replace('$', "\\$").replace('`', "\\`");
                script.push_str(&format!("\n    cat > \"{}\" <<'SHIMEOF'\n", shim.old_path));
                script.push_str(&escaped_code);
                script.push_str("\nSHIMEOF\n");
            }
        }

        script.push_str("\n    echo -e \"${GREEN}✓ Shims created${NC}\"\n");
        script.push_str("}\n\n");
    }

    // Main execution
    script.push_str("# Main execution\n");
    script.push_str("echo \"Refactor Plan Execution\"\n");
    script.push_str(&format!("echo \"Targets: {}\"\n", plans.len()));
    script.push_str(&format!("echo \"Phases: {}\"\n", total_phases));
    script.push_str("echo \"\"\n");
    script.push('\n');

    // Execute phases
    for phase_num in 1..=total_phases {
        script.push_str(&format!(
            "if [ -z \"$PHASE_FILTER\" ] || [ \"$PHASE_FILTER\" = \"{}\" ]; then\n",
            phase_num
        ));
        script.push_str(&format!("    phase_{}\n", phase_num));
        script.push_str("fi\n\n");
    }

    // Create shims at the end
    if !shims.is_empty() {
        script.push_str("if [ -z \"$PHASE_FILTER\" ]; then\n");
        script.push_str("    create_shims\n");
        script.push_str("fi\n\n");
    }

    // Summary
    script.push_str("echo \"\"\n");
    script.push_str("echo -e \"${GREEN}=== Refactoring Complete ===${NC}\"\n");
    script.push_str("echo \"Run 'git status' to review changes\"\n");
    script.push_str("echo \"Run 'loct health' to verify structure\"\n");

    script
}

// ============================================================================
// Print to stdout
// ============================================================================

/// Print plan summary to stdout.
pub fn print_plan_summary(plan: &RefactorPlan) {
    println!("Refactor Plan: {}/", plan.target);
    println!();
    println!(
        "  Files: {} total, {} to move",
        plan.stats.total_files, plan.stats.files_to_move
    );

    if !plan.stats.by_risk.is_empty() {
        let risk_str: Vec<String> = plan
            .stats
            .by_risk
            .iter()
            .map(|(k, v)| format!("{} {}", v, k))
            .collect();
        println!("  Risk: {}", risk_str.join(", "));
    }

    if plan.stats.shims_needed > 0 {
        println!("  Shims: {} needed", plan.stats.shims_needed);
    }

    if !plan.cyclic_groups.is_empty() {
        println!(
            "  Cycles: {} groups (move together)",
            plan.cyclic_groups.len()
        );
    }

    println!();

    // Brief phase summary
    for phase in &plan.phases {
        let emoji = match phase.risk {
            RiskLevel::Low => "🟢",
            RiskLevel::Medium => "🟡",
            RiskLevel::High => "🔴",
        };
        println!("  {} {} ({} files)", emoji, phase.name, phase.moves.len());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::refactor_plan::{Layer, Move, PlanStats, RefactorPhase, RiskLevel};
    use std::collections::HashMap;

    fn mock_plan() -> RefactorPlan {
        RefactorPlan {
            target: "src/features".to_string(),
            moves: vec![Move {
                source: "src/features/utils.ts".to_string(),
                target: "src/features/infra/utils.ts".to_string(),
                current_layer: Layer::Unknown,
                target_layer: Layer::Infra,
                risk: RiskLevel::Low,
                direct_consumers: 3,
                transitive_consumers: 8,
                loc: 120,
                reason: "Unknown → Infra".to_string(),
                verify_cmd: "loct impact src/features/infra/utils.ts".to_string(),
                affected_files: vec!["src/features/main.ts".to_string()],
            }],
            shims: vec![],
            cyclic_groups: vec![],
            phases: vec![RefactorPhase {
                name: "Phase 1: LOW Risk".to_string(),
                risk: RiskLevel::Low,
                moves: vec![Move {
                    source: "src/features/utils.ts".to_string(),
                    target: "src/features/infra/utils.ts".to_string(),
                    current_layer: Layer::Unknown,
                    target_layer: Layer::Infra,
                    risk: RiskLevel::Low,
                    direct_consumers: 3,
                    transitive_consumers: 8,
                    loc: 120,
                    reason: "Unknown → Infra".to_string(),
                    verify_cmd: "loct impact src/features/infra/utils.ts".to_string(),
                    affected_files: vec!["src/features/main.ts".to_string()],
                }],
                git_script: "git mv src/features/utils.ts src/features/infra/utils.ts".to_string(),
            }],
            stats: PlanStats {
                total_files: 10,
                files_to_move: 1,
                shims_needed: 0,
                layer_before: HashMap::from([("Unknown".to_string(), 1)]),
                layer_after: HashMap::from([("Infra".to_string(), 1)]),
                by_risk: HashMap::from([("LOW".to_string(), 1)]),
            },
        }
    }

    #[test]
    fn test_format_as_markdown() {
        let plan = mock_plan();
        let md = format_as_markdown(&plan);

        assert!(md.contains("# Refactor Plan: src/features"));
        assert!(md.contains("Files analyzed:** 10"));
        assert!(md.contains("Files to move:** 1"));
        assert!(md.contains("Phase 1: LOW Risk"));
    }

    #[test]
    fn test_format_as_script() {
        let plan = mock_plan();
        let script = format_as_script(&plan);

        assert!(script.starts_with("#!/bin/bash"));
        assert!(script.contains("set -e"));
        assert!(script.contains("phase_1"));
        assert!(script.contains("git mv"));
    }

    #[test]
    fn test_format_bundle_as_json() {
        let mut plan2 = mock_plan();
        plan2.target = "src/other".to_string();

        let json = format_bundle_as_json(&[mock_plan(), plan2]);
        assert!(json.trim_start().starts_with('['));
        assert!(json.contains("\"target\": \"src/features\""));
        assert!(json.contains("\"target\": \"src/other\""));
    }
}