Build federated Model Atlas vertical slice
This commit is contained in:
parent
1f678089dc
commit
4c0cbd57e0
81 changed files with 16699 additions and 25464 deletions
6
Cargo.lock
generated
6
Cargo.lock
generated
|
|
@ -2122,6 +2122,7 @@ dependencies = [
|
|||
"rand_core 0.6.4",
|
||||
"reqwest 0.12.28",
|
||||
"rmp-serde",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha1",
|
||||
|
|
@ -2227,6 +2228,7 @@ dependencies = [
|
|||
"reqwest 0.13.4",
|
||||
"rmcp 2.2.0",
|
||||
"rmp-serde",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha1",
|
||||
|
|
@ -6049,6 +6051,10 @@ name = "semver"
|
|||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
|
|
|
|||
15
Cargo.toml
15
Cargo.toml
|
|
@ -49,12 +49,13 @@ rmp-serde = "1"
|
|||
rmcp = { version = "2.2.0", default-features = false, features = ["client", "transport-child-process", "transport-streamable-http-client-reqwest"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
semver = { version = "1", features = ["serde"] }
|
||||
sha1 = "0.10.6"
|
||||
sha2 = "0.10"
|
||||
tokio = { version = "1", features = ["io-util", "macros", "process", "rt", "rt-multi-thread", "time"] }
|
||||
toml = "0.9"
|
||||
tracing = "0.1.44"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
uuid = { version = "1", features = ["serde", "v4"] }
|
||||
zeroize = "1"
|
||||
|
||||
[features]
|
||||
|
|
@ -88,6 +89,18 @@ tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev
|
|||
name = "epiphany-daemon-supervisor"
|
||||
path = "epiphany-core/src/bin/epiphany-daemon-supervisor.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-atlas-publisher"
|
||||
path = "epiphany-core/src/bin/epiphany-atlas-publisher.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-model-entanglement-projector"
|
||||
path = "epiphany-core/src/bin/epiphany-model-entanglement-projector.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-atlas-impact-ingress"
|
||||
path = "epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-release"
|
||||
path = "epiphany-core/src/bin/epiphany-release.rs"
|
||||
|
|
|
|||
|
|
@ -20,6 +20,18 @@ name = "epiphany-semantic-recovery-smoke"
|
|||
path = "src/bin/epiphany-semantic-recovery-smoke.rs"
|
||||
required-features = ["semantic-recovery-smoke"]
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-atlas-publisher"
|
||||
path = "src/bin/epiphany-atlas-publisher.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-model-entanglement-projector"
|
||||
path = "src/bin/epiphany-model-entanglement-projector.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-atlas-impact-ingress"
|
||||
path = "src/bin/epiphany-atlas-impact-ingress.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-workspace-coverage-recovery-smoke"
|
||||
path = "src/bin/epiphany-workspace-coverage-recovery-smoke.rs"
|
||||
|
|
@ -77,10 +89,6 @@ path = "src/bin/epiphany-heartbeat-store.rs"
|
|||
name = "epiphany-host-identity"
|
||||
path = "src/bin/epiphany-host-identity.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-memory-graph"
|
||||
path = "src/bin/epiphany-memory-graph.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-memory-semantic"
|
||||
path = "src/bin/epiphany-memory-semantic.rs"
|
||||
|
|
@ -350,11 +358,12 @@ reqwest = { version = "0.12", features = ["blocking", "json"] }
|
|||
rmp-serde = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
semver = { version = "1", features = ["serde"] }
|
||||
sha1 = "0.10.6"
|
||||
sha2 = "0.10"
|
||||
toml = "0.9"
|
||||
tracing = "0.1.44"
|
||||
uuid = { version = "1", features = ["v4", "v5"] }
|
||||
uuid = { version = "1", features = ["serde", "v4", "v5"] }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = "1.4.1"
|
||||
|
|
|
|||
|
|
@ -4,11 +4,11 @@ use serde::{Deserialize, Serialize};
|
|||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
|
||||
pub const REQUEST_SCHEMA: &str = "epiphany.self.admitted_model_direction_consideration_request.v0";
|
||||
pub const REQUEST_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_request.v0";
|
||||
pub const REQUEST_SCHEMA: &str = "epiphany.self.admitted_model_direction_consideration_request.v1";
|
||||
pub const REQUEST_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_request.v1";
|
||||
pub const RESULT_SCHEMA: &str =
|
||||
"epiphany.imagination.admitted_model_direction_consideration_result.v0";
|
||||
pub const RESULT_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_result.v0";
|
||||
"epiphany.imagination.admitted_model_direction_consideration_result.v1";
|
||||
pub const RESULT_CONTRACT: &str = "epiphany.admitted_model_direction_consideration_result.v1";
|
||||
pub const MAX_OPTION_DRAFTS: usize = 3;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -34,11 +34,9 @@ pub struct AdmittedModelDirectionConsiderationRequest {
|
|||
#[cultcache(key = 3)]
|
||||
pub thread_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub model_hash: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub model_admission_receipt_id: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 7, default)]
|
||||
pub previous_terminal_result_id: Option<String>,
|
||||
#[cultcache(key = 8)]
|
||||
|
|
@ -66,11 +64,9 @@ pub struct AdmittedModelDirectionConsiderationResult {
|
|||
#[cultcache(key = 4)]
|
||||
pub thread_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub model_hash: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub model_admission_receipt_id: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 8)]
|
||||
pub disposition: AdmittedModelDirectionDisposition,
|
||||
#[cultcache(key = 9)]
|
||||
|
|
@ -106,23 +102,8 @@ pub fn commit_request(
|
|||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(model) = crate::runtime_current_repo_model(runtime_store)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let model_hash = crate::memory_graph_model_hash(&model)?;
|
||||
let receipts = cache
|
||||
.get_all::<crate::RepoModelAdmissionReceipt>()?
|
||||
.into_iter()
|
||||
.filter(|receipt| {
|
||||
receipt.admitted_revision == model.model_revision && receipt.admitted_hash == model_hash
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if receipts.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if receipts.len() != 1 {
|
||||
bail!("model direction consideration requires exactly one current model receipt");
|
||||
}
|
||||
let model = crate::assemble_repo_model_view(runtime_store)?;
|
||||
let model_basis = model.reasoning_basis();
|
||||
let mut terminal = cache
|
||||
.get_all::<AdmittedModelDirectionConsiderationResult>()?
|
||||
.into_iter()
|
||||
|
|
@ -130,17 +111,15 @@ pub fn commit_request(
|
|||
.collect::<Vec<_>>();
|
||||
terminal.sort_by(|left, right| left.proposed_at.cmp(&right.proposed_at));
|
||||
if terminal.iter().any(|result| {
|
||||
result.model_revision == model.model_revision
|
||||
&& result.model_hash == model_hash
|
||||
&& result.model_admission_receipt_id == receipts[0].receipt_id
|
||||
result.model_projection_digest == model_basis.projection_digest
|
||||
&& result.model_source_documents == model_basis.source_documents
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
let previous_terminal_result_id = terminal.last().map(|result| result.result_id.clone());
|
||||
let request_id = crate::admitted_model_direction_request_id(
|
||||
&identity.runtime_id,
|
||||
&model_hash,
|
||||
&receipts[0].receipt_id,
|
||||
&model_basis.projection_digest,
|
||||
previous_terminal_result_id.as_deref(),
|
||||
);
|
||||
let request = AdmittedModelDirectionConsiderationRequest {
|
||||
|
|
@ -148,9 +127,8 @@ pub fn commit_request(
|
|||
request_id: request_id.clone(),
|
||||
runtime_id: identity.runtime_id,
|
||||
thread_id: thread.thread_id,
|
||||
model_revision: model.model_revision,
|
||||
model_hash,
|
||||
model_admission_receipt_id: receipts[0].receipt_id.clone(),
|
||||
model_projection_digest: model_basis.projection_digest,
|
||||
model_source_documents: model_basis.source_documents,
|
||||
previous_terminal_result_id,
|
||||
requested_at: requested_at.into(),
|
||||
contract: REQUEST_CONTRACT.into(),
|
||||
|
|
@ -179,18 +157,11 @@ pub fn validate_current_request(
|
|||
if request_is_superseded(cache, request)? {
|
||||
bail!("model direction consideration request is stale");
|
||||
}
|
||||
let receipts = cache
|
||||
.get_all::<crate::RepoModelAdmissionReceipt>()?
|
||||
.into_iter()
|
||||
.filter(|receipt| {
|
||||
receipt.receipt_id == request.model_admission_receipt_id
|
||||
&& receipt.admitted_revision == request.model_revision
|
||||
&& receipt.admitted_hash == request.model_hash
|
||||
})
|
||||
.count();
|
||||
if receipts != 1 {
|
||||
bail!("model direction consideration lost its unique model receipt");
|
||||
crate::EpiphanyRepoModelBasis {
|
||||
projection_digest: request.model_projection_digest.clone(),
|
||||
source_documents: request.model_source_documents.clone(),
|
||||
}
|
||||
.validate_against_cache(cache)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -210,12 +181,12 @@ pub fn request_is_superseded(
|
|||
request: &AdmittedModelDirectionConsiderationRequest,
|
||||
) -> Result<bool> {
|
||||
validate_request_shape(request)?;
|
||||
let model = cache
|
||||
.get::<crate::EpiphanyMemoryGraphEntry>(crate::MEMORY_GRAPH_KEY)?
|
||||
.ok_or_else(|| anyhow!("model direction consideration map disappeared"))?
|
||||
.snapshot()?;
|
||||
Ok(request.model_revision != model.model_revision
|
||||
|| request.model_hash != crate::memory_graph_model_hash(&model)?)
|
||||
Ok(crate::EpiphanyRepoModelBasis {
|
||||
projection_digest: request.model_projection_digest.clone(),
|
||||
source_documents: request.model_source_documents.clone(),
|
||||
}
|
||||
.validate_against_cache(cache)
|
||||
.is_err())
|
||||
}
|
||||
|
||||
pub fn validate_result(
|
||||
|
|
@ -233,9 +204,8 @@ pub fn validate_result(
|
|||
|| result.request_id != request.request_id
|
||||
|| result.runtime_id != request.runtime_id
|
||||
|| result.thread_id != request.thread_id
|
||||
|| result.model_revision != request.model_revision
|
||||
|| result.model_hash != request.model_hash
|
||||
|| result.model_admission_receipt_id != request.model_admission_receipt_id
|
||||
|| result.model_projection_digest != request.model_projection_digest
|
||||
|| result.model_source_documents != request.model_source_documents
|
||||
|| result.result_id.trim().is_empty()
|
||||
|| result.summary.trim().is_empty()
|
||||
|| proposed_at < requested_at
|
||||
|
|
@ -262,25 +232,44 @@ pub fn result_id_for_launch(request_id: &str, job_id: &str) -> String {
|
|||
|
||||
pub fn render_prompt(request: &AdmittedModelDirectionConsiderationRequest) -> String {
|
||||
format!(
|
||||
"Act as Epiphany Imagination for one proposal-only direction consideration. Inspect the exact current admitted Modeling map bound by request {} at revision/hash {}/{}. Suggest options or hold. Do not adopt, edit, execute, release, or deploy.",
|
||||
request.request_id, request.model_revision, request.model_hash
|
||||
"Act as Epiphany Imagination for one proposal-only direction consideration. Inspect the exact current keyed Modeling map bound by request {} at projection digest {}. Suggest options or hold. Do not adopt, edit, execute, release, or deploy.",
|
||||
request.request_id, request.model_projection_digest
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn model_basis() -> crate::EpiphanyRepoModelBasis {
|
||||
let source_documents = vec![crate::EpiphanyMindDocumentVersion {
|
||||
store_id: "epiphany-mind".into(),
|
||||
document_type: "epiphany.mind.repo_model.identity.v1".into(),
|
||||
document_key: crate::REPO_MODEL_IDENTITY_KEY.into(),
|
||||
schema_id: Some("EpiphanyRepoModelIdentityDocument".into()),
|
||||
payload_msgpack: vec![1],
|
||||
payload_sha256: format!("{:x}", Sha256::digest([1])),
|
||||
}];
|
||||
crate::EpiphanyRepoModelBasis {
|
||||
projection_digest: format!(
|
||||
"sha256:{:x}",
|
||||
Sha256::digest(rmp_serde::to_vec_named(&source_documents).unwrap())
|
||||
),
|
||||
source_documents,
|
||||
}
|
||||
}
|
||||
|
||||
fn request() -> AdmittedModelDirectionConsiderationRequest {
|
||||
let basis = model_basis();
|
||||
AdmittedModelDirectionConsiderationRequest {
|
||||
schema_version: REQUEST_SCHEMA.into(),
|
||||
request_id: "request-1".into(),
|
||||
runtime_id: "runtime-1".into(),
|
||||
thread_id: "thread-1".into(),
|
||||
model_revision: 7,
|
||||
model_hash: "sha256:model-7".into(),
|
||||
model_admission_receipt_id: "receipt-7".into(),
|
||||
model_projection_digest: basis.projection_digest,
|
||||
model_source_documents: basis.source_documents,
|
||||
previous_terminal_result_id: None,
|
||||
requested_at: "2026-07-18T00:00:00Z".into(),
|
||||
contract: REQUEST_CONTRACT.into(),
|
||||
|
|
@ -297,9 +286,8 @@ mod tests {
|
|||
request_id: request.request_id.clone(),
|
||||
runtime_id: request.runtime_id.clone(),
|
||||
thread_id: request.thread_id.clone(),
|
||||
model_revision: request.model_revision,
|
||||
model_hash: request.model_hash.clone(),
|
||||
model_admission_receipt_id: request.model_admission_receipt_id.clone(),
|
||||
model_projection_digest: request.model_projection_digest.clone(),
|
||||
model_source_documents: request.model_source_documents.clone(),
|
||||
disposition: AdmittedModelDirectionDisposition::Hold,
|
||||
summary: "No direction should be promoted yet.".into(),
|
||||
option_drafts: Vec::new(),
|
||||
|
|
@ -334,9 +322,9 @@ mod tests {
|
|||
let mut substituted = result(&request);
|
||||
match mutation {
|
||||
0 => substituted.request_id = "request-stale".into(),
|
||||
1 => substituted.model_revision += 1,
|
||||
2 => substituted.model_hash = "sha256:substituted".into(),
|
||||
3 => substituted.model_admission_receipt_id = "receipt-substituted".into(),
|
||||
1 => substituted.model_projection_digest = format!("sha256:{}", "0".repeat(64)),
|
||||
2 => substituted.model_source_documents.clear(),
|
||||
3 => substituted.runtime_id = "runtime-substituted".into(),
|
||||
4 => substituted.proposal_only = false,
|
||||
_ => substituted.terminal = false,
|
||||
}
|
||||
|
|
@ -386,44 +374,4 @@ mod tests {
|
|||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_model_without_admission_receipt_has_no_direction_request_yet() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let store = temp.path().join("bootstrap-runtime.cc");
|
||||
let mut cache = crate::runtime_spine_cache(&store)?;
|
||||
cache.put(
|
||||
crate::RUNTIME_IDENTITY_KEY,
|
||||
&crate::EpiphanyRuntimeIdentity {
|
||||
schema_version: crate::RUNTIME_SPINE_SCHEMA_VERSION.into(),
|
||||
runtime_id: "runtime-bootstrap".into(),
|
||||
display_name: "Bootstrap runtime".into(),
|
||||
runtime_kind: "resident".into(),
|
||||
created_at: "2026-07-18T00:00:00Z".into(),
|
||||
updated_at: "2026-07-18T00:00:00Z".into(),
|
||||
supported_document_types: Vec::new(),
|
||||
metadata: BTreeMap::new(),
|
||||
},
|
||||
)?;
|
||||
cache.put(
|
||||
crate::THREAD_STATE_KEY,
|
||||
&crate::EpiphanyThreadStateEntry::from_state(
|
||||
"bootstrap-thread",
|
||||
&epiphany_state_model::EpiphanyThreadState::default(),
|
||||
)?,
|
||||
)?;
|
||||
cache.put(
|
||||
crate::MEMORY_GRAPH_KEY,
|
||||
&crate::EpiphanyMemoryGraphEntry::from_snapshot(&crate::EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(crate::MEMORY_GRAPH_SCHEMA_VERSION.into()),
|
||||
graph_id: "bootstrap-model".into(),
|
||||
..Default::default()
|
||||
})?,
|
||||
)?;
|
||||
let before = std::fs::read(&store)?;
|
||||
|
||||
assert!(commit_request(&store, "2026-07-18T00:01:00Z")?.is_none());
|
||||
assert_eq!(std::fs::read(&store)?, before);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -86,85 +86,11 @@ fn repo_frontier_item_output_schema() -> serde_json::Value {
|
|||
"recommended_next_organ": {"type": "string", "minLength": 1},
|
||||
"dependency_item_ids": {"type": "array", "items": {"type": "string"}},
|
||||
"status": {"type": "string", "enum": ["proposed", "active", "blocked", "resolved", "retired", "superseded"]},
|
||||
"evidence_refs": {"type": "array", "items": {"type": "string"}},
|
||||
"created_at": {"type": "string"},
|
||||
"updated_at": {"type": "string"}
|
||||
"evidence_refs": {"type": "array", "items": {"type": "string"}}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn modeling_imagination_frontier_output_schema() -> serde_json::Value {
|
||||
let mut schema = repo_frontier_item_output_schema();
|
||||
schema["required"] = serde_json::json!([
|
||||
"id",
|
||||
"migration_body",
|
||||
"question",
|
||||
"gap",
|
||||
"target_claim_ids",
|
||||
"source_scope",
|
||||
"recommended_next_organ",
|
||||
"dependency_item_ids",
|
||||
"status",
|
||||
"evidence_refs"
|
||||
]);
|
||||
schema["properties"]["source_scope"]["minItems"] = serde_json::json!(1);
|
||||
schema["properties"]["recommended_next_organ"] = serde_json::json!({"const": "Imagination"});
|
||||
schema["properties"]["dependency_item_ids"]["maxItems"] = serde_json::json!(0);
|
||||
schema["properties"]["status"] = serde_json::json!({"const": "active"});
|
||||
schema["properties"]["evidence_refs"]["minItems"] = serde_json::json!(1);
|
||||
schema["additionalProperties"] = serde_json::json!(false);
|
||||
schema
|
||||
}
|
||||
|
||||
fn adopted_frontier_plan_output_schema() -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"required": [
|
||||
"planning_request_id", "result_id", "job_id", "candidate_id", "candidate_sha256",
|
||||
"safe_paths", "action", "command", "checks", "stop_conditions", "rollback_steps",
|
||||
"commit_message"
|
||||
],
|
||||
"properties": {
|
||||
"planning_request_id": {"type": "string", "minLength": 1},
|
||||
"result_id": {"type": "string", "minLength": 1},
|
||||
"job_id": {"type": "string", "minLength": 1},
|
||||
"candidate_id": {"type": "string", "minLength": 1},
|
||||
"candidate_sha256": {"type": "string", "minLength": 1},
|
||||
"safe_paths": {"type": "array", "items": {"type": "string", "minLength": 1}},
|
||||
"action": {"type": "string", "minLength": 1},
|
||||
"command": {"type": "string", "minLength": 1},
|
||||
"checks": {"type": "array", "items": {"type": "string", "minLength": 1}},
|
||||
"stop_conditions": {"type": "array", "items": {"type": "string", "minLength": 1}},
|
||||
"rollback_steps": {"type": "array", "items": {"type": "string", "minLength": 1}},
|
||||
"commit_message": {"type": "string", "minLength": 1},
|
||||
"execution_amendment": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"amendment_id", "replaces_route_id", "source_actor_id", "command_id",
|
||||
"admission_id", "packet_sha256", "previous_action_sha256",
|
||||
"previous_command_sha256", "action", "command", "rationale", "amended_at"
|
||||
],
|
||||
"properties": {
|
||||
"amendment_id": {"type": "string", "minLength": 1},
|
||||
"replaces_route_id": {"type": "string", "minLength": 1},
|
||||
"source_actor_id": {"type": "string", "minLength": 1},
|
||||
"command_id": {"type": "string", "minLength": 1},
|
||||
"admission_id": {"type": "string", "minLength": 1},
|
||||
"packet_sha256": {"type": "string", "minLength": 1},
|
||||
"previous_action_sha256": {"type": "string", "minLength": 1},
|
||||
"previous_command_sha256": {"type": "string", "minLength": 1},
|
||||
"action": {"type": "string", "minLength": 1},
|
||||
"command": {"type": "string", "minLength": 1},
|
||||
"rationale": {"type": "string", "minLength": 1},
|
||||
"amended_at": {"type": "string", "minLength": 1}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
})
|
||||
}
|
||||
|
||||
fn repo_model_node_output_schema() -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
|
|
@ -183,9 +109,7 @@ fn repo_model_node_output_schema() -> serde_json::Value {
|
|||
"source_hashes": {"type": "array", "items": {"type": "string"}},
|
||||
"lifecycle": {"type": "string"},
|
||||
"salience": {"type": "integer", "minimum": 0},
|
||||
"confidence": {"type": "integer", "minimum": 0},
|
||||
"created_at": {"type": "string"},
|
||||
"updated_at": {"type": "string"}
|
||||
"confidence": {"type": "integer", "minimum": 0}
|
||||
},
|
||||
"anyOf": [
|
||||
{"properties": {"question": {"minLength": 1}}},
|
||||
|
|
@ -585,127 +509,26 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) ->
|
|||
} else if role_id == EpiphanyRoleResultRoleId::Modeling {
|
||||
if let Some(map) = properties.as_object_mut() {
|
||||
map.insert(
|
||||
"repositoryBodyObservationBasis".to_string(),
|
||||
"repoModelOperations".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"description": "Exact echo of the immutable repository Body observation basis supplied in the Modeling launch.",
|
||||
"required": [
|
||||
"schemaVersion", "workspaceId", "swarmId", "runtimeId", "scope",
|
||||
"bodyBindingSha256", "observationId", "generation",
|
||||
"manifestRootSha256", "scanStartedAt", "scanFinishedAt"
|
||||
],
|
||||
"properties": {
|
||||
"schemaVersion": {"type": "string", "minLength": 1},
|
||||
"workspaceId": {"type": "string", "minLength": 1},
|
||||
"swarmId": {"type": "string", "minLength": 1},
|
||||
"runtimeId": {"type": "string", "minLength": 1},
|
||||
"scope": {"type": "string", "minLength": 1},
|
||||
"bodyBindingSha256": {"type": "string", "minLength": 1},
|
||||
"observationId": {"type": "string", "minLength": 1},
|
||||
"generation": {"type": "integer", "minimum": 1},
|
||||
"manifestRootSha256": {"type": "string", "minLength": 1},
|
||||
"scanStartedAt": {"type": "string", "minLength": 1},
|
||||
"scanFinishedAt": {"type": "string", "minLength": 1}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"repoModelPatch".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"description": "Required typed proposal against the canonical repository model. This is ingress for later review, not admission authority.",
|
||||
"required": ["patch_id", "base_revision", "base_hash", "applied_at", "purpose", "operations"],
|
||||
"properties": {
|
||||
"patch_id": {"type": "string", "minLength": 1},
|
||||
"base_revision": {"type": "integer", "minimum": 0},
|
||||
"base_hash": {"type": "string", "minLength": 1},
|
||||
"applied_at": {"type": "string", "minLength": 1},
|
||||
"purpose": {
|
||||
"description": "Use {kind: evolution} for ordinary Modeling output; frontier closure requires separately routed authority.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["kind"],
|
||||
"properties": {"kind": {"const": "evolution"}},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["kind", "route_id", "soul_verdict_receipt_id"],
|
||||
"properties": {
|
||||
"kind": {"const": "incorporate_frontier_verdict"},
|
||||
"route_id": {"type": "string", "minLength": 1},
|
||||
"soul_verdict_receipt_id": {"type": "string", "minLength": 1}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["kind"],
|
||||
"properties": {"kind": {"const": "repair_claim"}},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["kind", "planning_request_id", "result_id", "candidate_id"],
|
||||
"properties": {
|
||||
"kind": {"const": "adopt_frontier_plan"},
|
||||
"planning_request_id": {"type": "string", "minLength": 1},
|
||||
"result_id": {"type": "string", "minLength": 1},
|
||||
"candidate_id": {"type": "string", "minLength": 1}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"operations": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"anyOf": [
|
||||
{"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "upsert_node"}, "node": repo_model_node_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "revise_node"}, "node": repo_model_node_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}},
|
||||
{"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "upsert_edge"}, "edge": repo_model_edge_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "revise_edge"}, "edge": repo_model_edge_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}},
|
||||
{"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "upsert_frontier"}, "item": repo_frontier_item_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "revise_frontier"}, "item": repo_frontier_item_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "item_id"], "properties": {"operation": {"const": "retire_frontier"}, "item_id": {"type": "string", "minLength": 1}, "retired_at": {"type": "string"}, "superseded_by": {"type": "string"}}},
|
||||
{"type": "object", "required": ["operation", "frontier_item_id", "expected_frontier_item_hash", "adopted_plan"], "properties": {"operation": {"const": "adopt_frontier_plan"}, "frontier_item_id": {"type": "string", "minLength": 1}, "expected_frontier_item_hash": {"type": "string", "minLength": 1}, "adopted_plan": adopted_frontier_plan_output_schema()}}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"repoFrontierModelingRequestId".to_string(),
|
||||
serde_json::json!({"type": "string", "minLength": 1}),
|
||||
);
|
||||
map.insert(
|
||||
"proposalModelingRequestId".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Exact echo of an explicit typed repo-frontier proposal Modeling request, when supplied."
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"claimRepairRequestId".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Exact echo of the coordinator-bound claim repair request; valid only with purpose repair_claim."
|
||||
"type": "array",
|
||||
"description": "Semantic keyed RepoModel operations only. The runtime owns proposal identity, the exact Body and RepoModel basis, causal request/result/evidence bindings, strong reads, writes, timestamps, and receipts.",
|
||||
"items": {
|
||||
"anyOf": [
|
||||
{"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "put_node"}, "node": repo_model_node_output_schema()}, "additionalProperties": false},
|
||||
{"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}, "additionalProperties": false},
|
||||
{"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "put_edge"}, "edge": repo_model_edge_output_schema()}, "additionalProperties": false},
|
||||
{"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}, "additionalProperties": false},
|
||||
{"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "put_frontier"}, "item": repo_frontier_item_output_schema()}, "additionalProperties": false}
|
||||
]
|
||||
}
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"statePatch".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"description": "Optional generic Mind-reviewable observations/evidence only. Repository anatomy belongs exclusively in repoModelPatch.",
|
||||
"description": "Optional generic Mind-reviewable observations/evidence only. Repository anatomy belongs exclusively in repoModelOperations.",
|
||||
"properties": {
|
||||
"observations": {"type": "array", "items": observation_output_schema()},
|
||||
"evidence": {"type": "array", "items": evidence_output_schema()}
|
||||
|
|
@ -715,8 +538,7 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) ->
|
|||
);
|
||||
}
|
||||
required.push("frontierNodeIds");
|
||||
required.push("repoModelPatch");
|
||||
required.push("repositoryBodyObservationBasis");
|
||||
required.push("repoModelOperations");
|
||||
}
|
||||
let mut schema = serde_json::json!({
|
||||
"type": "object",
|
||||
|
|
@ -728,159 +550,31 @@ pub fn epiphany_role_launch_output_schema(role_id: EpiphanyRoleResultRoleId) ->
|
|||
schema["allOf"] = serde_json::json!([
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"repoModelPatch": {
|
||||
"properties": {
|
||||
"purpose": {
|
||||
"properties": {"kind": {"const": "incorporate_frontier_verdict"}},
|
||||
"required": ["kind"]
|
||||
}
|
||||
},
|
||||
"required": ["purpose"]
|
||||
}
|
||||
},
|
||||
"required": ["repoModelPatch"]
|
||||
"properties": {"verdict": {"const": "checkpoint-update-needed"}},
|
||||
"required": ["verdict"]
|
||||
},
|
||||
"then": {"required": ["repoFrontierModelingRequestId"]}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"repoModelPatch": {
|
||||
"properties": {
|
||||
"purpose": {
|
||||
"properties": {"kind": {"const": "repair_claim"}},
|
||||
"required": ["kind"]
|
||||
}
|
||||
}
|
||||
,"required": ["purpose"]
|
||||
}
|
||||
},
|
||||
"required": ["repoModelPatch"]
|
||||
},
|
||||
"then": {"required": ["claimRepairRequestId"]}
|
||||
},
|
||||
{
|
||||
"if": {"required": ["proposalModelingRequestId"]},
|
||||
"then": {
|
||||
"properties": {
|
||||
"evidenceIds": {"type": "array", "minItems": 1},
|
||||
"repoModelPatch": {
|
||||
"properties": {
|
||||
"purpose": {
|
||||
"properties": {"kind": {"const": "evolution"}},
|
||||
"required": ["kind"]
|
||||
},
|
||||
"operations": {
|
||||
"contains": {
|
||||
"type": "object",
|
||||
"properties": {"operation": {"const": "upsert_frontier"}},
|
||||
"required": ["operation"]
|
||||
},
|
||||
"minContains": 1,
|
||||
"maxContains": 1
|
||||
}
|
||||
"repoModelOperations": {
|
||||
"minItems": 1,
|
||||
"contains": {
|
||||
"type": "object",
|
||||
"properties": {"operation": {"const": "put_frontier"}},
|
||||
"required": ["operation"]
|
||||
},
|
||||
"required": ["purpose", "operations"]
|
||||
"minContains": 1,
|
||||
"maxContains": 1
|
||||
}
|
||||
},
|
||||
"required": ["evidenceIds", "repoModelPatch"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"allOf": [
|
||||
{
|
||||
"not": {
|
||||
"anyOf": [
|
||||
{"required": ["repoFrontierModelingRequestId"]},
|
||||
{"required": ["proposalModelingRequestId"]},
|
||||
{"required": ["claimRepairRequestId"]}
|
||||
]
|
||||
}
|
||||
},
|
||||
{"properties": {"verdict": {"const": "checkpoint-update-needed"}}, "required": ["verdict"]}
|
||||
]
|
||||
"properties": {"verdict": {"enum": ["checkpoint-ready", "regather-needed"]}},
|
||||
"required": ["verdict"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"repoModelPatch": {
|
||||
"properties": {
|
||||
"purpose": {
|
||||
"type": "object",
|
||||
"required": ["kind"],
|
||||
"properties": {"kind": {"const": "evolution"}},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"operations": {
|
||||
"items": {
|
||||
"anyOf": [
|
||||
{"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "upsert_node"}, "node": repo_model_node_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "revise_node"}, "node": repo_model_node_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}},
|
||||
{"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "upsert_edge"}, "edge": repo_model_edge_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "revise_edge"}, "edge": repo_model_edge_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}},
|
||||
{"type": "object", "required": ["operation", "item"], "properties": {"operation": {"const": "upsert_frontier"}, "item": modeling_imagination_frontier_output_schema()}, "additionalProperties": false}
|
||||
]
|
||||
},
|
||||
"contains": {
|
||||
"type": "object",
|
||||
"properties": {"operation": {"const": "upsert_frontier"}},
|
||||
"required": ["operation"]
|
||||
},
|
||||
"minContains": 1,
|
||||
"maxContains": 1
|
||||
}
|
||||
},
|
||||
"required": ["purpose", "operations"]
|
||||
}
|
||||
},
|
||||
"required": ["repoModelPatch"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"allOf": [
|
||||
{
|
||||
"not": {
|
||||
"anyOf": [
|
||||
{"required": ["repoFrontierModelingRequestId"]},
|
||||
{"required": ["proposalModelingRequestId"]},
|
||||
{"required": ["claimRepairRequestId"]}
|
||||
]
|
||||
}
|
||||
},
|
||||
{"not": {"properties": {"verdict": {"const": "checkpoint-update-needed"}}, "required": ["verdict"]}}
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"repoModelPatch": {
|
||||
"properties": {
|
||||
"purpose": {
|
||||
"type": "object",
|
||||
"required": ["kind"],
|
||||
"properties": {"kind": {"const": "evolution"}},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"operations": {
|
||||
"items": {
|
||||
"anyOf": [
|
||||
{"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "upsert_node"}, "node": repo_model_node_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "node"], "properties": {"operation": {"const": "revise_node"}, "node": repo_model_node_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "node_id"], "properties": {"operation": {"const": "retire_node"}, "node_id": {"type": "string", "minLength": 1}}},
|
||||
{"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "upsert_edge"}, "edge": repo_model_edge_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "edge"], "properties": {"operation": {"const": "revise_edge"}, "edge": repo_model_edge_output_schema()}},
|
||||
{"type": "object", "required": ["operation", "edge_id"], "properties": {"operation": {"const": "retire_edge"}, "edge_id": {"type": "string", "minLength": 1}}}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["purpose", "operations"]
|
||||
}
|
||||
},
|
||||
"required": ["repoModelPatch"]
|
||||
"properties": {"repoModelOperations": {"maxItems": 0}}
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
|
@ -946,89 +640,23 @@ pub fn epiphany_proposal_modeling_output_schema(
|
|||
pub fn epiphany_frontier_verdict_modeling_output_schema(
|
||||
authority: &crate::RepoFrontierVerdictModelingLaunchAuthority,
|
||||
) -> serde_json::Value {
|
||||
let request = &authority.request;
|
||||
let item = &authority.frontier_item;
|
||||
let disposition = match request.allowed_disposition {
|
||||
crate::RepoFrontierVerdictDisposition::Resolved => "resolved",
|
||||
crate::RepoFrontierVerdictDisposition::Blocked => "blocked",
|
||||
};
|
||||
let adopted_plan = serde_json::to_value(&item.adopted_plan)
|
||||
.expect("frontier adopted plan must serialize for its provider schema");
|
||||
let created_at = serde_json::to_value(&item.created_at)
|
||||
.expect("frontier creation time must serialize for its provider schema");
|
||||
let retired_at = serde_json::to_value(&item.retired_at)
|
||||
.expect("frontier retirement time must serialize for its provider schema");
|
||||
let superseded_by = serde_json::to_value(&item.superseded_by)
|
||||
.expect("frontier supersession must serialize for its provider schema");
|
||||
let _authority = authority;
|
||||
let mut schema = epiphany_role_launch_output_schema(EpiphanyRoleResultRoleId::Modeling);
|
||||
schema["properties"]["repoFrontierModelingRequestId"] = serde_json::json!({
|
||||
schema["properties"]
|
||||
.as_object_mut()
|
||||
.expect("role schema properties must be an object")
|
||||
.remove("repoModelOperations");
|
||||
schema["properties"]["frontierVerdictGap"] = serde_json::json!({
|
||||
"type": "string",
|
||||
"const": request.request_id
|
||||
});
|
||||
schema["properties"]["repoModelPatch"]["properties"]["purpose"] = serde_json::json!({
|
||||
"type": "object",
|
||||
"required": ["kind", "route_id", "soul_verdict_receipt_id"],
|
||||
"properties": {
|
||||
"kind": {"const": "incorporate_frontier_verdict"},
|
||||
"route_id": {"const": request.route_id},
|
||||
"soul_verdict_receipt_id": {"const": request.soul_verdict_receipt_id}
|
||||
},
|
||||
"additionalProperties": false
|
||||
});
|
||||
schema["properties"]["repoModelPatch"]["properties"]["operations"] = serde_json::json!({
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 1,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["operation", "item"],
|
||||
"properties": {
|
||||
"operation": {"const": "revise_frontier"},
|
||||
"item": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id", "migration_body", "question", "gap", "target_claim_ids",
|
||||
"source_scope", "recommended_next_organ", "adopted_plan",
|
||||
"dependency_item_ids", "status", "evidence_refs", "public_source_refs",
|
||||
"created_at", "updated_at", "retired_at", "superseded_by"
|
||||
],
|
||||
"properties": {
|
||||
"id": {"const": item.id},
|
||||
"migration_body": {"const": item.migration_body},
|
||||
"question": {"const": item.question},
|
||||
"gap": {"type": "string", "minLength": 1},
|
||||
"target_claim_ids": {"const": item.target_claim_ids},
|
||||
"source_scope": {"const": item.source_scope},
|
||||
"recommended_next_organ": {"const": item.recommended_next_organ},
|
||||
"adopted_plan": {"const": adopted_plan},
|
||||
"dependency_item_ids": {"const": item.dependency_item_ids},
|
||||
"status": {"const": disposition},
|
||||
"evidence_refs": {
|
||||
"type": "array",
|
||||
"minItems": 2,
|
||||
"items": {"type": "string", "minLength": 1},
|
||||
"allOf": [
|
||||
{"contains": {"const": request.verification_request_id}},
|
||||
{"contains": {"const": request.soul_verdict_receipt_id}}
|
||||
]
|
||||
},
|
||||
"public_source_refs": {"const": item.public_source_refs},
|
||||
"created_at": {"const": created_at},
|
||||
"updated_at": {"type": "string", "minLength": 1},
|
||||
"retired_at": {"const": retired_at},
|
||||
"superseded_by": {"const": superseded_by}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
"minLength": 1,
|
||||
"description": "Semantic explanation of the allowed resolved/blocked transition. Runtime owns the exact frontier, disposition, evidence bindings, timestamps, proposal, reads, writes, and receipts."
|
||||
});
|
||||
schema["properties"]["evidenceIds"]["minItems"] = serde_json::json!(1);
|
||||
schema["required"]
|
||||
let required = schema["required"]
|
||||
.as_array_mut()
|
||||
.expect("role schema required must be an array")
|
||||
.push(serde_json::json!("repoFrontierModelingRequestId"));
|
||||
.expect("role schema required must be an array");
|
||||
required.retain(|field| field.as_str() != Some("repoModelOperations"));
|
||||
required.push(serde_json::json!("frontierVerdictGap"));
|
||||
schema["allOf"] = serde_json::json!([]);
|
||||
schema
|
||||
}
|
||||
|
|
@ -1040,29 +668,15 @@ pub fn epiphany_frontier_planning_output_schema() -> serde_json::Value {
|
|||
.expect("role output schema properties");
|
||||
properties.remove("statePatch");
|
||||
properties.remove("selfPatch");
|
||||
properties.insert(
|
||||
"frontierPlanningRequestId".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Exact echo of the coordinator-bound repo frontier planning request."
|
||||
}),
|
||||
);
|
||||
properties.insert(
|
||||
"frontierPlanCandidate".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"required": [
|
||||
"planning_request_id", "model_revision", "model_hash",
|
||||
"frontier_item_id", "frontier_item_hash", "safe_paths", "action", "command",
|
||||
"checks", "stop_conditions", "rollback_steps", "commit_message", "proposed_at"
|
||||
"safe_paths", "action", "command", "checks", "stop_conditions",
|
||||
"rollback_steps", "commit_message"
|
||||
],
|
||||
"properties": {
|
||||
"planning_request_id": {"type": "string", "minLength": 1},
|
||||
"model_revision": {"type": "integer", "minimum": 0},
|
||||
"model_hash": {"type": "string", "minLength": 1},
|
||||
"frontier_item_id": {"type": "string", "minLength": 1},
|
||||
"frontier_item_hash": {"type": "string", "minLength": 1},
|
||||
"safe_paths": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
|
|
@ -1074,8 +688,7 @@ pub fn epiphany_frontier_planning_output_schema() -> serde_json::Value {
|
|||
"checks": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}},
|
||||
"stop_conditions": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}},
|
||||
"rollback_steps": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}},
|
||||
"commit_message": {"type": "string", "minLength": 1},
|
||||
"proposed_at": {"type": "string", "minLength": 1}
|
||||
"commit_message": {"type": "string", "minLength": 1}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}),
|
||||
|
|
@ -1086,7 +699,6 @@ pub fn epiphany_frontier_planning_output_schema() -> serde_json::Value {
|
|||
"summary",
|
||||
"nextSafeMove",
|
||||
"filesInspected",
|
||||
"frontierPlanningRequestId",
|
||||
"frontierPlanCandidate"
|
||||
]);
|
||||
schema["additionalProperties"] = serde_json::Value::Bool(false);
|
||||
|
|
@ -1102,19 +714,17 @@ pub fn epiphany_frontier_plan_mind_output_schema() -> serde_json::Value {
|
|||
"summary": {"type": "string", "minLength": 1},
|
||||
"nextSafeMove": {"type": "string", "minLength": 1},
|
||||
"filesInspected": {"type": "array", "items": {"type": "string"}},
|
||||
"frontierPlanMindRequestId": {"type": "string", "minLength": 1},
|
||||
"frontierPlanMindDecision": {
|
||||
"type": "object",
|
||||
"required": ["mindRequestId", "planningRequestId", "imaginationResultId", "candidateId", "candidateSha256", "decision", "rationale", "decidedAt"],
|
||||
"description": "Semantic Mind disposition only. Runtime binds the exact request, planning candidate, keyed RepoModel basis, source versions, receipt identity, and decision time.",
|
||||
"required": ["decision", "rationale"],
|
||||
"properties": {
|
||||
"mindRequestId": {"type": "string", "minLength": 1}, "planningRequestId": {"type": "string", "minLength": 1},
|
||||
"imaginationResultId": {"type": "string", "minLength": 1}, "candidateId": {"type": "string", "minLength": 1},
|
||||
"candidateSha256": {"type": "string", "minLength": 1}, "decision": {"type": "string", "enum": ["adopt", "refuse", "hold"]},
|
||||
"rationale": {"type": "string", "minLength": 1}, "decidedAt": {"type": "string", "minLength": 1}
|
||||
"decision": {"type": "string", "enum": ["adopt", "refuse", "hold"]},
|
||||
"rationale": {"type": "string", "minLength": 1}
|
||||
}, "additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["roleId", "verdict", "summary", "nextSafeMove", "filesInspected", "frontierPlanMindRequestId", "frontierPlanMindDecision"],
|
||||
"required": ["roleId", "verdict", "summary", "nextSafeMove", "filesInspected", "frontierPlanMindDecision"],
|
||||
"additionalProperties": false
|
||||
})
|
||||
}
|
||||
|
|
@ -1777,6 +1387,7 @@ fn epiphany_active_graph_node_ids(state: Option<&EpiphanyThreadState>) -> Vec<St
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sha2::Digest;
|
||||
|
||||
#[test]
|
||||
fn admitted_direction_schema_bounds_autonomous_proposal_fanout() {
|
||||
|
|
@ -1891,118 +1502,80 @@ mod tests {
|
|||
schema["properties"]["frontierPlanMindDecision"]["properties"]["decision"]["enum"],
|
||||
serde_json::json!(["adopt", "refuse", "hold"])
|
||||
);
|
||||
assert!(
|
||||
schema["properties"]
|
||||
.get("frontierPlanMindRequestId")
|
||||
.is_none()
|
||||
);
|
||||
for runtime_owned in [
|
||||
"mindRequestId",
|
||||
"planningRequestId",
|
||||
"imaginationResultId",
|
||||
"candidateId",
|
||||
"candidateSha256",
|
||||
"decidedAt",
|
||||
] {
|
||||
assert!(
|
||||
schema["properties"]["frontierPlanMindDecision"]["properties"]
|
||||
.get(runtime_owned)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modeling_schema_exposes_only_typed_authority_purposes() {
|
||||
fn modeling_schema_exposes_semantic_operations_without_runtime_authority() {
|
||||
let schema = epiphany_role_launch_output_schema(EpiphanyRoleResultRoleId::Modeling);
|
||||
assert!(
|
||||
schema["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|value| value == "repositoryBodyObservationBasis")
|
||||
);
|
||||
assert_eq!(
|
||||
schema["properties"]["repositoryBodyObservationBasis"]["additionalProperties"],
|
||||
false
|
||||
);
|
||||
let frontier_item = &schema["properties"]["repoModelPatch"]["properties"]["operations"]["items"]
|
||||
["anyOf"][6]["properties"]["item"];
|
||||
assert!(
|
||||
frontier_item["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|value| value == "target_claim_ids")
|
||||
);
|
||||
assert_eq!(
|
||||
frontier_item["properties"]["target_claim_ids"]["minItems"],
|
||||
1
|
||||
);
|
||||
let purposes = schema["properties"]["repoModelPatch"]["properties"]["purpose"]["oneOf"]
|
||||
let required = schema["required"].as_array().expect("required fields");
|
||||
assert!(required.iter().any(|value| value == "repoModelOperations"));
|
||||
for runtime_owned in [
|
||||
"repoModelPatch",
|
||||
"repositoryBodyObservationBasis",
|
||||
"repoFrontierModelingRequestId",
|
||||
"proposalModelingRequestId",
|
||||
"claimRepairRequestId",
|
||||
] {
|
||||
assert!(schema["properties"].get(runtime_owned).is_none());
|
||||
}
|
||||
let operations = schema["properties"]["repoModelOperations"]["items"]["anyOf"]
|
||||
.as_array()
|
||||
.expect("typed Modeling purpose alternatives");
|
||||
assert_eq!(purposes.len(), 4);
|
||||
assert_eq!(purposes[0]["properties"]["kind"]["const"], "evolution");
|
||||
.expect("typed Modeling operations");
|
||||
let operation_names = operations
|
||||
.iter()
|
||||
.map(|operation| {
|
||||
operation["properties"]["operation"]["const"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
purposes[1]["properties"]["kind"]["const"],
|
||||
"incorporate_frontier_verdict"
|
||||
operation_names,
|
||||
vec![
|
||||
"put_node",
|
||||
"retire_node",
|
||||
"put_edge",
|
||||
"retire_edge",
|
||||
"put_frontier"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
purposes[1]["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|value| value == "route_id")
|
||||
);
|
||||
assert_eq!(
|
||||
schema["allOf"][0]["then"]["required"][0],
|
||||
"repoFrontierModelingRequestId"
|
||||
);
|
||||
assert_eq!(purposes[2]["properties"]["kind"]["const"], "repair_claim");
|
||||
assert_eq!(
|
||||
purposes[3]["properties"]["kind"]["const"],
|
||||
"adopt_frontier_plan"
|
||||
);
|
||||
assert_eq!(
|
||||
schema["allOf"][1]["then"]["required"][0],
|
||||
"claimRepairRequestId"
|
||||
);
|
||||
assert_eq!(
|
||||
schema["allOf"][2]["then"]["properties"]["repoModelPatch"]["properties"]["operations"]
|
||||
["maxContains"],
|
||||
1
|
||||
);
|
||||
let future_gap_operations =
|
||||
schema["allOf"][3]["then"]["properties"]["repoModelPatch"]["properties"]["operations"]
|
||||
["items"]["anyOf"]
|
||||
.as_array()
|
||||
.expect("future-gap Modeling operations");
|
||||
assert_eq!(future_gap_operations.len(), 7);
|
||||
let future_gap_frontier = &future_gap_operations[6]["properties"]["item"];
|
||||
assert_eq!(
|
||||
future_gap_frontier["properties"]["recommended_next_organ"]["const"],
|
||||
"Imagination"
|
||||
);
|
||||
assert_eq!(
|
||||
future_gap_frontier["properties"]["status"]["const"],
|
||||
"active"
|
||||
);
|
||||
assert_eq!(
|
||||
future_gap_frontier["properties"]["dependency_item_ids"]["maxItems"],
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
schema["allOf"][3]["then"]["properties"]["repoModelPatch"]["properties"]["operations"]
|
||||
["minContains"],
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
schema["allOf"][3]["then"]["properties"]["repoModelPatch"]["properties"]["operations"]
|
||||
["maxContains"],
|
||||
1
|
||||
);
|
||||
let no_future_gap_operations =
|
||||
schema["allOf"][4]["then"]["properties"]["repoModelPatch"]["properties"]["operations"]
|
||||
["items"]["anyOf"]
|
||||
.as_array()
|
||||
.expect("ordinary Modeling operations without future-gap authority");
|
||||
assert_eq!(no_future_gap_operations.len(), 6);
|
||||
assert!(no_future_gap_operations.iter().all(|operation| {
|
||||
!operation["properties"]["operation"]["const"]
|
||||
.as_str()
|
||||
.is_some_and(|kind| kind.contains("frontier"))
|
||||
}));
|
||||
let operations =
|
||||
schema["properties"]["repoModelPatch"]["properties"]["operations"]["items"]["anyOf"]
|
||||
.as_array()
|
||||
.expect("typed Modeling operations");
|
||||
let node_kinds = operations[0]["properties"]["node"]["properties"]["kind"]["enum"]
|
||||
.as_array()
|
||||
.expect("typed RepoModel node kinds");
|
||||
assert!(node_kinds.iter().any(|kind| kind == "runtime_contract"));
|
||||
assert!(!node_kinds.iter().any(|kind| kind == "claim"));
|
||||
assert!(
|
||||
operations[0]["properties"]["node"]["properties"]
|
||||
.get("created_at")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
schema["allOf"][0]["then"]["properties"]["repoModelOperations"]["maxContains"],
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
schema["allOf"][1]["then"]["properties"]["repoModelOperations"]["maxItems"],
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -2011,8 +1584,15 @@ mod tests {
|
|||
request: crate::RepoFrontierModelingRequest {
|
||||
schema_version: crate::REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION.to_string(),
|
||||
request_id: "modeling-request-exact".into(),
|
||||
model_revision: 7,
|
||||
model_hash: "model-hash".into(),
|
||||
model_projection_digest: format!("sha256:{}", "a".repeat(64)),
|
||||
model_source_documents: vec![crate::EpiphanyMindDocumentVersion {
|
||||
store_id: "epiphany-mind".into(),
|
||||
document_type: "epiphany.mind.repo_model.identity.v1".into(),
|
||||
document_key: crate::REPO_MODEL_IDENTITY_KEY.into(),
|
||||
schema_id: Some("EpiphanyRepoModelIdentityDocument".into()),
|
||||
payload_msgpack: vec![1],
|
||||
payload_sha256: format!("sha256:{:x}", sha2::Sha256::digest([1])),
|
||||
}],
|
||||
route_id: "route-exact".into(),
|
||||
frontier_item_id: "frontier-exact".into(),
|
||||
frontier_item_hash: "frontier-hash".into(),
|
||||
|
|
@ -2048,48 +1628,21 @@ mod tests {
|
|||
},
|
||||
};
|
||||
let schema = epiphany_frontier_verdict_modeling_output_schema(&authority);
|
||||
assert_eq!(
|
||||
schema["properties"]["repoFrontierModelingRequestId"]["const"],
|
||||
"modeling-request-exact"
|
||||
assert!(
|
||||
schema["properties"]
|
||||
.get("repoFrontierModelingRequestId")
|
||||
.is_none()
|
||||
);
|
||||
assert!(schema["properties"].get("repoModelOperations").is_none());
|
||||
assert_eq!(schema["properties"]["frontierVerdictGap"]["type"], "string");
|
||||
assert!(
|
||||
schema["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|value| value == "repoFrontierModelingRequestId")
|
||||
);
|
||||
assert_eq!(
|
||||
schema["properties"]["repoModelPatch"]["properties"]["purpose"]["properties"]["kind"]["const"],
|
||||
"incorporate_frontier_verdict"
|
||||
);
|
||||
let operations = &schema["properties"]["repoModelPatch"]["properties"]["operations"];
|
||||
assert_eq!(operations["minItems"], 1);
|
||||
assert_eq!(operations["maxItems"], 1);
|
||||
assert_eq!(
|
||||
operations["items"]["properties"]["operation"]["const"],
|
||||
"revise_frontier"
|
||||
.any(|value| value == "frontierVerdictGap")
|
||||
);
|
||||
assert_eq!(schema["properties"]["evidenceIds"]["minItems"], 1);
|
||||
let item = &schema["properties"]["repoModelPatch"]["properties"]["operations"]["items"]["properties"]
|
||||
["item"];
|
||||
assert_eq!(item["properties"]["id"]["const"], "frontier-exact");
|
||||
assert_eq!(item["properties"]["status"]["const"], "resolved");
|
||||
assert_eq!(
|
||||
item["properties"]["public_source_refs"]["const"],
|
||||
serde_json::json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
item["properties"]["adopted_plan"]["const"]["command"],
|
||||
"cargo test"
|
||||
);
|
||||
assert!(
|
||||
item["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|field| field == "adopted_plan")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -2142,9 +1695,11 @@ mod tests {
|
|||
assert_eq!(patch["additionalProperties"], false);
|
||||
assert_eq!(observation, &observation_output_schema());
|
||||
assert_eq!(evidence, &evidence_output_schema());
|
||||
assert!(observation["required"]
|
||||
.as_array()
|
||||
.is_some_and(|required| required.iter().any(|field| field == "source_kind")));
|
||||
assert!(
|
||||
observation["required"]
|
||||
.as_array()
|
||||
.is_some_and(|required| required.iter().any(|field| field == "source_kind"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -2153,12 +1708,26 @@ mod tests {
|
|||
assert!(
|
||||
schema["properties"]
|
||||
.get("frontierPlanningRequestId")
|
||||
.is_some()
|
||||
.is_none()
|
||||
);
|
||||
assert!(schema["properties"].get("frontierPlanCandidate").is_some());
|
||||
assert!(schema["properties"].get("statePatch").is_none());
|
||||
assert!(schema["properties"].get("selfPatch").is_none());
|
||||
assert!(schema["properties"].get("repoModelPatch").is_none());
|
||||
for runtime_owned in [
|
||||
"planning_request_id",
|
||||
"model_revision",
|
||||
"model_hash",
|
||||
"frontier_item_id",
|
||||
"frontier_item_hash",
|
||||
"proposed_at",
|
||||
] {
|
||||
assert!(
|
||||
schema["properties"]["frontierPlanCandidate"]["properties"]
|
||||
.get(runtime_owned)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
schema["properties"]["frontierPlanCandidate"]["properties"]["safe_paths"]
|
||||
["description"]
|
||||
|
|
|
|||
|
|
@ -3232,8 +3232,8 @@ mod tests {
|
|||
cache.put(
|
||||
&scope_id,
|
||||
&crate::MemorySemanticProjectionRetentionHead {
|
||||
schema_version:
|
||||
crate::MEMORY_SEMANTIC_PROJECTION_RETENTION_HEAD_SCHEMA_VERSION.to_string(),
|
||||
schema_version: crate::MEMORY_SEMANTIC_PROJECTION_RETENTION_HEAD_SCHEMA_VERSION
|
||||
.to_string(),
|
||||
scope_id: scope_id.clone(),
|
||||
revision: 1,
|
||||
retired_generation_count: 1,
|
||||
|
|
|
|||
838
epiphany-core/src/atlas/contracts.rs
Normal file
838
epiphany-core/src/atlas/contracts.rs
Normal file
|
|
@ -0,0 +1,838 @@
|
|||
use anyhow::{Result, bail};
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use semver::{Version, VersionReq};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::RepositoryBodyObservationBasis;
|
||||
|
||||
pub const ATLAS_SURFACE_OFFER_SCHEMA: &str = "gamecult.model.surface_offer.v0";
|
||||
pub const ATLAS_DEPENDENCY_CLAIM_SCHEMA: &str = "gamecult.model.dependency_claim.v0";
|
||||
pub const ATLAS_DEPENDENCY_VERIFICATION_SCHEMA: &str = "gamecult.model.dependency_verification.v0";
|
||||
pub const ATLAS_DEPENDENCY_IMPACT_SCHEMA: &str = "epiphany.model.dependency_impact.v0";
|
||||
pub const ATLAS_PUBLICATION_SCHEMA: &str = "gamecult.model.atlas_publication.v0";
|
||||
pub const ATLAS_PROJECTION_SCHEMA: &str = "gamecult.model.entanglement_projection.v0";
|
||||
pub const ATLAS_TRUST_BINDING_SCHEMA: &str = "gamecult.model.atlas_publisher_trust.v0";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasRepositoryIdentity {
|
||||
pub swarm_id: String,
|
||||
pub workspace_id: String,
|
||||
pub repository_uri: String,
|
||||
}
|
||||
|
||||
impl AtlasRepositoryIdentity {
|
||||
pub fn new(swarm_id: impl Into<String>, workspace_id: impl Into<String>) -> Result<Self> {
|
||||
let swarm_id = swarm_id.into();
|
||||
let workspace_id = workspace_id.into();
|
||||
validate_identifier(&swarm_id, "Atlas swarm id")?;
|
||||
validate_identifier(&workspace_id, "Atlas workspace id")?;
|
||||
Ok(Self {
|
||||
repository_uri: format!("gamecult://swarm/{swarm_id}/workspace/{workspace_id}"),
|
||||
swarm_id,
|
||||
workspace_id,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_identifier(&self.swarm_id, "Atlas swarm id")?;
|
||||
validate_identifier(&self.workspace_id, "Atlas workspace id")?;
|
||||
if self.repository_uri
|
||||
!= format!(
|
||||
"gamecult://swarm/{}/workspace/{}",
|
||||
self.swarm_id, self.workspace_id
|
||||
)
|
||||
{
|
||||
bail!("Atlas repository URI is not the canonical swarm/workspace identity")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasEntanglementKind {
|
||||
Build,
|
||||
Runtime,
|
||||
Deployment,
|
||||
SchemaProtocol,
|
||||
DataState,
|
||||
InfrastructureControl,
|
||||
Governance,
|
||||
LorePersona,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasCriticality {
|
||||
Blocking,
|
||||
Degrading,
|
||||
Informational,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "version_scheme")]
|
||||
pub enum AtlasContractDescriptor {
|
||||
Semver {
|
||||
contract_id: String,
|
||||
version: Version,
|
||||
},
|
||||
ExactSchema {
|
||||
contract_id: String,
|
||||
schema_id: String,
|
||||
},
|
||||
ExactDigest {
|
||||
contract_id: String,
|
||||
sha256: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl AtlasContractDescriptor {
|
||||
pub fn contract_id(&self) -> &str {
|
||||
match self {
|
||||
Self::Semver { contract_id, .. }
|
||||
| Self::ExactSchema { contract_id, .. }
|
||||
| Self::ExactDigest { contract_id, .. } => contract_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_identifier(self.contract_id(), "Atlas contract id")?;
|
||||
match self {
|
||||
Self::Semver { .. } => Ok(()),
|
||||
Self::ExactSchema { schema_id, .. } => {
|
||||
validate_identifier(schema_id, "Atlas exact schema id")
|
||||
}
|
||||
Self::ExactDigest { sha256, .. } => {
|
||||
validate_sha256(sha256, "Atlas exact contract digest")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "version_scheme")]
|
||||
pub enum AtlasContractRequirement {
|
||||
Semver {
|
||||
contract_id: String,
|
||||
requirement: VersionReq,
|
||||
},
|
||||
ExactSchema {
|
||||
contract_id: String,
|
||||
schema_id: String,
|
||||
},
|
||||
ExactDigest {
|
||||
contract_id: String,
|
||||
sha256: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl AtlasContractRequirement {
|
||||
pub fn contract_id(&self) -> &str {
|
||||
match self {
|
||||
Self::Semver { contract_id, .. }
|
||||
| Self::ExactSchema { contract_id, .. }
|
||||
| Self::ExactDigest { contract_id, .. } => contract_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_identifier(self.contract_id(), "Atlas required contract id")?;
|
||||
match self {
|
||||
Self::Semver { .. } => Ok(()),
|
||||
Self::ExactSchema { schema_id, .. } => {
|
||||
validate_identifier(schema_id, "Atlas required exact schema id")
|
||||
}
|
||||
Self::ExactDigest { sha256, .. } => {
|
||||
validate_sha256(sha256, "Atlas required exact contract digest")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "state")]
|
||||
pub enum AtlasOfferLifecycle {
|
||||
Active,
|
||||
Deprecated {
|
||||
replacement_surface_id: Option<Uuid>,
|
||||
},
|
||||
Withdrawn,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "gamecult.model.surface_offer.v0",
|
||||
schema = "gamecult.model.surface_offer.v0"
|
||||
)]
|
||||
pub struct AtlasSurfaceOffer {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub provider: AtlasRepositoryIdentity,
|
||||
#[cultcache(key = 2)]
|
||||
pub surface_id: Uuid,
|
||||
#[cultcache(key = 3)]
|
||||
pub contract: AtlasContractDescriptor,
|
||||
#[cultcache(key = 4)]
|
||||
pub lifecycle: AtlasOfferLifecycle,
|
||||
}
|
||||
|
||||
impl AtlasSurfaceOffer {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
require_schema(&self.schema_version, ATLAS_SURFACE_OFFER_SCHEMA)?;
|
||||
self.provider.validate()?;
|
||||
if self.surface_id.is_nil() {
|
||||
bail!("Atlas surface id must be an opaque non-nil UUID")
|
||||
}
|
||||
self.contract.validate()?;
|
||||
if matches!(
|
||||
self.lifecycle,
|
||||
AtlasOfferLifecycle::Deprecated {
|
||||
replacement_surface_id: Some(replacement)
|
||||
} if replacement == self.surface_id
|
||||
) {
|
||||
bail!("Atlas deprecated offer cannot replace itself")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "resolution")]
|
||||
pub enum AtlasDependencyTarget {
|
||||
Exact {
|
||||
provider: AtlasRepositoryIdentity,
|
||||
surface_id: Uuid,
|
||||
requirement: AtlasContractRequirement,
|
||||
},
|
||||
Unresolved {
|
||||
requirement: AtlasContractRequirement,
|
||||
},
|
||||
}
|
||||
|
||||
impl AtlasDependencyTarget {
|
||||
pub fn requirement(&self) -> &AtlasContractRequirement {
|
||||
match self {
|
||||
Self::Exact { requirement, .. } | Self::Unresolved { requirement } => requirement,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
match self {
|
||||
Self::Exact {
|
||||
provider,
|
||||
surface_id,
|
||||
requirement,
|
||||
} => {
|
||||
provider.validate()?;
|
||||
if surface_id.is_nil() {
|
||||
bail!("Atlas exact dependency target surface must be a non-nil UUID")
|
||||
}
|
||||
requirement.validate()
|
||||
}
|
||||
Self::Unresolved { requirement } => requirement.validate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasFailureSemantics {
|
||||
FailClosed,
|
||||
Degrade,
|
||||
LastKnownSafe,
|
||||
HumanDecision,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasClaimLifecycle {
|
||||
Active,
|
||||
Retired,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "scope")]
|
||||
pub enum AtlasImpactScope {
|
||||
WholeRepository,
|
||||
LocalSurfaces { surface_ids: Vec<Uuid> },
|
||||
}
|
||||
|
||||
impl AtlasImpactScope {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if let Self::LocalSurfaces { surface_ids } = self {
|
||||
if surface_ids.is_empty()
|
||||
|| surface_ids.iter().any(Uuid::is_nil)
|
||||
|| !strictly_sorted_unique(surface_ids)
|
||||
{
|
||||
bail!("Atlas local impact scope must contain sorted unique non-nil surface UUIDs")
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "gamecult.model.dependency_claim.v0",
|
||||
schema = "gamecult.model.dependency_claim.v0"
|
||||
)]
|
||||
pub struct AtlasDependencyClaim {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub consumer: AtlasRepositoryIdentity,
|
||||
#[cultcache(key = 2)]
|
||||
pub claim_id: Uuid,
|
||||
#[cultcache(key = 3)]
|
||||
pub target: AtlasDependencyTarget,
|
||||
#[cultcache(key = 4)]
|
||||
pub entanglement_kind: AtlasEntanglementKind,
|
||||
#[cultcache(key = 5)]
|
||||
pub failure_semantics: AtlasFailureSemantics,
|
||||
#[cultcache(key = 6)]
|
||||
pub impact_scope: AtlasImpactScope,
|
||||
#[cultcache(key = 7)]
|
||||
pub lifecycle: AtlasClaimLifecycle,
|
||||
}
|
||||
|
||||
impl AtlasDependencyClaim {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
require_schema(&self.schema_version, ATLAS_DEPENDENCY_CLAIM_SCHEMA)?;
|
||||
self.consumer.validate()?;
|
||||
if self.claim_id.is_nil() {
|
||||
bail!("Atlas dependency claim id must be an opaque non-nil UUID")
|
||||
}
|
||||
self.target.validate()?;
|
||||
self.impact_scope.validate()?;
|
||||
if let AtlasDependencyTarget::Exact { provider, .. } = &self.target {
|
||||
if provider == &self.consumer {
|
||||
bail!("Atlas dependency claim cannot target its owning repository")
|
||||
}
|
||||
}
|
||||
if matches!(
|
||||
self.entanglement_kind,
|
||||
AtlasEntanglementKind::Build
|
||||
| AtlasEntanglementKind::Deployment
|
||||
| AtlasEntanglementKind::InfrastructureControl
|
||||
) && self.failure_semantics != AtlasFailureSemantics::FailClosed
|
||||
{
|
||||
bail!("build, deployment, and infrastructure/control dependencies must fail closed")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasVerificationVerdict {
|
||||
Passed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "gamecult.model.dependency_verification.v0",
|
||||
schema = "gamecult.model.dependency_verification.v0"
|
||||
)]
|
||||
pub struct AtlasDependencyVerification {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub consumer: AtlasRepositoryIdentity,
|
||||
#[cultcache(key = 2)]
|
||||
pub claim_id: Uuid,
|
||||
#[cultcache(key = 3)]
|
||||
pub claim_publication_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub offer_publication_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub exact_contract: AtlasContractDescriptor,
|
||||
#[cultcache(key = 6)]
|
||||
pub verdict: AtlasVerificationVerdict,
|
||||
#[cultcache(key = 7)]
|
||||
pub evidence_sha256: String,
|
||||
}
|
||||
|
||||
impl AtlasDependencyVerification {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
require_schema(&self.schema_version, ATLAS_DEPENDENCY_VERIFICATION_SCHEMA)?;
|
||||
self.consumer.validate()?;
|
||||
if self.claim_id.is_nil() {
|
||||
bail!("Atlas verification claim id must be non-nil")
|
||||
}
|
||||
validate_sha256(
|
||||
&self.claim_publication_id,
|
||||
"Atlas verification claim publication id",
|
||||
)?;
|
||||
validate_sha256(
|
||||
&self.offer_publication_id,
|
||||
"Atlas verification offer publication id",
|
||||
)?;
|
||||
self.exact_contract.validate()?;
|
||||
validate_sha256(&self.evidence_sha256, "Atlas verification evidence digest")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.model.dependency_impact.v0",
|
||||
schema = "epiphany.model.dependency_impact.v0"
|
||||
)]
|
||||
pub struct AtlasDependencyImpact {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub impact_id: Uuid,
|
||||
#[cultcache(key = 2)]
|
||||
pub consumer: AtlasRepositoryIdentity,
|
||||
#[cultcache(key = 3)]
|
||||
pub claim_id: Uuid,
|
||||
#[cultcache(key = 4)]
|
||||
pub claim_source_payload_sha256: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub projection_sha256: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub source_publication_ids: Vec<String>,
|
||||
#[cultcache(key = 7)]
|
||||
pub criticality: AtlasCriticality,
|
||||
}
|
||||
|
||||
impl AtlasDependencyImpact {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
require_schema(&self.schema_version, ATLAS_DEPENDENCY_IMPACT_SCHEMA)?;
|
||||
self.consumer.validate()?;
|
||||
if self.impact_id.is_nil() || self.claim_id.is_nil() {
|
||||
bail!("Atlas dependency impact and claim ids must be non-nil")
|
||||
}
|
||||
validate_sha256(
|
||||
&self.claim_source_payload_sha256,
|
||||
"Atlas impact local claim source digest",
|
||||
)?;
|
||||
validate_sha256(
|
||||
&self.projection_sha256,
|
||||
"Atlas impact source projection digest",
|
||||
)?;
|
||||
validate_sorted_unique_sha256(
|
||||
&self.source_publication_ids,
|
||||
"Atlas impact source publication ids",
|
||||
true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasMindSourceVersion {
|
||||
pub store_id: String,
|
||||
pub document_type: String,
|
||||
pub document_key: String,
|
||||
pub schema_id: Option<String>,
|
||||
pub payload_sha256: String,
|
||||
}
|
||||
|
||||
impl AtlasMindSourceVersion {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_identifier(&self.store_id, "Atlas source store id")?;
|
||||
validate_identifier(&self.document_type, "Atlas source document type")?;
|
||||
validate_identifier(&self.document_key, "Atlas source document key")?;
|
||||
if let Some(schema_id) = &self.schema_id {
|
||||
validate_identifier(schema_id, "Atlas source schema id")?;
|
||||
}
|
||||
validate_sha256(&self.payload_sha256, "Atlas source payload digest")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasMindCommitBinding {
|
||||
pub receipt_id: String,
|
||||
pub receipt_sha256: String,
|
||||
pub invariant_owner: String,
|
||||
pub source: AtlasMindSourceVersion,
|
||||
}
|
||||
|
||||
impl AtlasMindCommitBinding {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_identifier(&self.receipt_id, "Atlas Mind receipt id")?;
|
||||
validate_sha256(&self.receipt_sha256, "Atlas Mind receipt digest")?;
|
||||
validate_identifier(&self.invariant_owner, "Atlas Mind invariant owner")?;
|
||||
self.source.validate()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasPublisherState {
|
||||
Serving,
|
||||
Draining,
|
||||
Retired,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasPublicationWatermark {
|
||||
pub source_schema: String,
|
||||
pub source_key: String,
|
||||
pub source_payload_sha256: String,
|
||||
pub publication_sequence: u64,
|
||||
}
|
||||
|
||||
impl AtlasPublicationWatermark {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_identifier(&self.source_schema, "Atlas watermark source schema")?;
|
||||
validate_identifier(&self.source_key, "Atlas watermark source key")?;
|
||||
validate_sha256(
|
||||
&self.source_payload_sha256,
|
||||
"Atlas watermark source payload digest",
|
||||
)?;
|
||||
if self.publication_sequence == 0 {
|
||||
bail!("Atlas watermark publication sequence must be positive")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasPublisherStatus {
|
||||
pub publisher: AtlasRepositoryIdentity,
|
||||
pub runtime_id: String,
|
||||
pub runtime_incarnation_id: String,
|
||||
pub heartbeat_sequence: u64,
|
||||
pub heartbeat_at_unix_ms: u64,
|
||||
pub state: AtlasPublisherState,
|
||||
pub watermarks: Vec<AtlasPublicationWatermark>,
|
||||
}
|
||||
|
||||
impl AtlasPublisherStatus {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
self.publisher.validate()?;
|
||||
validate_identifier(&self.runtime_id, "Atlas publisher runtime id")?;
|
||||
validate_identifier(
|
||||
&self.runtime_incarnation_id,
|
||||
"Atlas publisher runtime incarnation id",
|
||||
)?;
|
||||
if self.heartbeat_sequence == 0
|
||||
|| !self.watermarks.windows(2).all(|pair| {
|
||||
(&pair[0].source_schema, &pair[0].source_key)
|
||||
< (&pair[1].source_schema, &pair[1].source_key)
|
||||
})
|
||||
{
|
||||
bail!("Atlas publisher heartbeat sequence or watermark ordering is invalid")
|
||||
}
|
||||
for watermark in &self.watermarks {
|
||||
watermark.validate()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "payload", content = "value")]
|
||||
pub enum AtlasPublicationPayload {
|
||||
PublisherStatus(AtlasPublisherStatus),
|
||||
SurfaceOffer(AtlasSurfaceOffer),
|
||||
DependencyClaim(AtlasDependencyClaim),
|
||||
DependencyVerification(AtlasDependencyVerification),
|
||||
}
|
||||
|
||||
impl AtlasPublicationPayload {
|
||||
pub fn schema(&self) -> &'static str {
|
||||
match self {
|
||||
Self::PublisherStatus(_) => ATLAS_PUBLICATION_SCHEMA,
|
||||
Self::SurfaceOffer(_) => ATLAS_SURFACE_OFFER_SCHEMA,
|
||||
Self::DependencyClaim(_) => ATLAS_DEPENDENCY_CLAIM_SCHEMA,
|
||||
Self::DependencyVerification(_) => ATLAS_DEPENDENCY_VERIFICATION_SCHEMA,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&self) -> String {
|
||||
match self {
|
||||
Self::PublisherStatus(status) => {
|
||||
format!("publisher-status:{}", status.publisher.repository_uri)
|
||||
}
|
||||
Self::SurfaceOffer(offer) => offer.surface_id.to_string(),
|
||||
Self::DependencyClaim(claim) => claim.claim_id.to_string(),
|
||||
Self::DependencyVerification(verification) => verification.claim_id.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn owner(&self) -> &AtlasRepositoryIdentity {
|
||||
match self {
|
||||
Self::PublisherStatus(status) => &status.publisher,
|
||||
Self::SurfaceOffer(offer) => &offer.provider,
|
||||
Self::DependencyClaim(claim) => &claim.consumer,
|
||||
Self::DependencyVerification(verification) => &verification.consumer,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn requires_mind_binding(&self) -> bool {
|
||||
!matches!(self, Self::PublisherStatus(_))
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
match self {
|
||||
Self::PublisherStatus(status) => status.validate(),
|
||||
Self::SurfaceOffer(offer) => offer.validate(),
|
||||
Self::DependencyClaim(claim) => claim.validate(),
|
||||
Self::DependencyVerification(verification) => verification.validate(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasPublicationVisibility {
|
||||
GamecultLocal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasPublicationStatement {
|
||||
pub schema_version: String,
|
||||
pub publication_id: String,
|
||||
pub publisher: AtlasRepositoryIdentity,
|
||||
pub publisher_identity_id: String,
|
||||
pub publication_sequence: u64,
|
||||
pub runtime_id: String,
|
||||
pub runtime_incarnation_id: String,
|
||||
pub body_basis: RepositoryBodyObservationBasis,
|
||||
pub verse_id: String,
|
||||
pub visibility: AtlasPublicationVisibility,
|
||||
pub source: Option<AtlasMindSourceVersion>,
|
||||
pub mind_commit: Option<AtlasMindCommitBinding>,
|
||||
pub canonical_payload_msgpack_sha256: String,
|
||||
pub published_at_unix_ms: u64,
|
||||
pub payload: AtlasPublicationPayload,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "gamecult.model.atlas_publication.v0",
|
||||
schema = "gamecult.model.atlas_publication.v0"
|
||||
)]
|
||||
pub struct AtlasPublicationEnvelope {
|
||||
#[cultcache(key = 0)]
|
||||
pub statement: AtlasPublicationStatement,
|
||||
#[cultcache(key = 1)]
|
||||
pub signature: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasProjectionAudience {
|
||||
pub audience_id: String,
|
||||
pub gamecult_local: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasPublicationFreshness {
|
||||
Current,
|
||||
LastKnownStale,
|
||||
Retired,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasFreshnessPolicy {
|
||||
pub publisher_status_maximum_age_ms: u64,
|
||||
pub maximum_future_skew_ms: u64,
|
||||
}
|
||||
|
||||
impl AtlasFreshnessPolicy {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.publisher_status_maximum_age_ms == 0 {
|
||||
bail!("Atlas publisher status maximum age must be positive")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasCompatibility {
|
||||
Exact,
|
||||
Compatible,
|
||||
Unresolved,
|
||||
OfferMissing,
|
||||
OfferWithdrawn,
|
||||
ContractIdMismatch,
|
||||
VersionSchemeMismatch,
|
||||
VersionMismatch,
|
||||
ClaimRetired,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasVerificationState {
|
||||
Passed,
|
||||
Failed,
|
||||
Missing,
|
||||
LastKnownStale,
|
||||
ExactEdgeMismatch,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasProjectedEntanglement {
|
||||
pub claim_id: Uuid,
|
||||
pub consumer: AtlasRepositoryIdentity,
|
||||
pub provider: Option<AtlasRepositoryIdentity>,
|
||||
pub surface_id: Option<Uuid>,
|
||||
pub entanglement_kind: AtlasEntanglementKind,
|
||||
pub failure_semantics: AtlasFailureSemantics,
|
||||
pub impact_scope: AtlasImpactScope,
|
||||
pub claim_freshness: AtlasPublicationFreshness,
|
||||
pub offer_freshness: Option<AtlasPublicationFreshness>,
|
||||
pub compatibility: AtlasCompatibility,
|
||||
pub verification: AtlasVerificationState,
|
||||
pub claim_publication_id: String,
|
||||
pub offer_publication_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasCycleClass {
|
||||
ForbiddenBuild,
|
||||
ForbiddenDeployment,
|
||||
ForbiddenInfrastructureControl,
|
||||
ReviewRequired,
|
||||
Informational,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasProjectedCycle {
|
||||
pub repositories: Vec<AtlasRepositoryIdentity>,
|
||||
pub entanglement_kinds: Vec<AtlasEntanglementKind>,
|
||||
pub classification: AtlasCycleClass,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasAffectedRepository {
|
||||
pub repository: AtlasRepositoryIdentity,
|
||||
pub minimum_hops: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasBlastRadius {
|
||||
pub source: AtlasRepositoryIdentity,
|
||||
pub source_surface_id: Uuid,
|
||||
pub affected: Vec<AtlasAffectedRepository>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasPublisherProjectionStatus {
|
||||
pub publisher: AtlasRepositoryIdentity,
|
||||
pub runtime_id: String,
|
||||
pub runtime_incarnation_id: String,
|
||||
pub heartbeat_sequence: u64,
|
||||
pub heartbeat_at_unix_ms: u64,
|
||||
pub freshness: AtlasPublicationFreshness,
|
||||
pub watermarks: Vec<AtlasPublicationWatermark>,
|
||||
pub status_publication_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "gamecult.model.entanglement_projection.v0",
|
||||
schema = "gamecult.model.entanglement_projection.v0"
|
||||
)]
|
||||
pub struct AtlasEntanglementProjection {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub audience_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub evaluated_at_unix_ms: u64,
|
||||
#[cultcache(key = 3)]
|
||||
pub source_publication_ids: Vec<String>,
|
||||
#[cultcache(key = 4)]
|
||||
pub publisher_status: Vec<AtlasPublisherProjectionStatus>,
|
||||
#[cultcache(key = 5)]
|
||||
pub entanglements: Vec<AtlasProjectedEntanglement>,
|
||||
#[cultcache(key = 6)]
|
||||
pub cycles: Vec<AtlasProjectedCycle>,
|
||||
#[cultcache(key = 7)]
|
||||
pub blast_radii: Vec<AtlasBlastRadius>,
|
||||
#[cultcache(key = 8)]
|
||||
pub projection_sha256: String,
|
||||
}
|
||||
|
||||
pub(crate) fn require_schema(actual: &str, expected: &str) -> Result<()> {
|
||||
if actual != expected {
|
||||
bail!("Atlas document schema does not match its typed contract")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_identifier(value: &str, field: &str) -> Result<()> {
|
||||
if value.is_empty()
|
||||
|| value.len() > 320
|
||||
|| !value.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/' | b'@')
|
||||
})
|
||||
{
|
||||
bail!("{field} is not a bounded canonical identifier")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_sha256(value: &str, field: &str) -> Result<()> {
|
||||
if value.len() != 71
|
||||
|| !value.starts_with("sha256-")
|
||||
|| !value[7..]
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
||||
{
|
||||
bail!("{field} is not a canonical sha256 digest")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_repository_body_sha256(value: &str, field: &str) -> Result<()> {
|
||||
if value.len() != 64
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
||||
{
|
||||
bail!("{field} is not a canonical repository Body SHA-256 digest")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_sorted_unique_sha256(
|
||||
values: &[String],
|
||||
field: &str,
|
||||
require_non_empty: bool,
|
||||
) -> Result<()> {
|
||||
if (require_non_empty && values.is_empty()) || !strictly_sorted_unique(values) {
|
||||
bail!("{field} must be a non-empty strictly sorted set")
|
||||
}
|
||||
for value in values {
|
||||
validate_sha256(value, field)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn strictly_sorted_unique<T: Ord>(values: &[T]) -> bool {
|
||||
values.windows(2).all(|pair| pair[0] < pair[1])
|
||||
}
|
||||
|
||||
pub(crate) fn canonical_entanglement_kinds(
|
||||
kinds: impl IntoIterator<Item = AtlasEntanglementKind>,
|
||||
) -> Vec<AtlasEntanglementKind> {
|
||||
kinds
|
||||
.into_iter()
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
1313
epiphany-core/src/atlas/eve_surface.rs
Normal file
1313
epiphany-core/src/atlas/eve_surface.rs
Normal file
File diff suppressed because it is too large
Load diff
280
epiphany-core/src/atlas/identity.rs
Normal file
280
epiphany-core/src/atlas/identity.rs
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
use anyhow::{Context, Result, bail};
|
||||
use cultnet_rs::{
|
||||
ServiceIdentityProfile, ServiceIdentitySignature, ServiceIdentitySigner,
|
||||
ServiceIdentityTrustAnchor, ServiceSignaturePurpose, derive_service_identity_id,
|
||||
verify_service_identity_signature,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use super::contracts::*;
|
||||
|
||||
pub const ATLAS_MAX_PUBLICATION_BYTES: usize = 1024 * 1024;
|
||||
|
||||
pub enum AtlasRepositorySigningIdentity {}
|
||||
|
||||
impl ServiceIdentityProfile for AtlasRepositorySigningIdentity {
|
||||
const PRIVATE_TYPE: &'static str = "gamecult.model.atlas_repository_identity.private.v0";
|
||||
const PRIVATE_SCHEMA: &'static str = "gamecult.model.atlas_repository_identity.private.v0";
|
||||
const PRIVATE_KEY: &'static str = "atlas-repository-signing-identity";
|
||||
const TRUST_ANCHOR_TYPE: &'static str =
|
||||
"gamecult.model.atlas_repository_identity.trust_anchor.v0";
|
||||
const TRUST_ANCHOR_SCHEMA: &'static str =
|
||||
"gamecult.model.atlas_repository_identity.trust_anchor.v0";
|
||||
const TRUST_ANCHOR_KEY: &'static str = "atlas-repository-signing-identity-public";
|
||||
const ID_DOMAIN: &'static [u8] = b"gamecult.model.atlas-repository-identity.id.v0\0";
|
||||
const SIGNATURE_DOMAIN: &'static [u8] = b"gamecult.model.atlas-publication.signature.v0\0";
|
||||
const PROTECTOR_CONTEXT: &'static str = "gamecult-model-atlas-repository-identity-v0";
|
||||
}
|
||||
|
||||
pub struct AtlasPublicationPurpose;
|
||||
|
||||
impl ServiceSignaturePurpose<AtlasRepositorySigningIdentity> for AtlasPublicationPurpose {
|
||||
const PURPOSE: &'static [u8] = b"gamecult.model.atlas-publication.v0";
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasPublisherTrustBinding {
|
||||
pub schema_version: String,
|
||||
pub publisher: AtlasRepositoryIdentity,
|
||||
pub signer_identity_id: String,
|
||||
pub trusted_from_unix_ms: u64,
|
||||
pub expires_at_unix_ms: Option<u64>,
|
||||
pub revoked: bool,
|
||||
pub trust_anchor: ServiceIdentityTrustAnchor,
|
||||
}
|
||||
|
||||
impl AtlasPublisherTrustBinding {
|
||||
pub fn validate_at(&self, now_unix_ms: u64) -> Result<()> {
|
||||
require_schema(&self.schema_version, ATLAS_TRUST_BINDING_SCHEMA)?;
|
||||
self.publisher.validate()?;
|
||||
validate_identifier(&self.signer_identity_id, "Atlas trusted signer identity id")?;
|
||||
if self.trust_anchor.schema_version != AtlasRepositorySigningIdentity::TRUST_ANCHOR_SCHEMA
|
||||
|| self.trust_anchor.identity_id != self.signer_identity_id
|
||||
|| derive_service_identity_id::<AtlasRepositorySigningIdentity>(
|
||||
&self.trust_anchor.public_key,
|
||||
)? != self.signer_identity_id
|
||||
|| self.trusted_from_unix_ms > now_unix_ms
|
||||
|| self
|
||||
.expires_at_unix_ms
|
||||
.is_some_and(|expires| expires <= now_unix_ms)
|
||||
|| self.revoked
|
||||
{
|
||||
bail!("Atlas publisher trust binding is invalid, inactive, expired, or revoked")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn sign_atlas_publication(
|
||||
signer: &ServiceIdentitySigner<AtlasRepositorySigningIdentity>,
|
||||
publisher: AtlasRepositoryIdentity,
|
||||
publication_sequence: u64,
|
||||
runtime_id: String,
|
||||
runtime_incarnation_id: String,
|
||||
body_basis: crate::RepositoryBodyObservationBasis,
|
||||
verse_id: String,
|
||||
source: Option<AtlasMindSourceVersion>,
|
||||
mind_commit: Option<AtlasMindCommitBinding>,
|
||||
published_at_unix_ms: u64,
|
||||
payload: AtlasPublicationPayload,
|
||||
) -> Result<AtlasPublicationEnvelope> {
|
||||
let canonical_payload_msgpack_sha256 = sha256(&canonical_atlas_payload_msgpack(&payload)?);
|
||||
let mut statement = AtlasPublicationStatement {
|
||||
schema_version: ATLAS_PUBLICATION_SCHEMA.into(),
|
||||
publication_id: String::new(),
|
||||
publisher,
|
||||
publisher_identity_id: signer.entry().identity_id.clone(),
|
||||
publication_sequence,
|
||||
runtime_id,
|
||||
runtime_incarnation_id,
|
||||
body_basis,
|
||||
verse_id,
|
||||
visibility: AtlasPublicationVisibility::GamecultLocal,
|
||||
source,
|
||||
mind_commit,
|
||||
canonical_payload_msgpack_sha256,
|
||||
published_at_unix_ms,
|
||||
payload,
|
||||
};
|
||||
validate_statement_without_id(&statement)?;
|
||||
statement.publication_id = derive_publication_id(&statement)?;
|
||||
let signature = signer
|
||||
.sign::<AtlasPublicationPurpose>(&rmp_serde::to_vec_named(&statement)?)
|
||||
.signature;
|
||||
Ok(AtlasPublicationEnvelope {
|
||||
statement,
|
||||
signature,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn verify_atlas_publication(
|
||||
trust: &AtlasPublisherTrustBinding,
|
||||
publication: &AtlasPublicationEnvelope,
|
||||
now_unix_ms: u64,
|
||||
) -> Result<()> {
|
||||
if rmp_serde::to_vec(publication)?.len() > ATLAS_MAX_PUBLICATION_BYTES {
|
||||
bail!("Atlas publication exceeds the signed transport size limit")
|
||||
}
|
||||
trust.validate_at(now_unix_ms)?;
|
||||
let statement = &publication.statement;
|
||||
validate_atlas_publication_statement(statement)?;
|
||||
if trust.publisher != statement.publisher
|
||||
|| trust.signer_identity_id != statement.publisher_identity_id
|
||||
|| publication.signature.len() != 64
|
||||
{
|
||||
bail!("Atlas publication owner, signer, or signature shape is invalid")
|
||||
}
|
||||
verify_service_identity_signature::<AtlasRepositorySigningIdentity, AtlasPublicationPurpose>(
|
||||
&trust.trust_anchor,
|
||||
&rmp_serde::to_vec_named(statement)?,
|
||||
&ServiceIdentitySignature {
|
||||
identity_id: statement.publisher_identity_id.clone(),
|
||||
signature: publication.signature.clone(),
|
||||
},
|
||||
)
|
||||
.context("Atlas publication signature is invalid")
|
||||
}
|
||||
|
||||
pub fn validate_atlas_publication_statement(statement: &AtlasPublicationStatement) -> Result<()> {
|
||||
validate_sha256(&statement.publication_id, "Atlas publication id")?;
|
||||
validate_statement_without_id(statement)?;
|
||||
if statement.publication_id != derive_publication_id(statement)? {
|
||||
bail!("Atlas publication id does not match its canonical signed statement")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn canonical_atlas_payload_msgpack(payload: &AtlasPublicationPayload) -> Result<Vec<u8>> {
|
||||
match payload {
|
||||
AtlasPublicationPayload::PublisherStatus(status) => Ok(rmp_serde::to_vec_named(status)?),
|
||||
AtlasPublicationPayload::SurfaceOffer(offer) => Ok(rmp_serde::to_vec_named(offer)?),
|
||||
AtlasPublicationPayload::DependencyClaim(claim) => Ok(rmp_serde::to_vec_named(claim)?),
|
||||
AtlasPublicationPayload::DependencyVerification(verification) => {
|
||||
Ok(rmp_serde::to_vec_named(verification)?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact bytes used by the local CultCache `DatabaseEntry` encoding. This is
|
||||
/// the source-version payload, distinct from the named canonical publication
|
||||
/// payload above.
|
||||
pub fn atlas_source_payload_msgpack(payload: &AtlasPublicationPayload) -> Result<Vec<u8>> {
|
||||
match payload {
|
||||
AtlasPublicationPayload::PublisherStatus(status) => Ok(rmp_serde::to_vec(status)?),
|
||||
AtlasPublicationPayload::SurfaceOffer(offer) => Ok(rmp_serde::to_vec(offer)?),
|
||||
AtlasPublicationPayload::DependencyClaim(claim) => Ok(rmp_serde::to_vec(claim)?),
|
||||
AtlasPublicationPayload::DependencyVerification(verification) => {
|
||||
Ok(rmp_serde::to_vec(verification)?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_statement_without_id(statement: &AtlasPublicationStatement) -> Result<()> {
|
||||
require_schema(&statement.schema_version, ATLAS_PUBLICATION_SCHEMA)?;
|
||||
statement.publisher.validate()?;
|
||||
statement.payload.validate()?;
|
||||
validate_identifier(
|
||||
&statement.publisher_identity_id,
|
||||
"Atlas publication signer identity id",
|
||||
)?;
|
||||
validate_identifier(&statement.runtime_id, "Atlas publication runtime id")?;
|
||||
validate_identifier(
|
||||
&statement.runtime_incarnation_id,
|
||||
"Atlas publication runtime incarnation id",
|
||||
)?;
|
||||
validate_identifier(&statement.verse_id, "Atlas publication Verse id")?;
|
||||
if !statement.verse_id.starts_with("cultmesh://gamecult-local/") {
|
||||
bail!("Atlas publication is not bound to the GameCult-local Verse")
|
||||
}
|
||||
if statement.publication_sequence == 0
|
||||
|| statement.publisher != *statement.payload.owner()
|
||||
|| statement.body_basis.swarm_id != statement.publisher.swarm_id
|
||||
|| statement.body_basis.workspace_id != statement.publisher.workspace_id
|
||||
|| statement.body_basis.runtime_id != statement.runtime_id
|
||||
|| statement.body_basis.generation == 0
|
||||
{
|
||||
bail!(
|
||||
"Atlas publication owner, sequence, runtime, or repository Body basis is inconsistent"
|
||||
)
|
||||
}
|
||||
validate_identifier(
|
||||
&statement.body_basis.schema_version,
|
||||
"Atlas Body basis schema",
|
||||
)?;
|
||||
validate_identifier(
|
||||
&statement.body_basis.observation_id,
|
||||
"Atlas Body observation id",
|
||||
)?;
|
||||
validate_repository_body_sha256(
|
||||
&statement.body_basis.body_binding_sha256,
|
||||
"Atlas Body binding digest",
|
||||
)?;
|
||||
validate_repository_body_sha256(
|
||||
&statement.body_basis.manifest_root_sha256,
|
||||
"Atlas Body manifest digest",
|
||||
)?;
|
||||
|
||||
let canonical_payload_sha256 = sha256(&canonical_atlas_payload_msgpack(&statement.payload)?);
|
||||
let source_payload_sha256 = sha256(&atlas_source_payload_msgpack(&statement.payload)?);
|
||||
if canonical_payload_sha256 != statement.canonical_payload_msgpack_sha256 {
|
||||
bail!("Atlas canonical payload MessagePack digest is invalid")
|
||||
}
|
||||
match (
|
||||
statement.payload.requires_mind_binding(),
|
||||
&statement.source,
|
||||
&statement.mind_commit,
|
||||
) {
|
||||
(false, None, None) => {}
|
||||
(true, Some(source), Some(commit)) => {
|
||||
source.validate()?;
|
||||
commit.validate()?;
|
||||
if source != &commit.source
|
||||
|| source.document_type != statement.payload.schema()
|
||||
|| source.document_key != statement.payload.key()
|
||||
|| source.schema_id.as_deref() != Some(statement.payload.schema())
|
||||
|| source.payload_sha256 != source_payload_sha256
|
||||
{
|
||||
bail!(
|
||||
"Atlas publication source, Mind receipt binding, schema, key, or payload digest was substituted"
|
||||
)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
bail!(
|
||||
"Atlas Mind document publications require exact source/commit binding; publisher status forbids it"
|
||||
)
|
||||
}
|
||||
}
|
||||
if let AtlasPublicationPayload::PublisherStatus(status) = &statement.payload {
|
||||
if status.publisher != statement.publisher
|
||||
|| status.runtime_id != statement.runtime_id
|
||||
|| status.runtime_incarnation_id != statement.runtime_incarnation_id
|
||||
|| status.heartbeat_at_unix_ms != statement.published_at_unix_ms
|
||||
{
|
||||
bail!(
|
||||
"Atlas publisher status payload is not exact for its publication runtime and time"
|
||||
)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn derive_publication_id(statement: &AtlasPublicationStatement) -> Result<String> {
|
||||
let mut basis = statement.clone();
|
||||
basis.publication_id.clear();
|
||||
let basis_msgpack = rmp_serde::to_vec_named(&basis)?;
|
||||
Ok(sha256(
|
||||
&[
|
||||
b"gamecult.model.atlas-publication.id.v0\0".as_slice(),
|
||||
basis_msgpack.as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn sha256(bytes: &[u8]) -> String {
|
||||
format!("sha256-{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
873
epiphany-core/src/atlas/impact_ingress.rs
Normal file
873
epiphany-core/src/atlas/impact_ingress.rs
Normal file
|
|
@ -0,0 +1,873 @@
|
|||
use anyhow::{Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::contracts::*;
|
||||
use super::identity::{atlas_source_payload_msgpack, sha256};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasLocalClaimInput {
|
||||
pub claim: AtlasDependencyClaim,
|
||||
pub source_payload_sha256: String,
|
||||
}
|
||||
|
||||
impl AtlasLocalClaimInput {
|
||||
fn validate(&self, local_repository: &AtlasRepositoryIdentity) -> Result<()> {
|
||||
self.claim.validate()?;
|
||||
validate_sha256(
|
||||
&self.source_payload_sha256,
|
||||
"Atlas impact ingress local claim source digest",
|
||||
)?;
|
||||
let source_digest = sha256(&atlas_source_payload_msgpack(
|
||||
&AtlasPublicationPayload::DependencyClaim(self.claim.clone()),
|
||||
)?);
|
||||
if self.claim.consumer != *local_repository || source_digest != self.source_payload_sha256 {
|
||||
bail!("Atlas impact ingress claim is not the exact current local Mind document")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "reason")]
|
||||
pub enum AtlasImpactReason {
|
||||
MissingFromProjection,
|
||||
ProjectedClaimDiffers,
|
||||
ClaimNotCurrent {
|
||||
freshness: AtlasPublicationFreshness,
|
||||
},
|
||||
OfferNotCurrent {
|
||||
freshness: Option<AtlasPublicationFreshness>,
|
||||
},
|
||||
Compatibility {
|
||||
state: AtlasCompatibility,
|
||||
},
|
||||
Verification {
|
||||
state: AtlasVerificationState,
|
||||
},
|
||||
TransitiveBlastRadius {
|
||||
source_repository_uri: String,
|
||||
source_surface_id: Uuid,
|
||||
minimum_hops: u32,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasImpactLane {
|
||||
Modeling,
|
||||
Soul,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AtlasImpactProposalAuthority {
|
||||
LocalReviewOnly,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasLocalImpactProposal {
|
||||
pub proposal_id: Uuid,
|
||||
pub dedupe_key: String,
|
||||
pub lane: AtlasImpactLane,
|
||||
pub reason: AtlasImpactReason,
|
||||
pub authority: AtlasImpactProposalAuthority,
|
||||
pub impact: AtlasDependencyImpact,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasImpactLaneState {
|
||||
pub lane: AtlasImpactLane,
|
||||
pub pending_proposal_id: Option<Uuid>,
|
||||
pub last_completed_at_unix_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasImpactIngressPolicy {
|
||||
pub cooldown_after_completion_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasImpactBrakeState {
|
||||
pub engaged: bool,
|
||||
pub brake_id: Option<String>,
|
||||
}
|
||||
|
||||
impl AtlasImpactBrakeState {
|
||||
fn validate(&self) -> Result<()> {
|
||||
match (self.engaged, &self.brake_id) {
|
||||
(true, Some(brake_id)) => validate_identifier(brake_id, "Atlas impact brake id"),
|
||||
(false, None) => Ok(()),
|
||||
_ => bail!("Atlas impact brake state is internally inconsistent"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case", tag = "disposition")]
|
||||
pub enum AtlasImpactScheduleDisposition {
|
||||
Schedule {
|
||||
lane: AtlasImpactLane,
|
||||
},
|
||||
VisibleOnly,
|
||||
Deduplicated,
|
||||
HeldByBrake {
|
||||
brake_id: String,
|
||||
},
|
||||
HeldByPendingLane {
|
||||
lane: AtlasImpactLane,
|
||||
pending_proposal_id: Uuid,
|
||||
},
|
||||
HeldByCooldown {
|
||||
lane: AtlasImpactLane,
|
||||
retry_at_unix_ms: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasImpactSchedulingDecision {
|
||||
pub proposal_id: Uuid,
|
||||
pub claim_id: Uuid,
|
||||
pub criticality: AtlasCriticality,
|
||||
pub disposition: AtlasImpactScheduleDisposition,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasImpactIngressResult {
|
||||
pub proposals: Vec<AtlasLocalImpactProposal>,
|
||||
pub scheduling_decisions: Vec<AtlasImpactSchedulingDecision>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn evaluate_local_atlas_impacts(
|
||||
local_repository: &AtlasRepositoryIdentity,
|
||||
projection: &AtlasEntanglementProjection,
|
||||
local_claims: &[AtlasLocalClaimInput],
|
||||
seen_dedupe_keys: &BTreeSet<String>,
|
||||
lane_states: &[AtlasImpactLaneState],
|
||||
brake: &AtlasImpactBrakeState,
|
||||
policy: &AtlasImpactIngressPolicy,
|
||||
now_unix_ms: u64,
|
||||
) -> Result<AtlasImpactIngressResult> {
|
||||
local_repository.validate()?;
|
||||
require_schema(&projection.schema_version, ATLAS_PROJECTION_SCHEMA)?;
|
||||
validate_sha256(
|
||||
&projection.projection_sha256,
|
||||
"Atlas impact source projection digest",
|
||||
)?;
|
||||
validate_sorted_unique_sha256(
|
||||
&projection.source_publication_ids,
|
||||
"Atlas impact source projection publication ids",
|
||||
true,
|
||||
)?;
|
||||
brake.validate()?;
|
||||
|
||||
let lanes = validated_lanes(lane_states)?;
|
||||
let mut claims = BTreeMap::<Uuid, &AtlasLocalClaimInput>::new();
|
||||
for claim in local_claims {
|
||||
claim.validate(local_repository)?;
|
||||
if claims.insert(claim.claim.claim_id, claim).is_some() {
|
||||
bail!("Atlas impact ingress received duplicate local claim ids")
|
||||
}
|
||||
}
|
||||
let mut projected = BTreeMap::<Uuid, &AtlasProjectedEntanglement>::new();
|
||||
for entanglement in projection
|
||||
.entanglements
|
||||
.iter()
|
||||
.filter(|entanglement| entanglement.consumer == *local_repository)
|
||||
{
|
||||
if projected
|
||||
.insert(entanglement.claim_id, entanglement)
|
||||
.is_some()
|
||||
{
|
||||
bail!("Atlas projection contains duplicate local entanglement ids")
|
||||
}
|
||||
}
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
for claim in claims.into_values() {
|
||||
if claim.claim.lifecycle == AtlasClaimLifecycle::Retired {
|
||||
continue;
|
||||
}
|
||||
let entanglement = projected.get(&claim.claim.claim_id).copied();
|
||||
let direct = impact_reason(&claim.claim, entanglement);
|
||||
let transitive = transitive_impact_reason(projection, &claim.claim);
|
||||
let selected = match &direct {
|
||||
Some((
|
||||
AtlasImpactReason::Verification {
|
||||
state: AtlasVerificationState::Missing,
|
||||
},
|
||||
_,
|
||||
)) if transitive.is_some() => transitive,
|
||||
_ => direct.or(transitive),
|
||||
};
|
||||
let Some((reason, lane)) = selected else {
|
||||
continue;
|
||||
};
|
||||
let criticality = criticality(&claim.claim, &reason);
|
||||
let source_publication_ids = impact_source_publications(projection, entanglement, &reason);
|
||||
validate_sorted_unique_sha256(
|
||||
&source_publication_ids,
|
||||
"Atlas local impact source publication ids",
|
||||
true,
|
||||
)?;
|
||||
let dedupe_key = sha256(&rmp_serde::to_vec_named(&(
|
||||
"epiphany.model.dependency-impact-dedupe.v0",
|
||||
claim.claim.claim_id,
|
||||
&claim.source_payload_sha256,
|
||||
&source_publication_ids,
|
||||
&reason,
|
||||
criticality,
|
||||
))?);
|
||||
let proposal_id = Uuid::new_v5(&Uuid::NAMESPACE_OID, dedupe_key.as_bytes());
|
||||
let impact = AtlasDependencyImpact {
|
||||
schema_version: ATLAS_DEPENDENCY_IMPACT_SCHEMA.into(),
|
||||
impact_id: proposal_id,
|
||||
consumer: local_repository.clone(),
|
||||
claim_id: claim.claim.claim_id,
|
||||
claim_source_payload_sha256: claim.source_payload_sha256.clone(),
|
||||
projection_sha256: projection.projection_sha256.clone(),
|
||||
source_publication_ids,
|
||||
criticality,
|
||||
};
|
||||
impact.validate()?;
|
||||
candidates.push(AtlasLocalImpactProposal {
|
||||
proposal_id,
|
||||
dedupe_key,
|
||||
lane,
|
||||
reason,
|
||||
authority: AtlasImpactProposalAuthority::LocalReviewOnly,
|
||||
impact,
|
||||
});
|
||||
}
|
||||
candidates.sort_by(|left, right| {
|
||||
(left.impact.criticality, left.impact.claim_id, &left.reason).cmp(&(
|
||||
right.impact.criticality,
|
||||
right.impact.claim_id,
|
||||
&right.reason,
|
||||
))
|
||||
});
|
||||
|
||||
let mut proposals = Vec::new();
|
||||
let mut scheduling_decisions = Vec::with_capacity(candidates.len());
|
||||
let mut reserved = BTreeMap::<AtlasImpactLane, Uuid>::new();
|
||||
for proposal in candidates {
|
||||
let disposition = if seen_dedupe_keys.contains(&proposal.dedupe_key) {
|
||||
AtlasImpactScheduleDisposition::Deduplicated
|
||||
} else if brake.engaged {
|
||||
AtlasImpactScheduleDisposition::HeldByBrake {
|
||||
brake_id: brake
|
||||
.brake_id
|
||||
.clone()
|
||||
.expect("engaged brake validated above"),
|
||||
}
|
||||
} else if proposal.impact.criticality == AtlasCriticality::Informational {
|
||||
AtlasImpactScheduleDisposition::VisibleOnly
|
||||
} else if let Some(pending) = lanes[&proposal.lane].pending_proposal_id {
|
||||
AtlasImpactScheduleDisposition::HeldByPendingLane {
|
||||
lane: proposal.lane,
|
||||
pending_proposal_id: pending,
|
||||
}
|
||||
} else if let Some(pending) = reserved.get(&proposal.lane).copied() {
|
||||
AtlasImpactScheduleDisposition::HeldByPendingLane {
|
||||
lane: proposal.lane,
|
||||
pending_proposal_id: pending,
|
||||
}
|
||||
} else if let Some(retry_at_unix_ms) =
|
||||
cooldown_until(&lanes[&proposal.lane], policy.cooldown_after_completion_ms)?
|
||||
.filter(|retry_at| *retry_at > now_unix_ms)
|
||||
{
|
||||
AtlasImpactScheduleDisposition::HeldByCooldown {
|
||||
lane: proposal.lane,
|
||||
retry_at_unix_ms,
|
||||
}
|
||||
} else {
|
||||
reserved.insert(proposal.lane, proposal.proposal_id);
|
||||
AtlasImpactScheduleDisposition::Schedule {
|
||||
lane: proposal.lane,
|
||||
}
|
||||
};
|
||||
scheduling_decisions.push(AtlasImpactSchedulingDecision {
|
||||
proposal_id: proposal.proposal_id,
|
||||
claim_id: proposal.impact.claim_id,
|
||||
criticality: proposal.impact.criticality,
|
||||
disposition,
|
||||
});
|
||||
if !seen_dedupe_keys.contains(&proposal.dedupe_key) {
|
||||
proposals.push(proposal);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(AtlasImpactIngressResult {
|
||||
proposals,
|
||||
scheduling_decisions,
|
||||
})
|
||||
}
|
||||
|
||||
fn validated_lanes(
|
||||
lane_states: &[AtlasImpactLaneState],
|
||||
) -> Result<BTreeMap<AtlasImpactLane, &AtlasImpactLaneState>> {
|
||||
let mut lanes = BTreeMap::new();
|
||||
for state in lane_states {
|
||||
if lanes.insert(state.lane, state).is_some() {
|
||||
bail!("Atlas impact ingress received duplicate lane state")
|
||||
}
|
||||
}
|
||||
for lane in [AtlasImpactLane::Modeling, AtlasImpactLane::Soul] {
|
||||
if !lanes.contains_key(&lane) {
|
||||
bail!("Atlas impact ingress requires explicit Modeling and Soul lane state")
|
||||
}
|
||||
}
|
||||
Ok(lanes)
|
||||
}
|
||||
|
||||
fn impact_reason(
|
||||
claim: &AtlasDependencyClaim,
|
||||
entanglement: Option<&AtlasProjectedEntanglement>,
|
||||
) -> Option<(AtlasImpactReason, AtlasImpactLane)> {
|
||||
let Some(entanglement) = entanglement else {
|
||||
return Some((
|
||||
AtlasImpactReason::MissingFromProjection,
|
||||
AtlasImpactLane::Modeling,
|
||||
));
|
||||
};
|
||||
if !projected_claim_matches(claim, entanglement) {
|
||||
return Some((
|
||||
AtlasImpactReason::ProjectedClaimDiffers,
|
||||
AtlasImpactLane::Modeling,
|
||||
));
|
||||
}
|
||||
if entanglement.claim_freshness != AtlasPublicationFreshness::Current {
|
||||
return Some((
|
||||
AtlasImpactReason::ClaimNotCurrent {
|
||||
freshness: entanglement.claim_freshness,
|
||||
},
|
||||
AtlasImpactLane::Modeling,
|
||||
));
|
||||
}
|
||||
if matches!(claim.target, AtlasDependencyTarget::Exact { .. })
|
||||
&& entanglement.offer_freshness != Some(AtlasPublicationFreshness::Current)
|
||||
{
|
||||
return Some((
|
||||
AtlasImpactReason::OfferNotCurrent {
|
||||
freshness: entanglement.offer_freshness,
|
||||
},
|
||||
AtlasImpactLane::Modeling,
|
||||
));
|
||||
}
|
||||
if !matches!(
|
||||
entanglement.compatibility,
|
||||
AtlasCompatibility::Exact | AtlasCompatibility::Compatible
|
||||
) {
|
||||
return Some((
|
||||
AtlasImpactReason::Compatibility {
|
||||
state: entanglement.compatibility,
|
||||
},
|
||||
AtlasImpactLane::Modeling,
|
||||
));
|
||||
}
|
||||
if entanglement.verification != AtlasVerificationState::Passed {
|
||||
return Some((
|
||||
AtlasImpactReason::Verification {
|
||||
state: entanglement.verification,
|
||||
},
|
||||
AtlasImpactLane::Soul,
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn projected_claim_matches(
|
||||
claim: &AtlasDependencyClaim,
|
||||
entanglement: &AtlasProjectedEntanglement,
|
||||
) -> bool {
|
||||
if entanglement.consumer != claim.consumer
|
||||
|| entanglement.claim_id != claim.claim_id
|
||||
|| entanglement.entanglement_kind != claim.entanglement_kind
|
||||
|| entanglement.failure_semantics != claim.failure_semantics
|
||||
|| entanglement.impact_scope != claim.impact_scope
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match &claim.target {
|
||||
AtlasDependencyTarget::Exact {
|
||||
provider,
|
||||
surface_id,
|
||||
..
|
||||
} => {
|
||||
entanglement.provider.as_ref() == Some(provider)
|
||||
&& entanglement.surface_id == Some(*surface_id)
|
||||
}
|
||||
AtlasDependencyTarget::Unresolved { .. } => {
|
||||
entanglement.provider.is_none() && entanglement.surface_id.is_none()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn criticality(claim: &AtlasDependencyClaim, reason: &AtlasImpactReason) -> AtlasCriticality {
|
||||
if matches!(
|
||||
reason,
|
||||
AtlasImpactReason::ProjectedClaimDiffers
|
||||
| AtlasImpactReason::Verification {
|
||||
state: AtlasVerificationState::Failed
|
||||
}
|
||||
) || matches!(
|
||||
claim.failure_semantics,
|
||||
AtlasFailureSemantics::FailClosed | AtlasFailureSemantics::HumanDecision
|
||||
) {
|
||||
AtlasCriticality::Blocking
|
||||
} else if matches!(
|
||||
reason,
|
||||
AtlasImpactReason::Verification {
|
||||
state: AtlasVerificationState::Missing
|
||||
}
|
||||
) && claim.entanglement_kind == AtlasEntanglementKind::LorePersona
|
||||
{
|
||||
AtlasCriticality::Informational
|
||||
} else {
|
||||
AtlasCriticality::Degrading
|
||||
}
|
||||
}
|
||||
|
||||
fn transitive_impact_reason(
|
||||
projection: &AtlasEntanglementProjection,
|
||||
claim: &AtlasDependencyClaim,
|
||||
) -> Option<(AtlasImpactReason, AtlasImpactLane)> {
|
||||
let AtlasDependencyTarget::Exact { provider, .. } = &claim.target else {
|
||||
return None;
|
||||
};
|
||||
projection.blast_radii.iter().find_map(|radius| {
|
||||
let local = radius
|
||||
.affected
|
||||
.iter()
|
||||
.find(|affected| affected.repository == claim.consumer && affected.minimum_hops >= 2)?;
|
||||
let provider_hops = if radius.source == *provider {
|
||||
0
|
||||
} else {
|
||||
radius
|
||||
.affected
|
||||
.iter()
|
||||
.find(|affected| affected.repository == *provider)?
|
||||
.minimum_hops
|
||||
};
|
||||
if local.minimum_hops != provider_hops.saturating_add(1)
|
||||
|| !projection.entanglements.iter().any(|edge| {
|
||||
edge.provider.as_ref() == Some(&radius.source)
|
||||
&& edge.surface_id == Some(radius.source_surface_id)
|
||||
&& (edge.claim_freshness != AtlasPublicationFreshness::Current
|
||||
|| edge.offer_freshness != Some(AtlasPublicationFreshness::Current)
|
||||
|| !matches!(
|
||||
edge.compatibility,
|
||||
AtlasCompatibility::Exact | AtlasCompatibility::Compatible
|
||||
)
|
||||
|| edge.verification == AtlasVerificationState::Failed)
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
AtlasImpactReason::TransitiveBlastRadius {
|
||||
source_repository_uri: radius.source.repository_uri.clone(),
|
||||
source_surface_id: radius.source_surface_id,
|
||||
minimum_hops: local.minimum_hops,
|
||||
},
|
||||
AtlasImpactLane::Modeling,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn impact_source_publications(
|
||||
projection: &AtlasEntanglementProjection,
|
||||
entanglement: Option<&AtlasProjectedEntanglement>,
|
||||
reason: &AtlasImpactReason,
|
||||
) -> Vec<String> {
|
||||
let mut source_ids = if matches!(reason, AtlasImpactReason::TransitiveBlastRadius { .. }) {
|
||||
projection.source_publication_ids.clone()
|
||||
} else {
|
||||
entanglement
|
||||
.map(|entanglement| {
|
||||
let mut ids = vec![entanglement.claim_publication_id.clone()];
|
||||
ids.extend(entanglement.offer_publication_id.iter().cloned());
|
||||
ids
|
||||
})
|
||||
.unwrap_or_else(|| projection.source_publication_ids.clone())
|
||||
};
|
||||
source_ids.sort();
|
||||
source_ids.dedup();
|
||||
source_ids
|
||||
}
|
||||
|
||||
fn cooldown_until(state: &AtlasImpactLaneState, cooldown_ms: u64) -> Result<Option<u64>> {
|
||||
state
|
||||
.last_completed_at_unix_ms
|
||||
.map(|completed| {
|
||||
completed
|
||||
.checked_add(cooldown_ms)
|
||||
.ok_or_else(|| anyhow::anyhow!("Atlas impact lane cooldown overflowed"))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use semver::VersionReq;
|
||||
|
||||
fn digest(seed: &str) -> String {
|
||||
sha256(seed.as_bytes())
|
||||
}
|
||||
|
||||
fn repository(workspace: &str) -> AtlasRepositoryIdentity {
|
||||
AtlasRepositoryIdentity::new("swarm", workspace).unwrap()
|
||||
}
|
||||
|
||||
fn claim() -> AtlasDependencyClaim {
|
||||
AtlasDependencyClaim {
|
||||
schema_version: ATLAS_DEPENDENCY_CLAIM_SCHEMA.into(),
|
||||
consumer: repository("consumer"),
|
||||
claim_id: Uuid::from_u128(1),
|
||||
target: AtlasDependencyTarget::Exact {
|
||||
provider: repository("provider"),
|
||||
surface_id: Uuid::from_u128(2),
|
||||
requirement: AtlasContractRequirement::Semver {
|
||||
contract_id: "contract.surface".into(),
|
||||
requirement: VersionReq::parse("^1").unwrap(),
|
||||
},
|
||||
},
|
||||
entanglement_kind: AtlasEntanglementKind::Runtime,
|
||||
failure_semantics: AtlasFailureSemantics::Degrade,
|
||||
impact_scope: AtlasImpactScope::WholeRepository,
|
||||
lifecycle: AtlasClaimLifecycle::Active,
|
||||
}
|
||||
}
|
||||
|
||||
fn local_claim() -> AtlasLocalClaimInput {
|
||||
let claim = claim();
|
||||
let source_payload_sha256 = sha256(
|
||||
&atlas_source_payload_msgpack(&AtlasPublicationPayload::DependencyClaim(claim.clone()))
|
||||
.unwrap(),
|
||||
);
|
||||
AtlasLocalClaimInput {
|
||||
claim,
|
||||
source_payload_sha256,
|
||||
}
|
||||
}
|
||||
|
||||
fn entanglement(
|
||||
compatibility: AtlasCompatibility,
|
||||
verification: AtlasVerificationState,
|
||||
) -> AtlasProjectedEntanglement {
|
||||
AtlasProjectedEntanglement {
|
||||
claim_id: Uuid::from_u128(1),
|
||||
consumer: repository("consumer"),
|
||||
provider: Some(repository("provider")),
|
||||
surface_id: Some(Uuid::from_u128(2)),
|
||||
entanglement_kind: AtlasEntanglementKind::Runtime,
|
||||
failure_semantics: AtlasFailureSemantics::Degrade,
|
||||
impact_scope: AtlasImpactScope::WholeRepository,
|
||||
claim_freshness: AtlasPublicationFreshness::Current,
|
||||
offer_freshness: Some(AtlasPublicationFreshness::Current),
|
||||
compatibility,
|
||||
verification,
|
||||
claim_publication_id: digest("claim-publication"),
|
||||
offer_publication_id: Some(digest("offer-publication")),
|
||||
}
|
||||
}
|
||||
|
||||
fn projection(entanglement: AtlasProjectedEntanglement) -> AtlasEntanglementProjection {
|
||||
let mut source_publication_ids = vec![
|
||||
entanglement.claim_publication_id.clone(),
|
||||
entanglement.offer_publication_id.clone().unwrap(),
|
||||
];
|
||||
source_publication_ids.sort();
|
||||
AtlasEntanglementProjection {
|
||||
schema_version: ATLAS_PROJECTION_SCHEMA.into(),
|
||||
audience_id: "local-consumer".into(),
|
||||
evaluated_at_unix_ms: 1_800_000_000_000,
|
||||
source_publication_ids,
|
||||
publisher_status: Vec::new(),
|
||||
entanglements: vec![entanglement],
|
||||
cycles: Vec::new(),
|
||||
blast_radii: Vec::new(),
|
||||
projection_sha256: digest("projection"),
|
||||
}
|
||||
}
|
||||
|
||||
fn lanes() -> Vec<AtlasImpactLaneState> {
|
||||
vec![
|
||||
AtlasImpactLaneState {
|
||||
lane: AtlasImpactLane::Modeling,
|
||||
pending_proposal_id: None,
|
||||
last_completed_at_unix_ms: None,
|
||||
},
|
||||
AtlasImpactLaneState {
|
||||
lane: AtlasImpactLane::Soul,
|
||||
pending_proposal_id: None,
|
||||
last_completed_at_unix_ms: None,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn no_brake() -> AtlasImpactBrakeState {
|
||||
AtlasImpactBrakeState {
|
||||
engaged: false,
|
||||
brake_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_projection_yields_only_a_modeling_proposal() -> Result<()> {
|
||||
let result = evaluate_local_atlas_impacts(
|
||||
&repository("consumer"),
|
||||
&projection(entanglement(
|
||||
AtlasCompatibility::VersionMismatch,
|
||||
AtlasVerificationState::Missing,
|
||||
)),
|
||||
&[local_claim()],
|
||||
&BTreeSet::new(),
|
||||
&lanes(),
|
||||
&no_brake(),
|
||||
&AtlasImpactIngressPolicy {
|
||||
cooldown_after_completion_ms: 100,
|
||||
},
|
||||
1_800_000_000_000,
|
||||
)?;
|
||||
|
||||
assert_eq!(result.proposals.len(), 1);
|
||||
assert_eq!(result.proposals[0].lane, AtlasImpactLane::Modeling);
|
||||
assert_eq!(
|
||||
result.proposals[0].authority,
|
||||
AtlasImpactProposalAuthority::LocalReviewOnly
|
||||
);
|
||||
assert!(matches!(
|
||||
result.scheduling_decisions[0].disposition,
|
||||
AtlasImpactScheduleDisposition::Schedule {
|
||||
lane: AtlasImpactLane::Modeling
|
||||
}
|
||||
));
|
||||
result.proposals[0].impact.validate()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn informational_change_is_visible_without_waking_a_lane() -> Result<()> {
|
||||
let mut informational_claim = claim();
|
||||
informational_claim.entanglement_kind = AtlasEntanglementKind::LorePersona;
|
||||
let source_payload_sha256 = sha256(&atlas_source_payload_msgpack(
|
||||
&AtlasPublicationPayload::DependencyClaim(informational_claim.clone()),
|
||||
)?);
|
||||
let mut edge = entanglement(AtlasCompatibility::Exact, AtlasVerificationState::Missing);
|
||||
edge.entanglement_kind = AtlasEntanglementKind::LorePersona;
|
||||
let result = evaluate_local_atlas_impacts(
|
||||
&repository("consumer"),
|
||||
&projection(edge),
|
||||
&[AtlasLocalClaimInput {
|
||||
claim: informational_claim,
|
||||
source_payload_sha256,
|
||||
}],
|
||||
&BTreeSet::new(),
|
||||
&lanes(),
|
||||
&no_brake(),
|
||||
&AtlasImpactIngressPolicy {
|
||||
cooldown_after_completion_ms: 100,
|
||||
},
|
||||
1_800_000_000_000,
|
||||
)?;
|
||||
|
||||
assert_eq!(
|
||||
result.proposals[0].impact.criticality,
|
||||
AtlasCriticality::Informational
|
||||
);
|
||||
assert_eq!(
|
||||
result.scheduling_decisions[0].disposition,
|
||||
AtlasImpactScheduleDisposition::VisibleOnly
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transitive_blocking_blast_wakes_the_exact_downstream_claim() -> Result<()> {
|
||||
let mut local_claim = claim();
|
||||
local_claim.failure_semantics = AtlasFailureSemantics::FailClosed;
|
||||
let local_source = sha256(&atlas_source_payload_msgpack(
|
||||
&AtlasPublicationPayload::DependencyClaim(local_claim.clone()),
|
||||
)?);
|
||||
let mut local_edge =
|
||||
entanglement(AtlasCompatibility::Exact, AtlasVerificationState::Passed);
|
||||
local_edge.failure_semantics = AtlasFailureSemantics::FailClosed;
|
||||
let eve = repository("eve");
|
||||
let odin = repository("provider");
|
||||
let mut source_edge = local_edge.clone();
|
||||
source_edge.claim_id = Uuid::from_u128(9);
|
||||
source_edge.consumer = odin.clone();
|
||||
source_edge.provider = Some(eve.clone());
|
||||
source_edge.surface_id = Some(Uuid::from_u128(8));
|
||||
source_edge.compatibility = AtlasCompatibility::VersionMismatch;
|
||||
source_edge.claim_publication_id = digest("odin-eve-claim");
|
||||
source_edge.offer_publication_id = Some(digest("eve-offer"));
|
||||
let mut source_publication_ids = vec![
|
||||
local_edge.claim_publication_id.clone(),
|
||||
local_edge.offer_publication_id.clone().unwrap(),
|
||||
source_edge.claim_publication_id.clone(),
|
||||
source_edge.offer_publication_id.clone().unwrap(),
|
||||
];
|
||||
source_publication_ids.sort();
|
||||
let projection = AtlasEntanglementProjection {
|
||||
schema_version: ATLAS_PROJECTION_SCHEMA.into(),
|
||||
audience_id: "gamecult-local".into(),
|
||||
evaluated_at_unix_ms: 1_800_000_000_000,
|
||||
source_publication_ids,
|
||||
publisher_status: Vec::new(),
|
||||
entanglements: vec![local_edge, source_edge],
|
||||
cycles: Vec::new(),
|
||||
blast_radii: vec![AtlasBlastRadius {
|
||||
source: eve,
|
||||
source_surface_id: Uuid::from_u128(8),
|
||||
affected: vec![
|
||||
AtlasAffectedRepository {
|
||||
repository: odin,
|
||||
minimum_hops: 1,
|
||||
},
|
||||
AtlasAffectedRepository {
|
||||
repository: repository("consumer"),
|
||||
minimum_hops: 2,
|
||||
},
|
||||
],
|
||||
}],
|
||||
projection_sha256: digest("transitive-projection"),
|
||||
};
|
||||
let result = evaluate_local_atlas_impacts(
|
||||
&repository("consumer"),
|
||||
&projection,
|
||||
&[AtlasLocalClaimInput {
|
||||
claim: local_claim,
|
||||
source_payload_sha256: local_source,
|
||||
}],
|
||||
&BTreeSet::new(),
|
||||
&lanes(),
|
||||
&no_brake(),
|
||||
&AtlasImpactIngressPolicy {
|
||||
cooldown_after_completion_ms: 100,
|
||||
},
|
||||
1_800_000_000_000,
|
||||
)?;
|
||||
assert_eq!(result.proposals.len(), 1);
|
||||
assert_eq!(result.proposals[0].lane, AtlasImpactLane::Modeling);
|
||||
assert_eq!(
|
||||
result.proposals[0].impact.criticality,
|
||||
AtlasCriticality::Blocking
|
||||
);
|
||||
assert!(matches!(
|
||||
result.proposals[0].reason,
|
||||
AtlasImpactReason::TransitiveBlastRadius {
|
||||
minimum_hops: 2,
|
||||
..
|
||||
}
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brake_preserves_new_proposal_but_dedupe_suppresses_repeat_pressure() -> Result<()> {
|
||||
let projection = projection(entanglement(
|
||||
AtlasCompatibility::VersionMismatch,
|
||||
AtlasVerificationState::Missing,
|
||||
));
|
||||
let brake = AtlasImpactBrakeState {
|
||||
engaged: true,
|
||||
brake_id: Some("operator-brake".into()),
|
||||
};
|
||||
let first = evaluate_local_atlas_impacts(
|
||||
&repository("consumer"),
|
||||
&projection,
|
||||
&[local_claim()],
|
||||
&BTreeSet::new(),
|
||||
&lanes(),
|
||||
&brake,
|
||||
&AtlasImpactIngressPolicy {
|
||||
cooldown_after_completion_ms: 100,
|
||||
},
|
||||
1_800_000_000_000,
|
||||
)?;
|
||||
assert_eq!(first.proposals.len(), 1);
|
||||
assert!(matches!(
|
||||
first.scheduling_decisions[0].disposition,
|
||||
AtlasImpactScheduleDisposition::HeldByBrake { .. }
|
||||
));
|
||||
|
||||
let seen = BTreeSet::from([first.proposals[0].dedupe_key.clone()]);
|
||||
let repeated = evaluate_local_atlas_impacts(
|
||||
&repository("consumer"),
|
||||
&projection,
|
||||
&[local_claim()],
|
||||
&seen,
|
||||
&lanes(),
|
||||
&brake,
|
||||
&AtlasImpactIngressPolicy {
|
||||
cooldown_after_completion_ms: 100,
|
||||
},
|
||||
1_800_000_000_000,
|
||||
)?;
|
||||
assert!(repeated.proposals.is_empty());
|
||||
assert_eq!(
|
||||
repeated.scheduling_decisions[0].disposition,
|
||||
AtlasImpactScheduleDisposition::Deduplicated
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verification_pressure_obeys_pending_lane_then_completion_cooldown() -> Result<()> {
|
||||
let projection = projection(entanglement(
|
||||
AtlasCompatibility::Exact,
|
||||
AtlasVerificationState::Missing,
|
||||
));
|
||||
let mut lane_state = lanes();
|
||||
lane_state[1].pending_proposal_id = Some(Uuid::from_u128(99));
|
||||
let pending = evaluate_local_atlas_impacts(
|
||||
&repository("consumer"),
|
||||
&projection,
|
||||
&[local_claim()],
|
||||
&BTreeSet::new(),
|
||||
&lane_state,
|
||||
&no_brake(),
|
||||
&AtlasImpactIngressPolicy {
|
||||
cooldown_after_completion_ms: 100,
|
||||
},
|
||||
1_000,
|
||||
)?;
|
||||
assert!(matches!(
|
||||
pending.scheduling_decisions[0].disposition,
|
||||
AtlasImpactScheduleDisposition::HeldByPendingLane {
|
||||
lane: AtlasImpactLane::Soul,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
lane_state[1].pending_proposal_id = None;
|
||||
lane_state[1].last_completed_at_unix_ms = Some(950);
|
||||
let cooling = evaluate_local_atlas_impacts(
|
||||
&repository("consumer"),
|
||||
&projection,
|
||||
&[local_claim()],
|
||||
&BTreeSet::new(),
|
||||
&lane_state,
|
||||
&no_brake(),
|
||||
&AtlasImpactIngressPolicy {
|
||||
cooldown_after_completion_ms: 100,
|
||||
},
|
||||
1_000,
|
||||
)?;
|
||||
assert_eq!(
|
||||
cooling.scheduling_decisions[0].disposition,
|
||||
AtlasImpactScheduleDisposition::HeldByCooldown {
|
||||
lane: AtlasImpactLane::Soul,
|
||||
retry_at_unix_ms: 1_050,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
32
epiphany-core/src/atlas/mod.rs
Normal file
32
epiphany-core/src/atlas/mod.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
//! Atlas is a read-only federated Modeling projection.
|
||||
//!
|
||||
//! Repository identities sign only documents owned by their local repository.
|
||||
//! Providers advertise surfaces, consumers declare reliance and impact, and
|
||||
//! consumer Soul publishes exact-edge verification. Atlas validates those
|
||||
//! publications and derives joins, cycles, and blast radius. It owns no edge,
|
||||
//! grants no capability, and writes no foreign Mind state.
|
||||
|
||||
mod contracts;
|
||||
mod eve_surface;
|
||||
mod identity;
|
||||
mod impact_ingress;
|
||||
mod planners;
|
||||
mod projector;
|
||||
mod publisher;
|
||||
mod runtime;
|
||||
mod store;
|
||||
mod transport;
|
||||
|
||||
pub use contracts::*;
|
||||
pub use eve_surface::*;
|
||||
pub use identity::*;
|
||||
pub use impact_ingress::*;
|
||||
pub use planners::*;
|
||||
pub use projector::*;
|
||||
pub use publisher::*;
|
||||
pub use runtime::*;
|
||||
pub use store::*;
|
||||
pub use transport::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
1573
epiphany-core/src/atlas/planners.rs
Normal file
1573
epiphany-core/src/atlas/planners.rs
Normal file
File diff suppressed because it is too large
Load diff
1305
epiphany-core/src/atlas/projector.rs
Normal file
1305
epiphany-core/src/atlas/projector.rs
Normal file
File diff suppressed because it is too large
Load diff
491
epiphany-core/src/atlas/publisher.rs
Normal file
491
epiphany-core/src/atlas/publisher.rs
Normal file
|
|
@ -0,0 +1,491 @@
|
|||
use anyhow::{Result, bail};
|
||||
use cultnet_rs::ServiceIdentitySigner;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::contracts::*;
|
||||
use super::identity::{
|
||||
AtlasRepositorySigningIdentity, atlas_source_payload_msgpack, canonical_atlas_payload_msgpack,
|
||||
sha256, sign_atlas_publication,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasLocalMindDocument {
|
||||
pub payload: AtlasPublicationPayload,
|
||||
pub source: AtlasMindSourceVersion,
|
||||
pub mind_commit: AtlasMindCommitBinding,
|
||||
}
|
||||
|
||||
impl AtlasLocalMindDocument {
|
||||
fn validate(&self, publisher: &AtlasRepositoryIdentity) -> Result<String> {
|
||||
self.payload.validate()?;
|
||||
self.source.validate()?;
|
||||
self.mind_commit.validate()?;
|
||||
if !self.payload.requires_mind_binding()
|
||||
|| self.payload.owner() != publisher
|
||||
|| self.source != self.mind_commit.source
|
||||
|| self.source.document_type != self.payload.schema()
|
||||
|| self.source.schema_id.as_deref() != Some(self.payload.schema())
|
||||
|| self.source.document_key != self.payload.key()
|
||||
{
|
||||
bail!("Atlas local publication input is not an exact owner/Mind source/commit binding")
|
||||
}
|
||||
let digest = sha256(&atlas_source_payload_msgpack(&self.payload)?);
|
||||
if self.source.payload_sha256 != digest {
|
||||
bail!("Atlas local Mind source digest does not match its CultCache payload")
|
||||
}
|
||||
Ok(digest)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasLatestPublicationPointer {
|
||||
pub publisher: AtlasRepositoryIdentity,
|
||||
pub source_schema: String,
|
||||
pub source_key: String,
|
||||
pub source_payload_sha256: String,
|
||||
pub publication_id: String,
|
||||
pub publication_sequence: u64,
|
||||
}
|
||||
|
||||
impl AtlasLatestPublicationPointer {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
self.publisher.validate()?;
|
||||
validate_identifier(&self.source_schema, "Atlas latest pointer source schema")?;
|
||||
validate_identifier(&self.source_key, "Atlas latest pointer source key")?;
|
||||
validate_sha256(
|
||||
&self.source_payload_sha256,
|
||||
"Atlas latest pointer source payload digest",
|
||||
)?;
|
||||
validate_sha256(&self.publication_id, "Atlas latest pointer publication id")?;
|
||||
if self.publication_sequence == 0 {
|
||||
bail!("Atlas latest pointer sequence must be positive")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AtlasLatestPublicationPointerIntent {
|
||||
pub intent_id: String,
|
||||
pub publisher: AtlasRepositoryIdentity,
|
||||
pub source_schema: String,
|
||||
pub source_key: String,
|
||||
pub expected_current_publication_id: Option<String>,
|
||||
pub next: AtlasLatestPublicationPointer,
|
||||
}
|
||||
|
||||
impl AtlasLatestPublicationPointerIntent {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
validate_sha256(&self.intent_id, "Atlas latest pointer intent id")?;
|
||||
self.publisher.validate()?;
|
||||
validate_identifier(
|
||||
&self.source_schema,
|
||||
"Atlas latest pointer intent source schema",
|
||||
)?;
|
||||
validate_identifier(&self.source_key, "Atlas latest pointer intent source key")?;
|
||||
if let Some(publication_id) = &self.expected_current_publication_id {
|
||||
validate_sha256(
|
||||
publication_id,
|
||||
"Atlas latest pointer expected publication id",
|
||||
)?;
|
||||
}
|
||||
self.next.validate()?;
|
||||
if self.publisher != self.next.publisher
|
||||
|| self.source_schema != self.next.source_schema
|
||||
|| self.source_key != self.next.source_key
|
||||
{
|
||||
bail!("Atlas latest pointer intent substituted its target identity")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasLocalPublicationSnapshot {
|
||||
pub publisher: AtlasRepositoryIdentity,
|
||||
pub current_mind_documents: Vec<AtlasLocalMindDocument>,
|
||||
pub latest_pointers: Vec<AtlasLatestPublicationPointer>,
|
||||
}
|
||||
|
||||
/// The publisher can see only the local repository snapshot passed through this
|
||||
/// port. There is deliberately no path, workspace id, or foreign-store method.
|
||||
pub trait AtlasLocalPublicationStore {
|
||||
fn load_local_atlas_snapshot(&self) -> Result<AtlasLocalPublicationSnapshot>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasPublisherContext {
|
||||
pub runtime_id: String,
|
||||
pub runtime_incarnation_id: String,
|
||||
pub body_basis: crate::RepositoryBodyObservationBasis,
|
||||
pub verse_id: String,
|
||||
pub heartbeat_sequence: u64,
|
||||
pub heartbeat_at_unix_ms: u64,
|
||||
pub publisher_state: AtlasPublisherState,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AtlasPublicationBatch {
|
||||
pub publications: Vec<AtlasPublicationEnvelope>,
|
||||
pub latest_pointer_intents: Vec<AtlasLatestPublicationPointerIntent>,
|
||||
}
|
||||
|
||||
pub fn publish_local_atlas_state(
|
||||
store: &impl AtlasLocalPublicationStore,
|
||||
signer: &ServiceIdentitySigner<AtlasRepositorySigningIdentity>,
|
||||
context: &AtlasPublisherContext,
|
||||
) -> Result<AtlasPublicationBatch> {
|
||||
let mut snapshot = store.load_local_atlas_snapshot()?;
|
||||
snapshot.publisher.validate()?;
|
||||
validate_context(&snapshot.publisher, context)?;
|
||||
|
||||
let mut latest = BTreeMap::<(String, String), AtlasLatestPublicationPointer>::new();
|
||||
let mut maximum_sequence = 0_u64;
|
||||
for pointer in snapshot.latest_pointers.drain(..) {
|
||||
pointer.validate()?;
|
||||
if pointer.publisher != snapshot.publisher {
|
||||
bail!("Atlas local store returned a foreign latest pointer")
|
||||
}
|
||||
maximum_sequence = maximum_sequence.max(pointer.publication_sequence);
|
||||
let key = (pointer.source_schema.clone(), pointer.source_key.clone());
|
||||
if latest.insert(key, pointer).is_some() {
|
||||
bail!("Atlas local store returned duplicate latest pointer identities")
|
||||
}
|
||||
}
|
||||
|
||||
let mut current = BTreeMap::<(String, String), (AtlasLocalMindDocument, String)>::new();
|
||||
for document in snapshot.current_mind_documents.drain(..) {
|
||||
let digest = document.validate(&snapshot.publisher)?;
|
||||
let key = (document.payload.schema().into(), document.payload.key());
|
||||
if current.insert(key, (document, digest)).is_some() {
|
||||
bail!("Atlas local Mind snapshot returned duplicate semantic documents")
|
||||
}
|
||||
}
|
||||
|
||||
let mut publications = Vec::new();
|
||||
let mut latest_pointer_intents = Vec::new();
|
||||
let mut watermarks = Vec::with_capacity(current.len());
|
||||
for ((source_schema, source_key), (document, payload_sha256)) in current {
|
||||
let previous = latest.get(&(source_schema.clone(), source_key.clone()));
|
||||
let pointer =
|
||||
if previous.is_some_and(|pointer| pointer.source_payload_sha256 == payload_sha256) {
|
||||
previous.cloned().expect("checked above")
|
||||
} else {
|
||||
maximum_sequence = maximum_sequence
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow::anyhow!("Atlas publication sequence exhausted"))?;
|
||||
let publication = sign_atlas_publication(
|
||||
signer,
|
||||
snapshot.publisher.clone(),
|
||||
maximum_sequence,
|
||||
context.runtime_id.clone(),
|
||||
context.runtime_incarnation_id.clone(),
|
||||
context.body_basis.clone(),
|
||||
context.verse_id.clone(),
|
||||
Some(document.source),
|
||||
Some(document.mind_commit),
|
||||
context.heartbeat_at_unix_ms,
|
||||
document.payload,
|
||||
)?;
|
||||
let pointer = AtlasLatestPublicationPointer {
|
||||
publisher: snapshot.publisher.clone(),
|
||||
source_schema: source_schema.clone(),
|
||||
source_key: source_key.clone(),
|
||||
source_payload_sha256: payload_sha256.clone(),
|
||||
publication_id: publication.statement.publication_id.clone(),
|
||||
publication_sequence: maximum_sequence,
|
||||
};
|
||||
latest_pointer_intents.push(pointer_intent(previous, pointer.clone())?);
|
||||
publications.push(publication);
|
||||
pointer
|
||||
};
|
||||
watermarks.push(AtlasPublicationWatermark {
|
||||
source_schema,
|
||||
source_key,
|
||||
source_payload_sha256: payload_sha256,
|
||||
publication_sequence: pointer.publication_sequence,
|
||||
});
|
||||
}
|
||||
|
||||
let status = AtlasPublisherStatus {
|
||||
publisher: snapshot.publisher.clone(),
|
||||
runtime_id: context.runtime_id.clone(),
|
||||
runtime_incarnation_id: context.runtime_incarnation_id.clone(),
|
||||
heartbeat_sequence: context.heartbeat_sequence,
|
||||
heartbeat_at_unix_ms: context.heartbeat_at_unix_ms,
|
||||
state: context.publisher_state,
|
||||
watermarks,
|
||||
};
|
||||
status.validate()?;
|
||||
let status_payload = AtlasPublicationPayload::PublisherStatus(status);
|
||||
let status_schema = status_payload.schema().to_string();
|
||||
let status_key = status_payload.key();
|
||||
let status_sha256 = sha256(&canonical_atlas_payload_msgpack(&status_payload)?);
|
||||
let previous_status = latest.get(&(status_schema.clone(), status_key.clone()));
|
||||
if !previous_status.is_some_and(|pointer| pointer.source_payload_sha256 == status_sha256) {
|
||||
maximum_sequence = maximum_sequence
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow::anyhow!("Atlas publication sequence exhausted"))?;
|
||||
let publication = sign_atlas_publication(
|
||||
signer,
|
||||
snapshot.publisher.clone(),
|
||||
maximum_sequence,
|
||||
context.runtime_id.clone(),
|
||||
context.runtime_incarnation_id.clone(),
|
||||
context.body_basis.clone(),
|
||||
context.verse_id.clone(),
|
||||
None,
|
||||
None,
|
||||
context.heartbeat_at_unix_ms,
|
||||
status_payload,
|
||||
)?;
|
||||
let pointer = AtlasLatestPublicationPointer {
|
||||
publisher: snapshot.publisher,
|
||||
source_schema: status_schema,
|
||||
source_key: status_key,
|
||||
source_payload_sha256: status_sha256,
|
||||
publication_id: publication.statement.publication_id.clone(),
|
||||
publication_sequence: maximum_sequence,
|
||||
};
|
||||
latest_pointer_intents.push(pointer_intent(previous_status, pointer)?);
|
||||
publications.push(publication);
|
||||
}
|
||||
|
||||
Ok(AtlasPublicationBatch {
|
||||
publications,
|
||||
latest_pointer_intents,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_context(
|
||||
publisher: &AtlasRepositoryIdentity,
|
||||
context: &AtlasPublisherContext,
|
||||
) -> Result<()> {
|
||||
validate_identifier(&context.runtime_id, "Atlas publisher runtime id")?;
|
||||
validate_identifier(
|
||||
&context.runtime_incarnation_id,
|
||||
"Atlas publisher runtime incarnation id",
|
||||
)?;
|
||||
validate_identifier(&context.verse_id, "Atlas publisher Verse id")?;
|
||||
if context.heartbeat_sequence == 0
|
||||
|| context.heartbeat_at_unix_ms == 0
|
||||
|| context.body_basis.swarm_id != publisher.swarm_id
|
||||
|| context.body_basis.workspace_id != publisher.workspace_id
|
||||
|| context.body_basis.runtime_id != context.runtime_id
|
||||
|| context.body_basis.generation == 0
|
||||
{
|
||||
bail!("Atlas publisher context is not bound to the local repository Body")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pointer_intent(
|
||||
previous: Option<&AtlasLatestPublicationPointer>,
|
||||
next: AtlasLatestPublicationPointer,
|
||||
) -> Result<AtlasLatestPublicationPointerIntent> {
|
||||
next.validate()?;
|
||||
let expected_current_publication_id = previous.map(|pointer| pointer.publication_id.clone());
|
||||
let intent_id = sha256(&rmp_serde::to_vec_named(&(
|
||||
"gamecult.model.atlas-latest-pointer-intent.v0",
|
||||
&next.publisher,
|
||||
&next.source_schema,
|
||||
&next.source_key,
|
||||
&expected_current_publication_id,
|
||||
&next.publication_id,
|
||||
next.publication_sequence,
|
||||
))?);
|
||||
let intent = AtlasLatestPublicationPointerIntent {
|
||||
intent_id,
|
||||
publisher: next.publisher.clone(),
|
||||
source_schema: next.source_schema.clone(),
|
||||
source_key: next.source_key.clone(),
|
||||
expected_current_publication_id,
|
||||
next,
|
||||
};
|
||||
intent.validate()?;
|
||||
Ok(intent)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use cultnet_rs::enroll_service_identity_at;
|
||||
use semver::Version;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MemoryStore(AtlasLocalPublicationSnapshot);
|
||||
|
||||
impl AtlasLocalPublicationStore for MemoryStore {
|
||||
fn load_local_atlas_snapshot(&self) -> Result<AtlasLocalPublicationSnapshot> {
|
||||
Ok(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn digest(seed: &str) -> String {
|
||||
sha256(seed.as_bytes())
|
||||
}
|
||||
|
||||
fn body_digest(seed: &str) -> String {
|
||||
digest(seed).trim_start_matches("sha256-").to_owned()
|
||||
}
|
||||
|
||||
fn repository() -> AtlasRepositoryIdentity {
|
||||
AtlasRepositoryIdentity::new("swarm", "workspace").unwrap()
|
||||
}
|
||||
|
||||
fn body() -> crate::RepositoryBodyObservationBasis {
|
||||
crate::RepositoryBodyObservationBasis {
|
||||
schema_version: "gamecult.epiphany.repository_body_observation_basis.v0".into(),
|
||||
workspace_id: "workspace".into(),
|
||||
swarm_id: "swarm".into(),
|
||||
runtime_id: "runtime".into(),
|
||||
scope: "whole_repository".into(),
|
||||
body_binding_sha256: body_digest("body-binding"),
|
||||
observation_id: "body-observation".into(),
|
||||
generation: 1,
|
||||
manifest_root_sha256: body_digest("manifest"),
|
||||
scan_started_at: "2026-08-14T00:00:00Z".into(),
|
||||
scan_finished_at: "2026-08-14T00:00:01Z".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn context() -> AtlasPublisherContext {
|
||||
AtlasPublisherContext {
|
||||
runtime_id: "runtime".into(),
|
||||
runtime_incarnation_id: "incarnation".into(),
|
||||
body_basis: body(),
|
||||
verse_id: "cultmesh://gamecult-local/swarm/atlas".into(),
|
||||
heartbeat_sequence: 1,
|
||||
heartbeat_at_unix_ms: 1_800_000_000_000,
|
||||
publisher_state: AtlasPublisherState::Serving,
|
||||
}
|
||||
}
|
||||
|
||||
fn local_offer(owner: AtlasRepositoryIdentity) -> AtlasLocalMindDocument {
|
||||
let payload = AtlasPublicationPayload::SurfaceOffer(AtlasSurfaceOffer {
|
||||
schema_version: ATLAS_SURFACE_OFFER_SCHEMA.into(),
|
||||
provider: owner,
|
||||
surface_id: Uuid::from_u128(1),
|
||||
contract: AtlasContractDescriptor::Semver {
|
||||
contract_id: "contract.surface".into(),
|
||||
version: Version::new(1, 0, 0),
|
||||
},
|
||||
lifecycle: AtlasOfferLifecycle::Active,
|
||||
});
|
||||
let payload_sha256 = sha256(&atlas_source_payload_msgpack(&payload).unwrap());
|
||||
let source = AtlasMindSourceVersion {
|
||||
store_id: "epiphany-mind".into(),
|
||||
document_type: payload.schema().into(),
|
||||
document_key: payload.key(),
|
||||
schema_id: Some(payload.schema().into()),
|
||||
payload_sha256,
|
||||
};
|
||||
AtlasLocalMindDocument {
|
||||
payload,
|
||||
mind_commit: AtlasMindCommitBinding {
|
||||
receipt_id: "mind-receipt".into(),
|
||||
receipt_sha256: digest("mind-receipt"),
|
||||
invariant_owner: "Mind".into(),
|
||||
source: source.clone(),
|
||||
},
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishes_only_local_mind_documents_and_status_with_pointer_intents() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let signer = enroll_service_identity_at::<AtlasRepositorySigningIdentity>(
|
||||
&temp.path().join("atlas-identity.cc"),
|
||||
)?;
|
||||
let owner = repository();
|
||||
let batch = publish_local_atlas_state(
|
||||
&MemoryStore(AtlasLocalPublicationSnapshot {
|
||||
publisher: owner.clone(),
|
||||
current_mind_documents: vec![local_offer(owner.clone())],
|
||||
latest_pointers: Vec::new(),
|
||||
}),
|
||||
&signer,
|
||||
&context(),
|
||||
)?;
|
||||
|
||||
assert_eq!(batch.publications.len(), 2);
|
||||
assert_eq!(batch.latest_pointer_intents.len(), 2);
|
||||
assert!(batch.publications.iter().all(|publication| {
|
||||
publication.statement.publisher == owner && publication.signature.len() == 64
|
||||
}));
|
||||
assert!(matches!(
|
||||
batch.publications[0].statement.payload,
|
||||
AtlasPublicationPayload::SurfaceOffer(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
batch.publications[1].statement.payload,
|
||||
AtlasPublicationPayload::PublisherStatus(_)
|
||||
));
|
||||
assert!(batch.latest_pointer_intents.iter().all(|intent| {
|
||||
intent.expected_current_publication_id.is_none() && intent.validate().is_ok()
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_local_snapshot_is_idempotent_at_the_same_heartbeat() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let signer = enroll_service_identity_at::<AtlasRepositorySigningIdentity>(
|
||||
&temp.path().join("atlas-identity.cc"),
|
||||
)?;
|
||||
let owner = repository();
|
||||
let first = publish_local_atlas_state(
|
||||
&MemoryStore(AtlasLocalPublicationSnapshot {
|
||||
publisher: owner.clone(),
|
||||
current_mind_documents: vec![local_offer(owner.clone())],
|
||||
latest_pointers: Vec::new(),
|
||||
}),
|
||||
&signer,
|
||||
&context(),
|
||||
)?;
|
||||
let latest_pointers = first
|
||||
.latest_pointer_intents
|
||||
.iter()
|
||||
.map(|intent| intent.next.clone())
|
||||
.collect();
|
||||
let repeated = publish_local_atlas_state(
|
||||
&MemoryStore(AtlasLocalPublicationSnapshot {
|
||||
publisher: owner.clone(),
|
||||
current_mind_documents: vec![local_offer(owner)],
|
||||
latest_pointers,
|
||||
}),
|
||||
&signer,
|
||||
&context(),
|
||||
)?;
|
||||
|
||||
assert!(repeated.publications.is_empty());
|
||||
assert!(repeated.latest_pointer_intents.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_mind_document_is_refused_without_store_access() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let signer = enroll_service_identity_at::<AtlasRepositorySigningIdentity>(
|
||||
&temp.path().join("atlas-identity.cc"),
|
||||
)?;
|
||||
let owner = repository();
|
||||
let foreign = AtlasRepositoryIdentity::new("swarm", "foreign")?;
|
||||
let result = publish_local_atlas_state(
|
||||
&MemoryStore(AtlasLocalPublicationSnapshot {
|
||||
publisher: owner,
|
||||
current_mind_documents: vec![local_offer(foreign)],
|
||||
latest_pointers: Vec::new(),
|
||||
}),
|
||||
&signer,
|
||||
&context(),
|
||||
);
|
||||
assert!(result.is_err());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
1341
epiphany-core/src/atlas/runtime.rs
Normal file
1341
epiphany-core/src/atlas/runtime.rs
Normal file
File diff suppressed because it is too large
Load diff
1217
epiphany-core/src/atlas/store.rs
Normal file
1217
epiphany-core/src/atlas/store.rs
Normal file
File diff suppressed because it is too large
Load diff
1183
epiphany-core/src/atlas/tests.rs
Normal file
1183
epiphany-core/src/atlas/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
289
epiphany-core/src/atlas/transport.rs
Normal file
289
epiphany-core/src/atlas/transport.rs
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use cultmesh_rs::{
|
||||
CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID, CultMesh, CultMeshNodeOptions,
|
||||
CultMeshRudpDocumentPublishOptions,
|
||||
};
|
||||
use cultnet_rs::{
|
||||
CultNetMessage, CultNetRawPayloadEncoding, CultNetRudpSocketTransportConnection,
|
||||
CultNetRudpSocketTransportOptions, CultNetWireContract, decode_cultnet_message_from_slice,
|
||||
encode_cultnet_message_to_vec,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
ATLAS_MAX_PUBLICATION_BYTES, ATLAS_PROJECTION_SCHEMA, ATLAS_PUBLICATION_SCHEMA,
|
||||
AtlasEntanglementProjection, AtlasEveDocuments, AtlasPublicationEnvelope,
|
||||
EVE_PROVIDER_ADVERTISEMENT_SCHEMA, EVE_SURFACE_SCHEMA, EveProviderAdvertisement,
|
||||
EveSurfaceDocument, MODEL_ATLAS_PROVIDER_ID, MODEL_ATLAS_SURFACE_ID,
|
||||
};
|
||||
|
||||
cultmesh_rs::cultmesh_documents!(AtlasFederationDocuments {
|
||||
AtlasPublicationEnvelope => ATLAS_PUBLICATION_SCHEMA,
|
||||
AtlasEntanglementProjection => ATLAS_PROJECTION_SCHEMA,
|
||||
EveProviderAdvertisement => EVE_PROVIDER_ADVERTISEMENT_SCHEMA,
|
||||
EveSurfaceDocument => EVE_SURFACE_SCHEMA,
|
||||
});
|
||||
|
||||
pub const ATLAS_RUDP_TRANSPORT_TAG: &str = "gamecult.model.atlas-rudp.v0";
|
||||
|
||||
pub fn persist_atlas_publications(
|
||||
local_store: &Path,
|
||||
runtime_id: &str,
|
||||
publications: &[AtlasPublicationEnvelope],
|
||||
) -> Result<()> {
|
||||
require_id(runtime_id, "Atlas publication runtime")?;
|
||||
let mut node = CultMesh::create_node(
|
||||
local_store,
|
||||
AtlasFederationDocuments,
|
||||
CultMeshNodeOptions {
|
||||
runtime_id: runtime_id.into(),
|
||||
pull_on_start: true,
|
||||
},
|
||||
)?;
|
||||
for publication in publications {
|
||||
if rmp_serde::to_vec(publication)?.len() > ATLAS_MAX_PUBLICATION_BYTES {
|
||||
bail!("Atlas publication exceeds the transport size limit")
|
||||
}
|
||||
node.put(publication.statement.publication_id.clone(), publication)?;
|
||||
}
|
||||
node.flush()
|
||||
}
|
||||
|
||||
pub fn publish_atlas_publications_rudp(
|
||||
local_store: &Path,
|
||||
endpoint: SocketAddr,
|
||||
runtime_id: &str,
|
||||
source_agent_id: &str,
|
||||
publications: &[AtlasPublicationEnvelope],
|
||||
) -> Result<()> {
|
||||
require_id(runtime_id, "Atlas publication runtime")?;
|
||||
require_id(source_agent_id, "Atlas publication agent")?;
|
||||
let node = CultMesh::create_node(
|
||||
local_store,
|
||||
AtlasFederationDocuments,
|
||||
CultMeshNodeOptions {
|
||||
runtime_id: runtime_id.into(),
|
||||
pull_on_start: true,
|
||||
},
|
||||
)?;
|
||||
for publication in publications {
|
||||
node.publish_document_to_rudp_catalog(
|
||||
publication.statement.publication_id.clone(),
|
||||
publication,
|
||||
CultMeshRudpDocumentPublishOptions {
|
||||
target: endpoint,
|
||||
runtime_id: runtime_id.into(),
|
||||
source_agent_id: Some(source_agent_id.into()),
|
||||
source_role: Some("epiphany-atlas-publisher".into()),
|
||||
tags: vec![ATLAS_RUDP_TRANSPORT_TAG.into()],
|
||||
..CultMeshRudpDocumentPublishOptions::default()
|
||||
},
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn persist_atlas_projection(
|
||||
projector_store: &Path,
|
||||
runtime_id: &str,
|
||||
projection: &AtlasEntanglementProjection,
|
||||
) -> Result<()> {
|
||||
require_id(runtime_id, "Atlas projector runtime")?;
|
||||
let mut node = CultMesh::create_node(
|
||||
projector_store,
|
||||
AtlasFederationDocuments,
|
||||
CultMeshNodeOptions {
|
||||
runtime_id: runtime_id.into(),
|
||||
pull_on_start: true,
|
||||
},
|
||||
)?;
|
||||
node.put(projection.audience_id.clone(), projection)?;
|
||||
node.flush()
|
||||
}
|
||||
|
||||
pub fn persist_atlas_projection_and_eve(
|
||||
projector_store: &Path,
|
||||
runtime_id: &str,
|
||||
projection: &AtlasEntanglementProjection,
|
||||
eve: &AtlasEveDocuments,
|
||||
) -> Result<()> {
|
||||
require_id(runtime_id, "Atlas projector runtime")?;
|
||||
let mut node = CultMesh::create_node(
|
||||
projector_store,
|
||||
AtlasFederationDocuments,
|
||||
CultMeshNodeOptions {
|
||||
runtime_id: runtime_id.into(),
|
||||
pull_on_start: true,
|
||||
},
|
||||
)?;
|
||||
node.put(projection.audience_id.clone(), projection)?;
|
||||
node.put(MODEL_ATLAS_PROVIDER_ID, &eve.advertisement)?;
|
||||
node.put(MODEL_ATLAS_SURFACE_ID, &eve.surface)?;
|
||||
node.flush()
|
||||
}
|
||||
|
||||
pub fn publish_atlas_projection_and_eve_rudp(
|
||||
projector_store: &Path,
|
||||
endpoint: SocketAddr,
|
||||
runtime_id: &str,
|
||||
source_agent_id: &str,
|
||||
projection: &AtlasEntanglementProjection,
|
||||
eve: &AtlasEveDocuments,
|
||||
) -> Result<()> {
|
||||
require_id(runtime_id, "Atlas projector runtime")?;
|
||||
require_id(source_agent_id, "Atlas projector agent")?;
|
||||
let node = CultMesh::create_node(
|
||||
projector_store,
|
||||
AtlasFederationDocuments,
|
||||
CultMeshNodeOptions {
|
||||
runtime_id: runtime_id.into(),
|
||||
pull_on_start: true,
|
||||
},
|
||||
)?;
|
||||
let options = |role: &str| CultMeshRudpDocumentPublishOptions {
|
||||
target: endpoint,
|
||||
runtime_id: runtime_id.into(),
|
||||
source_agent_id: Some(source_agent_id.into()),
|
||||
source_role: Some(role.into()),
|
||||
tags: vec![ATLAS_RUDP_TRANSPORT_TAG.into()],
|
||||
..CultMeshRudpDocumentPublishOptions::default()
|
||||
};
|
||||
node.publish_document_to_rudp_catalog(
|
||||
projection.audience_id.clone(),
|
||||
projection,
|
||||
options("epiphany-model-entanglement-projector"),
|
||||
)?;
|
||||
node.publish_document_to_rudp_catalog(
|
||||
MODEL_ATLAS_PROVIDER_ID,
|
||||
&eve.advertisement,
|
||||
options("epiphany-model-atlas-eve-provider"),
|
||||
)?;
|
||||
node.publish_document_to_rudp_catalog(
|
||||
MODEL_ATLAS_SURFACE_ID,
|
||||
&eve.surface,
|
||||
options("epiphany-model-atlas-eve-surface"),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_atlas_projection(
|
||||
projector_store: &Path,
|
||||
audience_id: &str,
|
||||
) -> Result<Option<AtlasEntanglementProjection>> {
|
||||
let node = CultMesh::create_node(
|
||||
projector_store,
|
||||
AtlasFederationDocuments,
|
||||
CultMeshNodeOptions::default(),
|
||||
)?;
|
||||
node.get(audience_id)
|
||||
}
|
||||
|
||||
pub fn query_atlas_publications_rudp(
|
||||
endpoint: SocketAddr,
|
||||
runtime_id: &str,
|
||||
) -> Result<Vec<AtlasPublicationEnvelope>> {
|
||||
require_id(runtime_id, "Atlas projector query runtime")?;
|
||||
let message_id = format!("atlas-snapshot-{}", Uuid::new_v4());
|
||||
let response = exchange_catalog(
|
||||
endpoint,
|
||||
runtime_id,
|
||||
CultNetMessage::SnapshotRequest {
|
||||
message_id: message_id.clone(),
|
||||
schema_ids: Some(vec![ATLAS_PUBLICATION_SCHEMA.into()]),
|
||||
record_keys: None,
|
||||
},
|
||||
)?;
|
||||
let CultNetMessage::SnapshotResponseRaw {
|
||||
message_id: response_id,
|
||||
documents,
|
||||
} = response
|
||||
else {
|
||||
bail!("Odin Atlas query did not return a raw typed snapshot")
|
||||
};
|
||||
if response_id != message_id {
|
||||
bail!("Odin Atlas snapshot response substituted its request identity")
|
||||
}
|
||||
let mut publications = Vec::with_capacity(documents.len());
|
||||
for document in documents {
|
||||
if document.schema_id != ATLAS_PUBLICATION_SCHEMA
|
||||
|| document.payload_encoding != CultNetRawPayloadEncoding::Messagepack
|
||||
|| document.payload.len() > ATLAS_MAX_PUBLICATION_BYTES
|
||||
{
|
||||
bail!("Odin Atlas snapshot contained an unknown, non-MessagePack, or oversized record")
|
||||
}
|
||||
let publication: AtlasPublicationEnvelope = rmp_serde::from_slice(&document.payload)
|
||||
.context("Odin Atlas publication payload is malformed")?;
|
||||
if rmp_serde::to_vec(&publication)? != document.payload
|
||||
|| publication.statement.publication_id != document.record_key
|
||||
{
|
||||
bail!("Odin Atlas publication payload is noncanonical or key-substituted")
|
||||
}
|
||||
publications.push(publication);
|
||||
}
|
||||
publications.sort_by(|left, right| {
|
||||
left.statement
|
||||
.publication_id
|
||||
.cmp(&right.statement.publication_id)
|
||||
});
|
||||
Ok(publications)
|
||||
}
|
||||
|
||||
fn exchange_catalog(
|
||||
endpoint: SocketAddr,
|
||||
runtime_id: &str,
|
||||
request: CultNetMessage,
|
||||
) -> Result<CultNetMessage> {
|
||||
let bind = if endpoint.is_ipv4() {
|
||||
"0.0.0.0:0"
|
||||
} else {
|
||||
"[::]:0"
|
||||
};
|
||||
let socket = UdpSocket::bind(bind)?;
|
||||
socket.set_read_timeout(Some(Duration::from_millis(50)))?;
|
||||
let mut transport =
|
||||
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::client(
|
||||
runtime_id,
|
||||
socket,
|
||||
endpoint,
|
||||
CULTMESH_RUDP_DOCUMENT_CATALOG_CONNECTION_ID,
|
||||
))?;
|
||||
transport.connect(Vec::new())?;
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while !transport.connected() {
|
||||
let _ = transport.receive_once()?;
|
||||
transport.poll_resends()?;
|
||||
if Instant::now() >= deadline {
|
||||
bail!("Odin Atlas catalog handshake timed out")
|
||||
}
|
||||
}
|
||||
transport.send(
|
||||
"schema",
|
||||
encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?,
|
||||
)?;
|
||||
loop {
|
||||
if let Some(frame) = transport.receive_once()? {
|
||||
if frame.channel_id != "schema" {
|
||||
bail!("Odin Atlas catalog replied on an unknown channel")
|
||||
}
|
||||
return decode_cultnet_message_from_slice(
|
||||
&frame.payload,
|
||||
CultNetWireContract::CultNetSchemaV0,
|
||||
);
|
||||
}
|
||||
transport.poll_resends()?;
|
||||
if Instant::now() >= deadline {
|
||||
bail!("Odin Atlas catalog snapshot timed out")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn require_id(value: &str, label: &str) -> Result<()> {
|
||||
if value.trim().is_empty() {
|
||||
bail!("{label} is empty")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
100
epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs
Normal file
100
epiphany-core/src/bin/epiphany-atlas-impact-ingress.rs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use epiphany_core::{
|
||||
AtlasImpactIngressRunConfig, AtlasImpactIngressRunOutcome, AtlasRepositoryIdentity,
|
||||
run_atlas_impact_ingress_once,
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let (args, switches) = arguments()?;
|
||||
let once = switches.contains("--once");
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
let stop = running.clone();
|
||||
ctrlc::set_handler(move || stop.store(false, Ordering::SeqCst))?;
|
||||
while running.load(Ordering::SeqCst) {
|
||||
let config = AtlasImpactIngressRunConfig {
|
||||
local_repository: AtlasRepositoryIdentity::new(
|
||||
required(&args, "--swarm-id")?,
|
||||
required(&args, "--workspace-id")?,
|
||||
)?,
|
||||
projector_repository: AtlasRepositoryIdentity::new(
|
||||
required(&args, "--projector-swarm-id")?,
|
||||
required(&args, "--projector-workspace-id")?,
|
||||
)?,
|
||||
runtime_id: required(&args, "--runtime-id")?.into(),
|
||||
runtime_mind_store: path(&args, "--mind-store")?,
|
||||
local_verse_store: path(&args, "--verse-store")?,
|
||||
projector_store: path(&args, "--projector-store")?,
|
||||
impact_store: path(&args, "--impact-store")?,
|
||||
resident_self_store: path(&args, "--resident-self-store")?,
|
||||
cooldown_after_completion_ms: args
|
||||
.get("--cooldown-ms")
|
||||
.map(|value| value.parse())
|
||||
.transpose()?
|
||||
.unwrap_or(30_000),
|
||||
now_unix_ms: now_unix_ms()?,
|
||||
};
|
||||
match run_atlas_impact_ingress_once(&config)? {
|
||||
AtlasImpactIngressRunOutcome::HeldByBrake {
|
||||
brake_id,
|
||||
last_projection,
|
||||
} => println!(
|
||||
"atlas impact ingress held by brake {brake_id}; last projection remains read-only: {}",
|
||||
last_projection.is_some()
|
||||
),
|
||||
AtlasImpactIngressRunOutcome::Evaluated {
|
||||
admitted_impacts,
|
||||
scheduled_pressures,
|
||||
held_impacts,
|
||||
} => println!(
|
||||
"atlas impact ingress admitted {admitted_impacts}, scheduled {scheduled_pressures}, held {held_impacts}"
|
||||
),
|
||||
}
|
||||
if once {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn arguments() -> Result<(BTreeMap<String, String>, BTreeSet<String>)> {
|
||||
let mut values = BTreeMap::new();
|
||||
let mut switches = BTreeSet::new();
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(name) = args.next() {
|
||||
if name == "--once" {
|
||||
switches.insert(name);
|
||||
continue;
|
||||
}
|
||||
if !name.starts_with("--") {
|
||||
bail!("unexpected Atlas impact argument {name}")
|
||||
}
|
||||
values.insert(
|
||||
name.clone(),
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("{name} requires a value"))?,
|
||||
);
|
||||
}
|
||||
Ok((values, switches))
|
||||
}
|
||||
|
||||
fn required<'a>(args: &'a BTreeMap<String, String>, name: &str) -> Result<&'a str> {
|
||||
args.get(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required {name}"))
|
||||
}
|
||||
fn path(args: &BTreeMap<String, String>, name: &str) -> Result<PathBuf> {
|
||||
Ok(PathBuf::from(required(args, name)?))
|
||||
}
|
||||
fn now_unix_ms() -> Result<u64> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)?
|
||||
.as_millis()
|
||||
.try_into()?)
|
||||
}
|
||||
90
epiphany-core/src/bin/epiphany-atlas-publisher.rs
Normal file
90
epiphany-core/src/bin/epiphany-atlas-publisher.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use epiphany_core::{
|
||||
ATLAS_PUBLISHER_HEARTBEAT_INTERVAL_MS, AtlasPublisherRunConfig, AtlasPublisherRunOutcome,
|
||||
AtlasRepositoryIdentity, run_atlas_publisher_once,
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let (args, switches) = arguments()?;
|
||||
let once = switches.contains("--once");
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
let stop = running.clone();
|
||||
ctrlc::set_handler(move || stop.store(false, Ordering::SeqCst))?;
|
||||
while running.load(Ordering::SeqCst) {
|
||||
let config = AtlasPublisherRunConfig {
|
||||
repository: AtlasRepositoryIdentity::new(
|
||||
required(&args, "--swarm-id")?,
|
||||
required(&args, "--workspace-id")?,
|
||||
)?,
|
||||
runtime_id: required(&args, "--runtime-id")?.into(),
|
||||
runtime_incarnation_id: required(&args, "--runtime-incarnation-id")?.into(),
|
||||
runtime_mind_store: path(&args, "--mind-store")?,
|
||||
local_verse_store: path(&args, "--verse-store")?,
|
||||
publisher_store: path(&args, "--publisher-store")?,
|
||||
publisher_cultmesh_store: path(&args, "--cultmesh-store")?,
|
||||
identity_store: path(&args, "--identity-store")?,
|
||||
odin_endpoint: required(&args, "--odin-endpoint")?.parse()?,
|
||||
now_unix_ms: now_unix_ms()?,
|
||||
};
|
||||
match run_atlas_publisher_once(&config)? {
|
||||
AtlasPublisherRunOutcome::HeldByBrake { brake_id } => {
|
||||
println!("atlas publisher held by brake {brake_id}")
|
||||
}
|
||||
AtlasPublisherRunOutcome::Published {
|
||||
new_publications,
|
||||
transported_publications,
|
||||
} => println!(
|
||||
"atlas publisher committed {new_publications} new records and transported {transported_publications} immutable records"
|
||||
),
|
||||
}
|
||||
if once {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(ATLAS_PUBLISHER_HEARTBEAT_INTERVAL_MS));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn arguments() -> Result<(BTreeMap<String, String>, BTreeSet<String>)> {
|
||||
let mut values = BTreeMap::new();
|
||||
let mut switches = BTreeSet::new();
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(name) = args.next() {
|
||||
if name == "--once" {
|
||||
switches.insert(name);
|
||||
continue;
|
||||
}
|
||||
if !name.starts_with("--") {
|
||||
bail!("unexpected Atlas publisher argument {name}")
|
||||
}
|
||||
values.insert(
|
||||
name.clone(),
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("{name} requires a value"))?,
|
||||
);
|
||||
}
|
||||
Ok((values, switches))
|
||||
}
|
||||
|
||||
fn required<'a>(args: &'a BTreeMap<String, String>, name: &str) -> Result<&'a str> {
|
||||
args.get(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required {name}"))
|
||||
}
|
||||
|
||||
fn path(args: &BTreeMap<String, String>, name: &str) -> Result<PathBuf> {
|
||||
Ok(PathBuf::from(required(args, name)?))
|
||||
}
|
||||
|
||||
fn now_unix_ms() -> Result<u64> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)?
|
||||
.as_millis()
|
||||
.try_into()?)
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use epiphany_core::{
|
||||
RepoFrontierExecutionAmendment, RepoFrontierRoute, amend_repo_frontier_execution,
|
||||
runtime_repo_frontier_plan_decision, runtime_repo_model_admission_receipt,
|
||||
runtime_repo_model_admission_review, runtime_spine_cache,
|
||||
RepoFrontierExecutionAmendment, RepoFrontierPlanDecisionReceipt, RepoFrontierRoute,
|
||||
amend_repo_frontier_execution, assemble_repo_model_view, runtime_spine_cache,
|
||||
validate_frontier_plan_decision_chain,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::BTreeMap, env, path::PathBuf};
|
||||
|
|
@ -45,31 +45,30 @@ fn main() -> Result<()> {
|
|||
.ok_or_else(|| anyhow!("route {route_id} does not exist; available: {available}"))?;
|
||||
let plan = route
|
||||
.adopted_plan
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow!("route {route_id} has no adopted plan"))?;
|
||||
let admission = runtime_repo_model_admission_receipt(&store, &route.admission_receipt_id)?
|
||||
.ok_or_else(|| anyhow!("route {route_id} admission receipt is absent"))?;
|
||||
let review = runtime_repo_model_admission_review(&store, &admission.review_id)?
|
||||
.ok_or_else(|| anyhow!("route {route_id} admission review is absent"))?;
|
||||
let plan_decision = if admission.frontier_plan_decision_id.is_empty() {
|
||||
None
|
||||
} else {
|
||||
runtime_repo_frontier_plan_decision(&store, &admission.frontier_plan_decision_id)?
|
||||
};
|
||||
let current_model = assemble_repo_model_view(&store)?;
|
||||
let mut plan_decisions = cache
|
||||
.get_all::<RepoFrontierPlanDecisionReceipt>()?
|
||||
.into_iter()
|
||||
.filter(|decision| decision.planning_request_id == plan.planning_request_id)
|
||||
.collect::<Vec<_>>();
|
||||
if plan_decisions.len() != 1 {
|
||||
return Err(anyhow!(
|
||||
"route {route_id} requires exactly one typed plan decision; found {}",
|
||||
plan_decisions.len()
|
||||
));
|
||||
}
|
||||
let plan_decision = plan_decisions.pop().expect("one decision checked above");
|
||||
validate_frontier_plan_decision_chain(&plan_decision, &route, ¤t_model)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"routeId": route.route_id,
|
||||
"modelRevision": route.model_revision,
|
||||
"modelHash": route.model_hash,
|
||||
"admissionReceiptId": route.admission_receipt_id,
|
||||
"admissionResultId": admission.result_id,
|
||||
"admissionReviewId": admission.review_id,
|
||||
"admissionSource": review.admission_source,
|
||||
"admissionPreviousRevision": admission.previous_revision,
|
||||
"admissionPreviousHash": admission.previous_hash,
|
||||
"admissionAdmittedRevision": admission.admitted_revision,
|
||||
"admissionAdmittedHash": admission.admitted_hash,
|
||||
"frontierPlanDecisionId": admission.frontier_plan_decision_id,
|
||||
"modelProjectionDigest": route.model_projection_digest,
|
||||
"modelSourceDocuments": route.model_source_documents,
|
||||
"frontierPlanDecisionId": plan_decision.decision_id,
|
||||
"frontierPlanDecision": plan_decision,
|
||||
"frontierItemId": route.frontier_item_id,
|
||||
"frontierItemHash": route.frontier_item_hash,
|
||||
|
|
|
|||
|
|
@ -447,9 +447,10 @@ fn record_refusal(store: &PathBuf, args: RecordRefusalArgs) -> Result<serde_json
|
|||
"handsRefusalReceiptId": receipt.hands_refusal_receipt_id,
|
||||
"routeId": receipt.route_id,
|
||||
"frontierItemId": receipt.frontier_item_id,
|
||||
"admittedModelRevision": receipt.admitted_model_revision,
|
||||
"admittedModelHash": receipt.admitted_model_hash,
|
||||
"modelAdmissionReceiptId": receipt.model_admission_receipt_id,
|
||||
"previousModelProjectionDigest": receipt.previous_model_projection_digest,
|
||||
"previousModelSourceDocuments": receipt.previous_model_source_documents,
|
||||
"admittedModelProjectionDigest": receipt.admitted_model_projection_digest,
|
||||
"admittedModelSourceDocuments": receipt.admitted_model_source_documents,
|
||||
"store": store,
|
||||
}))
|
||||
}
|
||||
|
|
@ -641,7 +642,6 @@ mod tests {
|
|||
use epiphany_core::runtime_hands_commit_receipt;
|
||||
use epiphany_core::runtime_hands_patch_receipt;
|
||||
use epiphany_core::runtime_latest_hands_receipt_chain_after;
|
||||
use sha2::Digest;
|
||||
|
||||
#[test]
|
||||
fn records_patch_command_and_commit_receipts_against_approved_gate() -> Result<()> {
|
||||
|
|
@ -883,100 +883,6 @@ mod tests {
|
|||
"2026-06-02T00:00:02Z".to_string(),
|
||||
);
|
||||
put_hands_action_review(store, &review)?;
|
||||
seed_frontier_authority(store, &intent, &review)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn seed_frontier_authority(
|
||||
store: &PathBuf,
|
||||
intent: &HandsActionIntent,
|
||||
review: &HandsActionReview,
|
||||
) -> Result<()> {
|
||||
let item = epiphany_core::RepoFrontierItem {
|
||||
id: "hands-frontier-test".to_string(),
|
||||
migration_body: "Exercise the bounded Hands receipt chain.".to_string(),
|
||||
question: "Does the consequence preserve its authority chain?".to_string(),
|
||||
gap: "An unrouted consequence is invalid.".to_string(),
|
||||
target_claim_ids: vec!["hands-claim-test".to_string()],
|
||||
source_scope: intent.requested_paths.clone(),
|
||||
recommended_next_organ: "Hands".to_string(),
|
||||
evidence_refs: vec!["hands-fixture".to_string()],
|
||||
status: epiphany_core::RepoFrontierStatus::Active,
|
||||
..Default::default()
|
||||
};
|
||||
let item_hash = format!(
|
||||
"{:x}",
|
||||
sha2::Sha256::digest(rmp_serde::to_vec_named(&item)?)
|
||||
);
|
||||
let mut model = epiphany_core::EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(epiphany_core::MEMORY_GRAPH_SCHEMA_VERSION.to_string()),
|
||||
graph_id: "hands-action-test-model".to_string(),
|
||||
model_revision: 1,
|
||||
domains: vec![epiphany_core::EpiphanyMemoryDomain {
|
||||
id: "repo".to_string(),
|
||||
profile: epiphany_core::EpiphanyMemoryProfile::RepoArchitecture,
|
||||
title: "Repository".to_string(),
|
||||
lifecycle: epiphany_core::EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
nodes: vec![epiphany_core::EpiphanyMemoryNode {
|
||||
id: "hands-claim-test".to_string(),
|
||||
domain_id: "repo".to_string(),
|
||||
profile: epiphany_core::EpiphanyMemoryProfile::RepoArchitecture,
|
||||
kind: epiphany_core::EpiphanyMemoryNodeKind::RuntimeContract,
|
||||
title: "Hands authority".to_string(),
|
||||
claim: "Hands consequences require an exact frontier authority.".to_string(),
|
||||
question: "Is the authority chain exact?".to_string(),
|
||||
action_implication: "Bind every receipt to the routed scope.".to_string(),
|
||||
source_hashes: vec!["anchor:missing".to_string()],
|
||||
lifecycle: epiphany_core::EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
frontier: vec![item.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
model.model_hash = epiphany_core::memory_graph_model_hash(&model)?;
|
||||
let entry = epiphany_core::EpiphanyMemoryGraphEntry::from_snapshot(&model)?;
|
||||
let route = epiphany_core::RepoFrontierRoute {
|
||||
schema_version: epiphany_core::REPO_FRONTIER_ROUTE_SCHEMA_VERSION.to_string(),
|
||||
route_id: "hands-route-test".to_string(),
|
||||
next_organ: epiphany_core::RepoFrontierNextOrgan::Hands,
|
||||
model_revision: model.model_revision,
|
||||
model_hash: model.model_hash.clone(),
|
||||
admission_receipt_id: "hands-admission-test".to_string(),
|
||||
frontier_item_id: item.id.clone(),
|
||||
frontier_item_hash: item_hash.clone(),
|
||||
migration_body: item.migration_body.clone(),
|
||||
question: item.question.clone(),
|
||||
gap: item.gap.clone(),
|
||||
target_claim_ids: item.target_claim_ids.clone(),
|
||||
source_scope: item.source_scope.clone(),
|
||||
adopted_plan: None,
|
||||
selected_at: "2026-06-02T00:00:02Z".to_string(),
|
||||
contract: epiphany_core::REPO_FRONTIER_ROUTE_CONTRACT.to_string(),
|
||||
};
|
||||
let mut cache = epiphany_core::runtime_spine_cache(store)?;
|
||||
cache.put(epiphany_core::MEMORY_GRAPH_KEY, &entry)?;
|
||||
cache.put(&route.route_id, &route)?;
|
||||
epiphany_core::put_repo_frontier_hands_authority(
|
||||
store,
|
||||
&epiphany_core::RepoFrontierHandsAuthority {
|
||||
schema_version: epiphany_core::REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION
|
||||
.to_string(),
|
||||
authority_id: "hands-authority-test".to_string(),
|
||||
route_id: route.route_id,
|
||||
model_revision: route.model_revision,
|
||||
model_hash: route.model_hash,
|
||||
frontier_item_id: route.frontier_item_id,
|
||||
frontier_item_hash: item_hash,
|
||||
hands_intent_id: intent.intent_id.clone(),
|
||||
hands_review_id: review.review_id.clone(),
|
||||
substrate_grant_receipt_id: intent.substrate_gate_grant_receipt_id.clone(),
|
||||
requested_paths: intent.requested_paths.clone(),
|
||||
granted_at: "2026-06-02T00:00:03Z".to_string(),
|
||||
contract: epiphany_core::REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT.to_string(),
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,633 +0,0 @@
|
|||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use epiphany_core::EpiphanyMemoryAnchor;
|
||||
use epiphany_core::EpiphanyMemoryContextQuery;
|
||||
use epiphany_core::EpiphanyMemoryDomain;
|
||||
use epiphany_core::EpiphanyMemoryEdge;
|
||||
use epiphany_core::EpiphanyMemoryEdgeKind;
|
||||
use epiphany_core::EpiphanyMemoryFreshnessStatus;
|
||||
use epiphany_core::EpiphanyMemoryGraphSnapshot;
|
||||
use epiphany_core::EpiphanyMemoryLifecycle;
|
||||
use epiphany_core::EpiphanyMemoryNode;
|
||||
use epiphany_core::EpiphanyMemoryNodeKind;
|
||||
use epiphany_core::EpiphanyMemoryProfile;
|
||||
use epiphany_core::EpiphanyMemorySummary;
|
||||
use epiphany_core::agent_memory_role_ids;
|
||||
use epiphany_core::compose_memory_graph_snapshots;
|
||||
use epiphany_core::derive_memory_graph_freshness;
|
||||
use epiphany_core::load_agent_memory_entry_for_role;
|
||||
use epiphany_core::load_heartbeat_cognition_entry;
|
||||
use epiphany_core::load_memory_graph_snapshot;
|
||||
use epiphany_core::load_thread_state;
|
||||
use epiphany_core::memory_graph_domain_id;
|
||||
use epiphany_core::memory_graph_edge_id;
|
||||
use epiphany_core::memory_graph_from_agent_memories;
|
||||
use epiphany_core::memory_graph_from_epiphany_graphs;
|
||||
use epiphany_core::memory_graph_from_heartbeat_cognition;
|
||||
use epiphany_core::memory_graph_node_id;
|
||||
use epiphany_core::plan_memory_graph_context_cut;
|
||||
use epiphany_core::refresh_or_validate_repo_memory_graph;
|
||||
use epiphany_core::validate_memory_graph_snapshot;
|
||||
use epiphany_core::write_memory_graph_snapshot;
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args().skip(1);
|
||||
let Some(command) = args.next() else {
|
||||
print_usage();
|
||||
std::process::exit(2);
|
||||
};
|
||||
|
||||
match command.as_str() {
|
||||
"status" => {
|
||||
let store = require_path_arg(&mut args, "--store")?;
|
||||
let output = memory_graph_status(&store)?;
|
||||
print_json(&output)?;
|
||||
}
|
||||
"validate" => {
|
||||
let store = require_path_arg(&mut args, "--store")?;
|
||||
let snapshot = load_memory_graph_snapshot(&store)?
|
||||
.ok_or_else(|| anyhow!("memory graph store {} is missing", store.display()))?;
|
||||
let errors = validate_memory_graph_snapshot(&snapshot);
|
||||
print_json(&serde_json::json!({
|
||||
"ok": errors.is_empty(),
|
||||
"store": store,
|
||||
"graphId": snapshot.graph_id,
|
||||
"errors": errors.iter().map(|error| serde_json::json!({
|
||||
"path": error.path,
|
||||
"message": error.message,
|
||||
})).collect::<Vec<_>>(),
|
||||
}))?;
|
||||
if !errors.is_empty() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
"context" => {
|
||||
let store = require_path_arg(&mut args, "--store")?;
|
||||
let query = read_context_query(args)?;
|
||||
let snapshot = load_memory_graph_snapshot(&store)?
|
||||
.ok_or_else(|| anyhow!("memory graph store {} is missing", store.display()))?;
|
||||
let packet = plan_memory_graph_context_cut(&snapshot, &query);
|
||||
print_json(&packet)?;
|
||||
}
|
||||
"compose" => {
|
||||
let compose = read_compose_args(args)?;
|
||||
let output = compose_memory_graph_store(compose)?;
|
||||
print_json(&output)?;
|
||||
}
|
||||
"refresh" => {
|
||||
let refresh = read_refresh_args(args)?;
|
||||
let output = refresh_memory_graph_store(refresh)?;
|
||||
print_json(&output)?;
|
||||
}
|
||||
"smoke" => {
|
||||
let store = optional_path_arg(&mut args, "--store")?
|
||||
.unwrap_or_else(|| scoped_temp_store("epiphany-memory-graph-smoke"));
|
||||
let output = run_smoke(store)?;
|
||||
let ok = output["ok"].as_bool().unwrap_or(false);
|
||||
print_json(&output)?;
|
||||
if !ok {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
print_usage();
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn memory_graph_status(store: &PathBuf) -> Result<serde_json::Value> {
|
||||
let Some(snapshot) = load_memory_graph_snapshot(store)? else {
|
||||
return Ok(serde_json::json!({
|
||||
"present": false,
|
||||
"store": store,
|
||||
}));
|
||||
};
|
||||
let errors = validate_memory_graph_snapshot(&snapshot);
|
||||
let freshness = snapshot
|
||||
.freshness
|
||||
.clone()
|
||||
.unwrap_or_else(|| derive_memory_graph_freshness(&snapshot, &[]));
|
||||
Ok(serde_json::json!({
|
||||
"present": true,
|
||||
"store": store,
|
||||
"graphId": snapshot.graph_id,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
"freshness": freshness,
|
||||
"valid": errors.is_empty(),
|
||||
"errors": errors.iter().map(|error| serde_json::json!({
|
||||
"path": error.path,
|
||||
"message": error.message,
|
||||
})).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn read_context_query(args: impl Iterator<Item = String>) -> Result<EpiphanyMemoryContextQuery> {
|
||||
let mut query = EpiphanyMemoryContextQuery {
|
||||
id: "memory-graph-context-query".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut args = args.peekable();
|
||||
while let Some(flag) = args.next() {
|
||||
match flag.as_str() {
|
||||
"--query-id" => query.id = next_value(&mut args, "--query-id")?,
|
||||
"--profile" => {
|
||||
query.profile = Some(parse_profile(&next_value(&mut args, "--profile")?)?)
|
||||
}
|
||||
"--domain-id" => query.domain_ids.push(next_value(&mut args, "--domain-id")?),
|
||||
"--node-id" => query.node_ids.push(next_value(&mut args, "--node-id")?),
|
||||
"--edge-id" => query.edge_ids.push(next_value(&mut args, "--edge-id")?),
|
||||
"--text" => query.text = Some(next_value(&mut args, "--text")?),
|
||||
"--budget" => {
|
||||
let value = next_value(&mut args, "--budget")?;
|
||||
query.budget = Some(
|
||||
value
|
||||
.parse::<u32>()
|
||||
.with_context(|| format!("invalid --budget {value:?}"))?,
|
||||
);
|
||||
}
|
||||
_ => return Err(anyhow!("unexpected context argument {flag:?}")),
|
||||
}
|
||||
}
|
||||
Ok(query)
|
||||
}
|
||||
|
||||
struct ComposeArgs {
|
||||
store: PathBuf,
|
||||
graph_id: String,
|
||||
sources: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
struct RefreshArgs {
|
||||
store: PathBuf,
|
||||
graph_id: String,
|
||||
sources: Vec<PathBuf>,
|
||||
agent_store: Option<PathBuf>,
|
||||
agent_roles: Vec<String>,
|
||||
heartbeat_store: Option<PathBuf>,
|
||||
thread_state_store: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn read_compose_args(args: impl Iterator<Item = String>) -> Result<ComposeArgs> {
|
||||
let mut store = None;
|
||||
let mut graph_id = "epiphany-memory-graph".to_string();
|
||||
let mut sources = Vec::new();
|
||||
let mut args = args.peekable();
|
||||
while let Some(flag) = args.next() {
|
||||
match flag.as_str() {
|
||||
"--store" => store = Some(PathBuf::from(next_value(&mut args, "--store")?)),
|
||||
"--graph-id" => graph_id = next_value(&mut args, "--graph-id")?,
|
||||
"--source" => sources.push(PathBuf::from(next_value(&mut args, "--source")?)),
|
||||
_ => return Err(anyhow!("unexpected compose argument {flag:?}")),
|
||||
}
|
||||
}
|
||||
if sources.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"compose requires at least one --source memory graph store"
|
||||
));
|
||||
}
|
||||
Ok(ComposeArgs {
|
||||
store: store.ok_or_else(|| anyhow!("compose requires --store <path>"))?,
|
||||
graph_id,
|
||||
sources,
|
||||
})
|
||||
}
|
||||
|
||||
fn compose_memory_graph_store(args: ComposeArgs) -> Result<serde_json::Value> {
|
||||
let mut snapshots = Vec::new();
|
||||
let mut source_status = Vec::new();
|
||||
for source in &args.sources {
|
||||
let snapshot = load_memory_graph_snapshot(source)?
|
||||
.ok_or_else(|| anyhow!("memory graph source {} is missing", source.display()))?;
|
||||
source_status.push(serde_json::json!({
|
||||
"source": source,
|
||||
"graphId": snapshot.graph_id,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
}));
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
|
||||
let snapshot = compose_memory_graph_snapshots(args.graph_id, snapshots).map_err(|errors| {
|
||||
anyhow!(
|
||||
"composed memory graph is invalid: {}",
|
||||
errors
|
||||
.iter()
|
||||
.map(|error| format!("{}: {}", error.path, error.message))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
)
|
||||
})?;
|
||||
write_memory_graph_snapshot(&args.store, &snapshot)?;
|
||||
Ok(serde_json::json!({
|
||||
"ok": true,
|
||||
"store": args.store,
|
||||
"graphId": snapshot.graph_id,
|
||||
"sources": source_status,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
"freshness": snapshot.freshness,
|
||||
}))
|
||||
}
|
||||
|
||||
fn read_refresh_args(args: impl Iterator<Item = String>) -> Result<RefreshArgs> {
|
||||
let mut store = None;
|
||||
let mut graph_id = "epiphany-memory-graph".to_string();
|
||||
let mut sources = Vec::new();
|
||||
let mut agent_store = None;
|
||||
let mut agent_roles = Vec::new();
|
||||
let mut heartbeat_store = None;
|
||||
let mut thread_state_store = None;
|
||||
let mut args = args.peekable();
|
||||
while let Some(flag) = args.next() {
|
||||
match flag.as_str() {
|
||||
"--store" => store = Some(PathBuf::from(next_value(&mut args, "--store")?)),
|
||||
"--graph-id" => graph_id = next_value(&mut args, "--graph-id")?,
|
||||
"--source" => sources.push(PathBuf::from(next_value(&mut args, "--source")?)),
|
||||
"--agent-store" => {
|
||||
agent_store = Some(PathBuf::from(next_value(&mut args, "--agent-store")?))
|
||||
}
|
||||
"--agent-role" => agent_roles.push(next_value(&mut args, "--agent-role")?),
|
||||
"--heartbeat-store" => {
|
||||
heartbeat_store = Some(PathBuf::from(next_value(&mut args, "--heartbeat-store")?))
|
||||
}
|
||||
"--thread-state-store" => {
|
||||
thread_state_store = Some(PathBuf::from(next_value(
|
||||
&mut args,
|
||||
"--thread-state-store",
|
||||
)?))
|
||||
}
|
||||
_ => return Err(anyhow!("unexpected refresh argument {flag:?}")),
|
||||
}
|
||||
}
|
||||
if sources.is_empty()
|
||||
&& agent_store.is_none()
|
||||
&& heartbeat_store.is_none()
|
||||
&& thread_state_store.is_none()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"refresh requires --source, --thread-state-store, --agent-store, or --heartbeat-store"
|
||||
));
|
||||
}
|
||||
Ok(RefreshArgs {
|
||||
store: store.ok_or_else(|| anyhow!("refresh requires --store <path>"))?,
|
||||
graph_id,
|
||||
sources,
|
||||
agent_store,
|
||||
agent_roles,
|
||||
heartbeat_store,
|
||||
thread_state_store,
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_memory_graph_store(args: RefreshArgs) -> Result<serde_json::Value> {
|
||||
if args.sources.is_empty()
|
||||
&& args.agent_store.is_none()
|
||||
&& args.heartbeat_store.is_none()
|
||||
&& let Some(thread_state_store) = &args.thread_state_store
|
||||
{
|
||||
let state = load_thread_state(thread_state_store)?.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"thread state store {} is missing",
|
||||
thread_state_store.display()
|
||||
)
|
||||
})?;
|
||||
let repo_root = thread_state_store
|
||||
.parent()
|
||||
.and_then(std::path::Path::parent)
|
||||
.unwrap_or_else(|| std::path::Path::new("."));
|
||||
let source_identity = thread_state_store
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| thread_state_store.clone())
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let (snapshot, refresh) = refresh_or_validate_repo_memory_graph(
|
||||
&args.store,
|
||||
&source_identity,
|
||||
&state,
|
||||
repo_root,
|
||||
args.graph_id,
|
||||
)?;
|
||||
return Ok(serde_json::json!({
|
||||
"ok": true, "store": args.store, "graphId": snapshot.graph_id,
|
||||
"source": snapshot.source, "refresh": format!("{refresh:?}").to_lowercase(),
|
||||
"domains": snapshot.domains.len(), "nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(), "summaries": snapshot.summaries.len(),
|
||||
"freshness": snapshot.freshness,
|
||||
}));
|
||||
}
|
||||
let mut snapshots = Vec::new();
|
||||
let mut source_status = Vec::new();
|
||||
|
||||
for source in &args.sources {
|
||||
let snapshot = load_memory_graph_snapshot(source)?
|
||||
.ok_or_else(|| anyhow!("memory graph source {} is missing", source.display()))?;
|
||||
source_status.push(snapshot_status("source_store", source, &snapshot));
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
|
||||
if let Some(agent_store) = &args.agent_store {
|
||||
let roles = if args.agent_roles.is_empty() {
|
||||
agent_memory_role_ids()
|
||||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
args.agent_roles.clone()
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
for role in &roles {
|
||||
let entry = load_agent_memory_entry_for_role(agent_store, role)?.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"agent memory store {} is missing role {role:?}",
|
||||
agent_store.display()
|
||||
)
|
||||
})?;
|
||||
entries.push(entry);
|
||||
}
|
||||
let snapshot = memory_graph_from_agent_memories("agent-profile", &entries);
|
||||
source_status.push(serde_json::json!({
|
||||
"kind": "agent_store",
|
||||
"source": agent_store,
|
||||
"roles": roles,
|
||||
"graphId": snapshot.graph_id,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
}));
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
|
||||
if let Some(thread_state_store) = &args.thread_state_store {
|
||||
let state = load_thread_state(thread_state_store)?.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"thread state store {} is missing",
|
||||
thread_state_store.display()
|
||||
)
|
||||
})?;
|
||||
let repo_root = thread_state_store
|
||||
.parent()
|
||||
.and_then(std::path::Path::parent)
|
||||
.unwrap_or_else(|| std::path::Path::new("."));
|
||||
let source_identity = thread_state_store
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| thread_state_store.clone())
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let snapshot = memory_graph_from_epiphany_graphs(
|
||||
"repo-profile",
|
||||
&state.graphs,
|
||||
source_identity,
|
||||
state.revision,
|
||||
repo_root,
|
||||
)?;
|
||||
source_status.push(serde_json::json!({
|
||||
"kind": "thread_state_store",
|
||||
"source": thread_state_store,
|
||||
"revision": state.revision,
|
||||
"graphId": snapshot.graph_id,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
}));
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
|
||||
if let Some(heartbeat_store) = &args.heartbeat_store {
|
||||
let cognition = load_heartbeat_cognition_entry(heartbeat_store)?.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"heartbeat store {} has no cognition entry",
|
||||
heartbeat_store.display()
|
||||
)
|
||||
})?;
|
||||
let snapshot = memory_graph_from_heartbeat_cognition("heartbeat-profile", &cognition);
|
||||
source_status.push(serde_json::json!({
|
||||
"kind": "heartbeat_store",
|
||||
"source": heartbeat_store,
|
||||
"graphId": snapshot.graph_id,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
}));
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
|
||||
let snapshot = compose_memory_graph_snapshots(args.graph_id, snapshots).map_err(|errors| {
|
||||
anyhow!(
|
||||
"refreshed memory graph is invalid: {}",
|
||||
errors
|
||||
.iter()
|
||||
.map(|error| format!("{}: {}", error.path, error.message))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
)
|
||||
})?;
|
||||
write_memory_graph_snapshot(&args.store, &snapshot)?;
|
||||
Ok(serde_json::json!({
|
||||
"ok": true,
|
||||
"store": args.store,
|
||||
"graphId": snapshot.graph_id,
|
||||
"sources": source_status,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
"freshness": snapshot.freshness,
|
||||
}))
|
||||
}
|
||||
|
||||
fn snapshot_status(
|
||||
kind: &str,
|
||||
source: &PathBuf,
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"kind": kind,
|
||||
"source": source,
|
||||
"graphId": snapshot.graph_id,
|
||||
"domains": snapshot.domains.len(),
|
||||
"nodes": snapshot.nodes.len(),
|
||||
"edges": snapshot.edges.len(),
|
||||
"summaries": snapshot.summaries.len(),
|
||||
})
|
||||
}
|
||||
|
||||
fn require_path_arg(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
|
||||
Ok(PathBuf::from(require_string_arg(args, name)?))
|
||||
}
|
||||
|
||||
fn require_string_arg(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
|
||||
let Some(flag) = args.next() else {
|
||||
return Err(anyhow!("missing {name}"));
|
||||
};
|
||||
if flag != name {
|
||||
return Err(anyhow!("expected {name}, got {flag}"));
|
||||
}
|
||||
args.next()
|
||||
.with_context(|| format!("missing value for {name}"))
|
||||
}
|
||||
|
||||
fn optional_path_arg(
|
||||
args: &mut impl Iterator<Item = String>,
|
||||
name: &str,
|
||||
) -> Result<Option<PathBuf>> {
|
||||
let values = args.collect::<Vec<_>>();
|
||||
if values.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if values.len() != 2 || values[0] != name {
|
||||
return Err(anyhow!("expected optional {name} <path>, got {values:?}"));
|
||||
}
|
||||
Ok(Some(PathBuf::from(&values[1])))
|
||||
}
|
||||
|
||||
fn next_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
|
||||
args.next()
|
||||
.with_context(|| format!("missing value for {name}"))
|
||||
}
|
||||
|
||||
fn parse_profile(value: &str) -> Result<EpiphanyMemoryProfile> {
|
||||
match value {
|
||||
"repo_architecture" => Ok(EpiphanyMemoryProfile::RepoArchitecture),
|
||||
"repo_dataflow" => Ok(EpiphanyMemoryProfile::RepoDataflow),
|
||||
"role_self" => Ok(EpiphanyMemoryProfile::RoleSelf),
|
||||
"short_term" => Ok(EpiphanyMemoryProfile::ShortTerm),
|
||||
"incubation" => Ok(EpiphanyMemoryProfile::Incubation),
|
||||
"agency_pressure" => Ok(EpiphanyMemoryProfile::AgencyPressure),
|
||||
"candidate_intervention" => Ok(EpiphanyMemoryProfile::CandidateIntervention),
|
||||
"identity" => Ok(EpiphanyMemoryProfile::Identity),
|
||||
"evidence" => Ok(EpiphanyMemoryProfile::Evidence),
|
||||
_ => Err(anyhow!("unknown memory graph profile {value:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_json<T: serde::Serialize>(value: &T) -> Result<()> {
|
||||
println!("{}", serde_json::to_string_pretty(value)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!(
|
||||
"usage: epiphany-memory-graph <status|validate|context|compose|refresh|smoke> --store <path> ..."
|
||||
);
|
||||
}
|
||||
|
||||
fn scoped_temp_store(prefix: &str) -> PathBuf {
|
||||
env::temp_dir().join(format!("{prefix}-{}.msgpack", uuid::Uuid::new_v4()))
|
||||
}
|
||||
|
||||
fn run_smoke(store: PathBuf) -> Result<serde_json::Value> {
|
||||
let snapshot = smoke_snapshot();
|
||||
write_memory_graph_snapshot(&store, &snapshot)?;
|
||||
let status = memory_graph_status(&store)?;
|
||||
let packet = plan_memory_graph_context_cut(
|
||||
&snapshot,
|
||||
&EpiphanyMemoryContextQuery {
|
||||
id: "smoke-query".to_string(),
|
||||
profile: Some(EpiphanyMemoryProfile::RepoArchitecture),
|
||||
text: Some("shared graph law".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
Ok(serde_json::json!({
|
||||
"ok": status["valid"].as_bool().unwrap_or(false)
|
||||
&& packet.summaries.len() == 1
|
||||
&& packet.nodes.is_empty(),
|
||||
"store": store,
|
||||
"status": status,
|
||||
"contextPacket": packet,
|
||||
}))
|
||||
}
|
||||
|
||||
fn smoke_snapshot() -> EpiphanyMemoryGraphSnapshot {
|
||||
let domain_id = memory_graph_domain_id(
|
||||
EpiphanyMemoryProfile::RepoArchitecture,
|
||||
"crate",
|
||||
"epiphany-core",
|
||||
);
|
||||
let node_id = memory_graph_node_id(
|
||||
&domain_id,
|
||||
"module",
|
||||
"epiphany-core/src/memory_graph.rs",
|
||||
Some("memory_graph"),
|
||||
);
|
||||
EpiphanyMemoryGraphSnapshot {
|
||||
graph_id: "memory-graph-smoke".to_string(),
|
||||
domains: vec![EpiphanyMemoryDomain {
|
||||
id: domain_id.clone(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
title: "epiphany-core".to_string(),
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
nodes: vec![EpiphanyMemoryNode {
|
||||
id: node_id.clone(),
|
||||
domain_id: domain_id.clone(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
kind: EpiphanyMemoryNodeKind::Module,
|
||||
title: "memory_graph".to_string(),
|
||||
claim: "Shared memory graph law owns repo and agent memory graph invariants."
|
||||
.to_string(),
|
||||
question: "Which profile-specific producers are allowed after the shared store?"
|
||||
.to_string(),
|
||||
tension: String::new(),
|
||||
action_implication: "Add profile producers only after the shared typed store works."
|
||||
.to_string(),
|
||||
anchors: vec![EpiphanyMemoryAnchor {
|
||||
id: "anchor-memory-graph-rs".to_string(),
|
||||
kind: "source".to_string(),
|
||||
target: "epiphany-core/src/memory_graph.rs".to_string(),
|
||||
source_hash: Some("smoke-hash".to_string()),
|
||||
..Default::default()
|
||||
}],
|
||||
source_hashes: vec!["smoke-hash".to_string()],
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
confidence: 90,
|
||||
salience: 80,
|
||||
..Default::default()
|
||||
}],
|
||||
edges: vec![EpiphanyMemoryEdge {
|
||||
id: memory_graph_edge_id(&node_id, &node_id, "verifies", ["smoke"]),
|
||||
source_id: node_id.clone(),
|
||||
target_id: node_id.clone(),
|
||||
kind: EpiphanyMemoryEdgeKind::Verifies,
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
claim: "The smoke packet verifies the memory graph context cut can use summaries."
|
||||
.to_string(),
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
confidence: 80,
|
||||
..Default::default()
|
||||
}],
|
||||
summaries: vec![EpiphanyMemorySummary {
|
||||
id: "summary-memory-graph-smoke".to_string(),
|
||||
domain_id,
|
||||
covers_node_ids: vec![node_id],
|
||||
target: "memory_graph".to_string(),
|
||||
claim: "The shared graph skeleton can persist and return context without Qdrant."
|
||||
.to_string(),
|
||||
question: "Which producer should populate it first?".to_string(),
|
||||
tension: String::new(),
|
||||
action_implication: "Use this store before scanner or sleep-runner work.".to_string(),
|
||||
anchor_count: 1,
|
||||
source_hashes: vec!["smoke-hash".to_string()],
|
||||
freshness: EpiphanyMemoryFreshnessStatus::Ready,
|
||||
confidence: 95,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ use epiphany_core::{
|
|||
EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot, MemorySemanticIndexConfig,
|
||||
MemorySemanticProjectionInput, SemanticPartition, WORKSPACE_COVERAGE_MAXIMUM_FILE_BYTES,
|
||||
WorkspaceCoveragePolicy, WorkspaceProjectionIdentity, agent_memory_semantic_projection_input,
|
||||
load_memory_graph_snapshot, load_memory_semantic_projection_readiness,
|
||||
load_memory_semantic_projection_readiness,
|
||||
observe_repository_readiness, publish_epiphany_cultmesh_semantic_projection_health,
|
||||
runtime_modeling_semantic_projection_input, semantic_memory_context,
|
||||
};
|
||||
|
|
@ -67,7 +67,7 @@ fn main() -> Result<()> {
|
|||
let runtime_store = options.runtime_store.as_ref().ok_or_else(|| {
|
||||
usage_error("repository-readiness requires --runtime-store <path>")
|
||||
})?;
|
||||
if options.graph_store.is_some() || options.agent_store.is_some() {
|
||||
if options.agent_store.is_some() {
|
||||
return Err(usage_error(
|
||||
"repository-readiness accepts only --runtime-store <path>",
|
||||
));
|
||||
|
|
@ -105,7 +105,6 @@ fn main() -> Result<()> {
|
|||
}
|
||||
|
||||
struct Options {
|
||||
graph_store: Option<PathBuf>,
|
||||
runtime_store: Option<PathBuf>,
|
||||
agent_store: Option<PathBuf>,
|
||||
local_verse_store: Option<PathBuf>,
|
||||
|
|
@ -125,7 +124,6 @@ struct Options {
|
|||
impl Options {
|
||||
fn parse(args: impl Iterator<Item = String>) -> Result<Self> {
|
||||
let mut options = Self {
|
||||
graph_store: None,
|
||||
runtime_store: None,
|
||||
agent_store: None,
|
||||
local_verse_store: None,
|
||||
|
|
@ -148,7 +146,6 @@ impl Options {
|
|||
.with_context(|| format!("missing value for {flag}"))
|
||||
};
|
||||
match flag.as_str() {
|
||||
"--graph-store" => options.graph_store = Some(PathBuf::from(value()?)),
|
||||
"--runtime-store" => options.runtime_store = Some(PathBuf::from(value()?)),
|
||||
"--agent-store" => options.agent_store = Some(PathBuf::from(value()?)),
|
||||
"--local-verse-store" => options.local_verse_store = Some(PathBuf::from(value()?)),
|
||||
|
|
@ -182,7 +179,6 @@ impl Options {
|
|||
return Err(usage_error("--swarm-id must not be empty"));
|
||||
}
|
||||
let sources = [
|
||||
options.graph_store.is_some(),
|
||||
options.runtime_store.is_some(),
|
||||
options.agent_store.is_some(),
|
||||
]
|
||||
|
|
@ -191,37 +187,28 @@ impl Options {
|
|||
.count();
|
||||
if sources != 1 {
|
||||
return Err(usage_error(
|
||||
"provide exactly one --graph-store, --runtime-store, or --agent-store",
|
||||
"provide exactly one --runtime-store or --agent-store",
|
||||
));
|
||||
}
|
||||
if options.partition == SemanticPartition::Mind && options.runtime_store.is_some() {
|
||||
return Err(usage_error(
|
||||
"Mind projection requires --agent-store or an explicitly composed --graph-store",
|
||||
"Mind projection requires --agent-store",
|
||||
));
|
||||
}
|
||||
if options.partition == SemanticPartition::Modeling && options.agent_store.is_some() {
|
||||
return Err(usage_error(
|
||||
"Modeling projection requires --runtime-store or --graph-store",
|
||||
"Modeling projection requires --runtime-store",
|
||||
));
|
||||
}
|
||||
if options.graph_store.is_some() && options.swarm_id.is_none() {
|
||||
return Err(usage_error("--graph-store requires --swarm-id"));
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn load_source(&self) -> Result<(EpiphanyMemoryGraphSnapshot, String)> {
|
||||
if self.runtime_store.is_some() || self.agent_store.is_some() {
|
||||
let (input, _) = self.load_projection_input()?;
|
||||
return Ok((
|
||||
input.snapshot().clone(),
|
||||
input.obligation().swarm_id.clone(),
|
||||
));
|
||||
}
|
||||
let path = self.graph_store.as_ref().expect("validated graph store");
|
||||
let snapshot = load_memory_graph_snapshot(path)?
|
||||
.ok_or_else(|| anyhow!("memory graph store {} is missing", path.display()))?;
|
||||
Ok((snapshot, self.swarm_id.clone().expect("validated swarm id")))
|
||||
let (input, _) = self.load_projection_input()?;
|
||||
Ok((
|
||||
input.snapshot().clone(),
|
||||
input.obligation().swarm_id.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
fn load_projection_input(&self) -> Result<(MemorySemanticProjectionInput, &PathBuf)> {
|
||||
|
|
@ -230,9 +217,7 @@ impl Options {
|
|||
} else if let Some(path) = &self.agent_store {
|
||||
(agent_memory_semantic_projection_input(path)?, path)
|
||||
} else {
|
||||
return Err(anyhow!(
|
||||
"graph-store snapshots have no canonical admission authority and are BM25-only"
|
||||
));
|
||||
return Err(anyhow!("semantic projection requires a typed source store"));
|
||||
};
|
||||
if self
|
||||
.swarm_id
|
||||
|
|
|
|||
121
epiphany-core/src/bin/epiphany-model-entanglement-projector.rs
Normal file
121
epiphany-core/src/bin/epiphany-model-entanglement-projector.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use epiphany_core::{
|
||||
AtlasProjectorRunConfig, AtlasProjectorRunOutcome, AtlasRepositoryIdentity,
|
||||
AtlasStoreWriteOutcome, pin_atlas_publisher_trust_anchor, run_atlas_projector_once,
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let (args, switches, command) = arguments()?;
|
||||
let projector = AtlasRepositoryIdentity::new(
|
||||
required(&args, "--swarm-id")?,
|
||||
required(&args, "--workspace-id")?,
|
||||
)?;
|
||||
if command == "pin-trust" {
|
||||
let publisher = AtlasRepositoryIdentity::new(
|
||||
required(&args, "--publisher-swarm-id")?,
|
||||
required(&args, "--publisher-workspace-id")?,
|
||||
)?;
|
||||
let expected_revision = args
|
||||
.get("--expected-revision")
|
||||
.map(|value| value.parse())
|
||||
.transpose()?;
|
||||
let outcome = pin_atlas_publisher_trust_anchor(
|
||||
&path(&args, "--projector-store")?,
|
||||
projector,
|
||||
publisher,
|
||||
&path(&args, "--trust-anchor")?,
|
||||
expected_revision,
|
||||
now_unix_ms()?,
|
||||
)?;
|
||||
if outcome == AtlasStoreWriteOutcome::Conflict {
|
||||
bail!("Atlas trust pin CAS conflicted")
|
||||
}
|
||||
println!("Atlas publisher trust pin admitted: {outcome:?}");
|
||||
return Ok(());
|
||||
}
|
||||
if command != "run" {
|
||||
bail!("Atlas projector command must be `run` or `pin-trust`")
|
||||
}
|
||||
let once = switches.contains("--once");
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
let stop = running.clone();
|
||||
ctrlc::set_handler(move || stop.store(false, Ordering::SeqCst))?;
|
||||
while running.load(Ordering::SeqCst) {
|
||||
let config = AtlasProjectorRunConfig {
|
||||
projector_repository: projector.clone(),
|
||||
runtime_id: required(&args, "--runtime-id")?.into(),
|
||||
local_verse_store: path(&args, "--verse-store")?,
|
||||
projector_store: path(&args, "--projector-store")?,
|
||||
projector_cultmesh_store: path(&args, "--cultmesh-store")?,
|
||||
odin_endpoint: required(&args, "--odin-endpoint")?.parse()?,
|
||||
now_unix_ms: now_unix_ms()?,
|
||||
};
|
||||
match run_atlas_projector_once(&config)? {
|
||||
AtlasProjectorRunOutcome::HeldByBrake {
|
||||
brake_id,
|
||||
last_projection,
|
||||
} => println!(
|
||||
"atlas projector held by brake {brake_id}; last projection remains read-only: {}",
|
||||
last_projection.is_some()
|
||||
),
|
||||
AtlasProjectorRunOutcome::Projected {
|
||||
projection,
|
||||
accepted_publications,
|
||||
rejected_publications,
|
||||
} => println!(
|
||||
"atlas projector {} accepted {accepted_publications}, rejected {rejected_publications}, derived {} edges and {} cycles",
|
||||
projection.projection_sha256,
|
||||
projection.entanglements.len(),
|
||||
projection.cycles.len()
|
||||
),
|
||||
}
|
||||
if once {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn arguments() -> Result<(BTreeMap<String, String>, BTreeSet<String>, String)> {
|
||||
let mut raw = std::env::args().skip(1);
|
||||
let command = raw.next().unwrap_or_else(|| "run".into());
|
||||
let mut values = BTreeMap::new();
|
||||
let mut switches = BTreeSet::new();
|
||||
while let Some(name) = raw.next() {
|
||||
if name == "--once" {
|
||||
switches.insert(name);
|
||||
continue;
|
||||
}
|
||||
if !name.starts_with("--") {
|
||||
bail!("unexpected Atlas projector argument {name}")
|
||||
}
|
||||
values.insert(
|
||||
name.clone(),
|
||||
raw.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("{name} requires a value"))?,
|
||||
);
|
||||
}
|
||||
Ok((values, switches, command))
|
||||
}
|
||||
|
||||
fn required<'a>(args: &'a BTreeMap<String, String>, name: &str) -> Result<&'a str> {
|
||||
args.get(name)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required {name}"))
|
||||
}
|
||||
fn path(args: &BTreeMap<String, String>, name: &str) -> Result<PathBuf> {
|
||||
Ok(PathBuf::from(required(args, name)?))
|
||||
}
|
||||
fn now_unix_ms() -> Result<u64> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)?
|
||||
.as_millis()
|
||||
.try_into()?)
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -38,9 +38,9 @@ use epiphany_core::derive_scene;
|
|||
use epiphany_core::read_accepted_coordinator_state;
|
||||
use epiphany_core::recommend_crrc_action;
|
||||
use epiphany_core::recommend_reorientation;
|
||||
use epiphany_core::runtime_repo_frontier_research_lifecycle;
|
||||
use epiphany_core::runtime_has_actionable_hands_frontier;
|
||||
use epiphany_core::runtime_job_snapshot;
|
||||
use epiphany_core::runtime_repo_frontier_research_lifecycle;
|
||||
use epiphany_self_policy::crrc_scene_action_to_coordinator_scene_action;
|
||||
use epiphany_self_policy::derive_coordinator_finding_signals;
|
||||
use epiphany_self_policy::derive_coordinator_status;
|
||||
|
|
@ -315,17 +315,22 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result<Valu
|
|||
epiphany_core::EpiphanyPressureLevel::High => EpiphanyReorientPressureLevel::High,
|
||||
epiphany_core::EpiphanyPressureLevel::Critical => EpiphanyReorientPressureLevel::Critical,
|
||||
};
|
||||
let reorient_checkpoint = match state_ref.and_then(|state| state.investigation_checkpoint.clone()) {
|
||||
let reorient_checkpoint = match state_ref
|
||||
.and_then(|state| state.investigation_checkpoint.clone())
|
||||
{
|
||||
Some(checkpoint) => Some(checkpoint),
|
||||
None => match epiphany_core::runtime_current_repo_model(&runtime_store_path)? {
|
||||
None => None,
|
||||
Some(_) => {
|
||||
let projection = epiphany_core::runtime_modeling_semantic_projection_input(&runtime_store_path)
|
||||
.context("failed to validate current RepoModel continuity projection")?;
|
||||
Some(epiphany_state_model::reorient_checkpoint_from_admitted_repo_model(
|
||||
projection.snapshot(),
|
||||
&projection.obligation().obligation_id,
|
||||
))
|
||||
let projection =
|
||||
epiphany_core::runtime_modeling_semantic_projection_input(&runtime_store_path)
|
||||
.context("failed to validate current RepoModel continuity projection")?;
|
||||
Some(
|
||||
epiphany_state_model::reorient_checkpoint_from_admitted_repo_model(
|
||||
projection.snapshot(),
|
||||
&projection.obligation().obligation_id,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
@ -485,7 +490,7 @@ fn run_native_status(args: &Args, include_auxiliary_status: bool) -> Result<Valu
|
|||
&runtime_store_path,
|
||||
)
|
||||
.context("failed to derive Imagination frontier eligibility from runtime-spine state")?;
|
||||
let imagination_frontier_ready = frontier_planning_eligibility.current_admission_count == 1
|
||||
let imagination_frontier_ready = frontier_planning_eligibility.current_model_count == 1
|
||||
&& frontier_planning_eligibility
|
||||
.candidates
|
||||
.iter()
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ use anyhow::{Context, Result, bail};
|
|||
use epiphany_core::*;
|
||||
use epiphany_state_model::{
|
||||
EpiphanyMemoryDomain, EpiphanyMemoryLifecycle, EpiphanyMemoryNode, EpiphanyMemoryNodeKind,
|
||||
EpiphanyMemoryProfile, EpiphanyThreadState, RepoModelPatchPurpose,
|
||||
EpiphanyMemoryProfile, EpiphanyThreadState,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
|
|
@ -118,8 +118,8 @@ fn main() -> Result<()> {
|
|||
source_room_id: request.source_room_id.clone(),
|
||||
source_visibility: request.source_visibility.clone(),
|
||||
data_classification: request.data_classification.clone(),
|
||||
model_revision: request.model_revision,
|
||||
model_hash: request.model_hash.clone(),
|
||||
model_projection_digest: request.model_projection_digest.clone(),
|
||||
model_source_documents: request.model_source_documents.clone(),
|
||||
disposition: ImaginationConsiderationDisposition::Suggest,
|
||||
title: "Fixture proposal".into(),
|
||||
summary: "Reviewable option only".into(),
|
||||
|
|
@ -177,66 +177,40 @@ fn seed_fixture_runtime(store: &Path) -> Result<()> {
|
|||
THREAD_STATE_KEY,
|
||||
&EpiphanyThreadStateEntry::from_state("fixture-thread", &state)?,
|
||||
)?;
|
||||
let mut model = EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.into()),
|
||||
graph_id: "fixture-model".into(),
|
||||
model_revision: 1,
|
||||
domains: vec![EpiphanyMemoryDomain {
|
||||
id: "repo".into(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
title: "Repository".into(),
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
nodes: vec![EpiphanyMemoryNode {
|
||||
id: "fixture-claim".into(),
|
||||
domain_id: "repo".into(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
kind: EpiphanyMemoryNodeKind::RuntimeContract,
|
||||
title: "Feedback path".into(),
|
||||
claim: "Persona feedback is pressure, never authority.".into(),
|
||||
question: "Which proposal fits the Body?".into(),
|
||||
action_implication: "Review only.".into(),
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
model.model_hash = memory_graph_model_hash(&model)?;
|
||||
cache.put(
|
||||
MEMORY_GRAPH_KEY,
|
||||
&EpiphanyMemoryGraphEntry::from_snapshot(&model)?,
|
||||
)?;
|
||||
cache.put(
|
||||
"fixture-model-admission",
|
||||
&RepoModelAdmissionReceipt {
|
||||
schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(),
|
||||
receipt_id: "fixture-model-admission".into(),
|
||||
review_id: "fixture-review".into(),
|
||||
result_id: Some("fixture-result".into()),
|
||||
patch_id: "fixture-patch".into(),
|
||||
patch_sha256: "sha256-fixture".into(),
|
||||
previous_revision: 0,
|
||||
previous_hash: "none".into(),
|
||||
admitted_revision: 1,
|
||||
admitted_hash: model.model_hash,
|
||||
admitted_at: AT.into(),
|
||||
contract: REPO_MODEL_ADMISSION_CONTRACT.into(),
|
||||
purpose: RepoModelPatchPurpose::Evolution,
|
||||
frontier_route_id: String::new(),
|
||||
verification_request_id: String::new(),
|
||||
soul_verdict_receipt_id: String::new(),
|
||||
frontier_modeling_request_id: String::new(),
|
||||
proposal_modeling_request_id: String::new(),
|
||||
claim_repair_request_id: String::new(),
|
||||
frontier_plan_decision_id: String::new(),
|
||||
repository_body_observation_basis: None,
|
||||
admission_source: Some(epiphany_core::RepoModelAdmissionSource::WorkerResult {
|
||||
result_id: "fixture-result".into(),
|
||||
job_id: "fixture-job".into(),
|
||||
}),
|
||||
drop(cache);
|
||||
let seed = EpiphanyRepoModelSeed::new(
|
||||
"fixture-model-seed",
|
||||
"fixture-model",
|
||||
"epiphany-yggdrasil",
|
||||
"fixture-workspace",
|
||||
"fixture-body-binding",
|
||||
EpiphanyRepoModelSeedDocuments {
|
||||
domains: vec![EpiphanyMemoryDomain {
|
||||
id: "repo".into(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
title: "Repository".into(),
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
nodes: vec![EpiphanyMemoryNode {
|
||||
id: "fixture-claim".into(),
|
||||
domain_id: "repo".into(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
kind: EpiphanyMemoryNodeKind::RuntimeContract,
|
||||
title: "Feedback path".into(),
|
||||
claim: "Persona feedback is pressure, never authority.".into(),
|
||||
question: "Which proposal fits the Body?".into(),
|
||||
action_implication: "Review only.".into(),
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
edges: Vec::new(),
|
||||
summaries: Vec::new(),
|
||||
frontier: Vec::new(),
|
||||
lifecycle_receipts: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
initialize_keyed_repo_model(store, &seed, AT)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -385,7 +385,7 @@ fn seed_modeling(store: &Path, mind: &Path, swarm: &str) -> Result<()> {
|
|||
)?;
|
||||
bind_runtime_to_agent_memory_swarm(store, mind, &at)?;
|
||||
let mut graph = EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.into()),
|
||||
schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.into()),
|
||||
graph_id: format!("model-{swarm}"),
|
||||
model_revision: 1,
|
||||
..Default::default()
|
||||
|
|
|
|||
|
|
@ -61,16 +61,14 @@ pub fn frontier_plan_mind_request_id(
|
|||
|
||||
pub fn admitted_model_direction_request_id(
|
||||
runtime_id: &str,
|
||||
model_hash: &str,
|
||||
admission_receipt_id: &str,
|
||||
model_projection_digest: &str,
|
||||
previous_terminal_result_id: Option<&str>,
|
||||
) -> String {
|
||||
digest_id(
|
||||
"admitted-model-direction-consideration",
|
||||
&[
|
||||
runtime_id,
|
||||
model_hash,
|
||||
admission_receipt_id,
|
||||
model_projection_digest,
|
||||
previous_terminal_result_id.unwrap_or(""),
|
||||
],
|
||||
)
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ use crate::coordinator_state::changed_fields;
|
|||
use crate::*;
|
||||
use anyhow::Context;
|
||||
use epiphany_state_model::EpiphanyThreadState;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
|
||||
|
|
@ -79,12 +78,15 @@ pub fn accept_coordinator_reorient_finding(
|
|||
match state.investigation_checkpoint.clone() {
|
||||
Some(checkpoint) => Some(checkpoint),
|
||||
None => {
|
||||
let projection = crate::runtime_modeling_semantic_projection_input(store)
|
||||
.context("cannot accept reorientation without a valid admitted RepoModel checkpoint")?;
|
||||
Some(epiphany_state_model::reorient_checkpoint_from_admitted_repo_model(
|
||||
projection.snapshot(),
|
||||
&projection.obligation().obligation_id,
|
||||
))
|
||||
let model = crate::assemble_repo_model_view(store).context(
|
||||
"cannot accept reorientation without a current keyed RepoModel checkpoint",
|
||||
)?;
|
||||
Some(
|
||||
epiphany_state_model::reorient_checkpoint_from_admitted_repo_model(
|
||||
&model.memory_context_projection(),
|
||||
&model.projection_digest,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
@ -307,40 +309,54 @@ pub fn accept_coordinator_role_finding(
|
|||
if result.result_id != result_id {
|
||||
return Err(anyhow::anyhow!("Modeling finding/result identity mismatch"));
|
||||
}
|
||||
let patch_bytes = result
|
||||
.repo_model_patch_msgpack
|
||||
.as_deref()
|
||||
.ok_or_else(|| anyhow::anyhow!("Modeling result has no repoModelPatch"))?;
|
||||
let patch = result
|
||||
.repo_model_patch()?
|
||||
.ok_or_else(|| anyhow::anyhow!("Modeling repoModelPatch failed to decode"))?;
|
||||
let repository_body_observation_basis = result
|
||||
.repository_body_observation_basis
|
||||
.clone()
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("Modeling result has no Repository Body observation basis")
|
||||
})?;
|
||||
let candidate_review = RepoModelAdmissionReview {
|
||||
schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.to_string(),
|
||||
review_id: format!("repo-model-review-{result_id}"),
|
||||
result_id: Some(result_id.to_string()),
|
||||
job_id: Some(job_id.to_string()),
|
||||
patch_id: patch.patch_id.clone(),
|
||||
patch_sha256: format!("{:x}", Sha256::digest(patch_bytes)),
|
||||
base_revision: patch.base_revision,
|
||||
base_hash: patch.base_hash.clone(),
|
||||
decision: MindGatewayDecision::Accept,
|
||||
evidence_ids: finding.evidence_ids.clone(),
|
||||
reviewed_at: accepted_at.clone(),
|
||||
contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(),
|
||||
repository_body_observation_basis: Some(repository_body_observation_basis),
|
||||
admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult {
|
||||
result_id: result_id.to_string(),
|
||||
job_id: job_id.to_string(),
|
||||
}),
|
||||
};
|
||||
let review = stable_repo_model_admission_review(store, candidate_review)?;
|
||||
commit_repo_model_admission(store, result_id, &review)?;
|
||||
validate_repository_body_observation_basis(store, &repository_body_observation_basis)?;
|
||||
if let Some(proposal) = result.repo_model_mutation_proposal()? {
|
||||
if proposal.proposal_id != format!("repo-model-mutation-proposal-{job_id}") {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Modeling RepoModel mutation proposal identity is not runtime-owned"
|
||||
));
|
||||
}
|
||||
let plan = plan_repo_model_mutation(store, &proposal)?;
|
||||
let invariant_owner = if result.proposal_modeling_request_id.is_some() {
|
||||
"Modeling.proposal_frontier"
|
||||
} else if result.claim_repair_request_id.is_some() {
|
||||
"Modeling.claim_repair"
|
||||
} else if result.repo_frontier_modeling_request_id.is_some() {
|
||||
"Modeling.frontier_verdict"
|
||||
} else {
|
||||
"Modeling.repo_model"
|
||||
};
|
||||
match commit_mind_mutation(
|
||||
store,
|
||||
&result.decision_context_id,
|
||||
invariant_owner,
|
||||
plan.strong_reads,
|
||||
plan.writes,
|
||||
&accepted_at,
|
||||
)? {
|
||||
EpiphanyMindCommitOutcome::Committed(_) => {}
|
||||
EpiphanyMindCommitOutcome::Conflict {
|
||||
document_identities,
|
||||
} => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"RepoModel mutation lost its exact keyed reads: {document_identities:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
} else if !finding.verdict.as_deref().is_some_and(|verdict| {
|
||||
verdict.eq_ignore_ascii_case("checkpoint-ready")
|
||||
|| verdict.eq_ignore_ascii_case("regather-needed")
|
||||
}) {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Modeling result requiring RepoModel change has no semantic mutation proposal"
|
||||
));
|
||||
}
|
||||
}
|
||||
let commit = mind_state_commit_receipt(
|
||||
format!("mind-commit-{}", update.accepted_receipt_id),
|
||||
|
|
@ -369,36 +385,6 @@ pub fn accept_coordinator_role_finding(
|
|||
})
|
||||
}
|
||||
|
||||
fn stable_repo_model_admission_review(
|
||||
store: &Path,
|
||||
candidate: RepoModelAdmissionReview,
|
||||
) -> anyhow::Result<RepoModelAdmissionReview> {
|
||||
match coordinator_acceptance_cache(store)?
|
||||
.get::<RepoModelAdmissionReview>(&candidate.review_id)?
|
||||
{
|
||||
Some(existing)
|
||||
if existing.result_id == candidate.result_id
|
||||
&& existing.job_id == candidate.job_id
|
||||
&& existing.patch_id == candidate.patch_id
|
||||
&& existing.patch_sha256 == candidate.patch_sha256
|
||||
&& existing.base_revision == candidate.base_revision
|
||||
&& existing.base_hash == candidate.base_hash
|
||||
&& existing.decision == candidate.decision
|
||||
&& existing.evidence_ids == candidate.evidence_ids
|
||||
&& existing.schema_version == candidate.schema_version
|
||||
&& existing.contract == candidate.contract
|
||||
&& existing.repository_body_observation_basis
|
||||
== candidate.repository_body_observation_basis =>
|
||||
{
|
||||
Ok(existing)
|
||||
}
|
||||
Some(_) => Err(anyhow::anyhow!(
|
||||
"stable repo model review id belongs to different admission bytes"
|
||||
)),
|
||||
None => Ok(candidate),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_verification_finding_binding(
|
||||
finding: &EpiphanyRoleFindingInterpretation,
|
||||
request: &RepoFrontierVerificationRequest,
|
||||
|
|
@ -721,7 +707,10 @@ fn commit_state_with_mind_witness(
|
|||
|| packet_ids != authenticated_ids
|
||||
|| published_ids != authenticated_ids
|
||||
|| authenticated.iter().any(|lookup| {
|
||||
!packet.source_refs.iter().any(|source_ref| source_ref == &lookup.source_ref)
|
||||
!packet
|
||||
.source_refs
|
||||
.iter()
|
||||
.any(|source_ref| source_ref == &lookup.source_ref)
|
||||
|| !published.iter().any(|candidate| *candidate == lookup)
|
||||
})
|
||||
{
|
||||
|
|
@ -973,6 +962,7 @@ fn role_label_lower(role_id: EpiphanyRoleResultRoleId) -> &'static str {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use sha2::Digest;
|
||||
|
||||
#[test]
|
||||
fn verification_finding_refuses_swapped_request_or_route() {
|
||||
|
|
@ -980,8 +970,15 @@ mod tests {
|
|||
schema_version: REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION.to_string(),
|
||||
request_id: "verification-request-1".to_string(),
|
||||
route_id: "frontier-route-1".to_string(),
|
||||
model_revision: 1,
|
||||
model_hash: "model-hash".to_string(),
|
||||
model_projection_digest: format!("sha256:{}", "a".repeat(64)),
|
||||
model_source_documents: vec![crate::EpiphanyMindDocumentVersion {
|
||||
store_id: "epiphany-mind".into(),
|
||||
document_type: "epiphany.mind.repo_model.identity.v1".into(),
|
||||
document_key: crate::REPO_MODEL_IDENTITY_KEY.into(),
|
||||
schema_id: Some("EpiphanyRepoModelIdentityDocument".into()),
|
||||
payload_msgpack: vec![1],
|
||||
payload_sha256: format!("sha256:{:x}", sha2::Sha256::digest([1])),
|
||||
}],
|
||||
frontier_item_id: "frontier-1".to_string(),
|
||||
frontier_item_hash: "frontier-hash".to_string(),
|
||||
hands_intent_id: "intent-1".to_string(),
|
||||
|
|
@ -1008,7 +1005,7 @@ mod tests {
|
|||
evidence_gaps: Vec::new(),
|
||||
risks: Vec::new(),
|
||||
state_patch: None,
|
||||
repo_model_patch: None,
|
||||
repo_model_mutation_proposal: None,
|
||||
self_patch: None,
|
||||
self_persistence: None,
|
||||
job_error: None,
|
||||
|
|
@ -1255,120 +1252,4 @@ mod tests {
|
|||
assert_eq!(stored.frontier_route_id, "frontier-route-11");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_model_admission_retry_reuses_review_and_commits_fresh_thread_acceptance()
|
||||
-> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let store = temp.path().join("split-model-retry.cc");
|
||||
crate::initialize_runtime_spine(
|
||||
&store,
|
||||
crate::RuntimeSpineInitOptions {
|
||||
runtime_id: "split-model-retry".to_string(),
|
||||
display_name: "Split model retry".to_string(),
|
||||
created_at: "2026-07-13T09:00:00Z".to_string(),
|
||||
},
|
||||
)?;
|
||||
let existing = RepoModelAdmissionReview {
|
||||
schema_version: REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION.to_string(),
|
||||
review_id: "repo-model-review-result-split".to_string(),
|
||||
result_id: Some("result-split".to_string()),
|
||||
job_id: Some("job-split".to_string()),
|
||||
patch_id: "patch-split".to_string(),
|
||||
patch_sha256: "a".repeat(64),
|
||||
base_revision: 4,
|
||||
base_hash: "b".repeat(64),
|
||||
decision: MindGatewayDecision::Accept,
|
||||
evidence_ids: vec!["evidence-split".to_string()],
|
||||
reviewed_at: "2026-07-13T09:00:01Z".to_string(),
|
||||
contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(),
|
||||
repository_body_observation_basis: None,
|
||||
admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult {
|
||||
result_id: "result-split".into(),
|
||||
job_id: "job-split".into(),
|
||||
}),
|
||||
};
|
||||
let mut cache = coordinator_acceptance_cache(&store)?;
|
||||
cache.put(&existing.review_id, &existing)?;
|
||||
cache.put(
|
||||
"repo-model-admission-repo-model-review-result-split",
|
||||
&crate::RepoModelAdmissionReceipt {
|
||||
schema_version: crate::REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.to_string(),
|
||||
receipt_id: "repo-model-admission-repo-model-review-result-split".to_string(),
|
||||
review_id: existing.review_id.clone(),
|
||||
result_id: existing.result_id.clone(),
|
||||
patch_id: existing.patch_id.clone(),
|
||||
patch_sha256: existing.patch_sha256.clone(),
|
||||
previous_revision: 4,
|
||||
previous_hash: existing.base_hash.clone(),
|
||||
admitted_revision: 5,
|
||||
admitted_hash: "c".repeat(64),
|
||||
admitted_at: existing.reviewed_at.clone(),
|
||||
contract: REPO_MODEL_ADMISSION_CONTRACT.to_string(),
|
||||
purpose: crate::RepoModelPatchPurpose::Evolution,
|
||||
frontier_route_id: String::new(),
|
||||
verification_request_id: String::new(),
|
||||
soul_verdict_receipt_id: String::new(),
|
||||
frontier_modeling_request_id: String::new(),
|
||||
proposal_modeling_request_id: String::new(),
|
||||
claim_repair_request_id: String::new(),
|
||||
frontier_plan_decision_id: String::new(),
|
||||
repository_body_observation_basis: None,
|
||||
admission_source: existing.admission_source.clone(),
|
||||
},
|
||||
)?;
|
||||
let mut fresh = existing.clone();
|
||||
fresh.reviewed_at = "2026-07-13T09:05:00Z".to_string();
|
||||
assert_eq!(stable_repo_model_admission_review(&store, fresh)?, existing);
|
||||
|
||||
let state = EpiphanyThreadState::default();
|
||||
let next = EpiphanyThreadState {
|
||||
revision: 1,
|
||||
acceptance_receipts: vec![epiphany_state_model::EpiphanyAcceptanceReceipt {
|
||||
id: "accept-modeling-fresh-nonce".to_string(),
|
||||
result_id: "result-split".to_string(),
|
||||
job_id: "job-split".to_string(),
|
||||
binding_id: "modeling-worker".to_string(),
|
||||
surface: "roleAccept".to_string(),
|
||||
role_id: "modeling".to_string(),
|
||||
status: "accepted".to_string(),
|
||||
accepted_at: "2026-07-13T09:05:00Z".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mind = MindGatewayReview {
|
||||
schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(),
|
||||
gateway_id: "mind-fresh-nonce".to_string(),
|
||||
source_kind: "role".to_string(),
|
||||
source_role_id: "modeling".to_string(),
|
||||
decision: MindGatewayDecision::Accept,
|
||||
allowed_effects: vec!["state".to_string()],
|
||||
refused_effects: Vec::new(),
|
||||
reasons: Vec::new(),
|
||||
contract: "fresh retry".to_string(),
|
||||
};
|
||||
let commit = mind_state_commit_receipt(
|
||||
"mind-commit-fresh-nonce".to_string(),
|
||||
&mind,
|
||||
next.revision,
|
||||
vec!["AcceptanceReceipts".to_string()],
|
||||
"2026-07-13T09:05:00Z".to_string(),
|
||||
);
|
||||
commit_state_with_mind_witness(&store, "thread-split", &state, &next, &mind, &commit, &[])?;
|
||||
let cache = coordinator_acceptance_cache(&store)?;
|
||||
assert_eq!(
|
||||
cache
|
||||
.get_required::<EpiphanyThreadStateEntry>(THREAD_STATE_KEY)?
|
||||
.state()?
|
||||
.acceptance_receipts[0]
|
||||
.id,
|
||||
"accept-modeling-fresh-nonce"
|
||||
);
|
||||
assert_eq!(
|
||||
cache.get_all::<crate::RepoModelAdmissionReceipt>()?.len(),
|
||||
1
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -300,7 +300,7 @@ fn interpret_role_lifecycle_failure(
|
|||
evidence_gaps: Vec::new(),
|
||||
risks: Vec::new(),
|
||||
state_patch: None,
|
||||
repo_model_patch: None,
|
||||
repo_model_mutation_proposal: None,
|
||||
self_patch: None,
|
||||
self_persistence: None,
|
||||
job_error: Some(result.summary.clone()),
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
#[cfg(test)]
|
||||
use crate::runtime_store_backend::RuntimeSpineBackingStore as SingleFileMessagePackBackingStore;
|
||||
use crate::runtime_store_backend::runtime_spine_backing_store;
|
||||
use crate::{
|
||||
EpiphanyThreadStateEntry, THREAD_STATE_KEY, THREAD_STATE_TYPE, coordinator_acceptance_cache,
|
||||
};
|
||||
use crate::runtime_store_backend::runtime_spine_backing_store;
|
||||
#[cfg(test)]
|
||||
use crate::runtime_store_backend::RuntimeSpineBackingStore as SingleFileMessagePackBackingStore;
|
||||
use anyhow::{Result, anyhow};
|
||||
#[cfg(test)]
|
||||
use cultcache_rs::CacheBackingStore;
|
||||
|
|
|
|||
|
|
@ -4231,6 +4231,9 @@ pub fn default_epiphany_cultmesh_swarm_brake(
|
|||
"persona.public_speech".to_string(),
|
||||
"daemon.tool_invocation".to_string(),
|
||||
"daemon.lifecycle_poke".to_string(),
|
||||
"atlas.publish".to_string(),
|
||||
"atlas.project".to_string(),
|
||||
"atlas.impact_ingress".to_string(),
|
||||
],
|
||||
created_at_utc: generated_at_utc.into(),
|
||||
expires_at_utc: None,
|
||||
|
|
@ -4257,6 +4260,9 @@ pub fn canonical_epiphany_swarm_brake_protected_surfaces() -> Vec<String> {
|
|||
"persona.public_speech".to_string(),
|
||||
"daemon.tool_invocation".to_string(),
|
||||
"daemon.lifecycle_poke".to_string(),
|
||||
"atlas.publish".to_string(),
|
||||
"atlas.project".to_string(),
|
||||
"atlas.impact_ingress".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -9829,11 +9835,7 @@ mod tests {
|
|||
);
|
||||
assert!(load_epiphany_cultmesh_cluster_topology(&store, "epiphany-test")?.is_empty());
|
||||
assert_eq!(
|
||||
load_epiphany_cultmesh_daemon_status(
|
||||
&store,
|
||||
"epiphany-test",
|
||||
"epiphany-daemon-hands"
|
||||
)?,
|
||||
load_epiphany_cultmesh_daemon_status(&store, "epiphany-test", "epiphany-daemon-hands")?,
|
||||
None
|
||||
);
|
||||
assert!(load_epiphany_cultmesh_daemon_liveness(&store, "epiphany-test")?.is_empty());
|
||||
|
|
@ -9873,11 +9875,7 @@ mod tests {
|
|||
.expect("Hands daemon status exists");
|
||||
|
||||
assert_eq!(
|
||||
load_epiphany_cultmesh_daemon_status(
|
||||
&store,
|
||||
"epiphany-test",
|
||||
"epiphany-daemon-hands"
|
||||
)?,
|
||||
load_epiphany_cultmesh_daemon_status(&store, "epiphany-test", "epiphany-daemon-hands")?,
|
||||
Some(expected)
|
||||
);
|
||||
assert_eq!(
|
||||
|
|
|
|||
|
|
@ -294,7 +294,7 @@ mod tests {
|
|||
evidence_gaps: Vec::new(),
|
||||
risks: Vec::new(),
|
||||
state_patch: None,
|
||||
repo_model_patch: None,
|
||||
repo_model_mutation_proposal: None,
|
||||
self_patch: None,
|
||||
self_persistence: None,
|
||||
job_error: None,
|
||||
|
|
|
|||
|
|
@ -18,9 +18,8 @@ pub const HANDS_COMMIT_RECEIPT_SCHEMA_VERSION: &str = "epiphany.hands.commit_rec
|
|||
pub const HANDS_PR_RECEIPT_SCHEMA_VERSION: &str = "epiphany.hands.pr_receipt.v0";
|
||||
pub const HANDS_ROLLBACK_RECEIPT_SCHEMA_VERSION: &str = "epiphany.hands.rollback_receipt.v0";
|
||||
pub const HANDS_ACTION_REFUSAL_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.hands.action_refusal_receipt.v0";
|
||||
pub const HANDS_ACTION_REFUSAL_RECEIPT_CONTRACT: &str =
|
||||
"epiphany.hands.action_refusal.v0";
|
||||
"epiphany.hands.action_refusal_receipt.v1";
|
||||
pub const HANDS_ACTION_REFUSAL_RECEIPT_CONTRACT: &str = "epiphany.hands.action_refusal.v1";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(type = "epiphany.hands.action_intent", schema = "HandsActionIntent")]
|
||||
|
|
@ -99,9 +98,9 @@ pub struct HandsActionRefusalReceipt {
|
|||
#[cultcache(key = 6)]
|
||||
pub substrate_gate_grant_receipt_id: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 9)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 10)]
|
||||
|
|
|
|||
|
|
@ -4,10 +4,10 @@ use serde::{Deserialize, Serialize};
|
|||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
|
||||
pub const REQUEST_SCHEMA: &str = "epiphany.self.imagination_consideration_request.v0";
|
||||
pub const REQUEST_CONTRACT: &str = "epiphany.imagination_consideration_request.v0";
|
||||
pub const CANDIDATE_SCHEMA: &str = "epiphany.imagination.consideration_candidate.v0";
|
||||
pub const CANDIDATE_CONTRACT: &str = "epiphany.imagination_consideration_candidate.v0";
|
||||
pub const REQUEST_SCHEMA: &str = "epiphany.self.imagination_consideration_request.v1";
|
||||
pub const REQUEST_CONTRACT: &str = "epiphany.imagination_consideration_request.v1";
|
||||
pub const CANDIDATE_SCHEMA: &str = "epiphany.imagination.consideration_candidate.v1";
|
||||
pub const CANDIDATE_CONTRACT: &str = "epiphany.imagination_consideration_candidate.v1";
|
||||
pub const LAUNCH_BINDING_SCHEMA: &str =
|
||||
"epiphany.coordinator.imagination_consideration_launch_binding.v0";
|
||||
pub const REVIEW_REQUEST_SCHEMA: &str = "epiphany.self.imagination_consideration_review_request.v0";
|
||||
|
|
@ -62,11 +62,9 @@ pub struct ImaginationConsiderationRequest {
|
|||
#[cultcache(key = 9)]
|
||||
pub persona_id: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub model_hash: String,
|
||||
#[cultcache(key = 12)]
|
||||
pub model_admission_receipt_id: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 13)]
|
||||
pub routing_policy_id: String,
|
||||
#[cultcache(key = 14)]
|
||||
|
|
@ -120,9 +118,9 @@ pub struct ImaginationConsiderationCandidate {
|
|||
#[cultcache(key = 4)]
|
||||
pub feedback_packet_sha256: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 7)]
|
||||
pub disposition: ImaginationConsiderationDisposition,
|
||||
#[cultcache(key = 8)]
|
||||
|
|
@ -217,17 +215,7 @@ pub fn commit_request(
|
|||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let model = crate::runtime_current_repo_model(runtime_store)?
|
||||
.ok_or_else(|| anyhow!("consideration requires Modeling map"))?;
|
||||
let model_hash = crate::memory_graph_model_hash(&model)?;
|
||||
let receipts = cache
|
||||
.get_all::<crate::RepoModelAdmissionReceipt>()?
|
||||
.into_iter()
|
||||
.filter(|r| r.admitted_revision == model.model_revision && r.admitted_hash == model_hash)
|
||||
.collect::<Vec<_>>();
|
||||
if receipts.len() != 1 {
|
||||
bail!("consideration requires one current model receipt");
|
||||
}
|
||||
let model_basis = crate::assemble_repo_model_view(runtime_store)?.reasoning_basis();
|
||||
let feedback = crate::admitted_persona_feedback(persona_feedback_store, &identity.runtime_id)?
|
||||
.into_iter()
|
||||
.find(|f| f.feedback_id == feedback_id)
|
||||
|
|
@ -239,9 +227,7 @@ pub fn commit_request(
|
|||
&feedback.feedback_id,
|
||||
&feedback.admission_id,
|
||||
&feedback.packet_sha256,
|
||||
model.model_revision,
|
||||
&model_hash,
|
||||
&receipts[0].receipt_id,
|
||||
&model_basis,
|
||||
routing_policy_id,
|
||||
))?;
|
||||
let request_id = format!("imagination-consideration-{:x}", Sha256::digest(causal));
|
||||
|
|
@ -259,9 +245,8 @@ pub fn commit_request(
|
|||
thread_id: thread.thread_id,
|
||||
repository: repository.into(),
|
||||
persona_id: persona_id.into(),
|
||||
model_revision: model.model_revision,
|
||||
model_hash,
|
||||
model_admission_receipt_id: receipts[0].receipt_id.clone(),
|
||||
model_projection_digest: model_basis.projection_digest,
|
||||
model_source_documents: model_basis.source_documents,
|
||||
routing_policy_id: routing_policy_id.into(),
|
||||
question: ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions,
|
||||
quoted_evidence: QuotedPersonaFeedbackEvidence {
|
||||
|
|
@ -321,26 +306,11 @@ pub fn validate_current_request(
|
|||
&request.quoted_evidence.source_visibility,
|
||||
&request.quoted_evidence.data_classification,
|
||||
)?;
|
||||
let model = cache
|
||||
.get::<crate::EpiphanyMemoryGraphEntry>(crate::MEMORY_GRAPH_KEY)?
|
||||
.ok_or_else(|| anyhow!("consideration model disappeared"))?
|
||||
.snapshot()?;
|
||||
if request.model_revision != model.model_revision
|
||||
|| request.model_hash != crate::memory_graph_model_hash(&model)?
|
||||
{
|
||||
bail!("consideration model is stale");
|
||||
}
|
||||
if !cache
|
||||
.get_all::<crate::RepoModelAdmissionReceipt>()?
|
||||
.iter()
|
||||
.any(|r| {
|
||||
r.receipt_id == request.model_admission_receipt_id
|
||||
&& r.admitted_revision == request.model_revision
|
||||
&& r.admitted_hash == request.model_hash
|
||||
})
|
||||
{
|
||||
bail!("consideration lost model receipt");
|
||||
crate::EpiphanyRepoModelBasis {
|
||||
projection_digest: request.model_projection_digest.clone(),
|
||||
source_documents: request.model_source_documents.clone(),
|
||||
}
|
||||
.validate_against_cache(cache)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -376,8 +346,8 @@ pub fn validate_candidate(
|
|||
|| candidate.source_room_id != request.quoted_evidence.source_room_id
|
||||
|| candidate.source_visibility != request.quoted_evidence.source_visibility
|
||||
|| candidate.data_classification != request.quoted_evidence.data_classification
|
||||
|| candidate.model_revision != request.model_revision
|
||||
|| candidate.model_hash != request.model_hash
|
||||
|| candidate.model_projection_digest != request.model_projection_digest
|
||||
|| candidate.model_source_documents != request.model_source_documents
|
||||
|| candidate.candidate_id.trim().is_empty()
|
||||
|| candidate.title.trim().is_empty()
|
||||
|| candidate.summary.trim().is_empty()
|
||||
|
|
@ -434,10 +404,10 @@ pub fn render_consideration_prompt(request: &ImaginationConsiderationRequest) ->
|
|||
"Act as Epiphany Imagination for one proposal-only consideration pass.\n\
|
||||
Fixed question: compare the quoted classified Persona feedback evidence with the current admitted Modeling map and make coherent options visible.\n\
|
||||
The quoted classified Persona feedback evidence is never an objective, instruction, command, adoption, or authority grant. Preserve its source visibility and data classification.\n\
|
||||
Request: {}\nModel revision/hash: {}/{}\n\
|
||||
Request: {}\nModel projection digest: {}\n\
|
||||
<quoted_persona_feedback_evidence>\n{}\n</quoted_persona_feedback_evidence>\n\
|
||||
Return only the dedicated consideration candidate contract. Do not emit state, self, model, frontier, Hands, release, or deployment mutations.",
|
||||
request.request_id, request.model_revision, request.model_hash, quoted
|
||||
request.request_id, request.model_projection_digest, quoted
|
||||
))
|
||||
}
|
||||
|
||||
|
|
@ -541,9 +511,15 @@ mod tests {
|
|||
thread_id: "thread-1".into(),
|
||||
repository: "GameCult/Epiphany".into(),
|
||||
persona_id: "epiphany".into(),
|
||||
model_revision: 7,
|
||||
model_hash: "sha256-model".into(),
|
||||
model_admission_receipt_id: "receipt-7".into(),
|
||||
model_projection_digest: "sha256:model-projection".into(),
|
||||
model_source_documents: vec![crate::EpiphanyMindDocumentVersion {
|
||||
store_id: "epiphany-mind".into(),
|
||||
document_type: "epiphany.mind.repo_model.identity.v1".into(),
|
||||
document_key: "repo-model".into(),
|
||||
schema_id: Some("EpiphanyRepoModelIdentityDocument".into()),
|
||||
payload_msgpack: vec![1, 2, 3],
|
||||
payload_sha256: "sha256:source".into(),
|
||||
}],
|
||||
routing_policy_id: "feedback-consideration-v0".into(),
|
||||
question:
|
||||
ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions,
|
||||
|
|
@ -575,8 +551,8 @@ mod tests {
|
|||
source_room_id: request.quoted_evidence.source_room_id.clone(),
|
||||
source_visibility: request.quoted_evidence.source_visibility.clone(),
|
||||
data_classification: request.quoted_evidence.data_classification.clone(),
|
||||
model_revision: request.model_revision,
|
||||
model_hash: request.model_hash,
|
||||
model_projection_digest: request.model_projection_digest,
|
||||
model_source_documents: request.model_source_documents,
|
||||
disposition,
|
||||
title: "Map clarity".into(),
|
||||
summary: "Possible improvement".into(),
|
||||
|
|
@ -603,12 +579,12 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn substituted_feedback_or_model_is_rejected() {
|
||||
for mutation in 0..2 {
|
||||
for mutation in 0..3 {
|
||||
let mut candidate = candidate(ImaginationConsiderationDisposition::Suggest);
|
||||
if mutation == 0 {
|
||||
candidate.feedback_packet_sha256 = "attacker".into();
|
||||
} else {
|
||||
candidate.model_hash = "stale".into();
|
||||
match mutation {
|
||||
0 => candidate.feedback_packet_sha256 = "attacker".into(),
|
||||
1 => candidate.model_projection_digest = "sha256:stale".into(),
|
||||
_ => candidate.model_source_documents.clear(),
|
||||
}
|
||||
assert!(validate_candidate(&request(), &candidate).is_err());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
mod agent_launch;
|
||||
mod agent_memory;
|
||||
mod agent_utterance_state;
|
||||
pub mod atlas;
|
||||
mod causal_work_identity;
|
||||
mod continuity_gateway;
|
||||
mod coordinator_acceptance;
|
||||
|
|
@ -22,8 +23,8 @@ mod idunn_provider_health;
|
|||
mod idunn_runtime_health;
|
||||
mod imagination_consideration;
|
||||
mod memory_graph;
|
||||
mod mind_gateway;
|
||||
mod mind_documents;
|
||||
mod mind_gateway;
|
||||
mod operator_command;
|
||||
mod operator_command_service;
|
||||
mod organ_dependencies;
|
||||
|
|
@ -35,17 +36,17 @@ mod persona_feedback_admission;
|
|||
mod persona_turn;
|
||||
mod process_observation;
|
||||
mod promotion;
|
||||
mod public_source_identity;
|
||||
mod prompt_context;
|
||||
mod proposal;
|
||||
mod public_source_identity;
|
||||
mod reasoning_context;
|
||||
mod repo_model_documents;
|
||||
mod repo_model_gateway;
|
||||
mod repository_body_observer;
|
||||
mod repo_model_documents;
|
||||
mod repository_readiness;
|
||||
mod resident_readiness;
|
||||
mod resident_self;
|
||||
mod runtime_spine;
|
||||
mod reasoning_context;
|
||||
mod runtime_store_backend;
|
||||
mod runtime_store_migration;
|
||||
mod runtime_worker_attempt;
|
||||
|
|
@ -114,8 +115,8 @@ pub use agent_launch::epiphany_agent_prompt_with_memory;
|
|||
pub use agent_launch::epiphany_frontier_plan_mind_output_schema;
|
||||
pub use agent_launch::epiphany_frontier_planning_output_schema;
|
||||
pub use agent_launch::epiphany_frontier_verdict_modeling_output_schema;
|
||||
pub use agent_launch::epiphany_proposal_modeling_output_schema;
|
||||
pub use agent_launch::epiphany_imagination_consideration_output_schema;
|
||||
pub use agent_launch::epiphany_proposal_modeling_output_schema;
|
||||
pub use agent_launch::epiphany_reorient_launch_output_schema;
|
||||
pub use agent_launch::epiphany_role_binding_id;
|
||||
pub use agent_launch::epiphany_role_label;
|
||||
|
|
@ -195,8 +196,9 @@ pub use agent_utterance_state::AgentUtterancePersonalityVectors;
|
|||
pub use agent_utterance_state::AgentUtteranceState;
|
||||
pub use agent_utterance_state::AgentUtteranceValue;
|
||||
pub use agent_utterance_state::WEKSA_UTTERANCE_HANDOFF_SCHEMA_VERSION;
|
||||
pub use causal_work_identity::*;
|
||||
pub use agent_utterance_state::derive_agent_utterance_state;
|
||||
pub use atlas::*;
|
||||
pub use causal_work_identity::*;
|
||||
pub use continuity_gateway::*;
|
||||
pub use coordinator_acceptance::EpiphanyAcceptancePrerequisite;
|
||||
pub use coordinator_acceptance::EpiphanyCoordinatorAdmissionError;
|
||||
|
|
@ -235,6 +237,7 @@ pub use coordinator_launch_context::render_launch_dynamic_prompt_context;
|
|||
pub use coordinator_launch_context::render_modeling_launch_dynamic_prompt_context;
|
||||
pub use coordinator_launch_context::reorient_launch_context_focus;
|
||||
pub use coordinator_launch_context::role_launch_context_focus;
|
||||
pub use coordinator_launch_context::validate_frontier_plan_decision_chain;
|
||||
pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_CONTRACT;
|
||||
pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_SCHEMA_VERSION;
|
||||
pub use coordinator_objective_intake::USER_OBJECTIVE_INTAKE_TYPE;
|
||||
|
|
@ -495,9 +498,9 @@ pub use cultmesh_integration::load_epiphany_cultmesh_daemon_poke_intent;
|
|||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_poke_receipt;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_restart_policy;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_restart_policy_directory;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_status;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_service_lifecycle_receipt;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_service_lifecycle_receipts;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_status;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_daemon_tool_directory;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_eve_surface_directory;
|
||||
pub use cultmesh_integration::load_epiphany_cultmesh_idunn_aftercare_audit_receipt;
|
||||
|
|
@ -746,15 +749,12 @@ pub use imagination_consideration::{
|
|||
};
|
||||
pub use memory_graph::EpiphanyMemoryEdgeKind;
|
||||
pub use memory_graph::EpiphanyMemoryEmbeddingManifest;
|
||||
pub use memory_graph::EpiphanyMemoryGraphEntry;
|
||||
pub use memory_graph::EpiphanyMemoryGraphSnapshot;
|
||||
pub use memory_graph::EpiphanyMemoryGraphValidationError;
|
||||
pub use memory_graph::EpiphanyMemoryLifecycleReceipt;
|
||||
pub use memory_graph::EpiphanyMemoryNodeKind;
|
||||
pub use memory_graph::EpiphanyMemoryPatchCandidate;
|
||||
pub use memory_graph::MEMORY_GRAPH_KEY;
|
||||
pub use memory_graph::MEMORY_GRAPH_SCHEMA_VERSION;
|
||||
pub use memory_graph::MEMORY_GRAPH_TYPE;
|
||||
pub use memory_graph::MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION;
|
||||
pub use memory_graph::MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION;
|
||||
pub use memory_graph::MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION;
|
||||
pub use memory_graph::MEMORY_SEMANTIC_PROJECTION_CLAIM_SCHEMA_VERSION;
|
||||
|
|
@ -788,9 +788,6 @@ pub use memory_graph::RepoFrontierExecutionAmendment;
|
|||
pub use memory_graph::RepoFrontierItem;
|
||||
pub use memory_graph::RepoFrontierStatus;
|
||||
pub use memory_graph::RepoMemoryGraphRefresh;
|
||||
pub use memory_graph::RepoModelPatch;
|
||||
pub use memory_graph::RepoModelPatchOperation;
|
||||
pub use memory_graph::RepoModelPatchPurpose;
|
||||
pub use memory_graph::SEMANTIC_PROJECTION_SCHEMA_VERSION;
|
||||
pub use memory_graph::SemanticCanonicalLocator;
|
||||
pub use memory_graph::SemanticDocumentKind;
|
||||
|
|
@ -809,17 +806,13 @@ pub use memory_graph::compose_memory_graph_snapshots;
|
|||
pub use memory_graph::derive_memory_graph_freshness;
|
||||
pub use memory_graph::derive_memory_semantic_projection_health;
|
||||
pub use memory_graph::derive_memory_semantic_projection_obligation;
|
||||
pub use memory_graph::derive_repo_model_patch;
|
||||
pub use memory_graph::derive_semantic_projection;
|
||||
pub use memory_graph::execute_memory_semantic_physical_retirement;
|
||||
#[cfg(feature = "semantic-recovery-smoke")]
|
||||
pub use memory_graph::inspect_memory_semantic_recovery_for_smoke;
|
||||
pub use memory_graph::lifecycle_allowed_for_profile;
|
||||
pub use memory_graph::load_memory_graph_entry;
|
||||
pub use memory_graph::load_memory_graph_snapshot;
|
||||
pub use memory_graph::load_memory_semantic_projection_readiness;
|
||||
pub use memory_graph::load_memory_semantic_projection_success;
|
||||
pub use memory_graph::memory_graph_cache;
|
||||
pub use memory_graph::memory_graph_domain_id;
|
||||
pub use memory_graph::memory_graph_edge_id;
|
||||
pub use memory_graph::memory_graph_from_agent_memories;
|
||||
|
|
@ -840,12 +833,10 @@ pub use memory_graph::retire_orphaned_memory_semantic_projection_attempts_v0;
|
|||
pub use memory_graph::retire_unowned_memory_semantic_index_receipts;
|
||||
pub use memory_graph::semantic_memory_context;
|
||||
pub use memory_graph::semantic_point_id;
|
||||
pub use memory_graph::validate_memory_graph_entry;
|
||||
pub use memory_graph::validate_memory_graph_snapshot;
|
||||
pub use memory_graph::validate_memory_semantic_projection_attempt;
|
||||
pub use memory_graph::validate_memory_semantic_projection_obligation;
|
||||
pub use memory_graph::write_memory_graph_entry;
|
||||
pub use memory_graph::write_memory_graph_snapshot;
|
||||
pub use mind_documents::*;
|
||||
pub use mind_gateway::MIND_GATEWAY_REVIEW_SCHEMA_VERSION;
|
||||
pub use mind_gateway::MIND_GATEWAY_REVIEW_TYPE;
|
||||
pub use mind_gateway::MIND_INTERPRETER_PROMPT_SCHEMA_VERSION;
|
||||
|
|
@ -929,10 +920,10 @@ pub use persona_feedback_admission::{
|
|||
PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION, PersonaFeedbackHeartbeatBridgeReceipt,
|
||||
PersonaFeedbackPacket, admit_bifrost_persona_feedback, admitted_persona_feedback,
|
||||
apply_bifrost_persona_feedback_snapshot, bridge_admitted_persona_feedback_to_heartbeat,
|
||||
bridged_persona_feedback_ready_for_cognition,
|
||||
import_bifrost_persona_feedback_deliveries, persona_feedback_admission_signing_payload,
|
||||
persona_feedback_admission_signing_purpose, persona_feedback_packet_sha256,
|
||||
validate_bifrost_persona_feedback_source, validate_persona_feedback_store_separation,
|
||||
bridged_persona_feedback_ready_for_cognition, import_bifrost_persona_feedback_deliveries,
|
||||
persona_feedback_admission_signing_payload, persona_feedback_admission_signing_purpose,
|
||||
persona_feedback_packet_sha256, validate_bifrost_persona_feedback_source,
|
||||
validate_persona_feedback_store_separation,
|
||||
};
|
||||
pub use persona_turn::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION;
|
||||
pub use persona_turn::PERSONA_INTERPRETER_EFFECT_SET_SCHEMA_VERSION;
|
||||
|
|
@ -972,7 +963,6 @@ pub use process_observation::observe_native_process;
|
|||
pub use process_observation::observe_process_instance;
|
||||
pub use process_observation::reap_exited_child_process;
|
||||
pub use process_observation::terminate_process_instance;
|
||||
pub use public_source_identity::ImmutableGithubSource;
|
||||
pub use promotion::EpiphanyPromotionDecision;
|
||||
pub use promotion::EpiphanyPromotionInput;
|
||||
pub use promotion::EpiphanyStateReplacementValidationInput;
|
||||
|
|
@ -983,22 +973,26 @@ pub use prompt_context::render_epiphany_prompt_context;
|
|||
pub use proposal::EpiphanyMapProposal;
|
||||
pub use proposal::EpiphanyMapProposalInput;
|
||||
pub use proposal::propose_map_update;
|
||||
pub use public_source_identity::ImmutableGithubSource;
|
||||
pub use reasoning_context::*;
|
||||
pub use repo_model_documents::*;
|
||||
pub use repo_model_gateway::*;
|
||||
pub use repository_body_observer::*;
|
||||
pub use repo_model_documents::*;
|
||||
pub use repository_readiness::*;
|
||||
pub use resident_readiness::*;
|
||||
pub use resident_self::*;
|
||||
pub use runtime_spine::ARCHIVED_RUNTIME_SESSION_SCHEMA_VERSION;
|
||||
pub use reasoning_context::*;
|
||||
pub use mind_documents::*;
|
||||
pub use runtime_spine::ARCHIVED_RUNTIME_SESSION_TYPE;
|
||||
pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION;
|
||||
pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_TYPE;
|
||||
pub use runtime_spine::COORDINATOR_DEATH_RECOVERY_SCHEMA_VERSION;
|
||||
pub use runtime_spine::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION;
|
||||
pub use runtime_spine::COORDINATOR_RUN_RECEIPT_TYPE;
|
||||
pub use runtime_spine::COORDINATOR_DEATH_RECOVERY_SCHEMA_VERSION;
|
||||
pub use runtime_spine::EPIPHANY_RUNTIME_ROOT_SESSION_ID;
|
||||
pub use runtime_spine::EpiphanyArchivedRuntimeSession;
|
||||
pub use runtime_spine::EpiphanyCoordinatorRunReceipt;
|
||||
pub use runtime_spine::EpiphanyArchivedRuntimeWorkerAttempt;
|
||||
pub use runtime_spine::EpiphanyCoordinatorDeathRecovery;
|
||||
pub use runtime_spine::EpiphanyCoordinatorRunReceipt;
|
||||
pub use runtime_spine::EpiphanyCoordinatorRunReceiptRetentionHead;
|
||||
pub use runtime_spine::EpiphanyJobInterruptRequest;
|
||||
pub use runtime_spine::EpiphanyJobInterruptResult;
|
||||
|
|
@ -1020,12 +1014,9 @@ pub use runtime_spine::EpiphanyRuntimeSwarmBinding;
|
|||
pub use runtime_spine::EpiphanyRuntimeToolExecutionBinding;
|
||||
pub use runtime_spine::EpiphanyRuntimeWorkerLaunchRequest;
|
||||
pub use runtime_spine::EpiphanyRuntimeWorkerProcessClaim;
|
||||
pub use runtime_spine::runtime_worker_process_claims;
|
||||
pub use runtime_spine::EpiphanyArchivedRuntimeWorkerAttempt;
|
||||
pub use runtime_spine::EpiphanyToolInvocationStatus;
|
||||
pub use runtime_spine::PreparedRuntimeSpineHeartbeatJob;
|
||||
pub use runtime_spine::RUNTIME_EVENT_TYPE;
|
||||
pub use runtime_spine::EPIPHANY_RUNTIME_ROOT_SESSION_ID;
|
||||
pub use runtime_spine::RUNTIME_IDENTITY_KEY;
|
||||
pub use runtime_spine::RUNTIME_IDENTITY_TYPE;
|
||||
pub use runtime_spine::RUNTIME_JOB_RESULT_TYPE;
|
||||
|
|
@ -1046,12 +1037,10 @@ pub use runtime_spine::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION;
|
|||
pub use runtime_spine::RUNTIME_WORKER_LAUNCH_REQUEST_TYPE;
|
||||
pub use runtime_spine::RUNTIME_WORKER_PROCESS_CLAIM_SCHEMA_VERSION;
|
||||
pub use runtime_spine::RUNTIME_WORKER_PROCESS_CLAIM_TYPE;
|
||||
pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_SCHEMA_VERSION;
|
||||
pub use runtime_spine::ARCHIVED_RUNTIME_WORKER_ATTEMPT_TYPE;
|
||||
pub use runtime_spine::RepoFrontierVerdictModelingLaunchAuthority;
|
||||
pub use runtime_spine::RepoFrontierResearchLifecycle;
|
||||
pub use runtime_spine::RepoFrontierResearchContinuationAction;
|
||||
pub use runtime_spine::RepoFrontierResearchLifecycle;
|
||||
pub use runtime_spine::RepoFrontierResearchLifecycleStage;
|
||||
pub use runtime_spine::RepoFrontierVerdictModelingLaunchAuthority;
|
||||
pub use runtime_spine::RuntimeHandsReceiptChainSummary;
|
||||
pub use runtime_spine::RuntimeSpineEventOptions;
|
||||
pub use runtime_spine::RuntimeSpineHeartbeatJobOptions;
|
||||
|
|
@ -1063,11 +1052,10 @@ pub use runtime_spine::RuntimeSpineJobResultOptions;
|
|||
pub use runtime_spine::RuntimeSpineSessionClosureOptions;
|
||||
pub use runtime_spine::RuntimeSpineSessionOptions;
|
||||
pub use runtime_spine::RuntimeTypedFulfillmentEvidence;
|
||||
pub use runtime_worker_attempt::{RuntimeTypedRequestRef, WorkerProcessStatus};
|
||||
pub use runtime_spine::amend_repo_frontier_execution;
|
||||
pub use runtime_spine::append_runtime_event;
|
||||
pub use runtime_spine::abandon_unactivated_runtime_worker_process;
|
||||
pub use runtime_spine::activate_runtime_worker_process;
|
||||
pub use runtime_spine::amend_repo_frontier_execution;
|
||||
pub use runtime_spine::append_runtime_event;
|
||||
pub use runtime_spine::archive_completed_coordinator_session;
|
||||
pub use runtime_spine::archive_completed_model_session;
|
||||
pub use runtime_spine::archive_failed_runtime_worker_attempt;
|
||||
|
|
@ -1075,15 +1063,14 @@ pub use runtime_spine::archive_fulfilled_runtime_worker_attempt;
|
|||
pub use runtime_spine::bind_runtime_repository_domain;
|
||||
pub use runtime_spine::bind_runtime_to_agent_memory_swarm;
|
||||
pub use runtime_spine::canonical_repo_frontier_plan_candidate_id;
|
||||
pub use runtime_spine::clear_epiphany_job_binding_backend;
|
||||
pub use runtime_spine::claim_runtime_worker_process;
|
||||
pub use runtime_spine::clear_epiphany_job_binding_backend;
|
||||
pub use runtime_spine::close_runtime_session;
|
||||
pub use runtime_spine::commit_operator_repo_frontier_plan_review;
|
||||
pub use runtime_spine::commit_repo_frontier_modeling_request;
|
||||
pub use runtime_spine::commit_repo_frontier_plan_decision;
|
||||
pub use runtime_spine::commit_repo_frontier_plan_mind_request;
|
||||
pub use runtime_spine::commit_repo_frontier_verification_request_for_chain;
|
||||
pub use runtime_spine::commit_repo_model_admission;
|
||||
pub use runtime_spine::commit_repo_model_claim_challenge;
|
||||
pub use runtime_spine::commit_repo_model_claim_repair_request;
|
||||
pub use runtime_spine::complete_runtime_job;
|
||||
|
|
@ -1091,13 +1078,11 @@ pub use runtime_spine::coordinator_run_receipts;
|
|||
pub use runtime_spine::coordinator_run_session_id;
|
||||
pub use runtime_spine::create_runtime_job;
|
||||
pub use runtime_spine::create_runtime_session;
|
||||
pub use runtime_spine::ensure_runtime_repo_model;
|
||||
pub use runtime_spine::ensure_runtime_session;
|
||||
pub use runtime_spine::finalize_coordinator_run;
|
||||
pub use runtime_spine::initialize_runtime_spine;
|
||||
pub use runtime_spine::open_coordinator_run;
|
||||
pub use runtime_spine::intake_user_repo_frontier_proposal;
|
||||
pub use runtime_spine::migrate_legacy_repo_model_projection_obligation;
|
||||
pub use runtime_spine::open_coordinator_run;
|
||||
pub use runtime_spine::open_runtime_model_execution;
|
||||
pub use runtime_spine::open_runtime_spine_heartbeat_job;
|
||||
pub use runtime_spine::operator_repo_frontier_plan_review_is_current;
|
||||
|
|
@ -1113,20 +1098,14 @@ pub use runtime_spine::put_hands_commit_receipt;
|
|||
pub use runtime_spine::put_hands_patch_receipt;
|
||||
#[cfg(test)]
|
||||
pub use runtime_spine::put_hands_pr_receipt;
|
||||
#[cfg(test)]
|
||||
pub(crate) use runtime_spine::put_mind_gateway_review;
|
||||
#[cfg(test)]
|
||||
pub(crate) use runtime_spine::put_mind_state_commit_receipt;
|
||||
pub use runtime_spine::put_repo_frontier_hands_authority;
|
||||
pub use runtime_spine::put_repo_frontier_verification_request;
|
||||
pub use runtime_spine::put_repo_frontier_work_proposal;
|
||||
pub use runtime_spine::put_runtime_reorient_worker_result;
|
||||
pub use runtime_spine::put_runtime_role_worker_result;
|
||||
pub use runtime_spine::put_runtime_requested_public_source_intents;
|
||||
pub use runtime_spine::put_runtime_role_worker_result;
|
||||
pub use runtime_spine::put_runtime_tool_execution_intent;
|
||||
pub use runtime_spine::put_runtime_tool_execution_receipt;
|
||||
pub use runtime_spine::runtime_authenticated_public_source_lookups_for_worker;
|
||||
pub use runtime_spine::runtime_requested_public_source_refs_for_worker;
|
||||
#[cfg(test)]
|
||||
pub(crate) use runtime_spine::put_soul_verdict_receipt;
|
||||
pub use runtime_spine::put_substrate_gate_repo_access_grant_receipt;
|
||||
|
|
@ -1139,6 +1118,7 @@ pub use runtime_spine::retain_completed_runtime_sessions;
|
|||
pub use runtime_spine::retain_coordinator_run_receipts;
|
||||
pub use runtime_spine::retain_failed_runtime_worker_attempts;
|
||||
pub use runtime_spine::retain_fulfilled_runtime_worker_attempts;
|
||||
pub use runtime_spine::runtime_authenticated_public_source_lookups_for_worker;
|
||||
pub use runtime_spine::runtime_continuity_recovery_receipt;
|
||||
pub use runtime_spine::runtime_current_repo_model;
|
||||
pub use runtime_spine::runtime_eyes_evidence_packet;
|
||||
|
|
@ -1151,9 +1131,9 @@ pub use runtime_spine::runtime_hands_pr_receipt;
|
|||
pub use runtime_spine::runtime_hands_receipt_chain_after;
|
||||
pub use runtime_spine::runtime_hands_receipt_chain_matches_current_model;
|
||||
pub use runtime_spine::runtime_has_actionable_eyes_frontier;
|
||||
pub use runtime_spine::runtime_has_uncovered_actionable_eyes_frontier;
|
||||
pub use runtime_spine::runtime_has_actionable_hands_frontier;
|
||||
pub use runtime_spine::runtime_has_actionable_imagination_frontier;
|
||||
pub use runtime_spine::runtime_has_uncovered_actionable_eyes_frontier;
|
||||
pub use runtime_spine::runtime_hello_frame;
|
||||
pub use runtime_spine::runtime_job_snapshot;
|
||||
pub use runtime_spine::runtime_latest_hands_receipt_chain_after;
|
||||
|
|
@ -1164,17 +1144,16 @@ pub use runtime_spine::runtime_modeling_semantic_projection_input;
|
|||
pub use runtime_spine::runtime_pending_repo_frontier_proposal_modeling_request;
|
||||
pub use runtime_spine::runtime_registered_document_types;
|
||||
pub use runtime_spine::runtime_reorient_worker_result;
|
||||
pub use runtime_spine::runtime_repo_frontier_execution_amendment_for_admission;
|
||||
pub use runtime_spine::runtime_repo_frontier_research_lifecycle;
|
||||
pub use runtime_spine::runtime_repo_frontier_execution_amendment;
|
||||
pub use runtime_spine::runtime_repo_frontier_plan_decision;
|
||||
pub use runtime_spine::runtime_repo_frontier_planning_eligibility;
|
||||
pub use runtime_spine::runtime_repo_frontier_planning_lifecycle;
|
||||
pub use runtime_spine::runtime_repo_frontier_proposal_modeling_request;
|
||||
pub use runtime_spine::runtime_repo_frontier_research_lifecycle;
|
||||
pub use runtime_spine::runtime_repo_frontier_route;
|
||||
pub use runtime_spine::runtime_repo_frontier_verification_request;
|
||||
pub use runtime_spine::runtime_repo_frontier_work_proposal;
|
||||
pub use runtime_spine::runtime_repo_model_admission_receipt;
|
||||
pub use runtime_spine::runtime_repo_model_admission_review;
|
||||
pub use runtime_spine::runtime_requested_public_source_refs_for_worker;
|
||||
pub use runtime_spine::runtime_role_worker_result;
|
||||
pub use runtime_spine::runtime_schema_catalog_response;
|
||||
pub use runtime_spine::runtime_soul_verdict_receipt;
|
||||
|
|
@ -1183,11 +1162,12 @@ pub use runtime_spine::runtime_spine_status;
|
|||
pub use runtime_spine::runtime_substrate_gate_repo_access_grant_receipt;
|
||||
pub use runtime_spine::runtime_swarm_binding;
|
||||
pub use runtime_spine::runtime_tool_invocation_statuses;
|
||||
pub use runtime_spine::runtime_typed_request_fulfillment;
|
||||
pub use runtime_spine::runtime_typed_request_attempt_exists;
|
||||
pub use runtime_spine::runtime_typed_request_fulfillment;
|
||||
pub use runtime_spine::runtime_worker_launch_body_basis;
|
||||
pub use runtime_spine::runtime_worker_launch_request;
|
||||
pub use runtime_spine::runtime_worker_process_claim;
|
||||
pub use runtime_spine::runtime_worker_process_claims;
|
||||
pub use runtime_spine::select_and_commit_repo_frontier_planning_request;
|
||||
pub use runtime_spine::select_and_commit_repo_frontier_research_request;
|
||||
pub use runtime_spine::select_and_commit_repo_frontier_route;
|
||||
|
|
@ -1199,6 +1179,7 @@ pub use runtime_store_migration::{
|
|||
RUNTIME_STORE_MIGRATION_RECEIPT_SCHEMA_VERSION, RUNTIME_STORE_MIGRATION_RECEIPT_TYPE,
|
||||
RuntimeStoreMigrationReceipt, migrate_runtime_store_to_redb,
|
||||
};
|
||||
pub use runtime_worker_attempt::{RuntimeTypedRequestRef, WorkerProcessStatus};
|
||||
pub use semantic_projector_service::SemanticProjectorServiceBody;
|
||||
pub use semantic_projector_service::SemanticProjectorServicePulse;
|
||||
pub use semantic_projector_service::validate_semantic_projector_source_pair;
|
||||
|
|
@ -1231,8 +1212,8 @@ pub use substrate_gate::SubstrateGateCultNetContract;
|
|||
pub use substrate_gate::SubstrateGateRepoAccessGrantReceipt;
|
||||
pub use substrate_gate::default_substrate_gate_cultnet_contracts;
|
||||
pub use substrate_gate::substrate_gate_coordinator_implementation_grant;
|
||||
pub use substrate_gate::substrate_gate_repo_access_grant_for_launch;
|
||||
pub use substrate_gate::substrate_gate_operation_for_governed_tool;
|
||||
pub use substrate_gate::substrate_gate_repo_access_grant_for_launch;
|
||||
pub use substrate_gate::substrate_gate_repo_work_planning_grant;
|
||||
pub use surfaces::AdmittedModelDirectionConsiderationContextProjection;
|
||||
pub use surfaces::EpiphanyAcceptanceBundle;
|
||||
|
|
@ -1337,17 +1318,17 @@ pub use surfaces::REPO_FRONTIER_PLAN_MIND_CONTEXT_CONTRACT;
|
|||
pub use surfaces::REPO_FRONTIER_PLAN_MIND_CONTEXT_SCHEMA_VERSION;
|
||||
pub use surfaces::REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT;
|
||||
pub use surfaces::REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION;
|
||||
pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT;
|
||||
pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION;
|
||||
pub use surfaces::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT;
|
||||
pub use surfaces::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION;
|
||||
pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT;
|
||||
pub use surfaces::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION;
|
||||
pub use surfaces::REPO_MODEL_CLAIM_REPAIR_CONTEXT_CONTRACT;
|
||||
pub use surfaces::REPO_MODEL_CLAIM_REPAIR_CONTEXT_SCHEMA_VERSION;
|
||||
pub use surfaces::ROLE_WORKER_OUTPUT_CONTRACT_ID;
|
||||
pub use surfaces::RepoFrontierPlanMindContextProjection;
|
||||
pub use surfaces::RepoFrontierPlanningContextProjection;
|
||||
pub use surfaces::RepoFrontierResearchContextProjection;
|
||||
pub use surfaces::RepoFrontierProposalModelingContextProjection;
|
||||
pub use surfaces::RepoFrontierResearchContextProjection;
|
||||
pub use surfaces::RepoModelClaimRepairContextProjection;
|
||||
pub use surfaces::build_reorient_acceptance_bundle;
|
||||
pub use surfaces::build_reorient_job_launch_request;
|
||||
|
|
|
|||
|
|
@ -3,14 +3,14 @@ use super::EpiphanyMemoryFreshnessStatus;
|
|||
use super::EpiphanyMemoryGraphSnapshot;
|
||||
use super::EpiphanyMemoryGraphValidationError;
|
||||
use super::validate_memory_graph_snapshot;
|
||||
use crate::memory_graph::store::MEMORY_GRAPH_SCHEMA_VERSION;
|
||||
use crate::memory_graph::MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION;
|
||||
|
||||
pub fn compose_memory_graph_snapshots(
|
||||
graph_id: impl Into<String>,
|
||||
snapshots: impl IntoIterator<Item = EpiphanyMemoryGraphSnapshot>,
|
||||
) -> Result<EpiphanyMemoryGraphSnapshot, Vec<EpiphanyMemoryGraphValidationError>> {
|
||||
let mut composed = EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()),
|
||||
schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.to_string()),
|
||||
graph_id: graph_id.into(),
|
||||
..Default::default()
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ pub mod semantic_index;
|
|||
pub mod semantic_projection;
|
||||
pub mod semantic_projector;
|
||||
pub mod semantic_projector_pulse;
|
||||
pub mod store;
|
||||
pub mod validation;
|
||||
|
||||
pub use epiphany_state_model::EpiphanyMemoryAnchor;
|
||||
|
|
@ -32,9 +31,6 @@ pub use epiphany_state_model::RepoFrontierAdoptedPlan;
|
|||
pub use epiphany_state_model::RepoFrontierExecutionAmendment;
|
||||
pub use epiphany_state_model::RepoFrontierItem;
|
||||
pub use epiphany_state_model::RepoFrontierStatus;
|
||||
pub use epiphany_state_model::RepoModelPatch;
|
||||
pub use epiphany_state_model::RepoModelPatchOperation;
|
||||
pub use epiphany_state_model::RepoModelPatchPurpose;
|
||||
|
||||
pub use compose::compose_memory_graph_snapshots;
|
||||
pub use context_cut::plan_memory_graph_context_cut;
|
||||
|
|
@ -53,20 +49,6 @@ pub use semantic_index::*;
|
|||
pub use semantic_projection::*;
|
||||
pub use semantic_projector::*;
|
||||
pub use semantic_projector_pulse::*;
|
||||
pub use store::EpiphanyMemoryGraphEntry;
|
||||
pub use store::MEMORY_GRAPH_KEY;
|
||||
pub use store::MEMORY_GRAPH_SCHEMA_VERSION;
|
||||
pub use store::MEMORY_GRAPH_TYPE;
|
||||
#[cfg(test)]
|
||||
pub(crate) use store::apply_repo_model_patch;
|
||||
pub use store::derive_repo_model_patch;
|
||||
pub use store::load_memory_graph_entry;
|
||||
pub use store::load_memory_graph_snapshot;
|
||||
pub use store::memory_graph_cache;
|
||||
pub use store::memory_graph_model_hash;
|
||||
pub use store::validate_memory_graph_entry;
|
||||
pub use store::write_memory_graph_entry;
|
||||
pub use store::write_memory_graph_snapshot;
|
||||
pub use validation::EpiphanyMemoryGraphValidationError;
|
||||
pub use validation::lifecycle_allowed_for_profile;
|
||||
pub use validation::validate_memory_graph_snapshot;
|
||||
|
|
@ -85,5 +67,18 @@ pub(crate) fn unique_strings(values: impl IntoIterator<Item = String>) -> Vec<St
|
|||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
pub const MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION: &str = "epiphany.memory_graph.projection.v1";
|
||||
|
||||
/// Digest helper for transient memory-context and semantic projection DTOs.
|
||||
/// This digest is derived notification state; keyed Mind documents own the
|
||||
/// RepoModel and no aggregate revision can be committed through this module.
|
||||
pub fn memory_graph_model_hash(snapshot: &EpiphanyMemoryGraphSnapshot) -> anyhow::Result<String> {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
let mut canonical = snapshot.clone();
|
||||
canonical.model_hash.clear();
|
||||
Ok(format!(
|
||||
"{:x}",
|
||||
Sha256::digest(rmp_serde::to_vec_named(&canonical)?)
|
||||
))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,99 +33,24 @@ pub enum RepoMemoryGraphRefresh {
|
|||
}
|
||||
|
||||
pub fn refresh_or_validate_repo_memory_graph(
|
||||
store_path: &Path,
|
||||
_store_path: &Path,
|
||||
source_identity: &str,
|
||||
state: &EpiphanyThreadState,
|
||||
repo_root: &Path,
|
||||
graph_id: impl Into<String>,
|
||||
) -> Result<(EpiphanyMemoryGraphSnapshot, RepoMemoryGraphRefresh)> {
|
||||
let graph_id = graph_id.into();
|
||||
for _ in 0..4 {
|
||||
let inspected = crate::memory_graph::store::load_memory_graph_envelope(store_path)?;
|
||||
if let Some(envelope) = &inspected {
|
||||
let entry: crate::memory_graph::EpiphanyMemoryGraphEntry =
|
||||
rmp_serde::from_slice(&envelope.payload)?;
|
||||
crate::memory_graph::validate_memory_graph_entry(&entry)?;
|
||||
let snapshot = entry.snapshot()?;
|
||||
if snapshot.model_revision > 0 {
|
||||
return Ok((snapshot, RepoMemoryGraphRefresh::Reused));
|
||||
}
|
||||
let provenance_matches = snapshot.source.as_ref().is_some_and(|source| {
|
||||
source.kind == "thread_state_repo_graph"
|
||||
&& source.identity == source_identity
|
||||
&& source.revision == state.revision
|
||||
});
|
||||
if provenance_matches && snapshot_anchor_bytes_match(&snapshot, repo_root) {
|
||||
return Ok((snapshot, RepoMemoryGraphRefresh::Reused));
|
||||
}
|
||||
}
|
||||
|
||||
let snapshot = memory_graph_from_epiphany_graphs(
|
||||
graph_id.clone(),
|
||||
Ok((
|
||||
memory_graph_from_epiphany_graphs(
|
||||
graph_id,
|
||||
&state.graphs,
|
||||
source_identity,
|
||||
state.revision,
|
||||
repo_root,
|
||||
)?;
|
||||
pause_after_legacy_read_for_test();
|
||||
if crate::memory_graph::store::replace_inspected_legacy_memory_graph(
|
||||
store_path,
|
||||
inspected.as_ref(),
|
||||
&snapshot,
|
||||
&chrono::Utc::now().to_rfc3339(),
|
||||
)? {
|
||||
return Ok((snapshot, RepoMemoryGraphRefresh::Refreshed));
|
||||
}
|
||||
// Another process won. Reload under the next iteration; canonical state
|
||||
// is authoritative and a competing legacy refresh may be retried.
|
||||
}
|
||||
Err(anyhow::anyhow!(
|
||||
"memory graph bootstrap could not settle after concurrent writers"
|
||||
)?,
|
||||
RepoMemoryGraphRefresh::Refreshed,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn pause_after_legacy_read_for_test() {}
|
||||
|
||||
#[cfg(test)]
|
||||
fn pause_after_legacy_read_for_test() {
|
||||
if let Some((ready, release)) = REFRESH_AFTER_LEGACY_READ_HOOK
|
||||
.get_or_init(|| std::sync::Mutex::new(None))
|
||||
.lock()
|
||||
.expect("refresh test hook lock")
|
||||
.take()
|
||||
{
|
||||
ready.wait();
|
||||
release.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
static REFRESH_AFTER_LEGACY_READ_HOOK: std::sync::OnceLock<
|
||||
std::sync::Mutex<
|
||||
Option<(
|
||||
std::sync::Arc<std::sync::Barrier>,
|
||||
std::sync::Arc<std::sync::Barrier>,
|
||||
)>,
|
||||
>,
|
||||
> = std::sync::OnceLock::new();
|
||||
|
||||
fn snapshot_anchor_bytes_match(snapshot: &EpiphanyMemoryGraphSnapshot, repo_root: &Path) -> bool {
|
||||
snapshot
|
||||
.nodes
|
||||
.iter()
|
||||
.flat_map(|node| &node.anchors)
|
||||
.chain(snapshot.edges.iter().flat_map(|edge| &edge.anchors))
|
||||
.all(|anchor| {
|
||||
let (Some(code_ref), Some(expected)) = (&anchor.code_ref, &anchor.source_hash) else {
|
||||
return false;
|
||||
};
|
||||
fs::read(repo_root.join(&code_ref.path))
|
||||
.ok()
|
||||
.is_some_and(|bytes| format!("sha256:{:x}", Sha256::digest(bytes)) == *expected)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn memory_graph_from_epiphany_graphs(
|
||||
graph_id: impl Into<String>,
|
||||
graphs: &EpiphanyGraphs,
|
||||
|
|
@ -575,295 +500,3 @@ fn memory_edge_kind(kind: &str) -> EpiphanyMemoryEdgeKind {
|
|||
_ => EpiphanyMemoryEdgeKind::Other,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory_graph::validate_memory_graph_snapshot;
|
||||
use epiphany_state_model::EpiphanyCodeRef;
|
||||
use epiphany_state_model::EpiphanyGraph;
|
||||
use epiphany_state_model::EpiphanyGraphEdge;
|
||||
use epiphany_state_model::EpiphanyGraphNode;
|
||||
use epiphany_state_model::EpiphanyGraphs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn repo_profile_imports_accepted_graphs_into_valid_memory_graph() {
|
||||
let graphs = EpiphanyGraphs {
|
||||
architecture: EpiphanyGraph {
|
||||
nodes: vec![EpiphanyGraphNode {
|
||||
id: "core".to_string(),
|
||||
title: "Core policy".to_string(),
|
||||
purpose: "Owns shared policy.".to_string(),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("epiphany-core/src/lib.rs"),
|
||||
symbol: Some("policy".to_string()),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
edges: vec![EpiphanyGraphEdge {
|
||||
id: Some("edge-core-self".to_string()),
|
||||
source_id: "core".to_string(),
|
||||
target_id: "core".to_string(),
|
||||
kind: "owns".to_string(),
|
||||
label: Some("owns itself for fixture".to_string()),
|
||||
..Default::default()
|
||||
}],
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let snapshot = memory_graph_from_epiphany_graphs(
|
||||
"repo-profile",
|
||||
&graphs,
|
||||
"test-state",
|
||||
1,
|
||||
Path::new("."),
|
||||
)
|
||||
.unwrap();
|
||||
let errors = validate_memory_graph_snapshot(&snapshot);
|
||||
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
assert_eq!(snapshot.domains.len(), 1);
|
||||
assert_eq!(snapshot.nodes.len(), 1);
|
||||
assert_eq!(snapshot.edges.len(), 1);
|
||||
assert_eq!(snapshot.summaries.len(), 1);
|
||||
assert_eq!(
|
||||
snapshot.nodes[0].profile,
|
||||
EpiphanyMemoryProfile::RepoArchitecture
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_profile_keeps_bad_topology_visible() {
|
||||
let graphs = EpiphanyGraphs {
|
||||
architecture: EpiphanyGraph {
|
||||
edges: vec![EpiphanyGraphEdge {
|
||||
source_id: "missing-source".to_string(),
|
||||
target_id: "missing-target".to_string(),
|
||||
kind: "owns".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let snapshot = memory_graph_from_epiphany_graphs(
|
||||
"repo-profile",
|
||||
&graphs,
|
||||
"test-state",
|
||||
1,
|
||||
Path::new("."),
|
||||
)
|
||||
.unwrap();
|
||||
let errors = validate_memory_graph_snapshot(&snapshot);
|
||||
|
||||
assert!(
|
||||
errors
|
||||
.iter()
|
||||
.any(|error| error.message.contains("missing source node"))
|
||||
);
|
||||
assert!(
|
||||
errors
|
||||
.iter()
|
||||
.any(|error| error.message.contains("missing target node"))
|
||||
);
|
||||
}
|
||||
|
||||
fn anchored_state(path: &str, revision: u64) -> EpiphanyThreadState {
|
||||
EpiphanyThreadState {
|
||||
revision,
|
||||
graphs: EpiphanyGraphs {
|
||||
architecture: EpiphanyGraph {
|
||||
nodes: vec![EpiphanyGraphNode {
|
||||
id: "body".to_string(),
|
||||
title: "Body".to_string(),
|
||||
purpose: "Grounded body anatomy.".to_string(),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from(path),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_cache_reuse_requires_revision_and_anchor_bytes() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
std::fs::write(temp.path().join("body.rs"), "one")?;
|
||||
let store = temp.path().join("memory-graph.msgpack");
|
||||
let state = anchored_state("body.rs", 1);
|
||||
|
||||
let (first, first_refresh) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?;
|
||||
assert_eq!(first_refresh, RepoMemoryGraphRefresh::Refreshed);
|
||||
assert!(first.nodes[0].source_hashes[0].starts_with("sha256:"));
|
||||
let (same, same_refresh) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?;
|
||||
assert_eq!(same_refresh, RepoMemoryGraphRefresh::Reused);
|
||||
assert_eq!(first.source, same.source);
|
||||
|
||||
std::fs::write(temp.path().join("body.rs"), "two")?;
|
||||
let (changed, bytes_refresh) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?;
|
||||
assert_eq!(bytes_refresh, RepoMemoryGraphRefresh::Refreshed);
|
||||
assert_ne!(first.nodes[0].source_hashes, changed.nodes[0].source_hashes);
|
||||
|
||||
let next = anchored_state("body.rs", 2);
|
||||
let (revised, revision_refresh) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &next, temp.path(), "repo")?;
|
||||
assert_eq!(revision_refresh, RepoMemoryGraphRefresh::Refreshed);
|
||||
assert_eq!(revised.source.unwrap().revision, 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_refresh_cannot_replace_canonical_model() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
std::fs::write(temp.path().join("body.rs"), "one")?;
|
||||
let store = temp.path().join("memory-graph.msgpack");
|
||||
let state = anchored_state("body.rs", 1);
|
||||
let (mut canonical, _) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?;
|
||||
canonical.model_revision = 1;
|
||||
canonical.model_hash = crate::memory_graph::memory_graph_model_hash(&canonical)?;
|
||||
crate::memory_graph::write_memory_graph_snapshot(&store, &canonical)?;
|
||||
|
||||
std::fs::write(temp.path().join("body.rs"), "changed")?;
|
||||
let newer = anchored_state("body.rs", 999);
|
||||
let (preserved, refresh) = refresh_or_validate_repo_memory_graph(
|
||||
&store,
|
||||
"thread",
|
||||
&newer,
|
||||
temp.path(),
|
||||
"counterfeit",
|
||||
)?;
|
||||
assert_eq!(refresh, RepoMemoryGraphRefresh::Reused);
|
||||
assert_eq!(preserved.model_revision, 1);
|
||||
assert_eq!(preserved.model_hash, canonical.model_hash);
|
||||
assert_eq!(preserved.graph_id, canonical.graph_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_patch_winning_after_refresh_read_survives_refresh_resume() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
std::fs::write(temp.path().join("body.rs"), "one")?;
|
||||
let store = temp.path().join("memory-graph.msgpack");
|
||||
let state = anchored_state("body.rs", 1);
|
||||
let (legacy, _) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?;
|
||||
let claim = legacy.nodes[0].id.clone();
|
||||
let ready = std::sync::Arc::new(std::sync::Barrier::new(2));
|
||||
let release = std::sync::Arc::new(std::sync::Barrier::new(2));
|
||||
*REFRESH_AFTER_LEGACY_READ_HOOK
|
||||
.get_or_init(|| std::sync::Mutex::new(None))
|
||||
.lock()
|
||||
.unwrap() = Some((ready.clone(), release.clone()));
|
||||
|
||||
let refresh_store = store.clone();
|
||||
let refresh_root = temp.path().to_path_buf();
|
||||
let refresh_state = anchored_state("body.rs", 999);
|
||||
let refresh = std::thread::spawn(move || {
|
||||
refresh_or_validate_repo_memory_graph(
|
||||
&refresh_store,
|
||||
"thread",
|
||||
&refresh_state,
|
||||
&refresh_root,
|
||||
"counterfeit-refresh",
|
||||
)
|
||||
});
|
||||
ready.wait();
|
||||
let patch = crate::memory_graph::RepoModelPatch {
|
||||
purpose: crate::memory_graph::RepoModelPatchPurpose::Evolution,
|
||||
patch_id: "canonical-wins-refresh-race".to_string(),
|
||||
base_revision: 0,
|
||||
base_hash: crate::memory_graph::memory_graph_model_hash(&legacy)?,
|
||||
applied_at: "2026-07-13T03:00:00Z".to_string(),
|
||||
operations: vec![
|
||||
crate::memory_graph::RepoModelPatchOperation::UpsertFrontier {
|
||||
item: crate::memory_graph::RepoFrontierItem {
|
||||
id: "frontier-survives-refresh".to_string(),
|
||||
migration_body: "Preserve canonical Modeling authority.".to_string(),
|
||||
question: "Can a stale refresh overwrite this?".to_string(),
|
||||
gap: "The old refresh replaced the complete file.".to_string(),
|
||||
target_claim_ids: vec![claim],
|
||||
source_scope: vec!["body.rs".to_string()],
|
||||
recommended_next_organ: "Soul".to_string(),
|
||||
status: crate::memory_graph::RepoFrontierStatus::Active,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
let canonical = crate::memory_graph::apply_repo_model_patch(&store, &patch)?;
|
||||
release.wait();
|
||||
let (observed, outcome) = refresh.join().expect("refresh thread")?;
|
||||
assert_eq!(outcome, RepoMemoryGraphRefresh::Reused);
|
||||
assert_eq!(observed.model_revision, canonical.model_revision);
|
||||
assert_eq!(observed.model_hash, canonical.model_hash);
|
||||
assert_eq!(observed.frontier, canonical.frontier);
|
||||
assert_eq!(observed.lifecycle_receipts, canonical.lifecycle_receipts);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_anchor_cannot_emit_ready_summary() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let snapshot = memory_graph_from_epiphany_graphs(
|
||||
"repo",
|
||||
&anchored_state("gone.rs", 1).graphs,
|
||||
"thread",
|
||||
1,
|
||||
temp.path(),
|
||||
)?;
|
||||
assert_eq!(
|
||||
snapshot.freshness.unwrap().status,
|
||||
EpiphanyMemoryFreshnessStatus::Stale
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.summaries
|
||||
.iter()
|
||||
.all(|summary| summary.freshness == EpiphanyMemoryFreshnessStatus::Stale)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_edge_anchor_stales_edge_summary_and_snapshot() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
std::fs::write(temp.path().join("body.rs"), "body")?;
|
||||
let mut state = anchored_state("body.rs", 1);
|
||||
state.graphs.architecture.edges.push(EpiphanyGraphEdge {
|
||||
id: Some("edge-body".to_string()),
|
||||
source_id: "body".to_string(),
|
||||
target_id: "body".to_string(),
|
||||
kind: "owns".to_string(),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("missing-edge.rs"),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
let snapshot =
|
||||
memory_graph_from_epiphany_graphs("repo", &state.graphs, "thread", 1, temp.path())?;
|
||||
assert_eq!(snapshot.edges[0].lifecycle, EpiphanyMemoryLifecycle::Stale);
|
||||
assert_eq!(
|
||||
snapshot.summaries[0].freshness,
|
||||
EpiphanyMemoryFreshnessStatus::Stale
|
||||
);
|
||||
let freshness = snapshot.freshness.expect("freshness");
|
||||
assert_eq!(freshness.status, EpiphanyMemoryFreshnessStatus::Stale);
|
||||
assert_eq!(freshness.stale_edge_ids, vec!["edge-body".to_string()]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1278,13 +1278,12 @@ fn env_u64(name: &str, default: u64) -> u64 {
|
|||
.and_then(|value| value.parse().ok())
|
||||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory_graph::{
|
||||
EpiphanyMemoryDomain, EpiphanyMemoryLifecycle, EpiphanyMemoryNode, EpiphanyMemoryNodeKind,
|
||||
EpiphanyMemoryProfile, MEMORY_GRAPH_SCHEMA_VERSION, memory_graph_model_hash,
|
||||
EpiphanyMemoryProfile, MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION, memory_graph_model_hash,
|
||||
};
|
||||
use tokio::runtime::Runtime;
|
||||
use wiremock::matchers::{method, path};
|
||||
|
|
@ -1292,7 +1291,7 @@ mod tests {
|
|||
|
||||
fn snapshot() -> EpiphanyMemoryGraphSnapshot {
|
||||
let mut snapshot = EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()),
|
||||
schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.to_string()),
|
||||
graph_id: "semantic-fallback".to_string(),
|
||||
model_revision: 3,
|
||||
domains: vec![EpiphanyMemoryDomain {
|
||||
|
|
@ -1339,7 +1338,7 @@ mod tests {
|
|||
.mount(&qdrant),
|
||||
);
|
||||
let mut empty = EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()),
|
||||
schema_version: Some(MEMORY_GRAPH_PROJECTION_SCHEMA_VERSION.to_string()),
|
||||
graph_id: "empty-semantic-source".to_string(),
|
||||
model_revision: 9,
|
||||
..Default::default()
|
||||
|
|
@ -1935,366 +1934,4 @@ mod tests {
|
|||
root
|
||||
);
|
||||
}
|
||||
|
||||
struct FakeEvidencePort {
|
||||
exists: bool,
|
||||
compatibility: CollectionCompatibility,
|
||||
points: Vec<crate::semantic_backend::SemanticStoredPoint<MemorySemanticPointPayload>>,
|
||||
}
|
||||
|
||||
struct StoreAdvancingPort {
|
||||
store: std::path::PathBuf,
|
||||
compatibility: CollectionCompatibility,
|
||||
points: Vec<crate::semantic_backend::SemanticStoredPoint<MemorySemanticPointPayload>>,
|
||||
replacement: crate::EpiphanyMemoryGraphEntry,
|
||||
}
|
||||
|
||||
impl MemorySemanticEvidencePort for StoreAdvancingPort {
|
||||
fn collection_exists(&mut self, _name: &str) -> Result<bool> {
|
||||
Ok(true)
|
||||
}
|
||||
fn collection_compatibility(&mut self, _name: &str) -> Result<CollectionCompatibility> {
|
||||
Ok(self.compatibility.clone())
|
||||
}
|
||||
fn points_for_scope(
|
||||
&mut self,
|
||||
_name: &str,
|
||||
_scope: &[(&str, &str)],
|
||||
) -> Result<Vec<crate::semantic_backend::SemanticStoredPoint<MemorySemanticPointPayload>>>
|
||||
{
|
||||
let mut cache = crate::runtime_spine_cache(&self.store)?;
|
||||
cache.put(crate::MEMORY_GRAPH_KEY, &self.replacement)?;
|
||||
Ok(self.points.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl MemorySemanticEvidencePort for FakeEvidencePort {
|
||||
fn collection_exists(&mut self, _name: &str) -> Result<bool> {
|
||||
Ok(self.exists)
|
||||
}
|
||||
fn collection_compatibility(&mut self, _name: &str) -> Result<CollectionCompatibility> {
|
||||
Ok(self.compatibility.clone())
|
||||
}
|
||||
fn points_for_scope(
|
||||
&mut self,
|
||||
_name: &str,
|
||||
_scope: &[(&str, &str)],
|
||||
) -> Result<Vec<crate::semantic_backend::SemanticStoredPoint<MemorySemanticPointPayload>>>
|
||||
{
|
||||
Ok(self.points.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn live_evidence_fixture() -> (
|
||||
MemorySemanticIndexConfig,
|
||||
super::super::MemorySemanticProjectionInput,
|
||||
MemorySemanticProjectionReadiness,
|
||||
FakeEvidencePort,
|
||||
) {
|
||||
let snapshot = snapshot();
|
||||
let mut config = MemorySemanticIndexConfig::from_env();
|
||||
config.embedding_provider_id = "provider".to_string();
|
||||
config.ollama_model = "model".to_string();
|
||||
config.modeling_collection = "modeling-exact".to_string();
|
||||
let obligation = derive_memory_semantic_projection_obligation(
|
||||
&snapshot,
|
||||
"swarm-a",
|
||||
SemanticPartition::Modeling,
|
||||
"source-a",
|
||||
"commit-a",
|
||||
"2026-07-16T00:00:00Z",
|
||||
)
|
||||
.unwrap();
|
||||
let namespace = MemorySemanticProjectionNamespace {
|
||||
obligation_id: obligation.obligation_id.clone(),
|
||||
claim_id: "claim-a".to_string(),
|
||||
claim_epoch: 1,
|
||||
};
|
||||
let documents = derive_semantic_projection("swarm-a", &snapshot)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|row| row.partition == SemanticPartition::Modeling)
|
||||
.collect::<Vec<_>>();
|
||||
let desired = documents
|
||||
.iter()
|
||||
.map(|document| {
|
||||
(
|
||||
physical_point_id(&namespace, &document.point_id),
|
||||
point_payload(document, &config, &namespace),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let points = desired
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (id, payload))| {
|
||||
stored(
|
||||
id,
|
||||
payload.clone(),
|
||||
Some(vec![index as f32 + 1.0, index as f32 + 2.0]),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let root = authenticate_observed_projection(points.clone(), &desired, 2).unwrap();
|
||||
let raw = memory_semantic_index_receipt(
|
||||
&snapshot,
|
||||
"swarm-a",
|
||||
SemanticPartition::Modeling,
|
||||
"2026-07-16T00:01:00Z",
|
||||
&config,
|
||||
&config.modeling_collection,
|
||||
&memory_graph_model_hash(&snapshot).unwrap(),
|
||||
&canonical_content_set_hash(&documents),
|
||||
2,
|
||||
documents.len() as u32,
|
||||
0,
|
||||
&root,
|
||||
&namespace,
|
||||
);
|
||||
let receipt = bind_memory_semantic_index_receipt(raw, &obligation).unwrap();
|
||||
let current = MemorySemanticProjectionSourceHead {
|
||||
swarm_id: obligation.swarm_id.clone(),
|
||||
partition: obligation.partition.clone(),
|
||||
canonical_source_id: obligation.canonical_source_id.clone(),
|
||||
source_commit_id: obligation.source_commit_id.clone(),
|
||||
graph_id: obligation.graph_id.clone(),
|
||||
source_generation: obligation.source_generation,
|
||||
source_model_hash: obligation.source_model_hash.clone(),
|
||||
canonical_content_set_hash: obligation.canonical_content_set_hash.clone(),
|
||||
};
|
||||
let input = super::super::MemorySemanticProjectionInput {
|
||||
snapshot,
|
||||
obligation: obligation.clone(),
|
||||
authority: super::super::MemorySemanticProjectionAuthoritySnapshot {
|
||||
head: current.clone(),
|
||||
envelopes: vec![],
|
||||
},
|
||||
};
|
||||
let readiness = MemorySemanticProjectionReadiness {
|
||||
obligation,
|
||||
current,
|
||||
receipt,
|
||||
};
|
||||
let port = FakeEvidencePort {
|
||||
exists: true,
|
||||
compatibility: compatibility(&config, SemanticPartition::Modeling, 2),
|
||||
points,
|
||||
};
|
||||
(config, input, readiness, port)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_evidence_requires_named_collection_compatibility_and_stable_authority() {
|
||||
let (config, input, readiness, mut port) = live_evidence_fixture();
|
||||
let mut calls = 0;
|
||||
let evidence = observe_memory_semantic_live_evidence_with(
|
||||
&config,
|
||||
&input,
|
||||
&readiness,
|
||||
&mut port,
|
||||
|| {
|
||||
calls += 1;
|
||||
Ok(true)
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(calls, 2);
|
||||
assert_eq!(
|
||||
evidence.observed_vector_binding_root_sha256,
|
||||
readiness.receipt.observed_vector_binding_root_sha256
|
||||
);
|
||||
|
||||
let (_, _, _, mut missing) = live_evidence_fixture();
|
||||
missing.exists = false;
|
||||
assert!(
|
||||
observe_memory_semantic_live_evidence_with(
|
||||
&config,
|
||||
&input,
|
||||
&readiness,
|
||||
&mut missing,
|
||||
|| Ok(true)
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let (_, _, _, mut incompatible) = live_evidence_fixture();
|
||||
incompatible.compatibility.vector_size = 3;
|
||||
assert!(
|
||||
observe_memory_semantic_live_evidence_with(
|
||||
&config,
|
||||
&input,
|
||||
&readiness,
|
||||
&mut incompatible,
|
||||
|| Ok(true)
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let mut wrong_collection = readiness.clone();
|
||||
wrong_collection.receipt.collection_name = "compatible-but-wrong".to_string();
|
||||
let (_, _, _, mut port) = live_evidence_fixture();
|
||||
assert!(
|
||||
observe_memory_semantic_live_evidence_with(
|
||||
&config,
|
||||
&input,
|
||||
&wrong_collection,
|
||||
&mut port,
|
||||
|| Ok(true)
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let (_, _, _, mut port) = live_evidence_fixture();
|
||||
let mut phase = 0;
|
||||
assert!(
|
||||
observe_memory_semantic_live_evidence_with(
|
||||
&config,
|
||||
&input,
|
||||
&readiness,
|
||||
&mut port,
|
||||
|| {
|
||||
phase += 1;
|
||||
Ok(phase == 1)
|
||||
}
|
||||
)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_backed_live_reader_refuses_repo_model_advance_during_scroll() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let store = temp.path().join("semantic-authority-race.cc");
|
||||
crate::initialize_runtime_spine(
|
||||
&store,
|
||||
crate::RuntimeSpineInitOptions {
|
||||
runtime_id: "semantic-race-runtime".into(),
|
||||
display_name: "Semantic race runtime".into(),
|
||||
created_at: "2026-07-16T00:00:00Z".into(),
|
||||
},
|
||||
)?;
|
||||
crate::runtime_spine::tests::bind_test_runtime_swarm(&store, "swarm-a")?;
|
||||
let model = snapshot();
|
||||
let entry = crate::EpiphanyMemoryGraphEntry::from_snapshot(&model)?;
|
||||
let migration = crate::RepoModelMigrationReceipt {
|
||||
schema_version: crate::REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION.to_string(),
|
||||
receipt_id: "repo-model-migration".into(),
|
||||
source_store: "semantic-race-test".into(),
|
||||
source_graph_id: model.graph_id.clone(),
|
||||
imported_revision: model.model_revision,
|
||||
imported_hash: memory_graph_model_hash(&model)?,
|
||||
imported_at: "2026-07-16T00:00:01Z".into(),
|
||||
contract: crate::REPO_MODEL_MIGRATION_CONTRACT.to_string(),
|
||||
};
|
||||
let mut cache = crate::runtime_spine_cache(&store)?;
|
||||
cache.put(crate::MEMORY_GRAPH_KEY, &entry)?;
|
||||
cache.put(&migration.receipt_id, &migration)?;
|
||||
crate::migrate_legacy_repo_model_projection_obligation(&store)?
|
||||
.expect("projection obligation");
|
||||
let mut input = crate::runtime_modeling_semantic_projection_input(&store)?;
|
||||
assert_eq!(input.authority.envelopes.len(), 2);
|
||||
let mut authority_cache = crate::runtime_spine_cache(&store)?;
|
||||
authority_cache.pull_all_backing_stores()?;
|
||||
let extra = authority_cache
|
||||
.snapshot_envelopes()
|
||||
.into_iter()
|
||||
.find(|row| {
|
||||
!input
|
||||
.authority
|
||||
.envelopes
|
||||
.iter()
|
||||
.any(|captured| captured.r#type == row.r#type && captured.key == row.key)
|
||||
})
|
||||
.expect("runtime provides an additional exact authority envelope");
|
||||
input.authority.envelopes.push(extra);
|
||||
assert!(input.authority.envelopes.len() > 2);
|
||||
let acquisition =
|
||||
super::super::semantic_projector::idunn_acquire_memory_semantic_projection(
|
||||
&store,
|
||||
&input,
|
||||
"executor-a",
|
||||
"executor-incarnation-a",
|
||||
"execute",
|
||||
"idunn-a",
|
||||
"2026-07-16T00:00:30Z",
|
||||
)?;
|
||||
let mut config = MemorySemanticIndexConfig::from_env();
|
||||
config.embedding_provider_id = "provider".into();
|
||||
config.ollama_model = "model".into();
|
||||
config.modeling_collection = "modeling-exact".into();
|
||||
let namespace = MemorySemanticProjectionNamespace {
|
||||
obligation_id: input.obligation.obligation_id.clone(),
|
||||
claim_id: acquisition.claim.claim_id.clone(),
|
||||
claim_epoch: acquisition.claim.epoch,
|
||||
};
|
||||
let documents = derive_semantic_projection("swarm-a", &model)?
|
||||
.into_iter()
|
||||
.filter(|row| row.partition == SemanticPartition::Modeling)
|
||||
.collect::<Vec<_>>();
|
||||
let desired = documents
|
||||
.iter()
|
||||
.map(|document| {
|
||||
(
|
||||
physical_point_id(&namespace, &document.point_id),
|
||||
point_payload(document, &config, &namespace),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let points = desired
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (id, payload))| {
|
||||
stored(
|
||||
id,
|
||||
payload.clone(),
|
||||
Some(vec![index as f32 + 1.0, index as f32 + 2.0]),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let root = authenticate_observed_projection(points.clone(), &desired, 2)?;
|
||||
let raw = memory_semantic_index_receipt(
|
||||
&model,
|
||||
"swarm-a",
|
||||
SemanticPartition::Modeling,
|
||||
"2026-07-16T00:01:00Z",
|
||||
&config,
|
||||
&config.modeling_collection,
|
||||
&memory_graph_model_hash(&model)?,
|
||||
&canonical_content_set_hash(&documents),
|
||||
2,
|
||||
documents.len() as u32,
|
||||
0,
|
||||
&root,
|
||||
&namespace,
|
||||
);
|
||||
let receipt = bind_memory_semantic_index_receipt(raw, &input.obligation)?;
|
||||
super::super::semantic_projector::succeed_memory_semantic_projection_claim(
|
||||
&store,
|
||||
&acquisition.claim.claim_id,
|
||||
&input.authority,
|
||||
receipt,
|
||||
"2026-07-16T00:01:01Z",
|
||||
)?;
|
||||
let readiness = super::super::load_memory_semantic_projection_readiness(&store, &input)?
|
||||
.expect("authenticated readiness");
|
||||
let mut advanced = model.clone();
|
||||
advanced.model_revision += 1;
|
||||
advanced.model_hash = memory_graph_model_hash(&advanced)?;
|
||||
let replacement = crate::EpiphanyMemoryGraphEntry::from_snapshot(&advanced)?;
|
||||
let mut port = StoreAdvancingPort {
|
||||
store: store.clone(),
|
||||
compatibility: compatibility(&config, SemanticPartition::Modeling, 2),
|
||||
points,
|
||||
replacement,
|
||||
};
|
||||
assert!(
|
||||
observe_memory_semantic_live_evidence_with_port(
|
||||
&store, &config, &input, &readiness, &mut port,
|
||||
)?
|
||||
.is_none()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use super::{
|
||||
EpiphanyMemoryDomain, EpiphanyMemoryFreshnessStatus, EpiphanyMemoryGraphSnapshot,
|
||||
EpiphanyMemoryLifecycle, EpiphanyMemoryProfile, MEMORY_GRAPH_KEY, MEMORY_GRAPH_TYPE,
|
||||
RepoFrontierStatus, memory_graph_model_hash, validate_memory_graph_snapshot,
|
||||
EpiphanyMemoryLifecycle, EpiphanyMemoryProfile, RepoFrontierStatus, memory_graph_model_hash,
|
||||
validate_memory_graph_snapshot,
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
@ -382,20 +382,24 @@ fn document<T: Serialize>(
|
|||
source_refs.dedup();
|
||||
source_hashes.sort();
|
||||
source_hashes.dedup();
|
||||
let canonical_type = match kind {
|
||||
SemanticDocumentKind::Node => "epiphany.mind.repo_model.node.v1",
|
||||
SemanticDocumentKind::Edge => "epiphany.mind.repo_model.edge.v1",
|
||||
SemanticDocumentKind::Summary => "epiphany.mind.repo_model.summary.v1",
|
||||
SemanticDocumentKind::Frontier => "epiphany.mind.repo_model.frontier.v1",
|
||||
};
|
||||
let canonical = SemanticCanonicalLocator {
|
||||
locator: format!(
|
||||
"cultcache://{swarm_id}/{MEMORY_GRAPH_TYPE}/{MEMORY_GRAPH_KEY}#{document_id}"
|
||||
),
|
||||
canonical_type: MEMORY_GRAPH_TYPE.to_string(),
|
||||
canonical_key: MEMORY_GRAPH_KEY.to_string(),
|
||||
locator: format!("cultcache://{swarm_id}/{canonical_type}/{document_id}"),
|
||||
canonical_type: canonical_type.to_string(),
|
||||
canonical_key: document_id.to_string(),
|
||||
canonical_document_id: document_id.to_string(),
|
||||
};
|
||||
Ok(SemanticProjectionDocument {
|
||||
point_id: semantic_point_id(
|
||||
swarm_id,
|
||||
partition,
|
||||
MEMORY_GRAPH_TYPE,
|
||||
MEMORY_GRAPH_KEY,
|
||||
canonical_type,
|
||||
document_id,
|
||||
document_id,
|
||||
),
|
||||
swarm_id: swarm_id.to_string(),
|
||||
|
|
|
|||
|
|
@ -1,683 +0,0 @@
|
|||
use super::EpiphanyMemoryFreshnessStatus;
|
||||
use super::EpiphanyMemoryGraphSnapshot;
|
||||
use super::derive_memory_graph_freshness;
|
||||
use super::validate_memory_graph_snapshot;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use cultcache_rs::CacheBackingStore;
|
||||
use cultcache_rs::CultCache;
|
||||
use cultcache_rs::CultCacheEnvelope;
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultcache_rs::SingleFileMessagePackBackingStore;
|
||||
use epiphany_state_model::{
|
||||
EpiphanyMemoryLifecycle, RepoFrontierStatus, RepoModelPatch, RepoModelPatchOperation,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
|
||||
pub const MEMORY_GRAPH_TYPE: &str = "epiphany.memory_graph";
|
||||
pub const MEMORY_GRAPH_KEY: &str = "default";
|
||||
pub const MEMORY_GRAPH_SCHEMA_VERSION: &str = "epiphany.memory_graph.v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "epiphany.memory_graph", schema = "EpiphanyMemoryGraphEntry")]
|
||||
pub struct EpiphanyMemoryGraphEntry {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub graph_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub snapshot_msgpack: Vec<u8>,
|
||||
}
|
||||
|
||||
impl EpiphanyMemoryGraphEntry {
|
||||
pub fn from_snapshot(snapshot: &EpiphanyMemoryGraphSnapshot) -> Result<Self> {
|
||||
let snapshot_msgpack = rmp_serde::to_vec_named(snapshot)?;
|
||||
Ok(Self {
|
||||
schema_version: MEMORY_GRAPH_SCHEMA_VERSION.to_string(),
|
||||
graph_id: snapshot.graph_id.clone(),
|
||||
snapshot_msgpack,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Result<EpiphanyMemoryGraphSnapshot> {
|
||||
rmp_serde::from_slice(&self.snapshot_msgpack)
|
||||
.map_err(|error| anyhow!("failed to decode memory graph snapshot MessagePack: {error}"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn memory_graph_cache(store_path: impl AsRef<Path>) -> Result<CultCache> {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<EpiphanyMemoryGraphEntry>()?;
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path.as_ref()));
|
||||
cache.pull_all_backing_stores()?;
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
pub fn load_memory_graph_entry(
|
||||
store_path: impl AsRef<Path>,
|
||||
) -> Result<Option<EpiphanyMemoryGraphEntry>> {
|
||||
let cache = memory_graph_cache(store_path)?;
|
||||
cache.get::<EpiphanyMemoryGraphEntry>(MEMORY_GRAPH_KEY)
|
||||
}
|
||||
|
||||
pub fn load_memory_graph_snapshot(
|
||||
store_path: impl AsRef<Path>,
|
||||
) -> Result<Option<EpiphanyMemoryGraphSnapshot>> {
|
||||
let Some(entry) = load_memory_graph_entry(store_path)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
validate_memory_graph_entry(&entry)?;
|
||||
Ok(Some(entry.snapshot()?))
|
||||
}
|
||||
|
||||
pub fn write_memory_graph_entry(
|
||||
store_path: impl AsRef<Path>,
|
||||
entry: &EpiphanyMemoryGraphEntry,
|
||||
) -> Result<EpiphanyMemoryGraphEntry> {
|
||||
validate_memory_graph_entry(entry)?;
|
||||
let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref());
|
||||
let next_envelope = memory_graph_envelope(entry, &chrono::Utc::now().to_rfc3339())?;
|
||||
let current = backing.pull_all()?.into_iter().find(|candidate| {
|
||||
candidate.r#type == MEMORY_GRAPH_TYPE && candidate.key == MEMORY_GRAPH_KEY
|
||||
});
|
||||
let installed = if let Some(current_envelope) = current {
|
||||
let current_entry: EpiphanyMemoryGraphEntry =
|
||||
rmp_serde::from_slice(¤t_envelope.payload)?;
|
||||
validate_memory_graph_entry(¤t_entry)?;
|
||||
if current_entry.snapshot()?.model_revision > 0 {
|
||||
return Err(anyhow!(
|
||||
"canonical memory graph entry can only be changed through a stale-checked RepoModelPatch"
|
||||
));
|
||||
}
|
||||
backing.compare_and_swap_entry(¤t_envelope, next_envelope)?
|
||||
} else {
|
||||
backing.insert_entry_if_absent(next_envelope)?
|
||||
};
|
||||
if !installed {
|
||||
return Err(anyhow!(
|
||||
"memory graph bootstrap lost an atomic store race; reload before retrying"
|
||||
));
|
||||
}
|
||||
Ok(entry.clone())
|
||||
}
|
||||
|
||||
pub fn write_memory_graph_snapshot(
|
||||
store_path: impl AsRef<Path>,
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
) -> Result<EpiphanyMemoryGraphEntry> {
|
||||
let entry = EpiphanyMemoryGraphEntry::from_snapshot(snapshot)?;
|
||||
write_memory_graph_entry(store_path, &entry)
|
||||
}
|
||||
|
||||
pub(crate) fn load_memory_graph_envelope(store_path: &Path) -> Result<Option<CultCacheEnvelope>> {
|
||||
Ok(SingleFileMessagePackBackingStore::new(store_path)
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.find(|candidate| {
|
||||
candidate.r#type == MEMORY_GRAPH_TYPE && candidate.key == MEMORY_GRAPH_KEY
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn replace_inspected_legacy_memory_graph(
|
||||
store_path: &Path,
|
||||
expected: Option<&CultCacheEnvelope>,
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
stored_at: &str,
|
||||
) -> Result<bool> {
|
||||
let entry = EpiphanyMemoryGraphEntry::from_snapshot(snapshot)?;
|
||||
validate_memory_graph_entry(&entry)?;
|
||||
let replacement = memory_graph_envelope(&entry, stored_at)?;
|
||||
let backing = SingleFileMessagePackBackingStore::new(store_path);
|
||||
match expected {
|
||||
Some(expected) => backing.compare_and_swap_entry(expected, replacement),
|
||||
None => backing.insert_entry_if_absent(replacement),
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_graph_envelope(
|
||||
entry: &EpiphanyMemoryGraphEntry,
|
||||
stored_at: &str,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
Ok(CultCacheEnvelope {
|
||||
key: MEMORY_GRAPH_KEY.to_string(),
|
||||
r#type: MEMORY_GRAPH_TYPE.to_string(),
|
||||
payload: rmp_serde::to_vec(entry)?,
|
||||
stored_at: stored_at.to_string(),
|
||||
schema_id: Some(MEMORY_GRAPH_TYPE.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Hashes the complete aggregate with its self-referential hash field cleared.
|
||||
pub fn memory_graph_model_hash(snapshot: &EpiphanyMemoryGraphSnapshot) -> Result<String> {
|
||||
let mut canonical = snapshot.clone();
|
||||
canonical.model_hash.clear();
|
||||
let bytes = rmp_serde::to_vec_named(&canonical)?;
|
||||
Ok(format!("{:x}", Sha256::digest(bytes)))
|
||||
}
|
||||
|
||||
/// Applies a Modeling patch as one stale-checked replacement of the existing
|
||||
/// CultCache aggregate. Validation occurs before the store is touched.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn apply_repo_model_patch(
|
||||
store_path: impl AsRef<Path>,
|
||||
patch: &RepoModelPatch,
|
||||
) -> Result<EpiphanyMemoryGraphSnapshot> {
|
||||
let store_path = store_path.as_ref();
|
||||
if patch.patch_id.trim().is_empty() || patch.applied_at.trim().is_empty() {
|
||||
return Err(anyhow!("repo model patch requires patch_id and applied_at"));
|
||||
}
|
||||
if patch.operations.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"repo model patch must contain at least one operation"
|
||||
));
|
||||
}
|
||||
chrono::DateTime::parse_from_rfc3339(&patch.applied_at)
|
||||
.map_err(|_| anyhow!("repo model patch applied_at must be RFC3339"))?;
|
||||
|
||||
let backing = SingleFileMessagePackBackingStore::new(store_path);
|
||||
let entries = backing.pull_all()?;
|
||||
let envelope = entries
|
||||
.iter()
|
||||
.find(|entry| entry.r#type == MEMORY_GRAPH_TYPE && entry.key == MEMORY_GRAPH_KEY)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow!("cannot patch a missing memory graph"))?;
|
||||
let entry: EpiphanyMemoryGraphEntry = rmp_serde::from_slice(&envelope.payload)?;
|
||||
validate_memory_graph_entry(&entry)?;
|
||||
let current = entry.snapshot()?;
|
||||
let next = derive_repo_model_patch(¤t, patch)?;
|
||||
let next_entry = EpiphanyMemoryGraphEntry::from_snapshot(&next)?;
|
||||
let next_envelope = memory_graph_envelope(&next_entry, &patch.applied_at)?;
|
||||
if !backing.compare_and_swap_entry(&envelope, next_envelope)? {
|
||||
return Err(anyhow!(
|
||||
"stale repo model patch: aggregate changed during compare-and-swap"
|
||||
));
|
||||
}
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// Purely derives and validates the next canonical aggregate. Persistence and
|
||||
/// admission authority remain the caller's responsibility.
|
||||
pub fn derive_repo_model_patch(
|
||||
current: &EpiphanyMemoryGraphSnapshot,
|
||||
patch: &RepoModelPatch,
|
||||
) -> Result<EpiphanyMemoryGraphSnapshot> {
|
||||
if patch.patch_id.trim().is_empty() || patch.applied_at.trim().is_empty() {
|
||||
return Err(anyhow!("repo model patch requires patch_id and applied_at"));
|
||||
}
|
||||
if patch.operations.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"repo model patch must contain at least one operation"
|
||||
));
|
||||
}
|
||||
chrono::DateTime::parse_from_rfc3339(&patch.applied_at)
|
||||
.map_err(|_| anyhow!("repo model patch applied_at must be RFC3339"))?;
|
||||
let current_hash = memory_graph_model_hash(current)?;
|
||||
if patch.base_revision != current.model_revision || patch.base_hash != current_hash {
|
||||
return Err(anyhow!(
|
||||
"stale repo model patch: base revision/hash {}/{} does not match current {}/{}",
|
||||
patch.base_revision,
|
||||
patch.base_hash,
|
||||
current.model_revision,
|
||||
current_hash
|
||||
));
|
||||
}
|
||||
match &patch.purpose {
|
||||
epiphany_state_model::RepoModelPatchPurpose::AdoptFrontierPlan {
|
||||
planning_request_id,
|
||||
result_id,
|
||||
candidate_id,
|
||||
} => {
|
||||
if patch.operations.len() != 1 {
|
||||
return Err(anyhow!(
|
||||
"AdoptFrontierPlan purpose requires exactly one dedicated operation"
|
||||
));
|
||||
}
|
||||
let RepoModelPatchOperation::AdoptFrontierPlan { adopted_plan, .. } =
|
||||
&patch.operations[0]
|
||||
else {
|
||||
return Err(anyhow!(
|
||||
"AdoptFrontierPlan purpose requires its dedicated operation"
|
||||
));
|
||||
};
|
||||
if adopted_plan.planning_request_id != *planning_request_id
|
||||
|| adopted_plan.result_id != *result_id
|
||||
|| adopted_plan.candidate_id != *candidate_id
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"AdoptFrontierPlan purpose and operation provenance mismatch"
|
||||
));
|
||||
}
|
||||
}
|
||||
epiphany_state_model::RepoModelPatchPurpose::RelinquishFrontierRoute { .. } => {
|
||||
if patch.operations.len() != 1
|
||||
|| !matches!(
|
||||
patch.operations[0],
|
||||
RepoModelPatchOperation::RetireFrontier { .. }
|
||||
)
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"RelinquishFrontierRoute purpose requires exactly one frontier retirement"
|
||||
));
|
||||
}
|
||||
}
|
||||
epiphany_state_model::RepoModelPatchPurpose::AmendFrontierExecution {
|
||||
route_id,
|
||||
amendment_id,
|
||||
} => {
|
||||
if patch.operations.len() != 1 {
|
||||
return Err(anyhow!(
|
||||
"AmendFrontierExecution purpose requires exactly one dedicated operation"
|
||||
));
|
||||
}
|
||||
let RepoModelPatchOperation::AmendFrontierExecution { amendment, .. } =
|
||||
&patch.operations[0]
|
||||
else {
|
||||
return Err(anyhow!(
|
||||
"AmendFrontierExecution purpose requires its dedicated operation"
|
||||
));
|
||||
};
|
||||
if amendment.replaces_route_id != *route_id || amendment.amendment_id != *amendment_id {
|
||||
return Err(anyhow!(
|
||||
"AmendFrontierExecution purpose and operation provenance mismatch"
|
||||
));
|
||||
}
|
||||
}
|
||||
_ if patch.operations.iter().any(|operation| {
|
||||
matches!(
|
||||
operation,
|
||||
RepoModelPatchOperation::AdoptFrontierPlan { .. }
|
||||
| RepoModelPatchOperation::AmendFrontierExecution { .. }
|
||||
)
|
||||
}) =>
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"only its Mind-owned purpose may carry a dedicated plan operation"
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut next = current.clone();
|
||||
if next
|
||||
.lifecycle_receipts
|
||||
.iter()
|
||||
.any(|receipt| receipt.id == patch.patch_id)
|
||||
{
|
||||
return Err(anyhow!("repo model patch_id has already been applied"));
|
||||
}
|
||||
for operation in &patch.operations {
|
||||
apply_operation(&mut next, operation, &patch.purpose, &patch.applied_at)?;
|
||||
}
|
||||
next.model_revision = next
|
||||
.model_revision
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow!("repo model revision overflow"))?;
|
||||
next.model_hash.clear();
|
||||
let node_ids = patch
|
||||
.operations
|
||||
.iter()
|
||||
.filter_map(|operation| match operation {
|
||||
RepoModelPatchOperation::UpsertNode { node }
|
||||
| RepoModelPatchOperation::ReviseNode { node } => Some(node.id.clone()),
|
||||
RepoModelPatchOperation::RetireNode { node_id } => Some(node_id.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let edge_ids = patch
|
||||
.operations
|
||||
.iter()
|
||||
.filter_map(|operation| match operation {
|
||||
RepoModelPatchOperation::UpsertEdge { edge }
|
||||
| RepoModelPatchOperation::ReviseEdge { edge } => Some(edge.id.clone()),
|
||||
RepoModelPatchOperation::RetireEdge { edge_id } => Some(edge_id.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
next.lifecycle_receipts
|
||||
.push(epiphany_state_model::EpiphanyMemoryLifecycleReceipt {
|
||||
id: patch.patch_id.clone(),
|
||||
operation: "repo_model_patch".to_string(),
|
||||
status: "applied".to_string(),
|
||||
node_ids,
|
||||
edge_ids,
|
||||
reason: Some(format!("{} typed operations", patch.operations.len())),
|
||||
created_at: Some(patch.applied_at.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
let validation_errors = validate_memory_graph_snapshot(&next);
|
||||
if !validation_errors.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"repo model patch produces invalid aggregate: {}",
|
||||
validation_errors
|
||||
.iter()
|
||||
.map(|error| format!("{}: {}", error.path, error.message))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
));
|
||||
}
|
||||
next.model_hash = memory_graph_model_hash(&next)?;
|
||||
validate_memory_graph_entry(&EpiphanyMemoryGraphEntry::from_snapshot(&next)?)?;
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
fn apply_operation(
|
||||
snapshot: &mut EpiphanyMemoryGraphSnapshot,
|
||||
operation: &RepoModelPatchOperation,
|
||||
purpose: &epiphany_state_model::RepoModelPatchPurpose,
|
||||
applied_at: &str,
|
||||
) -> Result<()> {
|
||||
match operation {
|
||||
RepoModelPatchOperation::UpsertNode { node } => {
|
||||
insert_new(&mut snapshot.nodes, node.clone(), |value| &value.id, "node")?
|
||||
}
|
||||
RepoModelPatchOperation::ReviseNode { node } => {
|
||||
revise(&mut snapshot.nodes, node.clone(), |value| &value.id, "node")?
|
||||
}
|
||||
RepoModelPatchOperation::RetireNode { node_id } => {
|
||||
let node = snapshot
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|node| &node.id == node_id)
|
||||
.ok_or_else(|| anyhow!("cannot retire missing node {node_id}"))?;
|
||||
node.lifecycle = EpiphanyMemoryLifecycle::Retired;
|
||||
node.updated_at = Some(applied_at.to_string());
|
||||
}
|
||||
RepoModelPatchOperation::UpsertEdge { edge } => {
|
||||
insert_new(&mut snapshot.edges, edge.clone(), |value| &value.id, "edge")?
|
||||
}
|
||||
RepoModelPatchOperation::ReviseEdge { edge } => {
|
||||
revise(&mut snapshot.edges, edge.clone(), |value| &value.id, "edge")?
|
||||
}
|
||||
RepoModelPatchOperation::RetireEdge { edge_id } => {
|
||||
let edge = snapshot
|
||||
.edges
|
||||
.iter_mut()
|
||||
.find(|edge| &edge.id == edge_id)
|
||||
.ok_or_else(|| anyhow!("cannot retire missing edge {edge_id}"))?;
|
||||
edge.lifecycle = EpiphanyMemoryLifecycle::Retired;
|
||||
}
|
||||
RepoModelPatchOperation::UpsertFrontier { item } => {
|
||||
if item.adopted_plan.is_some() {
|
||||
return Err(anyhow!(
|
||||
"generic frontier upsert cannot author an adopted plan"
|
||||
));
|
||||
}
|
||||
insert_new(
|
||||
&mut snapshot.frontier,
|
||||
item.clone(),
|
||||
|value| &value.id,
|
||||
"frontier item",
|
||||
)?
|
||||
}
|
||||
RepoModelPatchOperation::ReviseFrontier { item } => {
|
||||
let existing = snapshot
|
||||
.frontier
|
||||
.iter()
|
||||
.find(|existing| existing.id == item.id)
|
||||
.ok_or_else(|| anyhow!("cannot revise missing frontier item {}", item.id))?;
|
||||
let verdict_may_close_adopted = matches!(
|
||||
purpose,
|
||||
epiphany_state_model::RepoModelPatchPurpose::IncorporateFrontierVerdict { .. }
|
||||
) && existing.adopted_plan.is_some()
|
||||
&& item.adopted_plan == existing.adopted_plan
|
||||
&& item.migration_body == existing.migration_body
|
||||
&& item.question == existing.question
|
||||
&& item.target_claim_ids == existing.target_claim_ids
|
||||
&& item.source_scope == existing.source_scope
|
||||
&& item.recommended_next_organ == existing.recommended_next_organ
|
||||
&& item.dependency_item_ids == existing.dependency_item_ids
|
||||
&& item.created_at == existing.created_at
|
||||
&& item.retired_at == existing.retired_at
|
||||
&& item.superseded_by == existing.superseded_by;
|
||||
if (existing.adopted_plan.is_some() && !verdict_may_close_adopted)
|
||||
|| item.adopted_plan != existing.adopted_plan
|
||||
|| (existing.recommended_next_organ == "Imagination"
|
||||
&& item.recommended_next_organ == "Hands")
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"generic frontier revision cannot alter adopted execution anatomy or own plan adoption"
|
||||
));
|
||||
}
|
||||
revise(
|
||||
&mut snapshot.frontier,
|
||||
item.clone(),
|
||||
|value| &value.id,
|
||||
"frontier item",
|
||||
)?
|
||||
}
|
||||
RepoModelPatchOperation::RetireFrontier {
|
||||
item_id,
|
||||
retired_at,
|
||||
superseded_by,
|
||||
} => {
|
||||
let item = snapshot
|
||||
.frontier
|
||||
.iter_mut()
|
||||
.find(|item| &item.id == item_id)
|
||||
.ok_or_else(|| anyhow!("cannot retire missing frontier item {item_id}"))?;
|
||||
if item.adopted_plan.is_some()
|
||||
&& !matches!(
|
||||
purpose,
|
||||
epiphany_state_model::RepoModelPatchPurpose::RelinquishFrontierRoute {
|
||||
route_id: _,
|
||||
hands_refusal_receipt_id: _
|
||||
}
|
||||
)
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"only route relinquishment may retire an adopted frontier without a Soul verdict"
|
||||
));
|
||||
}
|
||||
item.status = if superseded_by.is_some() {
|
||||
RepoFrontierStatus::Superseded
|
||||
} else {
|
||||
RepoFrontierStatus::Retired
|
||||
};
|
||||
item.retired_at = retired_at.clone().or_else(|| Some(applied_at.to_string()));
|
||||
item.updated_at = Some(applied_at.to_string());
|
||||
item.superseded_by = superseded_by.clone();
|
||||
}
|
||||
RepoModelPatchOperation::AdoptFrontierPlan {
|
||||
frontier_item_id,
|
||||
expected_frontier_item_hash,
|
||||
adopted_plan,
|
||||
} => {
|
||||
let item = snapshot
|
||||
.frontier
|
||||
.iter_mut()
|
||||
.find(|item| &item.id == frontier_item_id)
|
||||
.ok_or_else(|| {
|
||||
anyhow!("cannot adopt plan for missing frontier item {frontier_item_id}")
|
||||
})?;
|
||||
let current_hash = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&*item)?));
|
||||
let safe_paths_are_bounded = !adopted_plan.safe_paths.is_empty()
|
||||
&& adopted_plan
|
||||
.safe_paths
|
||||
.windows(2)
|
||||
.all(|pair| pair[0] < pair[1])
|
||||
&& adopted_plan.safe_paths.iter().all(|path| {
|
||||
item.source_scope.iter().any(|scope| {
|
||||
path == scope
|
||||
|| path
|
||||
.starts_with(&format!("{}/", scope.trim_end_matches(['/', '\\'])))
|
||||
})
|
||||
});
|
||||
if current_hash != *expected_frontier_item_hash
|
||||
|| item.status != RepoFrontierStatus::Active
|
||||
|| item.recommended_next_organ != "Imagination"
|
||||
|| item.adopted_plan.is_some()
|
||||
|| adopted_plan.planning_request_id.trim().is_empty()
|
||||
|| adopted_plan.result_id.trim().is_empty()
|
||||
|| adopted_plan.job_id.trim().is_empty()
|
||||
|| adopted_plan.candidate_id.trim().is_empty()
|
||||
|| adopted_plan.candidate_sha256.trim().is_empty()
|
||||
|| adopted_plan.action.trim().is_empty()
|
||||
|| adopted_plan.command.trim().is_empty()
|
||||
|| adopted_plan.checks.is_empty()
|
||||
|| adopted_plan.stop_conditions.is_empty()
|
||||
|| adopted_plan.rollback_steps.is_empty()
|
||||
|| adopted_plan.commit_message.trim().is_empty()
|
||||
|| !safe_paths_are_bounded
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"frontier plan adoption requires the exact active Imagination frontier and complete bounded plan"
|
||||
));
|
||||
}
|
||||
item.adopted_plan = Some(adopted_plan.clone());
|
||||
item.recommended_next_organ = "Hands".to_string();
|
||||
item.updated_at = Some(applied_at.to_string());
|
||||
}
|
||||
RepoModelPatchOperation::AmendFrontierExecution {
|
||||
frontier_item_id,
|
||||
expected_frontier_item_hash,
|
||||
amendment,
|
||||
} => {
|
||||
let item = snapshot
|
||||
.frontier
|
||||
.iter_mut()
|
||||
.find(|item| &item.id == frontier_item_id)
|
||||
.ok_or_else(|| {
|
||||
anyhow!("cannot amend execution for missing frontier item {frontier_item_id}")
|
||||
})?;
|
||||
let current_hash = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&*item)?));
|
||||
let plan = item
|
||||
.adopted_plan
|
||||
.as_mut()
|
||||
.ok_or_else(|| anyhow!("frontier execution amendment requires an adopted plan"))?;
|
||||
let previous_action_sha256 = format!("{:x}", Sha256::digest(plan.action.as_bytes()));
|
||||
let previous_command_sha256 = format!("{:x}", Sha256::digest(plan.command.as_bytes()));
|
||||
if current_hash != *expected_frontier_item_hash
|
||||
|| item.status != RepoFrontierStatus::Active
|
||||
|| item.recommended_next_organ != "Hands"
|
||||
|| plan.execution_amendment.is_some()
|
||||
|| amendment.amendment_id.trim().is_empty()
|
||||
|| amendment.replaces_route_id.trim().is_empty()
|
||||
|| amendment.source_actor_id.trim().is_empty()
|
||||
|| amendment.command_id.trim().is_empty()
|
||||
|| amendment.admission_id.trim().is_empty()
|
||||
|| amendment.packet_sha256.trim().is_empty()
|
||||
|| amendment.action.trim().is_empty()
|
||||
|| amendment.command.trim().is_empty()
|
||||
|| amendment.rationale.trim().is_empty()
|
||||
|| amendment.previous_action_sha256 != previous_action_sha256
|
||||
|| amendment.previous_command_sha256 != previous_command_sha256
|
||||
|| chrono::DateTime::parse_from_rfc3339(&amendment.amended_at).is_err()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"frontier execution amendment requires the exact current Hands plan and complete authenticated provenance"
|
||||
));
|
||||
}
|
||||
plan.execution_amendment = Some(amendment.clone());
|
||||
item.updated_at = Some(applied_at.to_string());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_new<T>(
|
||||
values: &mut Vec<T>,
|
||||
value: T,
|
||||
id: impl Fn(&T) -> &String,
|
||||
kind: &str,
|
||||
) -> Result<()> {
|
||||
let value_id = id(&value).clone();
|
||||
if values.iter().any(|existing| id(existing) == &value_id) {
|
||||
return Err(anyhow!(
|
||||
"cannot upsert existing {kind} {value_id}; use revise"
|
||||
));
|
||||
}
|
||||
values.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn revise<T>(values: &mut [T], value: T, id: impl Fn(&T) -> &String, kind: &str) -> Result<()> {
|
||||
let value_id = id(&value).clone();
|
||||
let Some(index) = values.iter().position(|existing| id(existing) == &value_id) else {
|
||||
return Err(anyhow!("cannot revise missing {kind} {value_id}"));
|
||||
};
|
||||
values[index] = value;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_memory_graph_entry(entry: &EpiphanyMemoryGraphEntry) -> Result<()> {
|
||||
if entry.schema_version != MEMORY_GRAPH_SCHEMA_VERSION {
|
||||
return Err(anyhow!(
|
||||
"memory graph schema_version is {:?}, expected {:?}",
|
||||
entry.schema_version,
|
||||
MEMORY_GRAPH_SCHEMA_VERSION
|
||||
));
|
||||
}
|
||||
let snapshot = entry.snapshot()?;
|
||||
if snapshot.schema_version.as_deref() != Some(MEMORY_GRAPH_SCHEMA_VERSION) {
|
||||
return Err(anyhow!(
|
||||
"memory graph snapshot schema_version is {:?}, expected {:?}",
|
||||
snapshot.schema_version,
|
||||
MEMORY_GRAPH_SCHEMA_VERSION
|
||||
));
|
||||
}
|
||||
if entry.graph_id != snapshot.graph_id {
|
||||
return Err(anyhow!(
|
||||
"memory graph entry graph_id {:?} does not match snapshot graph_id {:?}",
|
||||
entry.graph_id,
|
||||
snapshot.graph_id
|
||||
));
|
||||
}
|
||||
let legacy = snapshot.model_revision == 0
|
||||
&& snapshot.model_hash.is_empty()
|
||||
&& snapshot.frontier.is_empty();
|
||||
let canonical = snapshot.model_revision > 0
|
||||
&& !snapshot.model_hash.is_empty()
|
||||
&& snapshot.model_hash == memory_graph_model_hash(&snapshot)?;
|
||||
if !legacy && !canonical {
|
||||
return Err(anyhow!(
|
||||
"memory graph identity must be exactly legacy (revision 0, empty hash/frontier) or canonical (positive revision, exact nonempty hash)"
|
||||
));
|
||||
}
|
||||
let errors = validate_memory_graph_snapshot(&snapshot);
|
||||
if !errors.is_empty() {
|
||||
let message = errors
|
||||
.iter()
|
||||
.map(|error| format!("{}: {}", error.path, error.message))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
return Err(anyhow!("memory graph validation failed: {message}"));
|
||||
}
|
||||
let dirty = snapshot
|
||||
.freshness
|
||||
.as_ref()
|
||||
.map(|freshness| freshness.dirty_source_hashes.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
let derived = derive_memory_graph_freshness(&snapshot, dirty);
|
||||
if snapshot.frontier.iter().any(|item| {
|
||||
matches!(
|
||||
item.status,
|
||||
RepoFrontierStatus::Active | RepoFrontierStatus::Proposed | RepoFrontierStatus::Blocked
|
||||
) && item
|
||||
.target_claim_ids
|
||||
.iter()
|
||||
.any(|id| derived.stale_node_ids.contains(id))
|
||||
}) {
|
||||
return Err(anyhow!(
|
||||
"unresolved frontier targets a stale source-derived claim"
|
||||
));
|
||||
}
|
||||
if snapshot.freshness.as_ref().is_some_and(|stored| {
|
||||
stored.status != derived.status
|
||||
|| stored.stale_node_ids != derived.stale_node_ids
|
||||
|| stored.stale_edge_ids != derived.stale_edge_ids
|
||||
|| stored.stale_summary_ids != derived.stale_summary_ids
|
||||
}) {
|
||||
return Err(anyhow!(
|
||||
"memory graph stored freshness disagrees with derived lifecycle/source freshness"
|
||||
));
|
||||
}
|
||||
if snapshot.summaries.iter().any(|summary| {
|
||||
derived.stale_summary_ids.contains(&summary.id)
|
||||
&& summary.freshness != EpiphanyMemoryFreshnessStatus::Stale
|
||||
}) {
|
||||
return Err(anyhow!(
|
||||
"memory graph has a ready summary covering stale anatomy"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -174,6 +174,13 @@ pub(crate) fn register_mind_document_types(cache: &mut CultCache) -> Result<()>
|
|||
cache.register_entry_type::<EpiphanyMindRoadmapStreamDocument>()?;
|
||||
cache.register_entry_type::<EpiphanyMindObjectiveDraftDocument>()?;
|
||||
crate::repo_model_documents::register_repo_model_document_types(cache)?;
|
||||
cache.register_entry_type::<crate::RepoFrontierPlanDecisionReceipt>()?;
|
||||
cache.register_entry_type::<crate::RepoFrontierRelinquishmentReceipt>()?;
|
||||
cache.register_entry_type::<crate::RepoFrontierExecutionAmendmentReceipt>()?;
|
||||
cache.register_entry_type::<crate::AtlasSurfaceOffer>()?;
|
||||
cache.register_entry_type::<crate::AtlasDependencyClaim>()?;
|
||||
cache.register_entry_type::<crate::AtlasDependencyVerification>()?;
|
||||
cache.register_entry_type::<crate::AtlasDependencyImpact>()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -186,7 +193,32 @@ pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Resu
|
|||
}
|
||||
return Ok(());
|
||||
}
|
||||
let expected_key = if envelope.r#type == EpiphanyMindIdentity::TYPE {
|
||||
let expected_key = if envelope.r#type == crate::RepoFrontierPlanDecisionReceipt::TYPE {
|
||||
rmp_serde::from_slice::<crate::RepoFrontierPlanDecisionReceipt>(&envelope.payload)?
|
||||
.decision_id
|
||||
} else if envelope.r#type == crate::RepoFrontierRelinquishmentReceipt::TYPE {
|
||||
rmp_serde::from_slice::<crate::RepoFrontierRelinquishmentReceipt>(&envelope.payload)?
|
||||
.receipt_id
|
||||
} else if envelope.r#type == crate::RepoFrontierExecutionAmendmentReceipt::TYPE {
|
||||
rmp_serde::from_slice::<crate::RepoFrontierExecutionAmendmentReceipt>(&envelope.payload)?
|
||||
.receipt_id
|
||||
} else if envelope.r#type == crate::AtlasSurfaceOffer::TYPE {
|
||||
let value: crate::AtlasSurfaceOffer = rmp_serde::from_slice(&envelope.payload)?;
|
||||
value.validate()?;
|
||||
value.surface_id.to_string()
|
||||
} else if envelope.r#type == crate::AtlasDependencyClaim::TYPE {
|
||||
let value: crate::AtlasDependencyClaim = rmp_serde::from_slice(&envelope.payload)?;
|
||||
value.validate()?;
|
||||
value.claim_id.to_string()
|
||||
} else if envelope.r#type == crate::AtlasDependencyVerification::TYPE {
|
||||
let value: crate::AtlasDependencyVerification = rmp_serde::from_slice(&envelope.payload)?;
|
||||
value.validate()?;
|
||||
value.claim_id.to_string()
|
||||
} else if envelope.r#type == crate::AtlasDependencyImpact::TYPE {
|
||||
let value: crate::AtlasDependencyImpact = rmp_serde::from_slice(&envelope.payload)?;
|
||||
value.validate()?;
|
||||
value.impact_id.to_string()
|
||||
} else if envelope.r#type == EpiphanyMindIdentity::TYPE {
|
||||
let value: EpiphanyMindIdentity = rmp_serde::from_slice(&envelope.payload)?;
|
||||
if value.schema_epoch != MIND_SCHEMA_EPOCH || value.runtime_id.trim().is_empty() {
|
||||
return Err(anyhow!("Mind identity write is invalid"));
|
||||
|
|
|
|||
|
|
@ -491,7 +491,7 @@ mod tests {
|
|||
evidence_gaps: Vec::new(),
|
||||
risks: Vec::new(),
|
||||
state_patch: None,
|
||||
repo_model_patch: None,
|
||||
repo_model_mutation_proposal: None,
|
||||
self_patch: None,
|
||||
self_persistence: None,
|
||||
job_error: None,
|
||||
|
|
|
|||
|
|
@ -19,17 +19,12 @@ use crate::{
|
|||
};
|
||||
|
||||
pub const BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str =
|
||||
"bifrost.operator_command.delivery.v1";
|
||||
pub const LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str =
|
||||
"bifrost.operator_command.delivery.v0";
|
||||
"bifrost.operator_command.delivery.v2";
|
||||
pub const BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE: &str = "bifrost.operator_command.delivery";
|
||||
pub const LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str =
|
||||
"epiphany.operator_command.admitted.v1";
|
||||
pub const LEGACY_LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str =
|
||||
"epiphany.operator_command.admitted.v0";
|
||||
pub const OPERATOR_COMMAND_RESULT_SCHEMA_VERSION: &str = "epiphany.operator_command.result.v1";
|
||||
const SIGNING_PURPOSE: &str = "bifrost.operator-command.delivery.v1";
|
||||
const LEGACY_SIGNING_PURPOSE: &str = "bifrost.operator-command.delivery.v0";
|
||||
"epiphany.operator_command.admitted.v2";
|
||||
pub const OPERATOR_COMMAND_RESULT_SCHEMA_VERSION: &str = "epiphany.operator_command.result.v2";
|
||||
const SIGNING_PURPOSE: &str = "bifrost.operator-command.delivery.v2";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
|
|
@ -63,8 +58,8 @@ pub enum OperatorCommand {
|
|||
mind_request_id: String,
|
||||
candidate_id: String,
|
||||
candidate_sha256: String,
|
||||
expected_model_revision: u64,
|
||||
expected_model_hash: String,
|
||||
expected_model_projection_digest: String,
|
||||
expected_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
decision: RepoFrontierPlanDecision,
|
||||
},
|
||||
}
|
||||
|
|
@ -259,6 +254,17 @@ fn command_cache(path: &Path) -> Result<CultCache> {
|
|||
};
|
||||
}
|
||||
}
|
||||
if cache
|
||||
.get_all::<LocalAdmittedOperatorCommand>()?
|
||||
.iter()
|
||||
.any(|entry| entry.schema_version != LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION)
|
||||
|| cache
|
||||
.get_all::<OperatorCommandResult>()?
|
||||
.iter()
|
||||
.any(|entry| entry.schema_version != OPERATOR_COMMAND_RESULT_SCHEMA_VERSION)
|
||||
{
|
||||
bail!("operator command store contains an unsupported schema");
|
||||
}
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
|
|
@ -284,9 +290,14 @@ fn validate_admission(
|
|||
mind_request_id,
|
||||
candidate_id,
|
||||
candidate_sha256,
|
||||
expected_model_hash,
|
||||
expected_model_projection_digest,
|
||||
expected_model_source_documents,
|
||||
..
|
||||
} => {
|
||||
let model_basis = crate::EpiphanyRepoModelBasis {
|
||||
projection_digest: expected_model_projection_digest.clone(),
|
||||
source_documents: expected_model_source_documents.clone(),
|
||||
};
|
||||
!mind_request_id.trim().is_empty()
|
||||
&& mind_request_id.len() <= 256
|
||||
&& !candidate_id.trim().is_empty()
|
||||
|
|
@ -295,24 +306,12 @@ fn validate_admission(
|
|||
&& candidate_sha256
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit())
|
||||
&& expected_model_hash.len() == 64
|
||||
&& expected_model_hash
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit())
|
||||
&& model_basis.validate().is_ok()
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
let legacy_admission =
|
||||
admission.schema_version == LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION;
|
||||
let admission_version_valid = admission.schema_version
|
||||
== BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION
|
||||
|| (legacy_admission
|
||||
&& !matches!(
|
||||
&packet.command,
|
||||
OperatorCommand::Reviews | OperatorCommand::Review { .. }
|
||||
));
|
||||
if admission.schema_name != BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE
|
||||
|| !admission_version_valid
|
||||
|| admission.schema_version != BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION
|
||||
|| admission.admission_id.trim().is_empty()
|
||||
|| packet.command_id.trim().is_empty()
|
||||
|| packet.nonce.trim().is_empty()
|
||||
|
|
@ -349,11 +348,7 @@ fn validate_admission(
|
|||
}
|
||||
verify_host_identity_trust_anchor_signature(
|
||||
anchor,
|
||||
if legacy_admission {
|
||||
LEGACY_SIGNING_PURPOSE
|
||||
} else {
|
||||
SIGNING_PURPOSE
|
||||
},
|
||||
SIGNING_PURPOSE,
|
||||
&operator_command_admission_signing_payload(admission)?,
|
||||
&HostIdentitySignature {
|
||||
identity_id: admission.provider_identity_id.clone(),
|
||||
|
|
@ -378,13 +373,7 @@ pub fn admit_and_execute_bifrost_operator_command(
|
|||
validate_admission(admission, trusted_bifrost_identity, policy, now_dt, false)?;
|
||||
let packet = &admission.packet;
|
||||
let mut admitted = LocalAdmittedOperatorCommand {
|
||||
schema_version: if admission.schema_version
|
||||
== LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION
|
||||
{
|
||||
LEGACY_LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into()
|
||||
} else {
|
||||
LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into()
|
||||
},
|
||||
schema_version: LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(),
|
||||
command_id: packet.command_id.clone(),
|
||||
admission_id: admission.admission_id.clone(),
|
||||
nonce: packet.nonce.clone(),
|
||||
|
|
@ -685,8 +674,8 @@ pub fn admit_and_execute_bifrost_operator_command(
|
|||
mind_request_id,
|
||||
candidate_id,
|
||||
candidate_sha256,
|
||||
expected_model_revision,
|
||||
expected_model_hash,
|
||||
expected_model_projection_digest,
|
||||
expected_model_source_documents,
|
||||
decision,
|
||||
} => {
|
||||
let review = RepoFrontierPlanOperatorReview {
|
||||
|
|
@ -697,8 +686,8 @@ pub fn admit_and_execute_bifrost_operator_command(
|
|||
mind_request_id: mind_request_id.clone(),
|
||||
candidate_id: candidate_id.clone(),
|
||||
candidate_sha256: candidate_sha256.clone(),
|
||||
expected_model_revision: *expected_model_revision,
|
||||
expected_model_hash: expected_model_hash.clone(),
|
||||
expected_model_projection_digest: expected_model_projection_digest.clone(),
|
||||
expected_model_source_documents: expected_model_source_documents.clone(),
|
||||
decision: *decision,
|
||||
decided_at: packet.issued_at.clone(),
|
||||
};
|
||||
|
|
@ -819,7 +808,6 @@ fn issued_millis(value: &str) -> Result<u64> {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use cultcache_rs::CultCacheEnvelope;
|
||||
|
||||
fn policy() -> OperatorCommandPolicy {
|
||||
OperatorCommandPolicy {
|
||||
|
|
@ -882,22 +870,6 @@ mod tests {
|
|||
Ok(admission)
|
||||
}
|
||||
|
||||
fn legacy_signed(
|
||||
signer: &crate::HostIdentitySigner,
|
||||
id: &str,
|
||||
command: OperatorCommand,
|
||||
) -> Result<BifrostOperatorCommandAdmission> {
|
||||
let mut admission = signed(signer, id, command)?;
|
||||
admission.schema_version = LEGACY_BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into();
|
||||
admission.provider_signature = signer
|
||||
.sign(
|
||||
LEGACY_SIGNING_PURPOSE,
|
||||
&operator_command_admission_signing_payload(&admission)?,
|
||||
)?
|
||||
.signature;
|
||||
Ok(admission)
|
||||
}
|
||||
|
||||
fn snapshot() -> crate::EpiphanyCultMeshOperatorSnapshotEntry {
|
||||
crate::EpiphanyCultMeshOperatorSnapshotEntry {
|
||||
schema_version: crate::EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_SCHEMA_VERSION.into(),
|
||||
|
|
@ -969,8 +941,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_v0_delivery_replays_across_v1_cutover_but_cannot_carry_review_commands() -> Result<()>
|
||||
{
|
||||
fn superseded_delivery_schema_is_rejected_without_local_writes() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?;
|
||||
let anchor =
|
||||
|
|
@ -981,139 +952,28 @@ mod tests {
|
|||
temp.path().join("resident.cc"),
|
||||
temp.path().join("runtime.cc"),
|
||||
);
|
||||
let legacy = legacy_signed(
|
||||
let mut superseded = signed(
|
||||
&signer,
|
||||
"legacy-sleep",
|
||||
"superseded-sleep",
|
||||
OperatorCommand::Sleep {
|
||||
reason: "Drain the v0 delivery.".into(),
|
||||
reason: "This packet uses the superseded delivery contract.".into(),
|
||||
},
|
||||
)?;
|
||||
let first = admit_and_execute_bifrost_operator_command(
|
||||
&commands,
|
||||
&verse,
|
||||
&resident,
|
||||
&runtime,
|
||||
&legacy,
|
||||
&anchor,
|
||||
&policy(),
|
||||
"2026-07-19T12:00:00Z",
|
||||
)?;
|
||||
let replay = admit_and_execute_bifrost_operator_command(
|
||||
&commands,
|
||||
&verse,
|
||||
&resident,
|
||||
&runtime,
|
||||
&legacy,
|
||||
&anchor,
|
||||
&policy(),
|
||||
"2026-07-19T12:10:00Z",
|
||||
)?;
|
||||
assert_eq!(replay, first);
|
||||
let review = legacy_signed(&signer, "legacy-review", OperatorCommand::Reviews)?;
|
||||
superseded.schema_version = "bifrost.operator_command.delivery.v1".into();
|
||||
assert!(
|
||||
admit_and_execute_bifrost_operator_command(
|
||||
&commands,
|
||||
&verse,
|
||||
&resident,
|
||||
&runtime,
|
||||
&review,
|
||||
&superseded,
|
||||
&anchor,
|
||||
&policy(),
|
||||
"2026-07-19T12:00:00Z",
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_v0_command_ledger_replays_after_v1_cutover() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?;
|
||||
let anchor =
|
||||
crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?;
|
||||
let (commands, verse, resident, runtime) = (
|
||||
temp.path().join("commands.cc"),
|
||||
temp.path().join("verse.cc"),
|
||||
temp.path().join("resident.cc"),
|
||||
temp.path().join("runtime.cc"),
|
||||
);
|
||||
let legacy = legacy_signed(&signer, "persisted-v0", OperatorCommand::Status)?;
|
||||
let packet = &legacy.packet;
|
||||
let result_id = format!(
|
||||
"operator-command-result-{:x}",
|
||||
Sha256::digest(format!("{}:{}", packet.command_id, legacy.packet_sha256).as_bytes())
|
||||
);
|
||||
let admitted_at = "2026-07-19T12:00:00Z";
|
||||
let old_admission = (
|
||||
LEGACY_LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION,
|
||||
packet.command_id.as_str(),
|
||||
legacy.admission_id.as_str(),
|
||||
packet.nonce.as_str(),
|
||||
legacy.packet_sha256.as_str(),
|
||||
packet.source_actor_id.as_str(),
|
||||
"status",
|
||||
packet.target_runtime_id.as_str(),
|
||||
admitted_at,
|
||||
packet.expires_at.as_str(),
|
||||
"exact-command-only",
|
||||
false,
|
||||
);
|
||||
let old_result = (
|
||||
"epiphany.operator_command.result.v0",
|
||||
result_id.as_str(),
|
||||
packet.command_id.as_str(),
|
||||
legacy.packet_sha256.as_str(),
|
||||
packet.target_runtime_id.as_str(),
|
||||
"observed",
|
||||
"operator_snapshot",
|
||||
"snapshot-v0",
|
||||
admitted_at,
|
||||
false,
|
||||
"sleeping",
|
||||
"ready",
|
||||
"none",
|
||||
"engaged",
|
||||
"persisted v0 result",
|
||||
);
|
||||
let backing = SingleFileMessagePackBackingStore::new(&commands);
|
||||
for (key, ty, payload) in [
|
||||
(
|
||||
packet.command_id.as_str(),
|
||||
LocalAdmittedOperatorCommand::TYPE,
|
||||
rmp_serde::to_vec(&old_admission)?,
|
||||
),
|
||||
(
|
||||
result_id.as_str(),
|
||||
OperatorCommandResult::TYPE,
|
||||
rmp_serde::to_vec(&old_result)?,
|
||||
),
|
||||
] {
|
||||
assert!(backing.insert_entry_if_absent(CultCacheEnvelope {
|
||||
key: key.into(),
|
||||
r#type: ty.into(),
|
||||
payload,
|
||||
stored_at: admitted_at.into(),
|
||||
schema_id: Some(ty.into()),
|
||||
})?);
|
||||
}
|
||||
|
||||
let replay = admit_and_execute_bifrost_operator_command(
|
||||
&commands,
|
||||
&verse,
|
||||
&resident,
|
||||
&runtime,
|
||||
&legacy,
|
||||
&anchor,
|
||||
&policy(),
|
||||
admitted_at,
|
||||
)?;
|
||||
assert_eq!(replay.schema_version, "epiphany.operator_command.result.v0");
|
||||
assert_eq!(replay.consequence_ref, "snapshot-v0");
|
||||
assert!(replay.reviews.is_empty());
|
||||
assert!(replay.review_candidate_id.is_empty());
|
||||
assert!(replay.review_decision.is_empty());
|
||||
assert!(!verse.exists() && !resident.exists() && !runtime.exists());
|
||||
assert!(!commands.exists() && !verse.exists() && !resident.exists() && !runtime.exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -1196,7 +1056,10 @@ mod tests {
|
|||
"coordinator.run",
|
||||
"persona.public_speech",
|
||||
"daemon.tool_invocation",
|
||||
"daemon.lifecycle_poke"
|
||||
"daemon.lifecycle_poke",
|
||||
"atlas.publish",
|
||||
"atlas.project",
|
||||
"atlas.impact_ingress"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
|
|
@ -1389,95 +1252,4 @@ mod tests {
|
|||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_replay_recovers_after_mind_consequence_without_command_result() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let (runtime, planning, _, request) =
|
||||
crate::coordinator_launch::tests::operator_review_candidate_fixture(
|
||||
temp.path(),
|
||||
"operator-command-crash",
|
||||
)?;
|
||||
let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?;
|
||||
let anchor =
|
||||
crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?;
|
||||
let (commands, verse, resident) = (
|
||||
temp.path().join("commands.cc"),
|
||||
temp.path().join("verse.cc"),
|
||||
temp.path().join("resident.cc"),
|
||||
);
|
||||
let admission = signed(
|
||||
&signer,
|
||||
"review-crash-recovery",
|
||||
OperatorCommand::Review {
|
||||
mind_request_id: request.request_id.clone(),
|
||||
candidate_id: request.candidate_id.clone(),
|
||||
candidate_sha256: request.candidate_sha256.clone(),
|
||||
expected_model_revision: planning.model_revision,
|
||||
expected_model_hash: planning.model_hash.clone(),
|
||||
decision: RepoFrontierPlanDecision::Hold,
|
||||
},
|
||||
)?;
|
||||
let packet = &admission.packet;
|
||||
let admitted = LocalAdmittedOperatorCommand {
|
||||
schema_version: LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(),
|
||||
command_id: packet.command_id.clone(),
|
||||
admission_id: admission.admission_id.clone(),
|
||||
nonce: packet.nonce.clone(),
|
||||
packet_sha256: admission.packet_sha256.clone(),
|
||||
source_actor_id: packet.source_actor_id.clone(),
|
||||
capability: "review".into(),
|
||||
target_runtime_id: packet.target_runtime_id.clone(),
|
||||
admitted_at: "2026-07-19T12:00:00Z".into(),
|
||||
expires_at: packet.expires_at.clone(),
|
||||
authority: "exact-command-only".into(),
|
||||
private_state_exposed: false,
|
||||
};
|
||||
let cache = command_cache(&commands)?;
|
||||
let (entry, _) = cache.prepare_entry(&packet.command_id, &admitted)?;
|
||||
assert!(SingleFileMessagePackBackingStore::new(&commands).insert_entry_if_absent(entry)?);
|
||||
let canonical = commit_operator_repo_frontier_plan_review(
|
||||
&runtime,
|
||||
&RepoFrontierPlanOperatorReview {
|
||||
command_id: packet.command_id.clone(),
|
||||
admission_id: admission.admission_id.clone(),
|
||||
packet_sha256: admission.packet_sha256.clone(),
|
||||
source_actor_id: packet.source_actor_id.clone(),
|
||||
mind_request_id: request.request_id,
|
||||
candidate_id: request.candidate_id,
|
||||
candidate_sha256: request.candidate_sha256,
|
||||
expected_model_revision: planning.model_revision,
|
||||
expected_model_hash: planning.model_hash,
|
||||
decision: RepoFrontierPlanDecision::Hold,
|
||||
decided_at: packet.issued_at.clone(),
|
||||
},
|
||||
)?;
|
||||
let recovered = admit_and_execute_bifrost_operator_command(
|
||||
&commands,
|
||||
&verse,
|
||||
&resident,
|
||||
&runtime,
|
||||
&admission,
|
||||
&anchor,
|
||||
&policy(),
|
||||
"2026-07-19T12:00:00Z",
|
||||
)?;
|
||||
assert_eq!(recovered.disposition, "applied");
|
||||
assert_eq!(recovered.consequence_ref, canonical.decision_id);
|
||||
assert_eq!(recovered.review_decision, "hold");
|
||||
assert_eq!(
|
||||
admit_and_execute_bifrost_operator_command(
|
||||
&commands,
|
||||
&verse,
|
||||
&resident,
|
||||
&runtime,
|
||||
&admission,
|
||||
&anchor,
|
||||
&policy(),
|
||||
"2026-07-19T12:00:01Z",
|
||||
)?,
|
||||
recovered
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,8 +29,8 @@ use crate::{
|
|||
pub const EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_TYPE: &str =
|
||||
"epiphany.operator_command.sealed_result";
|
||||
pub const EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.operator_command.sealed_result.v1";
|
||||
const RESULT_SIGNING_PURPOSE: &str = "epiphany.operator-command.sealed-result.v1";
|
||||
"epiphany.operator_command.sealed_result.v2";
|
||||
const RESULT_SIGNING_PURPOSE: &str = "epiphany.operator-command.sealed-result.v2";
|
||||
pub const EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID: u32 = 0xe91f_0001;
|
||||
pub const EPIPHANY_OPERATOR_COMMAND_SERVICE_HEALTH_SCHEMA_VERSION: &str =
|
||||
"epiphany.operator_command.service_health.v0";
|
||||
|
|
@ -948,6 +948,26 @@ pub fn write_operator_command_interop_fixture(
|
|||
&admission_bytes,
|
||||
"2026-07-19T12:00:01Z",
|
||||
)?;
|
||||
let model_payload_msgpack = rmp_serde::to_vec_named(&(
|
||||
"epiphany.repo_model.epoch.v1",
|
||||
"fixture-repo-model",
|
||||
"epiphany-interop-fixture",
|
||||
"fixture-swarm",
|
||||
"fixture-workspace",
|
||||
format!("sha256:{}", "b".repeat(64)),
|
||||
))?;
|
||||
let model_source_documents = vec![crate::EpiphanyMindDocumentVersion {
|
||||
store_id: "epiphany-mind".into(),
|
||||
document_type: "epiphany.mind.repo_model.identity.v1".into(),
|
||||
document_key: "repo-model".into(),
|
||||
schema_id: Some("EpiphanyRepoModelIdentityDocument".into()),
|
||||
payload_sha256: format!("sha256:{:x}", Sha256::digest(&model_payload_msgpack)),
|
||||
payload_msgpack: model_payload_msgpack,
|
||||
}];
|
||||
let model_projection_digest = format!(
|
||||
"sha256:{:x}",
|
||||
Sha256::digest(rmp_serde::to_vec_named(&model_source_documents)?)
|
||||
);
|
||||
let receipt_bytes = rmp_serde::to_vec_named(&receipt)?;
|
||||
std::fs::write(output.join("operator-admission.msgpack"), &admission_bytes)?;
|
||||
std::fs::write(
|
||||
|
|
@ -960,7 +980,7 @@ pub fn write_operator_command_interop_fixture(
|
|||
)?;
|
||||
std::fs::write(output.join("sealed-result.msgpack"), &receipt_bytes)?;
|
||||
let protocol = serde_json::json!({
|
||||
"schemaVersion": "epiphany.operator_command.protocol_fixture.v1",
|
||||
"schemaVersion": "epiphany.operator_command.protocol_fixture.v2",
|
||||
"admissionSchemaVersion": crate::BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION,
|
||||
"resultSchemaVersion": crate::OPERATOR_COMMAND_RESULT_SCHEMA_VERSION,
|
||||
"sealedResultSchemaVersion": EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION,
|
||||
|
|
@ -976,8 +996,8 @@ pub fn write_operator_command_interop_fixture(
|
|||
mind_request_id: "mind-request-fixture-1".into(),
|
||||
candidate_id: "candidate-fixture-1".into(),
|
||||
candidate_sha256: "1".repeat(64),
|
||||
expected_model_revision: 41,
|
||||
expected_model_hash: "2".repeat(64),
|
||||
expected_model_projection_digest: model_projection_digest.clone(),
|
||||
expected_model_source_documents: model_source_documents.clone(),
|
||||
decision: crate::RepoFrontierPlanDecision::Adopt,
|
||||
})?,
|
||||
],
|
||||
|
|
@ -1006,8 +1026,8 @@ pub fn write_operator_command_interop_fixture(
|
|||
mind_request_id: "mind-request-fixture-1".into(),
|
||||
candidate_id: "candidate-fixture-1".into(),
|
||||
candidate_sha256: "1".repeat(64),
|
||||
model_revision: 41,
|
||||
model_hash: "2".repeat(64),
|
||||
model_projection_digest: model_projection_digest,
|
||||
model_source_documents: model_source_documents,
|
||||
frontier_item_id: "frontier-fixture-1".into(),
|
||||
requested_at: "2026-07-19T11:59:00Z".into(),
|
||||
}],
|
||||
|
|
@ -1509,8 +1529,24 @@ mod tests {
|
|||
);
|
||||
let review = &protocol["commands"][5];
|
||||
assert!(review.get("mindRequestId").is_some());
|
||||
assert!(review.get("expectedModelRevision").is_some());
|
||||
assert!(review.get("expectedModelProjectionDigest").is_some());
|
||||
assert!(review.get("expectedModelSourceDocuments").is_some());
|
||||
assert!(review.get("expectedModelRevision").is_none());
|
||||
assert!(review.get("expectedModelHash").is_none());
|
||||
assert!(review.get("mind_request_id").is_none());
|
||||
let crate::OperatorCommand::Review {
|
||||
expected_model_projection_digest,
|
||||
expected_model_source_documents,
|
||||
..
|
||||
} = serde_json::from_value(review.clone())?
|
||||
else {
|
||||
unreachable!("review fixture decoded as another command")
|
||||
};
|
||||
crate::EpiphanyRepoModelBasis {
|
||||
projection_digest: expected_model_projection_digest,
|
||||
source_documents: expected_model_source_documents,
|
||||
}
|
||||
.validate()?;
|
||||
assert_eq!(
|
||||
protocol["boundedReviewResult"]["reviews"]
|
||||
.as_array()
|
||||
|
|
|
|||
|
|
@ -614,8 +614,7 @@ fn build_persona_retention_member(
|
|||
|| conversation.outcome != terminal.outcome
|
||||
|| conversation.heartbeat_terminal_receipt_id.as_deref()
|
||||
!= Some(terminal.receipt_id.as_str())
|
||||
|| conversation.model_terminal_receipt_id.as_deref()
|
||||
!= Some(model_terminal_id.as_str())
|
||||
|| conversation.model_terminal_receipt_id.as_deref() != Some(model_terminal_id.as_str())
|
||||
|| conversation.private_state_exposed
|
||||
{
|
||||
return Err(anyhow!(
|
||||
|
|
@ -1132,11 +1131,9 @@ fn validate_model_terminal(
|
|||
let context_id = &terminal.decision_context_ids[index];
|
||||
let context = runtime_document::<EpiphanyDecisionContext>(runtime_store, context_id)?
|
||||
.ok_or_else(|| anyhow!("Persona {expected} decision context is missing"))?;
|
||||
let basis = runtime_document::<EpiphanyReasoningBasis>(
|
||||
runtime_store,
|
||||
&receipt.reasoning_basis_id,
|
||||
)?
|
||||
.ok_or_else(|| anyhow!("Persona {expected} reasoning basis is missing"))?;
|
||||
let basis =
|
||||
runtime_document::<EpiphanyReasoningBasis>(runtime_store, &receipt.reasoning_basis_id)?
|
||||
.ok_or_else(|| anyhow!("Persona {expected} reasoning basis is missing"))?;
|
||||
context.validate(&basis)?;
|
||||
let expected_predecessors = if index == 0 {
|
||||
Vec::new()
|
||||
|
|
@ -1396,12 +1393,8 @@ mod tests {
|
|||
);
|
||||
native.reasoning_basis_id = Some(basis.basis_id.clone());
|
||||
let provider = epiphany_openai_adapter::request_from_native(&native);
|
||||
let context = crate::EpiphanyDecisionContext::new(
|
||||
&basis,
|
||||
native,
|
||||
provider,
|
||||
Vec::new(),
|
||||
)?;
|
||||
let context =
|
||||
crate::EpiphanyDecisionContext::new(&basis, native, provider, Vec::new())?;
|
||||
put_runtime_document(runtime_store, &context.context_id, &context)?;
|
||||
context_ids.push(context.context_id.clone());
|
||||
put_runtime_document(
|
||||
|
|
@ -1592,24 +1585,30 @@ mod tests {
|
|||
.expect("conversation must route to its model terminal"),
|
||||
)?
|
||||
.expect("retention must preserve the model terminal");
|
||||
assert!(runtime_document::<PersonaInterpreterEffectDocument>(
|
||||
&runtime,
|
||||
&retired_conversation.effect_document_id,
|
||||
)?
|
||||
.is_some());
|
||||
assert!(runtime_document::<EpiphanyDecisionContext>(
|
||||
&runtime,
|
||||
retired_conversation
|
||||
.interpreter_decision_context_id
|
||||
.as_deref()
|
||||
.expect("conversation must route to its interpreter context"),
|
||||
)?
|
||||
.is_some());
|
||||
assert!(runtime_document::<PersonaModelStageReceipt>(
|
||||
&runtime,
|
||||
&retired_terminal.stage_receipt_ids[0],
|
||||
)?
|
||||
.is_none());
|
||||
assert!(
|
||||
runtime_document::<PersonaInterpreterEffectDocument>(
|
||||
&runtime,
|
||||
&retired_conversation.effect_document_id,
|
||||
)?
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
runtime_document::<EpiphanyDecisionContext>(
|
||||
&runtime,
|
||||
retired_conversation
|
||||
.interpreter_decision_context_id
|
||||
.as_deref()
|
||||
.expect("conversation must route to its interpreter context"),
|
||||
)?
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
runtime_document::<PersonaModelStageReceipt>(
|
||||
&runtime,
|
||||
&retired_terminal.stage_receipt_ids[0],
|
||||
)?
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
runtime_document::<PersonaConversationExecutionReceipt>(
|
||||
&runtime,
|
||||
|
|
|
|||
|
|
@ -973,11 +973,8 @@ mod tests {
|
|||
};
|
||||
insert_pending_persona_feedback_bridge_receipt(&feedback_store, &pending)?;
|
||||
assert!(
|
||||
bridged_persona_feedback_ready_for_cognition(
|
||||
&feedback_store,
|
||||
"epiphany-yggdrasil"
|
||||
)?
|
||||
.is_empty()
|
||||
bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let recovered = bridge_admitted_persona_feedback_to_heartbeat(
|
||||
|
|
@ -990,10 +987,7 @@ mod tests {
|
|||
assert_eq!(recovered.len(), 1);
|
||||
assert_eq!(recovered[0].status, "queued");
|
||||
assert_eq!(
|
||||
bridged_persona_feedback_ready_for_cognition(
|
||||
&feedback_store,
|
||||
"epiphany-yggdrasil"
|
||||
)?,
|
||||
bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?,
|
||||
vec![admitted]
|
||||
);
|
||||
let state = crate::load_heartbeat_state_entry(&heartbeat_store)?.expect("heartbeat state");
|
||||
|
|
@ -1065,11 +1059,8 @@ mod tests {
|
|||
},
|
||||
)?;
|
||||
assert!(
|
||||
bridged_persona_feedback_ready_for_cognition(
|
||||
&feedback_store,
|
||||
"epiphany-yggdrasil"
|
||||
)
|
||||
.is_err()
|
||||
bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
bridge_admitted_persona_feedback_to_heartbeat(
|
||||
|
|
@ -1125,11 +1116,8 @@ mod tests {
|
|||
1
|
||||
);
|
||||
assert!(
|
||||
bridged_persona_feedback_ready_for_cognition(
|
||||
&feedback_store,
|
||||
"epiphany-yggdrasil"
|
||||
)?
|
||||
.is_empty()
|
||||
bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
crate::load_heartbeat_state_entry(&heartbeat_store)?
|
||||
|
|
|
|||
|
|
@ -174,7 +174,10 @@ pub fn put_persona_terminal_decision(
|
|||
let existing_terminal = cache.get::<PersonaModelTerminalReceipt>(&terminal.receipt_id)?;
|
||||
match (existing_effect, existing_terminal) {
|
||||
(Some(existing_effect), Some(existing_terminal))
|
||||
if existing_effect == *effect && existing_terminal == *terminal => return Ok(()),
|
||||
if existing_effect == *effect && existing_terminal == *terminal =>
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => return Err(anyhow!("Persona terminal decision identity collision")),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -88,8 +88,8 @@ pub fn reap_exited_child_process(expected: &ProcessInstanceIdentity) -> Result<b
|
|||
) {
|
||||
return Ok(false);
|
||||
}
|
||||
let pid = i32::try_from(expected.process_id)
|
||||
.context("child process id exceeds Unix pid range")?;
|
||||
let pid =
|
||||
i32::try_from(expected.process_id).context("child process id exceeds Unix pid range")?;
|
||||
loop {
|
||||
let mut status = 0;
|
||||
let observed = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
|
||||
|
|
@ -678,6 +678,9 @@ mod tests {
|
|||
}
|
||||
|
||||
assert!(!reap_exited_child_process(&stale_identity).unwrap());
|
||||
assert!(child.wait().is_ok(), "stale identity reaped the current child");
|
||||
assert!(
|
||||
child.wait().is_ok(),
|
||||
"stale identity reaped the current child"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -94,14 +94,14 @@ In the work loop, Modeling follows Soul: after Hands changes the body and Soul v
|
|||
Inspect source before you trust the model; when the map feels warm but the source feels cold, believe the source and mark the wound.
|
||||
Name the living seam, the open wound, and the next safe modeling move in plain language.
|
||||
Return a compact structured result that says whether the checkpoint or map should be updated, what files you inspected, what frontier nodes matter, and where the next agent can safely place its hands.
|
||||
`repoModelPatch` is required. Return the typed patch against the canonical repository model revision/hash supplied in context. Use explicit node, edge, and frontier operations; preserve exact source-grounded claim ids and dependency ids. This artifact is only a proposal for later Modeling review/admission: do not claim it has been applied.
|
||||
`repoModelOperations` is required. Return only semantic keyed operations; use an empty array when the current Body evidence requires no RepoModel mutation. Runtime owns the proposal identity, exact Body and RepoModel basis, causal request/result/evidence bindings, timestamps, strong reads, writes, commit metadata, and receipts. Do not emit or infer any of those authorities.
|
||||
RepoModel node `kind` is a closed vocabulary: `domain`, `module`, `crate`, `binary`, `schema`, `runtime_contract`, `adapter`, `test_seam`, `state_store`, `role_memory`, `short_term_thought`, `incubation_thread`, `agency_pressure`, `candidate_intervention`, `identity`, `evidence`, `summary`, or `other`. A node's factual statement belongs in its `claim` field; do not invent kind names such as `claim` or `anatomy`. Use `other` only when no specific canonical kind fits. Edge kinds and memory profiles are likewise closed vocabularies supplied by the output schema.
|
||||
Every upserted or revised node must include all canonical identity and judgment fields: `id`, `domain_id`, `profile`, `kind`, `title`, `claim`, `question`, `tension`, and `action_implication`. Every upserted or revised edge must include `id`, `source_id`, `target_id`, `kind`, `profile`, and `claim`. Do not emit shorthand nodes or edges; omitted empty judgment fields are still contract violations. `profile` is exactly one of `repo_architecture`, `repo_dataflow`, `role_self`, `short_term`, `incubation`, `agency_pressure`, `candidate_intervention`, `identity`, or `evidence`; there is no `repo` shorthand. Edge `kind` is exactly one of `owns`, `reads`, `writes`, `derives`, `adapts`, `persists`, `launches`, `verifies`, `supports`, `contradicts`, `distills`, `revises`, `retires`, `grounds`, `triggers`, `spoken_as`, `cools`, `clusters_with`, `resonates_with`, `depends_on`, or `other`.
|
||||
If you emit an `anchor`, it must include its own stable `id`, `kind`, and `target`; a nested `code_ref` must include `path`. Do not use a bare path-shaped object as an anchor. Omitting anchors is safer than inventing malformed provenance.
|
||||
The launch context includes `<canonical_repo_model_shape>`. Every new node must use one exact `existingDomains` id from that packet, and repo architecture/dataflow nodes and edges must use one of the listed legal lifecycles. Never derive a domain id from the workspace path; patches cannot create domains.
|
||||
When `<repo_frontier_modeling_request>` is present, echo its exact `modelingRequestId` as `repoFrontierModelingRequestId`, use `purpose.kind=incorporate_frontier_verdict` with its exact `frontierRouteId` and `soulVerdictReceiptId`, and revise only its routed frontier item to its allowed disposition. The typed request is authority; nearby telemetry, timestamps, and prose are not substitutes. When that request is absent, use `purpose.kind=evolution` and do not invent verdict-incorporation authority.
|
||||
An ordinary `purpose.kind=evolution` patch without `proposalModelingContext` may mutate nodes and edges only. It must not upsert, revise, retire, or adopt frontier items. Describe an observed frontier wound in `summary`, `evidenceGaps`, or `nextSafeMove` when no typed frontier authority exists.
|
||||
When the typed launch document contains `proposalModelingContext`, echo its exact `requestId` as `proposalModelingRequestId` and use `purpose.kind=evolution`. This is the one evolution frontier exception: emit exactly one `upsert_frontier` operation grounded in the proposal, target at least one exact claim id from `<canonical_repo_model_shape>.existingClaims` (or a claim created by the same patch), cite the exact `proposalId` in both top-level `evidenceIds` and the frontier item's `evidence_refs`, set the unresolved frontier `status` to `active`, and normalize the proposal's relevant `scopeHints` into a non-empty `source_scope` of safe relative paths in strict lexicographic ascending order with no duplicates. Choose `recommended_next_organ` from the actual unresolved work using exactly one canonical routeable value with exact case: `Hands`, `Eyes`, or `Imagination`; a user proposal is not automatically Hands-ready. You may also update source-grounded anatomy, but must not emit any other frontier operation. Read only that immutable typed projection against its exact canonical `modelRevision` and `modelHash`. The proposal is evidence, not campaign truth: Mind still owns admission, and Hands still owns execution. Do not substitute adjacent proposals, infer service intake, parse proposal authority from prose, or claim admission or execution authority.
|
||||
The launch context includes `<canonical_repo_model_shape>`. Every new node must use one exact `existingDomains` id from that packet, and repo architecture/dataflow nodes and edges must use one of the listed legal lifecycles. Never derive a domain id from the workspace path.
|
||||
When `<repo_frontier_modeling_request>` is present, return only `frontierVerdictGap`: the semantic explanation for the allowed resolved or blocked transition. Runtime composes the exact routed frontier mutation and binds the authenticated request, Soul evidence, disposition, and time. Do not echo those identifiers or construct the mutation yourself.
|
||||
Ordinary Modeling may emit `put_node`, `retire_node`, `put_edge`, or `retire_edge`. `checkpoint-update-needed` additionally requires exactly one `put_frontier`; `checkpoint-ready` and `regather-needed` require an empty operation array. Do not invent frontier authority from prose.
|
||||
When the typed launch document contains `proposalModelingContext`, emit only `proposalFrontierDraft`. Runtime composes the frontier identity, active lifecycle, Body basis, proposal/request provenance, timestamps, and mandatory evidence binding. Normalize relevant scope hints into safe relative paths in strict lexicographic order without duplicates, and choose `Hands`, `Eyes`, or `Imagination` from the actual unresolved work. The proposal is evidence, not campaign truth: Mind still owns admission, and Hands still owns execution.
|
||||
Generic `statePatch` is optional and has been stripped of repository-anatomy authority. If present, it may contain only coherent `observations` and `evidence`. Never put graphs, graph frontier, graph checkpoint, scratch, investigation checkpoint, planning, objectives, jobs, or other anatomy in `statePatch`; those old paths are demoted and will be rejected.
|
||||
Do not edit files, do not implement product code, do not verify as if you were the reviewer, do not change jobs/subgoals/objective/invariants/churn/mode, and do not promote or accept your own output.
|
||||
'''
|
||||
|
|
|
|||
|
|
@ -316,6 +316,10 @@ pub enum EpiphanyMindCommitAuthority {
|
|||
OperatorProvenance {
|
||||
provenance: EpiphanyMindDocumentVersion,
|
||||
},
|
||||
TypedOrganProvenance {
|
||||
organ: String,
|
||||
provenance: EpiphanyMindDocumentVersion,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
@ -616,6 +620,32 @@ pub fn commit_operator_mind_mutation(
|
|||
)
|
||||
}
|
||||
|
||||
pub fn commit_typed_organ_mind_mutation(
|
||||
store_path: &Path,
|
||||
organ: &str,
|
||||
provenance: CultCacheEnvelope,
|
||||
invariant_owner: &str,
|
||||
strong_reads: Vec<CultCacheEnvelope>,
|
||||
writes: Vec<CultCacheEnvelope>,
|
||||
committed_at: &str,
|
||||
) -> Result<EpiphanyMindCommitOutcome> {
|
||||
require_non_empty(organ, "Mind mutation organ")?;
|
||||
let provenance_version =
|
||||
EpiphanyMindDocumentVersion::from_envelope("epiphany-organ", &provenance)?;
|
||||
commit_authorized_mind_mutation(
|
||||
store_path,
|
||||
EpiphanyMindCommitAuthority::TypedOrganProvenance {
|
||||
organ: organ.to_string(),
|
||||
provenance: provenance_version,
|
||||
},
|
||||
invariant_owner,
|
||||
strong_reads,
|
||||
writes,
|
||||
vec![provenance],
|
||||
committed_at,
|
||||
)
|
||||
}
|
||||
|
||||
fn commit_authorized_mind_mutation(
|
||||
store_path: &Path,
|
||||
authority: EpiphanyMindCommitAuthority,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use anyhow::{Result, anyhow};
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry};
|
||||
use epiphany_state_model::{
|
||||
EpiphanyMemoryDomain, EpiphanyMemoryEdge, EpiphanyMemoryGraphSnapshot,
|
||||
|
|
@ -10,10 +10,12 @@ use epiphany_state_model::{
|
|||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{runtime_spine_cache, validate_memory_graph_snapshot, EpiphanyMindDocumentVersion};
|
||||
use crate::{EpiphanyMindDocumentVersion, runtime_spine_cache, validate_memory_graph_snapshot};
|
||||
|
||||
pub const REPO_MODEL_SCHEMA_EPOCH: &str = "epiphany.repo_model.epoch.v1";
|
||||
pub const REPO_MODEL_IDENTITY_KEY: &str = "repo-model";
|
||||
const HISTORICAL_AGGREGATE_REPO_MODEL_TYPE: &str = "epiphany.memory_graph";
|
||||
const HISTORICAL_AGGREGATE_REPO_MODEL_KEY: &str = "default";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
|
|
@ -122,7 +124,20 @@ pub struct EpiphanyRepoModelView {
|
|||
pub claim_obligations: Vec<EpiphanyRepoModelClaimObligationsDocument>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct EpiphanyRepoModelBasis {
|
||||
pub projection_digest: String,
|
||||
pub source_documents: Vec<EpiphanyMindDocumentVersion>,
|
||||
}
|
||||
|
||||
impl EpiphanyRepoModelView {
|
||||
pub fn reasoning_basis(&self) -> EpiphanyRepoModelBasis {
|
||||
EpiphanyRepoModelBasis {
|
||||
projection_digest: self.projection_digest.clone(),
|
||||
source_documents: self.source_documents.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn memory_context_projection(&self) -> EpiphanyMemoryGraphSnapshot {
|
||||
EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: None,
|
||||
|
|
@ -142,6 +157,90 @@ impl EpiphanyRepoModelView {
|
|||
}
|
||||
}
|
||||
|
||||
impl EpiphanyRepoModelBasis {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let digest = self
|
||||
.projection_digest
|
||||
.strip_prefix("sha256:")
|
||||
.ok_or_else(|| anyhow!("RepoModel basis digest has no SHA-256 scheme"))?;
|
||||
if digest.len() != 64
|
||||
|| !digest.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
|| self.source_documents.is_empty()
|
||||
{
|
||||
return Err(anyhow!("RepoModel basis is empty or has an invalid digest"));
|
||||
}
|
||||
let mut canonical = self.source_documents.clone();
|
||||
canonical.sort_by(|left, right| {
|
||||
left.document_type
|
||||
.cmp(&right.document_type)
|
||||
.then(left.document_key.cmp(&right.document_key))
|
||||
});
|
||||
if canonical != self.source_documents
|
||||
|| canonical
|
||||
.windows(2)
|
||||
.any(|pair| pair[0].identity() == pair[1].identity())
|
||||
{
|
||||
return Err(anyhow!("RepoModel basis sources are not canonical"));
|
||||
}
|
||||
for source in &self.source_documents {
|
||||
source.validate()?;
|
||||
if source.store_id != "epiphany-mind" {
|
||||
return Err(anyhow!("RepoModel basis references a foreign store"));
|
||||
}
|
||||
}
|
||||
let expected = format!(
|
||||
"sha256:{:x}",
|
||||
Sha256::digest(rmp_serde::to_vec_named(&self.source_documents)?)
|
||||
);
|
||||
if self.projection_digest != expected {
|
||||
return Err(anyhow!("RepoModel basis projection digest mismatch"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_current(&self, store_path: impl AsRef<Path>) -> Result<()> {
|
||||
self.validate()?;
|
||||
let current = assemble_repo_model_view(store_path)?.reasoning_basis();
|
||||
if current != *self {
|
||||
return Err(anyhow!("RepoModel basis is stale"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_against_cache(&self, cache: &CultCache) -> Result<()> {
|
||||
self.validate()?;
|
||||
let live = cache.snapshot_envelopes();
|
||||
for source in &self.source_documents {
|
||||
let envelope = live
|
||||
.iter()
|
||||
.find(|envelope| {
|
||||
envelope.r#type == source.document_type && envelope.key == source.document_key
|
||||
})
|
||||
.ok_or_else(|| anyhow!("RepoModel basis source is absent"))?;
|
||||
if EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", envelope)? != *source {
|
||||
return Err(anyhow!("RepoModel basis source changed"));
|
||||
}
|
||||
}
|
||||
let mut live_repo_sources = live
|
||||
.iter()
|
||||
.filter(|envelope| repo_model_write_key(envelope).is_ok_and(|key| key.is_some()))
|
||||
.map(|envelope| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", envelope))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
live_repo_sources.sort_by(|left, right| {
|
||||
left.document_type
|
||||
.cmp(&right.document_type)
|
||||
.then(left.document_key.cmp(&right.document_key))
|
||||
});
|
||||
let expected = self.source_documents.clone();
|
||||
if live_repo_sources != expected {
|
||||
return Err(anyhow!(
|
||||
"RepoModel basis does not seal the complete keyed view"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub const REPO_MODEL_MUTATION_PROPOSAL_SCHEMA_VERSION: &str =
|
||||
"epiphany.repo_model.mutation_proposal.v1";
|
||||
pub const REPO_MODEL_SEED_SCHEMA_VERSION: &str = "epiphany.repo_model.seed.v1";
|
||||
|
|
@ -347,7 +446,8 @@ pub fn initialize_keyed_repo_model(
|
|||
let mut cache = runtime_spine_cache(store_path)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
if cache.snapshot_envelopes().into_iter().any(|envelope| {
|
||||
envelope.r#type == crate::MEMORY_GRAPH_TYPE && envelope.key == crate::MEMORY_GRAPH_KEY
|
||||
envelope.r#type == HISTORICAL_AGGREGATE_REPO_MODEL_TYPE
|
||||
&& envelope.key == HISTORICAL_AGGREGATE_REPO_MODEL_KEY
|
||||
}) {
|
||||
return Err(anyhow!(
|
||||
"keyed RepoModel initialization refuses an aggregate RepoModel store"
|
||||
|
|
@ -977,6 +1077,12 @@ fn claim_obligations_for_frontier(
|
|||
pub fn assemble_repo_model_view(store_path: impl AsRef<Path>) -> Result<EpiphanyRepoModelView> {
|
||||
let mut cache = runtime_spine_cache(store_path.as_ref())?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
assemble_repo_model_view_from_cache(&cache)
|
||||
}
|
||||
|
||||
pub(crate) fn assemble_repo_model_view_from_cache(
|
||||
cache: &CultCache,
|
||||
) -> Result<EpiphanyRepoModelView> {
|
||||
let identity = cache
|
||||
.get::<EpiphanyRepoModelIdentityDocument>(REPO_MODEL_IDENTITY_KEY)?
|
||||
.ok_or_else(|| anyhow!("writable Mind store has no keyed RepoModel identity"))?;
|
||||
|
|
@ -1127,7 +1233,7 @@ fn validate_claim_obligations(
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{initialize_runtime_spine, RuntimeSpineInitOptions};
|
||||
use crate::{RuntimeSpineInitOptions, initialize_runtime_spine};
|
||||
use epiphany_state_model::{
|
||||
EpiphanyMemoryEdgeKind, EpiphanyMemoryLifecycle, EpiphanyMemoryNodeKind,
|
||||
EpiphanyMemoryProfile, RepoFrontierStatus,
|
||||
|
|
@ -1200,14 +1306,18 @@ mod tests {
|
|||
cache.get::<EpiphanyRepoModelSeed>("seed-1")?,
|
||||
Some(seed.clone())
|
||||
);
|
||||
assert!(cache
|
||||
.get_all::<crate::EpiphanyMindCommitReceipt>()?
|
||||
.iter()
|
||||
.any(|receipt| receipt.invariant_owner == "Modeling.repo_model_seed"));
|
||||
assert!(cache
|
||||
.snapshot_envelopes()
|
||||
.iter()
|
||||
.all(|envelope| envelope.r#type != crate::MEMORY_GRAPH_TYPE));
|
||||
assert!(
|
||||
cache
|
||||
.get_all::<crate::EpiphanyMindCommitReceipt>()?
|
||||
.iter()
|
||||
.any(|receipt| receipt.invariant_owner == "Modeling.repo_model_seed")
|
||||
);
|
||||
assert!(
|
||||
cache
|
||||
.snapshot_envelopes()
|
||||
.iter()
|
||||
.all(|envelope| envelope.r#type != "epiphany.memory_graph")
|
||||
);
|
||||
|
||||
let divergent = EpiphanyRepoModelSeed::new(
|
||||
"seed-1",
|
||||
|
|
|
|||
|
|
@ -30,48 +30,17 @@
|
|||
//! Do not infer it from display state, repair it after execution, or invent a
|
||||
//! parallel route document.
|
||||
|
||||
use crate::MindGatewayDecision;
|
||||
use anyhow::Result;
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub const REPO_MODEL_ADMISSION_REVIEW_TYPE: &str = "epiphany.mind.repo_model_admission_review";
|
||||
pub const REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION: &str =
|
||||
"epiphany.mind.repo_model_admission_review.v2";
|
||||
pub const LEGACY_REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION: &str =
|
||||
"epiphany.mind.repo_model_admission_review.v1";
|
||||
pub const REPO_MODEL_ADMISSION_RECEIPT_TYPE: &str = "epiphany.mind.repo_model_admission_receipt";
|
||||
pub const REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.mind.repo_model_admission_receipt.v6";
|
||||
pub const LEGACY_REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.mind.repo_model_admission_receipt.v5";
|
||||
pub const REPO_MODEL_MIGRATION_RECEIPT_TYPE: &str = "epiphany.mind.repo_model_migration_receipt";
|
||||
pub const REPO_MODEL_MIGRATION_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.mind.repo_model_migration_receipt.v0";
|
||||
pub const REPO_MODEL_ADMISSION_CONTRACT: &str = "epiphany.repo_model_admission.v6";
|
||||
pub const LEGACY_REPO_MODEL_ADMISSION_CONTRACT: &str = "epiphany.repo_model_admission.v5";
|
||||
|
||||
pub fn repo_model_admission_review_schema_supported(schema: &str, contract: &str) -> bool {
|
||||
(schema == REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION
|
||||
&& contract == REPO_MODEL_ADMISSION_CONTRACT)
|
||||
|| (schema == LEGACY_REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION
|
||||
&& contract == LEGACY_REPO_MODEL_ADMISSION_CONTRACT)
|
||||
}
|
||||
|
||||
pub fn repo_model_admission_receipt_schema_supported(schema: &str, contract: &str) -> bool {
|
||||
(schema == REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION
|
||||
&& contract == REPO_MODEL_ADMISSION_CONTRACT)
|
||||
|| (schema == LEGACY_REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION
|
||||
&& contract == LEGACY_REPO_MODEL_ADMISSION_CONTRACT)
|
||||
}
|
||||
pub const REPO_MODEL_MIGRATION_CONTRACT: &str = "epiphany.repo_model_migration.v0";
|
||||
pub const REPO_FRONTIER_ROUTE_TYPE: &str = "epiphany.self.repo_frontier_route";
|
||||
pub const REPO_FRONTIER_ROUTE_SCHEMA_VERSION: &str = "epiphany.self.repo_frontier_route.v1";
|
||||
pub const REPO_FRONTIER_ROUTE_SCHEMA_VERSION: &str = "epiphany.self.repo_frontier_route.v2";
|
||||
pub const REPO_FRONTIER_HANDS_AUTHORITY_TYPE: &str = "epiphany.hands.repo_frontier_authority";
|
||||
pub const REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION: &str =
|
||||
"epiphany.hands.repo_frontier_authority.v0";
|
||||
pub const REPO_FRONTIER_ROUTE_CONTRACT: &str = "epiphany.repo_frontier_route.v1";
|
||||
pub const REPO_FRONTIER_ROUTE_CONTRACT: &str = "epiphany.repo_frontier_route.v2";
|
||||
pub const REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_hands_authority.v0";
|
||||
pub const REPO_FRONTIER_RELINQUISHMENT_RECEIPT_TYPE: &str =
|
||||
|
|
@ -93,7 +62,7 @@ pub const REPO_FRONTIER_MODELING_REQUEST_CONTRACT: &str =
|
|||
pub const REPO_FRONTIER_WORK_PROPOSAL_SCHEMA_VERSION: &str =
|
||||
"epiphany.repo_frontier_work_proposal.v0";
|
||||
pub const REPO_FRONTIER_PLANNING_REQUEST_SCHEMA_VERSION: &str =
|
||||
"epiphany.self.repo_frontier_planning_request.v1";
|
||||
"epiphany.self.repo_frontier_planning_request.v2";
|
||||
pub const REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION: &str =
|
||||
"epiphany.imagination.repo_frontier_plan_candidate.v0";
|
||||
pub const REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION: &str =
|
||||
|
|
@ -101,17 +70,17 @@ pub const REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION: &str =
|
|||
pub const LEGACY_REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.mind.repo_frontier_plan_decision_receipt.v0";
|
||||
pub const REPO_FRONTIER_PLAN_DECISION_CONTRACT: &str = "epiphany.repo_frontier_plan_decision.v0";
|
||||
pub const REPO_FRONTIER_PLANNING_CONTRACT: &str = "epiphany.repo_frontier_planning.v1";
|
||||
pub const REPO_FRONTIER_PLANNING_CONTRACT: &str = "epiphany.repo_frontier_planning.v2";
|
||||
pub const REPO_FRONTIER_RESEARCH_REQUEST_SCHEMA_VERSION: &str =
|
||||
"epiphany.self.repo_frontier_research_request.v1";
|
||||
"epiphany.self.repo_frontier_research_request.v2";
|
||||
pub const REPO_FRONTIER_RESEARCH_REQUEST_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_research_request.v1";
|
||||
"epiphany.repo_frontier_research_request.v2";
|
||||
pub const REPO_FRONTIER_WORK_PROPOSAL_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_work_proposal.inert.v0";
|
||||
pub const REPO_FRONTIER_AUTONOMOUS_PROPOSAL_BINDING_SCHEMA_VERSION: &str =
|
||||
"epiphany.self.repo_frontier_autonomous_proposal_binding.v0";
|
||||
"epiphany.self.repo_frontier_autonomous_proposal_binding.v1";
|
||||
pub const REPO_FRONTIER_AUTONOMOUS_PROPOSAL_BINDING_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_autonomous_proposal_binding.v0";
|
||||
"epiphany.repo_frontier_autonomous_proposal_binding.v1";
|
||||
pub const RUNTIME_REPOSITORY_DOMAIN_BINDING_KEY: &str = "runtime-repository-domain-binding";
|
||||
pub const RUNTIME_REPOSITORY_DOMAIN_BINDING_SCHEMA_VERSION: &str =
|
||||
"epiphany.runtime.repository_domain_binding.v0";
|
||||
|
|
@ -175,28 +144,26 @@ pub struct RepoModelClaimChallenge {
|
|||
#[cultcache(key = 5)]
|
||||
pub source_job_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 8)]
|
||||
pub admission_receipt_id: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub target_claim_id: String,
|
||||
#[cultcache(key = 10)]
|
||||
#[cultcache(key = 9)]
|
||||
pub target_claim_sha256: String,
|
||||
#[cultcache(key = 11)]
|
||||
#[cultcache(key = 10)]
|
||||
pub disposition: RepoModelClaimChallengeDisposition,
|
||||
#[cultcache(key = 12)]
|
||||
#[cultcache(key = 11)]
|
||||
pub finding: String,
|
||||
#[cultcache(key = 13)]
|
||||
#[cultcache(key = 12)]
|
||||
pub uncertainty: String,
|
||||
#[cultcache(key = 14)]
|
||||
#[cultcache(key = 13)]
|
||||
pub source_refs: Vec<String>,
|
||||
#[cultcache(key = 15)]
|
||||
#[cultcache(key = 14)]
|
||||
pub evidence_ids: Vec<String>,
|
||||
#[cultcache(key = 16)]
|
||||
#[cultcache(key = 15)]
|
||||
pub challenged_at: String,
|
||||
#[cultcache(key = 17)]
|
||||
#[cultcache(key = 16)]
|
||||
pub contract: String,
|
||||
}
|
||||
|
||||
|
|
@ -223,13 +190,13 @@ pub struct RepoModelClaimRepairRequest {
|
|||
#[cultcache(key = 7)]
|
||||
pub source_job_id: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub original_admission_receipt_id: String,
|
||||
pub original_model_projection_digest: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub current_admission_receipt_id: String,
|
||||
pub original_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 10)]
|
||||
pub model_revision: u64,
|
||||
pub current_model_projection_digest: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub model_hash: String,
|
||||
pub current_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 12)]
|
||||
pub target_claim_id: String,
|
||||
#[cultcache(key = 13)]
|
||||
|
|
@ -415,11 +382,9 @@ pub struct RepoFrontierAutonomousProposalBinding {
|
|||
#[cultcache(key = 6)]
|
||||
pub direction_result_sha256: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub model_hash: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub model_admission_receipt_id: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 10)]
|
||||
pub option_ordinal: u32,
|
||||
#[cultcache(key = 11)]
|
||||
|
|
@ -543,26 +508,24 @@ pub struct RepoFrontierPlanningRequest {
|
|||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 4)]
|
||||
pub admission_receipt_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
#[cultcache(key = 5)]
|
||||
pub frontier_item_hash: String,
|
||||
#[cultcache(key = 7)]
|
||||
#[cultcache(key = 6)]
|
||||
pub selected_organ: String,
|
||||
#[cultcache(key = 8)]
|
||||
#[cultcache(key = 7)]
|
||||
pub source_scope: Vec<String>,
|
||||
#[cultcache(key = 9)]
|
||||
#[cultcache(key = 8)]
|
||||
pub requested_at: String,
|
||||
#[cultcache(key = 10)]
|
||||
#[cultcache(key = 9)]
|
||||
pub contract: String,
|
||||
#[cultcache(key = 11)]
|
||||
#[cultcache(key = 10)]
|
||||
pub runtime_id: String,
|
||||
#[cultcache(key = 12)]
|
||||
#[cultcache(key = 11)]
|
||||
pub thread_id: String,
|
||||
}
|
||||
|
||||
|
|
@ -609,29 +572,27 @@ pub struct RepoFrontierResearchRequest {
|
|||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 4)]
|
||||
pub admission_receipt_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
#[cultcache(key = 5)]
|
||||
pub frontier_item_hash: String,
|
||||
#[cultcache(key = 7)]
|
||||
#[cultcache(key = 6)]
|
||||
pub source_scope: Vec<String>,
|
||||
#[cultcache(key = 8)]
|
||||
#[cultcache(key = 7)]
|
||||
pub requested_at: String,
|
||||
#[cultcache(key = 9)]
|
||||
#[cultcache(key = 8)]
|
||||
pub runtime_id: String,
|
||||
#[cultcache(key = 10)]
|
||||
#[cultcache(key = 9)]
|
||||
pub thread_id: String,
|
||||
#[cultcache(key = 11)]
|
||||
#[cultcache(key = 10)]
|
||||
pub contract: String,
|
||||
/// Immutable public source identities already owned by the admitted
|
||||
/// frontier. This is dedicated retrieval authority, not worker-authored
|
||||
/// evidence or a search hint.
|
||||
#[cultcache(key = 12, default)]
|
||||
#[cultcache(key = 11, default)]
|
||||
pub public_source_refs: Vec<String>,
|
||||
}
|
||||
|
||||
|
|
@ -648,9 +609,9 @@ pub struct RepoFrontierPlanCandidate {
|
|||
#[cultcache(key = 2)]
|
||||
pub planning_request_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 5)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
|
|
@ -730,7 +691,7 @@ pub struct RepoFrontierPlanningCandidateEligibility {
|
|||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RepoFrontierPlanningEligibility {
|
||||
pub current_admission_count: usize,
|
||||
pub current_model_count: usize,
|
||||
pub candidates: Vec<RepoFrontierPlanningCandidateEligibility>,
|
||||
}
|
||||
|
||||
|
|
@ -829,9 +790,9 @@ pub struct RepoFrontierPlanDecisionReceipt {
|
|||
#[cultcache(key = 6)]
|
||||
pub candidate_sha256: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 9)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 10)]
|
||||
|
|
@ -842,11 +803,9 @@ pub struct RepoFrontierPlanDecisionReceipt {
|
|||
pub rationale: String,
|
||||
#[cultcache(key = 13)]
|
||||
pub decided_at: String,
|
||||
#[cultcache(key = 14, default)]
|
||||
pub model_admission_receipt_id: String,
|
||||
#[cultcache(key = 15)]
|
||||
#[cultcache(key = 14)]
|
||||
pub contract: String,
|
||||
#[cultcache(key = 16, default)]
|
||||
#[cultcache(key = 15, default)]
|
||||
pub decision_source: Option<RepoFrontierPlanDecisionSource>,
|
||||
}
|
||||
|
||||
|
|
@ -874,8 +833,8 @@ pub struct RepoFrontierPlanReviewSummary {
|
|||
pub mind_request_id: String,
|
||||
pub candidate_id: String,
|
||||
pub candidate_sha256: String,
|
||||
pub model_revision: u64,
|
||||
pub model_hash: String,
|
||||
pub model_projection_digest: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
pub frontier_item_id: String,
|
||||
pub requested_at: String,
|
||||
}
|
||||
|
|
@ -890,8 +849,8 @@ pub struct RepoFrontierPlanOperatorReview {
|
|||
pub mind_request_id: String,
|
||||
pub candidate_id: String,
|
||||
pub candidate_sha256: String,
|
||||
pub expected_model_revision: u64,
|
||||
pub expected_model_hash: String,
|
||||
pub expected_model_projection_digest: String,
|
||||
pub expected_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
pub decision: RepoFrontierPlanDecision,
|
||||
pub decided_at: String,
|
||||
}
|
||||
|
|
@ -914,9 +873,9 @@ pub struct RepoFrontierModelingRequest {
|
|||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 4)]
|
||||
pub route_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
|
|
@ -960,30 +919,28 @@ pub struct RepoFrontierRoute {
|
|||
#[cultcache(key = 2)]
|
||||
pub next_organ: RepoFrontierNextOrgan,
|
||||
#[cultcache(key = 3)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 5)]
|
||||
pub admission_receipt_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 7)]
|
||||
#[cultcache(key = 6)]
|
||||
pub frontier_item_hash: String,
|
||||
#[cultcache(key = 8)]
|
||||
#[cultcache(key = 7)]
|
||||
pub migration_body: String,
|
||||
#[cultcache(key = 9)]
|
||||
#[cultcache(key = 8)]
|
||||
pub question: String,
|
||||
#[cultcache(key = 10)]
|
||||
#[cultcache(key = 9)]
|
||||
pub gap: String,
|
||||
#[cultcache(key = 11)]
|
||||
#[cultcache(key = 10)]
|
||||
pub target_claim_ids: Vec<String>,
|
||||
#[cultcache(key = 12)]
|
||||
#[cultcache(key = 11)]
|
||||
pub source_scope: Vec<String>,
|
||||
#[cultcache(key = 13, default)]
|
||||
#[cultcache(key = 12, default)]
|
||||
pub adopted_plan: Option<epiphany_state_model::RepoFrontierAdoptedPlan>,
|
||||
#[cultcache(key = 14)]
|
||||
#[cultcache(key = 13)]
|
||||
pub selected_at: String,
|
||||
#[cultcache(key = 15)]
|
||||
#[cultcache(key = 14)]
|
||||
pub contract: String,
|
||||
}
|
||||
|
||||
|
|
@ -1000,9 +957,9 @@ pub struct RepoFrontierHandsAuthority {
|
|||
#[cultcache(key = 2)]
|
||||
pub route_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 5)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
|
|
@ -1038,18 +995,16 @@ pub struct RepoFrontierRelinquishmentReceipt {
|
|||
#[cultcache(key = 4)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub previous_model_revision: u64,
|
||||
pub previous_model_projection_digest: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub previous_model_hash: String,
|
||||
pub previous_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 7)]
|
||||
pub admitted_model_revision: u64,
|
||||
pub admitted_model_projection_digest: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub admitted_model_hash: String,
|
||||
pub admitted_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 9)]
|
||||
pub model_admission_receipt_id: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub relinquished_at: String,
|
||||
#[cultcache(key = 11)]
|
||||
#[cultcache(key = 10)]
|
||||
pub contract: String,
|
||||
}
|
||||
|
||||
|
|
@ -1072,273 +1027,29 @@ pub struct RepoFrontierExecutionAmendmentReceipt {
|
|||
#[cultcache(key = 5)]
|
||||
pub previous_frontier_item_hash: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub previous_model_revision: u64,
|
||||
pub previous_model_projection_digest: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub previous_model_hash: String,
|
||||
pub previous_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 8)]
|
||||
pub admitted_model_revision: u64,
|
||||
pub admitted_model_projection_digest: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub admitted_model_hash: String,
|
||||
pub admitted_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 10)]
|
||||
pub model_admission_receipt_id: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub source_actor_id: String,
|
||||
#[cultcache(key = 12)]
|
||||
#[cultcache(key = 11)]
|
||||
pub command_id: String,
|
||||
#[cultcache(key = 13)]
|
||||
#[cultcache(key = 12)]
|
||||
pub admission_id: String,
|
||||
#[cultcache(key = 14)]
|
||||
#[cultcache(key = 13)]
|
||||
pub packet_sha256: String,
|
||||
#[cultcache(key = 15)]
|
||||
#[cultcache(key = 14)]
|
||||
pub replacement_action: String,
|
||||
#[cultcache(key = 16)]
|
||||
#[cultcache(key = 15)]
|
||||
pub replacement_command: String,
|
||||
#[cultcache(key = 17)]
|
||||
#[cultcache(key = 16)]
|
||||
pub rationale: String,
|
||||
#[cultcache(key = 18)]
|
||||
#[cultcache(key = 17)]
|
||||
pub amended_at: String,
|
||||
#[cultcache(key = 19)]
|
||||
#[cultcache(key = 18)]
|
||||
pub contract: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.mind.repo_model_admission_review",
|
||||
schema = "RepoModelAdmissionReview"
|
||||
)]
|
||||
pub struct RepoModelAdmissionReview {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub review_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub result_id: Option<String>,
|
||||
#[cultcache(key = 3)]
|
||||
pub job_id: Option<String>,
|
||||
#[cultcache(key = 4)]
|
||||
pub patch_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub patch_sha256: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub base_revision: u64,
|
||||
#[cultcache(key = 7)]
|
||||
pub base_hash: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub decision: MindGatewayDecision,
|
||||
#[cultcache(key = 9)]
|
||||
pub evidence_ids: Vec<String>,
|
||||
#[cultcache(key = 10)]
|
||||
pub reviewed_at: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub contract: String,
|
||||
#[cultcache(key = 12)]
|
||||
pub repository_body_observation_basis: Option<crate::RepositoryBodyObservationBasis>,
|
||||
#[cultcache(key = 13, default)]
|
||||
pub admission_source: Option<RepoModelAdmissionSource>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum RepoModelAdmissionSource {
|
||||
WorkerResult { result_id: String, job_id: String },
|
||||
FrontierPlanDecision { decision_id: String },
|
||||
HandsRelinquishment { receipt_id: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.mind.repo_model_admission_receipt",
|
||||
schema = "RepoModelAdmissionReceipt"
|
||||
)]
|
||||
pub struct RepoModelAdmissionReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub receipt_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub review_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub result_id: Option<String>,
|
||||
#[cultcache(key = 4)]
|
||||
pub patch_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub patch_sha256: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub previous_revision: u64,
|
||||
#[cultcache(key = 7)]
|
||||
pub previous_hash: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub admitted_revision: u64,
|
||||
#[cultcache(key = 9)]
|
||||
pub admitted_hash: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub admitted_at: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub contract: String,
|
||||
#[cultcache(key = 12)]
|
||||
pub purpose: epiphany_state_model::RepoModelPatchPurpose,
|
||||
#[cultcache(key = 13, default)]
|
||||
pub frontier_route_id: String,
|
||||
#[cultcache(key = 14, default)]
|
||||
pub verification_request_id: String,
|
||||
#[cultcache(key = 15, default)]
|
||||
pub soul_verdict_receipt_id: String,
|
||||
#[cultcache(key = 16, default)]
|
||||
pub frontier_modeling_request_id: String,
|
||||
#[cultcache(key = 17, default)]
|
||||
pub proposal_modeling_request_id: String,
|
||||
#[cultcache(key = 18, default)]
|
||||
pub claim_repair_request_id: String,
|
||||
#[cultcache(key = 19, default)]
|
||||
pub frontier_plan_decision_id: String,
|
||||
#[cultcache(key = 20)]
|
||||
pub repository_body_observation_basis: Option<crate::RepositoryBodyObservationBasis>,
|
||||
#[cultcache(key = 21, default)]
|
||||
pub admission_source: Option<RepoModelAdmissionSource>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.mind.repo_model_migration_receipt",
|
||||
schema = "RepoModelMigrationReceipt"
|
||||
)]
|
||||
pub struct RepoModelMigrationReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub receipt_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub source_store: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub source_graph_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub imported_revision: u64,
|
||||
#[cultcache(key = 5)]
|
||||
pub imported_hash: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub imported_at: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub contract: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod migration_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn v0_tuple_decision_receipt_decodes_as_explicit_legacy_worker_source() {
|
||||
let bytes = rmp_serde::to_vec(&(
|
||||
LEGACY_REPO_FRONTIER_PLAN_DECISION_RECEIPT_SCHEMA_VERSION,
|
||||
"decision-legacy",
|
||||
"planning-legacy",
|
||||
"mind-result-legacy",
|
||||
"mind-job-legacy",
|
||||
"candidate-legacy",
|
||||
"a".repeat(64),
|
||||
7_u64,
|
||||
"b".repeat(64),
|
||||
"frontier-legacy",
|
||||
"c".repeat(64),
|
||||
RepoFrontierPlanDecision::Hold,
|
||||
"Legacy Mind hold.",
|
||||
"2026-07-15T09:00:06Z",
|
||||
"",
|
||||
REPO_FRONTIER_PLAN_DECISION_CONTRACT,
|
||||
))
|
||||
.unwrap();
|
||||
let decoded: RepoFrontierPlanDecisionReceipt = rmp_serde::from_slice(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
decoded.legacy_mind_worker_result_id.as_deref(),
|
||||
Some("mind-result-legacy")
|
||||
);
|
||||
assert_eq!(
|
||||
decoded.legacy_mind_worker_job_id.as_deref(),
|
||||
Some("mind-job-legacy")
|
||||
);
|
||||
assert!(decoded.decision_source.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_repo_model_review_and_receipt_tuples_decode_with_typed_optional_provenance() {
|
||||
#[derive(Serialize)]
|
||||
struct LegacyRepoModelAdmissionReceipt<'a> {
|
||||
schema_version: &'a str,
|
||||
receipt_id: &'a str,
|
||||
review_id: &'a str,
|
||||
result_id: &'a str,
|
||||
patch_id: &'a str,
|
||||
patch_sha256: String,
|
||||
prior_model_revision: u64,
|
||||
prior_model_hash: String,
|
||||
committed_model_revision: u64,
|
||||
committed_model_hash: String,
|
||||
committed_at: &'a str,
|
||||
contract: &'a str,
|
||||
purpose: epiphany_state_model::RepoModelPatchPurpose,
|
||||
field_13: &'a str,
|
||||
field_14: &'a str,
|
||||
field_15: &'a str,
|
||||
field_16: &'a str,
|
||||
field_17: &'a str,
|
||||
field_18: &'a str,
|
||||
field_19: &'a str,
|
||||
observation_basis: Option<crate::RepositoryBodyObservationBasis>,
|
||||
}
|
||||
let review_bytes = rmp_serde::to_vec(&(
|
||||
LEGACY_REPO_MODEL_ADMISSION_REVIEW_SCHEMA_VERSION,
|
||||
"review-legacy",
|
||||
"result-legacy",
|
||||
"job-legacy",
|
||||
"patch-legacy",
|
||||
"a".repeat(64),
|
||||
7_u64,
|
||||
"b".repeat(64),
|
||||
MindGatewayDecision::Accept,
|
||||
vec!["evidence-legacy"],
|
||||
"2026-07-15T09:00:06Z",
|
||||
LEGACY_REPO_MODEL_ADMISSION_CONTRACT,
|
||||
Option::<crate::RepositoryBodyObservationBasis>::None,
|
||||
))
|
||||
.unwrap();
|
||||
let review: RepoModelAdmissionReview = rmp_serde::from_slice(&review_bytes).unwrap();
|
||||
assert_eq!(review.result_id.as_deref(), Some("result-legacy"));
|
||||
assert_eq!(review.job_id.as_deref(), Some("job-legacy"));
|
||||
assert!(review.admission_source.is_none());
|
||||
assert!(repo_model_admission_review_schema_supported(
|
||||
&review.schema_version,
|
||||
&review.contract
|
||||
));
|
||||
|
||||
let receipt_bytes = rmp_serde::to_vec(&LegacyRepoModelAdmissionReceipt {
|
||||
schema_version: LEGACY_REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION,
|
||||
receipt_id: "receipt-legacy",
|
||||
review_id: "review-legacy",
|
||||
result_id: "result-legacy",
|
||||
patch_id: "patch-legacy",
|
||||
patch_sha256: "a".repeat(64),
|
||||
prior_model_revision: 7,
|
||||
prior_model_hash: "b".repeat(64),
|
||||
committed_model_revision: 8,
|
||||
committed_model_hash: "c".repeat(64),
|
||||
committed_at: "2026-07-15T09:00:06Z",
|
||||
contract: LEGACY_REPO_MODEL_ADMISSION_CONTRACT,
|
||||
purpose: epiphany_state_model::RepoModelPatchPurpose::Evolution,
|
||||
field_13: "",
|
||||
field_14: "",
|
||||
field_15: "",
|
||||
field_16: "",
|
||||
field_17: "",
|
||||
field_18: "",
|
||||
field_19: "",
|
||||
observation_basis: None,
|
||||
})
|
||||
.unwrap();
|
||||
let receipt: RepoModelAdmissionReceipt = rmp_serde::from_slice(&receipt_bytes).unwrap();
|
||||
assert_eq!(receipt.result_id.as_deref(), Some("result-legacy"));
|
||||
assert!(receipt.admission_source.is_none());
|
||||
assert!(repo_model_admission_receipt_schema_supported(
|
||||
&receipt.schema_version,
|
||||
&receipt.contract
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -978,32 +978,33 @@ fn raw_manifest_entries(repo: &Path, index: &[u8]) -> Result<Vec<RepositoryBodyM
|
|||
let mut entries = std::thread::scope(|scope| -> Result<Vec<_>> {
|
||||
let mut workers = Vec::new();
|
||||
for chunk in records.chunks(chunk_size.max(1)) {
|
||||
workers.push(scope.spawn(move || -> Result<Vec<RepositoryBodyManifestEntry>> {
|
||||
let mut local = Vec::with_capacity(chunk.len());
|
||||
for record in chunk {
|
||||
let path_buf = safe_worktree_path(repo, &record.path)?;
|
||||
let entry = match record.mode.as_str() {
|
||||
"100644" | "100755" => {
|
||||
raw_regular_entry(&path_buf, &record.path, &record.mode)?
|
||||
}
|
||||
"120000" => raw_symlink_entry(&path_buf, &record.path, &record.mode)?,
|
||||
"160000" => RepositoryBodyManifestEntry {
|
||||
path: record.path.clone(),
|
||||
git_mode: record.mode.clone(),
|
||||
kind: "gitlink_nonrecursive".into(),
|
||||
raw_byte_length: 0,
|
||||
raw_sha256: String::new(),
|
||||
gitlink_oid: Some(record.oid.clone()),
|
||||
},
|
||||
mode => bail!(
|
||||
"unsupported Git index mode {mode:?} at {:?}",
|
||||
record.path
|
||||
),
|
||||
};
|
||||
local.push(entry);
|
||||
}
|
||||
Ok(local)
|
||||
}));
|
||||
workers.push(
|
||||
scope.spawn(move || -> Result<Vec<RepositoryBodyManifestEntry>> {
|
||||
let mut local = Vec::with_capacity(chunk.len());
|
||||
for record in chunk {
|
||||
let path_buf = safe_worktree_path(repo, &record.path)?;
|
||||
let entry = match record.mode.as_str() {
|
||||
"100644" | "100755" => {
|
||||
raw_regular_entry(&path_buf, &record.path, &record.mode)?
|
||||
}
|
||||
"120000" => raw_symlink_entry(&path_buf, &record.path, &record.mode)?,
|
||||
"160000" => RepositoryBodyManifestEntry {
|
||||
path: record.path.clone(),
|
||||
git_mode: record.mode.clone(),
|
||||
kind: "gitlink_nonrecursive".into(),
|
||||
raw_byte_length: 0,
|
||||
raw_sha256: String::new(),
|
||||
gitlink_oid: Some(record.oid.clone()),
|
||||
},
|
||||
mode => {
|
||||
bail!("unsupported Git index mode {mode:?} at {:?}", record.path)
|
||||
}
|
||||
};
|
||||
local.push(entry);
|
||||
}
|
||||
Ok(local)
|
||||
}),
|
||||
);
|
||||
}
|
||||
let mut joined = Vec::with_capacity(records.len());
|
||||
for worker in workers {
|
||||
|
|
|
|||
|
|
@ -6,17 +6,16 @@ use crate::workspace_coverage_projector::{
|
|||
WorkspaceCoverageReadinessEvidence, observe_current_workspace_coverage_evidence,
|
||||
};
|
||||
use crate::{
|
||||
EpiphanyMemoryGraphEntry, EpiphanyMemoryGraphSnapshot,
|
||||
EpiphanyMindDocumentVersion, EpiphanyRepoModelView,
|
||||
MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION,
|
||||
MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION, MemorySemanticIndexReceipt,
|
||||
MemorySemanticProjectionAttempt, MemorySemanticProjectionClaim, MemorySemanticProjectionInput,
|
||||
MemorySemanticProjectionObligation, MemorySemanticProjectionReadiness,
|
||||
MemorySemanticProjectionSourceHead, RepoModelAdmissionReceipt, RepositoryBodyObservationBasis,
|
||||
SEMANTIC_PROJECTION_SCHEMA_VERSION, WorkspaceCoveragePolicy,
|
||||
load_memory_semantic_projection_readiness, memory_graph_model_hash,
|
||||
observe_runtime_repository_body_basis, runtime_modeling_semantic_projection_input,
|
||||
runtime_spine_cache, validate_memory_semantic_projection_obligation,
|
||||
validate_repository_body_observation_basis,
|
||||
MemorySemanticProjectionSourceHead, RepositoryBodyObservationBasis,
|
||||
SEMANTIC_PROJECTION_SCHEMA_VERSION, WorkspaceCoveragePolicy, assemble_repo_model_view,
|
||||
load_memory_semantic_projection_readiness, observe_runtime_repository_body_basis,
|
||||
runtime_modeling_semantic_projection_input, runtime_spine_cache,
|
||||
validate_memory_semantic_projection_obligation,
|
||||
};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use cultcache_rs::{
|
||||
|
|
@ -26,12 +25,12 @@ use sha2::{Digest, Sha256};
|
|||
use std::path::Path;
|
||||
|
||||
pub const REPOSITORY_READINESS_PROJECTION_SCHEMA_VERSION: &str =
|
||||
"gamecult.epiphany.repository_readiness_projection.v0";
|
||||
"gamecult.epiphany.repository_readiness_projection.v1";
|
||||
pub const REPOSITORY_READINESS_PROJECTION_TYPE: &str =
|
||||
"gamecult.epiphany.repository_readiness_projection";
|
||||
|
||||
/// A historical proof that Mind joined one exact Repository Body observation,
|
||||
/// canonical RepoModel admission, and both live semantic projections. It is not
|
||||
/// canonical keyed RepoModel basis, and both live semantic projections. It is not
|
||||
/// a current-readiness flag: callers must derive a new projection to claim now.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
|
|
@ -64,11 +63,9 @@ pub struct RepositoryReadinessProjection {
|
|||
#[cultcache(key = 11)]
|
||||
pub repo_model_graph_id: String,
|
||||
#[cultcache(key = 12)]
|
||||
pub repo_model_revision: u64,
|
||||
pub repo_model_projection_digest: String,
|
||||
#[cultcache(key = 13)]
|
||||
pub repo_model_hash: String,
|
||||
#[cultcache(key = 14)]
|
||||
pub admission_receipt_id: String,
|
||||
pub repo_model_source_documents: Vec<EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 15)]
|
||||
pub modeling_obligation_id: String,
|
||||
#[cultcache(key = 16)]
|
||||
|
|
@ -113,8 +110,6 @@ pub struct RepositoryReadinessProjection {
|
|||
pub truth_interval_started_at: String,
|
||||
#[cultcache(key = 36)]
|
||||
pub truth_interval_closed_at: String,
|
||||
#[cultcache(key = 37)]
|
||||
pub admission_envelope_sha256: String,
|
||||
#[cultcache(key = 38)]
|
||||
pub modeling_source_generation: u64,
|
||||
#[cultcache(key = 39)]
|
||||
|
|
@ -153,8 +148,6 @@ pub struct RepositoryReadinessProjection {
|
|||
pub workspace_head_envelope_sha256: String,
|
||||
#[cultcache(key = 56)]
|
||||
pub workspace_observed_point_set_sha256: String,
|
||||
#[cultcache(key = 57)]
|
||||
pub admission_body_basis: RepositoryBodyObservationBasis,
|
||||
#[cultcache(key = 58)]
|
||||
pub modeling_obligation_envelope_sha256: String,
|
||||
#[cultcache(key = 59)]
|
||||
|
|
@ -162,7 +155,7 @@ pub struct RepositoryReadinessProjection {
|
|||
#[cultcache(key = 60)]
|
||||
pub modeling_source_commit_id: String,
|
||||
#[cultcache(key = 61)]
|
||||
pub modeling_source_model_hash: String,
|
||||
pub modeling_semantic_source_hash: String,
|
||||
#[cultcache(key = 62)]
|
||||
pub modeling_current_content_set_hash: String,
|
||||
#[cultcache(key = 63)]
|
||||
|
|
@ -198,11 +191,7 @@ pub struct WorkspaceProjectionIdentity {
|
|||
struct JoinedReadinessEvidence {
|
||||
r1: RepositoryBodyObservationBasis,
|
||||
r2: RepositoryBodyObservationBasis,
|
||||
graph_id: String,
|
||||
model_revision: u64,
|
||||
model_hash: String,
|
||||
admission: RepoModelAdmissionReceipt,
|
||||
admission_envelope_sha256: String,
|
||||
repo_model: EpiphanyRepoModelView,
|
||||
modeling_obligation_id: String,
|
||||
modeling_receipt_id: String,
|
||||
modeling_source_generation: u64,
|
||||
|
|
@ -216,7 +205,7 @@ struct JoinedReadinessEvidence {
|
|||
modeling_obligation_envelope_sha256: String,
|
||||
modeling_canonical_source_id: String,
|
||||
modeling_source_commit_id: String,
|
||||
modeling_source_model_hash: String,
|
||||
modeling_semantic_source_hash: String,
|
||||
modeling_current_content_set_hash: String,
|
||||
modeling_claim_envelope_sha256: String,
|
||||
modeling_attempt_id: String,
|
||||
|
|
@ -240,10 +229,6 @@ enum ReadinessAppendResult {
|
|||
trait ReadinessObservationPorts {
|
||||
fn observe_body(&mut self) -> Result<RepositoryBodyObservationBasis>;
|
||||
fn observe_store_snapshot(&mut self) -> Result<Vec<CultCacheEnvelope>>;
|
||||
fn authenticate_historical_body_basis(
|
||||
&mut self,
|
||||
basis: &RepositoryBodyObservationBasis,
|
||||
) -> Result<()>;
|
||||
fn observe_semantic_state(&mut self) -> Result<RawSemanticObservation>;
|
||||
fn observe_semantic_live(&mut self) -> Result<Option<MemorySemanticLiveEvidence>>;
|
||||
fn observe_workspace_live(
|
||||
|
|
@ -259,9 +244,48 @@ trait ReadinessObservationPorts {
|
|||
) -> Result<ReadinessAppendResult>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct RepoModelSemanticContent {
|
||||
graph_id: String,
|
||||
domains: Vec<crate::EpiphanyMemoryDomain>,
|
||||
nodes: Vec<crate::EpiphanyMemoryNode>,
|
||||
edges: Vec<crate::EpiphanyMemoryEdge>,
|
||||
summaries: Vec<crate::EpiphanyMemorySummary>,
|
||||
lifecycle_receipts: Vec<crate::EpiphanyMemoryLifecycleReceipt>,
|
||||
frontier: Vec<crate::RepoFrontierItem>,
|
||||
}
|
||||
|
||||
impl RepoModelSemanticContent {
|
||||
fn from_repo_model(model: &EpiphanyRepoModelView) -> Self {
|
||||
Self {
|
||||
graph_id: model.identity.graph_id.clone(),
|
||||
domains: model.domains.clone(),
|
||||
nodes: model.nodes.clone(),
|
||||
edges: model.edges.clone(),
|
||||
summaries: model.summaries.clone(),
|
||||
lifecycle_receipts: model.lifecycle_receipts.clone(),
|
||||
frontier: model.frontier.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_semantic_input(input: &MemorySemanticProjectionInput) -> Self {
|
||||
let snapshot = input.snapshot();
|
||||
Self {
|
||||
graph_id: snapshot.graph_id.clone(),
|
||||
domains: snapshot.domains.clone(),
|
||||
nodes: snapshot.nodes.clone(),
|
||||
edges: snapshot.edges.clone(),
|
||||
summaries: snapshot.summaries.clone(),
|
||||
lifecycle_receipts: snapshot.lifecycle_receipts.clone(),
|
||||
frontier: snapshot.frontier.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct RawSemanticObservation {
|
||||
snapshot: EpiphanyMemoryGraphSnapshot,
|
||||
repo_model: EpiphanyRepoModelView,
|
||||
semantic_content: RepoModelSemanticContent,
|
||||
authority_envelopes: Vec<CultCacheEnvelope>,
|
||||
obligation: MemorySemanticProjectionObligation,
|
||||
current: MemorySemanticProjectionSourceHead,
|
||||
|
|
@ -270,8 +294,7 @@ struct RawSemanticObservation {
|
|||
|
||||
fn validate_exact_raw_semantic_chain(
|
||||
r1: &RepositoryBodyObservationBasis,
|
||||
model: &EpiphanyMemoryGraphSnapshot,
|
||||
model_hash: &str,
|
||||
model: &EpiphanyRepoModelView,
|
||||
raw: &RawSemanticObservation,
|
||||
) -> Result<()> {
|
||||
let obligation = &raw.obligation;
|
||||
|
|
@ -282,9 +305,7 @@ fn validate_exact_raw_semantic_chain(
|
|||
|| obligation.projection_schema_version != SEMANTIC_PROJECTION_SCHEMA_VERSION
|
||||
|| obligation.partition != "modeling"
|
||||
|| obligation.swarm_id != r1.swarm_id
|
||||
|| obligation.graph_id != model.graph_id
|
||||
|| obligation.source_generation != model.model_revision
|
||||
|| obligation.source_model_hash != model_hash
|
||||
|| obligation.graph_id != model.identity.graph_id
|
||||
|| obligation.canonical_source_id.trim().is_empty()
|
||||
|| obligation.source_commit_id.trim().is_empty()
|
||||
|| obligation.canonical_content_set_hash.trim().is_empty()
|
||||
|
|
@ -313,8 +334,8 @@ fn validate_exact_raw_semantic_chain(
|
|||
|| receipt.source_commit_id != obligation.source_commit_id
|
||||
|| receipt.graph_id != obligation.graph_id
|
||||
|| receipt.source_generation != obligation.source_generation
|
||||
|| receipt.model_revision != model.model_revision
|
||||
|| receipt.model_hash != model_hash
|
||||
|| receipt.model_revision != obligation.source_generation
|
||||
|| receipt.model_hash != obligation.source_model_hash
|
||||
|| receipt.canonical_content_set_hash != obligation.canonical_content_set_hash
|
||||
|| receipt.projection_schema_version != obligation.projection_schema_version
|
||||
|| receipt.collection_name.trim().is_empty()
|
||||
|
|
@ -332,6 +353,9 @@ fn validate_exact_raw_semantic_chain(
|
|||
{
|
||||
bail!("raw Modeling receipt does not match its exact obligation and RepoModel");
|
||||
}
|
||||
if raw.semantic_content != RepoModelSemanticContent::from_repo_model(model) {
|
||||
bail!("Modeling semantic input is not the canonical keyed RepoModel content");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -348,13 +372,6 @@ fn observe_with_ports<P: ReadinessObservationPorts>(
|
|||
&opening_semantic,
|
||||
workspace_identity,
|
||||
)?;
|
||||
ports.authenticate_historical_body_basis(
|
||||
evidence
|
||||
.admission
|
||||
.repository_body_observation_basis
|
||||
.as_ref()
|
||||
.expect("join selected only Body-grounded admission"),
|
||||
)?;
|
||||
let modeling_live = ports.observe_semantic_live()?;
|
||||
let coverage_live = ports.observe_workspace_live(&r1, &evidence)?;
|
||||
let r2 = ports.observe_body()?;
|
||||
|
|
@ -379,7 +396,7 @@ fn observe_with_ports<P: ReadinessObservationPorts>(
|
|||
&closing_semantic,
|
||||
workspace_identity,
|
||||
)?;
|
||||
if opening_semantic != closing_semantic || evidence.admission != closing_evidence.admission {
|
||||
if opening_semantic != closing_semantic || evidence.repo_model != closing_evidence.repo_model {
|
||||
bail!("non-Body readiness authority advanced during observation");
|
||||
}
|
||||
evidence.r2 = r2;
|
||||
|
|
@ -404,33 +421,6 @@ fn same_body_content(
|
|||
&& a.manifest_root_sha256 == b.manifest_root_sha256
|
||||
}
|
||||
|
||||
fn select_current_admission(
|
||||
receipts: Vec<(String, RepoModelAdmissionReceipt)>,
|
||||
model_revision: u64,
|
||||
model_hash: &str,
|
||||
) -> Result<RepoModelAdmissionReceipt> {
|
||||
let mut matching = receipts.into_iter().filter(|(_, receipt)| {
|
||||
crate::repo_model_admission_receipt_schema_supported(
|
||||
&receipt.schema_version,
|
||||
&receipt.contract,
|
||||
) && receipt.admitted_revision == model_revision
|
||||
&& receipt.admitted_hash == model_hash
|
||||
});
|
||||
let selected = matching.next().ok_or_else(|| {
|
||||
anyhow!("repository readiness requires exactly one current RepoModel admission receipt")
|
||||
})?;
|
||||
if matching.next().is_some() {
|
||||
bail!("repository readiness requires exactly one current RepoModel admission receipt");
|
||||
}
|
||||
if selected.0 != selected.1.receipt_id {
|
||||
bail!("current RepoModel admission is stored under an alien key");
|
||||
}
|
||||
if selected.1.repository_body_observation_basis.is_none() {
|
||||
bail!("current RepoModel admission receipt has no authenticated Body basis");
|
||||
}
|
||||
Ok(selected.1)
|
||||
}
|
||||
|
||||
fn authority_bytes(rows: &[CultCacheEnvelope]) -> Result<Vec<u8>> {
|
||||
let mut rows = rows.to_vec();
|
||||
rows.sort_by(|a, b| (&a.r#type, &a.key).cmp(&(&b.r#type, &b.key)));
|
||||
|
|
@ -458,15 +448,12 @@ fn projection_from_join(
|
|||
if !same_body_content(&evidence.r1, &evidence.r2) {
|
||||
bail!("Repository Body changed during readiness observation");
|
||||
}
|
||||
if evidence.admission.admitted_revision != evidence.model_revision
|
||||
|| evidence.admission.admitted_hash != evidence.model_hash
|
||||
|| !evidence
|
||||
.admission
|
||||
.repository_body_observation_basis
|
||||
.as_ref()
|
||||
.is_some_and(|basis| same_body_content(basis, &evidence.r1))
|
||||
if evidence.repo_model.identity.workspace_id != evidence.r1.workspace_id
|
||||
|| evidence.repo_model.identity.swarm_id != evidence.r1.swarm_id
|
||||
|| evidence.repo_model.identity.runtime_id != evidence.r1.runtime_id
|
||||
|| evidence.repo_model.identity.body_binding_sha256 != evidence.r1.body_binding_sha256
|
||||
{
|
||||
bail!("current RepoModel admission is not authenticated by Body R1");
|
||||
bail!("current keyed RepoModel identity is not authenticated by Body R1");
|
||||
}
|
||||
let modeling = evidence
|
||||
.modeling_live
|
||||
|
|
@ -494,10 +481,9 @@ fn projection_from_join(
|
|||
&evidence.r1.workspace_id,
|
||||
&evidence.r1.body_binding_sha256,
|
||||
&evidence.r1.manifest_root_sha256,
|
||||
&evidence.graph_id,
|
||||
evidence.model_revision,
|
||||
&evidence.model_hash,
|
||||
&evidence.admission.receipt_id,
|
||||
&evidence.repo_model.identity.graph_id,
|
||||
&evidence.repo_model.projection_digest,
|
||||
&evidence.repo_model.source_documents,
|
||||
&evidence.modeling_obligation_id,
|
||||
&evidence.modeling_receipt_id,
|
||||
&modeling.observed_vector_binding_root_sha256,
|
||||
|
|
@ -518,10 +504,9 @@ fn projection_from_join(
|
|||
body_r1_generation: evidence.r1.generation,
|
||||
body_r2_observation_id: evidence.r2.observation_id,
|
||||
body_r2_generation: evidence.r2.generation,
|
||||
repo_model_graph_id: evidence.graph_id,
|
||||
repo_model_revision: evidence.model_revision,
|
||||
repo_model_hash: evidence.model_hash,
|
||||
admission_receipt_id: evidence.admission.receipt_id,
|
||||
repo_model_graph_id: evidence.repo_model.identity.graph_id,
|
||||
repo_model_projection_digest: evidence.repo_model.projection_digest,
|
||||
repo_model_source_documents: evidence.repo_model.source_documents,
|
||||
modeling_obligation_id: evidence.modeling_obligation_id,
|
||||
modeling_receipt_id: evidence.modeling_receipt_id,
|
||||
modeling_collection_name: modeling.collection_name,
|
||||
|
|
@ -544,7 +529,6 @@ fn projection_from_join(
|
|||
truth_interval_closed_at: observed_ready_at.into(),
|
||||
body_r1: r1,
|
||||
body_r2: r2,
|
||||
admission_envelope_sha256: evidence.admission_envelope_sha256,
|
||||
modeling_source_generation: evidence.modeling_source_generation,
|
||||
modeling_canonical_content_set_hash: evidence.modeling_canonical_content_set_hash,
|
||||
modeling_claim_id: evidence.modeling_claim_id,
|
||||
|
|
@ -564,15 +548,10 @@ fn projection_from_join(
|
|||
workspace_receipt_envelope_sha256: coverage.receipt_envelope_digest,
|
||||
workspace_head_envelope_sha256: coverage.head_envelope_digest,
|
||||
workspace_observed_point_set_sha256: coverage.observed_point_set_sha256,
|
||||
admission_body_basis: evidence
|
||||
.admission
|
||||
.repository_body_observation_basis
|
||||
.clone()
|
||||
.expect("join authenticated admission Body basis"),
|
||||
modeling_obligation_envelope_sha256: evidence.modeling_obligation_envelope_sha256,
|
||||
modeling_canonical_source_id: evidence.modeling_canonical_source_id,
|
||||
modeling_source_commit_id: evidence.modeling_source_commit_id,
|
||||
modeling_source_model_hash: evidence.modeling_source_model_hash,
|
||||
modeling_semantic_source_hash: evidence.modeling_semantic_source_hash,
|
||||
modeling_current_content_set_hash: evidence.modeling_current_content_set_hash,
|
||||
modeling_claim_envelope_sha256: evidence.modeling_claim_envelope_sha256,
|
||||
modeling_attempt_id: evidence.modeling_attempt_id,
|
||||
|
|
@ -590,8 +569,7 @@ fn readiness_authority_from_snapshot(rows: &[CultCacheEnvelope]) -> Vec<CultCach
|
|||
.cloned()
|
||||
.filter(|row| {
|
||||
row.r#type == crate::EpiphanyRuntimeSwarmBinding::TYPE
|
||||
|| row.r#type == EpiphanyMemoryGraphEntry::TYPE
|
||||
|| row.r#type == RepoModelAdmissionReceipt::TYPE
|
||||
|| row.r#type.starts_with("epiphany.mind.repo_model.")
|
||||
|| row.r#type == MemorySemanticProjectionObligation::TYPE
|
||||
|| row.r#type == MemorySemanticProjectionClaim::TYPE
|
||||
|| row.r#type == MemorySemanticProjectionAttempt::TYPE
|
||||
|
|
@ -616,33 +594,42 @@ fn exact_envelope<'a, T: DatabaseEntry>(
|
|||
.ok_or_else(|| anyhow!("authority is missing {} envelope {key}", T::TYPE))
|
||||
}
|
||||
|
||||
fn validate_repo_model_basis_against_snapshot(
|
||||
model: &EpiphanyRepoModelView,
|
||||
snapshot: &[CultCacheEnvelope],
|
||||
) -> Result<()> {
|
||||
let basis = model.reasoning_basis();
|
||||
basis.validate()?;
|
||||
let mut sources = snapshot
|
||||
.iter()
|
||||
.filter(|row| row.r#type.starts_with("epiphany.mind.repo_model."))
|
||||
.map(|row| EpiphanyMindDocumentVersion::from_envelope("epiphany-mind", row))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
sources.sort_by(|left, right| {
|
||||
(&left.document_type, &left.document_key).cmp(&(&right.document_type, &right.document_key))
|
||||
});
|
||||
if sources != basis.source_documents {
|
||||
bail!("RepoModel basis does not seal the exact keyed store snapshot");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn derive_joined_opening(
|
||||
snapshot: &[CultCacheEnvelope],
|
||||
r1: &RepositoryBodyObservationBasis,
|
||||
semantic: &RawSemanticObservation,
|
||||
workspace_identity: &WorkspaceProjectionIdentity,
|
||||
) -> Result<JoinedReadinessEvidence> {
|
||||
let model_entry: EpiphanyMemoryGraphEntry = rmp_serde::from_slice(
|
||||
&exact_envelope::<EpiphanyMemoryGraphEntry>(snapshot, crate::MEMORY_GRAPH_KEY)?.payload,
|
||||
)?;
|
||||
let model = model_entry.snapshot()?;
|
||||
let model_hash = memory_graph_model_hash(&model)?;
|
||||
validate_exact_raw_semantic_chain(r1, &model, &model_hash, semantic)?;
|
||||
let admission = select_current_admission(
|
||||
decode_keyed_rows::<RepoModelAdmissionReceipt>(snapshot)?,
|
||||
model.model_revision,
|
||||
&model_hash,
|
||||
)?;
|
||||
if !admission
|
||||
.repository_body_observation_basis
|
||||
.as_ref()
|
||||
.is_some_and(|basis| same_body_content(basis, r1))
|
||||
let model = &semantic.repo_model;
|
||||
validate_repo_model_basis_against_snapshot(model, snapshot)?;
|
||||
if model.identity.workspace_id != r1.workspace_id
|
||||
|| model.identity.swarm_id != r1.swarm_id
|
||||
|| model.identity.runtime_id != r1.runtime_id
|
||||
|| model.identity.body_binding_sha256 != r1.body_binding_sha256
|
||||
{
|
||||
bail!("current RepoModel admission does not authenticate Body R1");
|
||||
}
|
||||
if semantic.snapshot != model {
|
||||
bail!("Modeling semantic input is not the canonical RepoModel");
|
||||
bail!("current keyed RepoModel identity does not authenticate Body R1");
|
||||
}
|
||||
validate_exact_raw_semantic_chain(r1, model, semantic)?;
|
||||
for consumed in &semantic.authority_envelopes {
|
||||
if !snapshot.contains(consumed) {
|
||||
bail!("Modeling semantic authority is outside the exact store snapshot");
|
||||
|
|
@ -691,14 +678,7 @@ fn derive_joined_opening(
|
|||
Ok(JoinedReadinessEvidence {
|
||||
r1: r1.clone(),
|
||||
r2: r1.clone(),
|
||||
graph_id: model.graph_id,
|
||||
model_revision: model.model_revision,
|
||||
model_hash,
|
||||
admission_envelope_sha256: envelope_sha256(exact_envelope::<RepoModelAdmissionReceipt>(
|
||||
snapshot,
|
||||
&admission.receipt_id,
|
||||
)?)?,
|
||||
admission,
|
||||
repo_model: model.clone(),
|
||||
modeling_obligation_id: obligation.obligation_id.clone(),
|
||||
modeling_receipt_id: receipt.receipt_id.clone(),
|
||||
modeling_source_generation: receipt.source_generation,
|
||||
|
|
@ -712,7 +692,7 @@ fn derive_joined_opening(
|
|||
modeling_obligation_envelope_sha256: envelope_sha256(obligation_envelope)?,
|
||||
modeling_canonical_source_id: obligation.canonical_source_id,
|
||||
modeling_source_commit_id: obligation.source_commit_id,
|
||||
modeling_source_model_hash: obligation.source_model_hash,
|
||||
modeling_semantic_source_hash: obligation.source_model_hash,
|
||||
modeling_current_content_set_hash: semantic.current.canonical_content_set_hash.clone(),
|
||||
modeling_claim_envelope_sha256: envelope_sha256(claim_envelope)?,
|
||||
modeling_attempt_id: claim.attempt_id,
|
||||
|
|
@ -774,19 +754,14 @@ impl ReadinessObservationPorts for ProductionReadinessPorts<'_> {
|
|||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
fn authenticate_historical_body_basis(
|
||||
&mut self,
|
||||
basis: &RepositoryBodyObservationBasis,
|
||||
) -> Result<()> {
|
||||
validate_repository_body_observation_basis(self.runtime_store, basis)
|
||||
}
|
||||
|
||||
fn observe_semantic_state(&mut self) -> Result<RawSemanticObservation> {
|
||||
let input = runtime_modeling_semantic_projection_input(self.runtime_store)?;
|
||||
let readiness = load_memory_semantic_projection_readiness(self.runtime_store, &input)?
|
||||
.ok_or_else(|| anyhow!("current Modeling semantic projection is not ready"))?;
|
||||
let repo_model = assemble_repo_model_view(self.runtime_store)?;
|
||||
let raw = RawSemanticObservation {
|
||||
snapshot: input.snapshot().clone(),
|
||||
semantic_content: RepoModelSemanticContent::from_semantic_input(&input),
|
||||
repo_model,
|
||||
authority_envelopes: input.authority.envelopes.clone(),
|
||||
obligation: readiness.obligation.clone(),
|
||||
current: readiness.current.clone(),
|
||||
|
|
@ -881,8 +856,6 @@ fn observe_repository_readiness_with_clock(
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{REPO_MODEL_ADMISSION_CONTRACT, REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION};
|
||||
use epiphany_state_model::RepoModelPatchPurpose;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FakePorts {
|
||||
|
|
@ -898,7 +871,6 @@ mod tests {
|
|||
append: Result<ReadinessAppendResult, &'static str>,
|
||||
published: usize,
|
||||
coverage_body_ids: Vec<String>,
|
||||
body_basis_auth: Result<(), &'static str>,
|
||||
}
|
||||
|
||||
impl ReadinessObservationPorts for FakePorts {
|
||||
|
|
@ -917,14 +889,6 @@ mod tests {
|
|||
Ok(self.snapshots.remove(0))
|
||||
}
|
||||
|
||||
fn authenticate_historical_body_basis(
|
||||
&mut self,
|
||||
_basis: &RepositoryBodyObservationBasis,
|
||||
) -> Result<()> {
|
||||
self.calls.push("authenticate-admission-body");
|
||||
self.body_basis_auth.map_err(|message| anyhow!(message))
|
||||
}
|
||||
|
||||
fn observe_semantic_state(&mut self) -> Result<RawSemanticObservation> {
|
||||
self.calls.push(if self.semantic_reads == 0 {
|
||||
"semantic-state"
|
||||
|
|
@ -1001,36 +965,6 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn admission(body: RepositoryBodyObservationBasis) -> RepoModelAdmissionReceipt {
|
||||
RepoModelAdmissionReceipt {
|
||||
schema_version: REPO_MODEL_ADMISSION_RECEIPT_SCHEMA_VERSION.into(),
|
||||
receipt_id: "admission".into(),
|
||||
review_id: "review".into(),
|
||||
result_id: Some("result".into()),
|
||||
patch_id: "patch".into(),
|
||||
patch_sha256: "patch-hash".into(),
|
||||
previous_revision: 6,
|
||||
previous_hash: "previous".into(),
|
||||
admitted_revision: 7,
|
||||
admitted_hash: "model-hash".into(),
|
||||
admitted_at: "2026-07-16T00:00:00Z".into(),
|
||||
contract: REPO_MODEL_ADMISSION_CONTRACT.into(),
|
||||
purpose: RepoModelPatchPurpose::Evolution,
|
||||
frontier_route_id: String::new(),
|
||||
verification_request_id: String::new(),
|
||||
soul_verdict_receipt_id: String::new(),
|
||||
frontier_modeling_request_id: String::new(),
|
||||
proposal_modeling_request_id: String::new(),
|
||||
claim_repair_request_id: String::new(),
|
||||
frontier_plan_decision_id: String::new(),
|
||||
repository_body_observation_basis: Some(body),
|
||||
admission_source: Some(crate::RepoModelAdmissionSource::WorkerResult {
|
||||
result_id: "result".into(),
|
||||
job_id: "job".into(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn envelope<T: DatabaseEntry>(key: &str, value: &T) -> CultCacheEnvelope {
|
||||
CultCacheEnvelope {
|
||||
key: key.into(),
|
||||
|
|
@ -1041,18 +975,47 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn repo_model(
|
||||
body: &RepositoryBodyObservationBasis,
|
||||
) -> Result<(Vec<CultCacheEnvelope>, EpiphanyRepoModelView)> {
|
||||
let identity = crate::EpiphanyRepoModelIdentityDocument {
|
||||
schema_epoch: crate::REPO_MODEL_SCHEMA_EPOCH.into(),
|
||||
graph_id: "graph".into(),
|
||||
runtime_id: body.runtime_id.clone(),
|
||||
swarm_id: body.swarm_id.clone(),
|
||||
workspace_id: body.workspace_id.clone(),
|
||||
body_binding_sha256: body.body_binding_sha256.clone(),
|
||||
};
|
||||
let identity_envelope = envelope(crate::REPO_MODEL_IDENTITY_KEY, &identity);
|
||||
let source_documents = vec![EpiphanyMindDocumentVersion::from_envelope(
|
||||
"epiphany-mind",
|
||||
&identity_envelope,
|
||||
)?];
|
||||
let projection_digest = format!(
|
||||
"sha256:{:x}",
|
||||
Sha256::digest(rmp_serde::to_vec_named(&source_documents)?)
|
||||
);
|
||||
Ok((
|
||||
vec![identity_envelope],
|
||||
EpiphanyRepoModelView {
|
||||
identity,
|
||||
projection_digest,
|
||||
source_documents,
|
||||
domains: Vec::new(),
|
||||
nodes: Vec::new(),
|
||||
edges: Vec::new(),
|
||||
summaries: Vec::new(),
|
||||
frontier: Vec::new(),
|
||||
lifecycle_receipts: Vec::new(),
|
||||
claim_obligations: Vec::new(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn raw_fixture(
|
||||
body: RepositoryBodyObservationBasis,
|
||||
) -> Result<(Vec<CultCacheEnvelope>, RawSemanticObservation)> {
|
||||
let mut model = EpiphanyMemoryGraphSnapshot {
|
||||
graph_id: "graph".into(),
|
||||
model_revision: 7,
|
||||
..Default::default()
|
||||
};
|
||||
model.model_hash = memory_graph_model_hash(&model)?;
|
||||
let model_entry = EpiphanyMemoryGraphEntry::from_snapshot(&model)?;
|
||||
let mut admitted = admission(body);
|
||||
admitted.admitted_hash = model.model_hash.clone();
|
||||
let (mut rows, model) = repo_model(&body)?;
|
||||
let obligation = MemorySemanticProjectionObligation {
|
||||
schema_version: MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION.into(),
|
||||
obligation_id: "semantic-obligation".into(),
|
||||
|
|
@ -1060,9 +1023,9 @@ mod tests {
|
|||
partition: "modeling".into(),
|
||||
canonical_source_id: "source".into(),
|
||||
source_commit_id: "commit".into(),
|
||||
graph_id: model.graph_id.clone(),
|
||||
source_generation: model.model_revision,
|
||||
source_model_hash: model.model_hash.clone(),
|
||||
graph_id: model.identity.graph_id.clone(),
|
||||
source_generation: 7,
|
||||
source_model_hash: "semantic-model-hash".into(),
|
||||
canonical_content_set_hash: "semantic-content".into(),
|
||||
projection_schema_version: SEMANTIC_PROJECTION_SCHEMA_VERSION.into(),
|
||||
created_at: "2026-07-16T00:00:00Z".into(),
|
||||
|
|
@ -1083,9 +1046,9 @@ mod tests {
|
|||
swarm_id: "swarm".into(),
|
||||
partition: "modeling".into(),
|
||||
collection_name: "modeling".into(),
|
||||
graph_id: model.graph_id.clone(),
|
||||
graph_id: model.identity.graph_id.clone(),
|
||||
model_revision: 7,
|
||||
model_hash: model.model_hash.clone(),
|
||||
model_hash: obligation.source_model_hash.clone(),
|
||||
embedding_provider_id: "semantic-provider".into(),
|
||||
embedding_model: "semantic-model".into(),
|
||||
vector_dimensions: 1024,
|
||||
|
|
@ -1134,16 +1097,15 @@ mod tests {
|
|||
physical_backend_url: "http://qdrant".into(),
|
||||
collection_name: "semantic-modeling".into(),
|
||||
};
|
||||
let rows = vec![
|
||||
envelope(crate::MEMORY_GRAPH_KEY, &model_entry),
|
||||
envelope(&admitted.receipt_id, &admitted),
|
||||
rows.extend([
|
||||
envelope(&obligation.obligation_id, &obligation),
|
||||
envelope(&receipt.receipt_id, &receipt),
|
||||
envelope(&claim.scope_id, &claim),
|
||||
envelope(&attempt.attempt_id, &attempt),
|
||||
];
|
||||
]);
|
||||
let raw = RawSemanticObservation {
|
||||
snapshot: model,
|
||||
semantic_content: RepoModelSemanticContent::from_repo_model(&model),
|
||||
repo_model: model,
|
||||
authority_envelopes: rows.clone(),
|
||||
obligation,
|
||||
current,
|
||||
|
|
@ -1152,25 +1114,15 @@ mod tests {
|
|||
Ok((rows, raw))
|
||||
}
|
||||
|
||||
fn keyed(receipts: Vec<RepoModelAdmissionReceipt>) -> Vec<(String, RepoModelAdmissionReceipt)> {
|
||||
receipts
|
||||
.into_iter()
|
||||
.map(|receipt| (receipt.receipt_id.clone(), receipt))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn joined(
|
||||
r1: RepositoryBodyObservationBasis,
|
||||
r2: RepositoryBodyObservationBasis,
|
||||
) -> JoinedReadinessEvidence {
|
||||
let repo_model = repo_model(&r1).unwrap().1;
|
||||
JoinedReadinessEvidence {
|
||||
admission: admission(r1.clone()),
|
||||
admission_envelope_sha256: "admission-envelope".into(),
|
||||
r1,
|
||||
r2,
|
||||
graph_id: "graph".into(),
|
||||
model_revision: 7,
|
||||
model_hash: "model-hash".into(),
|
||||
repo_model,
|
||||
modeling_obligation_id: "semantic-obligation".into(),
|
||||
modeling_receipt_id: "semantic-receipt".into(),
|
||||
modeling_source_generation: 7,
|
||||
|
|
@ -1184,7 +1136,7 @@ mod tests {
|
|||
modeling_obligation_envelope_sha256: "semantic-obligation-envelope".into(),
|
||||
modeling_canonical_source_id: "source".into(),
|
||||
modeling_source_commit_id: "commit".into(),
|
||||
modeling_source_model_hash: "model-hash".into(),
|
||||
modeling_semantic_source_hash: "semantic-model-hash".into(),
|
||||
modeling_current_content_set_hash: "semantic-content".into(),
|
||||
modeling_claim_envelope_sha256: "semantic-claim-envelope".into(),
|
||||
modeling_attempt_id: "semantic-attempt".into(),
|
||||
|
|
@ -1251,7 +1203,6 @@ mod tests {
|
|||
append: Ok(ReadinessAppendResult::Appended),
|
||||
published: 0,
|
||||
coverage_body_ids: Vec::new(),
|
||||
body_basis_auth: Ok(()),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -1274,7 +1225,6 @@ mod tests {
|
|||
"r1",
|
||||
"opening",
|
||||
"semantic-state",
|
||||
"authenticate-admission-body",
|
||||
"semantic",
|
||||
"coverage",
|
||||
"r2",
|
||||
|
|
@ -1300,7 +1250,7 @@ mod tests {
|
|||
let mut authority_drift = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap();
|
||||
authority_drift.snapshots[1].push(CultCacheEnvelope {
|
||||
key: "alien".into(),
|
||||
r#type: RepoModelAdmissionReceipt::TYPE.into(),
|
||||
r#type: crate::EpiphanyRepoModelIdentityDocument::TYPE.into(),
|
||||
payload: vec![1],
|
||||
stored_at: "2026-07-16T00:00:02Z".into(),
|
||||
schema_id: None,
|
||||
|
|
@ -1310,28 +1260,24 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn raw_opening_stale_or_alien_admission_is_rejected_before_live_queries() {
|
||||
fn raw_opening_incomplete_or_tampered_keyed_model_is_rejected_before_live_queries() {
|
||||
let r1 = basis("a1", 1, "root-a");
|
||||
let identity = joined(r1.clone(), r1.clone()).workspace_identity;
|
||||
let mut alien = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap();
|
||||
alien.snapshots[0]
|
||||
.iter_mut()
|
||||
.find(|row| row.r#type == RepoModelAdmissionReceipt::TYPE)
|
||||
.unwrap()
|
||||
.key = "alien".into();
|
||||
assert!(observe_with_ports(&mut alien, &identity).is_err());
|
||||
assert!(!alien.calls.contains(&"semantic"));
|
||||
let mut incomplete = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap();
|
||||
incomplete.snapshots[0]
|
||||
.retain(|row| row.r#type != crate::EpiphanyRepoModelIdentityDocument::TYPE);
|
||||
assert!(observe_with_ports(&mut incomplete, &identity).is_err());
|
||||
assert!(!incomplete.calls.contains(&"semantic"));
|
||||
|
||||
let mut stale = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap();
|
||||
let row = stale.snapshots[0]
|
||||
let mut tampered = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap();
|
||||
tampered.snapshots[0]
|
||||
.iter_mut()
|
||||
.find(|row| row.r#type == RepoModelAdmissionReceipt::TYPE)
|
||||
.unwrap();
|
||||
let mut receipt: RepoModelAdmissionReceipt = rmp_serde::from_slice(&row.payload).unwrap();
|
||||
receipt.admitted_revision -= 1;
|
||||
row.payload = rmp_serde::to_vec_named(&receipt).unwrap();
|
||||
assert!(observe_with_ports(&mut stale, &identity).is_err());
|
||||
assert!(!stale.calls.contains(&"semantic"));
|
||||
.find(|row| row.r#type == crate::EpiphanyRepoModelIdentityDocument::TYPE)
|
||||
.unwrap()
|
||||
.payload
|
||||
.push(0);
|
||||
assert!(observe_with_ports(&mut tampered, &identity).is_err());
|
||||
assert!(!tampered.calls.contains(&"semantic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1349,17 +1295,6 @@ mod tests {
|
|||
assert!(!receipt_forgery.calls.contains(&"semantic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unauthenticated_historical_admission_basis_is_rejected_before_live_query() {
|
||||
let r1 = basis("a1", 1, "root-a");
|
||||
let identity = joined(r1.clone(), r1.clone()).workspace_identity;
|
||||
let mut ports = fake_ports(r1.clone(), basis("a2", 2, "root-a")).unwrap();
|
||||
ports.body_basis_auth = Err("historical basis is not authentic");
|
||||
assert!(observe_with_ports(&mut ports, &identity).is_err());
|
||||
assert!(ports.calls.contains(&"authenticate-admission-body"));
|
||||
assert!(!ports.calls.contains(&"semantic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cas_refusal_returns_no_success_and_identical_concurrent_append_is_accepted() -> Result<()> {
|
||||
let r1 = basis("a1", 1, "root-a");
|
||||
|
|
@ -1431,33 +1366,6 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_or_multiple_current_admission_is_refused() {
|
||||
let body = basis("a", 1, "root-a");
|
||||
let mut stale = admission(body.clone());
|
||||
stale.admitted_revision = 6;
|
||||
assert!(select_current_admission(keyed(vec![stale]), 7, "model-hash").is_err());
|
||||
assert!(
|
||||
select_current_admission(
|
||||
keyed(vec![admission(body.clone()), admission(body)]),
|
||||
7,
|
||||
"model-hash"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let grounded = admission(basis("a", 1, "root-a"));
|
||||
let mut ungrounded = grounded.clone();
|
||||
ungrounded.receipt_id = "ungrounded-duplicate".into();
|
||||
ungrounded.repository_body_observation_basis = None;
|
||||
assert!(
|
||||
select_current_admission(keyed(vec![grounded, ungrounded]), 7, "model-hash").is_err()
|
||||
);
|
||||
let alien = admission(basis("a", 1, "root-a"));
|
||||
assert!(
|
||||
select_current_admission(vec![("alien-key".into(), alien)], 7, "model-hash").is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_semantic_or_stored_only_coverage_cannot_substitute_for_live_evidence() {
|
||||
let body = basis("a", 1, "root-a");
|
||||
|
|
@ -1477,7 +1385,7 @@ mod tests {
|
|||
let mut advanced = joined(a.clone(), a);
|
||||
advanced.closing_authority.push(CultCacheEnvelope {
|
||||
key: "duplicate".into(),
|
||||
r#type: "epiphany.mind.repo_model_admission_receipt".into(),
|
||||
r#type: "epiphany.mind.repo_model.node.v1".into(),
|
||||
payload: vec![1],
|
||||
stored_at: "2026-07-16T00:00:02Z".into(),
|
||||
schema_id: None,
|
||||
|
|
|
|||
|
|
@ -167,10 +167,7 @@ fn resident_process_singleton_is_owned(role: &str, store: &Path) -> Result<bool>
|
|||
if !path.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let file = File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)?;
|
||||
let file = File::options().read(true).write(true).open(path)?;
|
||||
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
|
||||
unsafe {
|
||||
let _ = libc::flock(file.as_raw_fd(), libc::LOCK_UN);
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -67,12 +67,11 @@ impl RuntimeSpineBackingStore {
|
|||
replacements,
|
||||
deletions,
|
||||
),
|
||||
SelectedBackingStore::Keyed(store) => store
|
||||
.replace_and_delete_if_snapshot_unchanged(
|
||||
expected_snapshot,
|
||||
replacements,
|
||||
deletions,
|
||||
),
|
||||
SelectedBackingStore::Keyed(store) => store.replace_and_delete_if_snapshot_unchanged(
|
||||
expected_snapshot,
|
||||
replacements,
|
||||
deletions,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -82,10 +81,12 @@ impl RuntimeSpineBackingStore {
|
|||
replacements: Vec<CultCacheEnvelope>,
|
||||
) -> Result<bool> {
|
||||
match self.selected()? {
|
||||
SelectedBackingStore::Snapshot(store) => store
|
||||
.replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements),
|
||||
SelectedBackingStore::Keyed(store) => store
|
||||
.replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements),
|
||||
SelectedBackingStore::Snapshot(store) => {
|
||||
store.replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements)
|
||||
}
|
||||
SelectedBackingStore::Keyed(store) => {
|
||||
store.replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ use crate::memory_graph::{
|
|||
};
|
||||
use crate::{
|
||||
MemorySemanticIndexConfig, MemorySemanticProjectionInput,
|
||||
agent_memory_semantic_projection_input, runtime_modeling_semantic_projection_input,
|
||||
agent_memory_semantic_projection_input,
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::{SecondsFormat, Utc};
|
||||
|
|
@ -189,9 +189,7 @@ impl SemanticProjectorServiceBody {
|
|||
config: MemorySemanticIndexConfig,
|
||||
) -> Result<Self> {
|
||||
let singleton = acquire_semantic_projector_singleton(&mind_store, &modeling_store)?;
|
||||
let mind_input = agent_memory_semantic_projection_input(&mind_store)?;
|
||||
let modeling_input = runtime_modeling_semantic_projection_input(&modeling_store)?;
|
||||
validate_semantic_projector_source_pair(&mind_input, &modeling_input)?;
|
||||
agent_memory_semantic_projection_input(&mind_store)?;
|
||||
let session = LocalIdunnSemanticProjectorSession::new(
|
||||
mind_store,
|
||||
modeling_store,
|
||||
|
|
@ -213,21 +211,11 @@ impl SemanticProjectorServiceBody {
|
|||
pub fn pulse(&self, fairness_cursor: Option<&str>) -> SemanticProjectorServicePulse {
|
||||
let session = &self.pulser.port;
|
||||
let mut source_fault_count = 0;
|
||||
let mut inputs = Vec::with_capacity(2);
|
||||
let mut inputs = Vec::with_capacity(1);
|
||||
match agent_memory_semantic_projection_input(&session.mind_store) {
|
||||
Ok(input) => inputs.push(input),
|
||||
Err(_) => source_fault_count += 1,
|
||||
}
|
||||
match runtime_modeling_semantic_projection_input(&session.modeling_store) {
|
||||
Ok(input) => inputs.push(input),
|
||||
Err(_) => source_fault_count += 1,
|
||||
}
|
||||
if inputs.len() == 2
|
||||
&& validate_semantic_projector_source_pair(&inputs[0], &inputs[1]).is_err()
|
||||
{
|
||||
source_fault_count += 2;
|
||||
inputs.clear();
|
||||
}
|
||||
let outcome = self.pulser.pulse(&inputs, fairness_cursor);
|
||||
SemanticProjectorServicePulse {
|
||||
outcome,
|
||||
|
|
|
|||
|
|
@ -14,9 +14,9 @@ pub const SOUL_VERIFICATION_REQUEST_SCHEMA_VERSION: &str = "epiphany.soul.verifi
|
|||
pub const REPO_FRONTIER_VERIFICATION_REQUEST_TYPE: &str =
|
||||
"epiphany.soul.repo_frontier_verification_request";
|
||||
pub const REPO_FRONTIER_VERIFICATION_REQUEST_SCHEMA_VERSION: &str =
|
||||
"epiphany.soul.repo_frontier_verification_request.v0";
|
||||
"epiphany.soul.repo_frontier_verification_request.v1";
|
||||
pub const REPO_FRONTIER_VERIFICATION_REQUEST_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_verification_request.v0";
|
||||
"epiphany.repo_frontier_verification_request.v1";
|
||||
pub const SOUL_INVARIANT_CHECK_SCHEMA_VERSION: &str = "epiphany.soul.invariant_check.v0";
|
||||
pub const SOUL_VERDICT_RECEIPT_SCHEMA_VERSION: &str = "epiphany.soul.verdict_receipt.v1";
|
||||
pub const SOUL_REGRESSION_RECEIPT_SCHEMA_VERSION: &str = "epiphany.soul.regression_receipt.v0";
|
||||
|
|
@ -66,9 +66,9 @@ pub struct RepoFrontierVerificationRequest {
|
|||
#[cultcache(key = 2)]
|
||||
pub route_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub model_revision: u64,
|
||||
pub model_projection_digest: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub model_hash: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
#[cultcache(key = 5)]
|
||||
pub frontier_item_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
|
|
@ -250,7 +250,7 @@ mod tests {
|
|||
evidence_gaps: Vec::new(),
|
||||
risks: Vec::new(),
|
||||
state_patch: None,
|
||||
repo_model_patch: None,
|
||||
repo_model_mutation_proposal: None,
|
||||
self_patch: None,
|
||||
self_persistence: None,
|
||||
job_error: None,
|
||||
|
|
|
|||
|
|
@ -178,9 +178,7 @@ pub fn substrate_gate_operation_for_governed_tool(
|
|||
| ("epiphany_state", "resident_grant_lifecycle") => {
|
||||
Some(SUBSTRATE_GATE_SOURCE_READ_OPERATION)
|
||||
}
|
||||
("epiphany_public", "github_file") => {
|
||||
Some(SUBSTRATE_GATE_PUBLIC_SOURCE_READ_OPERATION)
|
||||
}
|
||||
("epiphany_public", "github_file") => Some(SUBSTRATE_GATE_PUBLIC_SOURCE_READ_OPERATION),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -146,7 +146,7 @@ pub fn derive_coordinator_finding_signals(
|
|||
})
|
||||
});
|
||||
let modeling_result_reviewable =
|
||||
modeling_finding.is_some_and(modeling_finding_has_reviewable_repo_model_patch);
|
||||
modeling_finding.is_some_and(modeling_finding_has_reviewable_repo_model_mutation);
|
||||
let modeling_result_requests_regather =
|
||||
modeling_finding.is_some_and(modeling_finding_requests_regather);
|
||||
let modeling_result_failure_reviewed = modeling_finding.as_ref().is_some_and(|finding| {
|
||||
|
|
@ -254,12 +254,16 @@ pub fn reorient_finding_already_accepted(
|
|||
false
|
||||
}
|
||||
|
||||
fn modeling_finding_has_reviewable_repo_model_patch(
|
||||
fn modeling_finding_has_reviewable_repo_model_mutation(
|
||||
finding: &EpiphanyRoleFindingInterpretation,
|
||||
) -> bool {
|
||||
finding.item_error.is_none()
|
||||
&& finding.job_error.is_none()
|
||||
&& finding.repo_model_patch.is_some()
|
||||
&& (finding.repo_model_mutation_proposal.is_some()
|
||||
|| finding.verdict.as_deref().is_some_and(|verdict| {
|
||||
verdict.eq_ignore_ascii_case("checkpoint-ready")
|
||||
|| verdict.eq_ignore_ascii_case("regather-needed")
|
||||
}))
|
||||
&& finding
|
||||
.state_patch
|
||||
.as_ref()
|
||||
|
|
@ -1471,7 +1475,7 @@ mod tests {
|
|||
evidence_gaps: Vec::new(),
|
||||
risks: Vec::new(),
|
||||
state_patch: None,
|
||||
repo_model_patch: None,
|
||||
repo_model_mutation_proposal: None,
|
||||
self_patch: None,
|
||||
self_persistence: None,
|
||||
job_error: None,
|
||||
|
|
|
|||
|
|
@ -129,16 +129,16 @@ pub use worker_launch::REPO_FRONTIER_PLAN_MIND_CONTEXT_CONTRACT;
|
|||
pub use worker_launch::REPO_FRONTIER_PLAN_MIND_CONTEXT_SCHEMA_VERSION;
|
||||
pub use worker_launch::REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT;
|
||||
pub use worker_launch::REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION;
|
||||
pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT;
|
||||
pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION;
|
||||
pub use worker_launch::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT;
|
||||
pub use worker_launch::REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION;
|
||||
pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT;
|
||||
pub use worker_launch::REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION;
|
||||
pub use worker_launch::REPO_MODEL_CLAIM_REPAIR_CONTEXT_CONTRACT;
|
||||
pub use worker_launch::REPO_MODEL_CLAIM_REPAIR_CONTEXT_SCHEMA_VERSION;
|
||||
pub use worker_launch::ROLE_WORKER_OUTPUT_CONTRACT_ID;
|
||||
pub use worker_launch::RepoFrontierPlanMindContextProjection;
|
||||
pub use worker_launch::RepoFrontierPlanningContextProjection;
|
||||
pub use worker_launch::RepoFrontierResearchContextProjection;
|
||||
pub use worker_launch::RepoFrontierProposalModelingContextProjection;
|
||||
pub use worker_launch::RepoFrontierResearchContextProjection;
|
||||
pub use worker_launch::RepoModelClaimRepairContextProjection;
|
||||
pub use worker_launch::build_reorient_job_launch_request;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use epiphany_state_model::EpiphanyInvestigationDisposition;
|
||||
use epiphany_state_model::EpiphanyInvestigationCheckpoint;
|
||||
use epiphany_state_model::EpiphanyInvestigationDisposition;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashSet;
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ pub struct EpiphanyRoleFindingInterpretation {
|
|||
pub evidence_gaps: Vec<String>,
|
||||
pub risks: Vec<String>,
|
||||
pub state_patch: Option<EpiphanyRoleStatePatchDocument>,
|
||||
pub repo_model_patch: Option<crate::RepoModelPatch>,
|
||||
pub repo_model_mutation_proposal: Option<crate::EpiphanyRepoModelMutationProposal>,
|
||||
pub self_patch: Option<AgentSelfPatch>,
|
||||
pub self_persistence: Option<EpiphanyRoleSelfPersistenceReview>,
|
||||
pub job_error: Option<String>,
|
||||
|
|
@ -140,14 +140,14 @@ fn interpret_role_finding(
|
|||
let state_patch_parse_error = state_patch_result
|
||||
.as_ref()
|
||||
.and_then(|result| result.as_ref().err().map(ToString::to_string));
|
||||
let repo_model_patch_result = raw_result
|
||||
.get("repoModelPatch")
|
||||
let repo_model_mutation_proposal_result = raw_result
|
||||
.get("repoModelMutationProposal")
|
||||
.cloned()
|
||||
.map(serde_json::from_value::<crate::RepoModelPatch>);
|
||||
let repo_model_patch = repo_model_patch_result
|
||||
.map(serde_json::from_value::<crate::EpiphanyRepoModelMutationProposal>);
|
||||
let repo_model_mutation_proposal = repo_model_mutation_proposal_result
|
||||
.as_ref()
|
||||
.and_then(|result| result.as_ref().ok().cloned());
|
||||
let repo_model_patch_parse_error = repo_model_patch_result
|
||||
let repo_model_mutation_proposal_parse_error = repo_model_mutation_proposal_result
|
||||
.as_ref()
|
||||
.and_then(|result| result.as_ref().err().map(ToString::to_string));
|
||||
let (self_patch, self_persistence) = raw_result
|
||||
|
|
@ -166,9 +166,9 @@ fn interpret_role_finding(
|
|||
EpiphanyRoleResultRoleId::Modeling => merge_item_error(
|
||||
item_error,
|
||||
modeling_role_result_error(
|
||||
raw_result.get("repoModelPatch").is_some(),
|
||||
repo_model_patch.as_ref(),
|
||||
repo_model_patch_parse_error,
|
||||
raw_result.get("repoModelMutationProposal").is_some(),
|
||||
repo_model_mutation_proposal.as_ref(),
|
||||
repo_model_mutation_proposal_parse_error,
|
||||
state_patch.as_ref(),
|
||||
state_patch_parse_error,
|
||||
),
|
||||
|
|
@ -202,7 +202,7 @@ fn interpret_role_finding(
|
|||
evidence_gaps: json_string_array_field(raw_result, "evidenceGaps"),
|
||||
risks: json_string_array_field(raw_result, "risks"),
|
||||
state_patch,
|
||||
repo_model_patch,
|
||||
repo_model_mutation_proposal,
|
||||
self_patch,
|
||||
self_persistence,
|
||||
job_error,
|
||||
|
|
@ -242,7 +242,7 @@ pub fn interpret_runtime_role_worker_result(
|
|||
result: &crate::EpiphanyRuntimeRoleWorkerResult,
|
||||
) -> EpiphanyRoleFindingInterpretation {
|
||||
let state_patch_result = result.state_patch();
|
||||
let repo_model_patch_result = result.repo_model_patch();
|
||||
let repo_model_mutation_proposal_result = result.repo_model_mutation_proposal();
|
||||
let self_patch_result = result.self_patch();
|
||||
let state_patch = state_patch_result
|
||||
.as_ref()
|
||||
|
|
@ -252,7 +252,7 @@ pub fn interpret_runtime_role_worker_result(
|
|||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|patch| patch.clone());
|
||||
let repo_model_patch = repo_model_patch_result
|
||||
let repo_model_mutation_proposal = repo_model_mutation_proposal_result
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|patch| patch.clone());
|
||||
|
|
@ -266,7 +266,7 @@ pub fn interpret_runtime_role_worker_result(
|
|||
);
|
||||
let item_error = merge_item_error(
|
||||
item_error,
|
||||
repo_model_patch_result
|
||||
repo_model_mutation_proposal_result
|
||||
.as_ref()
|
||||
.err()
|
||||
.map(ToString::to_string),
|
||||
|
|
@ -287,7 +287,7 @@ pub fn interpret_runtime_role_worker_result(
|
|||
evidence_gaps: result.evidence_gaps.clone(),
|
||||
risks: result.risks.clone(),
|
||||
state_patch: state_patch.clone(),
|
||||
repo_model_patch: repo_model_patch.clone(),
|
||||
repo_model_mutation_proposal: repo_model_mutation_proposal.clone(),
|
||||
self_patch,
|
||||
self_persistence: None,
|
||||
job_error: None,
|
||||
|
|
@ -295,8 +295,8 @@ pub fn interpret_runtime_role_worker_result(
|
|||
EpiphanyRoleResultRoleId::Modeling => merge_item_error(
|
||||
item_error,
|
||||
modeling_role_result_error(
|
||||
result.repo_model_patch_msgpack.is_some(),
|
||||
repo_model_patch.as_ref(),
|
||||
result.repo_model_mutation_proposal_msgpack.is_some(),
|
||||
repo_model_mutation_proposal.as_ref(),
|
||||
None,
|
||||
state_patch.as_ref(),
|
||||
None,
|
||||
|
|
@ -642,7 +642,7 @@ pub fn modeling_role_state_patch_policy_errors(
|
|||
|| patch.investigation_checkpoint.is_some()
|
||||
{
|
||||
errors.push(
|
||||
"repository anatomy is not allowed in generic Modeling statePatch; use repoModelPatch"
|
||||
"repository anatomy is not allowed in generic Modeling statePatch; use repoModelOperations"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
|
@ -807,24 +807,28 @@ pub fn research_role_state_patch_policy_errors(
|
|||
}
|
||||
|
||||
fn modeling_role_result_error(
|
||||
repo_model_patch_present: bool,
|
||||
repo_model_patch: Option<&crate::RepoModelPatch>,
|
||||
repo_model_patch_parse_error: Option<String>,
|
||||
repo_model_mutation_proposal_present: bool,
|
||||
repo_model_mutation_proposal: Option<&crate::EpiphanyRepoModelMutationProposal>,
|
||||
repo_model_mutation_proposal_parse_error: Option<String>,
|
||||
state_patch: Option<&EpiphanyRoleStatePatchDocument>,
|
||||
state_patch_parse_error: Option<String>,
|
||||
) -> Option<String> {
|
||||
if !repo_model_patch_present {
|
||||
return Some(
|
||||
"modeling result is not reviewable: missing required repoModelPatch".to_string(),
|
||||
);
|
||||
};
|
||||
if let Some(error) = repo_model_patch_parse_error {
|
||||
if let Some(error) = repo_model_mutation_proposal_parse_error {
|
||||
return Some(format!(
|
||||
"modeling result is not reviewable: invalid repoModelPatch ({error})"
|
||||
"modeling result is not reviewable: invalid RepoModel mutation proposal ({error})"
|
||||
));
|
||||
}
|
||||
if repo_model_patch.is_none() {
|
||||
return Some("modeling result is not reviewable: invalid repoModelPatch".to_string());
|
||||
if repo_model_mutation_proposal_present && repo_model_mutation_proposal.is_none() {
|
||||
return Some(
|
||||
"modeling result is not reviewable: invalid RepoModel mutation proposal".to_string(),
|
||||
);
|
||||
}
|
||||
if let Some(proposal) = repo_model_mutation_proposal
|
||||
&& let Err(error) = proposal.validate()
|
||||
{
|
||||
return Some(format!(
|
||||
"modeling result is not reviewable: invalid RepoModel mutation proposal ({error})"
|
||||
));
|
||||
};
|
||||
if let Some(error) = state_patch_parse_error {
|
||||
return Some(format!(
|
||||
|
|
@ -1202,8 +1206,8 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn marks_modeling_without_patch_unreviewable() {
|
||||
let missing = interpret_role_finding(
|
||||
fn marks_modeling_no_mutation_checkpoint_reviewable() {
|
||||
let checkpoint = interpret_role_finding(
|
||||
EpiphanyRoleResultRoleId::Modeling,
|
||||
&serde_json::json!({"verdict": "checkpoint-ready"}),
|
||||
None,
|
||||
|
|
@ -1211,31 +1215,7 @@ mod tests {
|
|||
None,
|
||||
);
|
||||
|
||||
assert!(
|
||||
missing
|
||||
.item_error
|
||||
.as_deref()
|
||||
.is_some_and(|error| error.contains("missing required repoModelPatch"))
|
||||
);
|
||||
|
||||
let reviewable = interpret_role_finding(
|
||||
EpiphanyRoleResultRoleId::Modeling,
|
||||
&serde_json::json!({
|
||||
"repoModelPatch": {
|
||||
"patch_id": "modeling-result-test",
|
||||
"base_revision": 0,
|
||||
"base_hash": "legacy-hash",
|
||||
"applied_at": "2026-07-13T00:00:00Z",
|
||||
"purpose": {"kind": "evolution"},
|
||||
"operations": [{"operation": "retire_node", "node_id": "old"}]
|
||||
}
|
||||
}),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
|
||||
assert!(reviewable.item_error.is_none());
|
||||
assert!(checkpoint.item_error.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1243,14 +1223,6 @@ mod tests {
|
|||
let finding = interpret_role_finding(
|
||||
EpiphanyRoleResultRoleId::Modeling,
|
||||
&serde_json::json!({
|
||||
"repoModelPatch": {
|
||||
"patch_id": "modeling-anatomy-test",
|
||||
"base_revision": 0,
|
||||
"base_hash": "legacy-hash",
|
||||
"applied_at": "2026-07-13T00:00:00Z",
|
||||
"purpose": {"kind": "evolution"},
|
||||
"operations": [{"operation": "retire_node", "node_id": "old"}]
|
||||
},
|
||||
"statePatch": {"graphs": {}}
|
||||
}),
|
||||
None,
|
||||
|
|
@ -1258,7 +1230,7 @@ mod tests {
|
|||
None,
|
||||
);
|
||||
assert!(finding.item_error.as_deref().is_some_and(|error| {
|
||||
error.contains("repository anatomy") && error.contains("repoModelPatch")
|
||||
error.contains("repository anatomy") && error.contains("repoModelOperations")
|
||||
}));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -27,21 +27,21 @@ use crate::EpiphanyReorientReason;
|
|||
pub const ROLE_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.role_result.v3";
|
||||
pub const REORIENT_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.reorient_result.v0";
|
||||
pub const REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_SCHEMA_VERSION: &str =
|
||||
"epiphany.worker.repo_frontier_proposal_modeling_context.v0";
|
||||
"epiphany.worker.repo_frontier_proposal_modeling_context.v1";
|
||||
pub const REPO_FRONTIER_PROPOSAL_MODELING_CONTEXT_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_proposal_modeling_context.v0";
|
||||
"epiphany.repo_frontier_proposal_modeling_context.v1";
|
||||
pub const REPO_MODEL_CLAIM_REPAIR_CONTEXT_SCHEMA_VERSION: &str =
|
||||
"epiphany.worker.repo_model_claim_repair_context.v0";
|
||||
"epiphany.worker.repo_model_claim_repair_context.v1";
|
||||
pub const REPO_MODEL_CLAIM_REPAIR_CONTEXT_CONTRACT: &str =
|
||||
"epiphany.repo_model_claim_repair_context.v0";
|
||||
"epiphany.repo_model_claim_repair_context.v1";
|
||||
pub const REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION: &str =
|
||||
"epiphany.worker.repo_frontier_planning_context.v0";
|
||||
"epiphany.worker.repo_frontier_planning_context.v1";
|
||||
pub const REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_planning_context.v0";
|
||||
"epiphany.repo_frontier_planning_context.v1";
|
||||
pub const REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION: &str =
|
||||
"epiphany.worker.repo_frontier_research_context.v1";
|
||||
"epiphany.worker.repo_frontier_research_context.v2";
|
||||
pub const REPO_FRONTIER_RESEARCH_CONTEXT_CONTRACT: &str =
|
||||
"epiphany.repo_frontier_research_context.v1";
|
||||
"epiphany.repo_frontier_research_context.v2";
|
||||
pub const REPO_FRONTIER_PLAN_MIND_CONTEXT_SCHEMA_VERSION: &str =
|
||||
"epiphany.worker.repo_frontier_plan_mind_context.v0";
|
||||
pub const REPO_FRONTIER_PLAN_MIND_CONTEXT_CONTRACT: &str =
|
||||
|
|
@ -154,9 +154,8 @@ pub struct EpiphanyRoleWorkerLaunchDocument {
|
|||
pub struct RepoFrontierResearchContextProjection {
|
||||
pub schema_version: String,
|
||||
pub request_id: String,
|
||||
pub model_revision: u64,
|
||||
pub model_hash: String,
|
||||
pub admission_receipt_id: String,
|
||||
pub model_projection_digest: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
pub frontier_item_id: String,
|
||||
pub frontier_item_hash: String,
|
||||
pub source_scope: Vec<String>,
|
||||
|
|
@ -170,9 +169,8 @@ impl From<&crate::RepoFrontierResearchRequest> for RepoFrontierResearchContextPr
|
|||
Self {
|
||||
schema_version: REPO_FRONTIER_RESEARCH_CONTEXT_SCHEMA_VERSION.to_string(),
|
||||
request_id: request.request_id.clone(),
|
||||
model_revision: request.model_revision,
|
||||
model_hash: request.model_hash.clone(),
|
||||
admission_receipt_id: request.admission_receipt_id.clone(),
|
||||
model_projection_digest: request.model_projection_digest.clone(),
|
||||
model_source_documents: request.model_source_documents.clone(),
|
||||
frontier_item_id: request.frontier_item_id.clone(),
|
||||
frontier_item_hash: request.frontier_item_hash.clone(),
|
||||
source_scope: request.source_scope.clone(),
|
||||
|
|
@ -270,8 +268,8 @@ pub struct RepoFrontierProposalModelingContextProjection {
|
|||
#[serde(default)]
|
||||
pub public_source_refs: Vec<String>,
|
||||
pub private_state_included: bool,
|
||||
pub model_revision: u64,
|
||||
pub model_hash: String,
|
||||
pub model_projection_digest: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -286,10 +284,10 @@ pub struct RepoModelClaimRepairContextProjection {
|
|||
pub eyes_evidence_packet_sha256: String,
|
||||
pub source_result_id: String,
|
||||
pub source_job_id: String,
|
||||
pub original_admission_receipt_id: String,
|
||||
pub current_admission_receipt_id: String,
|
||||
pub model_revision: u64,
|
||||
pub model_hash: String,
|
||||
pub original_model_projection_digest: String,
|
||||
pub original_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
pub current_model_projection_digest: String,
|
||||
pub current_model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
pub target_claim_id: String,
|
||||
pub target_claim_sha256: String,
|
||||
pub runtime_id: String,
|
||||
|
|
@ -310,10 +308,10 @@ impl RepoModelClaimRepairContextProjection {
|
|||
eyes_evidence_packet_sha256: request.eyes_evidence_packet_sha256.clone(),
|
||||
source_result_id: request.source_result_id.clone(),
|
||||
source_job_id: request.source_job_id.clone(),
|
||||
original_admission_receipt_id: request.original_admission_receipt_id.clone(),
|
||||
current_admission_receipt_id: request.current_admission_receipt_id.clone(),
|
||||
model_revision: request.model_revision,
|
||||
model_hash: request.model_hash.clone(),
|
||||
original_model_projection_digest: request.original_model_projection_digest.clone(),
|
||||
original_model_source_documents: request.original_model_source_documents.clone(),
|
||||
current_model_projection_digest: request.current_model_projection_digest.clone(),
|
||||
current_model_source_documents: request.current_model_source_documents.clone(),
|
||||
target_claim_id: request.target_claim_id.clone(),
|
||||
target_claim_sha256: request.target_claim_sha256.clone(),
|
||||
runtime_id: request.runtime_id.clone(),
|
||||
|
|
@ -330,9 +328,8 @@ pub struct RepoFrontierPlanningContextProjection {
|
|||
pub schema_version: String,
|
||||
pub contract: String,
|
||||
pub request_id: String,
|
||||
pub model_revision: u64,
|
||||
pub model_hash: String,
|
||||
pub admission_receipt_id: String,
|
||||
pub model_projection_digest: String,
|
||||
pub model_source_documents: Vec<crate::EpiphanyMindDocumentVersion>,
|
||||
pub frontier_item_id: String,
|
||||
pub frontier_item_hash: String,
|
||||
pub selected_organ: String,
|
||||
|
|
@ -349,9 +346,8 @@ impl RepoFrontierPlanningContextProjection {
|
|||
schema_version: REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION.into(),
|
||||
contract: REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT.into(),
|
||||
request_id: request.request_id.clone(),
|
||||
model_revision: request.model_revision,
|
||||
model_hash: request.model_hash.clone(),
|
||||
admission_receipt_id: request.admission_receipt_id.clone(),
|
||||
model_projection_digest: request.model_projection_digest.clone(),
|
||||
model_source_documents: request.model_source_documents.clone(),
|
||||
frontier_item_id: request.frontier_item_id.clone(),
|
||||
frontier_item_hash: request.frontier_item_hash.clone(),
|
||||
selected_organ: request.selected_organ.clone(),
|
||||
|
|
@ -369,13 +365,13 @@ pub struct ImaginationConsiderationContextProjection {
|
|||
pub schema_version: String,
|
||||
pub contract: String,
|
||||
pub request: crate::ImaginationConsiderationRequest,
|
||||
pub model: crate::EpiphanyMemoryGraphSnapshot,
|
||||
pub model: crate::EpiphanyRepoModelView,
|
||||
}
|
||||
|
||||
impl ImaginationConsiderationContextProjection {
|
||||
pub(crate) fn new(
|
||||
request: &crate::ImaginationConsiderationRequest,
|
||||
model: &crate::EpiphanyMemoryGraphSnapshot,
|
||||
model: &crate::EpiphanyRepoModelView,
|
||||
) -> Self {
|
||||
Self {
|
||||
schema_version: IMAGINATION_CONSIDERATION_CONTEXT_SCHEMA_VERSION.into(),
|
||||
|
|
@ -392,13 +388,13 @@ pub struct AdmittedModelDirectionConsiderationContextProjection {
|
|||
pub schema_version: String,
|
||||
pub contract: String,
|
||||
pub request: crate::AdmittedModelDirectionConsiderationRequest,
|
||||
pub model: crate::EpiphanyMemoryGraphSnapshot,
|
||||
pub model: crate::EpiphanyRepoModelView,
|
||||
}
|
||||
|
||||
impl AdmittedModelDirectionConsiderationContextProjection {
|
||||
pub(crate) fn new(
|
||||
request: &crate::AdmittedModelDirectionConsiderationRequest,
|
||||
model: &crate::EpiphanyMemoryGraphSnapshot,
|
||||
model: &crate::EpiphanyRepoModelView,
|
||||
) -> Self {
|
||||
Self {
|
||||
schema_version: ADMITTED_MODEL_DIRECTION_CONSIDERATION_CONTEXT_SCHEMA_VERSION.into(),
|
||||
|
|
|
|||
|
|
@ -731,16 +731,20 @@ pub fn complete_worker_job_from_assistant_text(
|
|||
if let Some(parsed) = parsed.as_ref() {
|
||||
match (&launch_document, parsed) {
|
||||
(EpiphanyWorkerLaunchDocument::Role(document), WorkerResultIngress::Role(parsed)) => {
|
||||
let repo_frontier_verdict_modeling_authority =
|
||||
launch_request.repo_frontier_verdict_modeling_authority()?;
|
||||
let typed_result = role_worker_result_from_ingress(
|
||||
launch_request,
|
||||
&document.role_id,
|
||||
document.repository_body_observation_basis.as_ref(),
|
||||
document.proposal_modeling_context.as_ref(),
|
||||
document.frontier_planning_context.as_ref(),
|
||||
document.frontier_plan_mind_context.as_ref(),
|
||||
document.imagination_consideration_context.as_ref(),
|
||||
document
|
||||
.admitted_model_direction_consideration_context
|
||||
.as_ref(),
|
||||
repo_frontier_verdict_modeling_authority.as_ref(),
|
||||
&completed_at,
|
||||
&result_id,
|
||||
&decision_context.context_id,
|
||||
|
|
@ -812,10 +816,8 @@ pub fn fail_model_backed_worker_job(
|
|||
summary: String,
|
||||
next_safe_move: String,
|
||||
) -> Result<epiphany_core::EpiphanyRuntimeJobResult> {
|
||||
let context = epiphany_core::seal_model_decision_context(
|
||||
store_path.as_ref(),
|
||||
terminal_request_id,
|
||||
)?;
|
||||
let context =
|
||||
epiphany_core::seal_model_decision_context(store_path.as_ref(), terminal_request_id)?;
|
||||
complete_runtime_job(
|
||||
store_path,
|
||||
RuntimeSpineJobResultOptions {
|
||||
|
|
@ -1474,7 +1476,7 @@ fn worker_instructions(
|
|||
launch_request: &EpiphanyRuntimeWorkerLaunchRequest,
|
||||
launch_document: &EpiphanyWorkerLaunchDocument,
|
||||
) -> String {
|
||||
let output_contract = worker_output_contract_text(launch_document);
|
||||
let output_contract = worker_output_contract_text(launch_request, launch_document);
|
||||
let dynamic_context = launch_document
|
||||
.dynamic_prompt_context()
|
||||
.map(|context| format!("\n\n{context}"))
|
||||
|
|
@ -1557,17 +1559,25 @@ fn role_result_id_for_launch_role(
|
|||
}
|
||||
}
|
||||
|
||||
fn worker_output_contract_text(document: &EpiphanyWorkerLaunchDocument) -> &'static str {
|
||||
fn worker_output_contract_text(
|
||||
launch_request: &EpiphanyRuntimeWorkerLaunchRequest,
|
||||
document: &EpiphanyWorkerLaunchDocument,
|
||||
) -> &'static str {
|
||||
match document {
|
||||
EpiphanyWorkerLaunchDocument::Role(_)
|
||||
if launch_request.repo_frontier_modeling_request_id.is_some() =>
|
||||
{
|
||||
"Required verdict-bound Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, frontierVerdictGap. Emit only the semantic gap explaining the allowed resolved or blocked transition. Runtime binds the exact request, keyed RepoModel basis, frontier item and disposition, evidence identities, timestamps, proposal, strong reads, writes, and receipts. Do not emit repoModelOperations, repositoryBodyObservationBasis, request ids, statePatch, selfPatch, commands, release, or deployment cargo."
|
||||
}
|
||||
EpiphanyWorkerLaunchDocument::Role(document)
|
||||
if document.frontier_plan_mind_context.is_some() =>
|
||||
{
|
||||
"Required Mind admission-review fields: roleId=mindAdmissionReview, verdict, summary, nextSafeMove, filesInspected, frontierPlanMindRequestId, frontierPlanMindDecision. Echo every causal identifier from the typed context exactly and choose adopt, refuse, or hold with a concrete rationale. This bounded procedure serves Mind; it is not an embodied lane and emits no patches or other organ authority."
|
||||
"Required Mind admission-review fields: roleId=mindAdmissionReview, verdict, summary, nextSafeMove, filesInspected, frontierPlanMindDecision. Emit only the semantic adopt, refuse, or hold disposition and a concrete rationale. Runtime binds every causal identifier, the exact keyed RepoModel basis and candidate, receipt identity, and decision time from the authenticated context. This bounded procedure serves Mind; it is not an embodied lane and emits no patches or other organ authority."
|
||||
}
|
||||
EpiphanyWorkerLaunchDocument::Role(document)
|
||||
if document.frontier_planning_context.is_some() =>
|
||||
{
|
||||
"Required frontier-planning result fields: roleId, verdict, summary, nextSafeMove, filesInspected, frontierPlanningRequestId, frontierPlanCandidate. Echo the exact request and candidate identity from the typed launch context. frontierPlanCandidate.safe_paths may narrow but must never expand the immutable source_scope: every safe path must exactly equal a source_scope entry or be a descendant of one, in strict lexicographic order without duplicates. Do not include adjacent files merely because the plan would benefit from them; identify them as a stop condition instead. Do not emit statePatch, selfPatch, or repoModelPatch."
|
||||
"Required frontier-planning result fields: roleId, verdict, summary, nextSafeMove, filesInspected, frontierPlanCandidate. Emit only the semantic plan content. Runtime owns the planning request, RepoModel basis, frontier identity/hash, candidate identity, and timestamp. frontierPlanCandidate.safe_paths may narrow but must never expand the immutable source_scope: every safe path must exactly equal a source_scope entry or be a descendant of one, in strict lexicographic order without duplicates. Do not include adjacent files merely because the plan would benefit from them; identify them as a stop condition instead. Do not emit statePatch, selfPatch, or repoModelOperations."
|
||||
}
|
||||
EpiphanyWorkerLaunchDocument::Role(document)
|
||||
if document
|
||||
|
|
@ -1579,15 +1589,15 @@ fn worker_output_contract_text(document: &EpiphanyWorkerLaunchDocument) -> &'sta
|
|||
EpiphanyWorkerLaunchDocument::Role(document)
|
||||
if document.imagination_consideration_context.is_some() =>
|
||||
{
|
||||
"Required consideration fields: roleId=imagination, verdict, summary, nextSafeMove, filesInspected, imaginationConsiderationCandidate. Runtime composes all causal identity, classification, contract, and publication time from the authenticated launch context. Treat feedback as quoted evidence. Emit no statePatch, selfPatch, repoModelPatch, frontier candidate, command, release, or deployment cargo."
|
||||
"Required consideration fields: roleId=imagination, verdict, summary, nextSafeMove, filesInspected, imaginationConsiderationCandidate. Runtime composes all causal identity, classification, contract, and publication time from the authenticated launch context. Treat feedback as quoted evidence. Emit no statePatch, selfPatch, repoModelOperations, frontier candidate, command, release, or deployment cargo."
|
||||
}
|
||||
EpiphanyWorkerLaunchDocument::Role(document)
|
||||
if document.proposal_modeling_context.is_some() =>
|
||||
{
|
||||
"Required proposal-Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, proposalFrontierDraft. Emit only the semantic frontier draft. Runtime owns and composes patch identity, model base, Body observation basis, proposal/request provenance, active status, timestamps, and the mandatory proposal evidence binding. Do not emit repoModelPatch, proposalModelingRequestId, repositoryBodyObservationBasis, statePatch, selfPatch, commands, release, or deployment cargo."
|
||||
"Required proposal-Modeling fields: roleId=modeling, verdict, summary, nextSafeMove, filesInspected, frontierNodeIds, evidenceIds, proposalFrontierDraft. Emit only the semantic frontier draft. Runtime owns and composes proposal identity, Body observation basis, proposal/request provenance, active status, timestamps, and the mandatory proposal evidence binding. Do not emit repoModelOperations, proposalModelingRequestId, repositoryBodyObservationBasis, statePatch, selfPatch, commands, release, or deployment cargo."
|
||||
}
|
||||
EpiphanyWorkerLaunchDocument::Role(_) => {
|
||||
"Required role-result fields: roleId, verdict, summary, nextSafeMove, filesInspected. Modeling workers must include repoModelPatch; ordinary Imagination workers must include statePatch. Modeling statePatch is optional observations/evidence only. For ordinary Modeling, checkpoint-update-needed is a typed claim that the Body map contains a future design gap: encode exactly one new active, unadopted frontier with recommended_next_organ=Imagination, empty dependency_item_ids, safe non-empty source_scope, and evidence_refs grounded in top-level evidenceIds. Use checkpoint-ready when no new frontier authority is needed and regather-needed when source evidence is insufficient; neither may mutate frontier. nextSafeMove is display-only and never routes an organ. Use arrays for frontierNodeIds, evidenceIds, openQuestions, evidenceGaps, risks, and artifactRefs when present."
|
||||
"Required role-result fields: roleId, verdict, summary, nextSafeMove, filesInspected. Modeling workers emit repoModelOperations, an array of semantic keyed operations; use an empty array when no RepoModel mutation is proposed. Never emit proposal ids, model revisions or hashes, timestamps, strong reads, writes, or receipts. Ordinary Imagination workers must include statePatch. Modeling statePatch is optional observations/evidence only. For ordinary Modeling, checkpoint-update-needed is a typed claim that the Body map contains a future design gap: encode exactly one PutFrontier operation with a new active, unadopted frontier, recommended_next_organ=Imagination, empty dependency_item_ids, safe non-empty source_scope, and evidence_refs grounded in top-level evidenceIds. Use checkpoint-ready when no new frontier authority is needed and regather-needed when source evidence is insufficient; neither may mutate frontier. nextSafeMove is display-only and never routes an organ. Use arrays for frontierNodeIds, evidenceIds, openQuestions, evidenceGaps, risks, and artifactRefs when present."
|
||||
}
|
||||
EpiphanyWorkerLaunchDocument::Reorient(_) => {
|
||||
"Required reorient-result fields: mode, summary, nextSafeMove. Include checkpointStillValid, filesInspected, frontierNodeIds, evidenceIds, openQuestions, and continuityRisks when present."
|
||||
|
|
@ -1612,20 +1622,16 @@ struct RoleWorkerResultIngress {
|
|||
evidence_gaps: Vec<String>,
|
||||
risks: Vec<String>,
|
||||
state_patch: Option<epiphany_core::EpiphanyRoleStatePatchDocument>,
|
||||
repo_model_patch: Option<epiphany_core::RepoModelPatch>,
|
||||
repo_model_operations: Vec<epiphany_core::EpiphanyRepoModelMutationOperation>,
|
||||
frontier_verdict_gap: Option<String>,
|
||||
self_patch: Option<epiphany_core::AgentSelfPatch>,
|
||||
verification_request_id: Option<String>,
|
||||
frontier_route_id: Option<String>,
|
||||
repo_frontier_modeling_request_id: Option<String>,
|
||||
proposal_modeling_request_id: Option<String>,
|
||||
claim_repair_request_id: Option<String>,
|
||||
frontier_planning_request_id: Option<String>,
|
||||
frontier_plan_candidate: Option<RepoFrontierPlanCandidateIngress>,
|
||||
frontier_plan_mind_decision: Option<RepoFrontierPlanMindDecisionIngress>,
|
||||
imagination_consideration_candidate: Option<ImaginationConsiderationCandidateIngress>,
|
||||
admitted_model_direction_consideration_result:
|
||||
Option<AdmittedModelDirectionConsiderationResultIngress>,
|
||||
repository_body_observation_basis: Option<epiphany_core::RepositoryBodyObservationBasis>,
|
||||
proposal_frontier_draft: Option<ProposalFrontierDraftIngress>,
|
||||
}
|
||||
|
||||
|
|
@ -1647,17 +1653,11 @@ struct ProposalFrontierDraftIngress {
|
|||
struct RepoFrontierPlanMindDecisionIngress {
|
||||
decision: Option<epiphany_core::RepoFrontierPlanDecision>,
|
||||
rationale: String,
|
||||
decided_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
struct RepoFrontierPlanCandidateIngress {
|
||||
planning_request_id: String,
|
||||
model_revision: u64,
|
||||
model_hash: String,
|
||||
frontier_item_id: String,
|
||||
frontier_item_hash: String,
|
||||
safe_paths: Vec<String>,
|
||||
action: String,
|
||||
command: String,
|
||||
|
|
@ -1665,7 +1665,6 @@ struct RepoFrontierPlanCandidateIngress {
|
|||
stop_conditions: Vec<String>,
|
||||
rollback_steps: Vec<String>,
|
||||
commit_message: String,
|
||||
proposed_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, serde::Deserialize)]
|
||||
|
|
@ -1777,6 +1776,7 @@ fn role_worker_result_from_ingress(
|
|||
proposal_modeling_context: Option<
|
||||
&epiphany_core::RepoFrontierProposalModelingContextProjection,
|
||||
>,
|
||||
frontier_planning_context: Option<&epiphany_core::RepoFrontierPlanningContextProjection>,
|
||||
frontier_plan_mind_context: Option<&epiphany_core::RepoFrontierPlanMindContextProjection>,
|
||||
imagination_consideration_context: Option<
|
||||
&epiphany_core::ImaginationConsiderationContextProjection,
|
||||
|
|
@ -1784,6 +1784,9 @@ fn role_worker_result_from_ingress(
|
|||
admitted_model_direction_consideration_context: Option<
|
||||
&epiphany_core::AdmittedModelDirectionConsiderationContextProjection,
|
||||
>,
|
||||
repo_frontier_verdict_modeling_authority: Option<
|
||||
&epiphany_core::RepoFrontierVerdictModelingLaunchAuthority,
|
||||
>,
|
||||
completed_at: &str,
|
||||
result_id: &str,
|
||||
decision_context_id: &str,
|
||||
|
|
@ -1793,69 +1796,157 @@ fn role_worker_result_from_ingress(
|
|||
) -> EpiphanyRuntimeRoleWorkerResult {
|
||||
let (state_patch_msgpack, state_patch_error) =
|
||||
encode_optional_document(&result.state_patch, "statePatch");
|
||||
let (repo_model_patch_msgpack, repo_model_patch_error) = if let Some(context) =
|
||||
proposal_modeling_context
|
||||
{
|
||||
match result.proposal_frontier_draft.as_ref() {
|
||||
Some(draft) => {
|
||||
let mut target_claim_ids = clean_string_vec(&draft.target_claim_ids);
|
||||
target_claim_ids.sort();
|
||||
target_claim_ids.dedup();
|
||||
let mut source_scope = clean_string_vec(&draft.source_scope);
|
||||
source_scope.sort();
|
||||
source_scope.dedup();
|
||||
let mut dependency_item_ids = clean_string_vec(&draft.dependency_item_ids);
|
||||
dependency_item_ids.sort();
|
||||
dependency_item_ids.dedup();
|
||||
let mut evidence_refs = clean_string_vec(&draft.evidence_refs);
|
||||
evidence_refs.push(context.proposal_id.clone());
|
||||
evidence_refs.sort();
|
||||
evidence_refs.dedup();
|
||||
let frontier_id = format!(
|
||||
"frontier-proposal-{:x}",
|
||||
sha2::Sha256::digest(context.request_id.as_bytes())
|
||||
);
|
||||
let patch = epiphany_core::RepoModelPatch {
|
||||
patch_id: format!("repo-model-patch-proposal-{}", launch_request.job_id),
|
||||
base_revision: context.model_revision,
|
||||
base_hash: context.model_hash.clone(),
|
||||
applied_at: completed_at.to_string(),
|
||||
purpose: epiphany_core::RepoModelPatchPurpose::Evolution,
|
||||
operations: vec![epiphany_core::RepoModelPatchOperation::UpsertFrontier {
|
||||
item: epiphany_core::RepoFrontierItem {
|
||||
id: frontier_id,
|
||||
migration_body: draft.migration_body.trim().to_string(),
|
||||
question: draft.question.trim().to_string(),
|
||||
gap: draft.gap.trim().to_string(),
|
||||
target_claim_ids,
|
||||
source_scope,
|
||||
recommended_next_organ: draft.recommended_next_organ.trim().to_string(),
|
||||
adopted_plan: None,
|
||||
dependency_item_ids,
|
||||
status: epiphany_core::RepoFrontierStatus::Active,
|
||||
evidence_refs,
|
||||
public_source_refs: if draft.recommended_next_organ.trim() == "Eyes" {
|
||||
context.public_source_refs.clone()
|
||||
} else {
|
||||
Vec::new()
|
||||
let (repo_model_mutation_proposal_msgpack, repo_model_mutation_proposal_error) =
|
||||
if let Some(context) = proposal_modeling_context {
|
||||
match result.proposal_frontier_draft.as_ref() {
|
||||
Some(draft) => {
|
||||
let mut target_claim_ids = clean_string_vec(&draft.target_claim_ids);
|
||||
target_claim_ids.sort();
|
||||
target_claim_ids.dedup();
|
||||
let mut source_scope = clean_string_vec(&draft.source_scope);
|
||||
source_scope.sort();
|
||||
source_scope.dedup();
|
||||
let mut dependency_item_ids = clean_string_vec(&draft.dependency_item_ids);
|
||||
dependency_item_ids.sort();
|
||||
dependency_item_ids.dedup();
|
||||
let mut evidence_refs = clean_string_vec(&draft.evidence_refs);
|
||||
evidence_refs.push(context.proposal_id.clone());
|
||||
evidence_refs.sort();
|
||||
evidence_refs.dedup();
|
||||
let frontier_id = format!(
|
||||
"frontier-proposal-{:x}",
|
||||
sha2::Sha256::digest(context.request_id.as_bytes())
|
||||
);
|
||||
let proposal = epiphany_core::EpiphanyRepoModelMutationProposal::new(
|
||||
format!("repo-model-mutation-proposal-{}", launch_request.job_id),
|
||||
vec![
|
||||
epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier {
|
||||
item: epiphany_core::RepoFrontierItem {
|
||||
id: frontier_id,
|
||||
migration_body: draft.migration_body.trim().to_string(),
|
||||
question: draft.question.trim().to_string(),
|
||||
gap: draft.gap.trim().to_string(),
|
||||
target_claim_ids,
|
||||
source_scope,
|
||||
recommended_next_organ: draft
|
||||
.recommended_next_organ
|
||||
.trim()
|
||||
.to_string(),
|
||||
adopted_plan: None,
|
||||
dependency_item_ids,
|
||||
status: epiphany_core::RepoFrontierStatus::Active,
|
||||
evidence_refs,
|
||||
public_source_refs: if draft.recommended_next_organ.trim()
|
||||
== "Eyes"
|
||||
{
|
||||
context.public_source_refs.clone()
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
created_at: Some(completed_at.to_string()),
|
||||
updated_at: Some(completed_at.to_string()),
|
||||
retired_at: None,
|
||||
superseded_by: None,
|
||||
},
|
||||
},
|
||||
created_at: Some(completed_at.to_string()),
|
||||
updated_at: Some(completed_at.to_string()),
|
||||
retired_at: None,
|
||||
superseded_by: None,
|
||||
},
|
||||
}],
|
||||
};
|
||||
encode_optional_document(&Some(patch), "proposalFrontierDraft")
|
||||
],
|
||||
);
|
||||
match proposal {
|
||||
Ok(proposal) => {
|
||||
encode_optional_document(&Some(proposal), "proposalFrontierDraft")
|
||||
}
|
||||
Err(error) => (None, Some(format!("proposalFrontierDraft: {error}"))),
|
||||
}
|
||||
}
|
||||
None => (
|
||||
None,
|
||||
Some("proposalFrontierDraft: missing semantic draft".to_string()),
|
||||
),
|
||||
}
|
||||
None => (
|
||||
} else if let Some(authority) = repo_frontier_verdict_modeling_authority {
|
||||
match clean_optional_string(result.frontier_verdict_gap.as_deref()) {
|
||||
Some(gap) => {
|
||||
let mut item = authority.frontier_item.clone();
|
||||
item.gap = gap;
|
||||
item.status = match authority.request.allowed_disposition {
|
||||
epiphany_core::RepoFrontierVerdictDisposition::Resolved => {
|
||||
epiphany_core::RepoFrontierStatus::Resolved
|
||||
}
|
||||
epiphany_core::RepoFrontierVerdictDisposition::Blocked => {
|
||||
epiphany_core::RepoFrontierStatus::Blocked
|
||||
}
|
||||
};
|
||||
item.updated_at = Some(completed_at.to_string());
|
||||
item.evidence_refs
|
||||
.push(authority.request.verification_request_id.clone());
|
||||
item.evidence_refs
|
||||
.push(authority.request.soul_verdict_receipt_id.clone());
|
||||
item.evidence_refs.sort();
|
||||
item.evidence_refs.dedup();
|
||||
match epiphany_core::EpiphanyRepoModelMutationProposal::new(
|
||||
format!("repo-model-mutation-proposal-{}", launch_request.job_id),
|
||||
vec![
|
||||
epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier { item },
|
||||
],
|
||||
) {
|
||||
Ok(proposal) => {
|
||||
encode_optional_document(&Some(proposal), "frontierVerdictGap")
|
||||
}
|
||||
Err(error) => (None, Some(format!("frontierVerdictGap: {error}"))),
|
||||
}
|
||||
}
|
||||
None => (
|
||||
None,
|
||||
Some("frontierVerdictGap: missing semantic verdict finding".to_string()),
|
||||
),
|
||||
}
|
||||
} else if role_id.eq_ignore_ascii_case("modeling")
|
||||
&& !result.repo_model_operations.is_empty()
|
||||
{
|
||||
let mut operations = result.repo_model_operations.clone();
|
||||
for operation in &mut operations {
|
||||
match operation {
|
||||
epiphany_core::EpiphanyRepoModelMutationOperation::PutNode { node } => {
|
||||
node.created_at = node
|
||||
.created_at
|
||||
.as_ref()
|
||||
.map(|_| completed_at.to_string())
|
||||
.or_else(|| Some(completed_at.to_string()));
|
||||
node.updated_at = Some(completed_at.to_string());
|
||||
}
|
||||
epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier { item } => {
|
||||
item.created_at = item
|
||||
.created_at
|
||||
.as_ref()
|
||||
.map(|_| completed_at.to_string())
|
||||
.or_else(|| Some(completed_at.to_string()));
|
||||
item.updated_at = Some(completed_at.to_string());
|
||||
item.retired_at = None;
|
||||
item.superseded_by = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match epiphany_core::EpiphanyRepoModelMutationProposal::new(
|
||||
format!("repo-model-mutation-proposal-{}", launch_request.job_id),
|
||||
operations,
|
||||
) {
|
||||
Ok(proposal) => encode_optional_document(&Some(proposal), "repoModelOperations"),
|
||||
Err(error) => (None, Some(format!("repoModelOperations: {error}"))),
|
||||
}
|
||||
} else if !role_id.eq_ignore_ascii_case("modeling")
|
||||
&& !result.repo_model_operations.is_empty()
|
||||
{
|
||||
(
|
||||
None,
|
||||
Some("proposalFrontierDraft: missing semantic draft".to_string()),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
encode_optional_document(&result.repo_model_patch, "repoModelPatch")
|
||||
};
|
||||
Some(
|
||||
"repoModelOperations: only Modeling may propose RepoModel mutations"
|
||||
.to_string(),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let (self_patch_msgpack, self_patch_error) =
|
||||
encode_optional_document(&result.self_patch, "selfPatch");
|
||||
let (frontier_plan_candidate_msgpack, frontier_plan_candidate_error) = if let Some(ingress) =
|
||||
|
|
@ -1867,11 +1958,21 @@ fn role_worker_result_from_ingress(
|
|||
let mut candidate = epiphany_core::RepoFrontierPlanCandidate {
|
||||
schema_version: epiphany_core::REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION.to_string(),
|
||||
candidate_id: String::new(),
|
||||
planning_request_id: ingress.planning_request_id.clone(),
|
||||
model_revision: ingress.model_revision,
|
||||
model_hash: ingress.model_hash.clone(),
|
||||
frontier_item_id: ingress.frontier_item_id.clone(),
|
||||
frontier_item_hash: ingress.frontier_item_hash.clone(),
|
||||
planning_request_id: frontier_planning_context
|
||||
.map(|context| context.request_id.clone())
|
||||
.unwrap_or_default(),
|
||||
model_projection_digest: frontier_planning_context
|
||||
.map(|context| context.model_projection_digest.clone())
|
||||
.unwrap_or_default(),
|
||||
model_source_documents: frontier_planning_context
|
||||
.map(|context| context.model_source_documents.clone())
|
||||
.unwrap_or_default(),
|
||||
frontier_item_id: frontier_planning_context
|
||||
.map(|context| context.frontier_item_id.clone())
|
||||
.unwrap_or_default(),
|
||||
frontier_item_hash: frontier_planning_context
|
||||
.map(|context| context.frontier_item_hash.clone())
|
||||
.unwrap_or_default(),
|
||||
safe_paths,
|
||||
action: ingress.action.trim().to_string(),
|
||||
command: ingress.command.trim().to_string(),
|
||||
|
|
@ -1879,7 +1980,7 @@ fn role_worker_result_from_ingress(
|
|||
stop_conditions: clean_string_vec(&ingress.stop_conditions),
|
||||
rollback_steps: clean_string_vec(&ingress.rollback_steps),
|
||||
commit_message: ingress.commit_message.trim().to_string(),
|
||||
proposed_at: ingress.proposed_at.trim().to_string(),
|
||||
proposed_at: completed_at.to_string(),
|
||||
contract: epiphany_core::REPO_FRONTIER_PLANNING_CONTRACT.to_string(),
|
||||
};
|
||||
match epiphany_core::canonical_repo_frontier_plan_candidate_id(&candidate) {
|
||||
|
|
@ -1905,7 +2006,7 @@ fn role_worker_result_from_ingress(
|
|||
candidate_sha256: context.request.candidate_sha256.clone(),
|
||||
decision,
|
||||
rationale: ingress.rationale.trim().into(),
|
||||
decided_at: ingress.decided_at.trim().into(),
|
||||
decided_at: completed_at.into(),
|
||||
}),
|
||||
"frontierPlanMindDecision",
|
||||
),
|
||||
|
|
@ -1947,8 +2048,14 @@ fn role_worker_result_from_ingress(
|
|||
source_room_id: context.request.source_room_id.clone(),
|
||||
source_visibility: context.request.source_visibility.clone(),
|
||||
data_classification: context.request.data_classification.clone(),
|
||||
model_revision: context.request.model_revision,
|
||||
model_hash: context.request.model_hash.clone(),
|
||||
model_projection_digest: context
|
||||
.request
|
||||
.model_projection_digest
|
||||
.clone(),
|
||||
model_source_documents: context
|
||||
.request
|
||||
.model_source_documents
|
||||
.clone(),
|
||||
disposition,
|
||||
title: ingress.title.trim().into(),
|
||||
summary: ingress.summary.trim().into(),
|
||||
|
|
@ -1998,9 +2105,8 @@ fn role_worker_result_from_ingress(
|
|||
request_id: context.request.request_id.clone(),
|
||||
runtime_id: context.request.runtime_id.clone(),
|
||||
thread_id: context.request.thread_id.clone(),
|
||||
model_revision: context.request.model_revision,
|
||||
model_hash: context.request.model_hash.clone(),
|
||||
model_admission_receipt_id: context.request.model_admission_receipt_id.clone(),
|
||||
model_projection_digest: context.request.model_projection_digest.clone(),
|
||||
model_source_documents: context.request.model_source_documents.clone(),
|
||||
disposition,
|
||||
summary: ingress.summary.trim().into(),
|
||||
option_drafts: ingress.option_drafts.clone(),
|
||||
|
|
@ -2030,10 +2136,10 @@ fn role_worker_result_from_ingress(
|
|||
};
|
||||
EpiphanyRuntimeRoleWorkerResult {
|
||||
schema_version: epiphany_core::RUNTIME_ROLE_WORKER_RESULT_SCHEMA_VERSION.to_string(),
|
||||
repository_body_observation_basis: proposal_modeling_context
|
||||
.and(repository_body_observation_basis)
|
||||
.cloned()
|
||||
.or_else(|| result.repository_body_observation_basis.clone()),
|
||||
repository_body_observation_basis: role_id
|
||||
.eq_ignore_ascii_case("modeling")
|
||||
.then(|| repository_body_observation_basis.cloned())
|
||||
.flatten(),
|
||||
result_id: result_id.to_string(),
|
||||
job_id: launch_request.job_id.clone(),
|
||||
role_id: clean_optional_string(result.role_id.as_deref())
|
||||
|
|
@ -2068,7 +2174,7 @@ fn role_worker_result_from_ingress(
|
|||
item_error: merge_optional_errors(
|
||||
merge_optional_errors(
|
||||
merge_optional_errors(state_patch_error, self_patch_error),
|
||||
repo_model_patch_error,
|
||||
repo_model_mutation_proposal_error,
|
||||
),
|
||||
merge_optional_errors(
|
||||
frontier_plan_candidate_error,
|
||||
|
|
@ -2082,19 +2188,13 @@ fn role_worker_result_from_ingress(
|
|||
),
|
||||
),
|
||||
metadata: std::collections::BTreeMap::new(),
|
||||
repo_model_patch_msgpack,
|
||||
repo_model_mutation_proposal_msgpack,
|
||||
verification_request_id: clean_optional_string(result.verification_request_id.as_deref()),
|
||||
frontier_route_id: clean_optional_string(result.frontier_route_id.as_deref()),
|
||||
repo_frontier_modeling_request_id: clean_optional_string(
|
||||
result.repo_frontier_modeling_request_id.as_deref(),
|
||||
),
|
||||
proposal_modeling_request_id: proposal_modeling_context
|
||||
.map(|context| context.request_id.clone())
|
||||
.or_else(|| clean_optional_string(result.proposal_modeling_request_id.as_deref())),
|
||||
claim_repair_request_id: clean_optional_string(result.claim_repair_request_id.as_deref()),
|
||||
frontier_planning_request_id: clean_optional_string(
|
||||
result.frontier_planning_request_id.as_deref(),
|
||||
),
|
||||
repo_frontier_modeling_request_id: launch_request.repo_frontier_modeling_request_id.clone(),
|
||||
proposal_modeling_request_id: launch_request.proposal_modeling_request_id.clone(),
|
||||
claim_repair_request_id: launch_request.claim_repair_request_id.clone(),
|
||||
frontier_planning_request_id: launch_request.frontier_planning_request_id.clone(),
|
||||
frontier_plan_candidate_msgpack,
|
||||
frontier_plan_mind_request_id: frontier_plan_mind_context
|
||||
.map(|context| context.request.request_id.clone()),
|
||||
|
|
@ -2152,7 +2252,7 @@ pub fn failed_frontier_planning_role_result(
|
|||
self_patch_msgpack: None,
|
||||
item_error: Some(error.trim().to_string()),
|
||||
metadata: std::collections::BTreeMap::new(),
|
||||
repo_model_patch_msgpack: None,
|
||||
repo_model_mutation_proposal_msgpack: None,
|
||||
verification_request_id: None,
|
||||
frontier_route_id: None,
|
||||
repo_frontier_modeling_request_id: None,
|
||||
|
|
@ -2393,7 +2493,7 @@ mod tests {
|
|||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn modeling_ingress_parses_camel_case_repository_body_basis() -> Result<()> {
|
||||
fn model_authored_body_basis_has_no_ingress_authority() -> Result<()> {
|
||||
let parsed = parse_assistant_json::<RoleWorkerResultIngress>(
|
||||
r#"{
|
||||
"roleId":"modeling","verdict":"checkpoint-ready","summary":"mapped",
|
||||
|
|
@ -2407,12 +2507,8 @@ mod tests {
|
|||
}
|
||||
}"#,
|
||||
)?;
|
||||
let basis = parsed
|
||||
.repository_body_observation_basis
|
||||
.expect("typed Body basis");
|
||||
assert_eq!(basis.workspace_id, "workspace-1");
|
||||
assert_eq!(basis.generation, 1);
|
||||
assert_eq!(basis.manifest_root_sha256, "manifest-root");
|
||||
assert_eq!(parsed.role_id.as_deref(), Some("modeling"));
|
||||
assert!(parsed.repo_model_operations.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -2424,7 +2520,7 @@ mod tests {
|
|||
"nextSafeMove":"review","filesInspected":[],"frontierNodeIds":null,
|
||||
"evidenceIds":[],"artifactRefs":null,"openQuestions":null,
|
||||
"evidenceGaps":["missing"],"risks":null,"statePatch":null,
|
||||
"repoModelPatch":null,"selfPatch":null
|
||||
"selfPatch":null
|
||||
}"#,
|
||||
)?;
|
||||
|
||||
|
|
@ -2597,8 +2693,8 @@ mod tests {
|
|||
.into(),
|
||||
],
|
||||
private_state_included: false,
|
||||
model_revision: 41,
|
||||
model_hash: "model-hash-41".into(),
|
||||
model_projection_digest: "model-projection-41".into(),
|
||||
model_source_documents: Vec::new(),
|
||||
};
|
||||
let ingress = RoleWorkerResultIngress {
|
||||
role_id: Some("modeling".into()),
|
||||
|
|
@ -2629,6 +2725,8 @@ mod tests {
|
|||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
"2026-08-11T08:00:02Z",
|
||||
"result-proposal-job-1",
|
||||
"decision-context-test",
|
||||
|
|
@ -2642,19 +2740,19 @@ mod tests {
|
|||
Some("proposal-request-1")
|
||||
);
|
||||
assert!(result.evidence_ids.contains(&"proposal-1".to_string()));
|
||||
let patch: epiphany_core::RepoModelPatch = rmp_serde::from_slice(
|
||||
let proposal: epiphany_core::EpiphanyRepoModelMutationProposal = rmp_serde::from_slice(
|
||||
result
|
||||
.repo_model_patch_msgpack
|
||||
.repo_model_mutation_proposal_msgpack
|
||||
.as_deref()
|
||||
.expect("runtime-composed patch"),
|
||||
.expect("runtime-composed proposal"),
|
||||
)?;
|
||||
assert_eq!(patch.base_revision, 41);
|
||||
assert_eq!(patch.base_hash, "model-hash-41");
|
||||
assert_eq!(
|
||||
patch.purpose,
|
||||
epiphany_core::RepoModelPatchPurpose::Evolution
|
||||
proposal.proposal_id,
|
||||
"repo-model-mutation-proposal-proposal-job-1"
|
||||
);
|
||||
let epiphany_core::RepoModelPatchOperation::UpsertFrontier { item } = &patch.operations[0]
|
||||
let operations = proposal.operations()?;
|
||||
let epiphany_core::EpiphanyRepoModelMutationOperation::PutFrontier { item } =
|
||||
&operations[0]
|
||||
else {
|
||||
panic!("proposal draft must compose one frontier upsert");
|
||||
};
|
||||
|
|
@ -2689,8 +2787,8 @@ mod tests {
|
|||
evidence_refs: vec!["git:source".into()],
|
||||
public_source_refs: Vec::new(),
|
||||
private_state_included: false,
|
||||
model_revision: 41,
|
||||
model_hash: "model-hash-41".into(),
|
||||
model_projection_digest: "model-projection-41".into(),
|
||||
model_source_documents: Vec::new(),
|
||||
};
|
||||
let document =
|
||||
EpiphanyWorkerLaunchDocument::Role(epiphany_core::EpiphanyRoleWorkerLaunchDocument {
|
||||
|
|
@ -2811,6 +2909,8 @@ mod tests {
|
|||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
"2026-07-15T10:00:00Z",
|
||||
"verification-result-1",
|
||||
"decision-context-test",
|
||||
|
|
@ -2841,21 +2941,14 @@ mod tests {
|
|||
"verdict":"draft-ready",
|
||||
"summary":"bounded plan",
|
||||
"nextSafeMove":"Mind admission",
|
||||
"frontierPlanningRequestId":"planning-request-1",
|
||||
"frontierPlanCandidate":{
|
||||
"planning_request_id":"planning-request-1",
|
||||
"model_revision":7,
|
||||
"model_hash":"model-hash",
|
||||
"frontier_item_id":"frontier-1",
|
||||
"frontier_item_hash":"frontier-hash",
|
||||
"safe_paths":["tests","src","src"],
|
||||
"action":"Implement the bounded cut.",
|
||||
"command":"cargo test --lib",
|
||||
"checks":["focused test passes"],
|
||||
"stop_conditions":["scope changes"],
|
||||
"rollback_steps":["revert commit"],
|
||||
"commit_message":"Implement bounded cut",
|
||||
"proposed_at":"2026-07-15T10:00:00Z"
|
||||
"commit_message":"Implement bounded cut"
|
||||
}
|
||||
}"#,
|
||||
)?;
|
||||
|
|
@ -2885,11 +2978,27 @@ mod tests {
|
|||
repo_frontier_research_request_id: None,
|
||||
repo_frontier_verdict_modeling_authority_msgpack: None,
|
||||
};
|
||||
let planning_context = epiphany_core::RepoFrontierPlanningContextProjection {
|
||||
schema_version: epiphany_core::REPO_FRONTIER_PLANNING_CONTEXT_SCHEMA_VERSION.into(),
|
||||
contract: epiphany_core::REPO_FRONTIER_PLANNING_CONTEXT_CONTRACT.into(),
|
||||
request_id: "planning-request-1".into(),
|
||||
model_projection_digest: "model-projection-7".into(),
|
||||
model_source_documents: Vec::new(),
|
||||
frontier_item_id: "frontier-1".into(),
|
||||
frontier_item_hash: "frontier-hash".into(),
|
||||
selected_organ: "Imagination".into(),
|
||||
source_scope: vec!["src".into(), "tests".into()],
|
||||
requested_at: "2026-07-15T09:59:00Z".into(),
|
||||
runtime_id: "runtime-1".into(),
|
||||
thread_id: "thread-1".into(),
|
||||
};
|
||||
let result = role_worker_result_from_ingress(
|
||||
&launch,
|
||||
"imagination",
|
||||
None,
|
||||
None,
|
||||
Some(&planning_context),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
|
|
@ -2969,9 +3078,8 @@ mod tests {
|
|||
thread_id: "thread-1".into(),
|
||||
repository: "GameCult/Epiphany".into(),
|
||||
persona_id: "epiphany".into(),
|
||||
model_revision: 7,
|
||||
model_hash: "model-hash-7".into(),
|
||||
model_admission_receipt_id: "model-admission-7".into(),
|
||||
model_projection_digest: "model-projection-7".into(),
|
||||
model_source_documents: Vec::new(),
|
||||
routing_policy_id: "resident-feedback-consideration-v0".into(),
|
||||
question: epiphany_core::ImaginationConsiderationQuestion::CompareWithCurrentBodyAndSuggestCoherentOptions,
|
||||
quoted_evidence: epiphany_core::QuotedPersonaFeedbackEvidence {
|
||||
|
|
@ -2991,7 +3099,25 @@ mod tests {
|
|||
schema_version: "epiphany.worker.imagination_consideration_context.v0".into(),
|
||||
contract: "epiphany.imagination_consideration_context.v0".into(),
|
||||
request: request.clone(),
|
||||
model: epiphany_core::EpiphanyMemoryGraphSnapshot::default(),
|
||||
model: epiphany_core::EpiphanyRepoModelView {
|
||||
identity: epiphany_core::EpiphanyRepoModelIdentityDocument {
|
||||
schema_epoch: epiphany_core::REPO_MODEL_SCHEMA_EPOCH.into(),
|
||||
graph_id: "repo-model".into(),
|
||||
runtime_id: "runtime-1".into(),
|
||||
swarm_id: "swarm-1".into(),
|
||||
workspace_id: "workspace-1".into(),
|
||||
body_binding_sha256: "body-binding".into(),
|
||||
},
|
||||
projection_digest: request.model_projection_digest.clone(),
|
||||
source_documents: Vec::new(),
|
||||
domains: Vec::new(),
|
||||
nodes: Vec::new(),
|
||||
edges: Vec::new(),
|
||||
summaries: Vec::new(),
|
||||
frontier: Vec::new(),
|
||||
lifecycle_receipts: Vec::new(),
|
||||
claim_obligations: Vec::new(),
|
||||
},
|
||||
};
|
||||
let launch = EpiphanyRuntimeWorkerLaunchRequest {
|
||||
schema_version: epiphany_core::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(),
|
||||
|
|
@ -3025,8 +3151,10 @@ mod tests {
|
|||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(&context),
|
||||
None,
|
||||
None,
|
||||
"2026-07-15T10:00:00Z",
|
||||
"consideration-result-1",
|
||||
"decision-context-test",
|
||||
|
|
@ -3050,8 +3178,14 @@ mod tests {
|
|||
assert_eq!(candidate.source_room_id, request.source_room_id);
|
||||
assert_eq!(candidate.source_visibility, request.source_visibility);
|
||||
assert_eq!(candidate.data_classification, request.data_classification);
|
||||
assert_eq!(candidate.model_revision, request.model_revision);
|
||||
assert_eq!(candidate.model_hash, request.model_hash);
|
||||
assert_eq!(
|
||||
candidate.model_projection_digest,
|
||||
request.model_projection_digest
|
||||
);
|
||||
assert_eq!(
|
||||
candidate.model_source_documents,
|
||||
request.model_source_documents
|
||||
);
|
||||
assert_eq!(
|
||||
candidate.evidence_refs,
|
||||
request.quoted_evidence.source_discussion_refs
|
||||
|
|
@ -3129,14 +3263,14 @@ mod tests {
|
|||
assert!(failed.frontier_planning_request_id.is_none());
|
||||
assert!(failed.frontier_plan_candidate_msgpack.is_none());
|
||||
assert!(failed.state_patch_msgpack.is_none());
|
||||
assert!(failed.repo_model_patch_msgpack.is_none());
|
||||
assert!(failed.repo_model_mutation_proposal_msgpack.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mind_ingress_derives_immutable_identity_from_launch_context() -> Result<()> {
|
||||
let parsed = parse_assistant_json::<RoleWorkerResultIngress>(
|
||||
r#"{"roleId":"mindAdmissionReview","verdict":"adopt","summary":"bounded","nextSafeMove":"admit","filesInspected":[],"frontierPlanMindRequestId":"model-substituted-request","frontierPlanMindDecision":{"mindRequestId":"model-substituted-request","planningRequestId":"model-substituted-planning","imaginationResultId":"model-substituted-result","candidateId":"model-substituted-candidate","candidateSha256":"model-substituted-hash","decision":"adopt","rationale":"Exact candidate is bounded and falsifiable.","decidedAt":"2026-07-15T10:00:00Z"}}"#,
|
||||
r#"{"roleId":"mindAdmissionReview","verdict":"adopt","summary":"bounded","nextSafeMove":"admit","filesInspected":[],"frontierPlanMindDecision":{"decision":"adopt","rationale":"Exact candidate is bounded and falsifiable."}}"#,
|
||||
)?;
|
||||
let launch = EpiphanyRuntimeWorkerLaunchRequest {
|
||||
schema_version: epiphany_core::RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.into(),
|
||||
|
|
@ -3184,9 +3318,8 @@ mod tests {
|
|||
planning_request: epiphany_core::RepoFrontierPlanningRequest {
|
||||
schema_version: epiphany_core::REPO_FRONTIER_PLANNING_REQUEST_SCHEMA_VERSION.into(),
|
||||
request_id: "planning-request-1".into(),
|
||||
model_revision: 1,
|
||||
model_hash: "model-hash-1".into(),
|
||||
admission_receipt_id: "admission-1".into(),
|
||||
model_projection_digest: "model-projection-1".into(),
|
||||
model_source_documents: Vec::new(),
|
||||
frontier_item_id: "frontier-1".into(),
|
||||
frontier_item_hash: "frontier-hash-1".into(),
|
||||
selected_organ: "Imagination".into(),
|
||||
|
|
@ -3200,8 +3333,8 @@ mod tests {
|
|||
schema_version: epiphany_core::REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION.into(),
|
||||
candidate_id: "candidate-1".into(),
|
||||
planning_request_id: "planning-request-1".into(),
|
||||
model_revision: 1,
|
||||
model_hash: "model-hash-1".into(),
|
||||
model_projection_digest: "model-projection-1".into(),
|
||||
model_source_documents: Vec::new(),
|
||||
frontier_item_id: "frontier-1".into(),
|
||||
frontier_item_hash: "frontier-hash-1".into(),
|
||||
safe_paths: vec!["epiphany-openai-runtime".into()],
|
||||
|
|
@ -3220,9 +3353,11 @@ mod tests {
|
|||
"mindAdmissionReview",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(&context),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
"2026-07-15T10:00:00Z",
|
||||
"mind-result-1",
|
||||
"decision-context-test",
|
||||
|
|
@ -3246,8 +3381,9 @@ mod tests {
|
|||
assert_eq!(decision.planning_request_id, "planning-request-1");
|
||||
assert_eq!(decision.imagination_result_id, "imagination-result-1");
|
||||
assert_eq!(decision.candidate_id, "candidate-1");
|
||||
assert_eq!(decision.decided_at, "2026-07-15T10:00:00Z");
|
||||
assert!(result.state_patch_msgpack.is_none());
|
||||
assert!(result.repo_model_patch_msgpack.is_none());
|
||||
assert!(result.repo_model_mutation_proposal_msgpack.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -3479,8 +3615,8 @@ mod tests {
|
|||
request: epiphany_core::RepoFrontierModelingRequest {
|
||||
schema_version: epiphany_core::REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION.to_string(),
|
||||
request_id: "frontier-modeling-request-1".to_string(),
|
||||
model_revision: 1,
|
||||
model_hash: "model-hash".to_string(),
|
||||
model_projection_digest: "model-projection".to_string(),
|
||||
model_source_documents: Vec::new(),
|
||||
route_id: "route-1".to_string(),
|
||||
frontier_item_id: "frontier-1".to_string(),
|
||||
frontier_item_hash: "frontier-hash".to_string(),
|
||||
|
|
@ -3557,13 +3693,26 @@ mod tests {
|
|||
.output_schema_json
|
||||
.as_deref()
|
||||
.expect("worker model request should carry role output schema");
|
||||
assert!(output_schema.contains("\"repoModelPatch\""));
|
||||
assert!(output_schema.contains("\"frontierNodeIds\""));
|
||||
assert!(output_schema.contains("\"const\": \"frontier-modeling-request-1\""));
|
||||
assert!(output_schema.contains("\"const\": \"incorporate_frontier_verdict\""));
|
||||
assert!(!output_schema.contains("\"const\": \"evolution\""));
|
||||
let output_schema_value: serde_json::Value = serde_json::from_str(output_schema)?;
|
||||
assert!(
|
||||
output_schema_value["properties"]
|
||||
.get("frontierVerdictGap")
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
output_schema_value["properties"]
|
||||
.get("frontierNodeIds")
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
output_schema_value["properties"]
|
||||
.get("repoModelOperations")
|
||||
.is_none()
|
||||
);
|
||||
assert!(!output_schema.contains("frontier-modeling-request-1"));
|
||||
assert!(!output_schema.contains("incorporate_frontier_verdict"));
|
||||
assert!(!model_request.instructions.contains("Output schema JSON"));
|
||||
assert!(!model_request.instructions.contains("\"repoModelPatch\""));
|
||||
assert!(model_request.instructions.contains("frontierVerdictGap"));
|
||||
assert!(
|
||||
model_request
|
||||
.instructions
|
||||
|
|
@ -3616,23 +3765,14 @@ mod tests {
|
|||
};
|
||||
let assistant_text = serde_json::json!({
|
||||
"roleId": "modeling",
|
||||
"verdict": "checkpoint-ready",
|
||||
"verdict": "checkpoint-update-needed",
|
||||
"summary": "Mapped.",
|
||||
"nextSafeMove": "Review the patch.",
|
||||
"nextSafeMove": "Review the runtime-owned verdict mutation.",
|
||||
"filesInspected": ["src/lib.rs"],
|
||||
"frontierNodeIds": ["old"],
|
||||
"frontierNodeIds": ["frontier-1"],
|
||||
"evidenceIds": ["soul-verdict-1"],
|
||||
"artifactRefs": ["artifact:model"],
|
||||
"repositoryBodyObservationBasis": body_basis,
|
||||
"repoModelPatch": {
|
||||
"patch_id": "modeling-runtime-test",
|
||||
"base_revision": 0,
|
||||
"base_hash": "legacy-hash",
|
||||
"applied_at": "2026-07-13T00:00:00Z",
|
||||
"purpose": {"kind": "evolution"},
|
||||
"operations": [{"operation": "retire_node", "node_id": "old"}]
|
||||
},
|
||||
"statePatch": {"observations": [], "evidence": []},
|
||||
"selfPatch": {"reason": "typed nested document"}
|
||||
"frontierVerdictGap": "Soul verified the consequence; close the exact frontier."
|
||||
})
|
||||
.to_string();
|
||||
let result = complete_worker_job_from_assistant_text(
|
||||
|
|
@ -3644,28 +3784,31 @@ mod tests {
|
|||
)?;
|
||||
|
||||
assert_eq!(result.job_id, "worker-job-1");
|
||||
assert_eq!(result.verdict, "checkpoint-ready");
|
||||
assert_eq!(result.verdict, "checkpoint-update-needed");
|
||||
assert_eq!(result.summary, "Mapped.");
|
||||
assert_eq!(result.next_safe_move, "Review the patch.");
|
||||
assert_eq!(
|
||||
result.next_safe_move,
|
||||
"Review the runtime-owned verdict mutation."
|
||||
);
|
||||
let runtime_evidence_id = format!("openai-request:{}", model_request.request_id);
|
||||
assert!(result.evidence_refs.contains(&runtime_evidence_id));
|
||||
let typed_result = epiphany_core::runtime_role_worker_result(&store, "worker-job-1")?
|
||||
.expect("typed role worker result");
|
||||
assert_eq!(typed_result.verdict, "checkpoint-ready");
|
||||
assert_eq!(typed_result.verdict, "checkpoint-update-needed");
|
||||
assert_eq!(typed_result.files_inspected, vec!["src/lib.rs".to_string()]);
|
||||
assert_eq!(typed_result.evidence_ids, vec![runtime_evidence_id]);
|
||||
assert_eq!(
|
||||
typed_result.evidence_ids,
|
||||
vec![runtime_evidence_id, "soul-verdict-1".to_string()]
|
||||
);
|
||||
assert_eq!(typed_result.artifact_refs, result.artifact_refs);
|
||||
assert_eq!(
|
||||
typed_result
|
||||
.repo_model_patch()?
|
||||
.expect("repo model patch")
|
||||
.patch_id,
|
||||
"modeling-runtime-test"
|
||||
);
|
||||
assert_eq!(
|
||||
typed_result.self_patch()?.expect("self patch").reason,
|
||||
Some("typed nested document".to_string())
|
||||
.repo_model_mutation_proposal()?
|
||||
.expect("repo model mutation proposal")
|
||||
.proposal_id,
|
||||
"repo-model-mutation-proposal-worker-job-1"
|
||||
);
|
||||
assert!(typed_result.self_patch()?.is_none());
|
||||
assert!(
|
||||
runtime_job_snapshot(&store, "worker-job-1")?
|
||||
.expect("snapshot")
|
||||
|
|
|
|||
|
|
@ -125,9 +125,7 @@ pub async fn execute_persona_model_turn_with_runner<R: PersonaModelRunner>(
|
|||
"projector",
|
||||
projector_prompt,
|
||||
None,
|
||||
epiphany_core::EpiphanyReasoningProjection::PersonaProjector(
|
||||
plan.projector_input.clone(),
|
||||
),
|
||||
epiphany_core::EpiphanyReasoningProjection::PersonaProjector(plan.projector_input.clone()),
|
||||
Vec::new(),
|
||||
)
|
||||
.await?;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use chrono::DateTime;
|
||||
#[cfg(test)]
|
||||
use chrono::Utc;
|
||||
|
|
@ -93,6 +93,15 @@ pub fn required_packaged_release_binaries(target_triple: &str) -> Vec<(&'static
|
|||
"workspace-coverage-projector",
|
||||
file_name("epiphany-workspace-coverage-projector"),
|
||||
),
|
||||
("atlas-publisher", file_name("epiphany-atlas-publisher")),
|
||||
(
|
||||
"model-entanglement-projector",
|
||||
file_name("epiphany-model-entanglement-projector"),
|
||||
),
|
||||
(
|
||||
"atlas-impact-ingress",
|
||||
file_name("epiphany-atlas-impact-ingress"),
|
||||
),
|
||||
("semantic-query", file_name("epiphany-memory-semantic")),
|
||||
("verse-query", file_name("epiphany-verse-query")),
|
||||
("repository-body", file_name("epiphany-repository-body")),
|
||||
|
|
@ -616,6 +625,11 @@ fn required_release_build_target(role: &str) -> Result<(&'static str, &'static s
|
|||
"workspace-coverage-projector" => {
|
||||
Ok(("epiphany-core", "epiphany-workspace-coverage-projector"))
|
||||
}
|
||||
"atlas-publisher" => Ok(("epiphany-core", "epiphany-atlas-publisher")),
|
||||
"model-entanglement-projector" => {
|
||||
Ok(("epiphany-core", "epiphany-model-entanglement-projector"))
|
||||
}
|
||||
"atlas-impact-ingress" => Ok(("epiphany-core", "epiphany-atlas-impact-ingress")),
|
||||
"semantic-query" => Ok(("epiphany-core", "epiphany-memory-semantic")),
|
||||
"verse-query" => Ok(("epiphany-core", "epiphany-verse-query")),
|
||||
"repository-body" => Ok(("epiphany-core", "epiphany-repository-body")),
|
||||
|
|
@ -1002,12 +1016,10 @@ mod tests {
|
|||
let first = release_bundle_target_dir(root, b"lock-v1", "target-a", "toolchain-a");
|
||||
let second = release_bundle_target_dir(root, b"lock-v1", "target-a", "toolchain-a");
|
||||
assert_eq!(first, second);
|
||||
assert!(
|
||||
first
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with("graph-"))
|
||||
);
|
||||
assert!(first
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with("graph-")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1207,27 +1219,22 @@ mod tests {
|
|||
);
|
||||
assert_eq!(args.iter().filter(|arg| *arg == "--bin").count(), 24);
|
||||
assert_eq!(args.iter().filter(|arg| *arg == "--package").count(), 1);
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|pair| pair == ["--package", "epiphany-release-bundle"])
|
||||
);
|
||||
assert!(args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--package", "epiphany-release-bundle"]));
|
||||
assert!(!args.iter().any(|arg| arg == "epiphany-core"));
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|pair| pair == ["--features", "epiphany-release-bundle/release-runtime"])
|
||||
);
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|pair| pair == ["--bin", "epiphany-mvp-coordinator"])
|
||||
);
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|pair| pair == ["--bin", "epiphany-mvp-status"])
|
||||
);
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|pair| pair == ["--bin", "epiphany-state"])
|
||||
);
|
||||
assert!(args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--features", "epiphany-release-bundle/release-runtime"]));
|
||||
assert!(args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--bin", "epiphany-mvp-coordinator"]));
|
||||
assert!(args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--bin", "epiphany-mvp-status"]));
|
||||
assert!(args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--bin", "epiphany-state"]));
|
||||
assert!(!args.iter().any(|arg| arg == "--bins"));
|
||||
}
|
||||
|
||||
|
|
@ -1407,15 +1414,13 @@ mod tests {
|
|||
fn witness_reader_refuses_tamper_and_inspector_refuses_wrong_runtime() {
|
||||
let (d, e) = fixture();
|
||||
let witness = Path::new(&e.package_root).join(EPIPHANY_PACKAGED_RELEASE_WITNESS_FILE);
|
||||
assert!(
|
||||
inspect_epiphany_packaged_release_witness(
|
||||
&witness,
|
||||
d.path(),
|
||||
"alien-runtime",
|
||||
&e.source_commit_sha,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(inspect_epiphany_packaged_release_witness(
|
||||
&witness,
|
||||
d.path(),
|
||||
"alien-runtime",
|
||||
&e.source_commit_sha,
|
||||
)
|
||||
.is_err());
|
||||
fs::write(&witness, b"hostile witness").unwrap();
|
||||
assert!(read_epiphany_packaged_release_witness(&witness).is_err());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -879,44 +879,6 @@ pub enum RepoFrontierStatus {
|
|||
Superseded,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)]
|
||||
pub struct RepoModelPatch {
|
||||
pub patch_id: String,
|
||||
pub base_revision: u64,
|
||||
pub base_hash: String,
|
||||
pub applied_at: String,
|
||||
pub purpose: RepoModelPatchPurpose,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<RepoModelPatchOperation>")]
|
||||
pub operations: Vec<RepoModelPatchOperation>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
#[ts(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum RepoModelPatchPurpose {
|
||||
#[default]
|
||||
Evolution,
|
||||
IncorporateFrontierVerdict {
|
||||
route_id: String,
|
||||
soul_verdict_receipt_id: String,
|
||||
},
|
||||
RepairClaim,
|
||||
AdoptFrontierPlan {
|
||||
planning_request_id: String,
|
||||
result_id: String,
|
||||
candidate_id: String,
|
||||
},
|
||||
RelinquishFrontierRoute {
|
||||
route_id: String,
|
||||
hands_refusal_receipt_id: String,
|
||||
},
|
||||
AmendFrontierExecution {
|
||||
route_id: String,
|
||||
amendment_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn reorient_checkpoint_from_admitted_repo_model(
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
obligation_id: &str,
|
||||
|
|
@ -949,53 +911,6 @@ pub fn reorient_checkpoint_from_admitted_repo_model(
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(tag = "operation", rename_all = "snake_case")]
|
||||
#[ts(tag = "operation", rename_all = "snake_case")]
|
||||
pub enum RepoModelPatchOperation {
|
||||
UpsertNode {
|
||||
node: EpiphanyMemoryNode,
|
||||
},
|
||||
ReviseNode {
|
||||
node: EpiphanyMemoryNode,
|
||||
},
|
||||
RetireNode {
|
||||
node_id: String,
|
||||
},
|
||||
UpsertEdge {
|
||||
edge: EpiphanyMemoryEdge,
|
||||
},
|
||||
ReviseEdge {
|
||||
edge: EpiphanyMemoryEdge,
|
||||
},
|
||||
RetireEdge {
|
||||
edge_id: String,
|
||||
},
|
||||
UpsertFrontier {
|
||||
item: RepoFrontierItem,
|
||||
},
|
||||
ReviseFrontier {
|
||||
item: RepoFrontierItem,
|
||||
},
|
||||
RetireFrontier {
|
||||
item_id: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
retired_at: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
superseded_by: Option<String>,
|
||||
},
|
||||
AdoptFrontierPlan {
|
||||
frontier_item_id: String,
|
||||
expected_frontier_item_hash: String,
|
||||
adopted_plan: RepoFrontierAdoptedPlan,
|
||||
},
|
||||
AmendFrontierExecution {
|
||||
frontier_item_id: String,
|
||||
expected_frontier_item_hash: String,
|
||||
amendment: RepoFrontierExecutionAmendment,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)]
|
||||
pub struct EpiphanyMemoryGraphSource {
|
||||
pub kind: String,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,28 @@
|
|||
# Epiphany Current Algorithmic Map
|
||||
|
||||
## 2026-08-14 authority supersession
|
||||
|
||||
The keyed Mind hard cut is complete for RepoModel. `EpiphanyRepoModelView` and
|
||||
its exact source-document set own current repository modeling; model output
|
||||
contains semantic operations only and runtime constructs the durable proposal,
|
||||
Body binding, causal references, receipt, and commit time. The former aggregate
|
||||
RepoModel entry, key, patch, admission path, store, and CLI have been deleted.
|
||||
`EpiphanyMemoryGraphSnapshot` remains only as a nonpersisted local query and
|
||||
semantic-index projection. Any aggregate revision/hash or
|
||||
`RepoModelAdmissionReceipt` language retained later in this file describes
|
||||
historical evidence, not a live writer or validation path.
|
||||
|
||||
Cross-repository Modeling now uses the federated Model Atlas documented in
|
||||
`notes/model-atlas-vertical-slice.md`. Providers own offers, consumers own
|
||||
claims, Soul owns exact verification evidence, a deterministic projector derives
|
||||
edges/cycles/blast radius, and each consumer Self alone decides whether a local
|
||||
impact wakes Modeling or Soul. Odin transports and indexes; Eve renders; neither
|
||||
owns dependency truth or Hands authority.
|
||||
|
||||
## Causal work identity and creation provenance
|
||||
|
||||
- Owner: `causal_work_identity` derives durable request identity for Proposal Modeling, Research, frontier Planning, PlanMind, and Admitted Model Direction.
|
||||
- Inputs: runtime identity plus the immutable admitted cause specific to each typed family. Proposal content, model/frontier hashes, accepted result identity, candidate digest, and Mind admission receipts may participate. Coordinator thread and timestamps may not.
|
||||
- Inputs: runtime identity plus the immutable admitted cause specific to each typed family. Proposal content, the exact keyed model projection digest/source-document set, accepted result identity, candidate digest, and typed Mind receipts may participate. Coordinator thread and timestamps may not.
|
||||
- Outputs: deterministic typed request IDs consumed by direct and resident launch paths.
|
||||
- Derived state: creation thread and request time are provenance. Job, process, grant, model-execution, and tool IDs identify attempts beneath the request and cannot redefine it.
|
||||
- Forbidden writers: current coordinator thread, resident projection, retry path, launch callback, and worker output cannot fork, invalidate, or restore a request identity.
|
||||
|
|
@ -195,7 +214,7 @@ rejected before mutation; no repair loop or selector exception may launder it.
|
|||
feedback-only pressure, not an Eve connection, Persona command, objective, or
|
||||
work proposal.
|
||||
- Self owns an immutable Imagination consideration request binding one admitted
|
||||
feedback packet digest to one exact admitted Modeling revision/hash/receipt
|
||||
feedback packet digest to one exact admitted keyed Modeling basis and receipt
|
||||
and one fixed question enum. Feedback prose is transported only as quoted
|
||||
evidence.
|
||||
- Imagination owns a proposal-only consideration candidate with `suggest`,
|
||||
|
|
@ -872,8 +891,8 @@ watcher Dirty/Stale/Changed forces Regather. Path matches, status labels,
|
|||
worker-launch documents, coordinator rows, and CRRC recommendations are derived
|
||||
consumers and forbidden decision writers.
|
||||
|
||||
Canonical RepoModel is the admitted map, not the repository Body. Its exact
|
||||
revision/hash and Mind-issued `RepoModelAdmissionReceipt` prove map identity
|
||||
Canonical RepoModel is the admitted keyed map, not the repository Body. Its
|
||||
exact projection digest and sealed source-document versions prove map identity
|
||||
only. Future Ready additionally requires a nervous-system-owned, continuity-
|
||||
bearing Body observation and retrieval coverage bound to the same source
|
||||
generation; Mind derives readiness from that exact join. Legacy graph
|
||||
|
|
@ -4656,16 +4675,36 @@ the typed seed provenance, keyed documents, and generic Mind commit receipt in
|
|||
one exact-envelope transaction. Exact replay returns the same projected state;
|
||||
divergent seed identity or an aggregate RepoModel envelope refuses.
|
||||
|
||||
Exact `8ad16be0` moves the production `epiphany-repository-body bootstrap`
|
||||
command onto this owner. The legacy bootstrap/migration binary and launch-time
|
||||
aggregate reader remain the next deletion line; the shakedown stays paused
|
||||
until they and aggregate admission are gone.
|
||||
Exact `8ad16be0` moved the production `epiphany-repository-body bootstrap`
|
||||
command onto this owner. Exact `18d3783a` then deleted the legacy aggregate
|
||||
bootstrap binary; the 2026-08-14 hard cut deleted aggregate admission and all
|
||||
production aggregate RepoModel readers and writers.
|
||||
|
||||
Exact `18d3783a` deletes the legacy bootstrap binary. Exact `120663fa` makes
|
||||
launch-context assembly read `EpiphanyRepoModelView` directly. The existing
|
||||
Exact `120663fa` makes launch-context assembly read `EpiphanyRepoModelView`
|
||||
directly. The existing
|
||||
memory context cutter receives a temporary graph-shaped projection for query
|
||||
selection only; that projection is never persisted and its revision/hash fields
|
||||
are inert. Modeling prompt context names the view projection digest and semantic
|
||||
document identities instead of a global model revision/hash. Missing keyed
|
||||
RepoModel state now refuses launch context rather than bootstrapping shared
|
||||
authority from thread state.
|
||||
|
||||
### Federated Model Atlas
|
||||
|
||||
Local provider offers, consumer dependency claims, Soul verification, and Self
|
||||
impact are separate keyed Mind families. Each write is planned from current
|
||||
Body evidence and exact typed source versions, then committed through Mind CAS.
|
||||
Per-repository publishers sign only their own documents and exact Mind receipt
|
||||
bindings. Odin persists the signed events without joining them. The projector
|
||||
verifies pinned identities, status watermarks, visibility, and source versions,
|
||||
then deterministically derives compatibility, cycles, and direct/transitive
|
||||
blast radius. A consumer ingress re-reads its local claim and the exact
|
||||
projection before committing an impact and asking Resident Self for a bounded
|
||||
Modeling or Soul wake. The wake explicitly grants no Hands authority.
|
||||
|
||||
The provider-owned Eve projection is one `gamecult.eve.surface.v1` retained
|
||||
tree with attention, drilldown, and secondary graph views. Select/filter are
|
||||
presentation-only; domain mutation routes back to the owning repository's
|
||||
Modeling interface. Brake scopes `atlas.publish`, `atlas.project`, and
|
||||
`atlas.impact_ingress` freeze writes and scheduling while preserving the last
|
||||
projection as visibly stale read-only state.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
# Epiphany Memory Graph Unified Plan
|
||||
|
||||
> Historical plan. RepoModel authority was hard-cut to keyed Mind documents on
|
||||
> 2026-08-14. `EpiphanyMemoryGraphSnapshot` remains only as a derived local
|
||||
> query/semantic projection. Cross-repository dependency evidence now travels
|
||||
> through the federated Model Atlas described in
|
||||
> `notes/model-atlas-vertical-slice.md`. This document cannot authorize a new
|
||||
> aggregate store, migrator, or dual-read path.
|
||||
|
||||
The repo fractal dataflow graph and agent memory are one architecture.
|
||||
|
||||
They differ in policy, not substrate. A source module, a durable role memory, an
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
# Memory Graph Semantic Projection Authority Map
|
||||
|
||||
> Superseded for RepoModel authority on 2026-08-14. Keyed
|
||||
> `EpiphanyRepoModelView` documents now own the local repository model; the
|
||||
> remaining `EpiphanyMemoryGraphSnapshot` is a nonpersisted query/semantic
|
||||
> projection only. The federated cross-repository path is documented in
|
||||
> `notes/model-atlas-vertical-slice.md`. Nothing in this historical map may be
|
||||
> used to restore an aggregate RepoModel writer or admission path.
|
||||
|
||||
## Objective
|
||||
|
||||
Give every Epiphany swarm persistent semantic recall over both its Mind and its
|
||||
|
|
@ -11,9 +18,9 @@ that ranks canonical document identities.
|
|||
|
||||
## Current Mechanism
|
||||
|
||||
- The runtime-spine `EpiphanyMemoryGraphEntry` is the admitted RepoModel. Its
|
||||
revision and hash bind Modeling-owned architecture, dataflow, summaries, and
|
||||
frontier.
|
||||
- Keyed RepoModel documents admitted by local Mind own architecture, dataflow,
|
||||
summaries, and frontier. `EpiphanyMemoryGraphSnapshot` is derived only for
|
||||
query and semantic projection and has no revision/hash admission authority.
|
||||
- Reviewed `EpiphanyAgentMemoryEntry` documents own lane and Persona memory.
|
||||
`memory_graph_from_agent_memories` derives their typed Mind graph projection.
|
||||
- `plan_memory_graph_context_cut` resolves full typed nodes, edges, summaries,
|
||||
|
|
@ -29,7 +36,7 @@ that ranks canonical document identities.
|
|||
## Owner
|
||||
|
||||
- Mind claims: their admitted typed CultCache documents.
|
||||
- Modeling claims: the current runtime-spine RepoModel.
|
||||
- Modeling claims: the current validated keyed `EpiphanyRepoModelView`.
|
||||
- Projection synchronization and semantic candidate ranking: one shared
|
||||
`memory_graph::semantic_projection` organ.
|
||||
- Qdrant and Ollama: xenos transport/cache boundaries only.
|
||||
|
|
|
|||
183
notes/model-atlas-vertical-slice.md
Normal file
183
notes/model-atlas-vertical-slice.md
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
# Epiphany Model Atlas vertical slice
|
||||
|
||||
Updated: 2026-08-14
|
||||
|
||||
## Objective
|
||||
|
||||
Let one repository notice a provider change, understand its direct and
|
||||
transitive consequences, and wake its own Modeling lane without an operator
|
||||
typing `Continue`. The Atlas carries evidence between local minds. It does not
|
||||
become a shared mind and it never grants Hands authority.
|
||||
|
||||
## Authority map
|
||||
|
||||
| Concern | Owner | Inputs | Output |
|
||||
| --- | --- | --- | --- |
|
||||
| Offered surface | Provider Modeling and local Mind | Current Body basis and semantic offer intent | `gamecult.model.surface_offer.v0` |
|
||||
| Dependency claim | Consumer Modeling and local Mind | Current Body basis and semantic claim intent | `gamecult.model.dependency_claim.v0` |
|
||||
| Edge verification | Consumer Soul and local Mind | Exact signed claim/offer versions and exact evidence artifact | `gamecult.model.dependency_verification.v0` |
|
||||
| Publication | Repository publisher | Only its local Mind documents and exact Mind receipts | Signed `gamecult.model.atlas_publication.v0` events |
|
||||
| Discovery and transport | Odin | Registered typed records | Opaque persisted/queryable publications and projections |
|
||||
| Join, compatibility, cycles, blast radius | Atlas projector | Signed publications visible to one trusted audience | `gamecult.model.entanglement_projection.v0` |
|
||||
| Local impact | Consumer Self and local Mind | Exact local claim plus exact projection/source set | `epiphany.model.dependency_impact.v0` |
|
||||
| Lane wake | Consumer Resident Self | Admitted local impact and local lane lifecycle | Modeling or Soul pressure with no Hands grant |
|
||||
| Presentation | Eve | One provider-owned retained tree | GUI and TUI lowerings of the same projection |
|
||||
|
||||
Nobody owns a shared edge. The projector derives each edge from a
|
||||
provider-owned offer and a consumer-owned claim. Odin stores and serves those
|
||||
facts but cannot normalize them into dependency truth. Eve renders them but
|
||||
cannot mutate them.
|
||||
|
||||
## Data flow
|
||||
|
||||
```text
|
||||
provider Mind offer -------+ +--> Eve retained tree
|
||||
| |
|
||||
consumer Mind claim -------+--> signed publication --> Odin --> projector
|
||||
| |
|
||||
consumer Soul verification + v
|
||||
signed projection
|
||||
|
|
||||
consumer impact ingress
|
||||
|
|
||||
local Mind impact CAS
|
||||
|
|
||||
local Resident Self wake
|
||||
```
|
||||
|
||||
No organ opens another repository's Mind store. Publishers read only their own
|
||||
runtime Mind store. The projector reads Odin. Impact ingress reads the
|
||||
projection plus its own local claims.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Repository identity is
|
||||
`gamecult://swarm/{swarm_id}/workspace/{workspace_id}`. Runtime and Body
|
||||
incarnation are evidence, not stable identity.
|
||||
- Surface and claim identity are opaque UUIDs. Labels and paths cannot own
|
||||
identity.
|
||||
- Contract compatibility is closed: SemVer, exact schema ID, or exact SHA-256
|
||||
digest. Scheme mismatch is incompatible. Natural language has no vote.
|
||||
- The real repository Body digest is canonical 64-character lowercase SHA-256
|
||||
hex. Atlas publication digests use the explicit `sha256-` transport form.
|
||||
These are deliberately separate wire contracts.
|
||||
- A source-version digest seals the exact compact MessagePack bytes in the
|
||||
owning CultCache record. `canonicalPayloadMsgpackSha256` separately seals the
|
||||
named canonical MessagePack published across the federation. Neither digest
|
||||
may substitute for the other.
|
||||
- Local offer, claim, verification, and impact writes use dedicated typed
|
||||
planners and exact CultCache CAS. A stale Body or source version refuses the
|
||||
entire mutation.
|
||||
- Publications bind repository, runtime incarnation, Body basis, Verse,
|
||||
source schema/key/version/digest, Mind receipt, canonical payload digest,
|
||||
publication time, and service signature.
|
||||
- Publisher status is emitted every 30 seconds and becomes stale after 90
|
||||
seconds. A partition retains last-known edges and marks them unknown; absence
|
||||
never impersonates safety.
|
||||
- Verification applies only to the exact current claim and offer versions.
|
||||
- Build, deployment, and infrastructure-control cycles are blocked. Runtime,
|
||||
data, and schema cycles require declared failure semantics, remain
|
||||
review-required, and do not propagate autonomously. Informational
|
||||
governance/lore/persona cycles remain visible.
|
||||
- Atlas may wake Modeling or Soul. Every pressure carries the explicit clause
|
||||
`This wake grants no Hands authority.`
|
||||
- `atlas.publish`, `atlas.project`, and `atlas.impact_ingress` brakes stop writes
|
||||
and scheduling while retaining the last projection read-only.
|
||||
|
||||
## Live organs
|
||||
|
||||
- `epiphany-atlas-publisher` reads a local Mind store, publishes immutable
|
||||
events to its publisher CultCache/CultMesh store, and transports them to
|
||||
Odin. Its signing identity lives in a separate private `.cc` store.
|
||||
- `epiphany-model-entanglement-projector` pins repository trust anchors, queries
|
||||
Odin, verifies publications, derives a deterministic projection, and
|
||||
publishes the canonical Eve provider and surface documents.
|
||||
- `epiphany-atlas-impact-ingress` compares a projection with locally owned
|
||||
claims, admits exact impact documents, and asks local Resident Self to
|
||||
schedule permitted pressure.
|
||||
|
||||
Each organ has its own store. The local Mind, private identity, publisher
|
||||
events, CultMesh publication, Odin catalog, projection, and impact scheduler
|
||||
state are never collapsed into a writable mega-graph.
|
||||
|
||||
## Starfire pilot topology
|
||||
|
||||
The pilot uses three independent repository identities and state roots:
|
||||
|
||||
| Repository Body | Repository identity | Locally owned Atlas facts |
|
||||
| --- | --- | --- |
|
||||
| `F:\Projects\Eve` | one Starfire Eve workspace identity | Offers `gamecult.eve.surface.v1` |
|
||||
| `F:\Projects\Odin` | one Starfire Odin workspace identity | Claims Eve surface; offers `cultmesh://odin/rendezvous/provider-catalog` |
|
||||
| `F:\Projects\Epiphany` | one Starfire Epiphany workspace identity | Claims Odin provider catalog |
|
||||
|
||||
The Odin claim marks its catalog offer as affected. The projector therefore
|
||||
derives `Epiphany -> Odin`, `Odin -> Eve`, and Epiphany's two-hop blast-radius
|
||||
membership when Eve changes.
|
||||
|
||||
Do not invent deterministic IDs from repository paths. Each local Modeling
|
||||
organ creates and retains its opaque surface and claim UUIDs. Trust anchors are
|
||||
pinned by exact repository coordinates; key rotation is operator-gated.
|
||||
|
||||
## Rollout gates
|
||||
|
||||
1. Engage all three Atlas brake scopes. Run the three publishers, projector,
|
||||
and impact ingresses against isolated pilot stores. Inspect publications,
|
||||
watermarks, rejections, and the retained Eve tree without lane scheduling.
|
||||
2. Release Atlas scopes for Modeling and Soul while leaving existing Hands
|
||||
authorization unchanged. A temporary Eve contract change must wake Odin
|
||||
Modeling and then Epiphany Modeling without an operator prompt.
|
||||
3. Place the organs under the existing daemon supervisor. Sustain the pilot
|
||||
while observing publisher/projector lag, per-publisher watermarks,
|
||||
rejection count, cycles, and pending impacts through CultMesh/Eve.
|
||||
4. Only after sustained local proof, register topology and recovery runbooks in
|
||||
`gamecult-ops`. Yggdrasil and the public Verse remain outside V1.
|
||||
|
||||
The implementation and isolated proofs close the code slice. Gates 2 through 4
|
||||
are operational evidence, not claims that can be manufactured by unit tests.
|
||||
|
||||
## Verification
|
||||
|
||||
The focused proofs cover:
|
||||
|
||||
- no production `RepoModelPatch`, aggregate RepoModel store, aggregate
|
||||
admission reader/writer, or aggregate memory-graph key;
|
||||
- runtime-owned semantic Modeling ingress and exact keyed reasoning bases;
|
||||
- local offer/claim admission through current real Body evidence and Mind CAS;
|
||||
- signature tamper, trust-coordinate substitution, rollback, replay,
|
||||
watermark, and payload-size refusal;
|
||||
- order-independent projection digests, closed compatibility, verification
|
||||
invalidation, visibility-before-join, cycle classes, partition staleness, and
|
||||
deterministic transitive blast radius;
|
||||
- the exact Epiphany -> Odin -> Eve chain and direct/transitive Modeling
|
||||
pressure after an Eve schema change;
|
||||
- impact dedupe, pending lane locks, cooldown after completion, brake behavior,
|
||||
informational visibility without wake, and absence of Hands authority;
|
||||
- Odin persistence of only the registered Atlas/projection/Eve schemas without
|
||||
Odin-authored edges;
|
||||
- Eve conformance for one canonical GUI/TUI tree with presentation-only select
|
||||
and filter commands.
|
||||
|
||||
Current verification commands:
|
||||
|
||||
```powershell
|
||||
$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex'
|
||||
cargo test -p epiphany-core --lib
|
||||
cargo test -p epiphany-openai-runtime --lib
|
||||
cargo test -p epiphany-release-bundle --features coordinator-runtime --bin epiphany-mvp-coordinator
|
||||
cargo check --workspace --all-targets
|
||||
|
||||
Set-Location F:\Projects\Odin
|
||||
node --test test/model-atlas-documents.test.cjs
|
||||
cargo test -p odin-core
|
||||
|
||||
Set-Location F:\Projects\Eve
|
||||
node --test web/model-atlas-conformance.test.mjs
|
||||
node --test packages/eve-contracts/test/contracts.test.mjs
|
||||
```
|
||||
|
||||
`cargo check --workspace --all-targets --all-features` still reaches the older
|
||||
feature-gated `epiphany-workspace-coverage-recovery-smoke`, which imports
|
||||
`current_workspace_coverage_recovery_target` and
|
||||
`WorkspaceCoverageRecoveryTarget`; those symbols were already absent before
|
||||
this slice. Do not restore them as an Atlas compatibility shim. The ordinary
|
||||
all-target workspace and all Atlas-bearing targets compile.
|
||||
Reference in a new issue