Admit repository Body observations into Mind

This commit is contained in:
Meta Vens 2026-08-17 19:50:45 +02:00
commit 2eb95df627
7 changed files with 271 additions and 12 deletions

View file

@ -1255,7 +1255,11 @@ mod tests {
Some(claim.clone())
);
assert_eq!(
cache.get_all::<crate::EpiphanyMindCommitReceipt>()?.len(),
cache
.get_all::<crate::EpiphanyMindCommitReceipt>()?
.into_iter()
.filter(|receipt| receipt.invariant_owner.starts_with("Modeling.atlas."))
.count(),
2
);

View file

@ -3,10 +3,11 @@ use chrono::Utc;
use epiphany_core::{
EpiphanyMemoryAnchor, EpiphanyMemoryDomain, EpiphanyMemoryLifecycle, EpiphanyMemoryNode,
EpiphanyMemoryNodeKind, EpiphanyMemoryProfile, EpiphanyRepoModelSeed,
EpiphanyRepoModelSeedDocuments, ObserveOutcome, RuntimeSpineInitOptions, bind_repository_body,
bind_runtime_to_agent_memory_swarm, bind_runtime_workspace_coverage_store,
ensure_agent_memory_swarm_identity, initialize_fresh_agent_memory_store,
initialize_keyed_repo_model, initialize_runtime_spine, load_repository_body_status,
EpiphanyRepoModelSeedDocuments, ObserveOutcome, RuntimeSpineInitOptions,
admit_repository_body_observation, bind_repository_body, bind_runtime_to_agent_memory_swarm,
bind_runtime_workspace_coverage_store, ensure_agent_memory_swarm_identity,
initialize_fresh_agent_memory_store, initialize_keyed_repo_model, initialize_runtime_spine,
load_current_runtime_repository_body_basis, load_repository_body_status,
observe_repository_body,
};
use std::path::PathBuf;
@ -41,6 +42,8 @@ fn main() -> Result<()> {
let binding = bind_repository_body(&repo, &store, &runtime_store, workspace_id)?;
bind_runtime_workspace_coverage_store(&runtime_store, &workspace_coverage_store, &at)?;
observe_repository_body(&repo, &store, &runtime_store)?;
let body_basis = load_current_runtime_repository_body_basis(&runtime_store)?;
admit_repository_body_observation(&runtime_store, &body_basis)?;
let seed = EpiphanyRepoModelSeed::new(
format!("repo-model-seed-{}", binding.runtime_id),
format!("{}-repo-model", binding.runtime_id),
@ -122,11 +125,14 @@ fn main() -> Result<()> {
let repo = required(&args, "--repo")?;
let store = required(&args, "--store")?;
let runtime_store = required(&args, "--runtime-store")?;
match observe_repository_body(
let outcome = observe_repository_body(
&PathBuf::from(repo),
&PathBuf::from(store),
&PathBuf::from(runtime_store),
)? {
)?;
let basis = load_current_runtime_repository_body_basis(&PathBuf::from(runtime_store))?;
admit_repository_body_observation(&PathBuf::from(runtime_store), &basis)?;
match outcome {
ObserveOutcome::Created(value) => println!(
"created generation={} tree={}",
value.generation, value.tree_oid
@ -204,6 +210,8 @@ fn smoke() -> Result<()> {
"2026-07-15T00:00:02Z",
)?;
let outcome = observe_repository_body(&root, &store, &runtime_store)?;
let basis = load_current_runtime_repository_body_basis(&runtime_store)?;
admit_repository_body_observation(&runtime_store, &basis)?;
let observed = load_repository_body_status(&store)?
.ok_or_else(|| anyhow::anyhow!("smoke observation missing after commit"))?;
std::fs::remove_file(&store)?;

View file

@ -187,7 +187,8 @@ pub(crate) fn body_modeling_decision_envelope(
pub fn current_body_modeling_work(
store_path: impl AsRef<Path>,
) -> Result<EpiphanyBodyModelingWorkProjection> {
let body_basis = crate::observe_runtime_repository_body_basis(store_path.as_ref())?;
let body_basis = crate::current_mind_repository_body_observation(store_path.as_ref())?
.ok_or_else(|| anyhow!("Mind has no admitted repository Body observation"))?;
let repo_model_basis = crate::assemble_repo_model_view(store_path.as_ref())?.reasoning_basis();
EpiphanyBodyModelingWorkProjection::derive(
body_basis.runtime_id.clone(),
@ -385,6 +386,10 @@ mod tests {
)?,
"2026-08-17T00:00:01Z",
)?;
crate::reset_repository_body_read_counters();
let projected_work = current_body_modeling_work(&store)?;
assert_eq!(projected_work.body_basis, body);
assert_eq!(crate::repository_body_read_counters(), (0, 0));
let document =
crate::EpiphanyWorkerLaunchDocument::Role(crate::EpiphanyRoleWorkerLaunchDocument {
thread_id: "creation-thread".into(),

View file

@ -18,6 +18,51 @@ pub const MIND_OBJECTIVE_KEY: &str = "objective";
pub const MIND_FOCUS_KEY: &str = "focus";
pub const MIND_MODE_KEY: &str = "mode";
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "epiphany.mind.repository_body_observation.v1",
schema = "EpiphanyMindRepositoryBodyObservationDocument"
)]
pub struct EpiphanyMindRepositoryBodyObservationDocument {
#[cultcache(key = 0)]
pub basis: crate::RepositoryBodyObservationBasis,
#[cultcache(key = 1)]
pub source_observation: EpiphanyMindDocumentVersion,
}
impl EpiphanyMindRepositoryBodyObservationDocument {
pub fn validate(&self) -> Result<()> {
self.source_observation.validate()?;
if self.source_observation.store_id != "epiphany-repository-body"
|| self.source_observation.document_type != crate::BODY_OBSERVATION_TYPE
|| self.source_observation.document_key != self.basis.observation_id
{
return Err(anyhow!(
"Mind Body observation does not bind its exact external observation"
));
}
let source: crate::RepositoryBodyObservation =
rmp_serde::from_slice(&self.source_observation.payload_msgpack)?;
if self.basis.schema_version != crate::BODY_SCHEMA_VERSION
|| source.schema_version != self.basis.schema_version
|| source.observation_id != self.basis.observation_id
|| source.workspace_id != self.basis.workspace_id
|| source.swarm_id != self.basis.swarm_id
|| source.runtime_id != self.basis.runtime_id
|| source.scope != self.basis.scope
|| source.generation != self.basis.generation
|| source.manifest_root_sha256 != self.basis.manifest_root_sha256
|| source.scan_started_at != self.basis.scan_started_at
|| source.scan_finished_at != self.basis.scan_finished_at
{
return Err(anyhow!(
"Mind Body observation basis diverges from its exact source payload"
));
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "epiphany.mind.identity.v1", schema = "EpiphanyMindIdentity")]
pub struct EpiphanyMindIdentity {
@ -158,6 +203,7 @@ pub struct EpiphanyMindView {
pub investigation_checkpoint: Option<EpiphanyInvestigationCheckpoint>,
pub mode: Option<EpiphanyModeState>,
pub planning: EpiphanyPlanningState,
pub repository_body_observation: Option<crate::RepositoryBodyObservationBasis>,
pub repo_model: Option<crate::EpiphanyRepoModelView>,
}
@ -175,6 +221,7 @@ pub(crate) fn register_mind_document_types(cache: &mut CultCache) -> Result<()>
cache.register_entry_type::<EpiphanyMindBacklogItemDocument>()?;
cache.register_entry_type::<EpiphanyMindRoadmapStreamDocument>()?;
cache.register_entry_type::<EpiphanyMindObjectiveDraftDocument>()?;
cache.register_entry_type::<EpiphanyMindRepositoryBodyObservationDocument>()?;
crate::repo_model_documents::register_repo_model_document_types(cache)?;
cache.register_entry_type::<crate::RepoFrontierPlanDecisionReceipt>()?;
cache.register_entry_type::<crate::RepoFrontierRelinquishmentReceipt>()?;
@ -288,6 +335,11 @@ pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Resu
rmp_serde::from_slice::<EpiphanyMindObjectiveDraftDocument>(&envelope.payload)?
.value
.id
} else if envelope.r#type == EpiphanyMindRepositoryBodyObservationDocument::TYPE {
let value: EpiphanyMindRepositoryBodyObservationDocument =
rmp_serde::from_slice(&envelope.payload)?;
value.validate()?;
value.basis.observation_id
} else {
return Err(anyhow!(
"Mind mutation cannot write non-canonical document type {:?}",
@ -336,6 +388,24 @@ pub fn assemble_mind_view(store_path: impl AsRef<Path>) -> Result<EpiphanyMindVi
values::<EpiphanyMindRoadmapStreamDocument, _>(&cache, |value| value.value)?;
let mut objective_drafts =
values::<EpiphanyMindObjectiveDraftDocument, _>(&cache, |value| value.value)?;
let mut body_observations = cache.get_all::<EpiphanyMindRepositoryBodyObservationDocument>()?;
for observation in &body_observations {
observation.validate()?;
if observation.basis.runtime_id != identity.runtime_id {
return Err(anyhow!("Mind Body observation belongs to another runtime"));
}
}
body_observations.sort_by_key(|value| value.basis.generation);
if body_observations.windows(2).any(|pair| {
pair[0].basis.generation == pair[1].basis.generation
|| pair[0].basis.workspace_id != pair[1].basis.workspace_id
|| pair[0].basis.body_binding_sha256 != pair[1].basis.body_binding_sha256
}) {
return Err(anyhow!(
"Mind Body observation chain is not singular and ordered"
));
}
let repository_body_observation = body_observations.last().map(|value| value.basis.clone());
let repo_model = if cache
.get::<crate::EpiphanyRepoModelIdentityDocument>(crate::REPO_MODEL_IDENTITY_KEY)?
.is_some()
@ -398,6 +468,7 @@ pub fn assemble_mind_view(store_path: impl AsRef<Path>) -> Result<EpiphanyMindVi
roadmap_streams,
objective_drafts,
},
repository_body_observation,
repo_model,
})
}
@ -430,6 +501,7 @@ fn canonical_mind_versions(
| EpiphanyMindBacklogItemDocument::TYPE
| EpiphanyMindRoadmapStreamDocument::TYPE
| EpiphanyMindObjectiveDraftDocument::TYPE
| EpiphanyMindRepositoryBodyObservationDocument::TYPE
)
})
.map(|envelope| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", envelope))

View file

@ -109,6 +109,7 @@ pub struct EpiphanyMindPromptProjection {
pub investigation_checkpoint: Option<epiphany_state_model::EpiphanyInvestigationCheckpoint>,
pub mode: Option<epiphany_state_model::EpiphanyModeState>,
pub planning: epiphany_state_model::EpiphanyPlanningState,
pub repository_body_observation: Option<crate::RepositoryBodyObservationBasis>,
pub repo_model: Option<EpiphanyRepoModelPromptProjection>,
}
@ -127,6 +128,7 @@ impl From<crate::EpiphanyMindView> for EpiphanyMindPromptProjection {
investigation_checkpoint: value.investigation_checkpoint,
mode: value.mode,
planning: value.planning,
repository_body_observation: value.repository_body_observation,
repo_model: value.repo_model.map(Into::into),
}
}
@ -549,6 +551,8 @@ pub fn put_reasoning_basis(
if projection.authority != document.into()
|| projection.mind != current_mind.clone().into()
|| basis.source_documents != current_mind.source_documents
|| projection.authority.repository_body_observation_basis
!= current_mind.repository_body_observation
{
return Err(anyhow!(
"role reasoning projection diverges from its exact launch or keyed Mind sources"
@ -865,6 +869,31 @@ pub fn commit_typed_organ_mind_mutation(
)
}
pub(crate) fn commit_external_typed_observation_mind_mutation(
store_path: &Path,
organ: &str,
provenance: EpiphanyMindDocumentVersion,
invariant_owner: &str,
strong_reads: Vec<CultCacheEnvelope>,
writes: Vec<CultCacheEnvelope>,
committed_at: &str,
) -> Result<EpiphanyMindCommitOutcome> {
require_non_empty(organ, "Mind mutation organ")?;
provenance.validate()?;
commit_authorized_mind_mutation(
store_path,
EpiphanyMindCommitAuthority::TypedOrganProvenance {
organ: organ.to_string(),
provenance,
},
invariant_owner,
strong_reads,
writes,
Vec::new(),
committed_at,
)
}
fn commit_authorized_mind_mutation(
store_path: &Path,
authority: EpiphanyMindCommitAuthority,
@ -1265,6 +1294,7 @@ mod tests {
investigation_checkpoint: None,
mode: None,
planning: Default::default(),
repository_body_observation: None,
repo_model: None,
},
});

View file

@ -380,7 +380,7 @@ pub fn observe_runtime_repository_body_basis(
)? {
ObserveOutcome::Created(value) | ObserveOutcome::Unchanged(value) => value,
};
Ok(RepositoryBodyObservationBasis {
let basis = RepositoryBodyObservationBasis {
schema_version: BODY_SCHEMA_VERSION.into(),
workspace_id: body.workspace_id,
swarm_id: body.swarm_id,
@ -392,7 +392,59 @@ pub fn observe_runtime_repository_body_basis(
manifest_root_sha256: observation.manifest_root_sha256,
scan_started_at: observation.scan_started_at,
scan_finished_at: observation.scan_finished_at,
})
};
admit_repository_body_observation(runtime_store, &basis)?;
Ok(basis)
}
pub fn admit_repository_body_observation(
runtime_store: &Path,
basis: &RepositoryBodyObservationBasis,
) -> Result<crate::EpiphanyMindRepositoryBodyObservationDocument> {
validate_repository_body_observation_basis(runtime_store, basis)?;
let route = runtime_repository_body_store_binding(runtime_store)?
.ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?;
let entries = load_body_envelopes(Path::new(&route.body_store_path))?;
let source = find(&entries, BODY_OBSERVATION_TYPE, &basis.observation_id)
.ok_or_else(|| anyhow!("repository Body observation source is absent"))?;
let source_observation =
crate::EpiphanyMindDocumentVersion::from_envelope("epiphany-repository-body", source)?;
let document = crate::EpiphanyMindRepositoryBodyObservationDocument {
basis: basis.clone(),
source_observation: source_observation.clone(),
};
document.validate()?;
let mut cache = crate::runtime_spine_cache(runtime_store)?;
cache.pull_all_backing_stores()?;
if let Some(existing) =
cache.get::<crate::EpiphanyMindRepositoryBodyObservationDocument>(&basis.observation_id)?
{
if existing != document {
bail!("Mind repository Body observation identity collision");
}
return Ok(existing);
}
let write = cache.prepare_entry(&basis.observation_id, &document)?.0;
match crate::commit_external_typed_observation_mind_mutation(
runtime_store,
"Body",
source_observation,
"repository-body-observation-admission",
Vec::new(),
vec![write],
&basis.scan_finished_at,
)? {
crate::EpiphanyMindCommitOutcome::Committed(_) => Ok(document),
crate::EpiphanyMindCommitOutcome::Conflict { .. } => {
bail!("Mind repository Body observation lost its insert race")
}
}
}
pub fn current_mind_repository_body_observation(
runtime_store: &Path,
) -> Result<Option<RepositoryBodyObservationBasis>> {
Ok(crate::assemble_mind_view(runtime_store)?.repository_body_observation)
}
/// Loads the authenticated current Repository Body basis already persisted for
@ -1669,6 +1721,21 @@ mod tests {
write(&d.path().join("tracked.txt"), "one")?;
run(d.path(), &["add", "."])?;
let observed = observe_runtime_repository_body_basis(&runtime)?;
assert_eq!(
current_mind_repository_body_observation(&runtime)?,
Some(observed.clone())
);
let mut mind = crate::runtime_spine_cache(&runtime)?;
mind.pull_all_backing_stores()?;
let admitted = mind
.get::<crate::EpiphanyMindRepositoryBodyObservationDocument>(&observed.observation_id)?
.ok_or_else(|| anyhow!("Mind Body observation admission is absent"))?;
admitted.validate()?;
assert_eq!(admitted.basis, observed);
assert_eq!(
admitted.source_observation.store_id,
"epiphany-repository-body"
);
let before = std::fs::read(&store)?;
write(&d.path().join("tracked.txt"), "two")?;
@ -1688,6 +1755,35 @@ mod tests {
Ok(())
}
#[test]
fn body_admission_refuses_tampered_external_source_without_mutating_mind() -> Result<()> {
let d = repo()?;
let state = tempfile::tempdir()?;
let (store, runtime) = bound(d.path(), state.path(), "admitted", "runtime", "swarm")?;
write(&d.path().join("tracked.txt"), "one")?;
let basis = observe_runtime_repository_body_basis(&runtime)?;
let mind_before = std::fs::read(&runtime)?;
let backing = SingleFileMessagePackBackingStore::new(&store);
let opening = backing.pull_all()?;
let original = find(&opening, BODY_OBSERVATION_TYPE, &basis.observation_id)
.unwrap()
.clone();
let mut tampered: RepositoryBodyObservation = decode(&original)?;
tampered.manifest_root_sha256 = "sha256:tampered".into();
assert!(backing.compare_and_swap_batch(
&[original],
vec![envelope(
BODY_OBSERVATION_TYPE,
&basis.observation_id,
&tampered,
)?],
)?);
assert!(admit_repository_body_observation(&runtime, &basis).is_err());
assert_eq!(std::fs::read(&runtime)?, mind_before);
Ok(())
}
#[test]
fn persisted_current_basis_refuses_substituted_runtime_route() -> Result<()> {
let first_repo = repo()?;
let first_state = tempfile::tempdir()?;

View file

@ -2563,6 +2563,7 @@ mod tests {
investigation_checkpoint: None,
mode: None,
planning: Default::default(),
repository_body_observation: None,
repo_model: None,
};
epiphany_core::EpiphanyReasoningBasis::new(
@ -3754,13 +3755,13 @@ mod tests {
let temp = tempdir()?;
let store = temp.path().join("runtime.msgpack");
let body_basis = epiphany_core::RepositoryBodyObservationBasis {
schema_version: "epiphany.repository_body.observation_basis.v0".to_string(),
schema_version: epiphany_core::BODY_SCHEMA_VERSION.to_string(),
workspace_id: "workspace-test".to_string(),
swarm_id: "swarm-test".to_string(),
runtime_id: "epiphany-test".to_string(),
scope: "whole_repository".to_string(),
body_binding_sha256: "body-binding".to_string(),
observation_id: "body-observation-1".to_string(),
observation_id: "workspace-test:1".to_string(),
generation: 1,
manifest_root_sha256: "manifest-root".to_string(),
scan_started_at: "2026-07-13T00:00:00Z".to_string(),
@ -3873,6 +3874,49 @@ mod tests {
created_at: now(),
},
)?;
let source_observation = epiphany_core::RepositoryBodyObservation {
schema_version: body_basis.schema_version.clone(),
observation_id: body_basis.observation_id.clone(),
workspace_id: body_basis.workspace_id.clone(),
swarm_id: body_basis.swarm_id.clone(),
runtime_id: body_basis.runtime_id.clone(),
scope: body_basis.scope.clone(),
generation: body_basis.generation,
git_top_level: "C:/fixture".into(),
object_format: "sha1".into(),
head_oid: None,
tree_oid: "tree".into(),
core_ignorecase: true,
core_symlinks: false,
sparse_checkout: false,
sparse_checkout_cone: false,
submodule_limitation: "gitlinks-only".into(),
scan_started_at: body_basis.scan_started_at.clone(),
scan_finished_at: body_basis.scan_finished_at.clone(),
first_tree_oid: "tree".into(),
second_tree_oid: "tree".into(),
two_scan_outcome: "stable".into(),
global_excludes_policy: "disabled".into(),
manifest_root_sha256: body_basis.manifest_root_sha256.clone(),
manifest_entry_count: 0,
};
let source_envelope = cultcache_rs::CultCacheEnvelope {
key: body_basis.observation_id.clone(),
r#type: epiphany_core::BODY_OBSERVATION_TYPE.into(),
payload: rmp_serde::to_vec_named(&source_observation)?,
stored_at: body_basis.scan_finished_at.clone(),
schema_id: Some(epiphany_core::BODY_OBSERVATION_TYPE.into()),
};
let admitted_body = epiphany_core::EpiphanyMindRepositoryBodyObservationDocument {
basis: body_basis.clone(),
source_observation: epiphany_core::EpiphanyMindDocumentVersion::from_envelope(
"epiphany-repository-body",
&source_envelope,
)?,
};
admitted_body.validate()?;
let mut mind = epiphany_core::runtime_spine_cache(&store)?;
mind.put(&body_basis.observation_id, &admitted_body)?;
let launch_request = load_worker_launch_request(&store, "worker-job-1")?;
let reasoning_basis = epiphany_core::worker_reasoning_basis(&store, &launch_request)?;
epiphany_core::put_reasoning_basis(&store, &reasoning_basis)?;