Type self patch application

This commit is contained in:
Meta Vens 2026-05-14 07:17:56 +01:00
commit ed215d515b
10 changed files with 134 additions and 56 deletions

View file

@ -367,23 +367,13 @@ pub fn review_agent_self_patch(
};
match decode_agent_self_patch(patch_value) {
Ok(patch) => reasons.extend(review_agent_self_patch_contract(&target_agent_id, &patch)),
Ok(patch) => {
return review_agent_self_patch_document(role_id, &patch, store_path);
}
Err(reason) => reasons.push(reason),
}
AgentMemoryReview {
status: if reasons.is_empty() {
"accepted"
} else {
"rejected"
}
.to_string(),
target_agent_id,
target_role_id: role_id.to_string(),
target_store: store_path.display().to_string(),
reasons,
applied: None,
}
agent_memory_review(role_id, &target_agent_id, store_path, reasons, None)
}
pub(crate) fn decode_agent_self_patch(
@ -396,6 +386,30 @@ pub(crate) fn decode_agent_self_patch(
.map_err(|err| format!("selfPatch is not a valid AgentSelfPatch document: {err}"))
}
pub fn review_agent_self_patch_document(
role_id: &str,
patch: &AgentSelfPatch,
store_path: impl AsRef<Path>,
) -> AgentMemoryReview {
let store_path = store_path.as_ref();
let target_agent_id = match agent_id_for_role(role_id) {
Ok(agent_id) => agent_id,
Err(reason) => {
return AgentMemoryReview {
status: "rejected".to_string(),
target_agent_id: String::new(),
target_role_id: role_id.to_string(),
target_store: store_path.display().to_string(),
reasons: vec![reason],
applied: None,
};
}
};
let reasons = review_agent_self_patch_contract(target_agent_id, patch);
agent_memory_review(role_id, target_agent_id, store_path, reasons, None)
}
pub(crate) fn review_agent_self_patch_contract(
expected_agent_id: &str,
patch: &AgentSelfPatch,
@ -466,14 +480,24 @@ pub fn apply_agent_self_patch(
role_id: &str,
patch_value: &Value,
store_path: impl AsRef<Path>,
) -> Result<AgentMemoryReview> {
let patch = match decode_agent_self_patch(patch_value) {
Ok(patch) => patch,
Err(_) => return Ok(review_agent_self_patch(role_id, patch_value, store_path)),
};
apply_agent_self_patch_document(role_id, patch, store_path)
}
pub fn apply_agent_self_patch_document(
role_id: &str,
patch: AgentSelfPatch,
store_path: impl AsRef<Path>,
) -> Result<AgentMemoryReview> {
let store_path = store_path.as_ref();
let mut review = review_agent_self_patch(role_id, patch_value, store_path);
let mut review = review_agent_self_patch_document(role_id, &patch, store_path);
if review.status != "accepted" {
return Ok(review);
}
let patch: AgentSelfPatch = serde_json::from_value(patch_value.clone())
.context("failed to decode accepted selfPatch")?;
let mut cache = agent_memory_cache(store_path)?;
cache.pull_all_backing_stores()?;
let mut entry = cache
@ -510,6 +534,28 @@ pub fn apply_agent_self_patch(
Ok(review)
}
fn agent_memory_review(
role_id: &str,
target_agent_id: &str,
store_path: &Path,
reasons: Vec<String>,
applied: Option<bool>,
) -> AgentMemoryReview {
AgentMemoryReview {
status: if reasons.is_empty() {
"accepted"
} else {
"rejected"
}
.to_string(),
target_agent_id: target_agent_id.to_string(),
target_role_id: role_id.to_string(),
target_store: store_path.display().to_string(),
reasons,
applied,
}
}
pub fn apply_agent_canonical_trait_seeds(
seeds: &[AgentCanonicalTraitSeed],
store_path: impl AsRef<Path>,
@ -1244,7 +1290,7 @@ mod tests {
migrate_agent_memory_json_dir_to_cultcache(&agent_dir, &store)?;
assert!(validate_agent_memory_store(&store)?.is_empty());
let patch = serde_json::json!({
let patch: AgentSelfPatch = serde_json::from_value(serde_json::json!({
"agentId": "epiphany.body",
"reason": "The Body should remember accepted graph growth must stay source-grounded.",
"semanticMemories": [{
@ -1253,10 +1299,10 @@ mod tests {
"salience": 0.74,
"confidence": 0.86
}]
});
let review = review_agent_self_patch("modeling", &patch, &store);
}))?;
let review = review_agent_self_patch_document("modeling", &patch, &store);
assert_eq!(review.status, "accepted");
let applied = apply_agent_self_patch("modeling", &patch, &store)?;
let applied = apply_agent_self_patch_document("modeling", patch, &store)?;
assert_eq!(applied.status, "accepted");
assert_eq!(applied.applied, Some(true));

View file

@ -1,10 +1,11 @@
use anyhow::Context;
use anyhow::Result;
use epiphany_core::AgentSelfPatch;
use epiphany_core::agent_memory_status;
use epiphany_core::apply_agent_self_patch;
use epiphany_core::apply_agent_self_patch_document;
use epiphany_core::migrate_agent_memory_json_dir_to_cultcache;
use epiphany_core::project_agent_memory_to_json_dir;
use epiphany_core::review_agent_self_patch;
use epiphany_core::review_agent_self_patch_document;
use epiphany_core::validate_agent_memory_store;
use std::env;
use std::fs;
@ -51,13 +52,13 @@ fn main() -> Result<()> {
let store = require_path_arg(&mut args, "--store")?;
let role_id = require_string_arg(&mut args, "--role-id")?;
let patch = read_patch_arg(&require_string_arg(&mut args, "--patch")?)?;
print_json(&review_agent_self_patch(&role_id, &patch, store))?;
print_json(&review_agent_self_patch_document(&role_id, &patch, store))?;
}
"apply-patch" => {
let store = require_path_arg(&mut args, "--store")?;
let role_id = require_string_arg(&mut args, "--role-id")?;
let patch = read_patch_arg(&require_string_arg(&mut args, "--patch")?)?;
let result = apply_agent_self_patch(&role_id, &patch, store)?;
let result = apply_agent_self_patch_document(&role_id, patch, store)?;
let accepted = result.status == "accepted";
print_json(&result)?;
if !accepted {
@ -111,15 +112,15 @@ fn optional_path_arg(
Ok(Some(PathBuf::from(&values[1])))
}
fn read_patch_arg(value: &str) -> Result<serde_json::Value> {
fn read_patch_arg(value: &str) -> Result<AgentSelfPatch> {
let path = PathBuf::from(value);
if path.exists() {
let raw = fs::read_to_string(&path)
.with_context(|| format!("failed to read patch {}", path.display()))?;
return serde_json::from_str(&raw)
.with_context(|| format!("failed to decode patch {}", path.display()));
.with_context(|| format!("failed to decode typed selfPatch {}", path.display()));
}
serde_json::from_str(value).context("failed to decode patch JSON")
serde_json::from_str(value).context("failed to decode typed selfPatch JSON")
}
fn print_json<T: serde::Serialize>(value: &T) -> Result<()> {
@ -142,7 +143,7 @@ fn run_smoke(store: &Path) -> Result<serde_json::Value> {
"errors": errors,
}));
}
let accepted_patch = serde_json::json!({
let accepted_patch: AgentSelfPatch = serde_json::from_value(serde_json::json!({
"agentId": "epiphany.body",
"reason": "The Body should remember accepted graph growth must be source-grounded and bounded.",
"semanticMemories": [{
@ -151,10 +152,10 @@ fn run_smoke(store: &Path) -> Result<serde_json::Value> {
"salience": 0.74,
"confidence": 0.86,
}],
});
let accepted = review_agent_self_patch("modeling", &accepted_patch, store);
let wrong_role = review_agent_self_patch("verification", &accepted_patch, store);
let forbidden_patch = serde_json::json!({
}))?;
let accepted = review_agent_self_patch_document("modeling", &accepted_patch, store);
let wrong_role = review_agent_self_patch_document("verification", &accepted_patch, store);
let forbidden_patch: AgentSelfPatch = serde_json::from_value(serde_json::json!({
"agentId": "epiphany.body",
"reason": "This tries to put project state in lane memory, which should be refused.",
"graphs": {},
@ -164,8 +165,8 @@ fn run_smoke(store: &Path) -> Result<serde_json::Value> {
"salience": 0.5,
"confidence": 0.5,
}],
});
let forbidden = review_agent_self_patch("modeling", &forbidden_patch, store);
}))?;
let forbidden = review_agent_self_patch_document("modeling", &forbidden_patch, store);
let temp_dir = scoped_temp_dir("epiphany-agent-memory-smoke")?;
let temp_store = temp_dir.join("agents.msgpack");
@ -176,7 +177,7 @@ fn run_smoke(store: &Path) -> Result<serde_json::Value> {
temp_store.display()
)
})?;
let applied = apply_agent_self_patch("modeling", &accepted_patch, &temp_store)?;
let applied = apply_agent_self_patch_document("modeling", accepted_patch, &temp_store)?;
let temp_validation_errors = validate_agent_memory_store(&temp_store)?;
let _ = fs::remove_dir_all(&temp_dir);

View file

@ -6,7 +6,7 @@ use epiphany_core::HeartbeatCompleteOptions;
use epiphany_core::HeartbeatPumpOptions;
use epiphany_core::HeartbeatTickOptions;
use epiphany_core::VoidRoutineOptions;
use epiphany_core::apply_agent_self_patch;
use epiphany_core::apply_agent_self_patch_document;
use epiphany_core::complete_heartbeat_store;
use epiphany_core::heartbeat_status_projection;
use epiphany_core::initialize_ghostlight_scene_heartbeat_store;
@ -398,8 +398,9 @@ fn run_smoke(agent_store: &Path) -> Result<serde_json::Value> {
.as_str()
.ok_or_else(|| anyhow!("idle rumination has no roleId"))?
.to_string();
let patch = serde_json::Value::Object(patch.clone());
let applied = apply_agent_self_patch(&role_id, &patch, &temp_agent_store)?;
let patch = serde_json::from_value(serde_json::Value::Object(patch.clone()))
.context("idle rumination selfPatch is not a typed AgentSelfPatch")?;
let applied = apply_agent_self_patch_document(&role_id, patch, &temp_agent_store)?;
idle["rumination"]["result"] = serde_json::to_value(applied)?;
idle["rumination"]["applied"] = serde_json::Value::Bool(true);
write_rumination_artifact(&artifact_dir, "smoke-idle", &idle["rumination"])?;
@ -587,8 +588,9 @@ fn apply_rumination_patch(
.as_str()
.ok_or_else(|| anyhow!("rumination has no roleId"))?
.to_string();
let patch = serde_json::Value::Object(patch.clone());
let applied = apply_agent_self_patch(&role_id, &patch, agent_store)?;
let patch = serde_json::from_value(serde_json::Value::Object(patch.clone()))
.context("rumination selfPatch is not a typed AgentSelfPatch")?;
let applied = apply_agent_self_patch_document(&role_id, patch, agent_store)?;
result["rumination"]["result"] = serde_json::to_value(applied)?;
result["rumination"]["applied"] = serde_json::Value::Bool(true);
write_rumination_artifact(artifact_dir, schedule_id, &result["rumination"])?;

View file

@ -6,11 +6,12 @@ use cultcache_rs::CultCache;
use cultcache_rs::DatabaseEntry;
use cultcache_rs::SingleFileMessagePackBackingStore;
use epiphany_core::AgentCanonicalTraitSeed;
use epiphany_core::AgentSelfPatch;
use epiphany_core::apply_agent_canonical_trait_seeds;
use epiphany_core::apply_agent_self_patch;
use epiphany_core::apply_agent_self_patch_document;
use epiphany_core::default_heartbeat_state;
use epiphany_core::load_heartbeat_state_entry;
use epiphany_core::review_agent_self_patch;
use epiphany_core::review_agent_self_patch_document;
use epiphany_core::write_heartbeat_state_entry;
use ignore::WalkBuilder;
use serde::Deserialize;
@ -1414,9 +1415,9 @@ fn process_initialization_result_patches(
let mut applied = 0usize;
for patch in patches {
let review = if apply_self_patches {
apply_agent_self_patch(&patch.role_id, &patch.self_patch, store)?
apply_agent_self_patch_document(&patch.role_id, patch.self_patch.clone(), store)?
} else {
review_agent_self_patch(&patch.role_id, &patch.self_patch, store)
review_agent_self_patch_document(&patch.role_id, &patch.self_patch, store)
};
if review.status == "accepted" {
accepted += 1;
@ -2114,7 +2115,7 @@ fn number_from_map(values: &BTreeMap<String, f64>, key: &str) -> f64 {
struct InitializationSelfPatch {
role_id: String,
source: String,
self_patch: Value,
self_patch: AgentSelfPatch,
}
fn extract_initialization_self_patches(
@ -2135,13 +2136,13 @@ fn extract_trajectory_self_patches(result: &Value) -> Result<Vec<InitializationS
};
let mut patches = Vec::new();
for (index, item) in items.iter().enumerate() {
let self_patch = item.get("selfPatch").unwrap_or(item).clone();
let self_patch_value = item.get("selfPatch").unwrap_or(item).clone();
let role_id = item
.get("roleId")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| {
self_patch
self_patch_value
.get("agentId")
.and_then(Value::as_str)
.and_then(role_id_for_agent_id)
@ -2150,6 +2151,8 @@ fn extract_trajectory_self_patches(result: &Value) -> Result<Vec<InitializationS
.ok_or_else(|| {
anyhow!("selfPatchCandidates[{index}] needs roleId or known selfPatch.agentId")
})?;
let self_patch = serde_json::from_value(self_patch_value)
.with_context(|| format!("selfPatchCandidates[{index}] is not a typed selfPatch"))?;
patches.push(InitializationSelfPatch {
role_id,
source: format!("selfPatchCandidates[{index}]"),
@ -2165,13 +2168,13 @@ fn extract_personality_self_patches(result: &Value) -> Result<Vec<Initialization
};
let mut patches = Vec::new();
for (index, item) in items.iter().enumerate() {
let self_patch = item.get("selfPatch").unwrap_or(item).clone();
let self_patch_value = item.get("selfPatch").unwrap_or(item).clone();
let role_id = item
.get("roleId")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| {
self_patch
self_patch_value
.get("agentId")
.and_then(Value::as_str)
.and_then(role_id_for_agent_id)
@ -2180,6 +2183,8 @@ fn extract_personality_self_patches(result: &Value) -> Result<Vec<Initialization
.ok_or_else(|| {
anyhow!("selfPatchCandidates[{index}] needs roleId or known selfPatch.agentId")
})?;
let self_patch = serde_json::from_value(self_patch_value)
.with_context(|| format!("selfPatchCandidates[{index}] is not a typed selfPatch"))?;
patches.push(InitializationSelfPatch {
role_id,
source: format!("selfPatchCandidates[{index}]"),
@ -2195,7 +2200,7 @@ fn extract_memory_self_patches(result: &Value) -> Result<Vec<InitializationSelfP
};
let mut patches = Vec::new();
for (index, item) in items.iter().enumerate() {
let Some(self_patch) = item.get("selfPatch").cloned() else {
let Some(self_patch_value) = item.get("selfPatch").cloned() else {
continue;
};
let role_id = item
@ -2203,7 +2208,7 @@ fn extract_memory_self_patches(result: &Value) -> Result<Vec<InitializationSelfP
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| {
self_patch
self_patch_value
.get("agentId")
.and_then(Value::as_str)
.and_then(role_id_for_agent_id)
@ -2212,6 +2217,9 @@ fn extract_memory_self_patches(result: &Value) -> Result<Vec<InitializationSelfP
.ok_or_else(|| {
anyhow!("roleMemoryPatches[{index}] needs roleId or known selfPatch.agentId")
})?;
let self_patch = serde_json::from_value(self_patch_value).with_context(|| {
format!("roleMemoryPatches[{index}].selfPatch is not a typed selfPatch")
})?;
patches.push(InitializationSelfPatch {
role_id,
source: format!("roleMemoryPatches[{index}].selfPatch"),

View file

@ -21,11 +21,13 @@ pub use agent_memory::GhostlightTraitVector;
pub use agent_memory::agent_memory_status;
pub use agent_memory::apply_agent_canonical_trait_seeds;
pub use agent_memory::apply_agent_self_patch;
pub use agent_memory::apply_agent_self_patch_document;
pub use agent_memory::dossier_profile_for_role;
pub use agent_memory::load_agent_memory_entry_for_role;
pub use agent_memory::migrate_agent_memory_json_dir_to_cultcache;
pub use agent_memory::project_agent_memory_to_json_dir;
pub use agent_memory::review_agent_self_patch;
pub use agent_memory::review_agent_self_patch_document;
pub use agent_memory::validate_agent_memory_store;
pub use cultcache_rs::CacheBackingStore;
pub use cultcache_rs::CultCache;
@ -265,6 +267,7 @@ pub use surfaces::recommend_reorientation;
pub use surfaces::render_role_board_note;
pub use surfaces::reorientation_role_status;
pub use surfaces::review_role_self_patch;
pub use surfaces::review_role_self_patch_document;
pub use surfaces::role_board_job_status_to_role_status;
pub use surfaces::role_self_memory_target;
pub use surfaces::select_coordinator_automation_action;

View file

@ -108,6 +108,7 @@ pub use role_result::interpret_runtime_reorient_worker_result;
pub use role_result::interpret_runtime_role_worker_result;
pub use role_result::modeling_role_state_patch_policy_errors;
pub use role_result::review_role_self_patch;
pub use role_result::review_role_self_patch_document;
pub use role_result::role_self_memory_target;
pub use scene::EpiphanyScene;
pub use scene::EpiphanySceneAction;

View file

@ -451,12 +451,27 @@ pub fn role_label(role_id: EpiphanyRoleResultRoleId) -> Result<&'static str, Str
pub fn review_role_self_patch(
role_id: EpiphanyRoleResultRoleId,
patch: &serde_json::Value,
) -> EpiphanyRoleSelfPersistenceReview {
match decode_agent_self_patch(patch) {
Ok(patch) => review_role_self_patch_document(role_id, &patch),
Err(reason) => {
let (expected_agent_id, target_path) = role_self_memory_target(role_id);
EpiphanyRoleSelfPersistenceReview {
status: EpiphanyRoleSelfPersistenceStatus::Rejected,
target_agent_id: Some(expected_agent_id.to_string()),
target_path: Some(target_path.to_string()),
reasons: vec![reason],
}
}
}
}
pub fn review_role_self_patch_document(
role_id: EpiphanyRoleResultRoleId,
patch: &AgentSelfPatch,
) -> EpiphanyRoleSelfPersistenceReview {
let (expected_agent_id, target_path) = role_self_memory_target(role_id);
let reasons = match decode_agent_self_patch(patch) {
Ok(patch) => review_agent_self_patch_contract(expected_agent_id, &patch),
Err(reason) => vec![reason],
};
let reasons = review_agent_self_patch_contract(expected_agent_id, patch);
EpiphanyRoleSelfPersistenceReview {
status: if reasons.is_empty() {