use std::path::Path;
use memstead_schema::workspace_config::CrossLinkValue;
use crate::FullEngineError;
use crate::backend::BackendError;
use crate::engine::GitBranchOps;
use crate::ops::WarningHint;
use crate::vcs::CommitContext;
use crate::workspace_config_edit::{
CrossLinkTarget, grant_cross_link, scrub_policy_for_deleted_mem,
};
use super::lifecycle::{
NOTE_MAX_LEN, ResidueProbe, admit_by_create_rules, classify_invalid_mem_name,
residue_probe_for_workspace, sibling_name_suggestion,
};
#[derive(Debug, Clone)]
pub struct MemForkParams {
pub source: String,
pub sha: Option<String>,
pub name: String,
pub remote: Option<String>,
pub adopt: bool,
pub note: Option<String>,
pub operator_mode: bool,
pub actor: crate::vcs::Actor,
pub client: Option<crate::vcs::ClientId>,
}
#[derive(Debug, Clone)]
pub struct MemForkResponse {
pub name: String,
pub forked_from: memstead_schema::ForkedFrom,
pub schema_ref: memstead_schema::SchemaRef,
pub branch_ref: String,
pub inherited_grants: Option<CrossLinkValue>,
pub warnings: Vec<WarningHint>,
}
pub fn fork_mem(
engine: &mut crate::Engine,
params: MemForkParams,
) -> Result<MemForkResponse, FullEngineError> {
if let Some(note) = params.note.as_deref()
&& note.chars().count() > NOTE_MAX_LEN
{
return Err(crate::EngineError::InvalidInput(format!(
"note exceeds {NOTE_MAX_LEN} characters"
))
.into());
}
if let Some(reason) = classify_invalid_mem_name(¶ms.name) {
return Err(FullEngineError::InvalidMemName {
name: params.name.clone(),
reason,
});
}
if crate::entity::id::validate_mem_name_grammar(¶ms.name).is_err() {
return Err(FullEngineError::InvalidMemName {
name: params.name.clone(),
reason: "invalid_char",
});
}
if crate::entity::id::validate_mem_name_grammar(¶ms.source).is_err() {
return Err(crate::EngineError::InvalidInput(format!(
"source {:?} is not a mem name (grammar `[a-z0-9-]+(/[a-z0-9-]+)*`)",
params.source
))
.into());
}
if params.source == params.name {
return Err(crate::EngineError::InvalidInput(format!(
"a fork needs its own name: {:?} is the source",
params.name
))
.into());
}
if params.adopt {
if params.remote.is_none() {
return Err(crate::EngineError::InvalidInput(
"adopt names a fork branch on a remote: pass the remote it lives on".to_string(),
)
.into());
}
if params.sha.is_some() {
return Err(crate::EngineError::InvalidInput(format!(
"an adopted fork starts at the remote branch's tip: `{}@<sha>` and adopt exclude \
each other",
params.source
))
.into());
}
}
let root = engine
.workspace_root()
.map(Path::to_path_buf)
.ok_or_else(|| {
crate::EngineError::InvalidInput(
"mem fork requires a workspace root to locate mem-repo/.git/".to_string(),
)
})?;
let gitdir = root.join("mem-repo").join(".git");
if !gitdir.is_dir() {
return Err(crate::EngineError::InvalidInput(format!(
"mem fork requires a mem-repo workspace ({} not found): a fork is a branch at \
an ancestor, and a folder-only workspace has no branch to fork",
gitdir.display()
))
.into());
}
let gitdir = gitdir.canonicalize().unwrap_or(gitdir);
let ops = engine.git_branch_ops().ok_or_else(|| {
crate::EngineError::InvalidInput(
"mem fork requires the git-branch ops bundle (full boot only)".to_string(),
)
})?;
let ctx = engine.commit_context(
Some("memstead_mem_fork"),
params.actor,
params.client.clone(),
params.note.clone(),
);
let (config_bytes, tip_ref, adopted_source_ref) = match params.remote.as_deref() {
None => {
let (bytes, tip_ref) = resolve_local_source(engine, &gitdir, ¶ms.source)?;
(bytes, tip_ref, None)
}
Some(remote) if params.adopt => {
let (bytes, source_ref) = resolve_local_source(engine, &gitdir, ¶ms.source)?;
let tracking = fetch_adopted_fork(&ops, &gitdir, remote, ¶ms.source, ¶ms.name)?;
(bytes, tracking, Some(source_ref))
}
Some(remote) => {
let (bytes, tip_ref) = resolve_remote_source(&ops, &gitdir, remote, ¶ms.source)?;
(bytes, tip_ref, None)
}
};
let source_value: serde_json::Value = serde_json::from_slice(&config_bytes).map_err(|e| {
crate::EngineError::InvalidInput(format!(
"source {:?}: its config is not JSON: {e}",
params.source
))
})?;
let source_config = memstead_schema::parse_mem_config(&source_value).map_err(|e| {
crate::EngineError::InvalidInput(format!(
"source {:?}: its config does not parse: {e}",
params.source
))
})?;
let tip = (ops.resolve_ref)(&gitdir, &tip_ref)
.map_err(crate::EngineError::Backend)?
.ok_or_else(|| crate::EngineError::UnknownRef(tip_ref.clone()))?;
let sha = match params.sha.as_deref() {
None => tip.clone(),
Some(raw) => {
let full = (ops.resolve_ref)(&gitdir, &format!("{raw}^{{commit}}"))
.map_err(crate::EngineError::Backend)?
.ok_or_else(|| {
crate::EngineError::UnknownRef(format!(
"{raw} is not a commit in the mem-repo (source branch {tip_ref})"
))
})?;
let on_branch = (ops.is_ancestor)(&gitdir, &full, &tip).map_err(|e| {
crate::EngineError::UnknownRef(format!(
"{raw} could not be placed against {tip_ref}: {e}"
))
})?;
if !on_branch {
return Err(crate::EngineError::UnknownRef(format!(
"{raw} is not on {tip_ref} (tip {tip}): a fork starts at a commit the \
source branch reaches"
))
.into());
}
full
}
};
let ancestor = match &adopted_source_ref {
None => sha.clone(),
Some(source_ref) => {
let source_tip = (ops.resolve_ref)(&gitdir, source_ref)
.map_err(crate::EngineError::Backend)?
.ok_or_else(|| crate::EngineError::UnknownRef(source_ref.clone()))?;
(ops.merge_base)(&gitdir, &sha, &source_tip)
.map_err(crate::EngineError::Backend)?
.ok_or_else(|| {
crate::EngineError::UnknownRef(format!(
"remote branch {} at {sha} shares no history with the local source {:?} \
at {source_tip}: it is not a fork of this mem",
tip_ref, params.source
))
})?
}
};
let pin = source_config.schema.clone().ok_or_else(|| {
crate::EngineError::InvalidInput(format!(
"source {:?}: its config declares no schema pin",
params.source
))
})?;
let mut catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> =
engine.workspace_schemas().to_vec();
catalogue.extend_from_slice(engine.builtin_schemas());
let resolved_schema = crate::engine::SchemaResolver::new(&catalogue)
.resolve(&pin)
.map_err(|sources| {
let hint = crate::engine::error::probe_authoring_package(&root, &pin.name)
.unwrap_or_else(|| {
crate::engine::error::SCHEMA_INSTALL_PACKAGE_UNKNOWN.to_string()
});
crate::EngineError::SchemaNotFound {
mem: params.name.clone(),
pin: pin.to_string(),
sources,
install_hint: Some(hint),
}
})?;
let canonical_schema_ref = memstead_schema::SchemaRef::new(
resolved_schema.manifest.name.clone(),
resolved_schema.version.clone(),
);
let canonical_location = root.join(¶ms.name);
if !params.operator_mode {
admit_by_create_rules(
engine,
¶ms.name,
&canonical_location,
&canonical_schema_ref,
&catalogue,
)?;
}
if let Some(existing) = engine.mem_router().origin_for_mem(¶ms.name) {
return Err(crate::EngineError::MemNameCollision {
name: params.name,
source_origin: existing.render_source(),
}
.into());
}
if engine
.mem_router()
.archive_path_for_mem(¶ms.name)
.is_some()
{
return Err(crate::EngineError::MemNameCollision {
name: params.name,
source_origin: "attached read mem".to_string(),
}
.into());
}
let conflicting = (ops.branch_namespace_conflicts)(&gitdir, ¶ms.name)
.map_err(|e| crate::EngineError::Mem(format!("ref namespace probe: {e}")))?;
if !conflicting.is_empty() {
let suggestion = sibling_name_suggestion(¶ms.name, &conflicting);
return Err(FullEngineError::MemNameRefConflict {
branch_ref: format!("refs/heads/{}", params.name),
name: params.name,
conflicting_branches: conflicting,
suggestion,
});
}
if let ResidueProbe::Present {
branch_ref,
config_blob,
..
} = residue_probe_for_workspace(
engine,
Some(&root),
¶ms.name,
¶ms.name,
&canonical_schema_ref,
) {
return Err(FullEngineError::MemStorageResidueDetected {
branch_ref,
config_blob,
entity_count: 0,
});
}
if params.remote.is_some() {
crate::Engine::validate_ref_with_schema(
&ops,
&gitdir,
¶ms.name,
&sha,
resolved_schema.as_ref(),
)?;
}
let mut config = source_config;
config.name = None;
config.sync_state.clear();
config.review_mark = None;
config.unregistered_at = None;
let branch_ref = format!("refs/heads/{}", params.name);
(ops.create_branch_at)(&gitdir, ¶ms.name, &sha)
.map_err(|e| crate::EngineError::Mem(format!("fork branch: {e}")))?;
let mount = crate::workspace::Mount {
mem: params.name.clone(),
schema: Some(canonical_schema_ref.clone()),
storage: crate::workspace::MountStorage::GitBranch {
gitdir: gitdir.clone(),
branch: branch_ref.clone(),
},
capability: crate::workspace::MountCapability::Write,
lifecycle: crate::workspace::MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let factory = engine.backend_factory();
let backend = match factory(&mount) {
Ok(b) => b,
Err(e) => {
roll_back(
&ops,
&gitdir,
&root,
¶ms.name,
&ctx,
"backend instantiate",
);
return Err(crate::EngineError::Mem(format!("instantiate backend: {e}")).into());
}
};
let base = if params.adopt {
match adopted_fork_base(
&ops,
&gitdir,
&branch_ref,
¶ms.name,
¶ms.source,
&ancestor,
) {
Ok(base) => base,
Err(e) => {
roll_back(
&ops,
&gitdir,
&root,
¶ms.name,
&ctx,
"fork commit lookup",
);
return Err(e.into());
}
}
} else {
match retarget_fork_tree(backend.as_ref(), ¶ms.source, ¶ms.name, &sha, &ctx) {
Ok(base) => Some(base),
Err(e) => {
roll_back(&ops, &gitdir, &root, ¶ms.name, &ctx, "fork commit");
return Err(e.into());
}
}
};
let forked_from = memstead_schema::ForkedFrom {
mem: params.source.clone(),
sha: ancestor.clone(),
remote: params.remote.clone(),
base,
};
config.forked_from = Some(forked_from.clone());
let config_bytes = match serde_json::to_vec_pretty(&config) {
Ok(mut bytes) => {
bytes.push(b'\n');
bytes
}
Err(e) => {
roll_back(&ops, &gitdir, &root, ¶ms.name, &ctx, "config serialize");
return Err(crate::EngineError::InvalidInput(format!(
"could not serialize the fork's config: {e}"
))
.into());
}
};
if let Err(e) = backend.write_mem_config(&config_bytes, &ctx) {
roll_back(&ops, &gitdir, &root, ¶ms.name, &ctx, "config write");
return Err(crate::EngineError::Mem(format!("write mem config: {e}")).into());
}
let inherited_grants: Option<CrossLinkValue> = if params.remote.is_none() {
match engine.settings().cross_mem_links.get(¶ms.source) {
Some(CrossLinkValue::List(targets)) if targets.is_empty() => None,
other => other.cloned(),
}
} else {
None
};
if let Some(value) = &inherited_grants
&& let Err(e) = write_inherited_grants(engine, &root, ¶ms.name, value)
{
roll_back(
&ops,
&gitdir,
&root,
¶ms.name,
&ctx,
"grant inheritance",
);
return Err(crate::EngineError::Mem(format!("inherit cross-link grants: {e}")).into());
}
let origin = crate::MemOrigin::RuntimeCreated {
at: std::time::SystemTime::now(),
by_tool: "memstead_mem_fork",
};
if let Err(e) = engine.register_writable_mem(mount, backend, origin) {
roll_back(
&ops,
&gitdir,
&root,
¶ms.name,
&ctx,
"mount registration",
);
return Err(e.into());
}
if let Some(value) = &inherited_grants {
let mut settings = engine.settings().clone();
settings
.cross_mem_links
.insert(params.name.clone(), value.clone());
engine.set_settings(settings);
}
engine.persist_state()?;
let warnings: Vec<WarningHint> = engine
.note_missing_warning("fork_mem", params.note.as_deref())
.into_iter()
.collect();
Ok(MemForkResponse {
name: params.name,
forked_from,
schema_ref: canonical_schema_ref,
branch_ref,
inherited_grants,
warnings,
})
}
fn retarget_fork_tree(
backend: &dyn crate::backend::MemBackend,
source: &str,
fork: &str,
ancestor: &str,
ctx: &CommitContext<'_>,
) -> Result<String, crate::EngineError> {
if let Some(bytes) = backend.read_anchors_sidecar()? {
let mut sidecar = crate::anchor::AnchorSidecar::from_bytes(&bytes).map_err(|e| {
crate::EngineError::Mem(format!(
"fork {fork:?}: the source's anchors sidecar does not parse: {e}"
))
})?;
let mut moved = false;
for row in sidecar.entities.values_mut().flatten() {
if row.grain == crate::anchor::AnchorGrain::Entity
&& let Some(to) = retarget_entity_id(&row.artifact, source, fork)
{
row.artifact = to;
moved = true;
}
for input in &mut row.derived_from {
if let Some(to) = retarget_entity_id(input, source, fork) {
*input = to;
moved = true;
}
}
}
let keys: Vec<String> = sidecar.entities.keys().cloned().collect();
for key in keys {
if let Some(to) = retarget_entity_id(&key, source, fork) {
sidecar.rename(&key, &to);
moved = true;
}
}
if moved {
backend.write_anchors_sidecar(&sidecar.to_bytes())?;
}
}
let derivations_path = Path::new(crate::derivation::DERIVATION_SIDECAR_PATH);
if let Some(bytes) = backend.read_entity(derivations_path)? {
let sidecar = crate::derivation::DerivationSidecar::from_bytes(&bytes).map_err(|e| {
crate::EngineError::Mem(format!(
"fork {fork:?}: the source's derivations sidecar does not parse: {e}"
))
})?;
let mut moved = false;
let mut retargeted = crate::derivation::DerivationSidecar {
version: sidecar.version,
baselines: Default::default(),
};
for (key, baselines) in sidecar.baselines {
let key = match retarget_entity_id(&key, source, fork) {
Some(to) => {
moved = true;
to
}
None => key,
};
let baselines = baselines
.into_iter()
.map(|mut b| {
if let Some(to) = retarget_entity_id(&b.target, source, fork) {
b.target = to;
moved = true;
}
b
})
.collect();
retargeted.baselines.insert(key, baselines);
}
if moved {
backend.write_entity(derivations_path, &retargeted.to_bytes())?;
}
}
for rel_path in backend.list_entities()? {
let Some(bytes) = backend.read_entity(&rel_path)? else {
continue;
};
let retargeted = crate::ops::export::retarget_mem_links(bytes.clone(), source, fork);
if retargeted != bytes {
backend.write_entity(&rel_path, &retargeted)?;
}
}
backend.delete_entity(std::path::Path::new(
crate::ops::proposal::PROPOSAL_RECORD_PATH,
))?;
let short = &ancestor[..ancestor.len().min(12)];
let subject = format!("memstead: fork mem {fork} from {source}@{short}");
Ok(backend.commit(&subject, ctx)?)
}
fn retarget_entity_id(id: &str, source: &str, fork: &str) -> Option<String> {
let slug = id.strip_prefix(source)?.strip_prefix("--")?;
(!slug.is_empty()).then(|| format!("{fork}--{slug}"))
}
fn resolve_local_source(
engine: &crate::Engine,
gitdir: &Path,
source: &str,
) -> Result<(Vec<u8>, String), FullEngineError> {
let mount = engine
.mount(source)
.cloned()
.ok_or_else(|| engine.unknown_mem_error(source))?;
let branch = match &mount.storage {
crate::workspace::MountStorage::GitBranch {
gitdir: source_gitdir,
branch,
} => {
let source_gitdir = source_gitdir
.canonicalize()
.unwrap_or(source_gitdir.clone());
if source_gitdir != gitdir {
return Err(crate::EngineError::InvalidInput(format!(
"source {source:?} lives in {} and not in the workspace mem-repo {}: a fork \
is a branch of the same mem-repo",
source_gitdir.display(),
gitdir.display()
))
.into());
}
crate::workspace::branch_full_ref(branch)
}
crate::workspace::MountStorage::Folder { .. } => {
return Err(crate::EngineError::InvalidInput(format!(
"source {source:?} is a folder mem: a fork needs a git-branch source, because \
the branch is the lineage"
))
.into());
}
crate::workspace::MountStorage::Archive { .. } => {
return Err(crate::EngineError::InvalidInput(format!(
"source {source:?} is a sealed archive mount: a fork needs a git-branch source, \
because the branch is the lineage"
))
.into());
}
crate::workspace::MountStorage::InMemory => {
return Err(crate::EngineError::InvalidInput(format!(
"source {source:?} is an in-memory mem: a fork needs a git-branch source, \
because the branch is the lineage"
))
.into());
}
};
let factory = engine.backend_factory();
let backend = factory(&mount)
.map_err(|e| crate::EngineError::Mem(format!("source backend instantiate: {e}")))?;
let bytes = backend
.read_mem_config()
.map_err(crate::EngineError::Backend)?
.ok_or_else(|| {
crate::EngineError::Mem(format!(
"source {source:?}: no config on __MEMSTEAD:mems/{source}/config.json"
))
})?;
Ok((bytes, branch))
}
fn resolve_remote_source(
ops: &GitBranchOps,
gitdir: &Path,
remote: &str,
source: &str,
) -> Result<(Vec<u8>, String), FullEngineError> {
let heads = (ops.ls_remote)(gitdir, remote).map_err(lift_remote_marker)?;
let source_ref = format!("refs/heads/{source}");
if !heads.iter().any(|(name, _)| name == &source_ref) {
return Err(crate::EngineError::UnknownRef(format!(
"remote {remote:?} has no branch {source_ref}: the source mem {source:?} is not on \
that remote"
))
.into());
}
if !heads
.iter()
.any(|(name, _)| name == "refs/heads/__MEMSTEAD")
{
return Err(crate::EngineError::InvalidInput(format!(
"remote {remote:?} carries no __MEMSTEAD ref: it is not a mem-repo, so there is no \
config to fork from it; a fork branch of a mem this workspace mounts that already \
lives on the remote is adopted instead (`memstead mem fork <source> <name> --remote \
{remote} --adopt`), which derives the config from the local source"
))
.into());
}
let tracking_source = format!("refs/remotes/{remote}/{source}");
let tracking_registry = format!("refs/remotes/{remote}/__MEMSTEAD");
(ops.fetch)(
gitdir,
remote,
&[
format!("+{source_ref}:{tracking_source}"),
format!("+refs/heads/__MEMSTEAD:{tracking_registry}"),
],
)
.map_err(lift_remote_marker)?;
let bytes = (ops.read_config_at_ref)(gitdir, &tracking_registry, source)
.map_err(crate::EngineError::Backend)?
.ok_or_else(|| {
crate::EngineError::InvalidInput(format!(
"remote {remote:?}: its __MEMSTEAD carries no config for {source:?} \
(mems/{source}/config.json)"
))
})?;
Ok((bytes, tracking_source))
}
fn fetch_adopted_fork(
ops: &GitBranchOps,
gitdir: &Path,
remote: &str,
source: &str,
name: &str,
) -> Result<String, FullEngineError> {
let heads = (ops.ls_remote)(gitdir, remote).map_err(lift_remote_marker)?;
let fork_ref = format!("refs/heads/{name}");
if !heads.iter().any(|(head, _)| head == &fork_ref) {
return Err(crate::EngineError::UnknownRef(format!(
"remote {remote:?} has no branch {fork_ref}: nothing to adopt as {name:?} (a fork \
that does not exist yet is made with `memstead mem fork {source} {name}`)"
))
.into());
}
let tracking = format!("refs/remotes/{remote}/{name}");
(ops.fetch)(gitdir, remote, &[format!("+{fork_ref}:{tracking}")])
.map_err(lift_remote_marker)?;
Ok(tracking)
}
fn adopted_fork_base(
ops: &GitBranchOps,
gitdir: &Path,
branch_ref: &str,
name: &str,
source: &str,
ancestor: &str,
) -> Result<Option<String>, crate::EngineError> {
let changes = (ops.changes_since)(
gitdir,
branch_ref,
name,
ancestor,
crate::ops::RENAME_SIMILARITY_DEFAULT,
)
.map_err(crate::EngineError::Backend)?;
let prefix = format!("memstead: fork mem {name} from {source}@");
Ok(changes
.notes
.iter()
.filter(|n| n.tool_verb.as_deref() == Some("fork") && n.subject.starts_with(&prefix))
.map(|n| n.sha.clone())
.next_back())
}
fn lift_remote_marker(e: BackendError) -> FullEngineError {
match e {
BackendError::Other(msg) if msg.starts_with("UNKNOWN_REMOTE:") => {
crate::EngineError::UnknownRemote(
msg.trim_start_matches("UNKNOWN_REMOTE:").trim().to_string(),
)
.into()
}
other => crate::EngineError::Backend(other).into(),
}
}
fn write_inherited_grants(
engine: &crate::Engine,
root: &Path,
name: &str,
value: &CrossLinkValue,
) -> Result<(), crate::workspace_config_edit::WorkspaceEditError> {
let known: Vec<String> = engine.mem_names().into_iter().map(str::to_string).collect();
match value {
CrossLinkValue::Wildcard => {
grant_cross_link(root, name, &CrossLinkTarget::Wildcard, &known)?;
}
CrossLinkValue::List(targets) => {
for target in targets {
grant_cross_link(root, name, &CrossLinkTarget::Named(target.clone()), &known)?;
}
}
}
Ok(())
}
fn roll_back(
ops: &GitBranchOps,
gitdir: &Path,
root: &Path,
name: &str,
ctx: &CommitContext<'_>,
stage: &str,
) {
if let Err(e) = (ops.prune_residue)(gitdir, name, ctx) {
tracing::warn!(
mem = %name,
stage,
error = %e,
"fork_mem: {stage} failed and the branch rollback failed too; \
`memstead mem delete <name> --operator-mode` removes the leftover"
);
}
if let Err(e) = scrub_policy_for_deleted_mem(root, name) {
tracing::warn!(
mem = %name,
stage,
error = %e,
"fork_mem: {stage} failed and the policy rollback failed too; \
`memstead workspace revoke-cross-link <name> <target>` removes the leftover"
);
}
}
#[cfg(test)]
mod tests {
use super::retarget_entity_id;
#[test]
fn retarget_entity_id_moves_the_sources_ids_and_nothing_else() {
assert_eq!(
retarget_entity_id("specs--alpha", "specs", "specs-fork").as_deref(),
Some("specs-fork--alpha")
);
assert_eq!(
retarget_entity_id(
"library/sample--claim-one",
"library/sample",
"proposals/sample-001"
)
.as_deref(),
Some("proposals/sample-001--claim-one")
);
assert_eq!(
retarget_entity_id("specs--a--b", "specs", "f").as_deref(),
Some("f--a--b")
);
assert_eq!(retarget_entity_id("plans--roadmap", "specs", "f"), None);
assert_eq!(retarget_entity_id("specs-old--alpha", "specs", "f"), None);
assert_eq!(retarget_entity_id("alpha", "specs", "f"), None);
assert_eq!(retarget_entity_id("specs--", "specs", "f"), None);
}
}