1mod record;
23mod rewrite;
24
25use std::collections::{BTreeMap, HashSet};
26use std::path::{Path, PathBuf};
27
28use sha2::{Digest, Sha256};
29
30use crate::access::{self, ReadOnlyKind};
31use crate::adapters::adapter;
32use crate::apply::exec::{document_value, strip_container, swap_file};
33use crate::apply::ledger::{EntryKind, LedgerEntry};
34use crate::apply::plan::{canonical, list_members, read_target};
35use crate::apply::{ApplyEnv, backup};
36use crate::error::{CoreError, ErrorCode};
37use crate::formats::{Document, NativeValue};
38use crate::fs::Fs;
39use crate::layering::{TrustStore, known_projects, same_folder, same_path};
40use crate::model::applied::Scope;
41use crate::model::ids;
42use crate::paths::SurjectionHome;
43use crate::secrets::catalog::Catalog;
44use crate::skills::link::{
45 self, LinkMethod, SkillLedger, SkillLink, SyncReport, marker_text, remove_copy, remove_link,
46 unchanged_copy,
47};
48use crate::skills::{
49 Entry, LEGACY_MARKER_FILE, MARKER_FILE, SkillsEnv, confine, content_hash, entry,
50 new_folder_access, read_folder, write_files,
51};
52use crate::store::{LOCK_TIMEOUT, Machine, Store, StoreLock, utc_datetime};
53
54#[cfg(test)]
55pub(crate) use record::EJECT_SCHEMA;
56pub use record::{
57 ActiveRun, CopiedSkill, EJECT_FILE, EjectFile, EjectRun, Ejected, EjectedFile, status_at,
58};
59pub use rewrite::{EnvNeed, ManualSecret};
60
61use rewrite::{Analysis, Rewriter, Taken};
62
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct EjectOptions {
66 pub clients: Option<Vec<String>>,
68 pub project: Option<PathBuf>,
71 pub keep_agent_skill: bool,
73 pub execute: bool,
75 #[doc(hidden)]
77 pub hooks: EjectHooks,
78}
79
80#[doc(hidden)]
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84pub struct EjectHooks {
85 pub crash_after_files: Option<usize>,
87 pub fail_skill_move: bool,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93pub enum EntryAction {
94 Keep,
96 Rewrite,
98 Manual,
100 Gone,
102}
103
104impl EntryAction {
105 pub const fn as_str(self) -> &'static str {
106 match self {
107 EntryAction::Keep => "keep",
108 EntryAction::Rewrite => "rewrite",
109 EntryAction::Manual => "manual",
110 EntryAction::Gone => "gone",
111 }
112 }
113}
114
115#[derive(Debug, Clone)]
117pub struct EjectEntry {
118 pub client: String,
119 pub scope: Scope,
120 pub project_id: Option<String>,
121 pub name: String,
122 pub kind: EntryKind,
123 pub action: EntryAction,
124 pub needs_env: Vec<EnvNeed>,
126 pub needs_manual_secret: Vec<ManualSecret>,
128 pub uses_data_folder: bool,
131 pub problem: Option<CoreError>,
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
137pub enum TargetOutcome {
138 Planned,
140 Unchanged,
142 Written,
143 Blocked,
145 Failed,
147}
148
149impl TargetOutcome {
150 pub const fn as_str(self) -> &'static str {
151 match self {
152 TargetOutcome::Planned => "planned",
153 TargetOutcome::Unchanged => "unchanged",
154 TargetOutcome::Written => "written",
155 TargetOutcome::Blocked => "blocked",
156 TargetOutcome::Failed => "failed",
157 }
158 }
159}
160
161#[derive(Debug, Clone)]
163pub struct EjectTarget {
164 pub clients: Vec<String>,
166 pub file: PathBuf,
167 pub project: Option<PathBuf>,
169 pub entries: Vec<EjectEntry>,
170 pub outcome: TargetOutcome,
171 pub backup: Option<PathBuf>,
172 pub read_only: Option<ReadOnlyKind>,
173 pub error: Option<CoreError>,
174 before: Option<Vec<u8>>,
175 after: Option<Vec<u8>>,
176 format: Option<crate::formats::Format>,
177 rewrites: Vec<(Vec<String>, String, String, NativeValue)>,
179 rows: Vec<LedgerEntry>,
180}
181
182impl EjectTarget {
183 pub fn rewrites(&self) -> bool {
185 self.after.is_some()
186 }
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
191pub enum SkillAction {
192 Copy,
194 Keep,
196 Remove,
198 Changed,
200 Gone,
202}
203
204impl SkillAction {
205 pub const fn as_str(self) -> &'static str {
206 match self {
207 SkillAction::Copy => "copy",
208 SkillAction::Keep => "keep",
209 SkillAction::Remove => "remove",
210 SkillAction::Changed => "changed",
211 SkillAction::Gone => "gone",
212 }
213 }
214}
215
216#[derive(Debug, Clone)]
218pub struct EjectSkill {
219 pub client: String,
220 pub scope: Scope,
221 pub project_id: Option<String>,
222 pub skill_id: String,
223 pub path: PathBuf,
224 pub method: LinkMethod,
225 pub action: SkillAction,
226 pub done: bool,
228 pub read_only: Option<ReadOnlyKind>,
229 pub error: Option<CoreError>,
230 row: SkillLink,
231}
232
233#[derive(Debug, Clone, PartialEq, Eq)]
235pub struct EnvSummary {
236 pub name: String,
237 pub secret: Option<String>,
238 pub reference: String,
240 pub entries: Vec<String>,
242}
243
244#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct ManualSummary {
247 pub client: String,
248 pub entry: String,
249 pub file: PathBuf,
250 pub project: Option<PathBuf>,
251 pub secret: ManualSecret,
252}
253
254#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct EnvConflict {
258 pub name: String,
259 pub secrets: Vec<String>,
262 pub entries: Vec<String>,
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
268pub enum StillReason {
269 Manual,
271 UsesDataFolder,
273 Blocked,
276 Failed,
278 SkillLink,
280}
281
282impl StillReason {
283 pub const fn as_str(self) -> &'static str {
284 match self {
285 StillReason::Manual => "manual",
286 StillReason::UsesDataFolder => "uses_data_folder",
287 StillReason::Blocked => "blocked",
288 StillReason::Failed => "failed",
289 StillReason::SkillLink => "skill_link",
290 }
291 }
292}
293
294#[derive(Debug, Clone, PartialEq, Eq)]
297pub struct StillNeeded {
298 pub client: String,
299 pub entry: Option<String>,
301 pub file: PathBuf,
303 pub project: Option<PathBuf>,
304 pub reason: StillReason,
305 pub detail: Option<String>,
306}
307
308#[derive(Debug, Clone)]
310pub struct EjectReport {
311 pub eject_id: Option<String>,
314 pub executed: bool,
315 pub targets: Vec<EjectTarget>,
316 pub skills: Vec<EjectSkill>,
317 pub all: bool,
319 pub unfinished: Option<String>,
321}
322
323impl EjectReport {
324 pub fn env(&self) -> Vec<EnvSummary> {
326 let mut out: Vec<EnvSummary> = Vec::new();
327 for target in &self.targets {
328 for entry in &target.entries {
329 for need in &entry.needs_env {
330 let label = format!("{}: {}", entry.client, entry.name);
331 match out.iter_mut().find(|summary| summary.name == need.name) {
332 Some(summary) => {
333 if !summary.entries.contains(&label) {
334 summary.entries.push(label);
335 }
336 }
337 None => out.push(EnvSummary {
338 name: need.name.clone(),
339 secret: need.secret.clone(),
340 reference: need.reference.clone(),
341 entries: vec![label],
342 }),
343 }
344 }
345 }
346 }
347 out
348 }
349
350 pub fn conflicts(&self) -> Vec<EnvConflict> {
352 let env = self.env();
353 let mut out: Vec<EnvConflict> = Vec::new();
354 for item in self.manual() {
355 let Some(name) = &item.secret.conflicts_with else {
356 continue;
357 };
358 let label = format!("{}: {}", item.client, item.entry);
359 let conflict = match out.iter_mut().position(|c| &c.name == name) {
360 Some(index) => &mut out[index],
361 None => {
362 let first = env.iter().find(|summary| &summary.name == name);
363 out.push(EnvConflict {
364 name: name.clone(),
365 secrets: first
366 .map(|s| s.secret.clone().unwrap_or_else(|| s.reference.clone()))
367 .into_iter()
368 .collect(),
369 entries: first.map(|s| s.entries.clone()).unwrap_or_default(),
370 });
371 out.last_mut().expect("pushed")
372 }
373 };
374 if !conflict.secrets.contains(&item.secret.secret) {
375 conflict.secrets.push(item.secret.secret.clone());
376 }
377 if !conflict.entries.contains(&label) {
378 conflict.entries.push(label);
379 }
380 }
381 out
382 }
383
384 pub fn still_needs_surjection(&self) -> Vec<StillNeeded> {
387 let mut out = Vec::new();
388 for target in &self.targets {
389 let stuck = match target.outcome {
390 TargetOutcome::Blocked => Some(StillReason::Blocked),
391 TargetOutcome::Failed => Some(StillReason::Failed),
392 _ => None,
393 };
394 let detail = target.error.as_ref().map(|err| err.message().to_owned());
395 let mut listed = false;
396 for entry in &target.entries {
397 let reason = match (stuck, entry.action) {
398 (Some(reason), EntryAction::Rewrite | EntryAction::Manual) => Some(reason),
399 (_, EntryAction::Manual) => Some(StillReason::Manual),
400 _ if entry.uses_data_folder => Some(StillReason::UsesDataFolder),
401 _ => None,
402 };
403 if let Some(reason) = reason {
404 listed = true;
405 out.push(StillNeeded {
406 client: entry.client.clone(),
407 entry: Some(entry.name.clone()),
408 file: target.file.clone(),
409 project: target.project.clone(),
410 reason,
411 detail: match reason {
412 StillReason::Manual => {
413 entry.problem.as_ref().map(|err| err.message().to_owned())
414 }
415 _ => detail.clone(),
416 },
417 });
418 }
419 }
420 if let (Some(reason), false, None) = (stuck, listed, target.after.as_ref())
423 && target.entries.iter().all(|e| e.action == EntryAction::Keep)
424 && target.error.is_some()
425 && !target.entries.is_empty()
426 {
427 out.push(StillNeeded {
428 client: target.clients.join(", "),
429 entry: None,
430 file: target.file.clone(),
431 project: target.project.clone(),
432 reason,
433 detail,
434 });
435 }
436 }
437 for skill in &self.skills {
438 if skill.action == SkillAction::Copy && !(self.executed && skill.done) {
439 if !self.executed && skill.error.is_none() {
440 continue;
441 }
442 out.push(StillNeeded {
443 client: skill.client.clone(),
444 entry: Some(skill.skill_id.clone()),
445 file: skill.path.clone(),
446 project: None,
447 reason: StillReason::SkillLink,
448 detail: skill.error.as_ref().map(|err| err.message().to_owned()),
449 });
450 }
451 }
452 out
453 }
454
455 pub fn manual(&self) -> Vec<ManualSummary> {
457 let mut out = Vec::new();
458 for target in &self.targets {
459 for entry in &target.entries {
460 for secret in &entry.needs_manual_secret {
461 out.push(ManualSummary {
462 client: entry.client.clone(),
463 entry: entry.name.clone(),
464 file: target.file.clone(),
465 project: target.project.clone(),
466 secret: secret.clone(),
467 });
468 }
469 }
470 }
471 out
472 }
473
474 pub fn failed(&self) -> bool {
477 self.targets
478 .iter()
479 .any(|target| target.outcome == TargetOutcome::Failed)
480 || self
481 .skills
482 .iter()
483 .any(|skill| skill.error.is_some() && skill.read_only.is_none())
484 }
485}
486
487pub fn status(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<Ejected>, CoreError> {
489 status_at(fs, &home.state_dir())
490}
491
492pub fn eject(
494 store: Option<&Store<'_>>,
495 ax: &ApplyEnv<'_>,
496 options: &EjectOptions,
497) -> Result<EjectReport, CoreError> {
498 check_clients(options.clients.as_deref())?;
499 let fs = ax.fs;
500 let state = ax.home.state_dir();
501 let roots = project_roots(store, ax)?;
502 let project_id = match &options.project {
503 Some(root) => Some(
504 roots
505 .iter()
506 .find(|(_, known)| same_path(known, root))
507 .map(|(id, _)| id.clone())
508 .ok_or_else(|| {
509 CoreError::new(
510 ErrorCode::NotFound,
511 "the folder is not a project this machine knows",
512 )
513 .with_path(root)
514 })?,
515 ),
516 None => None,
517 };
518 let catalog = match store {
519 Some(store) => {
520 let machine = Machine::load(fs, &state)?;
521 Catalog::load(store, machine.as_ref().map(|machine| machine.id.as_str()))?
522 }
523 None => Catalog::default(),
524 };
525 let _lock = if options.execute {
526 Some(StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?)
527 } else {
528 None
529 };
530 let mut ledger = SkillLedger::load(fs, &state)?;
531 let selected = |client: &str, project: Option<&str>| {
532 options
533 .clients
534 .as_ref()
535 .is_none_or(|clients| clients.iter().any(|id| id == client))
536 && project_id.as_deref().is_none_or(|id| project == Some(id))
537 };
538 let rows: Vec<LedgerEntry> = ledger
539 .mcp_mut()
540 .entries
541 .iter()
542 .filter(|row| selected(&row.client, row.project_id.as_deref()))
543 .cloned()
544 .collect();
545 let planner = Planner {
546 ax,
547 catalog: &catalog,
548 roots: &roots,
549 taken: Taken::default(),
550 };
551 let mut targets = planner.targets(rows);
552 let mut skills: Vec<EjectSkill> = ledger
553 .links
554 .iter()
555 .filter(|link| selected(&link.client, link.project_id.as_deref()))
556 .map(|link| plan_skill(fs, link, options.keep_agent_skill))
557 .collect();
558 let all = options.clients.is_none() && project_id.is_none();
559 let mut record = EjectFile::load(fs, &state)?;
560 let unfinished = record
561 .runs
562 .iter()
563 .find(|run| !run.finished && !run.rolled_back)
564 .map(|run| run.id.clone());
565 if !options.execute {
566 return Ok(EjectReport {
567 eject_id: None,
568 executed: false,
569 targets,
570 skills,
571 all,
572 unfinished,
573 });
574 }
575 if let Some(open) = &unfinished {
576 return Err(unfinished_error(open));
577 }
578
579 let now = ax.env.now();
580 let id = ids::new_ulid(now)?;
581 let mut run = EjectRun {
582 id: id.clone(),
583 time: utc_datetime(now).to_string(),
584 clients: options.clients.clone(),
585 project_id: project_id.clone(),
586 finished: false,
587 resumed: false,
588 rolled_back: false,
589 files: Vec::new(),
590 ledger: Vec::new(),
591 skill_links: Vec::new(),
592 copied: Vec::new(),
593 unmarked: Vec::new(),
594 extra: serde_json::Map::new(),
595 };
596 record.runs.push(run.clone());
602 record.save(fs, &state)?;
603 let mut journal = |run: &EjectRun| -> Result<(), CoreError> {
604 if let Some(saved) = record
605 .runs
606 .iter_mut()
607 .rev()
608 .find(|saved| saved.id == run.id)
609 {
610 *saved = run.clone();
611 }
612 record.save(fs, &state)
613 };
614
615 let run_dir = backup::run_dir(ax.home, now, &id);
616 let mut dropped: Vec<LedgerEntry> = Vec::new();
617 let mut written = 0;
618 for target in &mut targets {
619 execute_target(ax, &run_dir, target, &mut |file| {
620 run.files.push(file);
621 journal(&run)
622 });
623 let path = target.file.to_string_lossy().into_owned();
624 if target.outcome == TargetOutcome::Written {
625 written += 1;
626 if options.hooks.crash_after_files == Some(written) {
627 return Err(CoreError::new(
628 ErrorCode::IoError,
629 "test hook: the run stopped here",
630 ));
631 }
632 } else if run.files.last().is_some_and(|file| file.file == path) {
633 run.files.pop();
635 }
636 if matches!(
637 target.outcome,
638 TargetOutcome::Written | TargetOutcome::Unchanged
639 ) {
640 dropped.extend(target.rows.iter().cloned());
641 }
642 }
643 for skill in &mut skills {
644 execute_skill(fs, skill, &mut run, &options.hooks, &mut journal);
645 if skill.done {
646 ledger.remove(&skill.path);
647 run.skill_links.push(skill.row.clone());
648 }
649 }
650 let mcp = ledger.mcp_mut();
651 mcp.entries.retain(|row| !dropped.contains(row));
652 run.ledger = dropped;
653 journal(&run)?;
654 ledger.save(fs, &state)?;
655 run.finished = true;
656 journal(&run)?;
657 backup::prune(fs, ax.home, now)?;
658 crate::diagnostics::log::event(
659 "eject",
660 &[
661 ("targets", &targets.len()),
662 ("writes", &written),
663 ("skills", &skills.len()),
664 ],
665 );
666 Ok(EjectReport {
667 eject_id: Some(id),
668 executed: true,
669 targets,
670 skills,
671 all,
672 unfinished: None,
673 })
674}
675
676fn unfinished_error(id: &str) -> CoreError {
677 CoreError::new(
678 ErrorCode::UnfinishedApply,
679 format!(
680 "eject {id} did not finish; roll it back first (`{} rollback {id}`), then run it again",
681 crate::brand::BIN_NAME
682 ),
683 )
684}
685
686fn check_clients(clients: Option<&[String]>) -> Result<(), CoreError> {
687 for id in clients.into_iter().flatten() {
688 if crate::model::clients::known_client(id).is_none() && adapter(id).is_none() {
689 return Err(CoreError::new(
690 ErrorCode::UnknownClient,
691 format!("{id:?} is not a client Surjection knows"),
692 ));
693 }
694 }
695 Ok(())
696}
697
698fn project_roots(
700 store: Option<&Store<'_>>,
701 ax: &ApplyEnv<'_>,
702) -> Result<BTreeMap<String, PathBuf>, CoreError> {
703 let Some(store) = store else {
704 return Ok(BTreeMap::new());
705 };
706 let state = ax.home.state_dir();
707 let overlay = crate::layering::projects::this_overlay(store, ax.fs, &state)?;
708 let trust = TrustStore::load(ax.fs, &state)?;
709 Ok(known_projects(ax.fs, ax.env, overlay.as_ref(), &trust)
710 .into_iter()
711 .map(|known| (known.id, known.root))
712 .collect())
713}
714
715struct Planner<'a> {
716 ax: &'a ApplyEnv<'a>,
717 catalog: &'a Catalog,
718 roots: &'a BTreeMap<String, PathBuf>,
719 taken: Taken,
721}
722
723impl Planner<'_> {
724 fn targets(&self, rows: Vec<LedgerEntry>) -> Vec<EjectTarget> {
726 let mut groups: Vec<(String, Vec<LedgerEntry>)> = Vec::new();
727 for row in rows {
728 match groups.iter_mut().find(|(file, _)| *file == row.file) {
729 Some((_, rows)) => rows.push(row),
730 None => groups.push((row.file.clone(), vec![row])),
731 }
732 }
733 let mut targets: Vec<EjectTarget> = groups
734 .into_iter()
735 .map(|(file, rows)| self.target(PathBuf::from(file), rows))
736 .collect();
737 let wanted: Vec<(PathBuf, Option<u64>)> = targets
738 .iter()
739 .filter(|target| target.after.is_some())
740 .map(|target| {
741 (
742 target.file.clone(),
743 access::fingerprint(target.before.as_deref()),
744 )
745 })
746 .collect();
747 if !wanted.is_empty() {
748 let found = access::probe_files(self.ax.fs, &wanted, None);
749 for target in &mut targets {
750 if let Some(kind) = found
751 .get(&target.file)
752 .and_then(|access| access.read_only())
753 {
754 target.read_only = Some(kind);
755 target.outcome = TargetOutcome::Blocked;
756 target.error = Some(access::read_only_target(kind, &target.file));
757 }
758 }
759 }
760 targets
761 }
762
763 fn target(&self, file: PathBuf, rows: Vec<LedgerEntry>) -> EjectTarget {
764 let mut clients: Vec<String> = Vec::new();
765 for row in &rows {
766 if !clients.contains(&row.client) {
767 clients.push(row.client.clone());
768 }
769 }
770 let project = rows
771 .iter()
772 .find_map(|row| row.project_id.as_ref())
773 .and_then(|id| self.roots.get(id))
774 .cloned();
775 let format = rows
776 .iter()
777 .find_map(|row| adapter(&row.client).and_then(|spec| spec.mcp.as_ref()))
778 .map(|mcp| mcp.format);
779 let mut target = EjectTarget {
780 clients,
781 file,
782 project,
783 entries: Vec::new(),
784 outcome: TargetOutcome::Unchanged,
785 backup: None,
786 read_only: None,
787 error: None,
788 before: None,
789 after: None,
790 format,
791 rewrites: Vec::new(),
792 rows: Vec::new(),
793 };
794 let fail = |mut target: EjectTarget, rows: &[LedgerEntry], err: CoreError| {
795 target.entries = rows
796 .iter()
797 .map(|row| entry_of(row, EntryAction::Keep))
798 .collect();
799 target.outcome = TargetOutcome::Failed;
800 target.error = Some(err);
801 target
802 };
803 let Some(format) = format else {
804 let err = CoreError::new(
805 ErrorCode::NoAdapter,
806 "no client of this build writes this file; its entries are left as they are",
807 )
808 .with_path(&target.file);
809 return fail(target, &rows, err);
810 };
811 let bytes = match read_target(self.ax.fs, &target.file) {
812 Ok(bytes) => bytes,
813 Err(err) => return fail(target, &rows, err),
814 };
815 let Some(bytes) = bytes else {
816 let project_missing = rows.iter().any(|row| row.project_id.is_some())
820 && match &target.project {
821 Some(root) => !self.ax.fs.is_dir(root),
822 None => target
823 .file
824 .parent()
825 .is_none_or(|dir| !self.ax.fs.is_dir(dir)),
826 };
827 if project_missing {
828 target.entries = rows
829 .iter()
830 .map(|row| entry_of(row, EntryAction::Keep))
831 .collect();
832 target.outcome = TargetOutcome::Blocked;
833 target.error = Some(
834 CoreError::new(
835 ErrorCode::NotFound,
836 "the project folder is missing; its entries stay managed until it is back",
837 )
838 .with_path(&target.file),
839 );
840 return target;
841 }
842 target.entries = rows
843 .iter()
844 .map(|row| entry_of(row, EntryAction::Gone))
845 .collect();
846 target.rows = rows;
847 return target;
848 };
849 let doc = match Document::parse(&bytes, format) {
850 Ok(doc) => doc,
851 Err(err) => {
852 let err = err.with_path(&target.file);
853 return fail(target, &rows, err);
854 }
855 };
856 let mut after_doc = doc.clone();
857 for row in &rows {
858 match self.entry(&doc, &mut after_doc, row, &mut target.rewrites) {
859 Ok(entry) => target.entries.push(entry),
860 Err(err) => {
861 let err = err.with_path(&target.file);
862 return fail(target, &rows, err);
863 }
864 }
865 }
866 if !target.rewrites.is_empty() {
867 let after = after_doc.to_bytes();
868 if after != bytes {
869 target.after = Some(after);
870 target.outcome = TargetOutcome::Planned;
871 }
872 }
873 target.before = Some(bytes);
874 target.rows = rows;
875 target
876 }
877
878 fn entry(
879 &self,
880 doc: &Document,
881 after: &mut Document,
882 row: &LedgerEntry,
883 rewrites: &mut Vec<(Vec<String>, String, String, NativeValue)>,
884 ) -> Result<EjectEntry, CoreError> {
885 let keys = pointer_keys(&row.container);
886 let container: Vec<&str> = keys.iter().map(String::as_str).collect();
887 if row.kind == EntryKind::ListMember {
888 let present = list_members(doc, &container)?.contains(&row.key);
889 let action = if present {
890 EntryAction::Keep
891 } else {
892 EntryAction::Gone
893 };
894 return Ok(entry_of(row, action));
895 }
896 let Some(value) = doc.get(&container, &row.key)? else {
897 return Ok(entry_of(row, EntryAction::Gone));
898 };
899 let Some(spec) = adapter(&row.client).filter(|spec| spec.mcp.is_some()) else {
900 return Ok(entry_of(row, EntryAction::Keep));
901 };
902 let rewriter = Rewriter {
903 spec,
904 os: self.ax.env.os(),
905 catalog: self.catalog,
906 launcher: self.ax.delivery.launcher_path(),
907 surjection_home: &self.ax.home.path,
908 taken: &self.taken,
909 };
910 let mut entry = entry_of(row, EntryAction::Keep);
911 match rewriter.analyze(&row.key, &value) {
912 Analysis::Keep { uses_data_folder } => entry.uses_data_folder = uses_data_folder,
913 Analysis::Manual(problem) => {
914 entry.action = EntryAction::Manual;
915 entry.problem = Some(problem);
916 }
917 Analysis::Rewrite {
918 value,
919 needs_env,
920 manual,
921 uses_data_folder,
922 } => {
923 after.upsert(&container, &row.key, &value)?;
924 entry.action = EntryAction::Rewrite;
925 entry.needs_env = needs_env;
926 entry.needs_manual_secret = manual;
927 entry.uses_data_folder = uses_data_folder;
928 rewrites.push((keys.clone(), row.key.clone(), row.client.clone(), value));
929 }
930 }
931 Ok(entry)
932 }
933}
934
935fn entry_of(row: &LedgerEntry, action: EntryAction) -> EjectEntry {
936 EjectEntry {
937 client: row.client.clone(),
938 scope: row.scope,
939 project_id: row.project_id.clone(),
940 name: row.key.clone(),
941 kind: row.kind,
942 action,
943 needs_env: Vec::new(),
944 needs_manual_secret: Vec::new(),
945 uses_data_folder: false,
946 problem: None,
947 }
948}
949
950fn pointer_keys(pointer: &str) -> Vec<String> {
952 pointer
953 .split('/')
954 .skip(1)
955 .map(|key| key.replace("~1", "/").replace("~0", "~"))
956 .collect()
957}
958
959fn sha256(bytes: &[u8]) -> String {
960 let digest = Sha256::digest(bytes);
961 let mut out = String::from("sha256:");
962 for byte in digest {
963 out.push_str(&format!("{byte:02x}"));
964 }
965 out
966}
967
968fn execute_target(
972 ax: &ApplyEnv<'_>,
973 run_dir: &Path,
974 target: &mut EjectTarget,
975 journal: &mut dyn FnMut(EjectedFile) -> Result<(), CoreError>,
976) {
977 match target.outcome {
978 TargetOutcome::Blocked | TargetOutcome::Failed | TargetOutcome::Unchanged => return,
979 TargetOutcome::Planned | TargetOutcome::Written => {}
980 }
981 let (Some(before), Some(after)) = (target.before.clone(), target.after.clone()) else {
982 target.outcome = TargetOutcome::Unchanged;
983 return;
984 };
985 let result = self_check(target, &before, &after)
986 .and_then(|()| backup::save(ax.fs, ax.home, run_dir, &target.file, &before))
987 .and_then(|path| {
988 target.backup = Some(path.clone());
989 journal(EjectedFile {
990 file: target.file.to_string_lossy().into_owned(),
991 backup: Some(path.to_string_lossy().into_owned()),
992 written: sha256(&after),
993 })
994 })
995 .and_then(|()| swap_file(ax.fs, &target.file, Some(&before), &after));
996 match result {
997 Ok(true) => target.outcome = TargetOutcome::Written,
998 Ok(false) => {
999 target.outcome = TargetOutcome::Failed;
1000 target.error = Some(
1001 CoreError::new(
1002 ErrorCode::FileChangedDuringApply,
1003 "the file changed while ejecting; it was left as it is (run eject again)",
1004 )
1005 .with_path(&target.file),
1006 );
1007 }
1008 Err(err) => {
1009 if let Some(kind) = err.read_only() {
1010 target.read_only = Some(kind);
1011 target.outcome = TargetOutcome::Blocked;
1012 } else {
1013 target.outcome = TargetOutcome::Failed;
1014 }
1015 target.error = Some(err);
1016 }
1017 }
1018}
1019
1020fn self_check(target: &EjectTarget, before: &[u8], after: &[u8]) -> Result<(), CoreError> {
1023 let fail = |detail: String| {
1024 Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&target.file))
1025 };
1026 let format = target.format.expect("a planned target has a format");
1027 let before_doc = Document::parse(before, format)?;
1028 let after_doc = match Document::parse(after, format) {
1029 Ok(doc) => doc,
1030 Err(err) => return fail(format!("the edited file does not parse: {err}")),
1031 };
1032 let mut before_root = document_value(&before_doc)?;
1033 let mut after_root = document_value(&after_doc)?;
1034 let mut containers: Vec<&Vec<String>> = Vec::new();
1035 for (keys, _, _, _) in &target.rewrites {
1036 if !containers.contains(&keys) {
1037 containers.push(keys);
1038 }
1039 }
1040 for keys in containers {
1041 let container: Vec<&str> = keys.iter().map(String::as_str).collect();
1042 let names = before_doc.list(&container)?;
1043 if names != after_doc.list(&container)? {
1044 return fail("the entries of a container changed".to_owned());
1045 }
1046 for name in &names {
1047 let got = after_doc.get(&container, name)?;
1048 let planned = target
1049 .rewrites
1050 .iter()
1051 .find(|(k, key, _, _)| k == keys && key == name);
1052 let ok = match planned {
1053 Some((_, _, client, want)) => got
1054 .as_ref()
1055 .is_some_and(|got| canonical(client, got) == canonical(client, want)),
1056 None => got == before_doc.get(&container, name)?,
1057 };
1058 if !ok {
1059 return fail(format!("entry {name:?} does not read back as planned"));
1060 }
1061 }
1062 strip_container(&mut before_root, &container);
1063 strip_container(&mut after_root, &container);
1064 }
1065 if before_root != after_root {
1066 return fail("something outside the server containers changed".to_owned());
1067 }
1068 Ok(())
1069}
1070
1071fn plan_skill(fs: &dyn Fs, link: &SkillLink, keep_agent_skill: bool) -> EjectSkill {
1072 let path = PathBuf::from(&link.path);
1073 let agent = link.skill_id == crate::agent::SKILL_ID && !keep_agent_skill;
1074 let mut skill = EjectSkill {
1075 client: link.client.clone(),
1076 scope: link.scope,
1077 project_id: link.project_id.clone(),
1078 skill_id: link.skill_id.clone(),
1079 path: path.clone(),
1080 method: link.method,
1081 action: SkillAction::Changed,
1082 done: false,
1083 read_only: None,
1084 error: None,
1085 row: link.clone(),
1086 };
1087 let aside = aside_link(&path);
1090 let found = entry(fs, &path).and_then(|found| match found {
1091 Entry::Missing if matches!(entry(fs, &aside)?, Entry::Link(_)) => entry(fs, &aside),
1092 found => Ok(found),
1093 });
1094 let found = found.and_then(|found| {
1095 Ok(match found {
1096 Entry::Missing => SkillAction::Gone,
1097 Entry::Link(to)
1098 if link.method != LinkMethod::Copy
1099 && same_folder(fs, &to, Path::new(&link.target)) =>
1100 {
1101 if agent {
1102 SkillAction::Remove
1103 } else {
1104 SkillAction::Copy
1105 }
1106 }
1107 Entry::Dir if link.method == LinkMethod::Copy => {
1108 match unchanged_copy(fs, &path, link)? {
1109 None => SkillAction::Changed,
1110 Some(_) if agent => SkillAction::Remove,
1111 Some(_) => SkillAction::Keep,
1112 }
1113 }
1114 _ => SkillAction::Changed,
1115 })
1116 });
1117 match found {
1118 Ok(action) => skill.action = action,
1119 Err(err) => {
1120 skill.error = Some(err);
1121 return skill;
1122 }
1123 }
1124 if matches!(
1125 skill.action,
1126 SkillAction::Copy | SkillAction::Keep | SkillAction::Remove
1127 ) && let Some(kind) = new_folder_access(fs, &temp_folder(&path)).read_only()
1128 {
1129 skill.read_only = Some(kind);
1130 skill.error = Some(access::read_only_target(kind, &path));
1131 }
1132 skill
1133}
1134
1135fn temp_folder(path: &Path) -> PathBuf {
1137 sibling(path, "surjection-eject")
1138}
1139
1140fn aside_link(path: &Path) -> PathBuf {
1142 sibling(path, "surjection-link")
1143}
1144
1145fn sibling(path: &Path, suffix: &str) -> PathBuf {
1146 let name = path
1147 .file_name()
1148 .map(|name| name.to_string_lossy().into_owned())
1149 .unwrap_or_default();
1150 path.with_file_name(format!(".{name}.{suffix}"))
1151}
1152
1153fn recover_leftovers(fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
1156 let aside = aside_link(path);
1157 if matches!(entry(fs, &aside)?, Entry::Link(_)) {
1158 if entry(fs, path)? == Entry::Missing {
1159 fs.replace(&aside, path).map_err(|err| {
1160 crate::access::write_error(fs, "cannot put the link back", path, &err)
1161 })?;
1162 } else {
1163 remove_link(fs, &aside)?;
1164 }
1165 }
1166 let temp = temp_folder(path);
1167 if fs.is_dir(&temp) {
1168 remove_copy(fs, &temp)?;
1169 }
1170 Ok(())
1171}
1172
1173fn execute_skill(
1174 fs: &dyn Fs,
1175 skill: &mut EjectSkill,
1176 run: &mut EjectRun,
1177 hooks: &EjectHooks,
1178 journal: &mut dyn FnMut(&EjectRun) -> Result<(), CoreError>,
1179) {
1180 if skill.error.is_some() {
1181 return;
1182 }
1183 let path = skill.path.clone();
1184 let done = (|| -> Result<(), CoreError> {
1185 if skill.action != SkillAction::Gone {
1186 recover_leftovers(fs, &path)?;
1187 }
1188 match skill.action {
1189 SkillAction::Changed | SkillAction::Gone => Ok(()),
1190 SkillAction::Remove => match skill.method {
1191 LinkMethod::Copy => remove_copy(fs, &path),
1192 LinkMethod::Junction | LinkMethod::Symlink => remove_link(fs, &path),
1193 },
1194 SkillAction::Keep => {
1195 for marker in [MARKER_FILE, LEGACY_MARKER_FILE].map(|name| path.join(name)) {
1196 if fs.exists(&marker) {
1197 fs.remove_file(&marker).map_err(|err| {
1198 crate::skills::removal_error(fs, "cannot remove file", &marker, &err)
1199 })?;
1200 }
1201 }
1202 run.unmarked.push(path.to_string_lossy().into_owned());
1203 Ok(())
1204 }
1205 SkillAction::Copy => {
1206 let files = read_folder(fs, Path::new(&skill.row.target))?;
1207 run.copied.push(CopiedSkill {
1208 path: path.to_string_lossy().into_owned(),
1209 hash: content_hash(&files),
1210 });
1211 journal(run)?;
1212 copy_in_place(fs, &skill.row, &files, hooks.fail_skill_move).inspect_err(|_| {
1213 run.copied.pop();
1214 })
1215 }
1216 }
1217 })();
1218 match done {
1219 Ok(()) => skill.done = true,
1220 Err(err) => {
1221 skill.read_only = err.read_only();
1222 skill.error = Some(err);
1223 }
1224 }
1225}
1226
1227fn copy_in_place(
1232 fs: &dyn Fs,
1233 link: &SkillLink,
1234 files: &crate::skills::SkillFiles,
1235 fail_move: bool,
1236) -> Result<(), CoreError> {
1237 let path = PathBuf::from(&link.path);
1238 let temp = temp_folder(&path);
1239 let aside = aside_link(&path);
1240 confine(fs, &temp)?;
1241 confine(fs, &aside)?;
1242 fs.create_dir_all(&temp)
1243 .map_err(|err| crate::access::write_error(fs, "cannot create directory", &temp, &err))?;
1244 write_files(fs, &temp, files)?;
1245 fs.replace(&path, &aside)
1246 .map_err(|err| crate::access::write_error(fs, "cannot move the link aside", &path, &err))?;
1247 let moved = if fail_move {
1248 Err(std::io::Error::other("test hook: the move failed"))
1249 } else {
1250 fs.replace(&temp, &path)
1251 };
1252 if let Err(err) = moved {
1253 let _ = fs.replace(&aside, &path);
1254 let _ = remove_copy(fs, &temp);
1255 return Err(crate::access::write_error(
1256 fs,
1257 "cannot move the copy into place",
1258 &path,
1259 &err,
1260 ));
1261 }
1262 let _ = remove_link(fs, &aside);
1264 Ok(())
1265}
1266
1267pub fn resume(fs: &dyn Fs, home: &SurjectionHome) -> Result<Vec<String>, CoreError> {
1271 set_resumed(fs, home, None, true)
1272}
1273
1274pub fn unresume(fs: &dyn Fs, home: &SurjectionHome, ids: &[String]) -> Result<(), CoreError> {
1276 if ids.is_empty() {
1277 return Ok(());
1278 }
1279 set_resumed(fs, home, Some(ids), false).map(|_| ())
1280}
1281
1282fn set_resumed(
1283 fs: &dyn Fs,
1284 home: &SurjectionHome,
1285 ids: Option<&[String]>,
1286 resumed: bool,
1287) -> Result<Vec<String>, CoreError> {
1288 let state = home.state_dir();
1289 if !fs.exists(&state.join(EJECT_FILE)) {
1290 return Ok(Vec::new());
1291 }
1292 let _lock = StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?;
1293 let mut record = EjectFile::load(fs, &state)?;
1294 let mut changed = Vec::new();
1295 for run in record.runs.iter_mut().filter(|run| !run.rolled_back) {
1296 let chosen = match ids {
1297 Some(ids) => ids.contains(&run.id),
1298 None => !run.resumed,
1299 };
1300 if chosen && run.resumed != resumed {
1301 run.resumed = resumed;
1302 changed.push(run.id.clone());
1303 }
1304 }
1305 if !changed.is_empty() {
1306 record.save(fs, &state)?;
1307 }
1308 Ok(changed)
1309}
1310
1311pub fn left_over(fs: &dyn Fs, home: &SurjectionHome) -> Result<usize, CoreError> {
1315 let state = home.state_dir();
1316 let Some(ejected) = status_at(fs, &state)? else {
1317 return Ok(0);
1318 };
1319 let ledger = SkillLedger::load(fs, &state)?;
1320 let mcp = ledger.clone().mcp_mut().entries.clone();
1321 let entries = mcp
1322 .iter()
1323 .filter(|row| ejected.covers(&row.client, row.project_id.as_deref()))
1324 .count();
1325 let links = ledger
1326 .links
1327 .iter()
1328 .filter(|link| ejected.covers(&link.client, link.project_id.as_deref()))
1329 .count();
1330 Ok(entries + links)
1331}
1332
1333pub fn last_run(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<EjectRun>, CoreError> {
1335 Ok(EjectFile::load(fs, &home.state_dir())?
1336 .runs
1337 .into_iter()
1338 .rev()
1339 .find(|run| !run.rolled_back))
1340}
1341
1342#[derive(Debug)]
1344pub struct EjectRollback {
1345 pub eject_id: String,
1346 pub restored: Vec<PathBuf>,
1348 pub changed_since: Vec<PathBuf>,
1351 pub errors: Vec<(PathBuf, CoreError)>,
1355 pub skills: Option<SyncReport>,
1357}
1358
1359pub fn rollback(
1366 store: Option<&Store<'_>>,
1367 sx: &SkillsEnv<'_>,
1368 id: Option<&str>,
1369) -> Result<EjectRollback, CoreError> {
1370 let fs = sx.fs;
1371 let state = sx.home.state_dir();
1372 let mut result = {
1373 let _lock = StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?;
1374 let mut record = EjectFile::load(fs, &state)?;
1375 let index = record
1376 .runs
1377 .iter()
1378 .rposition(|run| {
1379 !run.rolled_back && id.is_none_or(|id| run.id.eq_ignore_ascii_case(id))
1380 })
1381 .ok_or_else(|| {
1382 CoreError::new(
1383 ErrorCode::NotFound,
1384 match id {
1385 Some(id) => format!("no eject run {id:?} to roll back on this machine"),
1386 None => "this machine has no eject run to roll back".to_owned(),
1387 },
1388 )
1389 })?;
1390 let run = record.runs[index].clone();
1391 let mut result = EjectRollback {
1392 eject_id: run.id.clone(),
1393 restored: Vec::new(),
1394 changed_since: Vec::new(),
1395 errors: Vec::new(),
1396 skills: None,
1397 };
1398 let reads: Vec<_> = run
1400 .files
1401 .iter()
1402 .map(|file| {
1403 let path = PathBuf::from(&file.file);
1404 let backup = match &file.backup {
1405 Some(backup) => fs.read(Path::new(backup)).map_err(|err| {
1406 CoreError::new(ErrorCode::IoError, format!("cannot read backup: {err}"))
1407 .with_path(backup)
1408 }),
1409 None => Err(CoreError::new(
1410 ErrorCode::NotFound,
1411 "the eject recorded no backup of this file",
1412 )
1413 .with_path(&path)),
1414 };
1415 (path, file.written.as_str(), backup)
1416 })
1417 .collect();
1418 for (path, written, backup) in reads {
1419 let outcome = backup.and_then(|backup| {
1420 let current = read_target(fs, &path)?;
1421 let now = current.as_deref().map(sha256);
1422 if now.as_deref() == Some(sha256(&backup).as_str()) {
1423 return Ok(true);
1424 }
1425 if now.as_deref() != Some(written) {
1426 return Ok(false);
1427 }
1428 swap_file(fs, &path, current.as_deref(), &backup)
1429 });
1430 match outcome {
1431 Ok(true) => result.restored.push(path),
1432 Ok(false) => result.changed_since.push(path),
1433 Err(err) => result.errors.push((path, err)),
1434 }
1435 }
1436 let mut ledger = SkillLedger::load(fs, &state)?;
1437 let skipped: HashSet<String> = result
1438 .changed_since
1439 .iter()
1440 .chain(result.errors.iter().map(|(path, _)| path))
1441 .map(|path| path.to_string_lossy().into_owned())
1442 .collect();
1443 for row in &run.ledger {
1444 let newer = ledger.mcp_mut().get(&row.slot(), &row.key).is_some();
1446 if !skipped.contains(&row.file) && !newer {
1447 ledger.mcp_mut().upsert(row.clone());
1448 }
1449 }
1450 let as_copy = |mut row: SkillLink, copied: &CopiedSkill| {
1454 row.method = LinkMethod::Copy;
1455 row.written_hash = Some(copied.hash.clone());
1456 row
1457 };
1458 for copied in &run.copied {
1459 if let Some(owned) = ledger.get(Path::new(&copied.path)).cloned()
1460 && owned.method != LinkMethod::Copy
1461 {
1462 ledger.upsert(as_copy(owned, copied));
1463 }
1464 }
1465 for row in &run.skill_links {
1466 if ledger.get(Path::new(&row.path)).is_some() {
1467 continue;
1468 }
1469 let row = match run.copied.iter().find(|copied| copied.path == row.path) {
1470 Some(copied) => as_copy(row.clone(), copied),
1471 None => {
1472 if run.unmarked.contains(&row.path) {
1473 let marker = Path::new(&row.path).join(MARKER_FILE);
1474 if fs.is_dir(Path::new(&row.path)) && !fs.exists(&marker) {
1475 fs.write(&marker, marker_text(&row.skill_id).as_bytes())
1476 .map_err(|err| {
1477 crate::access::write_error(
1478 fs,
1479 "cannot write file",
1480 &marker,
1481 &err,
1482 )
1483 })?;
1484 }
1485 }
1486 row.clone()
1487 }
1488 };
1489 ledger.upsert(row);
1490 }
1491 ledger.save(fs, &state)?;
1492 if result.errors.is_empty() {
1493 record.runs[index].rolled_back = true;
1494 record.save(fs, &state)?;
1495 }
1496 result
1497 };
1498 if let Some(store) = store {
1499 result.skills = Some(link::sync(store, sx)?);
1500 }
1501 Ok(result)
1502}