1use crate::error::SpriteError;
4use crate::models::ConflictResolution;
5use crate::utils::git;
6use anyhow::{Context, Result};
7use std::path::PathBuf;
8use tokio::process::Command as TokioCommand;
9
10pub fn execute(agent: Option<&str>, force: bool, strategy: &str, dry_run: bool) -> Result<()> {
12 git::validate_git_repository()?;
14
15 let conflict_strategy = match strategy {
17 "manual" => ConflictResolution::Manual,
18 "auto-theirs" => ConflictResolution::AutoTheirs,
19 "auto-ours" => ConflictResolution::AutoOurs,
20 _ => {
21 return Err(SpriteError::validation(
22 format!("Invalid conflict resolution strategy: '{}'. Valid options: manual, auto-theirs, auto-ours", strategy),
23 Some("strategy".to_string()),
24 Some(strategy.to_string())
25 ).into());
26 }
27 };
28
29 let sync_context = determine_sync_context(agent.map(|s| s.to_string()))?;
31
32 println!("🔄 Syncing in {:?} context...", sync_context.context_type);
33
34 if dry_run {
35 println!("🔍 Dry run mode - no changes will be made");
36 }
37
38 match &sync_context.context_type {
40 SyncContextType::MainWorktree => {
41 sync_main_worktree(&sync_context, conflict_strategy, dry_run, force)?
42 }
43 SyncContextType::AgentWorktree { agent_id } => {
44 sync_agent_worktree(&sync_context, agent_id, conflict_strategy, dry_run, force)?
45 }
46 SyncContextType::Unknown => {
47 return Err(SpriteError::sync(
48 "Cannot determine sync context. Please run from main worktree or an agent worktree."
49 ).into());
50 }
51 }
52
53 if !dry_run {
54 println!("✓ Sync completed successfully");
55 } else {
56 println!("✓ Dry run completed - no changes made");
57 }
58
59 Ok(())
60}
61
62#[derive(Debug)]
64struct SyncContext {
65 context_type: SyncContextType,
67 current_dir: PathBuf,
69 current_branch: String,
71 #[allow(dead_code)]
73 git_root: PathBuf,
74}
75
76#[derive(Debug)]
78enum SyncContextType {
79 MainWorktree,
81 AgentWorktree { agent_id: String },
83 Unknown,
85}
86
87fn determine_sync_context(agent_id: Option<String>) -> Result<SyncContext> {
89 let current_dir = std::env::current_dir().context("Failed to get current directory")?;
90
91 let git_root = git::get_git_root().context("Failed to get git repository root")?;
92
93 let current_branch =
94 git::get_current_branch_at(¤t_dir).context("Failed to get current git branch")?;
95
96 let current_dir_normalized = current_dir
98 .canonicalize()
99 .context("Failed to canonicalize current directory")?;
100 let git_root_normalized = git_root
101 .canonicalize()
102 .context("Failed to canonicalize git root")?;
103
104 if current_dir_normalized == git_root_normalized {
106 return Ok(SyncContext {
107 context_type: SyncContextType::MainWorktree,
108 current_dir,
109 current_branch,
110 git_root,
111 });
112 }
113
114 let relative_path = match current_dir_normalized.strip_prefix(&git_root_normalized) {
116 Ok(path) => path,
117 Err(_) => {
118 return Ok(SyncContext {
119 context_type: SyncContextType::Unknown,
120 current_dir,
121 current_branch,
122 git_root,
123 });
124 }
125 };
126
127 let path_str = relative_path.to_string_lossy();
129
130 if let Some(extracted_agent_id) = extract_agent_id_from_path(&path_str) {
132 if let Some(provided_id) = &agent_id {
134 if provided_id != &extracted_agent_id {
135 return Err(SpriteError::validation(
136 format!(
137 "Agent ID mismatch. Path suggests '{}' but you specified '{}'",
138 extracted_agent_id, provided_id
139 ),
140 Some("agent".to_string()),
141 Some(format!("path: {}, agent: {}", path_str, provided_id)),
142 )
143 .into());
144 }
145 }
146
147 return Ok(SyncContext {
148 context_type: SyncContextType::AgentWorktree {
149 agent_id: extracted_agent_id,
150 },
151 current_dir,
152 current_branch,
153 git_root,
154 });
155 }
156
157 Ok(SyncContext {
158 context_type: SyncContextType::Unknown,
159 current_dir,
160 current_branch,
161 git_root,
162 })
163}
164
165fn extract_agent_id_from_path(path: &str) -> Option<String> {
167 if let Some(remaining) = path.strip_prefix("agents/") {
169 if remaining.is_empty() {
171 return None;
172 }
173
174 if let Some(slash_pos) = remaining.find('/') {
176 let potential_id = &remaining[..slash_pos];
177 if potential_id
179 .chars()
180 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
181 {
182 return Some(potential_id.to_string());
183 }
184 } else {
185 if remaining
187 .chars()
188 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
189 {
190 return Some(remaining.to_string());
191 }
192 }
193 }
194
195 None
196}
197
198fn sync_main_worktree(
200 context: &SyncContext,
201 _conflict_strategy: ConflictResolution,
202 dry_run: bool,
203 force: bool,
204) -> Result<()> {
205 println!("📥 Syncing main worktree (pull from remote origin/main)");
206
207 if dry_run {
208 println!(" Would run: git pull origin main");
209 return Ok(());
210 }
211
212 let status =
214 git::get_status_string_at(&context.current_dir).context("Failed to get git status")?;
215
216 if !status.is_empty() {
217 println!("⚠️ You have uncommitted changes:");
218 println!("{}", status);
219
220 if !force {
221 return Err(SpriteError::sync(
222 "Cannot sync main worktree with uncommitted changes. Use --force to proceed anyway or commit your changes first."
223 ).into());
224 }
225
226 println!("⚠️ Proceeding with uncommitted changes due to --force flag");
227 }
228
229 println!(" Pulling changes from origin/main...");
231 git::pull().with_context(|| "Failed to pull changes from remote")?;
232
233 println!("✓ Main worktree synced successfully");
234 Ok(())
235}
236
237fn sync_agent_worktree(
239 context: &SyncContext,
240 agent_id: &str,
241 conflict_strategy: ConflictResolution,
242 dry_run: bool,
243 force: bool,
244) -> Result<()> {
245 println!(
246 "📥 Syncing agent worktree '{}' (merge from main branch)",
247 agent_id
248 );
249
250 if dry_run {
251 println!(" Would run: git merge main");
252 return Ok(());
253 }
254
255 let status = git::get_status_string_at(&context.current_dir)
257 .context("Failed to get git status for agent worktree")?;
258
259 if !status.is_empty() {
260 println!("⚠️ Agent {} has uncommitted changes:", agent_id);
261 println!("{}", status);
262
263 if !force {
264 return Err(SpriteError::sync(
265 format!("Cannot sync agent worktree '{}' with uncommitted changes. Use --force to proceed or commit your changes first.", agent_id)
266 ).into());
267 }
268
269 println!("⚠️ Proceeding with uncommitted changes due to --force flag");
270 }
271
272 println!(" Ensuring main branch is available...");
274
275 let current_branch = context.current_branch.clone();
277 if current_branch != "main" && current_branch != "master" {
278 println!(" Switching to main branch temporarily...");
279 git::switch_branch("main")
280 .or_else(|_| {
281 git::switch_branch("master")
283 })
284 .with_context(|| "Failed to switch to main branch")?;
285
286 defer_switch_back(¤t_branch)?;
288 }
289
290 println!(" Merging changes from main branch...");
292
293 let output = std::process::Command::new("git")
294 .args(["merge", "main"])
295 .current_dir(&context.current_dir)
296 .output()
297 .with_context(|| "Failed to merge main branch into agent worktree")?;
298
299 if !output.status.success() {
300 let stderr = String::from_utf8_lossy(&output.stderr);
301
302 if stderr.contains("CONFLICT") || stderr.contains("Merge conflict") {
304 handle_merge_conflicts(&stderr, conflict_strategy, dry_run)?;
305 } else {
306 return Err(SpriteError::git_with_source(
307 "Failed to merge main branch",
308 stderr.to_string(),
309 )
310 .into());
311 }
312 }
313
314 println!("✓ Agent worktree '{}' synced successfully", agent_id);
315 Ok(())
316}
317
318fn handle_merge_conflicts(
320 error_output: &str,
321 strategy: ConflictResolution,
322 dry_run: bool,
323) -> Result<()> {
324 if dry_run {
325 println!(
326 " Merge conflicts detected - would use strategy: {:?}",
327 strategy
328 );
329 return Ok(());
330 }
331
332 match strategy {
333 ConflictResolution::Manual => {
334 println!("❌ Merge conflicts detected:");
335 println!("{}", error_output);
336 return Err(SpriteError::sync(
337 "Merge conflicts detected. Please resolve them manually and try again.",
338 )
339 .into());
340 }
341 ConflictResolution::AutoTheirs => {
342 println!("🔄 Automatically accepting their changes...");
343 let output = std::process::Command::new("git")
344 .args(["checkout", "--theirs", "--", "."])
345 .output()
346 .with_context(|| "Failed to auto-accept their changes")?;
347
348 if !output.status.success() {
349 return Err(SpriteError::git_with_source(
350 "Failed to auto-accept their changes",
351 String::from_utf8_lossy(&output.stderr),
352 )
353 .into());
354 }
355
356 println!("✓ Automatically accepted their changes");
357 }
358 ConflictResolution::AutoOurs => {
359 println!("🔄 Automatically accepting our changes...");
360 let output = std::process::Command::new("git")
361 .args(["checkout", "--ours", "--", "."])
362 .output()
363 .with_context(|| "Failed to auto-accept our changes")?;
364
365 if !output.status.success() {
366 return Err(SpriteError::git_with_source(
367 "Failed to auto-accept our changes",
368 String::from_utf8_lossy(&output.stderr),
369 )
370 .into());
371 }
372
373 println!("✓ Automatically accepted our changes");
374 }
375 }
376
377 let output = std::process::Command::new("git")
379 .args(["add", "."])
380 .output()
381 .with_context(|| "Failed to stage resolved files")?;
382
383 if !output.status.success() {
384 return Err(SpriteError::git_with_source(
385 "Failed to stage resolved files",
386 String::from_utf8_lossy(&output.stderr),
387 )
388 .into());
389 }
390
391 Ok(())
392}
393
394fn defer_switch_back(original_branch: &str) -> Result<()> {
396 if original_branch != "main" && original_branch != "master" {
400 println!(
402 " Note: Would switch back to '{}' after operations",
403 original_branch
404 );
405 }
406 Ok(())
407}
408
409#[derive(Debug, Clone)]
411#[allow(dead_code)]
412pub struct SyncStatus {
413 pub start_time: std::time::SystemTime,
414 pub end_time: Option<std::time::SystemTime>,
415 pub context_type: String,
416 pub operations_completed: Vec<SyncOperation>,
417 pub conflicts_detected: Vec<MergeConflict>,
418 pub success: bool,
419 pub error_message: Option<String>,
420}
421
422#[derive(Debug, Clone)]
423#[allow(dead_code)]
424pub struct SyncOperation {
425 pub operation_type: String,
426 pub description: String,
427 pub start_time: std::time::SystemTime,
428 pub end_time: Option<std::time::SystemTime>,
429 pub success: bool,
430 pub output: Option<String>,
431}
432
433#[derive(Debug, Clone)]
434#[allow(dead_code)]
435pub struct MergeConflict {
436 pub file_path: String,
437 pub conflict_type: String,
438 pub detected_at: std::time::SystemTime,
439}
440
441#[allow(dead_code)]
443pub struct SyncHooks {
444 pub pre_sync_hooks: Vec<SyncHook>,
445 pub post_sync_hooks: Vec<SyncHook>,
446}
447
448#[derive(Debug, Clone)]
449#[allow(dead_code)]
450pub struct SyncHook {
451 pub name: String,
452 pub command: String,
453 pub args: Vec<String>,
454 pub working_dir: Option<PathBuf>,
455 pub required: bool,
456 pub timeout: Option<std::time::Duration>,
457}
458
459impl SyncHooks {
460 #[allow(dead_code)]
461 pub fn load_from_config() -> Result<Self> {
462 Ok(Self {
465 pre_sync_hooks: vec![SyncHook {
466 name: "Check for uncommitted changes".to_string(),
467 command: "git".to_string(),
468 args: vec!["status".to_string(), "--porcelain".to_string()],
469 working_dir: None,
470 required: true,
471 timeout: Some(std::time::Duration::from_secs(5)),
472 }],
473 post_sync_hooks: vec![SyncHook {
474 name: "Run tests if available".to_string(),
475 command: "cargo".to_string(),
476 args: vec!["test".to_string(), "--quiet".to_string()],
477 working_dir: None,
478 required: false,
479 timeout: Some(std::time::Duration::from_secs(60)),
480 }],
481 })
482 }
483
484 #[allow(dead_code)]
485 pub async fn execute_pre_sync_hooks(&self, status: &mut SyncStatus) -> Result<()> {
486 println!("🔧 Running pre-sync hooks...");
487
488 for hook in &self.pre_sync_hooks {
489 let operation = SyncOperation {
490 operation_type: "pre-sync-hook".to_string(),
491 description: hook.name.clone(),
492 start_time: std::time::SystemTime::now(),
493 end_time: None,
494 success: false,
495 output: None,
496 };
497
498 println!(" Running: {}", hook.name);
499
500 let result = tokio::time::timeout(
501 hook.timeout.unwrap_or(std::time::Duration::from_secs(30)),
502 execute_hook_command(hook),
503 )
504 .await;
505
506 let mut completed_operation = operation;
507 completed_operation.end_time = Some(std::time::SystemTime::now());
508
509 match result {
510 Ok(Ok(output)) => {
511 completed_operation.success = true;
512 completed_operation.output = Some(output);
513 status.operations_completed.push(completed_operation);
514 println!(" ✓ {} completed successfully", hook.name);
515 }
516 Ok(Err(e)) => {
517 completed_operation.output = Some(format!("Error: {}", e));
518 status.operations_completed.push(completed_operation);
519
520 if hook.required {
521 status.success = false;
522 status.error_message =
523 Some(format!("Required pre-sync hook failed: {}", e));
524 return Err(SpriteError::sync(format!(
525 "Required pre-sync hook '{}' failed: {}",
526 hook.name, e
527 ))
528 .into());
529 } else {
530 println!(
531 " ⚠️ Optional pre-sync hook failed, continuing: {}",
532 hook.name
533 );
534 }
535 }
536 Err(_) => {
537 completed_operation.output = Some("Hook timed out".to_string());
538 status.operations_completed.push(completed_operation);
539
540 if hook.required {
541 status.success = false;
542 status.error_message =
543 Some(format!("Required pre-sync hook '{}' timed out", hook.name));
544 return Err(SpriteError::sync(format!(
545 "Required pre-sync hook '{}' timed out",
546 hook.name
547 ))
548 .into());
549 } else {
550 println!(
551 " ⚠️ Optional pre-sync hook timed out, continuing: {}",
552 hook.name
553 );
554 }
555 }
556 }
557 }
558
559 Ok(())
560 }
561
562 #[allow(dead_code)]
563 pub async fn execute_post_sync_hooks(&self, status: &mut SyncStatus) -> Result<()> {
564 println!("🔧 Running post-sync hooks...");
565
566 for hook in &self.post_sync_hooks {
567 let operation = SyncOperation {
568 operation_type: "post-sync-hook".to_string(),
569 description: hook.name.clone(),
570 start_time: std::time::SystemTime::now(),
571 end_time: None,
572 success: false,
573 output: None,
574 };
575
576 println!(" Running: {}", hook.name);
577
578 let result = tokio::time::timeout(
579 hook.timeout.unwrap_or(std::time::Duration::from_secs(30)),
580 execute_hook_command(hook),
581 )
582 .await;
583
584 let mut completed_operation = operation;
585 completed_operation.end_time = Some(std::time::SystemTime::now());
586
587 match result {
588 Ok(Ok(output)) => {
589 completed_operation.success = true;
590 completed_operation.output = Some(output);
591 status.operations_completed.push(completed_operation);
592 println!(" ✓ {} completed successfully", hook.name);
593 }
594 Ok(Err(e)) => {
595 completed_operation.output = Some(format!("Error: {}", e));
596 status.operations_completed.push(completed_operation);
597
598 if hook.required {
599 println!(" ❌ Required post-sync hook failed: {}", hook.name);
600 } else {
602 println!(" ⚠️ Optional post-sync hook failed: {}", hook.name);
603 }
604 }
605 Err(_) => {
606 completed_operation.output = Some("Hook timed out".to_string());
607 status.operations_completed.push(completed_operation);
608
609 if hook.required {
610 println!(" ❌ Required post-sync hook timed out: {}", hook.name);
611 } else {
612 println!(" ⚠️ Optional post-sync hook timed out: {}", hook.name);
613 }
614 }
615 }
616 }
617
618 Ok(())
619 }
620}
621
622#[allow(dead_code)]
623async fn execute_hook_command(hook: &SyncHook) -> Result<String> {
624 let mut cmd = TokioCommand::new(&hook.command);
625 cmd.args(&hook.args);
626
627 if let Some(dir) = &hook.working_dir {
628 cmd.current_dir(dir);
629 }
630
631 let output = cmd.output().await.with_context(|| {
632 format!(
633 "Failed to execute hook command: {} {}",
634 hook.command,
635 hook.args.join(" ")
636 )
637 })?;
638
639 if !output.status.success() {
640 return Err(SpriteError::git_with_source(
641 format!(
642 "Hook command failed: {} {}",
643 hook.command,
644 hook.args.join(" ")
645 ),
646 String::from_utf8_lossy(&output.stderr),
647 )
648 .into());
649 }
650
651 Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
652}
653
654impl SyncStatus {
655 #[allow(dead_code)]
656 pub fn new(context_type: String) -> Self {
657 Self {
658 start_time: std::time::SystemTime::now(),
659 end_time: None,
660 context_type,
661 operations_completed: Vec::new(),
662 conflicts_detected: Vec::new(),
663 success: true,
664 error_message: None,
665 }
666 }
667
668 #[allow(dead_code)]
669 pub fn complete(&mut self) {
670 self.end_time = Some(std::time::SystemTime::now());
671 }
672
673 #[allow(dead_code)]
674 pub fn duration(&self) -> Option<std::time::Duration> {
675 self.end_time
676 .map(|end| end.duration_since(self.start_time).unwrap_or_default())
677 }
678
679 #[allow(dead_code)]
680 pub fn format_report(&self) -> String {
681 let mut report = String::new();
682
683 report.push_str("📊 Sync Status Report\n");
684 report.push_str("===================\n\n");
685 report.push_str(&format!("Context: {}\n", self.context_type));
686 report.push_str(&format!(
687 "Status: {}\n",
688 if self.success {
689 "✅ Success"
690 } else {
691 "❌ Failed"
692 }
693 ));
694
695 if let Some(duration) = self.duration() {
696 report.push_str(&format!("Duration: {:.2}s\n", duration.as_secs_f64()));
697 }
698
699 if !self.operations_completed.is_empty() {
700 report.push_str(&format!(
701 "\nOperations Completed ({}):\n",
702 self.operations_completed.len()
703 ));
704 for (i, op) in self.operations_completed.iter().enumerate() {
705 let status = if op.success { "✅" } else { "❌" };
706 report.push_str(&format!(" {}. {} {}\n", i + 1, status, op.description));
707 }
708 }
709
710 if !self.conflicts_detected.is_empty() {
711 report.push_str(&format!(
712 "\nConflicts Detected ({}):\n",
713 self.conflicts_detected.len()
714 ));
715 for (i, conflict) in self.conflicts_detected.iter().enumerate() {
716 report.push_str(&format!(
717 " {}. {} in {}\n",
718 i + 1,
719 conflict.conflict_type,
720 conflict.file_path
721 ));
722 }
723 }
724
725 if let Some(error) = &self.error_message {
726 report.push_str(&format!("\nError: {}\n", error));
727 }
728
729 report
730 }
731
732 #[allow(dead_code)]
733 pub fn format_accessible_summary(&self) -> String {
734 let mut summary = String::new();
735
736 summary.push_str(&format!(
737 "Sync operation in {} context. ",
738 self.context_type
739 ));
740
741 if self.success {
742 summary.push_str("Completed successfully. ");
743 } else {
744 summary.push_str("Failed. ");
745 }
746
747 if let Some(duration) = self.duration() {
748 summary.push_str(&format!(
749 "Duration: {:.2} seconds. ",
750 duration.as_secs_f64()
751 ));
752 }
753
754 summary.push_str(&format!(
755 "{} operations completed. ",
756 self.operations_completed.len()
757 ));
758
759 if !self.conflicts_detected.is_empty() {
760 summary.push_str(&format!(
761 "{} conflicts detected. ",
762 self.conflicts_detected.len()
763 ));
764 }
765
766 if let Some(error) = &self.error_message {
767 summary.push_str(&format!("Error: {}. ", error));
768 }
769
770 summary
771 }
772}
773
774#[allow(dead_code)]
776fn mark_task_completed(task_id: &str) -> Result<()> {
777 let tasks_path = PathBuf::from("specs/001-multi-agent-toolkit/tasks.md");
778
779 if !tasks_path.exists() {
780 return Ok(()); }
782
783 let content =
784 std::fs::read_to_string(&tasks_path).with_context(|| "Failed to read tasks.md")?;
785
786 let updated_content =
788 content.replace(&format!("- [ ] {}", task_id), &format!("- [x] {}", task_id));
789
790 if updated_content != content {
791 std::fs::write(&tasks_path, updated_content)
792 .with_context(|| "Failed to update tasks.md")?;
793 }
794
795 Ok(())
796}
797
798#[cfg(test)]
799mod tests {
800 use super::*;
801
802 #[test]
803 fn test_extract_agent_id_from_path() {
804 assert_eq!(
805 extract_agent_id_from_path("agents/1"),
806 Some("1".to_string())
807 );
808 assert_eq!(
809 extract_agent_id_from_path("agents/2/"),
810 Some("2".to_string())
811 );
812 assert_eq!(
813 extract_agent_id_from_path("agents/agent-3"),
814 Some("agent-3".to_string())
815 );
816 assert_eq!(
817 extract_agent_id_from_path("agents/agent_4"),
818 Some("agent_4".to_string())
819 );
820 assert_eq!(extract_agent_id_from_path("other/path"), None);
821 assert_eq!(extract_agent_id_from_path("agents/"), None);
822 }
823
824 #[test]
825 fn test_determine_sync_context() {
826 let _context = determine_sync_context(None);
829 }
830
831 #[test]
832 fn test_conflict_resolution_parsing() {
833 let _valid_manual = "manual";
835 let _valid_theirs = "auto-theirs";
836 let _valid_ours = "auto-ours";
837
838 }
841}