1use anyhow::{Context, Result};
2use schemars::JsonSchema;
3use serde::Deserialize;
4use std::path::{Path, PathBuf};
5
6#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)]
8#[serde(rename_all = "lowercase")]
9pub enum SectionType {
10 Free,
11 Tasks,
12 Qa,
13}
14
15#[derive(Debug, Clone, Deserialize, JsonSchema)]
17pub struct TicketSection {
18 pub name: String,
20 #[serde(rename = "type")]
22 pub type_: SectionType,
23 #[serde(default)]
25 pub required: bool,
26 #[serde(default)]
28 pub placeholder: Option<String>,
29}
30
31#[derive(Debug, Deserialize, Default, JsonSchema)]
34pub struct TicketConfig {
35 #[serde(default)]
36 pub sections: Vec<TicketSection>,
37}
38
39#[derive(Debug, Clone, PartialEq, Deserialize, Default, JsonSchema)]
44#[serde(rename_all = "lowercase")]
45pub enum CompletionStrategy {
46 Pr,
47 Merge,
48 Pull,
49 #[serde(rename = "pr_or_epic_merge")]
50 PrOrEpicMerge,
51 #[default]
52 None,
53}
54
55#[derive(Debug, Clone, Deserialize, JsonSchema)]
56pub struct IsolationConfig {
57 #[serde(default = "default_read_allow")]
61 pub read_allow: Vec<String>,
62 #[serde(default)]
65 pub enforce_worktree_isolation: bool,
66}
67
68fn default_read_allow() -> Vec<String> {
69 vec!["/etc/resolv.conf".to_string(), "~/.gitconfig".to_string()]
70}
71
72impl Default for IsolationConfig {
73 fn default() -> Self {
74 Self {
75 read_allow: default_read_allow(),
76 enforce_worktree_isolation: false,
77 }
78 }
79}
80
81#[derive(Debug, Clone, Deserialize, Default, JsonSchema)]
82pub struct LoggingConfig {
83 #[serde(default)]
85 pub enabled: bool,
86 pub file: Option<std::path::PathBuf>,
88}
89
90#[derive(Debug, Clone, Deserialize, Default, JsonSchema)]
91#[serde(default)]
92pub struct GitHostConfig {
93 pub provider: Option<String>,
95 pub repo: Option<String>,
97 pub token_env: Option<String>,
99}
100
101#[derive(Debug, Clone, Deserialize, JsonSchema)]
102pub struct WorkersConfig {
103 pub container: Option<String>,
105 #[serde(default)]
107 pub keychain: std::collections::HashMap<String, String>,
108 pub command: Option<String>,
110 pub args: Option<Vec<String>>,
112 #[serde(default)]
114 pub model: Option<String>,
115 #[serde(default)]
117 pub env: std::collections::HashMap<String, String>,
118 pub agent: Option<String>,
120 #[serde(default)]
122 pub options: std::collections::HashMap<String, String>,
123 pub instructions: Option<String>,
125}
126
127impl Default for WorkersConfig {
128 fn default() -> Self {
129 Self {
130 container: None,
131 keychain: std::collections::HashMap::new(),
132 command: None,
133 args: None,
134 model: None,
135 env: std::collections::HashMap::new(),
136 agent: None,
137 options: std::collections::HashMap::new(),
138 instructions: None,
139 }
140 }
141}
142
143#[derive(Debug, Clone, Deserialize, Default, JsonSchema)]
144pub struct WorkerProfileConfig {
145 pub command: Option<String>,
147 pub args: Option<Vec<String>>,
149 pub model: Option<String>,
151 #[serde(default)]
153 pub env: std::collections::HashMap<String, String>,
154 pub container: Option<String>,
156 pub instructions: Option<String>,
158 pub role_prefix: Option<String>,
160 pub agent: Option<String>,
162 #[serde(default)]
164 pub options: std::collections::HashMap<String, String>,
165 pub role: Option<String>,
167}
168
169#[derive(Debug, Deserialize, Default, JsonSchema)]
170pub struct WorkConfig {
171 #[serde(default)]
173 pub epic: Option<String>,
174}
175
176#[derive(Debug, Clone, Deserialize, JsonSchema)]
177pub struct ServerConfig {
178 #[serde(default = "default_server_origin")]
180 pub origin: String,
181 #[serde(default = "default_server_url")]
183 pub url: String,
184}
185
186fn default_server_origin() -> String {
187 "http://localhost:3000".to_string()
188}
189
190fn default_server_url() -> String {
191 "http://127.0.0.1:3000".to_string()
192}
193
194impl Default for ServerConfig {
195 fn default() -> Self {
196 Self { origin: default_server_origin(), url: default_server_url() }
197 }
198}
199
200#[derive(Debug, Deserialize, JsonSchema)]
201pub struct ContextConfig {
202 #[serde(default = "default_epic_sibling_cap")]
204 pub epic_sibling_cap: usize,
205 #[serde(default = "default_epic_byte_cap")]
207 pub epic_byte_cap: usize,
208}
209
210fn default_epic_sibling_cap() -> usize { 20 }
211fn default_epic_byte_cap() -> usize { 8192 }
212
213impl Default for ContextConfig {
214 fn default() -> Self {
215 Self {
216 epic_sibling_cap: default_epic_sibling_cap(),
217 epic_byte_cap: default_epic_byte_cap(),
218 }
219 }
220}
221
222#[derive(Debug, Deserialize, JsonSchema)]
223pub struct Config {
224 pub project: ProjectConfig,
225 #[serde(default)]
226 pub ticket: TicketConfig,
227 #[serde(default)]
228 pub tickets: TicketsConfig,
229 #[serde(default)]
230 pub workflow: WorkflowConfig,
231 #[serde(default)]
232 pub agents: AgentsConfig,
233 #[serde(default)]
234 pub worktrees: WorktreesConfig,
235 #[serde(default)]
236 pub sync: SyncConfig,
237 #[serde(default)]
238 pub logging: LoggingConfig,
239 #[serde(default)]
240 pub workers: WorkersConfig,
241 #[serde(default)]
242 pub work: WorkConfig,
243 #[serde(default)]
244 pub server: ServerConfig,
245 #[serde(default)]
246 pub git_host: GitHostConfig,
247 #[serde(default)]
248 pub worker_profiles: std::collections::HashMap<String, WorkerProfileConfig>,
249 #[serde(default)]
250 pub context: ContextConfig,
251 #[serde(default)]
252 pub isolation: IsolationConfig,
253 #[serde(skip)]
255 pub load_warnings: Vec<String>,
256}
257
258#[derive(Deserialize)]
259pub(crate) struct WorkflowFile {
260 pub(crate) workflow: WorkflowConfig,
261}
262
263#[derive(Deserialize)]
264pub(crate) struct TicketFile {
265 pub(crate) ticket: TicketConfig,
266}
267
268#[derive(Debug, Clone, Deserialize, JsonSchema)]
269pub struct SyncConfig {
270 #[serde(default = "default_true")]
272 pub aggressive: bool,
273}
274
275impl Default for SyncConfig {
276 fn default() -> Self {
277 Self { aggressive: true }
278 }
279}
280
281#[derive(Debug, Deserialize, JsonSchema)]
282pub struct ProjectConfig {
283 pub name: String,
285 #[serde(default)]
287 pub description: String,
288 #[serde(default = "default_branch_main")]
290 pub default_branch: String,
291 #[serde(default)]
293 pub collaborators: Vec<String>,
294}
295
296fn default_branch_main() -> String {
297 "main".to_string()
298}
299
300#[derive(Debug, Deserialize, JsonSchema)]
301pub struct TicketsConfig {
302 pub dir: PathBuf,
304 #[serde(default)]
305 pub sections: Vec<String>,
306 #[serde(default)]
308 pub archive_dir: Option<PathBuf>,
309}
310
311impl Default for TicketsConfig {
312 fn default() -> Self {
313 Self {
314 dir: PathBuf::from("tickets"),
315 sections: Vec::new(),
316 archive_dir: None,
317 }
318 }
319}
320
321#[derive(Debug, Deserialize, Default, JsonSchema)]
323pub struct WorkflowConfig {
324 #[serde(default)]
326 pub states: Vec<StateConfig>,
327 #[serde(default)]
329 pub prioritization: PrioritizationConfig,
330}
331
332#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)]
334#[serde(untagged)]
335pub enum SatisfiesDeps {
336 Bool(bool),
338 Tag(String),
340}
341
342impl Default for SatisfiesDeps {
343 fn default() -> Self { SatisfiesDeps::Bool(false) }
344}
345
346#[derive(Debug, Clone, Deserialize, JsonSchema)]
348pub struct StateConfig {
349 pub id: String,
351 pub label: String,
353 #[serde(default)]
355 pub description: String,
356 #[serde(default)]
358 pub terminal: bool,
359 #[serde(default)]
361 pub worker_end: bool,
362 #[serde(default)]
364 pub satisfies_deps: SatisfiesDeps,
365 #[serde(default)]
367 pub dep_requires: Option<String>,
368 #[serde(default)]
370 pub transitions: Vec<TransitionConfig>,
371 #[serde(default)]
373 pub actionable: Vec<String>,
374 #[serde(default)]
376 pub instructions: Option<String>,
377}
378
379#[derive(Debug, Clone, Deserialize, JsonSchema)]
381pub struct TransitionConfig {
382 pub to: String,
384 #[serde(default)]
386 pub trigger: String,
387 #[serde(default)]
389 pub label: String,
390 #[serde(default)]
392 pub hint: String,
393 #[serde(default)]
395 pub completion: CompletionStrategy,
396 #[serde(default)]
398 pub focus_section: Option<String>,
399 #[serde(default)]
401 pub context_section: Option<String>,
402 #[serde(default)]
404 pub warning: Option<String>,
405 #[serde(default)]
407 pub profile: Option<String>,
408 #[serde(default)]
409 pub on_failure: Option<String>,
410 #[serde(default)]
415 pub outcome: Option<String>,
416}
417
418#[derive(Debug, Deserialize, Default, JsonSchema)]
420pub struct PrioritizationConfig {
421 #[serde(default = "default_priority_weight")]
423 pub priority_weight: f64,
424 #[serde(default = "default_effort_weight")]
426 pub effort_weight: f64,
427 #[serde(default = "default_risk_weight")]
429 pub risk_weight: f64,
430}
431
432fn default_priority_weight() -> f64 { 10.0 }
433fn default_effort_weight() -> f64 { -2.0 }
434fn default_risk_weight() -> f64 { -1.0 }
435
436pub fn resolve_outcome<'a>(
443 transition: &'a TransitionConfig,
444 target_state: &StateConfig,
445) -> &'a str {
446 if let Some(ref o) = transition.outcome {
447 return o.as_str();
448 }
449 if transition.completion != CompletionStrategy::None {
450 return "success";
451 }
452 if target_state.terminal {
453 return "cancelled";
454 }
455 "needs_input"
456}
457
458#[derive(Debug, Deserialize, JsonSchema)]
459pub struct AgentsConfig {
460 #[serde(default = "default_max_concurrent")]
462 pub max_concurrent: usize,
463 #[serde(default = "default_max_workers_per_epic")]
465 pub max_workers_per_epic: usize,
466 #[serde(default = "default_max_workers_on_default")]
468 pub max_workers_on_default: usize,
469 #[serde(default)]
471 pub instructions: Option<PathBuf>,
472 #[serde(default = "default_true")]
474 pub side_tickets: bool,
475 #[serde(default)]
477 pub skip_permissions: bool,
478}
479
480fn default_max_concurrent() -> usize { 3 }
481fn default_max_workers_per_epic() -> usize { 1 }
482fn default_max_workers_on_default() -> usize { 1 }
483fn default_true() -> bool { true }
484
485#[derive(Debug, Deserialize, JsonSchema)]
486pub struct WorktreesConfig {
487 pub dir: PathBuf,
489 #[serde(default)]
491 pub agent_dirs: Vec<String>,
492}
493
494impl Default for WorktreesConfig {
495 fn default() -> Self {
496 Self {
497 dir: PathBuf::from("../worktrees"),
498 agent_dirs: Vec::new(),
499 }
500 }
501}
502
503impl Default for AgentsConfig {
504 fn default() -> Self {
505 Self {
506 max_concurrent: default_max_concurrent(),
507 max_workers_per_epic: default_max_workers_per_epic(),
508 max_workers_on_default: default_max_workers_on_default(),
509 instructions: None,
510 side_tickets: true,
511 skip_permissions: false,
512 }
513 }
514}
515
516#[derive(Debug, Deserialize, Default)]
517pub struct LocalConfig {
518 #[serde(default)]
519 pub workers: LocalWorkersOverride,
520 #[serde(default)]
521 pub username: Option<String>,
522 #[serde(default)]
523 pub github_token: Option<String>,
524}
525
526#[derive(Debug, Deserialize, Default)]
527pub struct LocalWorkersOverride {
528 pub command: Option<String>,
529 pub args: Option<Vec<String>>,
530 pub model: Option<String>,
531 #[serde(default)]
532 pub env: std::collections::HashMap<String, String>,
533}
534
535impl LocalConfig {
536 pub fn load(root: &Path) -> Self {
537 let local_path = root.join(".apm").join("local.toml");
538 std::fs::read_to_string(&local_path)
539 .ok()
540 .and_then(|s| toml::from_str(&s).ok())
541 .unwrap_or_default()
542 }
543}
544
545fn effective_github_token(local: &LocalConfig, git_host: &GitHostConfig) -> Option<String> {
546 if let Some(ref t) = local.github_token {
547 if !t.is_empty() {
548 return Some(t.clone());
549 }
550 }
551 if let Some(ref env_var) = git_host.token_env {
552 if let Ok(t) = std::env::var(env_var) {
553 if !t.is_empty() {
554 return Some(t);
555 }
556 }
557 }
558 std::env::var("GITHUB_TOKEN").ok().filter(|t| !t.is_empty())
559}
560
561pub fn resolve_identity(repo_root: &Path) -> String {
562 let local_path = repo_root.join(".apm").join("local.toml");
563 let local: LocalConfig = std::fs::read_to_string(&local_path)
564 .ok()
565 .and_then(|s| toml::from_str(&s).ok())
566 .unwrap_or_default();
567
568 let config_path = repo_root.join(".apm").join("config.toml");
569 let config: Option<Config> = std::fs::read_to_string(&config_path)
570 .ok()
571 .and_then(|s| toml::from_str(&s).ok());
572
573 let git_host = config.as_ref().map(|c| &c.git_host).cloned().unwrap_or_default();
574 if git_host.provider.is_some() {
575 if git_host.provider.as_deref() == Some("github") {
577 if let Some(login) = crate::github::gh_username() {
578 return login;
579 }
580 if let Some(token) = effective_github_token(&local, &git_host) {
581 if let Ok(login) = crate::github::fetch_authenticated_user(&token) {
582 return login;
583 }
584 }
585 }
586 return "unassigned".to_string();
587 }
588
589 if let Some(ref u) = local.username {
591 if !u.is_empty() {
592 return u.clone();
593 }
594 }
595 "unassigned".to_string()
596}
597
598pub fn resolve_caller_name() -> String {
608 std::env::var("APM_AGENT_NAME")
609 .or_else(|_| std::env::var("USER"))
610 .or_else(|_| std::env::var("USERNAME"))
611 .unwrap_or_else(|_| "apm".to_string())
612}
613
614pub fn try_github_username(git_host: &GitHostConfig) -> Option<String> {
615 if git_host.provider.as_deref() != Some("github") {
616 return None;
617 }
618 if let Some(login) = crate::github::gh_username() {
619 return Some(login);
620 }
621 let local = LocalConfig::default();
622 let token = effective_github_token(&local, git_host)?;
623 crate::github::fetch_authenticated_user(&token).ok()
624}
625
626pub fn resolve_collaborators(config: &Config, local: &LocalConfig) -> (Vec<String>, Vec<String>) {
627 let mut warnings = Vec::new();
628 if config.git_host.provider.as_deref() == Some("github") {
629 if let Some(ref repo) = config.git_host.repo {
630 if let Some(token) = effective_github_token(local, &config.git_host) {
631 match crate::github::fetch_repo_collaborators(&token, repo) {
632 Ok(logins) => return (logins, warnings),
633 Err(e) => warnings.push(format!("apm: GitHub collaborators fetch failed: {e:#}")),
634 }
635 }
636 }
637 }
638 (config.project.collaborators.clone(), warnings)
639}
640
641impl WorkersConfig {
642 pub fn merge_local(&mut self, local: &LocalWorkersOverride) {
643 if let Some(ref cmd) = local.command {
644 self.command = Some(cmd.clone());
645 }
646 if let Some(ref args) = local.args {
647 self.args = Some(args.clone());
648 }
649 if let Some(ref model) = local.model {
650 self.model = Some(model.clone());
651 }
652 for (k, v) in &local.env {
653 self.env.insert(k.clone(), v.clone());
654 }
655 }
656}
657
658impl Config {
659 pub fn blocked_epics(&self, active_epic_ids: &[Option<String>]) -> Vec<String> {
662 let limit = self.agents.max_workers_per_epic;
663 let mut counts: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
664 for eid in active_epic_ids.iter().filter_map(|e| e.as_deref()) {
665 *counts.entry(eid).or_insert(0) += 1;
666 }
667 counts.into_iter()
668 .filter(|(_, count)| *count >= limit)
669 .map(|(eid, _)| eid.to_string())
670 .collect()
671 }
672
673 pub fn is_default_branch_blocked(&self, active_epic_ids: &[Option<String>]) -> bool {
676 if self.agents.max_workers_on_default == 0 {
677 return false;
678 }
679 let count = active_epic_ids.iter().filter(|e| e.is_none()).count();
680 count >= self.agents.max_workers_on_default
681 }
682
683 pub fn actionable_states_for(&self, actor: &str) -> Vec<String> {
686 self.workflow.states.iter()
687 .filter(|s| s.actionable.iter().any(|a| a == actor || a == "any"))
688 .map(|s| s.id.clone())
689 .collect()
690 }
691
692 pub fn terminal_state_ids(&self) -> std::collections::HashSet<String> {
693 let mut ids: std::collections::HashSet<String> = self.workflow.states.iter()
694 .filter(|s| s.terminal)
695 .map(|s| s.id.clone())
696 .collect();
697 ids.insert("closed".to_string());
698 ids
699 }
700
701 pub fn find_section(&self, name: &str) -> Option<&TicketSection> {
702 self.ticket.sections.iter()
703 .find(|s| s.name.eq_ignore_ascii_case(name))
704 }
705
706 pub fn has_section(&self, name: &str) -> bool {
707 self.find_section(name).is_some()
708 }
709
710 pub fn load(repo_root: &Path) -> Result<Self> {
711 let apm_dir = repo_root.join(".apm");
712 let apm_dir_config = apm_dir.join("config.toml");
713 let path = apm_dir_config;
714 let contents = std::fs::read_to_string(&path)
715 .with_context(|| format!(
716 "cannot read {} -- run 'apm init' to initialise this repository",
717 path.display()
718 ))?;
719 let mut config: Config = toml::from_str(&contents)
720 .with_context(|| format!("cannot parse {}", path.display()))?;
721
722 let workflow_path = apm_dir.join("workflow.toml");
723 if workflow_path.exists() {
724 let wf_contents = std::fs::read_to_string(&workflow_path)
725 .with_context(|| format!("cannot read {}", workflow_path.display()))?;
726 let wf: WorkflowFile = toml::from_str(&wf_contents)
727 .with_context(|| format!("cannot parse {}", workflow_path.display()))?;
728 if !config.workflow.states.is_empty() {
729 config.load_warnings.push(
730 "both .apm/workflow.toml and [workflow] in config.toml exist; workflow.toml takes precedence".into()
731 );
732 }
733 config.workflow = wf.workflow;
734 }
735
736 let ticket_path = apm_dir.join("ticket.toml");
737 if ticket_path.exists() {
738 let tk_contents = std::fs::read_to_string(&ticket_path)
739 .with_context(|| format!("cannot read {}", ticket_path.display()))?;
740 let tk: TicketFile = toml::from_str(&tk_contents)
741 .with_context(|| format!("cannot parse {}", ticket_path.display()))?;
742 if !config.ticket.sections.is_empty() {
743 config.load_warnings.push(
744 "both .apm/ticket.toml and [[ticket.sections]] in config.toml exist; ticket.toml takes precedence".into()
745 );
746 }
747 config.ticket = tk.ticket;
748 }
749
750 let local_path = apm_dir.join("local.toml");
751 if local_path.exists() {
752 let local_contents = std::fs::read_to_string(&local_path)
753 .with_context(|| format!("cannot read {}", local_path.display()))?;
754 let local: LocalConfig = toml::from_str(&local_contents)
755 .with_context(|| format!("cannot parse {}", local_path.display()))?;
756 config.workers.merge_local(&local.workers);
757 }
758
759 Ok(config)
760 }
761}
762
763#[cfg(test)]
764mod tests {
765 use super::*;
766 use std::sync::Mutex;
767
768 static ENV_LOCK: Mutex<()> = Mutex::new(());
769
770 #[test]
771 fn ticket_section_full_parse() {
772 let toml = r#"
773name = "Problem"
774type = "free"
775required = true
776placeholder = "What is broken or missing?"
777"#;
778 let s: TicketSection = toml::from_str(toml).unwrap();
779 assert_eq!(s.name, "Problem");
780 assert_eq!(s.type_, SectionType::Free);
781 assert!(s.required);
782 assert_eq!(s.placeholder.as_deref(), Some("What is broken or missing?"));
783 }
784
785 #[test]
786 fn ticket_section_minimal_parse() {
787 let toml = r#"
788name = "Open questions"
789type = "qa"
790"#;
791 let s: TicketSection = toml::from_str(toml).unwrap();
792 assert_eq!(s.name, "Open questions");
793 assert_eq!(s.type_, SectionType::Qa);
794 assert!(!s.required);
795 assert!(s.placeholder.is_none());
796 }
797
798 #[test]
799 fn section_type_all_variants() {
800 #[derive(Deserialize)]
801 struct W { t: SectionType }
802 let free: W = toml::from_str("t = \"free\"").unwrap();
803 assert_eq!(free.t, SectionType::Free);
804 let tasks: W = toml::from_str("t = \"tasks\"").unwrap();
805 assert_eq!(tasks.t, SectionType::Tasks);
806 let qa: W = toml::from_str("t = \"qa\"").unwrap();
807 assert_eq!(qa.t, SectionType::Qa);
808 }
809
810 #[test]
811 fn completion_strategy_all_variants() {
812 #[derive(Deserialize)]
813 struct W { c: CompletionStrategy }
814 let pr: W = toml::from_str("c = \"pr\"").unwrap();
815 assert_eq!(pr.c, CompletionStrategy::Pr);
816 let merge: W = toml::from_str("c = \"merge\"").unwrap();
817 assert_eq!(merge.c, CompletionStrategy::Merge);
818 let pull: W = toml::from_str("c = \"pull\"").unwrap();
819 assert_eq!(pull.c, CompletionStrategy::Pull);
820 let none: W = toml::from_str("c = \"none\"").unwrap();
821 assert_eq!(none.c, CompletionStrategy::None);
822 let prem: W = toml::from_str("c = \"pr_or_epic_merge\"").unwrap();
823 assert_eq!(prem.c, CompletionStrategy::PrOrEpicMerge);
824 }
825
826 #[test]
827 fn completion_strategy_default() {
828 assert_eq!(CompletionStrategy::default(), CompletionStrategy::None);
829 }
830
831 #[test]
832 fn state_config_with_instructions() {
833 let toml = r#"
834id = "in_progress"
835label = "In Progress"
836instructions = "apm.worker.md"
837"#;
838 let s: StateConfig = toml::from_str(toml).unwrap();
839 assert_eq!(s.id, "in_progress");
840 assert_eq!(s.instructions.as_deref(), Some("apm.worker.md"));
841 }
842
843 #[test]
844 fn state_config_instructions_default_none() {
845 let toml = r#"
846id = "new"
847label = "New"
848"#;
849 let s: StateConfig = toml::from_str(toml).unwrap();
850 assert!(s.instructions.is_none());
851 }
852
853 #[test]
854 fn transition_config_new_fields() {
855 let toml = r#"
856to = "implemented"
857trigger = "manual"
858completion = "pr"
859focus_section = "Code review"
860context_section = "Problem"
861"#;
862 let t: TransitionConfig = toml::from_str(toml).unwrap();
863 assert_eq!(t.completion, CompletionStrategy::Pr);
864 assert_eq!(t.focus_section.as_deref(), Some("Code review"));
865 assert_eq!(t.context_section.as_deref(), Some("Problem"));
866 }
867
868 #[test]
869 fn transition_config_new_fields_default() {
870 let toml = r#"
871to = "ready"
872trigger = "manual"
873"#;
874 let t: TransitionConfig = toml::from_str(toml).unwrap();
875 assert_eq!(t.completion, CompletionStrategy::None);
876 assert!(t.focus_section.is_none());
877 assert!(t.context_section.is_none());
878 assert!(t.outcome.is_none());
879 }
880
881 #[test]
882 fn resolve_outcome_explicit_override() {
883 let t: TransitionConfig = toml::from_str(r#"
884to = "ammend"
885outcome = "rejected"
886"#).unwrap();
887 let s: StateConfig = toml::from_str(r#"
888id = "ammend"
889label = "Ammend"
890"#).unwrap();
891 assert_eq!(super::resolve_outcome(&t, &s), "rejected");
892 }
893
894 #[test]
895 fn resolve_outcome_implicit_success() {
896 let t: TransitionConfig = toml::from_str(r#"
897to = "implemented"
898completion = "merge"
899"#).unwrap();
900 let s: StateConfig = toml::from_str(r#"
901id = "implemented"
902label = "Implemented"
903"#).unwrap();
904 assert_eq!(super::resolve_outcome(&t, &s), "success");
905 }
906
907 #[test]
908 fn resolve_outcome_implicit_cancelled() {
909 let t: TransitionConfig = toml::from_str(r#"
910to = "closed"
911"#).unwrap();
912 let s: StateConfig = toml::from_str(r#"
913id = "closed"
914label = "Closed"
915terminal = true
916"#).unwrap();
917 assert_eq!(super::resolve_outcome(&t, &s), "cancelled");
918 }
919
920 #[test]
921 fn resolve_outcome_implicit_needs_input() {
922 let t: TransitionConfig = toml::from_str(r#"
923to = "blocked"
924"#).unwrap();
925 let s: StateConfig = toml::from_str(r#"
926id = "blocked"
927label = "Blocked"
928"#).unwrap();
929 assert_eq!(super::resolve_outcome(&t, &s), "needs_input");
930 }
931
932 #[test]
933 fn workers_config_parses() {
934 let toml = r#"
935[project]
936name = "test"
937
938[tickets]
939dir = "tickets"
940
941[workers]
942container = "apm-worker:latest"
943
944[workers.keychain]
945ANTHROPIC_API_KEY = "anthropic-api-key"
946"#;
947 let config: Config = toml::from_str(toml).unwrap();
948 assert_eq!(config.workers.container.as_deref(), Some("apm-worker:latest"));
949 assert_eq!(config.workers.keychain.get("ANTHROPIC_API_KEY").map(|s| s.as_str()), Some("anthropic-api-key"));
950 }
951
952 #[test]
953 fn workers_config_default() {
954 let toml = r#"
955[project]
956name = "test"
957
958[tickets]
959dir = "tickets"
960"#;
961 let config: Config = toml::from_str(toml).unwrap();
962 assert!(config.workers.container.is_none());
963 assert!(config.workers.keychain.is_empty());
964 assert!(config.workers.command.is_none());
965 assert!(config.workers.args.is_none());
966 assert!(config.workers.agent.is_none());
967 assert!(config.workers.options.is_empty());
968 assert!(config.workers.model.is_none());
969 assert!(config.workers.env.is_empty());
970 }
971
972 #[test]
973 fn workers_config_all_fields() {
974 let toml = r#"
975[project]
976name = "test"
977
978[tickets]
979dir = "tickets"
980
981[workers]
982command = "codex"
983args = ["--full-auto"]
984model = "o3"
985
986[workers.env]
987CUSTOM_VAR = "value"
988"#;
989 let config: Config = toml::from_str(toml).unwrap();
990 assert_eq!(config.workers.command.as_deref(), Some("codex"));
991 assert_eq!(config.workers.args.as_deref(), Some(["--full-auto".to_string()][..].as_ref()));
992 assert_eq!(config.workers.model.as_deref(), Some("o3"));
993 assert_eq!(config.workers.env.get("CUSTOM_VAR").map(|s| s.as_str()), Some("value"));
994 }
995
996 #[test]
997 fn local_config_parses() {
998 let toml = r#"
999[workers]
1000command = "aider"
1001model = "gpt-4"
1002
1003[workers.env]
1004OPENAI_API_KEY = "sk-test"
1005"#;
1006 let local: LocalConfig = toml::from_str(toml).unwrap();
1007 assert_eq!(local.workers.command.as_deref(), Some("aider"));
1008 assert_eq!(local.workers.model.as_deref(), Some("gpt-4"));
1009 assert_eq!(local.workers.env.get("OPENAI_API_KEY").map(|s| s.as_str()), Some("sk-test"));
1010 assert!(local.workers.args.is_none());
1011 }
1012
1013 #[test]
1014 fn merge_local_overrides_and_extends() {
1015 let mut wc = WorkersConfig::default();
1016 assert!(wc.command.is_none());
1017 assert!(wc.args.is_none());
1018
1019 let local = LocalWorkersOverride {
1020 command: Some("aider".to_string()),
1021 args: None,
1022 model: Some("gpt-4".to_string()),
1023 env: [("KEY".to_string(), "val".to_string())].into(),
1024 };
1025 wc.merge_local(&local);
1026
1027 assert_eq!(wc.command.as_deref(), Some("aider"));
1028 assert!(wc.args.is_none()); assert_eq!(wc.model.as_deref(), Some("gpt-4"));
1030 assert_eq!(wc.env.get("KEY").map(|s| s.as_str()), Some("val"));
1031 }
1032
1033 #[test]
1034 fn agents_skip_permissions_parses_and_defaults() {
1035 let base = "[project]\nname = \"test\"\n[tickets]\ndir = \"tickets\"\n";
1036
1037 let config: Config = toml::from_str(base).unwrap();
1039 assert!(!config.agents.skip_permissions, "absent skip_permissions should default to false");
1040
1041 let with_agents = format!("{base}[agents]\n");
1043 let config: Config = toml::from_str(&with_agents).unwrap();
1044 assert!(!config.agents.skip_permissions, "[agents] without skip_permissions should default to false");
1045
1046 let explicit_true = format!("{base}[agents]\nskip_permissions = true\n");
1048 let config: Config = toml::from_str(&explicit_true).unwrap();
1049 assert!(config.agents.skip_permissions, "explicit skip_permissions = true should be true");
1050
1051 let explicit_false = format!("{base}[agents]\nskip_permissions = false\n");
1053 let config: Config = toml::from_str(&explicit_false).unwrap();
1054 assert!(!config.agents.skip_permissions, "explicit skip_permissions = false should be false");
1055 }
1056
1057 #[test]
1058 fn actionable_states_for_agent_includes_ready() {
1059 let toml = r#"
1060[project]
1061name = "test"
1062
1063[tickets]
1064dir = "tickets"
1065
1066[[workflow.states]]
1067id = "ready"
1068label = "Ready"
1069actionable = ["agent"]
1070
1071[[workflow.states]]
1072id = "in_progress"
1073label = "In Progress"
1074
1075[[workflow.states]]
1076id = "specd"
1077label = "Specd"
1078actionable = ["supervisor"]
1079"#;
1080 let config: Config = toml::from_str(toml).unwrap();
1081 let states = config.actionable_states_for("agent");
1082 assert!(states.contains(&"ready".to_string()));
1083 assert!(!states.contains(&"specd".to_string()));
1084 assert!(!states.contains(&"in_progress".to_string()));
1085 }
1086
1087 #[test]
1088 fn work_epic_parses() {
1089 let toml = r#"
1090[project]
1091name = "test"
1092
1093[tickets]
1094dir = "tickets"
1095
1096[work]
1097epic = "ab12cd34"
1098"#;
1099 let config: Config = toml::from_str(toml).unwrap();
1100 assert_eq!(config.work.epic.as_deref(), Some("ab12cd34"));
1101 }
1102
1103 #[test]
1104 fn work_config_defaults_to_none() {
1105 let toml = r#"
1106[project]
1107name = "test"
1108
1109[tickets]
1110dir = "tickets"
1111"#;
1112 let config: Config = toml::from_str(toml).unwrap();
1113 assert!(config.work.epic.is_none());
1114 }
1115
1116 #[test]
1117 fn sync_aggressive_defaults_to_true() {
1118 let base = "[project]\nname = \"test\"\n[tickets]\ndir = \"tickets\"\n";
1119
1120 let config: Config = toml::from_str(base).unwrap();
1122 assert!(config.sync.aggressive, "no [sync] section should default to true");
1123
1124 let with_sync = format!("{base}[sync]\n");
1126 let config: Config = toml::from_str(&with_sync).unwrap();
1127 assert!(config.sync.aggressive, "[sync] without aggressive key should default to true");
1128
1129 let explicit_false = format!("{base}[sync]\naggressive = false\n");
1131 let config: Config = toml::from_str(&explicit_false).unwrap();
1132 assert!(!config.sync.aggressive, "explicit aggressive = false should be false");
1133
1134 let explicit_true = format!("{base}[sync]\naggressive = true\n");
1136 let config: Config = toml::from_str(&explicit_true).unwrap();
1137 assert!(config.sync.aggressive, "explicit aggressive = true should be true");
1138 }
1139
1140 #[test]
1141 fn collaborators_parses() {
1142 let toml = r#"
1143[project]
1144name = "test"
1145collaborators = ["alice", "bob"]
1146
1147[tickets]
1148dir = "tickets"
1149"#;
1150 let config: Config = toml::from_str(toml).unwrap();
1151 assert_eq!(config.project.collaborators, vec!["alice", "bob"]);
1152 }
1153
1154 #[test]
1155 fn collaborators_defaults_empty() {
1156 let toml = r#"
1157[project]
1158name = "test"
1159
1160[tickets]
1161dir = "tickets"
1162"#;
1163 let config: Config = toml::from_str(toml).unwrap();
1164 assert!(config.project.collaborators.is_empty());
1165 }
1166
1167 #[test]
1168 fn resolve_identity_returns_username_when_present() {
1169 let tmp = tempfile::tempdir().unwrap();
1170 let apm_dir = tmp.path().join(".apm");
1171 std::fs::create_dir_all(&apm_dir).unwrap();
1172 std::fs::write(apm_dir.join("local.toml"), "username = \"alice\"\n").unwrap();
1173 assert_eq!(resolve_identity(tmp.path()), "alice");
1174 }
1175
1176 #[test]
1177 fn resolve_identity_returns_unassigned_when_absent() {
1178 let tmp = tempfile::tempdir().unwrap();
1179 assert_eq!(resolve_identity(tmp.path()), "unassigned");
1180 }
1181
1182 #[test]
1183 fn resolve_identity_returns_unassigned_when_empty() {
1184 let tmp = tempfile::tempdir().unwrap();
1185 let apm_dir = tmp.path().join(".apm");
1186 std::fs::create_dir_all(&apm_dir).unwrap();
1187 std::fs::write(apm_dir.join("local.toml"), "username = \"\"\n").unwrap();
1188 assert_eq!(resolve_identity(tmp.path()), "unassigned");
1189 }
1190
1191 #[test]
1192 fn resolve_identity_returns_unassigned_when_username_key_absent() {
1193 let tmp = tempfile::tempdir().unwrap();
1194 let apm_dir = tmp.path().join(".apm");
1195 std::fs::create_dir_all(&apm_dir).unwrap();
1196 std::fs::write(apm_dir.join("local.toml"), "[workers]\ncommand = \"claude\"\n").unwrap();
1197 assert_eq!(resolve_identity(tmp.path()), "unassigned");
1198 }
1199
1200 #[test]
1201 fn local_config_username_parses() {
1202 let toml = r#"
1203username = "bob"
1204"#;
1205 let local: LocalConfig = toml::from_str(toml).unwrap();
1206 assert_eq!(local.username.as_deref(), Some("bob"));
1207 }
1208
1209 #[test]
1210 fn local_config_username_defaults_none() {
1211 let local: LocalConfig = toml::from_str("").unwrap();
1212 assert!(local.username.is_none());
1213 }
1214
1215 #[test]
1216 fn server_config_defaults() {
1217 let toml = r#"
1218[project]
1219name = "test"
1220
1221[tickets]
1222dir = "tickets"
1223"#;
1224 let config: Config = toml::from_str(toml).unwrap();
1225 assert_eq!(config.server.origin, "http://localhost:3000");
1226 }
1227
1228 #[test]
1229 fn server_config_custom_origin() {
1230 let toml = r#"
1231[project]
1232name = "test"
1233
1234[tickets]
1235dir = "tickets"
1236
1237[server]
1238origin = "https://apm.example.com"
1239"#;
1240 let config: Config = toml::from_str(toml).unwrap();
1241 assert_eq!(config.server.origin, "https://apm.example.com");
1242 }
1243
1244 #[test]
1245 fn git_host_config_parses() {
1246 let toml = r#"
1247[project]
1248name = "test"
1249
1250[tickets]
1251dir = "tickets"
1252
1253[git_host]
1254provider = "github"
1255repo = "owner/name"
1256"#;
1257 let config: Config = toml::from_str(toml).unwrap();
1258 assert_eq!(config.git_host.provider.as_deref(), Some("github"));
1259 assert_eq!(config.git_host.repo.as_deref(), Some("owner/name"));
1260 }
1261
1262 #[test]
1263 fn git_host_config_absent_defaults_none() {
1264 let toml = r#"
1265[project]
1266name = "test"
1267
1268[tickets]
1269dir = "tickets"
1270"#;
1271 let config: Config = toml::from_str(toml).unwrap();
1272 assert!(config.git_host.provider.is_none());
1273 assert!(config.git_host.repo.is_none());
1274 }
1275
1276 #[test]
1277 fn local_config_github_token_parses() {
1278 let toml = r#"github_token = "ghp_abc123""#;
1279 let local: LocalConfig = toml::from_str(toml).unwrap();
1280 assert_eq!(local.github_token.as_deref(), Some("ghp_abc123"));
1281 }
1282
1283 #[test]
1284 fn local_config_github_token_absent_defaults_none() {
1285 let local: LocalConfig = toml::from_str("").unwrap();
1286 assert!(local.github_token.is_none());
1287 }
1288
1289 #[test]
1290 fn tickets_archive_dir_parses() {
1291 let toml = r#"
1292[project]
1293name = "test"
1294
1295[tickets]
1296dir = "tickets"
1297archive_dir = "archive/tickets"
1298"#;
1299 let config: Config = toml::from_str(toml).unwrap();
1300 assert_eq!(
1301 config.tickets.archive_dir.as_deref(),
1302 Some(std::path::Path::new("archive/tickets"))
1303 );
1304 }
1305
1306 #[test]
1307 fn tickets_archive_dir_absent_defaults_none() {
1308 let toml = r#"
1309[project]
1310name = "test"
1311
1312[tickets]
1313dir = "tickets"
1314"#;
1315 let config: Config = toml::from_str(toml).unwrap();
1316 assert!(config.tickets.archive_dir.is_none());
1317 }
1318
1319 #[test]
1320 fn agents_max_workers_per_epic_defaults_to_one() {
1321 let toml = "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n";
1322 let config: Config = toml::from_str(toml).unwrap();
1323 assert_eq!(config.agents.max_workers_per_epic, 1);
1324 }
1325
1326 #[test]
1327 fn blocked_epics_global_limit_one() {
1328 let toml = "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n";
1329 let config: Config = toml::from_str(toml).unwrap();
1330 let active = vec![Some("epicA".to_string())];
1332 let blocked = config.blocked_epics(&active);
1333 assert!(blocked.contains(&"epicA".to_string()));
1334 }
1335
1336 #[test]
1337 fn blocked_epics_global_limit_two() {
1338 let toml = "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n\n[agents]\nmax_workers_per_epic = 2\n";
1339 let config: Config = toml::from_str(toml).unwrap();
1340 let active = vec![Some("epicA".to_string())];
1342 let blocked = config.blocked_epics(&active);
1343 assert!(!blocked.contains(&"epicA".to_string()));
1344 }
1345
1346 #[test]
1347 fn default_branch_not_blocked_when_no_active_non_epic_workers() {
1348 let base = "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n";
1349 let config: Config = toml::from_str(base).unwrap();
1350 assert_eq!(config.agents.max_workers_on_default, 1);
1351 let active: Vec<Option<String>> = vec![];
1353 assert!(!config.is_default_branch_blocked(&active));
1354 }
1355
1356 #[test]
1357 fn default_branch_blocked_when_one_active_non_epic_worker_and_limit_one() {
1358 let base = "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n";
1359 let config: Config = toml::from_str(base).unwrap();
1360 let active = vec![None];
1362 assert!(config.is_default_branch_blocked(&active));
1363 }
1364
1365 #[test]
1366 fn default_branch_not_blocked_when_limit_zero() {
1367 let toml = "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n\n[agents]\nmax_workers_on_default = 0\n";
1368 let config: Config = toml::from_str(toml).unwrap();
1369 let active = vec![None, None, None];
1371 assert!(!config.is_default_branch_blocked(&active));
1372 }
1373
1374 #[test]
1375 fn default_branch_not_blocked_when_all_workers_are_epic_linked() {
1376 let base = "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n";
1377 let config: Config = toml::from_str(base).unwrap();
1378 let active = vec![Some("epicA".to_string()), Some("epicB".to_string())];
1380 assert!(!config.is_default_branch_blocked(&active));
1381 }
1382
1383 #[test]
1384 fn prefers_apm_agent_name() {
1385 let _g = ENV_LOCK.lock().unwrap();
1386 std::env::set_var("APM_AGENT_NAME", "explicit-agent");
1387 assert_eq!(resolve_caller_name(), "explicit-agent");
1388 std::env::remove_var("APM_AGENT_NAME");
1389 }
1390
1391 #[test]
1392 fn falls_back_to_user() {
1393 let _g = ENV_LOCK.lock().unwrap();
1394 std::env::remove_var("APM_AGENT_NAME");
1395 std::env::set_var("USER", "unix-user");
1396 std::env::remove_var("USERNAME");
1397 assert_eq!(resolve_caller_name(), "unix-user");
1398 std::env::remove_var("USER");
1399 }
1400
1401 #[test]
1402 fn defaults_to_apm() {
1403 let _g = ENV_LOCK.lock().unwrap();
1404 std::env::remove_var("APM_AGENT_NAME");
1405 std::env::remove_var("USER");
1406 std::env::remove_var("USERNAME");
1407 assert_eq!(resolve_caller_name(), "apm");
1408 }
1409
1410 #[test]
1411 fn config_round_trip_new_shape() {
1412 let toml = r#"
1413[project]
1414name = "test"
1415
1416[tickets]
1417dir = "tickets"
1418
1419[workers]
1420agent = "claude"
1421
1422[workers.options]
1423model = "sonnet"
1424timeout = "30"
1425"#;
1426 let config: Config = toml::from_str(toml).unwrap();
1427 assert_eq!(config.workers.agent.as_deref(), Some("claude"));
1428 assert_eq!(config.workers.options.get("model").map(|s| s.as_str()), Some("sonnet"));
1429 assert_eq!(config.workers.options.get("timeout").map(|s| s.as_str()), Some("30"));
1430 assert!(config.workers.command.is_none());
1431 assert!(config.workers.args.is_none());
1432 }
1433
1434 #[test]
1435 fn config_round_trip_legacy_shape() {
1436 let toml = r#"
1437[project]
1438name = "test"
1439
1440[tickets]
1441dir = "tickets"
1442
1443[workers]
1444command = "claude"
1445args = ["--print"]
1446model = "opus"
1447"#;
1448 let config: Config = toml::from_str(toml).unwrap();
1449 assert!(config.workers.agent.is_none());
1450 assert_eq!(config.workers.command.as_deref(), Some("claude"));
1451 assert_eq!(config.workers.model.as_deref(), Some("opus"));
1452 }
1453
1454 #[test]
1455 fn worker_profile_config_new_fields() {
1456 let toml = r#"
1457[project]
1458name = "test"
1459
1460[tickets]
1461dir = "tickets"
1462
1463[worker_profiles.my_agent]
1464agent = "mock-happy"
1465
1466[worker_profiles.my_agent.options]
1467model = "sonnet"
1468"#;
1469 let config: Config = toml::from_str(toml).unwrap();
1470 let profile = config.worker_profiles.get("my_agent").unwrap();
1471 assert_eq!(profile.agent.as_deref(), Some("mock-happy"));
1472 assert_eq!(profile.options.get("model").map(|s| s.as_str()), Some("sonnet"));
1473 }
1474}