1use crate::{Runner, output::path_line, process::args, worktree_path::registered_path};
3use std::path::{Path, PathBuf};
4use workyard_core::{
5 Control, GitFacts, ObservationGit, Participant, Phase, Problem, ProblemCode, ProblemDetail,
6};
7
8struct RegisteredWorktree {
9 path: PathBuf,
10 git_dir: PathBuf,
11 common: PathBuf,
12 identity: String,
13}
14
15struct Observation<'a> {
16 runner: &'a Runner,
17}
18
19impl ObservationGit for Runner {
20 async fn observe(
21 &self,
22 participant: &Participant,
23 control: &Control,
24 ) -> Result<GitFacts, Problem> {
25 Observation { runner: self }
26 .observe(participant, control)
27 .await
28 }
29}
30
31impl Observation<'_> {
32 async fn observe(
33 &self,
34 participant: &Participant,
35 control: &Control,
36 ) -> Result<GitFacts, Problem> {
37 let repository = if participant.worktree_identity.is_some() {
38 self.runner
39 .placement_repository(participant, None, control)
40 .await?
41 .source
42 } else {
43 self.locate_backing(participant, control).await?
44 };
45 let current = match self
46 .find_participant(&repository, participant, control)
47 .await
48 {
49 Ok(Some(current)) => current,
50 Ok(None) => return self.inspect_unresolved(participant, None, control).await,
51 Err(problem) => {
52 return self
53 .inspect_unresolved(participant, Some(problem), control)
54 .await;
55 }
56 };
57
58 if participant.worktree_identity.is_some() && current.path != participant.destination {
59 let preview = self
60 .runner
61 .inspect_placement(participant, None, control)
62 .await?;
63 if preview.competing {
64 return Err(preview.diagnostic());
65 }
66 }
67 self.inspect_worktree(current, repository, control).await
68 }
69
70 async fn inspect_unresolved(
72 &self,
73 participant: &Participant,
74 original: Option<Problem>,
75 control: &Control,
76 ) -> Result<GitFacts, Problem> {
77 let detail = if participant.worktree_identity.is_some() {
78 match self
79 .runner
80 .inspect_placement(participant, None, control)
81 .await
82 {
83 Ok(placement) if placement.needs_repair && original.is_none() => {
84 return Err(placement.diagnostic());
85 }
86 Err(problem) => problem.detail.filter(|detail| {
87 matches!(detail.as_ref(), ProblemDetail::MissingWorktree { .. })
88 }),
89 _ => None,
90 }
91 } else {
92 None
93 };
94
95 if let Some(mut problem) = original {
96 if detail.is_some() {
97 problem.detail = detail;
98 }
99 return Err(problem);
100 }
101
102 if detail.is_none() {
105 control.check()?;
106 }
107 let mut facts = missing_participant(participant)?;
108 if let Some(problem) = &mut facts.problem
109 && detail.is_some()
110 {
111 problem.detail = detail;
112 }
113 Ok(facts)
114 }
115
116 async fn find_participant(
117 &self,
118 repository: &Path,
119 participant: &Participant,
120 control: &Control,
121 ) -> Result<Option<RegisteredWorktree>, Problem> {
122 let output = self
123 .runner
124 .checked(
125 repository,
126 &args(&["worktree", "list", "--porcelain", "-z"]),
127 control,
128 )
129 .await?;
130
131 let mut current = None;
132 for field in output.split(|byte| *byte == 0) {
133 control.check()?;
134 let Some(bytes) = field.strip_prefix(b"worktree ") else {
135 continue;
136 };
137 let path = crate::output::path_field(bytes)
138 .map_err(|_| changed("Invalid Git worktree path."))?;
139 let path = registered_path(path, &participant.destination);
140
141 match path.try_exists() {
144 Ok(true) => {}
145 Err(error) if path == participant.destination => {
146 return Err(Problem::io("Inspect registered worktree location", error));
147 }
148 Ok(false) | Err(_) => continue,
149 }
150
151 let candidate = match self.registered_worktree(&path, control).await {
152 Ok(candidate) => candidate,
153 Err(problem) if problem.code == ProblemCode::Cancelled => return Err(problem),
154 Err(problem) if path == participant.destination => return Err(problem),
155 Err(_) => continue,
156 };
157 let matches = participant
158 .worktree_identity
159 .as_ref()
160 .map_or(path == participant.destination, |expected| {
161 expected == &candidate.identity
162 });
163 if !matches {
164 continue;
165 }
166
167 if workyard_system::directory_identity(&candidate.common)?
168 != participant.backing_identity
169 {
170 return Err(changed("Registered participant backing identity differs."));
171 }
172 if current.replace(candidate).is_some() {
173 return Err(changed(
174 "Several registrations match the participant identity.",
175 ));
176 }
177 }
178
179 Ok(current)
180 }
181
182 async fn registered_worktree(
183 &self,
184 path: &Path,
185 control: &Control,
186 ) -> Result<RegisteredWorktree, Problem> {
187 let git_dir = self.git_directory(path, "--git-dir", control).await?;
188 let identity = workyard_system::directory_identity(&git_dir)?;
189 Ok(RegisteredWorktree {
190 path: path.into(),
191 git_dir,
192 identity,
193 common: self
194 .git_directory(path, "--git-common-dir", control)
195 .await?,
196 })
197 }
198
199 async fn inspect_worktree(
200 &self,
201 current: RegisteredWorktree,
202 repository: PathBuf,
203 control: &Control,
204 ) -> Result<GitFacts, Problem> {
205 let branch = self
206 .runner
207 .checked(
208 ¤t.path,
209 &args(&["rev-parse", "--abbrev-ref", "HEAD"]),
210 control,
211 )
212 .await?;
213 let branch = std::str::from_utf8(&branch)
214 .map_err(|_| changed("Invalid Git branch output."))?
215 .trim_end_matches(['\r', '\n'])
216 .to_owned();
217
218 let status = self
219 .runner
220 .checked(
221 ¤t.path,
222 &args(&[
223 "--no-optional-locks",
224 "status",
225 "--porcelain",
226 "-z",
227 "--untracked-files=normal",
228 ]),
229 control,
230 )
231 .await?;
232 let conflicts = self
233 .runner
234 .checked(
235 ¤t.path,
236 &args(&["ls-files", "--unmerged", "-z"]),
237 control,
238 )
239 .await?;
240 let operation_in_progress =
241 crate::operations::operations_present(¤t.git_dir, ¤t.common)?;
242
243 Ok(GitFacts {
244 common_dir: Some(current.common),
245 repository_source: Some(repository),
246 problem: None,
247 path: Some(current.path),
248 branch: Some(branch),
249 dirty: !status.is_empty(),
250 conflicted: !conflicts.is_empty(),
251 operation_in_progress,
252 })
253 }
254
255 async fn git_directory(
256 &self,
257 path: &Path,
258 selector: &str,
259 control: &Control,
260 ) -> Result<PathBuf, Problem> {
261 let output = self
262 .runner
263 .checked(
264 path,
265 &args(&["rev-parse", "--path-format=absolute", selector]),
266 control,
267 )
268 .await?;
269 path_line(&output).map_err(|_| changed("Invalid Git directory output."))
270 }
271
272 async fn locate_backing(
273 &self,
274 participant: &Participant,
275 control: &Control,
276 ) -> Result<PathBuf, Problem> {
277 for path in [
278 &participant.source,
279 &participant.destination,
280 &participant.common_dir,
281 ] {
282 if !path
283 .try_exists()
284 .map_err(|e| Problem::io("Inspect cached Git location", e))?
285 {
286 continue;
287 }
288 let common = self
289 .git_directory(path, "--git-common-dir", control)
290 .await?;
291 if workyard_system::directory_identity(&common)? != participant.backing_identity {
292 return Err(changed(
293 "Cached Git location now refers to different backing storage.",
294 ));
295 }
296 return Ok(path.clone());
297 }
298 Err(changed("Backing Git storage is unreachable."))
299 }
300}
301
302fn missing_participant(participant: &Participant) -> Result<GitFacts, Problem> {
303 if participant
304 .destination
305 .try_exists()
306 .map_err(|error| Problem::io("Inspect recorded destination", error))?
307 {
308 return Err(changed(
309 "Recorded destination exists but its participant identity is not registered.",
310 ));
311 }
312 let problem = if matches!(participant.phase, Phase::WorktreeCreated | Phase::Completed) {
313 Some(changed(
314 "Previously created participant worktree is missing. Restore access or repair its Git registration before recovery.",
315 ))
316 } else {
317 None
318 };
319 Ok(GitFacts {
320 common_dir: None,
321 repository_source: None,
322 problem,
323 path: None,
324 branch: None,
325 dirty: false,
326 conflicted: false,
327 operation_in_progress: false,
328 })
329}
330
331fn changed(message: &str) -> Problem {
332 Problem::new(ProblemCode::RepositoryChanged, message).remedy("Inspect git worktree list --porcelain and git status. Repair moved Git relationships with git worktree repair from the main clone; preserve worktrees and state.")
333}