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
//! Configuration loader with tier-based merging.
//!
//! Loads configuration from multiple tiers and merges them field-by-field.
use super::merge::deep_merge_all;
use super::types::{Config, Prompts};
use anyhow::Result;
use serde_json::Value;
use std::path::{Path, PathBuf};
use tracing::warn;
/// Configuration tier priority (lowest to highest).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConfigTier {
/// Embedded defaults (lowest priority)
Defaults = 0,
/// Project-level config ($CWD/task-graph/ or .task-graph/)
Project = 1,
/// User-level config (~/.task-graph/)
User = 2,
/// Environment variables (highest priority)
Environment = 3,
}
impl std::fmt::Display for ConfigTier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConfigTier::Defaults => write!(f, "defaults"),
ConfigTier::Project => write!(f, "project"),
ConfigTier::User => write!(f, "user"),
ConfigTier::Environment => write!(f, "environment"),
}
}
}
/// Paths for each configuration tier.
#[derive(Debug, Clone)]
pub struct ConfigPaths {
/// Embedded defaults directory (not a real path, but conceptual)
pub defaults_dir: Option<PathBuf>,
/// Install/package config directory (e.g., $CWD/config/ for built-in workflows)
pub install_dir: Option<PathBuf>,
/// Project-level config directory
pub project_dir: Option<PathBuf>,
/// Deprecated project-level config directory (.task-graph)
pub project_dir_deprecated: Option<PathBuf>,
/// User-level config directory
pub user_dir: Option<PathBuf>,
}
impl Default for ConfigPaths {
fn default() -> Self {
Self::discover()
}
}
/// Walk up from CWD looking for an existing directory with the given name.
/// Returns an absolute path if found, otherwise falls back to a relative path
/// (creating it in CWD on first use). This lets agents running in
/// subdirectories (e.g., git worktrees) share the project root's task-graph
/// directory. Works regardless of source control system.
fn find_project_dir(dir_name: &str) -> Option<PathBuf> {
let cwd = std::env::current_dir().ok()?;
find_project_dir_from(dir_name, &cwd, None)
}
/// Walk up from `start_dir` looking for a directory named `dir_name`.
/// Searches at most `max_depth` ancestor levels (None = unlimited).
/// Returns the first match found, or falls back to a relative `dir_name` path.
fn find_project_dir_from(
dir_name: &str,
start_dir: &Path,
max_depth: Option<usize>,
) -> Option<PathBuf> {
let mut search = start_dir;
let mut depth = 0;
loop {
if max_depth.is_some_and(|max| depth > max) {
break;
}
let candidate = search.join(dir_name);
if candidate.is_dir() {
if candidate != start_dir.join(dir_name) {
tracing::info!(
"Found '{}' at {} (resolved from {})",
dir_name,
candidate.display(),
start_dir.display()
);
}
return Some(candidate);
}
match search.parent() {
Some(parent) => {
search = parent;
depth += 1;
}
None => break,
}
}
// Not found anywhere — fall back to relative (will be created in start_dir)
Some(PathBuf::from(dir_name))
}
impl ConfigPaths {
/// Discover configuration paths from environment and defaults.
pub fn discover() -> Self {
// User dir: TASK_GRAPH_USER_DIR or ~/.task-graph
let user_dir = std::env::var("TASK_GRAPH_USER_DIR")
.ok()
.map(PathBuf::from)
.or_else(|| dirs::home_dir().map(|h| h.join(".task-graph")));
// Project dir: TASK_GRAPH_PROJECT_DIR or walk up from CWD to find task-graph/
let project_dir = std::env::var("TASK_GRAPH_PROJECT_DIR")
.ok()
.map(PathBuf::from)
.or_else(|| find_project_dir("task-graph"));
// Deprecated project dir: walk up for .task-graph/
let project_dir_deprecated = find_project_dir(".task-graph");
// Install dir: TASK_GRAPH_INSTALL_DIR or walk up for config/
let install_dir = std::env::var("TASK_GRAPH_INSTALL_DIR")
.ok()
.map(PathBuf::from)
.or_else(|| find_project_dir("config"));
Self {
defaults_dir: None, // Defaults are embedded, not on disk
install_dir,
project_dir,
project_dir_deprecated,
user_dir,
}
}
/// Create paths with explicit directories.
/// Does not include install_dir (use with_all_dirs for full control).
pub fn with_dirs(project_dir: Option<PathBuf>, user_dir: Option<PathBuf>) -> Self {
Self {
defaults_dir: None,
install_dir: None, // Not included for test isolation
project_dir,
project_dir_deprecated: Some(PathBuf::from(".task-graph")),
user_dir,
}
}
/// Create paths with all directories explicitly specified.
pub fn with_all_dirs(
install_dir: Option<PathBuf>,
project_dir: Option<PathBuf>,
user_dir: Option<PathBuf>,
) -> Self {
Self {
defaults_dir: None,
install_dir,
project_dir,
project_dir_deprecated: Some(PathBuf::from(".task-graph")),
user_dir,
}
}
/// Get the effective project directory (prefers new location, falls back to deprecated).
pub fn effective_project_dir(&self) -> Option<&Path> {
// Check new location first
if let Some(ref dir) = self.project_dir
&& dir.exists()
{
return Some(dir);
}
// Fall back to deprecated location
if let Some(ref dir) = self.project_dir_deprecated
&& dir.exists()
{
return Some(dir);
}
// If neither exists, prefer new location for creation
self.project_dir.as_deref()
}
/// Check if using deprecated project directory.
pub fn is_using_deprecated(&self) -> bool {
if let Some(ref new_dir) = self.project_dir
&& new_dir.exists()
{
return false;
}
if let Some(ref dep_dir) = self.project_dir_deprecated {
return dep_dir.exists();
}
false
}
}
/// Configuration loader that handles tier-based merging.
#[derive(Debug, Clone)]
pub struct ConfigLoader {
/// Paths for each tier
pub paths: ConfigPaths,
/// Loaded configuration
config: Config,
/// Path to the config file that was used (if any)
config_path: Option<PathBuf>,
/// Whether deprecated paths are in use
using_deprecated: bool,
}
impl ConfigLoader {
/// Load configuration from all tiers with proper merging.
pub fn load() -> Result<Self> {
Self::load_with_paths(ConfigPaths::discover())
}
/// Load configuration with explicit paths.
pub fn load_with_paths(paths: ConfigPaths) -> Result<Self> {
let using_deprecated = paths.is_using_deprecated();
if using_deprecated {
warn!(
"Using deprecated config directory '.task-graph/'. \
Run 'task-graph migrate' to move to 'task-graph/'."
);
}
// Check for explicit config path override
if let Ok(explicit_path) = std::env::var("TASK_GRAPH_CONFIG_PATH") {
let path = PathBuf::from(&explicit_path);
let config = Config::load(&path)?;
return Ok(Self {
paths,
config,
config_path: Some(path),
using_deprecated,
});
}
// Collect configs from each tier
let mut configs: Vec<Value> = Vec::new();
// Tier 1: Defaults (embedded)
let default_config = Config::default();
if let Ok(default_json) = serde_json::to_value(&default_config) {
configs.push(default_json);
}
// Tier 2: Project config
let mut project_config_path = None;
if let Some(project_dir) = paths.effective_project_dir() {
let config_file = project_dir.join("config.yaml");
if config_file.exists()
&& let Ok(content) = std::fs::read_to_string(&config_file)
&& let Ok(yaml_value) = serde_yaml::from_str::<Value>(&content)
{
configs.push(yaml_value);
project_config_path = Some(config_file);
}
}
// Tier 3: User config
if let Some(ref user_dir) = paths.user_dir {
let config_file = user_dir.join("config.yaml");
if config_file.exists()
&& let Ok(content) = std::fs::read_to_string(&config_file)
&& let Ok(yaml_value) = serde_yaml::from_str::<Value>(&content)
{
configs.push(yaml_value);
}
}
// Merge all configs
let merged = deep_merge_all(configs);
let mut config: Config = serde_json::from_value(merged)?;
// Tier 4: Environment variable overrides
Self::apply_env_overrides(&mut config);
// Resolve relative server paths against the discovered project root.
// This ensures agents running in subdirectories (e.g., git worktrees)
// share the project's database instead of creating a new one.
if let Some(project_dir) = paths.effective_project_dir()
&& project_dir.is_absolute()
&& let Some(project_root) = project_dir.parent()
{
Self::resolve_server_paths(&mut config, project_root);
}
Ok(Self {
paths,
config,
config_path: project_config_path,
using_deprecated,
})
}
/// Apply environment variable overrides to config.
/// If server paths (db_path, media_dir, etc.) are relative, resolve them
/// against the given project root so agents in subdirectories use the same DB.
fn resolve_server_paths(config: &mut Config, project_root: &Path) {
let resolve = |p: &mut PathBuf| {
if p.is_relative() {
*p = project_root.join(&*p);
}
};
resolve(&mut config.server.db_path);
resolve(&mut config.server.media_dir);
resolve(&mut config.server.log_dir);
resolve(&mut config.server.skills_dir);
}
fn apply_env_overrides(config: &mut Config) {
if let Ok(db_path) = std::env::var("TASK_GRAPH_DB_PATH") {
config.server.db_path = PathBuf::from(db_path);
}
if let Ok(media_dir) = std::env::var("TASK_GRAPH_MEDIA_DIR") {
config.server.media_dir = PathBuf::from(media_dir);
}
if let Ok(log_dir) = std::env::var("TASK_GRAPH_LOG_DIR") {
config.server.log_dir = PathBuf::from(log_dir);
}
if let Ok(skills_dir) = std::env::var("TASK_GRAPH_SKILLS_DIR") {
config.server.skills_dir = PathBuf::from(skills_dir);
}
}
/// Load prompts configuration with tier merging.
pub fn load_prompts(&self) -> Prompts {
let mut prompts_configs: Vec<Value> = Vec::new();
// Tier 1: Defaults (empty)
if let Ok(default_json) = serde_json::to_value(Prompts::default()) {
prompts_configs.push(default_json);
}
// Tier 2: Project prompts
if let Some(project_dir) = self.paths.effective_project_dir() {
let prompts_file = project_dir.join("prompts.yaml");
if prompts_file.exists()
&& let Ok(content) = std::fs::read_to_string(&prompts_file)
&& let Ok(yaml_value) = serde_yaml::from_str::<Value>(&content)
{
prompts_configs.push(yaml_value);
}
}
// Tier 3: User prompts
if let Some(ref user_dir) = self.paths.user_dir {
let prompts_file = user_dir.join("prompts.yaml");
if prompts_file.exists()
&& let Ok(content) = std::fs::read_to_string(&prompts_file)
&& let Ok(yaml_value) = serde_yaml::from_str::<Value>(&content)
{
prompts_configs.push(yaml_value);
}
}
// Merge and deserialize
let merged = deep_merge_all(prompts_configs);
serde_json::from_value(merged).unwrap_or_default()
}
/// Load workflows configuration with tier merging.
///
/// Loads from embedded defaults, then project workflows.yaml, then user workflows.yaml.
/// Later tiers override earlier ones (objects are deep-merged, prompts are replaced).
pub fn load_workflows(&self) -> super::workflows::WorkflowsConfig {
let mut workflows_configs: Vec<Value> = Vec::new();
// Tier 1: Defaults (embedded)
if let Ok(default_json) = serde_json::to_value(super::workflows::WorkflowsConfig::default())
{
workflows_configs.push(default_json);
}
// Tier 2: Project workflows
if let Some(project_dir) = self.paths.effective_project_dir() {
let workflows_file = project_dir.join("workflows.yaml");
if workflows_file.exists()
&& let Ok(content) = std::fs::read_to_string(&workflows_file)
&& let Ok(yaml_value) = serde_yaml::from_str::<Value>(&content)
{
workflows_configs.push(yaml_value);
}
}
// Tier 3: User workflows
if let Some(ref user_dir) = self.paths.user_dir {
let workflows_file = user_dir.join("workflows.yaml");
if workflows_file.exists()
&& let Ok(content) = std::fs::read_to_string(&workflows_file)
&& let Ok(yaml_value) = serde_yaml::from_str::<Value>(&content)
{
workflows_configs.push(yaml_value);
}
}
// Merge and deserialize
let merged = deep_merge_all(workflows_configs);
serde_json::from_value(merged).unwrap_or_default()
}
/// Get the loaded configuration.
pub fn config(&self) -> &Config {
&self.config
}
/// Get mutable access to the configuration.
pub fn config_mut(&mut self) -> &mut Config {
&mut self.config
}
/// Consume the loader and return the configuration.
pub fn into_config(self) -> Config {
self.config
}
/// Get the config file path that was used.
pub fn config_path(&self) -> Option<&Path> {
self.config_path.as_deref()
}
/// Check if using deprecated paths.
pub fn is_using_deprecated(&self) -> bool {
self.using_deprecated
}
/// Get the effective project directory.
pub fn project_dir(&self) -> Option<&Path> {
self.paths.effective_project_dir()
}
/// Get the user directory.
pub fn user_dir(&self) -> Option<&Path> {
self.paths.user_dir.as_deref()
}
/// Get the skills directory, checking all tiers.
pub fn skills_dir(&self) -> PathBuf {
// Environment override takes precedence
if let Ok(skills_dir) = std::env::var("TASK_GRAPH_SKILLS_DIR") {
return PathBuf::from(skills_dir);
}
// Check project dir
if let Some(project_dir) = self.paths.effective_project_dir() {
let skills_dir = project_dir.join("skills");
if skills_dir.exists() {
return skills_dir;
}
}
// Use config default
self.config.server.skills_dir.clone()
}
/// Load a named workflow file (workflow-{name}.yaml).
///
/// Searches in order: user directory, project directory, install directory, embedded.
/// User overrides project, project overrides install, install overrides embedded.
/// Returns the merged workflow config (defaults + named workflow).
pub fn load_workflow_by_name(&self, name: &str) -> Result<super::workflows::WorkflowsConfig> {
let filename = format!("workflow-{}.yaml", name);
// Check user directory first (highest priority)
if let Some(ref user_dir) = self.paths.user_dir {
let workflow_file = user_dir.join(&filename);
if workflow_file.exists() {
return self.load_workflow_from_path(&workflow_file);
}
}
// Check project directory second
if let Some(project_dir) = self.paths.effective_project_dir() {
let workflow_file = project_dir.join(&filename);
if workflow_file.exists() {
return self.load_workflow_from_path(&workflow_file);
}
}
// Check install directory (built-in defaults on disk)
if let Some(ref install_dir) = self.paths.install_dir {
let workflow_file = install_dir.join(&filename);
if workflow_file.exists() {
return self.load_workflow_from_path(&workflow_file);
}
}
// Fall back to embedded workflows (always available)
if let Some(content) = super::embedded::workflows::get(name) {
return self.load_workflow_from_content(content, name);
}
Err(anyhow::anyhow!(
"Workflow '{}' not found. Searched for '{}' in user, project, install directories, and embedded defaults.",
name,
filename
))
}
/// Load workflow from a specific path, merging with defaults.
fn load_workflow_from_path(&self, path: &Path) -> Result<super::workflows::WorkflowsConfig> {
let content = std::fs::read_to_string(path)?;
let yaml_value: Value = serde_yaml::from_str(&content)?;
// Start with defaults and merge the named workflow on top
let mut configs: Vec<Value> = Vec::new();
// Tier 1: Defaults
if let Ok(default_json) = serde_json::to_value(super::workflows::WorkflowsConfig::default())
{
configs.push(default_json);
}
// Tier 2: The named workflow file
configs.push(yaml_value);
let merged = deep_merge_all(configs);
let mut workflow: super::workflows::WorkflowsConfig = serde_json::from_value(merged)?;
// Populate source_file (not serialized, so must be set after deserialization)
workflow.source_file = Some(path.to_path_buf());
Ok(workflow)
}
/// Load workflow from embedded content string, merging with defaults.
fn load_workflow_from_content(
&self,
content: &str,
name: &str,
) -> Result<super::workflows::WorkflowsConfig> {
let yaml_value: Value = serde_yaml::from_str(content)?;
// Start with defaults and merge the named workflow on top
let mut configs: Vec<Value> = Vec::new();
// Tier 1: Defaults
if let Ok(default_json) = serde_json::to_value(super::workflows::WorkflowsConfig::default())
{
configs.push(default_json);
}
// Tier 2: The embedded workflow content
configs.push(yaml_value);
let merged = deep_merge_all(configs);
let mut workflow: super::workflows::WorkflowsConfig = serde_json::from_value(merged)?;
// Mark as embedded (no file path)
workflow.source_file = None;
// Store embedded source indicator
workflow.description = workflow
.description
.or_else(|| Some(format!("Built-in workflow: {}", name)));
Ok(workflow)
}
/// List available named workflows.
///
/// Returns workflow names (e.g., "solo", "swarm") found in user, project, install directories,
/// and embedded defaults. Embedded workflows are always available as fallbacks.
pub fn list_workflows(&self) -> Vec<String> {
let mut workflows = Vec::new();
// Check user directory
if let Some(ref user_dir) = self.paths.user_dir
&& let Ok(entries) = std::fs::read_dir(user_dir)
{
for entry in entries.filter_map(|e| e.ok()) {
if let Some(name) = Self::extract_workflow_name(&entry.path())
&& !workflows.contains(&name)
{
workflows.push(name);
}
}
}
// Check project directory
if let Some(project_dir) = self.paths.effective_project_dir()
&& let Ok(entries) = std::fs::read_dir(project_dir)
{
for entry in entries.filter_map(|e| e.ok()) {
if let Some(name) = Self::extract_workflow_name(&entry.path())
&& !workflows.contains(&name)
{
workflows.push(name);
}
}
}
// Check install directory (built-in workflows on disk)
if let Some(ref install_dir) = self.paths.install_dir
&& let Ok(entries) = std::fs::read_dir(install_dir)
{
for entry in entries.filter_map(|e| e.ok()) {
if let Some(name) = Self::extract_workflow_name(&entry.path())
&& !workflows.contains(&name)
{
workflows.push(name);
}
}
}
// Include embedded workflows (always available as fallbacks)
for name in super::embedded::workflows::names() {
if !workflows.contains(&name.to_string()) {
workflows.push(name.to_string());
}
}
workflows.sort();
workflows
}
/// Extract workflow name from a path like "workflow-swarm.yaml" -> "swarm".
fn extract_workflow_name(path: &Path) -> Option<String> {
let filename = path.file_name()?.to_str()?;
if filename.starts_with("workflow-") && filename.ends_with(".yaml") {
let name = filename.strip_prefix("workflow-")?.strip_suffix(".yaml")?;
if !name.is_empty() {
return Some(name.to_string());
}
}
None
}
/// List available overlay files (overlay-*.yaml).
///
/// Returns overlay names (e.g., "git", "troubleshooting") found in user, project, install directories,
/// and embedded defaults. Embedded overlays are always available as fallbacks.
pub fn list_overlays(&self) -> Vec<String> {
let mut overlays = Vec::new();
// Check user directory
if let Some(ref user_dir) = self.paths.user_dir
&& let Ok(entries) = std::fs::read_dir(user_dir)
{
for entry in entries.filter_map(|e| e.ok()) {
if let Some(name) = Self::extract_overlay_name(&entry.path())
&& !overlays.contains(&name)
{
overlays.push(name);
}
}
}
// Check project directory
if let Some(project_dir) = self.paths.effective_project_dir()
&& let Ok(entries) = std::fs::read_dir(project_dir)
{
for entry in entries.filter_map(|e| e.ok()) {
if let Some(name) = Self::extract_overlay_name(&entry.path())
&& !overlays.contains(&name)
{
overlays.push(name);
}
}
}
// Check install directory (built-in overlays on disk)
if let Some(ref install_dir) = self.paths.install_dir
&& let Ok(entries) = std::fs::read_dir(install_dir)
{
for entry in entries.filter_map(|e| e.ok()) {
if let Some(name) = Self::extract_overlay_name(&entry.path())
&& !overlays.contains(&name)
{
overlays.push(name);
}
}
}
// Include embedded overlays (always available as fallbacks)
for name in super::embedded::overlays::names() {
if !overlays.contains(&name.to_string()) {
overlays.push(name.to_string());
}
}
overlays.sort();
overlays
}
/// Load an overlay by name (overlay-{name}.yaml).
///
/// Unlike `load_workflow_by_name`, overlays are loaded as raw deltas WITHOUT
/// merging with defaults. This prevents double-appending prompts when
/// the overlay is later applied via `apply_overlay()`.
///
/// Searches in order: user directory, project directory, install directory, embedded.
pub fn load_overlay_by_name(&self, name: &str) -> Result<super::workflows::WorkflowsConfig> {
let filename = format!("overlay-{}.yaml", name);
// Check user directory first (highest priority)
if let Some(ref user_dir) = self.paths.user_dir {
let overlay_file = user_dir.join(&filename);
if overlay_file.exists() {
return self.load_overlay_from_path(&overlay_file);
}
}
// Check project directory second
if let Some(project_dir) = self.paths.effective_project_dir() {
let overlay_file = project_dir.join(&filename);
if overlay_file.exists() {
return self.load_overlay_from_path(&overlay_file);
}
}
// Check install directory (built-in defaults on disk)
if let Some(ref install_dir) = self.paths.install_dir {
let overlay_file = install_dir.join(&filename);
if overlay_file.exists() {
return self.load_overlay_from_path(&overlay_file);
}
}
// Fall back to embedded overlays (always available)
if let Some(content) = super::embedded::overlays::get(name) {
return self.load_overlay_from_content(content);
}
Err(anyhow::anyhow!(
"Overlay '{}' not found. Searched for '{}' in user, project, install directories, and embedded defaults.",
name,
filename
))
}
/// Load an overlay from a specific path WITHOUT merging with defaults.
/// This is the critical difference from `load_workflow_from_path`.
fn load_overlay_from_path(&self, path: &Path) -> Result<super::workflows::WorkflowsConfig> {
let content = std::fs::read_to_string(path)?;
let mut overlay: super::workflows::WorkflowsConfig = serde_yaml::from_str(&content)?;
overlay.source_file = Some(path.to_path_buf());
Ok(overlay)
}
/// Load an overlay from embedded content WITHOUT merging with defaults.
fn load_overlay_from_content(
&self,
content: &str,
) -> Result<super::workflows::WorkflowsConfig> {
let overlay: super::workflows::WorkflowsConfig = serde_yaml::from_str(content)?;
// No source_file for embedded content
Ok(overlay)
}
/// Extract overlay name from a path like "overlay-git.yaml" -> "git".
fn extract_overlay_name(path: &Path) -> Option<String> {
let filename = path.file_name()?.to_str()?;
if filename.starts_with("overlay-") && filename.ends_with(".yaml") {
let name = filename.strip_prefix("overlay-")?.strip_suffix(".yaml")?;
if !name.is_empty() {
return Some(name.to_string());
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_config_paths_discover() {
let paths = ConfigPaths::discover();
assert!(paths.project_dir.is_some());
// user_dir may or may not exist depending on environment
}
#[test]
fn test_load_defaults_only() {
// Create empty temp dirs so no config files are found
let temp = TempDir::new().unwrap();
let paths = ConfigPaths::with_dirs(
Some(temp.path().join("project")),
Some(temp.path().join("user")),
);
let loader = ConfigLoader::load_with_paths(paths).unwrap();
let config = loader.config();
// Should have default values
assert_eq!(config.server.claim_limit, 5);
assert_eq!(config.server.stale_timeout_seconds, 900);
}
#[test]
fn test_project_config_overrides_defaults() {
let temp = TempDir::new().unwrap();
let project_dir = temp.path().join("task-graph");
std::fs::create_dir_all(&project_dir).unwrap();
// Create project config that overrides claim_limit
let config_content = r#"
server:
claim_limit: 10
"#;
std::fs::write(project_dir.join("config.yaml"), config_content).unwrap();
let paths = ConfigPaths::with_dirs(Some(project_dir), Some(temp.path().join("user")));
let loader = ConfigLoader::load_with_paths(paths).unwrap();
let config = loader.config();
// claim_limit should be overridden
assert_eq!(config.server.claim_limit, 10);
// stale_timeout_seconds should be default
assert_eq!(config.server.stale_timeout_seconds, 900);
}
#[test]
fn test_user_config_overrides_project() {
let temp = TempDir::new().unwrap();
let project_dir = temp.path().join("task-graph");
let user_dir = temp.path().join("user");
std::fs::create_dir_all(&project_dir).unwrap();
std::fs::create_dir_all(&user_dir).unwrap();
// Project config
let project_config = r#"
server:
claim_limit: 10
stale_timeout_seconds: 600
"#;
std::fs::write(project_dir.join("config.yaml"), project_config).unwrap();
// User config overrides claim_limit
let user_config = r#"
server:
claim_limit: 20
"#;
std::fs::write(user_dir.join("config.yaml"), user_config).unwrap();
let paths = ConfigPaths::with_dirs(Some(project_dir), Some(user_dir));
let loader = ConfigLoader::load_with_paths(paths).unwrap();
let config = loader.config();
// claim_limit should be from user
assert_eq!(config.server.claim_limit, 20);
// stale_timeout_seconds should be from project
assert_eq!(config.server.stale_timeout_seconds, 600);
}
/// Verifies that `find_project_dir_from` walks up from a subdirectory to find
/// a `task-graph/` directory in an ancestor. This is the core mechanism that
/// enables agents running in git worktrees or project subdirectories to share
/// the parent project's database and configuration.
#[test]
fn find_project_dir_from_subdirectory() {
let temp = TempDir::new().unwrap();
let root = temp.path();
// Create project structure:
// root/
// task-graph/ ← the project config dir
// src/
// deep/
// nested/ ← agent runs from here
let project_dir = root.join("task-graph");
let nested_dir = root.join("src").join("deep").join("nested");
std::fs::create_dir_all(&project_dir).unwrap();
std::fs::create_dir_all(&nested_dir).unwrap();
// Starting from nested subdir (3 levels deep), should find task-graph/ in root
let found = find_project_dir_from("task-graph", &nested_dir, Some(5));
assert_eq!(found, Some(project_dir));
}
/// Verifies that `find_project_dir_from` finds the nearest ancestor's directory,
/// not a more distant one. This matters for nested project structures.
#[test]
fn find_project_dir_from_finds_nearest_ancestor() {
let temp = TempDir::new().unwrap();
let root = temp.path();
// Create nested project structure:
// root/
// task-graph/ ← outer (should NOT be found)
// subproject/
// task-graph/ ← inner (should be found)
// src/ ← agent runs from here
let outer = root.join("task-graph");
let inner_project = root.join("subproject");
let inner = inner_project.join("task-graph");
let working_dir = inner_project.join("src");
std::fs::create_dir_all(&outer).unwrap();
std::fs::create_dir_all(&inner).unwrap();
std::fs::create_dir_all(&working_dir).unwrap();
let found = find_project_dir_from("task-graph", &working_dir, Some(3));
assert_eq!(found, Some(inner));
}
/// Verifies that when max_depth is too shallow to reach the target,
/// the function falls back to a relative path.
#[test]
fn find_project_dir_from_respects_max_depth() {
let temp = TempDir::new().unwrap();
let root = temp.path();
// Create: root/task-graph/ and root/a/b/c/ (3 levels deep)
let project_dir = root.join("task-graph");
let deep_dir = root.join("a").join("b").join("c");
std::fs::create_dir_all(&project_dir).unwrap();
std::fs::create_dir_all(&deep_dir).unwrap();
// Depth 2 can't reach root from a/b/c (needs 3 hops)
let not_found = find_project_dir_from("task-graph", &deep_dir, Some(2));
assert_eq!(not_found, Some(PathBuf::from("task-graph")));
// Depth 3 can reach it
let found = find_project_dir_from("task-graph", &deep_dir, Some(3));
assert_eq!(found, Some(project_dir));
}
/// Verifies that when no ancestor has the target directory, the function
/// falls back to a relative path (for creation in the starting directory).
#[test]
fn find_project_dir_from_falls_back_when_not_found() {
let temp = TempDir::new().unwrap();
let empty_dir = temp.path().join("empty");
std::fs::create_dir_all(&empty_dir).unwrap();
// max_depth=0 means only check start_dir itself
let found = find_project_dir_from("task-graph", &empty_dir, Some(0));
assert_eq!(found, Some(PathBuf::from("task-graph")));
}
}