1mod registrations;
2
3use crate::operations::operations_present;
4use crate::{Repository, Runner, process::args, worktree_path::registered_path};
5use registrations::registrations;
6use std::path::PathBuf;
7use workyard_core::{Control, Participant, Problem, ProblemCode, RecoveryGit, RecoveryObservation};
8
9struct Reconciliation<'a> {
10 runner: &'a Runner,
11 participant: &'a Participant,
12 task: &'a str,
13 control: &'a Control,
14}
15
16impl RecoveryGit for Runner {
17 async fn recovery_relationship(
18 &self,
19 participant: &Participant,
20 control: &Control,
21 ) -> Result<Option<workyard_core::Relationship>, Problem> {
22 if participant.worktree_identity.is_none() {
23 return Ok(None);
24 }
25 let reconciliation = Reconciliation {
26 runner: self,
27 participant,
28 task: "",
29 control,
30 };
31 let repository = reconciliation.locate_repository().await?;
32 workyard_core::AmendGit::relationship(self, &repository.into(), participant, control)
33 .await
34 .map(Some)
35 }
36
37 async fn repair_relationship(
38 &self,
39 repository: &workyard_core::Repository,
40 participant: &Participant,
41 control: &Control,
42 ) -> Result<(), Problem> {
43 workyard_core::AmendGit::repair(self, repository, participant, control).await
44 }
45
46 async fn reconcile(
47 &self,
48 participant: &Participant,
49 task: &str,
50 control: &Control,
51 ) -> Result<RecoveryObservation, Problem> {
52 Reconciliation {
53 runner: self,
54 participant,
55 task,
56 control,
57 }
58 .run()
59 .await
60 }
61}
62
63impl Reconciliation<'_> {
64 async fn run(&self) -> Result<RecoveryObservation, Problem> {
65 let repository = self.locate_repository().await?;
66 if self.participant.worktree_identity.is_some() {
67 let placement = self
68 .runner
69 .inspect_placement(self.participant, None, self.control)
70 .await?;
71 if placement.competing {
72 return Err(placement.diagnostic());
73 }
74 }
75 let destination = self.registered_destination(&repository).await?;
76 let operation_in_progress = match &destination {
77 Some(path) => self.inspect_registered(&repository, path).await?,
78 None => {
79 if self
80 .participant
81 .destination
82 .try_exists()
83 .map_err(|error| Problem::io("Inspect participant destination", error))?
84 {
85 return Err(changed(
86 "Participant destination exists without its registered task worktree. Inspect git worktree list and repair registration; do not replace its files.",
87 ));
88 }
89 operations_present(&repository.common_dir, &repository.common_dir)?
90 }
91 };
92 Ok(RecoveryObservation {
93 repository: repository.into(),
94 destination,
95 operation_in_progress,
96 })
97 }
98
99 async fn locate_repository(&self) -> Result<Repository, Problem> {
100 if self.participant.worktree_identity.is_some() {
101 let placement = self
102 .runner
103 .placement_repository(self.participant, None, self.control)
104 .await?;
105 let mut repository = Repository::from(&placement);
106 repository.remote = self.participant.remote.clone();
108 return Ok(repository);
109 }
110 for path in [
112 &self.participant.source,
113 &self.participant.destination,
114 &self.participant.common_dir,
115 ] {
116 if !path
117 .try_exists()
118 .map_err(|error| Problem::io("Inspect cached Git location", error))?
119 {
120 continue;
121 }
122
123 let repository = Repository::inspect(
124 self.runner,
125 path,
126 self.participant.remote.as_deref(),
127 self.control,
128 )
129 .await?;
130 if repository.identity != self.participant.backing_identity {
131 return Err(changed(
132 "Cached Git location points to different backing storage.",
133 ));
134 }
135
136 return Ok(repository);
137 }
138
139 Err(changed(
140 "Backing Git storage is unreachable. Repair moved Git relationships with git worktree repair from the actual main clone, then retry.",
141 ))
142 }
143
144 async fn registered_destination(
145 &self,
146 repository: &Repository,
147 ) -> Result<Option<PathBuf>, Problem> {
148 let output = self
149 .runner
150 .checked(
151 &repository.source,
152 &args(&["worktree", "list", "--porcelain", "-z"]),
153 self.control,
154 )
155 .await?;
156 let branch = format!("refs/heads/{}", self.task);
157 let matching: Vec<_> = registrations(&output)?
158 .into_iter()
159 .filter(|(_, candidate)| candidate == &branch)
160 .collect();
161 if matching.len() > 1 {
162 return Err(changed(
163 "Several worktrees use the task branch; ownership is ambiguous.",
164 ));
165 }
166
167 let destination = &self.participant.destination;
168 Ok(matching
169 .into_iter()
170 .next()
171 .map(|(path, _)| registered_path(path, destination)))
172 }
173
174 async fn inspect_registered(
175 &self,
176 repository: &Repository,
177 path: &std::path::Path,
178 ) -> Result<bool, Problem> {
179 let participant = self.participant;
180 if matches!(
182 participant.phase,
183 workyard_core::Phase::NotStarted | workyard_core::Phase::Fetching
184 ) || (participant.phase == workyard_core::Phase::Creating
185 && participant.worktree_identity.is_none())
186 {
187 return Err(changed(
188 "A worktree already uses a not-started participant branch; recovery cannot adopt it.",
189 ));
190 }
191
192 let current = Repository::local(self.runner, path, self.control).await?;
193 if current.identity != participant.backing_identity {
194 return Err(changed("Registered worktree backing identity differs."));
195 }
196
197 let output = self
198 .runner
199 .checked(
200 path,
201 &args(&["rev-parse", "--path-format=absolute", "--git-dir"]),
202 self.control,
203 )
204 .await?;
205 let git_dir =
206 crate::output::path_line(&output).map_err(|_| changed("Invalid Git path output."))?;
207 if let Some(expected) = &participant.worktree_identity {
208 if &workyard_system::directory_identity(&git_dir)? != expected {
209 return Err(changed(
210 "Worktree administrative identity changed; recovery cannot adopt its replacement.",
211 ));
212 }
213 } else if path != participant.destination {
214 return Err(changed(
215 "Legacy worktree has no administrative identity evidence to verify an external move.",
216 ));
217 }
218
219 let conflicts = self
220 .runner
221 .checked(path, &args(&["ls-files", "--unmerged", "-z"]), self.control)
222 .await?;
223 let branch_lock = repository
224 .common_dir
225 .join("refs/heads")
226 .join(format!("{}.lock", self.task));
227 Ok(operations_present(&git_dir, &repository.common_dir)?
228 || !conflicts.is_empty()
229 || branch_lock
230 .try_exists()
231 .map_err(|error| Problem::io("Inspect task branch lock", error))?)
232 }
233}
234
235fn changed(message: &str) -> Problem {
236 Problem::new(ProblemCode::RepositoryChanged, message).remedy("Inspect git worktree list --porcelain and git status at the recorded paths. Repair Git relationships manually; preserve worktrees and native Git locks.")
237}