mod record;
mod rewrite;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
use crate::access::{self, ReadOnlyKind};
use crate::adapters::adapter;
use crate::apply::exec::{document_value, strip_container, swap_file};
use crate::apply::ledger::{EntryKind, LedgerEntry};
use crate::apply::plan::{canonical, list_members, read_target};
use crate::apply::{ApplyEnv, backup};
use crate::error::{CoreError, ErrorCode};
use crate::formats::{Document, NativeValue};
use crate::fs::Fs;
use crate::layering::{TrustStore, known_projects, same_folder, same_path};
use crate::model::applied::Scope;
use crate::model::ids;
use crate::paths::SurjectionHome;
use crate::secrets::catalog::Catalog;
use crate::skills::link::{
self, LinkMethod, SkillLedger, SkillLink, SyncReport, marker_text, remove_copy, remove_link,
unchanged_copy,
};
use crate::skills::{
Entry, LEGACY_MARKER_FILE, MARKER_FILE, SkillsEnv, confine, content_hash, entry,
new_folder_access, read_folder, write_files,
};
use crate::store::{LOCK_TIMEOUT, Machine, Store, StoreLock, utc_datetime};
#[cfg(test)]
pub(crate) use record::EJECT_SCHEMA;
pub use record::{
ActiveRun, CopiedSkill, EJECT_FILE, EjectFile, EjectRun, Ejected, EjectedFile, status_at,
};
pub use rewrite::{EnvNeed, ManualSecret};
use rewrite::{Analysis, Rewriter, Taken};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EjectOptions {
pub clients: Option<Vec<String>>,
pub project: Option<PathBuf>,
pub keep_agent_skill: bool,
pub execute: bool,
#[doc(hidden)]
pub hooks: EjectHooks,
}
#[doc(hidden)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EjectHooks {
pub crash_after_files: Option<usize>,
pub fail_skill_move: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryAction {
Keep,
Rewrite,
Manual,
Gone,
}
impl EntryAction {
pub const fn as_str(self) -> &'static str {
match self {
EntryAction::Keep => "keep",
EntryAction::Rewrite => "rewrite",
EntryAction::Manual => "manual",
EntryAction::Gone => "gone",
}
}
}
#[derive(Debug, Clone)]
pub struct EjectEntry {
pub client: String,
pub scope: Scope,
pub project_id: Option<String>,
pub name: String,
pub kind: EntryKind,
pub action: EntryAction,
pub needs_env: Vec<EnvNeed>,
pub needs_manual_secret: Vec<ManualSecret>,
pub uses_data_folder: bool,
pub problem: Option<CoreError>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TargetOutcome {
Planned,
Unchanged,
Written,
Blocked,
Failed,
}
impl TargetOutcome {
pub const fn as_str(self) -> &'static str {
match self {
TargetOutcome::Planned => "planned",
TargetOutcome::Unchanged => "unchanged",
TargetOutcome::Written => "written",
TargetOutcome::Blocked => "blocked",
TargetOutcome::Failed => "failed",
}
}
}
#[derive(Debug, Clone)]
pub struct EjectTarget {
pub clients: Vec<String>,
pub file: PathBuf,
pub project: Option<PathBuf>,
pub entries: Vec<EjectEntry>,
pub outcome: TargetOutcome,
pub backup: Option<PathBuf>,
pub read_only: Option<ReadOnlyKind>,
pub error: Option<CoreError>,
before: Option<Vec<u8>>,
after: Option<Vec<u8>>,
format: Option<crate::formats::Format>,
rewrites: Vec<(Vec<String>, String, String, NativeValue)>,
rows: Vec<LedgerEntry>,
}
impl EjectTarget {
pub fn rewrites(&self) -> bool {
self.after.is_some()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SkillAction {
Copy,
Keep,
Remove,
Changed,
Gone,
}
impl SkillAction {
pub const fn as_str(self) -> &'static str {
match self {
SkillAction::Copy => "copy",
SkillAction::Keep => "keep",
SkillAction::Remove => "remove",
SkillAction::Changed => "changed",
SkillAction::Gone => "gone",
}
}
}
#[derive(Debug, Clone)]
pub struct EjectSkill {
pub client: String,
pub scope: Scope,
pub project_id: Option<String>,
pub skill_id: String,
pub path: PathBuf,
pub method: LinkMethod,
pub action: SkillAction,
pub done: bool,
pub read_only: Option<ReadOnlyKind>,
pub error: Option<CoreError>,
row: SkillLink,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvSummary {
pub name: String,
pub secret: Option<String>,
pub reference: String,
pub entries: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManualSummary {
pub client: String,
pub entry: String,
pub file: PathBuf,
pub project: Option<PathBuf>,
pub secret: ManualSecret,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvConflict {
pub name: String,
pub secrets: Vec<String>,
pub entries: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StillReason {
Manual,
UsesDataFolder,
Blocked,
Failed,
SkillLink,
}
impl StillReason {
pub const fn as_str(self) -> &'static str {
match self {
StillReason::Manual => "manual",
StillReason::UsesDataFolder => "uses_data_folder",
StillReason::Blocked => "blocked",
StillReason::Failed => "failed",
StillReason::SkillLink => "skill_link",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StillNeeded {
pub client: String,
pub entry: Option<String>,
pub file: PathBuf,
pub project: Option<PathBuf>,
pub reason: StillReason,
pub detail: Option<String>,
}
#[derive(Debug, Clone)]
pub struct EjectReport {
pub eject_id: Option<String>,
pub executed: bool,
pub targets: Vec<EjectTarget>,
pub skills: Vec<EjectSkill>,
pub all: bool,
pub unfinished: Option<String>,
}
impl EjectReport {
pub fn env(&self) -> Vec<EnvSummary> {
let mut out: Vec<EnvSummary> = Vec::new();
for target in &self.targets {
for entry in &target.entries {
for need in &entry.needs_env {
let label = format!("{}: {}", entry.client, entry.name);
match out.iter_mut().find(|summary| summary.name == need.name) {
Some(summary) => {
if !summary.entries.contains(&label) {
summary.entries.push(label);
}
}
None => out.push(EnvSummary {
name: need.name.clone(),
secret: need.secret.clone(),
reference: need.reference.clone(),
entries: vec![label],
}),
}
}
}
}
out
}
pub fn conflicts(&self) -> Vec<EnvConflict> {
let env = self.env();
let mut out: Vec<EnvConflict> = Vec::new();
for item in self.manual() {
let Some(name) = &item.secret.conflicts_with else {
continue;
};
let label = format!("{}: {}", item.client, item.entry);
let conflict = match out.iter_mut().position(|c| &c.name == name) {
Some(index) => &mut out[index],
None => {
let first = env.iter().find(|summary| &summary.name == name);
out.push(EnvConflict {
name: name.clone(),
secrets: first
.map(|s| s.secret.clone().unwrap_or_else(|| s.reference.clone()))
.into_iter()
.collect(),
entries: first.map(|s| s.entries.clone()).unwrap_or_default(),
});
out.last_mut().expect("pushed")
}
};
if !conflict.secrets.contains(&item.secret.secret) {
conflict.secrets.push(item.secret.secret.clone());
}
if !conflict.entries.contains(&label) {
conflict.entries.push(label);
}
}
out
}
pub fn still_needs_surjection(&self) -> Vec<StillNeeded> {
let mut out = Vec::new();
for target in &self.targets {
let stuck = match target.outcome {
TargetOutcome::Blocked => Some(StillReason::Blocked),
TargetOutcome::Failed => Some(StillReason::Failed),
_ => None,
};
let detail = target.error.as_ref().map(|err| err.message().to_owned());
let mut listed = false;
for entry in &target.entries {
let reason = match (stuck, entry.action) {
(Some(reason), EntryAction::Rewrite | EntryAction::Manual) => Some(reason),
(_, EntryAction::Manual) => Some(StillReason::Manual),
_ if entry.uses_data_folder => Some(StillReason::UsesDataFolder),
_ => None,
};
if let Some(reason) = reason {
listed = true;
out.push(StillNeeded {
client: entry.client.clone(),
entry: Some(entry.name.clone()),
file: target.file.clone(),
project: target.project.clone(),
reason,
detail: match reason {
StillReason::Manual => {
entry.problem.as_ref().map(|err| err.message().to_owned())
}
_ => detail.clone(),
},
});
}
}
if let (Some(reason), false, None) = (stuck, listed, target.after.as_ref())
&& target.entries.iter().all(|e| e.action == EntryAction::Keep)
&& target.error.is_some()
&& !target.entries.is_empty()
{
out.push(StillNeeded {
client: target.clients.join(", "),
entry: None,
file: target.file.clone(),
project: target.project.clone(),
reason,
detail,
});
}
}
for skill in &self.skills {
if skill.action == SkillAction::Copy && !(self.executed && skill.done) {
if !self.executed && skill.error.is_none() {
continue;
}
out.push(StillNeeded {
client: skill.client.clone(),
entry: Some(skill.skill_id.clone()),
file: skill.path.clone(),
project: None,
reason: StillReason::SkillLink,
detail: skill.error.as_ref().map(|err| err.message().to_owned()),
});
}
}
out
}
pub fn manual(&self) -> Vec<ManualSummary> {
let mut out = Vec::new();
for target in &self.targets {
for entry in &target.entries {
for secret in &entry.needs_manual_secret {
out.push(ManualSummary {
client: entry.client.clone(),
entry: entry.name.clone(),
file: target.file.clone(),
project: target.project.clone(),
secret: secret.clone(),
});
}
}
}
out
}
pub fn failed(&self) -> bool {
self.targets
.iter()
.any(|target| target.outcome == TargetOutcome::Failed)
|| self
.skills
.iter()
.any(|skill| skill.error.is_some() && skill.read_only.is_none())
}
}
pub fn status(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<Ejected>, CoreError> {
status_at(fs, &home.state_dir())
}
pub fn eject(
store: Option<&Store<'_>>,
ax: &ApplyEnv<'_>,
options: &EjectOptions,
) -> Result<EjectReport, CoreError> {
check_clients(options.clients.as_deref())?;
let fs = ax.fs;
let state = ax.home.state_dir();
let roots = project_roots(store, ax)?;
let project_id = match &options.project {
Some(root) => Some(
roots
.iter()
.find(|(_, known)| same_path(known, root))
.map(|(id, _)| id.clone())
.ok_or_else(|| {
CoreError::new(
ErrorCode::NotFound,
"the folder is not a project this machine knows",
)
.with_path(root)
})?,
),
None => None,
};
let catalog = match store {
Some(store) => {
let machine = Machine::load(fs, &state)?;
Catalog::load(store, machine.as_ref().map(|machine| machine.id.as_str()))?
}
None => Catalog::default(),
};
let _lock = if options.execute {
Some(StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?)
} else {
None
};
let mut ledger = SkillLedger::load(fs, &state)?;
let selected = |client: &str, project: Option<&str>| {
options
.clients
.as_ref()
.is_none_or(|clients| clients.iter().any(|id| id == client))
&& project_id.as_deref().is_none_or(|id| project == Some(id))
};
let rows: Vec<LedgerEntry> = ledger
.mcp_mut()
.entries
.iter()
.filter(|row| selected(&row.client, row.project_id.as_deref()))
.cloned()
.collect();
let planner = Planner {
ax,
catalog: &catalog,
roots: &roots,
taken: Taken::default(),
};
let mut targets = planner.targets(rows);
let mut skills: Vec<EjectSkill> = ledger
.links
.iter()
.filter(|link| selected(&link.client, link.project_id.as_deref()))
.map(|link| plan_skill(fs, link, options.keep_agent_skill))
.collect();
let all = options.clients.is_none() && project_id.is_none();
let mut record = EjectFile::load(fs, &state)?;
let unfinished = record
.runs
.iter()
.find(|run| !run.finished && !run.rolled_back)
.map(|run| run.id.clone());
if !options.execute {
return Ok(EjectReport {
eject_id: None,
executed: false,
targets,
skills,
all,
unfinished,
});
}
if let Some(open) = &unfinished {
return Err(unfinished_error(open));
}
let now = ax.env.now();
let id = ids::new_ulid(now)?;
let mut run = EjectRun {
id: id.clone(),
time: utc_datetime(now).to_string(),
clients: options.clients.clone(),
project_id: project_id.clone(),
finished: false,
resumed: false,
rolled_back: false,
files: Vec::new(),
ledger: Vec::new(),
skill_links: Vec::new(),
copied: Vec::new(),
unmarked: Vec::new(),
extra: serde_json::Map::new(),
};
record.runs.push(run.clone());
record.save(fs, &state)?;
let mut journal = |run: &EjectRun| -> Result<(), CoreError> {
if let Some(saved) = record
.runs
.iter_mut()
.rev()
.find(|saved| saved.id == run.id)
{
*saved = run.clone();
}
record.save(fs, &state)
};
let run_dir = backup::run_dir(ax.home, now, &id);
let mut dropped: Vec<LedgerEntry> = Vec::new();
let mut written = 0;
for target in &mut targets {
execute_target(ax, &run_dir, target, &mut |file| {
run.files.push(file);
journal(&run)
});
let path = target.file.to_string_lossy().into_owned();
if target.outcome == TargetOutcome::Written {
written += 1;
if options.hooks.crash_after_files == Some(written) {
return Err(CoreError::new(
ErrorCode::IoError,
"test hook: the run stopped here",
));
}
} else if run.files.last().is_some_and(|file| file.file == path) {
run.files.pop();
}
if matches!(
target.outcome,
TargetOutcome::Written | TargetOutcome::Unchanged
) {
dropped.extend(target.rows.iter().cloned());
}
}
for skill in &mut skills {
execute_skill(fs, skill, &mut run, &options.hooks, &mut journal);
if skill.done {
ledger.remove(&skill.path);
run.skill_links.push(skill.row.clone());
}
}
let mcp = ledger.mcp_mut();
mcp.entries.retain(|row| !dropped.contains(row));
run.ledger = dropped;
journal(&run)?;
ledger.save(fs, &state)?;
run.finished = true;
journal(&run)?;
backup::prune(fs, ax.home, now)?;
crate::diagnostics::log::event(
"eject",
&[
("targets", &targets.len()),
("writes", &written),
("skills", &skills.len()),
],
);
Ok(EjectReport {
eject_id: Some(id),
executed: true,
targets,
skills,
all,
unfinished: None,
})
}
fn unfinished_error(id: &str) -> CoreError {
CoreError::new(
ErrorCode::UnfinishedApply,
format!(
"eject {id} did not finish; roll it back first (`{} rollback {id}`), then run it again",
crate::brand::BIN_NAME
),
)
}
fn check_clients(clients: Option<&[String]>) -> Result<(), CoreError> {
for id in clients.into_iter().flatten() {
if crate::model::clients::known_client(id).is_none() && adapter(id).is_none() {
return Err(CoreError::new(
ErrorCode::UnknownClient,
format!("{id:?} is not a client Surjection knows"),
));
}
}
Ok(())
}
fn project_roots(
store: Option<&Store<'_>>,
ax: &ApplyEnv<'_>,
) -> Result<BTreeMap<String, PathBuf>, CoreError> {
let Some(store) = store else {
return Ok(BTreeMap::new());
};
let state = ax.home.state_dir();
let overlay = crate::layering::projects::this_overlay(store, ax.fs, &state)?;
let trust = TrustStore::load(ax.fs, &state)?;
Ok(known_projects(ax.fs, ax.env, overlay.as_ref(), &trust)
.into_iter()
.map(|known| (known.id, known.root))
.collect())
}
struct Planner<'a> {
ax: &'a ApplyEnv<'a>,
catalog: &'a Catalog,
roots: &'a BTreeMap<String, PathBuf>,
taken: Taken,
}
impl Planner<'_> {
fn targets(&self, rows: Vec<LedgerEntry>) -> Vec<EjectTarget> {
let mut groups: Vec<(String, Vec<LedgerEntry>)> = Vec::new();
for row in rows {
match groups.iter_mut().find(|(file, _)| *file == row.file) {
Some((_, rows)) => rows.push(row),
None => groups.push((row.file.clone(), vec![row])),
}
}
let mut targets: Vec<EjectTarget> = groups
.into_iter()
.map(|(file, rows)| self.target(PathBuf::from(file), rows))
.collect();
let wanted: Vec<(PathBuf, Option<u64>)> = targets
.iter()
.filter(|target| target.after.is_some())
.map(|target| {
(
target.file.clone(),
access::fingerprint(target.before.as_deref()),
)
})
.collect();
if !wanted.is_empty() {
let found = access::probe_files(self.ax.fs, &wanted, None);
for target in &mut targets {
if let Some(kind) = found
.get(&target.file)
.and_then(|access| access.read_only())
{
target.read_only = Some(kind);
target.outcome = TargetOutcome::Blocked;
target.error = Some(access::read_only_target(kind, &target.file));
}
}
}
targets
}
fn target(&self, file: PathBuf, rows: Vec<LedgerEntry>) -> EjectTarget {
let mut clients: Vec<String> = Vec::new();
for row in &rows {
if !clients.contains(&row.client) {
clients.push(row.client.clone());
}
}
let project = rows
.iter()
.find_map(|row| row.project_id.as_ref())
.and_then(|id| self.roots.get(id))
.cloned();
let format = rows
.iter()
.find_map(|row| adapter(&row.client).and_then(|spec| spec.mcp.as_ref()))
.map(|mcp| mcp.format);
let mut target = EjectTarget {
clients,
file,
project,
entries: Vec::new(),
outcome: TargetOutcome::Unchanged,
backup: None,
read_only: None,
error: None,
before: None,
after: None,
format,
rewrites: Vec::new(),
rows: Vec::new(),
};
let fail = |mut target: EjectTarget, rows: &[LedgerEntry], err: CoreError| {
target.entries = rows
.iter()
.map(|row| entry_of(row, EntryAction::Keep))
.collect();
target.outcome = TargetOutcome::Failed;
target.error = Some(err);
target
};
let Some(format) = format else {
let err = CoreError::new(
ErrorCode::NoAdapter,
"no client of this build writes this file; its entries are left as they are",
)
.with_path(&target.file);
return fail(target, &rows, err);
};
let bytes = match read_target(self.ax.fs, &target.file) {
Ok(bytes) => bytes,
Err(err) => return fail(target, &rows, err),
};
let Some(bytes) = bytes else {
let project_missing = rows.iter().any(|row| row.project_id.is_some())
&& match &target.project {
Some(root) => !self.ax.fs.is_dir(root),
None => target
.file
.parent()
.is_none_or(|dir| !self.ax.fs.is_dir(dir)),
};
if project_missing {
target.entries = rows
.iter()
.map(|row| entry_of(row, EntryAction::Keep))
.collect();
target.outcome = TargetOutcome::Blocked;
target.error = Some(
CoreError::new(
ErrorCode::NotFound,
"the project folder is missing; its entries stay managed until it is back",
)
.with_path(&target.file),
);
return target;
}
target.entries = rows
.iter()
.map(|row| entry_of(row, EntryAction::Gone))
.collect();
target.rows = rows;
return target;
};
let doc = match Document::parse(&bytes, format) {
Ok(doc) => doc,
Err(err) => {
let err = err.with_path(&target.file);
return fail(target, &rows, err);
}
};
let mut after_doc = doc.clone();
for row in &rows {
match self.entry(&doc, &mut after_doc, row, &mut target.rewrites) {
Ok(entry) => target.entries.push(entry),
Err(err) => {
let err = err.with_path(&target.file);
return fail(target, &rows, err);
}
}
}
if !target.rewrites.is_empty() {
let after = after_doc.to_bytes();
if after != bytes {
target.after = Some(after);
target.outcome = TargetOutcome::Planned;
}
}
target.before = Some(bytes);
target.rows = rows;
target
}
fn entry(
&self,
doc: &Document,
after: &mut Document,
row: &LedgerEntry,
rewrites: &mut Vec<(Vec<String>, String, String, NativeValue)>,
) -> Result<EjectEntry, CoreError> {
let keys = pointer_keys(&row.container);
let container: Vec<&str> = keys.iter().map(String::as_str).collect();
if row.kind == EntryKind::ListMember {
let present = list_members(doc, &container)?.contains(&row.key);
let action = if present {
EntryAction::Keep
} else {
EntryAction::Gone
};
return Ok(entry_of(row, action));
}
let Some(value) = doc.get(&container, &row.key)? else {
return Ok(entry_of(row, EntryAction::Gone));
};
let Some(spec) = adapter(&row.client).filter(|spec| spec.mcp.is_some()) else {
return Ok(entry_of(row, EntryAction::Keep));
};
let rewriter = Rewriter {
spec,
os: self.ax.env.os(),
catalog: self.catalog,
launcher: self.ax.delivery.launcher_path(),
surjection_home: &self.ax.home.path,
taken: &self.taken,
};
let mut entry = entry_of(row, EntryAction::Keep);
match rewriter.analyze(&row.key, &value) {
Analysis::Keep { uses_data_folder } => entry.uses_data_folder = uses_data_folder,
Analysis::Manual(problem) => {
entry.action = EntryAction::Manual;
entry.problem = Some(problem);
}
Analysis::Rewrite {
value,
needs_env,
manual,
uses_data_folder,
} => {
after.upsert(&container, &row.key, &value)?;
entry.action = EntryAction::Rewrite;
entry.needs_env = needs_env;
entry.needs_manual_secret = manual;
entry.uses_data_folder = uses_data_folder;
rewrites.push((keys.clone(), row.key.clone(), row.client.clone(), value));
}
}
Ok(entry)
}
}
fn entry_of(row: &LedgerEntry, action: EntryAction) -> EjectEntry {
EjectEntry {
client: row.client.clone(),
scope: row.scope,
project_id: row.project_id.clone(),
name: row.key.clone(),
kind: row.kind,
action,
needs_env: Vec::new(),
needs_manual_secret: Vec::new(),
uses_data_folder: false,
problem: None,
}
}
fn pointer_keys(pointer: &str) -> Vec<String> {
pointer
.split('/')
.skip(1)
.map(|key| key.replace("~1", "/").replace("~0", "~"))
.collect()
}
fn sha256(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut out = String::from("sha256:");
for byte in digest {
out.push_str(&format!("{byte:02x}"));
}
out
}
fn execute_target(
ax: &ApplyEnv<'_>,
run_dir: &Path,
target: &mut EjectTarget,
journal: &mut dyn FnMut(EjectedFile) -> Result<(), CoreError>,
) {
match target.outcome {
TargetOutcome::Blocked | TargetOutcome::Failed | TargetOutcome::Unchanged => return,
TargetOutcome::Planned | TargetOutcome::Written => {}
}
let (Some(before), Some(after)) = (target.before.clone(), target.after.clone()) else {
target.outcome = TargetOutcome::Unchanged;
return;
};
let result = self_check(target, &before, &after)
.and_then(|()| backup::save(ax.fs, ax.home, run_dir, &target.file, &before))
.and_then(|path| {
target.backup = Some(path.clone());
journal(EjectedFile {
file: target.file.to_string_lossy().into_owned(),
backup: Some(path.to_string_lossy().into_owned()),
written: sha256(&after),
})
})
.and_then(|()| swap_file(ax.fs, &target.file, Some(&before), &after));
match result {
Ok(true) => target.outcome = TargetOutcome::Written,
Ok(false) => {
target.outcome = TargetOutcome::Failed;
target.error = Some(
CoreError::new(
ErrorCode::FileChangedDuringApply,
"the file changed while ejecting; it was left as it is (run eject again)",
)
.with_path(&target.file),
);
}
Err(err) => {
if let Some(kind) = err.read_only() {
target.read_only = Some(kind);
target.outcome = TargetOutcome::Blocked;
} else {
target.outcome = TargetOutcome::Failed;
}
target.error = Some(err);
}
}
}
fn self_check(target: &EjectTarget, before: &[u8], after: &[u8]) -> Result<(), CoreError> {
let fail = |detail: String| {
Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&target.file))
};
let format = target.format.expect("a planned target has a format");
let before_doc = Document::parse(before, format)?;
let after_doc = match Document::parse(after, format) {
Ok(doc) => doc,
Err(err) => return fail(format!("the edited file does not parse: {err}")),
};
let mut before_root = document_value(&before_doc)?;
let mut after_root = document_value(&after_doc)?;
let mut containers: Vec<&Vec<String>> = Vec::new();
for (keys, _, _, _) in &target.rewrites {
if !containers.contains(&keys) {
containers.push(keys);
}
}
for keys in containers {
let container: Vec<&str> = keys.iter().map(String::as_str).collect();
let names = before_doc.list(&container)?;
if names != after_doc.list(&container)? {
return fail("the entries of a container changed".to_owned());
}
for name in &names {
let got = after_doc.get(&container, name)?;
let planned = target
.rewrites
.iter()
.find(|(k, key, _, _)| k == keys && key == name);
let ok = match planned {
Some((_, _, client, want)) => got
.as_ref()
.is_some_and(|got| canonical(client, got) == canonical(client, want)),
None => got == before_doc.get(&container, name)?,
};
if !ok {
return fail(format!("entry {name:?} does not read back as planned"));
}
}
strip_container(&mut before_root, &container);
strip_container(&mut after_root, &container);
}
if before_root != after_root {
return fail("something outside the server containers changed".to_owned());
}
Ok(())
}
fn plan_skill(fs: &dyn Fs, link: &SkillLink, keep_agent_skill: bool) -> EjectSkill {
let path = PathBuf::from(&link.path);
let agent = link.skill_id == crate::agent::SKILL_ID && !keep_agent_skill;
let mut skill = EjectSkill {
client: link.client.clone(),
scope: link.scope,
project_id: link.project_id.clone(),
skill_id: link.skill_id.clone(),
path: path.clone(),
method: link.method,
action: SkillAction::Changed,
done: false,
read_only: None,
error: None,
row: link.clone(),
};
let aside = aside_link(&path);
let found = entry(fs, &path).and_then(|found| match found {
Entry::Missing if matches!(entry(fs, &aside)?, Entry::Link(_)) => entry(fs, &aside),
found => Ok(found),
});
let found = found.and_then(|found| {
Ok(match found {
Entry::Missing => SkillAction::Gone,
Entry::Link(to)
if link.method != LinkMethod::Copy
&& same_folder(fs, &to, Path::new(&link.target)) =>
{
if agent {
SkillAction::Remove
} else {
SkillAction::Copy
}
}
Entry::Dir if link.method == LinkMethod::Copy => {
match unchanged_copy(fs, &path, link)? {
None => SkillAction::Changed,
Some(_) if agent => SkillAction::Remove,
Some(_) => SkillAction::Keep,
}
}
_ => SkillAction::Changed,
})
});
match found {
Ok(action) => skill.action = action,
Err(err) => {
skill.error = Some(err);
return skill;
}
}
if matches!(
skill.action,
SkillAction::Copy | SkillAction::Keep | SkillAction::Remove
) && let Some(kind) = new_folder_access(fs, &temp_folder(&path)).read_only()
{
skill.read_only = Some(kind);
skill.error = Some(access::read_only_target(kind, &path));
}
skill
}
fn temp_folder(path: &Path) -> PathBuf {
sibling(path, "surjection-eject")
}
fn aside_link(path: &Path) -> PathBuf {
sibling(path, "surjection-link")
}
fn sibling(path: &Path, suffix: &str) -> PathBuf {
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
path.with_file_name(format!(".{name}.{suffix}"))
}
fn recover_leftovers(fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
let aside = aside_link(path);
if matches!(entry(fs, &aside)?, Entry::Link(_)) {
if entry(fs, path)? == Entry::Missing {
fs.replace(&aside, path).map_err(|err| {
crate::access::write_error(fs, "cannot put the link back", path, &err)
})?;
} else {
remove_link(fs, &aside)?;
}
}
let temp = temp_folder(path);
if fs.is_dir(&temp) {
remove_copy(fs, &temp)?;
}
Ok(())
}
fn execute_skill(
fs: &dyn Fs,
skill: &mut EjectSkill,
run: &mut EjectRun,
hooks: &EjectHooks,
journal: &mut dyn FnMut(&EjectRun) -> Result<(), CoreError>,
) {
if skill.error.is_some() {
return;
}
let path = skill.path.clone();
let done = (|| -> Result<(), CoreError> {
if skill.action != SkillAction::Gone {
recover_leftovers(fs, &path)?;
}
match skill.action {
SkillAction::Changed | SkillAction::Gone => Ok(()),
SkillAction::Remove => match skill.method {
LinkMethod::Copy => remove_copy(fs, &path),
LinkMethod::Junction | LinkMethod::Symlink => remove_link(fs, &path),
},
SkillAction::Keep => {
for marker in [MARKER_FILE, LEGACY_MARKER_FILE].map(|name| path.join(name)) {
if fs.exists(&marker) {
fs.remove_file(&marker).map_err(|err| {
crate::skills::removal_error(fs, "cannot remove file", &marker, &err)
})?;
}
}
run.unmarked.push(path.to_string_lossy().into_owned());
Ok(())
}
SkillAction::Copy => {
let files = read_folder(fs, Path::new(&skill.row.target))?;
run.copied.push(CopiedSkill {
path: path.to_string_lossy().into_owned(),
hash: content_hash(&files),
});
journal(run)?;
copy_in_place(fs, &skill.row, &files, hooks.fail_skill_move).inspect_err(|_| {
run.copied.pop();
})
}
}
})();
match done {
Ok(()) => skill.done = true,
Err(err) => {
skill.read_only = err.read_only();
skill.error = Some(err);
}
}
}
fn copy_in_place(
fs: &dyn Fs,
link: &SkillLink,
files: &crate::skills::SkillFiles,
fail_move: bool,
) -> Result<(), CoreError> {
let path = PathBuf::from(&link.path);
let temp = temp_folder(&path);
let aside = aside_link(&path);
confine(fs, &temp)?;
confine(fs, &aside)?;
fs.create_dir_all(&temp)
.map_err(|err| crate::access::write_error(fs, "cannot create directory", &temp, &err))?;
write_files(fs, &temp, files)?;
fs.replace(&path, &aside)
.map_err(|err| crate::access::write_error(fs, "cannot move the link aside", &path, &err))?;
let moved = if fail_move {
Err(std::io::Error::other("test hook: the move failed"))
} else {
fs.replace(&temp, &path)
};
if let Err(err) = moved {
let _ = fs.replace(&aside, &path);
let _ = remove_copy(fs, &temp);
return Err(crate::access::write_error(
fs,
"cannot move the copy into place",
&path,
&err,
));
}
let _ = remove_link(fs, &aside);
Ok(())
}
pub fn resume(fs: &dyn Fs, home: &SurjectionHome) -> Result<Vec<String>, CoreError> {
set_resumed(fs, home, None, true)
}
pub fn unresume(fs: &dyn Fs, home: &SurjectionHome, ids: &[String]) -> Result<(), CoreError> {
if ids.is_empty() {
return Ok(());
}
set_resumed(fs, home, Some(ids), false).map(|_| ())
}
fn set_resumed(
fs: &dyn Fs,
home: &SurjectionHome,
ids: Option<&[String]>,
resumed: bool,
) -> Result<Vec<String>, CoreError> {
let state = home.state_dir();
if !fs.exists(&state.join(EJECT_FILE)) {
return Ok(Vec::new());
}
let _lock = StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?;
let mut record = EjectFile::load(fs, &state)?;
let mut changed = Vec::new();
for run in record.runs.iter_mut().filter(|run| !run.rolled_back) {
let chosen = match ids {
Some(ids) => ids.contains(&run.id),
None => !run.resumed,
};
if chosen && run.resumed != resumed {
run.resumed = resumed;
changed.push(run.id.clone());
}
}
if !changed.is_empty() {
record.save(fs, &state)?;
}
Ok(changed)
}
pub fn left_over(fs: &dyn Fs, home: &SurjectionHome) -> Result<usize, CoreError> {
let state = home.state_dir();
let Some(ejected) = status_at(fs, &state)? else {
return Ok(0);
};
let ledger = SkillLedger::load(fs, &state)?;
let mcp = ledger.clone().mcp_mut().entries.clone();
let entries = mcp
.iter()
.filter(|row| ejected.covers(&row.client, row.project_id.as_deref()))
.count();
let links = ledger
.links
.iter()
.filter(|link| ejected.covers(&link.client, link.project_id.as_deref()))
.count();
Ok(entries + links)
}
pub fn last_run(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<EjectRun>, CoreError> {
Ok(EjectFile::load(fs, &home.state_dir())?
.runs
.into_iter()
.rev()
.find(|run| !run.rolled_back))
}
#[derive(Debug)]
pub struct EjectRollback {
pub eject_id: String,
pub restored: Vec<PathBuf>,
pub changed_since: Vec<PathBuf>,
pub errors: Vec<(PathBuf, CoreError)>,
pub skills: Option<SyncReport>,
}
pub fn rollback(
store: Option<&Store<'_>>,
sx: &SkillsEnv<'_>,
id: Option<&str>,
) -> Result<EjectRollback, CoreError> {
let fs = sx.fs;
let state = sx.home.state_dir();
let mut result = {
let _lock = StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?;
let mut record = EjectFile::load(fs, &state)?;
let index = record
.runs
.iter()
.rposition(|run| {
!run.rolled_back && id.is_none_or(|id| run.id.eq_ignore_ascii_case(id))
})
.ok_or_else(|| {
CoreError::new(
ErrorCode::NotFound,
match id {
Some(id) => format!("no eject run {id:?} to roll back on this machine"),
None => "this machine has no eject run to roll back".to_owned(),
},
)
})?;
let run = record.runs[index].clone();
let mut result = EjectRollback {
eject_id: run.id.clone(),
restored: Vec::new(),
changed_since: Vec::new(),
errors: Vec::new(),
skills: None,
};
let reads: Vec<_> = run
.files
.iter()
.map(|file| {
let path = PathBuf::from(&file.file);
let backup = match &file.backup {
Some(backup) => fs.read(Path::new(backup)).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot read backup: {err}"))
.with_path(backup)
}),
None => Err(CoreError::new(
ErrorCode::NotFound,
"the eject recorded no backup of this file",
)
.with_path(&path)),
};
(path, file.written.as_str(), backup)
})
.collect();
for (path, written, backup) in reads {
let outcome = backup.and_then(|backup| {
let current = read_target(fs, &path)?;
let now = current.as_deref().map(sha256);
if now.as_deref() == Some(sha256(&backup).as_str()) {
return Ok(true);
}
if now.as_deref() != Some(written) {
return Ok(false);
}
swap_file(fs, &path, current.as_deref(), &backup)
});
match outcome {
Ok(true) => result.restored.push(path),
Ok(false) => result.changed_since.push(path),
Err(err) => result.errors.push((path, err)),
}
}
let mut ledger = SkillLedger::load(fs, &state)?;
let skipped: HashSet<String> = result
.changed_since
.iter()
.chain(result.errors.iter().map(|(path, _)| path))
.map(|path| path.to_string_lossy().into_owned())
.collect();
for row in &run.ledger {
let newer = ledger.mcp_mut().get(&row.slot(), &row.key).is_some();
if !skipped.contains(&row.file) && !newer {
ledger.mcp_mut().upsert(row.clone());
}
}
let as_copy = |mut row: SkillLink, copied: &CopiedSkill| {
row.method = LinkMethod::Copy;
row.written_hash = Some(copied.hash.clone());
row
};
for copied in &run.copied {
if let Some(owned) = ledger.get(Path::new(&copied.path)).cloned()
&& owned.method != LinkMethod::Copy
{
ledger.upsert(as_copy(owned, copied));
}
}
for row in &run.skill_links {
if ledger.get(Path::new(&row.path)).is_some() {
continue;
}
let row = match run.copied.iter().find(|copied| copied.path == row.path) {
Some(copied) => as_copy(row.clone(), copied),
None => {
if run.unmarked.contains(&row.path) {
let marker = Path::new(&row.path).join(MARKER_FILE);
if fs.is_dir(Path::new(&row.path)) && !fs.exists(&marker) {
fs.write(&marker, marker_text(&row.skill_id).as_bytes())
.map_err(|err| {
crate::access::write_error(
fs,
"cannot write file",
&marker,
&err,
)
})?;
}
}
row.clone()
}
};
ledger.upsert(row);
}
ledger.save(fs, &state)?;
if result.errors.is_empty() {
record.runs[index].rolled_back = true;
record.save(fs, &state)?;
}
result
};
if let Some(store) = store {
result.skills = Some(link::sync(store, sx)?);
}
Ok(result)
}