1use std::path::{Path, PathBuf};
17
18use crate::adapters::adapter;
19use crate::apply::exec::{ApplyReport, ApplyRequest, apply_in, swap_file};
20use crate::apply::ledger::{EntryKind, Ledger};
21use crate::apply::plan::{PlanOptions, read_target};
22use crate::apply::{ApplyEnv, backup};
23use crate::error::{CoreError, ErrorCode};
24use crate::formats::Document;
25use crate::model::TomlDocument;
26use crate::model::applied::ApplyTrigger;
27use crate::model::machine::MachineOverlay;
28use crate::secrets::catalog::overlay_path;
29use crate::store::diff::trailer_entities;
30use crate::store::merge::Files;
31use crate::store::{
32 CommitId, LOCK_TIMEOUT, Machine, Operation, Store, StoreLock, StoreRead, entity_paths,
33};
34
35const SHARED_MANIFEST: &str = "project.toml";
37const LOCAL_MANIFEST: &str = "project.local.toml";
38
39#[derive(Debug, Clone)]
41pub struct RestoreRequest {
42 pub target: CommitId,
43 pub entities: Vec<String>,
46 pub confirmed: bool,
48 pub apply: bool,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct ManifestWrite {
55 pub project: String,
56 pub relative: String,
58 pub path: PathBuf,
60 pub shared: bool,
62}
63
64#[derive(Debug, Clone)]
66pub struct RestorePlan {
67 pub target: CommitId,
68 pub head: CommitId,
70 pub files: Vec<String>,
72 pub manifests: Vec<ManifestWrite>,
74 pub unplaced: Vec<String>,
76}
77
78impl RestorePlan {
79 pub fn needs_confirmation(&self) -> bool {
80 self.manifests.iter().any(|manifest| manifest.shared)
81 }
82}
83
84#[derive(Debug)]
86pub struct RestoreReport {
87 pub plan: RestorePlan,
88 pub tag: Option<String>,
90 pub commit: Option<CommitId>,
91 pub written: Vec<PathBuf>,
93 pub apply: Option<ApplyReport>,
94}
95
96fn restorable(file: &str, machine_id: &str) -> bool {
100 match file.strip_prefix("machines/") {
101 Some(name) => name == format!("{machine_id}.toml"),
102 None => true,
103 }
104}
105
106pub fn prepare(
108 store: &Store<'_>,
109 machine_id: &str,
110 request: &RestoreRequest,
111) -> Result<RestorePlan, CoreError> {
112 let mut selected: Vec<String> = Vec::new();
113 for entity in &request.entities {
114 let paths = entity_paths(entity);
115 if paths.is_empty() {
116 return Err(CoreError::new(
117 ErrorCode::InvalidValue,
118 format!(
119 "unknown entity {entity:?}; expected server/<id>, skill/<id>, project/<id>, \
120 machine/<id>, secrets, clients, settings or sources"
121 ),
122 ));
123 }
124 if entity
125 .strip_prefix("machine/")
126 .is_some_and(|id| id != machine_id)
127 {
128 return Err(CoreError::new(
129 ErrorCode::InvalidValue,
130 format!("{entity} belongs to another machine; only that machine writes its files"),
131 ));
132 }
133 selected.extend(paths);
134 }
135 let head = store.head()?;
136 let files: Vec<String> = store
137 .changed_files(&head, &request.target)?
138 .into_iter()
139 .filter(|file| restorable(file, machine_id))
140 .filter(|file| {
141 selected.is_empty()
142 || selected
143 .iter()
144 .any(|path| file == path || file.starts_with(&format!("{path}/")))
145 })
146 .collect();
147
148 let target = store.revision(&request.target)?;
149 let overlay_file = overlay_path(machine_id)?;
151 let overlay_text = if files.contains(&overlay_file) {
152 target.read_file(&overlay_file)?
153 } else {
154 store.read_file(&overlay_file)?
155 };
156 let overlay = overlay_text
157 .and_then(|text| TomlDocument::<MachineOverlay>::parse(&text).ok())
158 .map(TomlDocument::into_value);
159 let mut manifests = Vec::new();
160 let mut unplaced = Vec::new();
161 for file in &files {
162 let Some((project, name)) = manifest_parts(file) else {
163 continue;
164 };
165 let Some(bytes) = target.read_bytes(file)? else {
166 continue;
168 };
169 let folder = overlay
172 .as_ref()
173 .and_then(|overlay| overlay.projects.as_ref())
174 .and_then(|projects| projects.get(project))
175 .map(|project| PathBuf::from(&project.path))
176 .filter(|folder| folder.is_absolute() && store.fs.is_dir(folder));
177 let Some(folder) = folder else {
178 unplaced.push(file.clone());
179 continue;
180 };
181 let path = crate::layering::manifest::manifest_dir(store.fs, &folder).join(name);
182 if read_target(store.fs, &path)?.as_deref() == Some(bytes.as_slice()) {
183 continue;
184 }
185 manifests.push(ManifestWrite {
186 project: project.to_owned(),
187 relative: file.clone(),
188 path,
189 shared: name == SHARED_MANIFEST,
190 });
191 }
192 Ok(RestorePlan {
193 target: request.target.clone(),
194 head,
195 files,
196 manifests,
197 unplaced,
198 })
199}
200
201fn manifest_parts(file: &str) -> Option<(&str, &str)> {
203 let rest = file.strip_prefix("projects/")?;
204 let (id, name) = rest.split_once('/')?;
205 matches!(name, SHARED_MANIFEST | LOCAL_MANIFEST).then_some((id, name))
206}
207
208pub fn restore(
213 store: &Store<'_>,
214 ax: &ApplyEnv<'_>,
215 request: &RestoreRequest,
216) -> Result<RestoreReport, CoreError> {
217 let summary = format!("restore: {}", request.target.short());
218 restore_as(store, ax, request, "store.restore", summary, None)
219}
220
221pub(crate) fn restore_as(
228 store: &Store<'_>,
229 ax: &ApplyEnv<'_>,
230 request: &RestoreRequest,
231 op: &str,
232 summary: String,
233 expected_head: Option<&CommitId>,
234) -> Result<RestoreReport, CoreError> {
235 let machine = Machine::load_or_create(ax.env, ax.fs, &ax.home.state_dir())?;
236 let plan = prepare(store, &machine.id, request)?;
237 if expected_head.is_some_and(|head| *head != plan.head) {
238 return Err(CoreError::new(
239 ErrorCode::FileChangedDuringApply,
240 "the store changed since the pending changes were read; review them again",
241 ));
242 }
243 if plan.needs_confirmation() && !request.confirmed {
244 let files: Vec<String> = plan
245 .manifests
246 .iter()
247 .filter(|manifest| manifest.shared)
248 .map(|manifest| manifest.path.display().to_string())
249 .collect();
250 return Err(CoreError::new(
251 ErrorCode::ConfirmationRequired,
252 format!(
253 "the restore writes shared project manifests a team may use ({}); confirm to \
254 write them back",
255 files.join(", ")
256 ),
257 ));
258 }
259 if plan.files.is_empty() {
260 return Ok(RestoreReport {
261 plan,
262 tag: None,
263 commit: None,
264 written: Vec::new(),
265 apply: None,
266 });
267 }
268 let mut operation = Operation::new(op, summary);
269 for entity in trailer_entities(&plan.files) {
270 operation = operation.entity(entity);
271 }
272 let committed = store.transaction(operation, |tx| {
273 if tx.store().head()? != plan.head {
276 return Err(CoreError::new(
277 ErrorCode::FileChangedDuringApply,
278 "the store changed while the restore was being prepared; run it again",
279 ));
280 }
281 let source = tx.store().revision(&plan.target)?;
282 let mut contents = Vec::with_capacity(plan.files.len());
283 for file in &plan.files {
284 contents.push((file.clone(), source.read_bytes(file)?));
285 }
286 drop(source);
287 for (file, content) in contents {
288 match content {
289 Some(bytes) => tx.write(&file, bytes)?,
290 None => tx.remove(&file)?,
291 }
292 }
293 if request.apply {
294 let request = ApplyRequest {
295 options: PlanOptions::default(),
296 trigger: ApplyTrigger::Restore,
297 };
298 apply_in(tx, ax, &request).map(Some)
299 } else {
300 Ok(None)
301 }
302 })?;
303 let tag = store.create_auto_tag_at("pre-restore", &plan.head)?;
305
306 let target = store.revision(&plan.target)?;
307 let mut written = Vec::new();
308 for manifest in &plan.manifests {
309 let Some(bytes) = target.read_bytes(&manifest.relative)? else {
310 continue;
311 };
312 crate::apply::write_atomic(ax.fs, &manifest.path, &bytes)?;
313 written.push(manifest.path.clone());
314 }
315 Ok(RestoreReport {
316 plan,
317 tag: Some(tag),
318 commit: committed.commit,
319 written,
320 apply: committed.value,
321 })
322}
323
324pub fn restore_tree(
330 store: &Store<'_>,
331 ax: &ApplyEnv<'_>,
332 files: &Files,
333 label: &str,
334 apply: bool,
335) -> Result<RestoreReport, CoreError> {
336 let machine = Machine::load_or_create(ax.env, ax.fs, &ax.home.state_dir())?;
337 let head = store.head()?;
338 let current = store.files_at(&head)?;
339 let changed: Vec<String> = current
340 .keys()
341 .chain(files.keys())
342 .filter(|file| restorable(file, &machine.id))
343 .filter(|file| current.get(*file) != files.get(*file))
344 .cloned()
345 .collect::<std::collections::BTreeSet<_>>()
346 .into_iter()
347 .collect();
348 let plan = RestorePlan {
349 target: head.clone(),
350 head: head.clone(),
351 files: changed,
352 manifests: Vec::new(),
353 unplaced: Vec::new(),
354 };
355 if plan.files.is_empty() {
356 return Ok(RestoreReport {
357 plan,
358 tag: None,
359 commit: None,
360 written: Vec::new(),
361 apply: None,
362 });
363 }
364 let mut operation = Operation::new("store.restore", format!("restore: from {label}"));
365 for entity in trailer_entities(&plan.files) {
366 operation = operation.entity(entity);
367 }
368 let committed = store.transaction(operation, |tx| {
369 if tx.store().head()? != plan.head {
370 return Err(CoreError::new(
371 ErrorCode::FileChangedDuringApply,
372 "the store changed while the restore was being prepared; run it again",
373 ));
374 }
375 for file in &plan.files {
376 match files.get(file) {
377 Some(bytes) => tx.write(file, bytes.clone())?,
378 None => tx.remove(file)?,
379 }
380 }
381 if apply {
382 let request = ApplyRequest {
383 options: PlanOptions::default(),
384 trigger: ApplyTrigger::Restore,
385 };
386 apply_in(tx, ax, &request).map(Some)
387 } else {
388 Ok(None)
389 }
390 })?;
391 let tag = store.create_auto_tag_at("pre-restore", &plan.head)?;
392 Ok(RestoreReport {
393 plan,
394 tag: Some(tag),
395 commit: committed.commit,
396 written: Vec::new(),
397 apply: committed.value,
398 })
399}
400
401#[derive(Debug)]
403pub enum FileOutcome {
404 Restored { previous: Option<PathBuf> },
406 Unchanged,
408 Failed(CoreError),
410 Removed,
414}
415
416#[derive(Debug)]
418pub struct FileRestore {
419 pub file: PathBuf,
420 pub outcome: FileOutcome,
421}
422
423pub fn restore_files(
433 ax: &ApplyEnv<'_>,
434 run: &str,
435 only: Option<&Path>,
436) -> Result<Vec<FileRestore>, CoreError> {
437 let fs = ax.fs;
438 let state_dir = ax.home.state_dir();
439 let _lock = StoreLock::acquire(fs, &state_dir, LOCK_TIMEOUT)?;
440 let apply_id = run;
441 let removed: Vec<PathBuf> = backup::removed_backups(fs, &state_dir, run_apply_id(run))
444 .unwrap_or_default()
445 .into_iter()
446 .filter(|file| only.is_none_or(|only| same_path(ax, file, only)))
447 .collect();
448 let run = match find_run(ax, run) {
450 Ok(run) => Some(run),
451 Err(err) if err.code() == ErrorCode::NotFound && !removed.is_empty() => None,
452 Err(err) => return Err(err),
453 };
454 let entries = match &run {
455 Some(run) => fs.read_dir(run).map_err(|err| {
456 CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}")).with_path(run)
457 })?,
458 None => Vec::new(),
459 };
460 let mut files: Vec<(PathBuf, PathBuf)> = entries
461 .into_iter()
462 .filter_map(|backup| {
463 let name = backup.file_name()?.to_str()?.to_owned();
464 let original = PathBuf::from(backup::decode_path(&name)?);
465 Some((original, backup))
466 })
467 .filter(|(original, _)| only.is_none_or(|only| same_path(ax, original, only)))
468 .filter(|(original, _)| !removed.iter().any(|file| same_path(ax, original, file)))
471 .collect();
472 files.sort();
473 if files.is_empty() && removed.is_empty() {
474 return Err(CoreError::new(
475 ErrorCode::NotFound,
476 match only {
477 Some(only) => format!("apply {apply_id} has no backup of {}", only.display()),
478 None => format!("apply {apply_id} has no file backups"),
479 },
480 ));
481 }
482 let mut results: Vec<FileRestore> = removed
483 .into_iter()
484 .map(|file| FileRestore {
485 file,
486 outcome: FileOutcome::Removed,
487 })
488 .collect();
489 let Some(run) = run else {
490 return Ok(results);
491 };
492 let run_id = run
496 .file_name()
497 .and_then(|name| name.to_str())
498 .and_then(|name| name.split_once('-'))
499 .map_or(apply_id, |(_, id)| id);
500 let base = run_id
501 .strip_prefix("restore-")
502 .and_then(|rest| rest.split('-').next())
503 .unwrap_or(run_id);
504 let undo_id = format!(
505 "restore-{base}-{}",
506 crate::model::ids::new_ulid(ax.env.now())?
507 );
508 let undo_dir = backup::run_dir(ax.home, ax.env.now(), &undo_id);
509 let mut ledger = Ledger::load(fs, &state_dir)?;
510 for (file, saved) in files {
511 let outcome = restore_one(ax, &undo_dir, &file, &saved).and_then(|outcome| {
514 if matches!(outcome, FileOutcome::Restored { .. }) {
515 refresh_ledger(ax, &mut ledger, &file)?;
516 ledger.save(fs, &state_dir)?;
517 }
518 Ok(outcome)
519 });
520 let outcome = outcome.unwrap_or_else(|err| FileOutcome::Failed(err.with_path(&file)));
521 results.push(FileRestore { file, outcome });
522 }
523 Ok(results)
524}
525
526fn run_apply_id(run: &str) -> &str {
529 match run.get(..16).and_then(backup::parse_timestamp) {
530 Some(_) if run.as_bytes().get(16) == Some(&b'-') => &run[17..],
531 _ => run,
532 }
533}
534
535fn find_run(ax: &ApplyEnv<'_>, run: &str) -> Result<PathBuf, CoreError> {
538 let root = ax.home.backups_dir().join(backup::FILES_DIR);
539 let runs = if ax.fs.is_dir(&root) {
540 ax.fs.read_dir(&root).map_err(|err| {
541 CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}"))
542 .with_path(&root)
543 })?
544 } else {
545 Vec::new()
546 };
547 let runs: Vec<(String, PathBuf)> = runs
548 .into_iter()
549 .filter(|dir| ax.fs.is_dir(dir))
550 .filter_map(|dir| Some((dir.file_name()?.to_str()?.to_owned(), dir)))
551 .collect();
552 if let Some((_, dir)) = runs.iter().find(|(name, _)| name == run) {
553 return Ok(dir.clone());
554 }
555 runs.into_iter()
558 .filter(|(name, _)| {
559 name.split_once('-')
560 .is_some_and(|(_, id)| id.eq_ignore_ascii_case(run))
561 })
562 .max_by(|a, b| a.0.cmp(&b.0))
563 .map(|(_, dir)| dir)
564 .ok_or_else(|| {
565 CoreError::new(
566 ErrorCode::NotFound,
567 format!("no file backups of {run:?} on this machine"),
568 )
569 })
570}
571
572fn same_path(ax: &ApplyEnv<'_>, a: &Path, b: &Path) -> bool {
573 match ax.env.os() {
574 crate::env::Os::Windows => a
575 .to_string_lossy()
576 .eq_ignore_ascii_case(&b.to_string_lossy()),
577 _ => a == b,
578 }
579}
580
581fn restore_one(
584 ax: &ApplyEnv<'_>,
585 undo_dir: &Path,
586 file: &Path,
587 saved: &Path,
588) -> Result<FileOutcome, CoreError> {
589 let fs = ax.fs;
590 let bytes = fs.read(saved).map_err(|err| {
591 CoreError::new(ErrorCode::IoError, format!("cannot read backup: {err}")).with_path(saved)
592 })?;
593 let current = read_target(fs, file)?;
594 if current.as_deref() == Some(bytes.as_slice()) {
595 return Ok(FileOutcome::Unchanged);
596 }
597 let previous = match ¤t {
598 Some(current) => Some(backup::save(fs, ax.home, undo_dir, file, current)?),
599 None => None,
600 };
601 if !swap_file(fs, file, current.as_deref(), &bytes)? {
602 return Err(CoreError::new(
603 ErrorCode::FileChangedDuringApply,
604 "the file changed while it was being restored; nothing was written",
605 ));
606 }
607 Ok(FileOutcome::Restored { previous })
608}
609
610fn refresh_ledger(ax: &ApplyEnv<'_>, ledger: &mut Ledger, file: &Path) -> Result<(), CoreError> {
617 let name = file.to_string_lossy().into_owned();
618 let bytes = read_target(ax.fs, file)?;
619 let owned: Vec<_> = ledger
620 .entries
621 .iter()
622 .filter(|entry| entry.file == name && entry.kind == EntryKind::McpEntry)
623 .cloned()
624 .collect();
625 for entry in owned {
626 let present = match &bytes {
627 None => false,
628 Some(bytes) => {
629 let Some(format) = adapter(&entry.client)
630 .and_then(|spec| spec.mcp.as_ref())
631 .map(|mcp| mcp.format)
632 else {
633 continue;
634 };
635 let Ok(doc) = Document::parse(bytes, format) else {
636 continue;
637 };
638 let keys = pointer_keys(&entry.container);
639 let keys: Vec<&str> = keys.iter().map(String::as_str).collect();
640 !matches!(doc.get(&keys, &entry.key), Ok(None))
641 }
642 };
643 if !present {
644 ledger.remove(&entry.slot(), &entry.key);
645 }
646 }
647 Ok(())
648}
649
650fn pointer_keys(pointer: &str) -> Vec<String> {
652 pointer
653 .split('/')
654 .skip(1)
655 .map(|key| key.replace("~1", "/").replace("~0", "~"))
656 .collect()
657}