Extract Epiphany role result policy into core

This commit is contained in:
Meta Vens 2026-05-12 19:47:04 +01:00
commit 1429141b5b
8 changed files with 985 additions and 587 deletions

View file

@ -523,12 +523,19 @@ use epiphany_core::EpiphanyRoleBoardJob;
use epiphany_core::EpiphanyRoleBoardJobStatus;
use epiphany_core::EpiphanyRoleBoardLane;
use epiphany_core::EpiphanyRoleBoardPlanningSummary;
use epiphany_core::EpiphanyRoleFindingInterpretation;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::EpiphanyRoleSelfPersistenceReview as CoreEpiphanyRoleSelfPersistenceReview;
use epiphany_core::EpiphanyRoleSelfPersistenceStatus as CoreEpiphanyRoleSelfPersistenceStatus;
use epiphany_core::EpiphanyRuntimeJobResult;
use epiphany_core::EpiphanyRuntimeJobSnapshot;
use epiphany_core::EpiphanyRuntimeJobStatus;
use epiphany_core::coordinator_automation_action;
use epiphany_core::derive_pressure_view;
use epiphany_core::derive_role_board;
use epiphany_core::imagination_role_state_patch_policy_errors;
use epiphany_core::interpret_role_finding;
use epiphany_core::modeling_role_state_patch_policy_errors;
use epiphany_core::recommend_coordinator_action;
use epiphany_core::recommend_crrc_action;
use epiphany_core::render_role_board_note;
@ -13306,464 +13313,85 @@ fn map_epiphany_role_finding(
job_error: Option<String>,
item_error: Option<String>,
) -> ThreadEpiphanyRoleFinding {
let state_patch = raw_result
let state_patch_result = raw_result
.get("statePatch")
.cloned()
.and_then(|patch| serde_json::from_value(patch).ok());
let self_patch = raw_result.get("selfPatch").cloned();
let self_persistence = self_patch
.map(serde_json::from_value::<ThreadEpiphanyUpdatePatch>);
let state_patch = state_patch_result
.as_ref()
.map(|patch| review_epiphany_role_self_patch(role_id, patch));
let item_error = match role_id {
ThreadEpiphanyRoleId::Imagination => merge_epiphany_item_error(
item_error,
imagination_role_state_patch_error(&raw_result, state_patch.as_ref()),
),
ThreadEpiphanyRoleId::Modeling => merge_epiphany_item_error(
item_error,
modeling_role_state_patch_error(&raw_result, state_patch.as_ref()),
),
ThreadEpiphanyRoleId::Implementation
| ThreadEpiphanyRoleId::Verification
| ThreadEpiphanyRoleId::Reorientation => item_error,
};
ThreadEpiphanyRoleFinding {
role_id,
verdict: json_string_field(&raw_result, "verdict"),
summary: json_string_field(&raw_result, "summary"),
next_safe_move: json_string_field(&raw_result, "nextSafeMove"),
checkpoint_summary: json_string_field(&raw_result, "checkpointSummary"),
scratch_summary: json_string_field(&raw_result, "scratchSummary"),
files_inspected: json_string_array_field(&raw_result, "filesInspected"),
frontier_node_ids: json_string_array_field(&raw_result, "frontierNodeIds"),
evidence_ids: json_string_array_field(&raw_result, "evidenceIds"),
artifact_refs: json_string_array_field(&raw_result, "artifactRefs"),
runtime_result_id: json_string_field(&raw_result, "runtimeResultId"),
runtime_job_id: json_string_field(&raw_result, "runtimeJobId"),
open_questions: json_string_array_field(&raw_result, "openQuestions"),
evidence_gaps: json_string_array_field(&raw_result, "evidenceGaps"),
risks: json_string_array_field(&raw_result, "risks"),
state_patch,
self_patch,
self_persistence,
.and_then(|result| result.as_ref().ok().cloned());
let state_patch_parse_error = state_patch_result
.as_ref()
.and_then(|result| result.as_ref().err().map(ToString::to_string));
let finding = interpret_role_finding(
map_core_role_result_role_id(role_id),
&raw_result,
state_patch_parse_error,
job_error,
item_error,
}
);
map_protocol_role_finding(role_id, finding, state_patch)
}
fn merge_epiphany_item_error(
item_error: Option<String>,
modeling_error: Option<String>,
) -> Option<String> {
match (item_error, modeling_error) {
(Some(existing), Some(extra)) => Some(format!("{existing}; {extra}")),
(Some(existing), None) => Some(existing),
(None, Some(extra)) => Some(extra),
(None, None) => None,
}
}
fn epiphany_role_self_memory_target(role_id: ThreadEpiphanyRoleId) -> (&'static str, &'static str) {
match role_id {
ThreadEpiphanyRoleId::Imagination => (
"epiphany.imagination",
"state/agents/imagination.agent-state.json",
),
ThreadEpiphanyRoleId::Modeling => ("epiphany.body", "state/agents/body.agent-state.json"),
ThreadEpiphanyRoleId::Verification => {
("epiphany.soul", "state/agents/soul.agent-state.json")
}
ThreadEpiphanyRoleId::Implementation => {
("epiphany.hands", "state/agents/hands.agent-state.json")
}
ThreadEpiphanyRoleId::Reorientation => {
("epiphany.life", "state/agents/life.agent-state.json")
}
}
}
fn review_epiphany_role_self_patch(
fn map_protocol_role_finding(
role_id: ThreadEpiphanyRoleId,
patch: &serde_json::Value,
finding: EpiphanyRoleFindingInterpretation,
state_patch: Option<ThreadEpiphanyUpdatePatch>,
) -> ThreadEpiphanyRoleFinding {
ThreadEpiphanyRoleFinding {
role_id,
verdict: finding.verdict,
summary: finding.summary,
next_safe_move: finding.next_safe_move,
checkpoint_summary: finding.checkpoint_summary,
scratch_summary: finding.scratch_summary,
files_inspected: finding.files_inspected,
frontier_node_ids: finding.frontier_node_ids,
evidence_ids: finding.evidence_ids,
artifact_refs: finding.artifact_refs,
runtime_result_id: finding.runtime_result_id,
runtime_job_id: finding.runtime_job_id,
open_questions: finding.open_questions,
evidence_gaps: finding.evidence_gaps,
risks: finding.risks,
state_patch,
self_patch: finding.self_patch,
self_persistence: finding
.self_persistence
.map(map_protocol_role_self_persistence_review),
job_error: finding.job_error,
item_error: finding.item_error,
}
}
fn map_core_role_result_role_id(role_id: ThreadEpiphanyRoleId) -> EpiphanyRoleResultRoleId {
match role_id {
ThreadEpiphanyRoleId::Implementation => EpiphanyRoleResultRoleId::Implementation,
ThreadEpiphanyRoleId::Imagination => EpiphanyRoleResultRoleId::Imagination,
ThreadEpiphanyRoleId::Modeling => EpiphanyRoleResultRoleId::Modeling,
ThreadEpiphanyRoleId::Verification => EpiphanyRoleResultRoleId::Verification,
ThreadEpiphanyRoleId::Reorientation => EpiphanyRoleResultRoleId::Reorientation,
}
}
fn map_protocol_role_self_persistence_review(
review: CoreEpiphanyRoleSelfPersistenceReview,
) -> ThreadEpiphanyRoleSelfPersistenceReview {
let (expected_agent_id, target_path) = epiphany_role_self_memory_target(role_id);
let mut reasons = Vec::new();
let Some(object) = patch.as_object() else {
return ThreadEpiphanyRoleSelfPersistenceReview {
status: ThreadEpiphanyRoleSelfPersistenceStatus::Rejected,
target_agent_id: Some(expected_agent_id.to_string()),
target_path: Some(target_path.to_string()),
reasons: vec!["selfPatch must be a JSON object".to_string()],
};
};
let agent_id = object.get("agentId").and_then(serde_json::Value::as_str);
match agent_id {
Some(id) if id == expected_agent_id => {}
Some(id) => reasons.push(format!(
"selfPatch agentId {id:?} does not match this lane; expected {expected_agent_id:?}"
)),
None => reasons.push(format!(
"selfPatch must include agentId {expected_agent_id:?}"
)),
}
match object.get("reason").and_then(serde_json::Value::as_str) {
Some(reason) if reason.trim().len() >= 16 && reason.len() <= 800 => {}
Some(_) => reasons.push(
"selfPatch reason must be a bounded explanation of at least 16 characters".to_string(),
),
None => reasons.push(
"selfPatch must include a reason explaining why this improves the lane".to_string(),
),
}
let allowed = [
"agentId",
"reason",
"evidenceIds",
"semanticMemories",
"episodicMemories",
"relationshipMemories",
"goals",
"values",
"privateNotes",
];
let forbidden = [
"statePatch",
"objective",
"activeSubgoalId",
"subgoals",
"invariants",
"graphs",
"graphFrontier",
"graphCheckpoint",
"scratch",
"investigationCheckpoint",
"jobBindings",
"planning",
"churn",
"mode",
"codeEdits",
"files",
"authorityScope",
"backendJobId",
"rawResult",
];
for key in object.keys() {
if forbidden.contains(&key.as_str()) {
reasons.push(format!(
"selfPatch field {key:?} is project truth or authority; use statePatch, roleAccept, or another explicit control surface instead"
));
} else if !allowed.contains(&key.as_str()) {
reasons.push(format!(
"selfPatch field {key:?} is not part of the bounded memory mutation contract"
));
}
}
let mut mutation_count = 0usize;
mutation_count += review_self_patch_memories(&mut reasons, object, "semanticMemories");
mutation_count += review_self_patch_memories(&mut reasons, object, "episodicMemories");
mutation_count += review_self_patch_memories(&mut reasons, object, "relationshipMemories");
mutation_count += review_self_patch_goals(&mut reasons, object);
mutation_count += review_self_patch_values(&mut reasons, object);
mutation_count += review_self_patch_private_notes(&mut reasons, object);
review_self_patch_string_array(&mut reasons, object, "evidenceIds", 16, 160);
if mutation_count == 0 {
reasons.push(
"selfPatch must contain at least one semantic memory, episodic memory, relationship memory, goal, value, or private note"
.to_string(),
);
}
ThreadEpiphanyRoleSelfPersistenceReview {
status: if reasons.is_empty() {
ThreadEpiphanyRoleSelfPersistenceStatus::Accepted
} else {
ThreadEpiphanyRoleSelfPersistenceStatus::Rejected
status: match review.status {
CoreEpiphanyRoleSelfPersistenceStatus::Missing => {
ThreadEpiphanyRoleSelfPersistenceStatus::Missing
}
CoreEpiphanyRoleSelfPersistenceStatus::Accepted => {
ThreadEpiphanyRoleSelfPersistenceStatus::Accepted
}
CoreEpiphanyRoleSelfPersistenceStatus::Rejected => {
ThreadEpiphanyRoleSelfPersistenceStatus::Rejected
}
},
target_agent_id: Some(expected_agent_id.to_string()),
target_path: Some(target_path.to_string()),
reasons,
}
}
fn review_self_patch_memories(
reasons: &mut Vec<String>,
object: &serde_json::Map<String, serde_json::Value>,
field: &str,
) -> usize {
let Some(value) = object.get(field) else {
return 0;
};
let Some(items) = value.as_array() else {
reasons.push(format!("selfPatch {field} must be an array"));
return 0;
};
if items.len() > 8 {
reasons.push(format!("selfPatch {field} may contain at most 8 records"));
}
let mut valid = 0usize;
for (index, item) in items.iter().enumerate() {
let Some(record) = item.as_object() else {
reasons.push(format!("selfPatch {field}[{index}] must be an object"));
continue;
};
review_self_patch_id(reasons, record, field, index, "memoryId", "mem-");
review_self_patch_summary(reasons, record, field, index, "summary", 600);
review_self_patch_unit(reasons, record, field, index, "salience");
review_self_patch_unit(reasons, record, field, index, "confidence");
valid += 1;
}
valid
}
fn review_self_patch_goals(
reasons: &mut Vec<String>,
object: &serde_json::Map<String, serde_json::Value>,
) -> usize {
let Some(value) = object.get("goals") else {
return 0;
};
let Some(items) = value.as_array() else {
reasons.push("selfPatch goals must be an array".to_string());
return 0;
};
if items.len() > 6 {
reasons.push("selfPatch goals may contain at most 6 records".to_string());
}
let mut valid = 0usize;
for (index, item) in items.iter().enumerate() {
let Some(record) = item.as_object() else {
reasons.push(format!("selfPatch goals[{index}] must be an object"));
continue;
};
review_self_patch_id(reasons, record, "goals", index, "goalId", "goal-");
review_self_patch_summary(reasons, record, "goals", index, "description", 700);
review_self_patch_string(reasons, record, "goals", index, "scope", 80);
review_self_patch_unit(reasons, record, "goals", index, "priority");
review_self_patch_string(reasons, record, "goals", index, "emotionalStake", 400);
review_self_patch_string(reasons, record, "goals", index, "status", 80);
valid += 1;
}
valid
}
fn review_self_patch_values(
reasons: &mut Vec<String>,
object: &serde_json::Map<String, serde_json::Value>,
) -> usize {
let Some(value) = object.get("values") else {
return 0;
};
let Some(items) = value.as_array() else {
reasons.push("selfPatch values must be an array".to_string());
return 0;
};
if items.len() > 6 {
reasons.push("selfPatch values may contain at most 6 records".to_string());
}
let mut valid = 0usize;
for (index, item) in items.iter().enumerate() {
let Some(record) = item.as_object() else {
reasons.push(format!("selfPatch values[{index}] must be an object"));
continue;
};
review_self_patch_id(reasons, record, "values", index, "valueId", "value-");
review_self_patch_summary(reasons, record, "values", index, "label", 240);
review_self_patch_unit(reasons, record, "values", index, "priority");
if !record
.get("unforgivableIfBetrayed")
.is_some_and(serde_json::Value::is_boolean)
{
reasons.push(format!(
"selfPatch values[{index}].unforgivableIfBetrayed must be a boolean"
));
}
valid += 1;
}
valid
}
fn review_self_patch_private_notes(
reasons: &mut Vec<String>,
object: &serde_json::Map<String, serde_json::Value>,
) -> usize {
let Some(value) = object.get("privateNotes") else {
return 0;
};
let Some(items) = value.as_array() else {
reasons.push("selfPatch privateNotes must be an array".to_string());
return 0;
};
if items.len() > 6 {
reasons.push("selfPatch privateNotes may contain at most 6 records".to_string());
}
for (index, item) in items.iter().enumerate() {
match item.as_str() {
Some(text) if !text.trim().is_empty() && text.len() <= 600 => {}
_ => reasons.push(format!(
"selfPatch privateNotes[{index}] must be non-empty text under 600 characters"
)),
}
}
items.len()
}
fn review_self_patch_string_array(
reasons: &mut Vec<String>,
object: &serde_json::Map<String, serde_json::Value>,
field: &str,
max_items: usize,
max_len: usize,
) {
let Some(value) = object.get(field) else {
return;
};
let Some(items) = value.as_array() else {
reasons.push(format!("selfPatch {field} must be an array"));
return;
};
if items.len() > max_items {
reasons.push(format!(
"selfPatch {field} may contain at most {max_items} records"
));
}
for (index, item) in items.iter().enumerate() {
match item.as_str() {
Some(text) if !text.trim().is_empty() && text.len() <= max_len => {}
_ => reasons.push(format!(
"selfPatch {field}[{index}] must be non-empty text under {max_len} characters"
)),
}
}
}
fn review_self_patch_id(
reasons: &mut Vec<String>,
record: &serde_json::Map<String, serde_json::Value>,
collection: &str,
index: usize,
field: &str,
prefix: &str,
) {
match record.get(field).and_then(serde_json::Value::as_str) {
Some(id)
if id.starts_with(prefix)
&& id.len() <= 120
&& id.chars().all(|ch| ch.is_ascii_alphanumeric() || "-_.".contains(ch)) => {}
Some(_) => reasons.push(format!(
"selfPatch {collection}[{index}].{field} must start with {prefix:?}, avoid whitespace, and stay under 120 characters"
)),
None => reasons.push(format!(
"selfPatch {collection}[{index}].{field} is required"
)),
}
}
fn review_self_patch_summary(
reasons: &mut Vec<String>,
record: &serde_json::Map<String, serde_json::Value>,
collection: &str,
index: usize,
field: &str,
max_len: usize,
) {
match record.get(field).and_then(serde_json::Value::as_str) {
Some(text) if !text.trim().is_empty() && text.len() <= max_len => {}
Some(_) => reasons.push(format!(
"selfPatch {collection}[{index}].{field} must be non-empty text under {max_len} characters"
)),
None => reasons.push(format!(
"selfPatch {collection}[{index}].{field} is required"
)),
}
}
fn review_self_patch_string(
reasons: &mut Vec<String>,
record: &serde_json::Map<String, serde_json::Value>,
collection: &str,
index: usize,
field: &str,
max_len: usize,
) {
match record.get(field).and_then(serde_json::Value::as_str) {
Some(text) if !text.trim().is_empty() && text.len() <= max_len => {}
Some(_) => reasons.push(format!(
"selfPatch {collection}[{index}].{field} must be non-empty text under {max_len} characters"
)),
None => reasons.push(format!(
"selfPatch {collection}[{index}].{field} is required"
)),
}
}
fn review_self_patch_unit(
reasons: &mut Vec<String>,
record: &serde_json::Map<String, serde_json::Value>,
collection: &str,
index: usize,
field: &str,
) {
match record.get(field).and_then(serde_json::Value::as_f64) {
Some(value) if (0.0..=1.0).contains(&value) => {}
Some(_) => reasons.push(format!(
"selfPatch {collection}[{index}].{field} must be between 0 and 1"
)),
None => reasons.push(format!(
"selfPatch {collection}[{index}].{field} is required"
)),
}
}
fn modeling_role_state_patch_error(
raw_result: &serde_json::Value,
state_patch: Option<&ThreadEpiphanyUpdatePatch>,
) -> Option<String> {
let Some(value) = raw_result.get("statePatch") else {
return Some("modeling result is not reviewable: missing required statePatch".to_string());
};
let Some(patch) = state_patch else {
return Some(format!(
"modeling result is not reviewable: invalid statePatch ({})",
serde_json::from_value::<ThreadEpiphanyUpdatePatch>(value.clone()).unwrap_err()
));
};
let errors = modeling_role_accept_patch_errors(patch);
if errors.is_empty() {
None
} else {
Some(format!(
"modeling result is not reviewable: {}",
errors.join("; ")
))
}
}
fn imagination_role_state_patch_error(
raw_result: &serde_json::Value,
state_patch: Option<&ThreadEpiphanyUpdatePatch>,
) -> Option<String> {
let Some(value) = raw_result.get("statePatch") else {
return Some(
"imagination result is not reviewable: missing required statePatch".to_string(),
);
};
let Some(patch) = state_patch else {
return Some(format!(
"imagination result is not reviewable: invalid statePatch ({})",
serde_json::from_value::<ThreadEpiphanyUpdatePatch>(value.clone()).unwrap_err()
));
};
let errors = imagination_role_accept_patch_errors(patch);
if errors.is_empty() {
None
} else {
Some(format!(
"imagination result is not reviewable: {}",
errors.join("; ")
))
target_agent_id: review.target_agent_id,
target_path: review.target_path,
reasons: review.reasons,
}
}
@ -15232,142 +14860,13 @@ fn parse_role_finding_state_patch(
}
fn imagination_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec<String> {
let mut errors = Vec::new();
if patch.objective.is_some() {
errors.push(
"objective changes are not allowed through imagination role acceptance".to_string(),
);
}
if patch.active_subgoal_id.is_some() || patch.subgoals.is_some() {
errors.push(
"subgoal changes are not allowed through imagination role acceptance".to_string(),
);
}
if patch.invariants.is_some() {
errors.push(
"invariant changes are not allowed through imagination role acceptance".to_string(),
);
}
if patch.graphs.is_some()
|| patch.graph_frontier.is_some()
|| patch.graph_checkpoint.is_some()
|| patch.investigation_checkpoint.is_some()
{
errors.push(
"graph or checkpoint changes are not allowed through imagination role acceptance"
.to_string(),
);
}
if patch.scratch.is_some() {
errors.push(
"scratch changes are not allowed through imagination role acceptance".to_string(),
);
}
if patch.job_bindings.is_some() {
errors.push(
"job binding changes are not allowed through imagination role acceptance".to_string(),
);
}
if !patch.acceptance_receipts.is_empty() {
errors.push(
"acceptance receipt changes are owned by roleAccept, not worker statePatch".to_string(),
);
}
if !patch.runtime_links.is_empty() {
errors.push(
"runtime link changes are owned by launch/read-back surfaces, not worker statePatch"
.to_string(),
);
}
if patch.churn.is_some() || patch.mode.is_some() {
errors.push(
"churn or mode changes are not allowed through imagination role acceptance".to_string(),
);
}
let Some(planning) = patch.planning.as_ref() else {
errors.push("statePatch must include planning changes".to_string());
return errors;
};
if planning.objective_drafts.is_empty() {
errors.push("planning patch must include at least one objective draft".to_string());
}
if !planning
.objective_drafts
.iter()
.any(|draft| draft.status.eq_ignore_ascii_case("draft"))
{
errors.push(
"planning patch must include at least one objective draft with status draft"
.to_string(),
);
}
for draft in &planning.objective_drafts {
if draft.acceptance_criteria.is_empty() {
errors.push(format!(
"planning objective draft {:?} must include acceptance criteria",
draft.id
));
}
if draft.review_gates.is_empty() {
errors.push(format!(
"planning objective draft {:?} must include review gates",
draft.id
));
}
}
errors
let value = serde_json::to_value(patch).unwrap_or_else(|_| serde_json::Value::Null);
imagination_role_state_patch_policy_errors(&value)
}
fn modeling_role_accept_patch_errors(patch: &ThreadEpiphanyUpdatePatch) -> Vec<String> {
let mut errors = Vec::new();
if patch.objective.is_some() {
errors
.push("objective changes are not allowed through modeling role acceptance".to_string());
}
if patch.active_subgoal_id.is_some() || patch.subgoals.is_some() {
errors.push("subgoal changes are not allowed through modeling role acceptance".to_string());
}
if patch.invariants.is_some() {
errors
.push("invariant changes are not allowed through modeling role acceptance".to_string());
}
if patch.job_bindings.is_some() {
errors.push(
"job binding changes are not allowed through modeling role acceptance".to_string(),
);
}
if !patch.acceptance_receipts.is_empty() {
errors.push(
"acceptance receipt changes are owned by roleAccept, not worker statePatch".to_string(),
);
}
if !patch.runtime_links.is_empty() {
errors.push(
"runtime link changes are owned by launch/read-back surfaces, not worker statePatch"
.to_string(),
);
}
if patch.planning.is_some() {
errors
.push("planning changes are not allowed through modeling role acceptance".to_string());
}
if patch.churn.is_some() || patch.mode.is_some() {
errors.push(
"churn or mode changes are not allowed through modeling role acceptance".to_string(),
);
}
if patch.graphs.is_none()
&& patch.graph_frontier.is_none()
&& patch.graph_checkpoint.is_none()
&& patch.scratch.is_none()
&& patch.investigation_checkpoint.is_none()
{
errors.push(
"statePatch must include a modeling field: graphs, graphFrontier, graphCheckpoint, scratch, or investigationCheckpoint"
.to_string(),
);
}
errors
let value = serde_json::to_value(patch).unwrap_or_else(|_| serde_json::Value::Null);
modeling_role_state_patch_policy_errors(&value)
}
fn role_finding_summary(finding: &ThreadEpiphanyRoleFinding) -> String {