coda-core 0.1.0

Core execution engine for CODA — orchestrates AI-driven feature development workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
//! Core execution engine implementation.
//!
//! The `Engine` orchestrates all CODA operations: initialization, planning,
//! execution, and cleanup. It delegates git/gh operations through the
//! [`GitOps`](crate::git::GitOps) and [`GhOps`](crate::gh::GhOps) traits,
//! and feature discovery through [`FeatureScanner`](crate::scanner::FeatureScanner).

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use claude_agent_sdk_rs::Message;
use coda_pm::PromptManager;
use serde::Serialize;
use tracing::{debug, info, warn};

use tokio::sync::mpsc::UnboundedSender;

use crate::CoreError;
use crate::config::CodaConfig;
use crate::gh::{DefaultGhOps, GhOps};
use crate::git::{DefaultGitOps, GitOps};
use crate::planner::PlanSession;
use crate::profile::AgentProfile;
use crate::runner::RunEvent;
use crate::scanner::FeatureScanner;
use crate::task::TaskResult;

/// Directories to skip when building the repository tree.
const SKIP_DIRS: &[&str] = &[
    ".git",
    ".coda",
    ".trees",
    "target",
    "node_modules",
    ".next",
    "dist",
    "build",
    "__pycache__",
    ".venv",
    "venv",
    ".tox",
    ".mypy_cache",
    ".pytest_cache",
    ".cargo",
    "vendor",
    ".idea",
    ".vscode",
];

/// Key files to sample for repository analysis.
const SAMPLE_FILES: &[&str] = &[
    "Cargo.toml",
    "package.json",
    "pyproject.toml",
    "requirements.txt",
    "go.mod",
    "Makefile",
    "Dockerfile",
    "docker-compose.yml",
    "README.md",
    "CLAUDE.md",
    ".gitignore",
    "tsconfig.json",
    "CMakeLists.txt",
    "build.gradle",
    "pom.xml",
];

/// Maximum number of lines to read from each sample file.
const SAMPLE_MAX_LINES: usize = 40;

/// Maximum tree depth when gathering the repository tree.
const TREE_MAX_DEPTH: usize = 4;

/// A sampled file for repository analysis, serializable for template rendering.
#[derive(Debug, Serialize)]
struct FileSample {
    /// Relative path of the sampled file.
    path: String,
    /// First N lines of file content.
    content: String,
}

/// The core execution engine for CODA.
///
/// Manages project configuration, prompt templates, and orchestrates
/// interactions with the Claude Agent SDK.
pub struct Engine {
    /// Root directory of the project.
    project_root: PathBuf,

    /// Prompt template manager loaded with built-in and custom templates.
    pm: PromptManager,

    /// Project configuration loaded from `.coda/config.yml`.
    config: CodaConfig,

    /// Feature worktree scanner.
    scanner: FeatureScanner,

    /// Git operations implementation (Arc for sharing with sub-sessions).
    git: Arc<dyn GitOps>,

    /// GitHub CLI operations implementation.
    gh: Arc<dyn GhOps>,
}

impl Engine {
    /// Creates a new engine for the given project root.
    ///
    /// Loads configuration from `.coda/config.yml` (falling back to defaults
    /// if the file doesn't exist), initializes the prompt manager with
    /// built-in templates, and loads any custom templates from configured
    /// extra directories.
    ///
    /// # Errors
    ///
    /// Returns `CoreError` if configuration parsing fails or template
    /// loading encounters an error.
    pub async fn new(project_root: PathBuf) -> Result<Self, CoreError> {
        // Load config from .coda/config.yml, or use defaults if not present
        let config_path = project_root.join(".coda/config.yml");
        let config = if config_path.exists() {
            let content = fs::read_to_string(&config_path).map_err(|e| {
                CoreError::ConfigError(format!(
                    "Cannot read config file at {}: {e}",
                    config_path.display()
                ))
            })?;
            serde_yaml::from_str::<CodaConfig>(&content).map_err(|e| {
                CoreError::ConfigError(format!(
                    "Invalid YAML in config file at {}: {e}",
                    config_path.display()
                ))
            })?
        } else {
            info!("No .coda/config.yml found, using default configuration");
            CodaConfig::default()
        };

        // Create PromptManager pre-loaded with built-in templates
        let mut pm = PromptManager::with_builtin_templates()?;
        info!(
            template_count = pm.template_count(),
            "Loaded built-in templates"
        );

        // Load custom templates from configured extra directories
        for extra_dir in &config.prompts.extra_dirs {
            let dir = project_root.join(extra_dir);
            if dir.exists() {
                pm.load_from_dir(&dir)?;
                info!(dir = %dir.display(), "Loaded custom templates");
            }
        }

        let scanner = FeatureScanner::new(&project_root);
        let git: Arc<dyn GitOps> = Arc::new(DefaultGitOps::new(project_root.clone()));
        let gh: Arc<dyn GhOps> = Arc::new(DefaultGhOps::new(project_root.clone()));

        Ok(Self {
            project_root,
            pm,
            config,
            scanner,
            git,
            gh,
        })
    }

    /// Returns a reference to the project root directory.
    pub fn project_root(&self) -> &Path {
        &self.project_root
    }

    /// Returns a reference to the prompt manager.
    pub fn prompt_manager(&self) -> &PromptManager {
        &self.pm
    }

    /// Returns a reference to the project configuration.
    pub fn config(&self) -> &CodaConfig {
        &self.config
    }

    /// Returns a reference to the git operations implementation.
    pub fn git(&self) -> &dyn GitOps {
        self.git.as_ref()
    }

    /// Returns a reference to the GitHub CLI operations implementation.
    pub fn gh(&self) -> &dyn GhOps {
        self.gh.as_ref()
    }

    /// Initializes the current repository as a CODA project.
    ///
    /// The init flow performs two agent calls:
    /// 1. `query(Planner)` with `init/analyze_repo` to analyze the repository
    ///    structure, tech stack, and architecture.
    /// 2. `query(Coder)` with `init/setup_project` to create `.coda/`, `.trees/`,
    ///    `config.yml`, `.coda.md`, and update `.gitignore`.
    ///
    /// # Errors
    ///
    /// Returns `CoreError::ConfigError` if the project is already initialized
    /// (`.coda/` exists), or `CoreError::AgentError` if agent calls fail.
    pub async fn init(&self) -> Result<(), CoreError> {
        // 1. Check if .coda/ already exists
        if self.project_root.join(".coda").exists() {
            return Err(CoreError::ConfigError(
                "Project already initialized. .coda/ directory exists.".into(),
            ));
        }

        // 2. Render system prompt for init
        let system_prompt = self.pm.render("init/system", minijinja::context!())?;

        // 3. Analyze repository structure
        let repo_tree = gather_repo_tree(&self.project_root)?;
        let file_samples = gather_file_samples(&self.project_root)?;

        let analyze_prompt = self.pm.render(
            "init/analyze_repo",
            minijinja::context!(
                repo_tree => repo_tree,
                file_samples => file_samples,
            ),
        )?;

        debug!("Analyzing repository structure...");

        let planner_options = AgentProfile::Planner.to_options(
            &system_prompt,
            self.project_root.clone(),
            5, // max_turns for analysis
            self.config.agent.max_budget_usd,
            &self.config.agent.model,
        );

        let messages = claude_agent_sdk_rs::query(analyze_prompt, Some(planner_options))
            .await
            .map_err(|e| CoreError::AgentError(e.to_string()))?;

        // Extract analysis result text from messages
        let analysis_result = extract_text_from_messages(&messages);
        debug!(
            analysis_len = analysis_result.len(),
            "Repository analysis complete"
        );

        // 4. Setup project structure
        let setup_prompt = self.pm.render(
            "init/setup_project",
            minijinja::context!(
                project_root => self.project_root.display().to_string(),
                analysis_result => analysis_result,
            ),
        )?;

        debug!("Setting up project structure...");

        let coder_options = AgentProfile::Coder.to_options(
            &system_prompt,
            self.project_root.clone(),
            10, // max_turns for setup
            self.config.agent.max_budget_usd,
            &self.config.agent.model,
        );

        let _messages = claude_agent_sdk_rs::query(setup_prompt, Some(coder_options))
            .await
            .map_err(|e| CoreError::AgentError(e.to_string()))?;

        info!("Project initialized successfully");
        Ok(())
    }

    /// Starts an interactive planning session for a feature.
    ///
    /// Validates the slug format and checks for duplicate features before
    /// creating a `PlanSession` wrapping a `ClaudeClient` with the Planner
    /// profile for multi-turn conversation. The session must be explicitly
    /// connected and finalized by the caller (typically the CLI layer).
    ///
    /// # Errors
    ///
    /// Returns `CoreError::PlanError` if the slug is invalid or a feature
    /// with the same slug already exists. Returns other `CoreError` variants
    /// if the session cannot be created.
    pub fn plan(&self, feature_slug: &str) -> Result<PlanSession, CoreError> {
        validate_feature_slug(feature_slug)?;

        let worktree_path = self.project_root.join(".trees").join(feature_slug);
        if worktree_path.exists() {
            return Err(CoreError::PlanError(format!(
                "Feature '{feature_slug}' already exists at {}. \
                 Use `coda status {feature_slug}` to check its state, \
                 or choose a different slug.",
                worktree_path.display(),
            )));
        }

        info!(feature_slug, "Starting planning session");
        PlanSession::new(
            feature_slug.to_string(),
            self.project_root.clone(),
            &self.pm,
            &self.config,
            Arc::clone(&self.git),
        )
    }

    /// Lists all features: active worktrees from `.trees/` and merged
    /// features from `.coda/`.
    ///
    /// Delegates to [`FeatureScanner::list`].
    ///
    /// # Errors
    ///
    /// Returns `CoreError::ConfigError` if neither `.trees/` nor `.coda/`
    /// contains any features and `.trees/` does not exist.
    pub fn list_features(&self) -> Result<Vec<crate::state::FeatureState>, CoreError> {
        self.scanner.list()
    }

    /// Returns detailed state for a specific feature identified by its slug.
    ///
    /// Delegates to [`FeatureScanner::get`].
    ///
    /// # Errors
    ///
    /// Returns `CoreError::ConfigError` if `.trees/` does not exist, or
    /// `CoreError::StateError` if no matching feature is found.
    pub fn feature_status(
        &self,
        feature_slug: &str,
    ) -> Result<crate::state::FeatureState, CoreError> {
        self.scanner.get(feature_slug)
    }

    /// Executes a feature development run through all phases.
    ///
    /// Reads `state.yml` and resumes from the last completed phase. Uses
    /// a single continuous `ClaudeClient` session with the Coder profile
    /// to execute setup → implement → test → review → verify → PR.
    ///
    /// When `progress_tx` is provided, emits [`RunEvent`]s for real-time
    /// progress display.
    ///
    /// # Errors
    ///
    /// Returns `CoreError` if the runner cannot be created or any phase
    /// fails after all retries.
    pub async fn run(
        &self,
        feature_slug: &str,
        progress_tx: Option<UnboundedSender<RunEvent>>,
    ) -> Result<Vec<TaskResult>, CoreError> {
        info!(feature_slug, "Starting feature run");
        let mut runner = crate::runner::Runner::new(
            feature_slug,
            self.project_root.clone(),
            &self.pm,
            &self.config,
            Arc::clone(&self.git),
            Arc::clone(&self.gh),
        )?;
        if let Some(tx) = progress_tx {
            runner.set_progress_sender(tx);
        }
        runner.execute().await
    }

    /// Cleans up worktrees whose corresponding PR has been merged or closed.
    ///
    /// For each feature in `.trees/`:
    /// 1. If `state.yml` contains a PR number, queries its status via `gh pr view`.
    /// 2. Otherwise, queries `gh pr list --head <branch>` to discover the PR.
    /// 3. If the PR is `MERGED` or `CLOSED`, removes the worktree and deletes
    ///    the local branch.
    ///
    /// Scans features and returns candidates whose PR is merged or closed.
    ///
    /// Does **not** delete anything. Use [`remove_worktrees`](Self::remove_worktrees)
    /// to perform the actual removal after user confirmation.
    ///
    /// # Errors
    ///
    /// Returns `CoreError` if `.trees/` does not exist.
    pub fn scan_cleanable_worktrees(&self) -> Result<Vec<CleanedWorktree>, CoreError> {
        let features = self.list_features()?;
        let mut candidates = Vec::new();

        for feature in &features {
            match self.check_feature_pr_status(feature) {
                Ok(Some(result)) => candidates.push(result),
                Ok(None) => {}
                Err(e) => {
                    warn!(
                        slug = %feature.feature.slug,
                        error = %e,
                        "Failed to check PR status, skipping"
                    );
                }
            }
        }

        Ok(candidates)
    }

    /// Removes worktrees and branches for the given candidates.
    ///
    /// For each candidate, removes the git worktree, deletes the local branch,
    /// and cleans up the corresponding log directory at `.coda/<slug>/logs/`.
    ///
    /// Designed to be called after [`scan_cleanable_worktrees`](Self::scan_cleanable_worktrees)
    /// and user confirmation.
    ///
    /// # Errors
    ///
    /// Returns `CoreError` if a git operation fails during removal.
    pub fn remove_worktrees(
        &self,
        candidates: &[CleanedWorktree],
    ) -> Result<Vec<CleanedWorktree>, CoreError> {
        let mut removed = Vec::new();

        for c in candidates {
            let worktree_abs = self.project_root.join(".trees").join(&c.slug);
            if !worktree_abs.exists() {
                info!(path = %worktree_abs.display(), "Worktree path does not exist, running prune");
                self.git.worktree_prune()?;
            } else {
                self.git.worktree_remove(&worktree_abs, true)?;
            }

            if let Err(e) = self.git.branch_delete(&c.branch) {
                warn!(branch = %c.branch, error = %e, "Failed to delete local branch (may already be deleted)");
            }

            // Clean up log directory in the main repo (best-effort)
            let _ = remove_feature_logs(&self.project_root, &c.slug);

            removed.push(c.clone());
        }

        Ok(removed)
    }

    /// Removes log directories for all features under `.coda/*/logs/`.
    ///
    /// Scans the `.coda/` directory for feature subdirectories that contain
    /// a `logs/` child, deletes each one, and returns the list of feature
    /// slugs whose logs were successfully cleaned.
    ///
    /// # Errors
    ///
    /// Returns `CoreError::ConfigError` if `.coda/` cannot be read.
    pub fn clean_logs(&self) -> Result<Vec<String>, CoreError> {
        let coda_dir = self.project_root.join(".coda");
        if !coda_dir.is_dir() {
            return Ok(Vec::new());
        }

        let entries = fs::read_dir(&coda_dir).map_err(|e| {
            CoreError::ConfigError(format!(
                "Cannot read .coda/ directory at {}: {e}",
                coda_dir.display()
            ))
        })?;

        let mut cleaned = Vec::new();
        for entry in entries.filter_map(Result::ok) {
            if !entry.file_type().is_ok_and(|ft| ft.is_dir()) {
                continue;
            }
            let slug = entry.file_name();
            let slug_str = slug.to_string_lossy();
            let logs_dir = entry.path().join("logs");
            if logs_dir.is_dir() && remove_feature_logs(&self.project_root, &slug_str) {
                cleaned.push(slug_str.into_owned());
            }
        }

        cleaned.sort();
        info!(count = cleaned.len(), "Cleaned all feature logs");
        Ok(cleaned)
    }

    /// Checks a single feature's PR status. Returns a [`CleanedWorktree`]
    /// candidate if the PR is merged or closed, `None` otherwise.
    ///
    /// As a defensive check, skips features whose worktree directory no
    /// longer exists under `.trees/` (e.g. ghost entries from merged branches).
    fn check_feature_pr_status(
        &self,
        feature: &crate::state::FeatureState,
    ) -> Result<Option<CleanedWorktree>, CoreError> {
        let slug = &feature.feature.slug;
        let branch = &feature.git.branch;

        let worktree_dir = self.project_root.join(".trees").join(slug);
        if !worktree_dir.is_dir() {
            debug!(
                slug,
                path = %worktree_dir.display(),
                "Worktree directory does not exist, skipping ghost feature"
            );
            return Ok(None);
        }

        let pr_status = if let Some(ref pr) = feature.pr {
            self.gh.pr_view_state(pr.number)?
        } else {
            self.gh.pr_list_by_branch(branch)?
        };

        let Some(pr_status) = pr_status else {
            debug!(slug, branch, "No PR found, skipping");
            return Ok(None);
        };

        let state_upper = pr_status.state.to_uppercase();
        if state_upper != "MERGED" && state_upper != "CLOSED" {
            debug!(
                slug,
                branch,
                state = %pr_status.state,
                "PR still open, skipping"
            );
            return Ok(None);
        }

        Ok(Some(CleanedWorktree {
            slug: slug.clone(),
            branch: branch.clone(),
            pr_number: Some(pr_status.number),
            pr_state: state_upper,
        }))
    }
}

/// Result of cleaning a single worktree.
#[derive(Debug, Clone)]
pub struct CleanedWorktree {
    /// Feature slug.
    pub slug: String,

    /// Git branch name.
    pub branch: String,

    /// PR number if found.
    pub pr_number: Option<u32>,

    /// PR state (e.g., "MERGED", "CLOSED").
    pub pr_state: String,
}

impl std::fmt::Debug for Engine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Engine")
            .field("project_root", &self.project_root)
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Maximum length for a feature slug (keeps branch names and paths manageable).
const SLUG_MAX_LEN: usize = 64;

/// Validates that a feature slug is URL-safe and suitable for use in
/// branch names and filesystem paths.
///
/// Accepted format: lowercase ASCII alphanumeric characters and hyphens,
/// starting and ending with an alphanumeric character (e.g., `"add-user-auth"`).
///
/// # Errors
///
/// Returns `CoreError::PlanError` with a human-readable explanation when
/// validation fails.
pub fn validate_feature_slug(slug: &str) -> Result<(), CoreError> {
    if slug.is_empty() {
        return Err(CoreError::PlanError(
            "Feature slug cannot be empty.".to_string(),
        ));
    }
    if slug.len() > SLUG_MAX_LEN {
        return Err(CoreError::PlanError(format!(
            "Feature slug is too long ({} chars, max {SLUG_MAX_LEN}).",
            slug.len(),
        )));
    }
    if !slug
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
    {
        return Err(CoreError::PlanError(format!(
            "Feature slug '{slug}' contains invalid characters. \
             Only lowercase letters, digits, and hyphens are allowed.",
        )));
    }
    if slug.starts_with('-') || slug.ends_with('-') {
        return Err(CoreError::PlanError(format!(
            "Feature slug '{slug}' must not start or end with a hyphen.",
        )));
    }
    if slug.contains("--") {
        return Err(CoreError::PlanError(format!(
            "Feature slug '{slug}' must not contain consecutive hyphens.",
        )));
    }
    Ok(())
}

/// Removes the log directory for a feature at `.coda/<slug>/logs/`.
///
/// Returns `true` if the directory was successfully removed or did not
/// exist. Returns `false` if deletion failed (a warning is logged).
///
/// # Examples
///
/// ```no_run
/// # use std::path::Path;
/// // After cleaning a worktree, remove its logs:
/// let removed = coda_core::remove_feature_logs(Path::new("/repo"), "my-feature");
/// ```
pub fn remove_feature_logs(project_root: &Path, slug: &str) -> bool {
    let logs_dir = project_root.join(".coda").join(slug).join("logs");
    match fs::remove_dir_all(&logs_dir) {
        Ok(()) => {
            info!(slug, path = %logs_dir.display(), "Removed feature log directory");
            true
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            debug!(slug, path = %logs_dir.display(), "No log directory to clean");
            true
        }
        Err(e) => {
            warn!(
                slug,
                path = %logs_dir.display(),
                error = %e,
                "Failed to remove feature log directory"
            );
            false
        }
    }
}

/// Builds a simple directory tree listing of the repository.
///
/// Skips common non-source directories (`.git`, `target`, `node_modules`, etc.)
/// and limits depth to [`TREE_MAX_DEPTH`] levels.
fn gather_repo_tree(root: &Path) -> Result<String, CoreError> {
    let mut output = String::new();
    build_tree(root, "", &mut output, 0)?;
    Ok(output)
}

/// Recursively builds the tree string for [`gather_repo_tree`].
fn build_tree(
    current: &Path,
    prefix: &str,
    output: &mut String,
    depth: usize,
) -> Result<(), CoreError> {
    if depth > TREE_MAX_DEPTH {
        return Ok(());
    }

    let mut entries: Vec<_> = fs::read_dir(current)?
        .filter_map(|e| e.ok())
        .filter(|entry| {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            // Skip hidden files (except key dotfiles)
            if name_str.starts_with('.')
                && !matches!(
                    name_str.as_ref(),
                    ".gitignore" | ".coda.md" | ".env.example"
                )
            {
                return false;
            }
            // Skip excluded directories
            if entry.file_type().is_ok_and(|ft| ft.is_dir())
                && SKIP_DIRS.contains(&name_str.as_ref())
            {
                return false;
            }
            true
        })
        .collect();

    entries.sort_by_key(|e| e.file_name());

    let total = entries.len();
    for (i, entry) in entries.iter().enumerate() {
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        let is_last = i == total - 1;
        let connector = if is_last { "└── " } else { "├── " };
        let child_prefix = if is_last { "    " } else { "" };

        if entry.file_type().is_ok_and(|ft| ft.is_dir()) {
            output.push_str(&format!("{prefix}{connector}{name_str}/\n"));
            build_tree(
                &entry.path(),
                &format!("{prefix}{child_prefix}"),
                output,
                depth + 1,
            )?;
        } else {
            output.push_str(&format!("{prefix}{connector}{name_str}\n"));
        }
    }

    Ok(())
}

/// Reads the first [`SAMPLE_MAX_LINES`] lines from key project files.
///
/// Returns a list of [`FileSample`] structs suitable for template rendering.
/// Only files that actually exist in the repository are included.
fn gather_file_samples(root: &Path) -> Result<Vec<FileSample>, CoreError> {
    let mut samples = Vec::new();

    for &filename in SAMPLE_FILES {
        let path = root.join(filename);
        if path.is_file() {
            let content = fs::read_to_string(&path)?;
            let truncated: String = content
                .lines()
                .take(SAMPLE_MAX_LINES)
                .collect::<Vec<_>>()
                .join("\n");

            samples.push(FileSample {
                path: filename.to_string(),
                content: truncated,
            });
        }
    }

    Ok(samples)
}

/// Extracts all text content from a sequence of Claude SDK messages.
///
/// Iterates through assistant messages, collecting text blocks into a
/// single concatenated string. Non-text content blocks are skipped.
fn extract_text_from_messages(messages: &[Message]) -> String {
    let mut text_parts: Vec<String> = Vec::new();

    for message in messages {
        match message {
            Message::Assistant(assistant) => {
                for block in &assistant.message.content {
                    if let claude_agent_sdk_rs::ContentBlock::Text(text_block) = block {
                        text_parts.push(text_block.text.clone());
                    }
                }
            }
            Message::Result(result) => {
                if let Some(ref result_text) = result.result {
                    text_parts.push(result_text.clone());
                }
            }
            _ => {}
        }
    }

    text_parts.join("\n")
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;
    use crate::state::{
        FeatureInfo, FeatureState, FeatureStatus, GitInfo, PhaseKind, PhaseRecord, PhaseStatus,
        TokenCost, TotalStats,
    };

    fn make_state(slug: &str) -> FeatureState {
        let now = chrono::Utc::now();
        FeatureState {
            feature: FeatureInfo {
                slug: slug.to_string(),
                created_at: now,
                updated_at: now,
            },
            status: FeatureStatus::Planned,
            current_phase: 0,
            git: GitInfo {
                worktree_path: std::path::PathBuf::from(format!(".trees/{slug}")),
                branch: format!("feature/{slug}"),
                base_branch: "main".to_string(),
            },
            phases: vec![
                PhaseRecord {
                    name: "dev".to_string(),
                    kind: PhaseKind::Dev,
                    status: PhaseStatus::Pending,
                    started_at: None,
                    completed_at: None,
                    turns: 0,
                    cost_usd: 0.0,
                    cost: TokenCost::default(),
                    duration_secs: 0,
                    details: serde_json::json!({}),
                },
                PhaseRecord {
                    name: "review".to_string(),
                    kind: PhaseKind::Quality,
                    status: PhaseStatus::Pending,
                    started_at: None,
                    completed_at: None,
                    turns: 0,
                    cost_usd: 0.0,
                    cost: TokenCost::default(),
                    duration_secs: 0,
                    details: serde_json::json!({}),
                },
                PhaseRecord {
                    name: "verify".to_string(),
                    kind: PhaseKind::Quality,
                    status: PhaseStatus::Pending,
                    started_at: None,
                    completed_at: None,
                    turns: 0,
                    cost_usd: 0.0,
                    cost: TokenCost::default(),
                    duration_secs: 0,
                    details: serde_json::json!({}),
                },
            ],
            pr: None,
            total: TotalStats::default(),
        }
    }

    fn write_state(root: &std::path::Path, slug: &str, state: &FeatureState) {
        let dir = root.join(".trees").join(slug).join(".coda").join(slug);
        fs::create_dir_all(&dir).expect("create state dir");
        let yaml = serde_yaml::to_string(state).expect("serialize state");
        fs::write(dir.join("state.yml"), yaml).expect("write state.yml");
    }

    async fn make_engine(root: &std::path::Path) -> Engine {
        Engine::new(root.to_path_buf())
            .await
            .expect("create Engine")
    }

    #[tokio::test]
    async fn test_should_list_features_empty() {
        let tmp = tempfile::tempdir().expect("tempdir");
        fs::create_dir_all(tmp.path().join(".trees")).expect("mkdir");
        let engine = make_engine(tmp.path()).await;

        let features = engine.list_features().expect("list");
        assert!(features.is_empty());
    }

    #[tokio::test]
    async fn test_should_list_features_single() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let state = make_state("add-auth");
        write_state(tmp.path(), "add-auth", &state);
        let engine = make_engine(tmp.path()).await;

        let features = engine.list_features().expect("list");
        assert_eq!(features.len(), 1);
        assert_eq!(features[0].feature.slug, "add-auth");
    }

    #[tokio::test]
    async fn test_should_list_features_sorted_by_slug() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_state(tmp.path(), "zzz-last", &make_state("zzz-last"));
        write_state(tmp.path(), "aaa-first", &make_state("aaa-first"));
        write_state(tmp.path(), "mmm-middle", &make_state("mmm-middle"));
        let engine = make_engine(tmp.path()).await;

        let features = engine.list_features().expect("list");
        assert_eq!(features.len(), 3);
        assert_eq!(features[0].feature.slug, "aaa-first");
        assert_eq!(features[1].feature.slug, "mmm-middle");
        assert_eq!(features[2].feature.slug, "zzz-last");
    }

    #[tokio::test]
    async fn test_should_list_features_skip_invalid_state() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_state(tmp.path(), "good", &make_state("good"));
        // Write invalid YAML
        let bad_dir = tmp.path().join(".trees/bad/.coda/bad");
        fs::create_dir_all(&bad_dir).expect("mkdir");
        fs::write(bad_dir.join("state.yml"), "not: valid: yaml: [").expect("write");
        let engine = make_engine(tmp.path()).await;

        let features = engine.list_features().expect("list");
        assert_eq!(features.len(), 1);
        assert_eq!(features[0].feature.slug, "good");
    }

    #[tokio::test]
    async fn test_should_list_features_error_when_no_trees_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let engine = make_engine(tmp.path()).await;

        let result = engine.list_features();
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains(".trees/"));
    }

    #[tokio::test]
    async fn test_should_get_feature_status_direct_lookup() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let state = make_state("add-auth");
        write_state(tmp.path(), "add-auth", &state);
        let engine = make_engine(tmp.path()).await;

        let found = engine.feature_status("add-auth").expect("status");
        assert_eq!(found.feature.slug, "add-auth");
        assert_eq!(found.git.branch, "feature/add-auth");
    }

    #[tokio::test]
    async fn test_should_get_feature_status_not_found() {
        let tmp = tempfile::tempdir().expect("tempdir");
        write_state(tmp.path(), "existing", &make_state("existing"));
        let engine = make_engine(tmp.path()).await;

        let result = engine.feature_status("nonexistent");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("nonexistent"));
        assert!(err.contains("existing"));
    }

    #[tokio::test]
    async fn test_should_get_feature_status_error_when_no_trees_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let engine = make_engine(tmp.path()).await;

        let result = engine.feature_status("anything");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains(".trees/"));
    }

    #[test]
    fn test_should_gather_repo_tree_from_temp_dir() {
        let tmp = tempfile::tempdir().expect("failed to create temp dir");
        let root = tmp.path();

        // Create a simple structure
        fs::create_dir_all(root.join("src")).expect("mkdir");
        fs::write(root.join("src/main.rs"), "fn main() {}").expect("write");
        fs::write(root.join("Cargo.toml"), "[package]").expect("write");
        fs::create_dir_all(root.join("target/debug")).expect("mkdir");

        let tree = gather_repo_tree(root).expect("gather_repo_tree");

        assert!(tree.contains("src/"));
        assert!(tree.contains("Cargo.toml"));
        // target/ should be skipped
        assert!(!tree.contains("target"));
    }

    #[test]
    fn test_should_gather_file_samples() {
        let tmp = tempfile::tempdir().expect("failed to create temp dir");
        let root = tmp.path();

        fs::write(root.join("Cargo.toml"), "[package]\nname = \"test\"\n").expect("write");
        fs::write(root.join("README.md"), "# Test\nHello world").expect("write");

        let samples = gather_file_samples(root).expect("gather_file_samples");

        assert_eq!(samples.len(), 2);
        let names: Vec<&str> = samples.iter().map(|s| s.path.as_str()).collect();
        assert!(names.contains(&"Cargo.toml"));
        assert!(names.contains(&"README.md"));
    }

    #[test]
    fn test_should_extract_text_from_assistant_messages() {
        let messages = vec![
            Message::Assistant(claude_agent_sdk_rs::AssistantMessage {
                message: claude_agent_sdk_rs::AssistantMessageInner {
                    content: vec![claude_agent_sdk_rs::ContentBlock::Text(
                        claude_agent_sdk_rs::TextBlock {
                            text: "Hello from assistant".to_string(),
                        },
                    )],
                    model: None,
                    id: None,
                    stop_reason: None,
                    usage: None,
                    error: None,
                },
                parent_tool_use_id: None,
                session_id: None,
                uuid: None,
            }),
            Message::Result(claude_agent_sdk_rs::ResultMessage {
                subtype: "success".to_string(),
                duration_ms: 100,
                duration_api_ms: 80,
                is_error: false,
                num_turns: 1,
                session_id: "test".to_string(),
                total_cost_usd: Some(0.01),
                usage: None,
                result: Some("Result text".to_string()),
                structured_output: None,
            }),
        ];

        let text = extract_text_from_messages(&messages);
        assert!(text.contains("Hello from assistant"));
        assert!(text.contains("Result text"));
    }

    #[test]
    fn test_should_return_empty_for_no_text_messages() {
        let messages: Vec<Message> = vec![];
        let text = extract_text_from_messages(&messages);
        assert!(text.is_empty());
    }

    #[test]
    fn test_should_accept_valid_slugs() {
        assert!(validate_feature_slug("add-auth").is_ok());
        assert!(validate_feature_slug("feature123").is_ok());
        assert!(validate_feature_slug("a").is_ok());
        assert!(validate_feature_slug("a-b-c").is_ok());
    }

    #[test]
    fn test_should_reject_empty_slug() {
        let err = validate_feature_slug("").unwrap_err().to_string();
        assert!(err.contains("empty"));
    }

    #[test]
    fn test_should_reject_slug_with_invalid_chars() {
        assert!(validate_feature_slug("Add-Auth").is_err());
        assert!(validate_feature_slug("add auth").is_err());
        assert!(validate_feature_slug("add/auth").is_err());
        assert!(validate_feature_slug("add_auth").is_err());
        assert!(validate_feature_slug("add.auth").is_err());
    }

    #[test]
    fn test_should_reject_slug_with_leading_trailing_hyphen() {
        assert!(validate_feature_slug("-add").is_err());
        assert!(validate_feature_slug("add-").is_err());
    }

    #[test]
    fn test_should_reject_slug_with_consecutive_hyphens() {
        assert!(validate_feature_slug("add--auth").is_err());
    }

    #[test]
    fn test_should_reject_slug_too_long() {
        let long_slug = "a".repeat(65);
        assert!(validate_feature_slug(&long_slug).is_err());
    }

    #[test]
    fn test_should_remove_existing_log_directory() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path();
        let logs_dir = root.join(".coda/my-feature/logs");
        fs::create_dir_all(&logs_dir).expect("mkdir");
        fs::write(logs_dir.join("run-20260101T000000.log"), "log data").expect("write");

        assert!(remove_feature_logs(root, "my-feature"));

        assert!(!logs_dir.exists());
        // The parent .coda/my-feature/ should still exist
        assert!(root.join(".coda/my-feature").exists());
    }

    #[test]
    fn test_should_ignore_missing_log_directory() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path();
        // No .coda directory at all — should not panic and should return true
        assert!(remove_feature_logs(root, "nonexistent"));
    }

    #[tokio::test]
    async fn test_should_clean_logs_for_multiple_features() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path();

        // Create log directories for two features
        let logs_a = root.join(".coda/feature-a/logs");
        let logs_b = root.join(".coda/feature-b/logs");
        fs::create_dir_all(&logs_a).expect("mkdir");
        fs::create_dir_all(&logs_b).expect("mkdir");
        fs::write(logs_a.join("run.log"), "data").expect("write");
        fs::write(logs_b.join("run.log"), "data").expect("write");

        // Feature without logs should be skipped
        fs::create_dir_all(root.join(".coda/feature-c")).expect("mkdir");

        let engine = make_engine(root).await;
        let cleaned = engine.clean_logs().expect("clean_logs");

        assert_eq!(cleaned, vec!["feature-a", "feature-b"]);
        assert!(!logs_a.exists());
        assert!(!logs_b.exists());
        // Parent dirs remain
        assert!(root.join(".coda/feature-a").exists());
        assert!(root.join(".coda/feature-b").exists());
    }

    #[tokio::test]
    async fn test_should_return_empty_when_no_coda_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let engine = make_engine(tmp.path()).await;

        let cleaned = engine.clean_logs().expect("clean_logs");
        assert!(cleaned.is_empty());
    }

    #[tokio::test]
    async fn test_should_return_empty_when_no_features_have_logs() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path();
        fs::create_dir_all(root.join(".coda/some-feature")).expect("mkdir");

        let engine = make_engine(root).await;
        let cleaned = engine.clean_logs().expect("clean_logs");
        assert!(cleaned.is_empty());
    }
}