2026-05-13 06:51:28 +01:00
use chrono ::SecondsFormat ;
use chrono ::Utc ;
2026-05-19 10:18:27 +01:00
use std ::path ::Path ;
2026-05-19 14:56:46 +01:00
use std ::path ::PathBuf ;
2026-05-19 10:18:27 +01:00
2026-05-17 21:01:26 +01:00
use epiphany_core ::EpiphanyJobInterruptRequest ;
2026-05-19 10:18:27 +01:00
use epiphany_core ::EpiphanyJobInterruptResult ;
2026-05-17 21:01:26 +01:00
use epiphany_core ::EpiphanyJobLaunchRequest ;
2026-05-19 10:18:27 +01:00
use epiphany_core ::EpiphanyJobLaunchResult ;
2026-05-19 16:42:58 +01:00
use epiphany_core ::EpiphanyJobView ;
2026-05-14 08:57:31 +01:00
use epiphany_core ::EpiphanyPromotionInput ;
2026-05-19 17:08:10 +01:00
use epiphany_core ::EpiphanyReorientDecision ;
2026-05-20 02:26:04 +01:00
use epiphany_core ::EpiphanyReorientFindingInterpretation ;
2026-05-19 17:08:10 +01:00
use epiphany_core ::EpiphanyReorientStateStatus ;
2026-05-20 02:26:04 +01:00
use epiphany_core ::EpiphanyRoleFindingInterpretation ;
2026-05-20 02:44:47 +01:00
use epiphany_core ::EpiphanyRoleResultRoleId ;
2026-05-20 02:26:04 +01:00
use epiphany_core ::EpiphanyRoleStatePatchDocument ;
2026-05-19 10:18:27 +01:00
use epiphany_core ::EpiphanyStateUpdate ;
2026-05-20 02:37:10 +01:00
use epiphany_core ::EpiphanyStateUpdatedField ;
2026-05-19 15:33:45 +01:00
use epiphany_core ::EpiphanyTokenUsageSnapshot ;
2026-05-19 10:18:27 +01:00
use epiphany_core ::RuntimeSpineHeartbeatJobOptions ;
use epiphany_core ::RuntimeSpineHeartbeatLaunchPlanOptions ;
use epiphany_core ::apply_epiphany_state_update ;
use epiphany_core ::clear_epiphany_job_binding_backend ;
use epiphany_core ::epiphany_state_update_validation_errors ;
2026-05-14 08:57:31 +01:00
use epiphany_core ::evaluate_promotion ;
2026-05-19 10:18:27 +01:00
use epiphany_core ::open_runtime_spine_heartbeat_job ;
use epiphany_core ::plan_runtime_spine_heartbeat_launch ;
use epiphany_core ::replace_or_append_epiphany_job_binding ;
2026-05-19 15:24:57 +01:00
use epiphany_state_model ::EpiphanyEvidenceRecord ;
use epiphany_state_model ::EpiphanyJobKind as CoreEpiphanyJobKind ;
use epiphany_state_model ::EpiphanyRetrievalState ;
use epiphany_state_model ::EpiphanyThreadState ;
2026-05-13 06:42:57 +01:00
2026-05-20 02:46:58 +01:00
use crate ::cultnet ::EpiphanySurfaceSource ;
2026-05-19 15:38:31 +01:00
use crate ::error ::EpiphanyBridgeError ;
use crate ::error ::Result as BridgeResult ;
2026-05-19 16:42:58 +01:00
use crate ::jobs ::derive_epiphany_jobs ;
2026-05-20 01:39:27 +01:00
use crate ::jobs ::epiphany_blocked_state_job ;
2026-05-13 06:55:37 +01:00
use crate ::jobs ::map_interrupted_epiphany_job ;
use crate ::jobs ::map_launched_epiphany_job ;
2026-05-13 06:59:58 +01:00
use crate ::launch ::EPIPHANY_REORIENT_LAUNCH_BINDING_ID ;
use crate ::launch ::build_epiphany_reorient_launch_request ;
2026-05-13 06:55:37 +01:00
use crate ::launch ::build_epiphany_role_launch_request ;
use crate ::launch ::epiphany_role_label ;
2026-05-13 06:51:28 +01:00
use crate ::mutation ::build_reorient_acceptance_update ;
use crate ::mutation ::build_role_acceptance_update ;
2026-05-13 06:55:37 +01:00
use crate ::mutation ::epiphany_job_launch_changed_fields ;
2026-05-13 06:42:57 +01:00
use crate ::mutation ::epiphany_promote_changed_fields ;
use crate ::mutation ::epiphany_update_patch_changed_fields ;
use crate ::mutation ::thread_epiphany_patch_has_state_replacements ;
2026-05-19 16:47:28 +01:00
use crate ::pressure ::derive_epiphany_pressure ;
2026-05-13 06:59:58 +01:00
use crate ::reorient ::EpiphanyFreshnessWatcherSnapshot ;
2026-05-19 16:58:37 +01:00
use crate ::reorient ::derive_epiphany_freshness_view ;
2026-05-19 17:05:26 +01:00
use crate ::reorient ::derive_epiphany_reorient ;
2026-05-20 01:39:27 +01:00
use crate ::runtime_results ::load_completed_core_epiphany_reorient_finding ;
use crate ::runtime_results ::load_completed_core_epiphany_role_finding ;
2026-05-13 06:51:28 +01:00
use uuid ::Uuid ;
2026-05-13 06:42:57 +01:00
2026-05-19 14:56:46 +01:00
#[ allow(async_fn_in_trait) ]
pub trait EpiphanyMutationHost {
async fn epiphany_state ( & self ) -> Option < EpiphanyThreadState > ;
async fn epiphany_reference_turn_id ( & self ) -> Option < String > ;
async fn epiphany_persist_state (
& self ,
next_state : EpiphanyThreadState ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyThreadState > ;
2026-05-19 14:56:46 +01:00
async fn epiphany_runtime_spine_store_path ( & self ) -> PathBuf ;
async fn client_visible_epiphany_state (
& self ,
fallback : EpiphanyThreadState ,
) -> EpiphanyThreadState ;
}
2026-05-13 06:42:57 +01:00
#[ derive(Debug, Clone) ]
pub struct EpiphanyThreadUpdateApplied {
pub revision : u64 ,
2026-05-20 02:37:10 +01:00
pub changed_fields : Vec < EpiphanyStateUpdatedField > ,
2026-05-13 06:42:57 +01:00
pub epiphany_state : EpiphanyThreadState ,
}
#[ derive(Debug, Clone) ]
pub enum EpiphanyThreadPromoteApplied {
Rejected { reasons : Vec < String > } ,
Accepted ( EpiphanyThreadUpdateApplied ) ,
}
2026-05-13 06:51:28 +01:00
#[ derive(Debug, Clone) ]
pub struct EpiphanyRoleAcceptApplied {
pub revision : u64 ,
2026-05-20 02:37:10 +01:00
pub changed_fields : Vec < EpiphanyStateUpdatedField > ,
2026-05-13 06:51:28 +01:00
pub epiphany_state : EpiphanyThreadState ,
pub accepted_receipt_id : String ,
pub accepted_observation_id : String ,
pub accepted_evidence_id : String ,
2026-05-20 02:26:04 +01:00
pub applied_patch : EpiphanyRoleStatePatchDocument ,
pub finding : EpiphanyRoleFindingInterpretation ,
2026-05-13 06:51:28 +01:00
}
#[ derive(Debug, Clone) ]
pub struct EpiphanyReorientAcceptApplied {
pub revision : u64 ,
2026-05-20 02:37:10 +01:00
pub changed_fields : Vec < EpiphanyStateUpdatedField > ,
2026-05-13 06:51:28 +01:00
pub epiphany_state : EpiphanyThreadState ,
pub accepted_receipt_id : String ,
pub accepted_observation_id : String ,
pub accepted_evidence_id : String ,
2026-05-20 02:26:04 +01:00
pub finding : EpiphanyReorientFindingInterpretation ,
2026-05-13 06:51:28 +01:00
}
2026-05-13 06:55:37 +01:00
#[ derive(Debug, Clone) ]
pub struct EpiphanyJobLaunchApplied {
2026-05-19 16:42:58 +01:00
pub launcher_job_id : String ,
pub backend_job_id : String ,
2026-05-13 06:55:37 +01:00
pub revision : u64 ,
2026-05-20 02:37:10 +01:00
pub changed_fields : Vec < EpiphanyStateUpdatedField > ,
2026-05-13 06:55:37 +01:00
pub epiphany_state : EpiphanyThreadState ,
2026-05-19 16:42:58 +01:00
pub job : EpiphanyJobView ,
2026-05-13 06:55:37 +01:00
}
#[ derive(Debug, Clone) ]
pub struct EpiphanyJobInterruptApplied {
pub cancel_requested : bool ,
pub interrupted_thread_ids : Vec < String > ,
pub revision : u64 ,
2026-05-20 02:37:10 +01:00
pub changed_fields : Vec < EpiphanyStateUpdatedField > ,
2026-05-13 06:55:37 +01:00
pub epiphany_state : EpiphanyThreadState ,
2026-05-19 16:42:58 +01:00
pub job : EpiphanyJobView ,
2026-05-13 06:55:37 +01:00
}
2026-05-13 06:59:58 +01:00
#[ derive(Debug, Clone) ]
pub struct EpiphanyReorientLaunchApplied {
2026-05-19 16:42:58 +01:00
pub launcher_job_id : String ,
pub backend_job_id : String ,
2026-05-20 02:46:58 +01:00
pub source : EpiphanySurfaceSource ,
2026-05-19 17:08:10 +01:00
pub state_status : EpiphanyReorientStateStatus ,
2026-05-13 06:59:58 +01:00
pub state_revision : Option < u64 > ,
2026-05-19 17:08:10 +01:00
pub decision : EpiphanyReorientDecision ,
2026-05-13 06:59:58 +01:00
pub revision : u64 ,
2026-05-20 02:37:10 +01:00
pub changed_fields : Vec < EpiphanyStateUpdatedField > ,
2026-05-13 06:59:58 +01:00
pub epiphany_state : EpiphanyThreadState ,
2026-05-19 16:42:58 +01:00
pub job : EpiphanyJobView ,
2026-05-13 06:59:58 +01:00
}
2026-05-19 10:18:27 +01:00
pub async fn apply_epiphany_state_update_to_thread (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-19 10:18:27 +01:00
update : EpiphanyStateUpdate ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyThreadState > {
2026-05-19 14:18:42 +01:00
let current_state = thread . epiphany_state ( ) . await . unwrap_or_default ( ) ;
let reference_turn_id = thread . epiphany_reference_turn_id ( ) . await ;
let next_state =
apply_epiphany_state_update_to_state ( & current_state , update , reference_turn_id ) ? ;
thread . epiphany_persist_state ( next_state ) . await
}
pub fn apply_epiphany_state_update_to_state (
current_state : & EpiphanyThreadState ,
update : EpiphanyStateUpdate ,
reference_turn_id : Option < String > ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyThreadState > {
2026-05-19 10:18:27 +01:00
if update . is_empty ( ) {
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest (
2026-05-19 10:18:27 +01:00
" epiphany update patch must contain at least one mutation " . to_string ( ) ,
) ) ;
}
2026-05-19 14:18:42 +01:00
let mut next_state = current_state . clone ( ) ;
2026-05-19 10:18:27 +01:00
if let Some ( expected_revision ) = update . expected_revision
& & next_state . revision ! = expected_revision
{
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest ( format! (
2026-05-19 10:18:27 +01:00
" epiphany state revision mismatch: expected {expected_revision}, found {} " ,
next_state . revision
) ) ) ;
}
let validation_errors = epiphany_state_update_validation_errors ( & next_state , & update ) ;
if ! validation_errors . is_empty ( ) {
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest ( format! (
2026-05-19 10:18:27 +01:00
" invalid epiphany update patch: {} " ,
validation_errors . join ( " ; " )
) ) ) ;
}
apply_epiphany_state_update ( & mut next_state , update , reference_turn_id ) ;
2026-05-19 14:18:42 +01:00
Ok ( next_state )
2026-05-19 10:18:27 +01:00
}
pub async fn launch_epiphany_job_on_thread (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-19 10:18:27 +01:00
request : EpiphanyJobLaunchRequest ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyJobLaunchResult > {
2026-05-19 10:18:27 +01:00
let current_state = thread . epiphany_state ( ) . await . unwrap_or_default ( ) ;
validate_expected_revision ( request . expected_revision , current_state . revision ) ? ;
let launcher_job_id = format! ( " epiphany-heartbeat-launch- {} " , Uuid ::new_v4 ( ) ) ;
let backend_job_id = Uuid ::new_v4 ( ) . to_string ( ) ;
let launch_plan = plan_runtime_spine_heartbeat_launch (
& current_state ,
RuntimeSpineHeartbeatLaunchPlanOptions {
binding_id : request . binding_id . clone ( ) ,
kind : request . kind ,
scope : request . scope . clone ( ) ,
owner_role : request . owner_role . clone ( ) ,
authority_scope : request . authority_scope . clone ( ) ,
linked_subgoal_ids : request . linked_subgoal_ids . clone ( ) ,
linked_graph_node_ids : request . linked_graph_node_ids . clone ( ) ,
instruction : request . instruction . clone ( ) ,
launch_document : request . launch_document . clone ( ) ,
output_contract_id : request . output_contract_id . clone ( ) ,
max_runtime_seconds : request . max_runtime_seconds ,
runtime_job_id : backend_job_id . clone ( ) ,
} ,
)
2026-05-19 15:38:31 +01:00
. map_err ( | err | EpiphanyBridgeError ::InvalidRequest ( err . to_string ( ) ) ) ? ;
2026-05-19 10:18:27 +01:00
let runtime_store = thread . epiphany_runtime_spine_store_path ( ) . await ;
open_epiphany_runtime_spine_job (
runtime_store . as_path ( ) ,
& current_state ,
& request ,
backend_job_id . as_str ( ) ,
) ? ;
let next_job_bindings = replace_or_append_epiphany_job_binding (
current_state . job_bindings . clone ( ) ,
launch_plan . binding ,
) ;
let validation_errors = epiphany_state_update_validation_errors (
& current_state ,
& EpiphanyStateUpdate {
job_bindings : Some ( next_job_bindings . clone ( ) ) ,
runtime_links : vec ! [ launch_plan . runtime_link . clone ( ) ] ,
.. Default ::default ( )
} ,
) ;
if ! validation_errors . is_empty ( ) {
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest ( format! (
2026-05-19 10:18:27 +01:00
" invalid Epiphany job launch patch: {} " ,
validation_errors . join ( " ; " )
) ) ) ;
}
let epiphany_state = apply_epiphany_state_update_to_thread (
thread ,
EpiphanyStateUpdate {
expected_revision : request . expected_revision ,
job_bindings : Some ( next_job_bindings ) ,
runtime_links : vec ! [ launch_plan . runtime_link ] ,
.. Default ::default ( )
} ,
)
. await ? ;
Ok ( EpiphanyJobLaunchResult {
epiphany_state ,
binding_id : request . binding_id ,
launcher_job_id ,
backend_job_id ,
} )
}
pub async fn interrupt_epiphany_job_on_thread (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-19 10:18:27 +01:00
request : EpiphanyJobInterruptRequest ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyJobInterruptResult > {
2026-05-19 10:18:27 +01:00
if request . binding_id . trim ( ) . is_empty ( ) {
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest (
2026-05-19 10:18:27 +01:00
" epiphany job interrupt binding_id must be non-empty " . to_string ( ) ,
) ) ;
}
let current_state = thread . epiphany_state ( ) . await . unwrap_or_default ( ) ;
validate_expected_revision ( request . expected_revision , current_state . revision ) ? ;
let Some ( binding_index ) = current_state
. job_bindings
. iter ( )
. position ( | binding | binding . id = = request . binding_id )
else {
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest ( format! (
2026-05-19 10:18:27 +01:00
" epiphany job binding {:?} was not found " ,
request . binding_id
) ) ) ;
} ;
let interrupted_thread_ids = Vec ::new ( ) ;
let cancel_requested = false ;
let next_job_bindings = clear_epiphany_job_binding_backend (
current_state . job_bindings . clone ( ) ,
binding_index ,
" No active heartbeat turn is currently bound; launch explicitly to resume specialist work. " ,
) ;
let epiphany_state = apply_epiphany_state_update_to_thread (
thread ,
EpiphanyStateUpdate {
expected_revision : request . expected_revision ,
job_bindings : Some ( next_job_bindings ) ,
.. Default ::default ( )
} ,
)
. await ? ;
Ok ( EpiphanyJobInterruptResult {
epiphany_state ,
binding_id : request . binding_id ,
cancel_requested ,
interrupted_thread_ids ,
} )
}
2026-05-13 06:42:57 +01:00
pub async fn apply_thread_epiphany_update (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-13 06:42:57 +01:00
expected_revision : Option < u64 > ,
2026-05-20 02:28:52 +01:00
patch : EpiphanyRoleStatePatchDocument ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyThreadUpdateApplied > {
2026-05-20 02:28:52 +01:00
let changed_fields = epiphany_update_patch_changed_fields (
& crate ::mutation ::protocol_patch_from_core ( patch . clone ( ) ) ,
) ;
let update = crate ::mutation ::state_update_from_core_patch ( expected_revision , patch ) ;
2026-05-19 10:18:27 +01:00
let epiphany_state = apply_epiphany_state_update_to_thread ( thread , update ) . await ? ;
2026-05-19 14:56:46 +01:00
let epiphany_state = thread . client_visible_epiphany_state ( epiphany_state ) . await ;
2026-05-13 06:42:57 +01:00
Ok ( EpiphanyThreadUpdateApplied {
revision : epiphany_state . revision ,
changed_fields ,
epiphany_state ,
} )
}
pub async fn apply_thread_epiphany_promote (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-13 06:42:57 +01:00
expected_revision : Option < u64 > ,
2026-05-20 02:28:52 +01:00
patch : EpiphanyRoleStatePatchDocument ,
2026-05-13 06:42:57 +01:00
verifier_evidence : EpiphanyEvidenceRecord ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyThreadPromoteApplied > {
2026-05-13 06:42:57 +01:00
let decision = evaluate_promotion ( EpiphanyPromotionInput {
has_state_replacements : thread_epiphany_patch_has_state_replacements ( & patch ) ,
active_subgoal_id : patch . active_subgoal_id . clone ( ) ,
subgoals : patch . subgoals . clone ( ) ,
invariants : patch . invariants . clone ( ) ,
graphs : patch . graphs . clone ( ) ,
graph_frontier : patch . graph_frontier . clone ( ) ,
graph_checkpoint : patch . graph_checkpoint . clone ( ) ,
investigation_checkpoint : patch . investigation_checkpoint . clone ( ) ,
churn : patch . churn . clone ( ) ,
observations : patch . observations . clone ( ) ,
evidence : patch . evidence . clone ( ) ,
verifier_evidence : verifier_evidence . clone ( ) ,
} ) ;
if ! decision . accepted {
return Ok ( EpiphanyThreadPromoteApplied ::Rejected {
reasons : decision . reasons ,
} ) ;
}
let changed_fields = epiphany_promote_changed_fields ( & patch ) ;
let mut patch = patch ;
patch . evidence . push ( verifier_evidence ) ;
2026-05-20 02:28:52 +01:00
let update = crate ::mutation ::state_update_from_core_patch ( expected_revision , patch ) ;
2026-05-19 10:18:27 +01:00
let epiphany_state = apply_epiphany_state_update_to_thread ( thread , update ) . await ? ;
2026-05-19 14:56:46 +01:00
let epiphany_state = thread . client_visible_epiphany_state ( epiphany_state ) . await ;
2026-05-13 06:42:57 +01:00
Ok ( EpiphanyThreadPromoteApplied ::Accepted (
EpiphanyThreadUpdateApplied {
revision : epiphany_state . revision ,
changed_fields ,
epiphany_state ,
} ,
) )
}
2026-05-13 06:51:28 +01:00
pub async fn apply_thread_epiphany_role_accept (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-20 02:44:47 +01:00
role_id : EpiphanyRoleResultRoleId ,
2026-05-13 06:51:28 +01:00
expected_revision : Option < u64 > ,
binding_id : & str ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyRoleAcceptApplied > {
2026-05-13 06:51:28 +01:00
let state = thread . epiphany_state ( ) . await . ok_or_else ( | | {
2026-05-19 15:38:31 +01:00
EpiphanyBridgeError ::InvalidRequest (
2026-05-13 06:51:28 +01:00
" cannot accept an Epiphany role finding without authoritative Epiphany state "
. to_string ( ) ,
)
} ) ? ;
validate_expected_revision ( expected_revision , state . revision ) ? ;
2026-05-19 13:51:25 +01:00
let runtime_store_path = thread . epiphany_runtime_spine_store_path ( ) . await ;
2026-05-20 01:39:27 +01:00
let finding = load_completed_core_epiphany_role_finding (
2026-05-19 13:51:25 +01:00
Some ( runtime_store_path . as_path ( ) ) ,
& state ,
role_id ,
binding_id ,
) ? ;
2026-05-13 06:51:28 +01:00
let accepted_prefix = epiphany_role_label ( role_id ) ;
let acceptance_update = build_role_acceptance_update (
2026-05-20 02:08:53 +01:00
expected_revision ,
2026-05-13 06:51:28 +01:00
role_id ,
binding_id ,
& finding ,
format! ( " ev- {accepted_prefix} - {} " , Uuid ::new_v4 ( ) ) ,
format! ( " obs- {accepted_prefix} - {} " , Uuid ::new_v4 ( ) ) ,
Utc ::now ( ) . to_rfc3339_opts ( SecondsFormat ::Secs , true ) ,
)
2026-05-19 15:38:31 +01:00
. map_err ( EpiphanyBridgeError ::InvalidRequest ) ? ;
2026-05-13 06:51:28 +01:00
let accepted_receipt_id = acceptance_update . accepted_receipt_id . clone ( ) ;
let accepted_observation_id = acceptance_update . accepted_observation_id . clone ( ) ;
let accepted_evidence_id = acceptance_update . accepted_evidence_id . clone ( ) ;
let changed_fields = acceptance_update . changed_fields . clone ( ) ;
2026-05-20 02:08:53 +01:00
let applied_patch = acceptance_update . applied_patch . clone ( ) ;
let epiphany_state =
apply_epiphany_state_update_to_thread ( thread , acceptance_update . state_update ) . await ? ;
2026-05-19 14:56:46 +01:00
let epiphany_state = thread . client_visible_epiphany_state ( epiphany_state ) . await ;
2026-05-13 06:51:28 +01:00
Ok ( EpiphanyRoleAcceptApplied {
revision : epiphany_state . revision ,
changed_fields ,
epiphany_state ,
accepted_receipt_id ,
accepted_observation_id ,
accepted_evidence_id ,
applied_patch ,
2026-05-20 02:26:04 +01:00
finding ,
2026-05-13 06:51:28 +01:00
} )
}
pub async fn apply_thread_epiphany_reorient_accept (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-13 06:51:28 +01:00
expected_revision : Option < u64 > ,
binding_id : & str ,
update_scratch : bool ,
update_investigation_checkpoint : bool ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyReorientAcceptApplied > {
2026-05-13 06:51:28 +01:00
let state = thread . epiphany_state ( ) . await . ok_or_else ( | | {
2026-05-19 15:38:31 +01:00
EpiphanyBridgeError ::InvalidRequest (
2026-05-13 06:51:28 +01:00
" cannot accept a reorientation finding without authoritative Epiphany state "
. to_string ( ) ,
)
} ) ? ;
validate_expected_revision ( expected_revision , state . revision ) ? ;
if update_investigation_checkpoint & & state . investigation_checkpoint . is_none ( ) {
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest (
2026-05-13 06:51:28 +01:00
" cannot update investigation checkpoint because this thread has no durable checkpoint "
. to_string ( ) ,
) ) ;
}
2026-05-19 13:51:25 +01:00
let runtime_store_path = thread . epiphany_runtime_spine_store_path ( ) . await ;
2026-05-20 01:39:27 +01:00
let finding = load_completed_core_epiphany_reorient_finding (
2026-05-19 13:51:25 +01:00
Some ( runtime_store_path . as_path ( ) ) ,
& state ,
binding_id ,
) ? ;
2026-05-13 06:51:28 +01:00
let acceptance_update = build_reorient_acceptance_update (
expected_revision ,
binding_id ,
& finding ,
format! ( " ev-reorient- {} " , Uuid ::new_v4 ( ) ) ,
format! ( " obs-reorient- {} " , Uuid ::new_v4 ( ) ) ,
Utc ::now ( ) . to_rfc3339_opts ( SecondsFormat ::Secs , true ) ,
update_scratch ,
update_investigation_checkpoint ,
state . investigation_checkpoint . clone ( ) ,
)
2026-05-19 15:38:31 +01:00
. map_err ( EpiphanyBridgeError ::InvalidRequest ) ? ;
2026-05-13 06:51:28 +01:00
let accepted_receipt_id = acceptance_update . accepted_receipt_id . clone ( ) ;
let accepted_observation_id = acceptance_update . accepted_observation_id . clone ( ) ;
let accepted_evidence_id = acceptance_update . accepted_evidence_id . clone ( ) ;
let changed_fields = acceptance_update . changed_fields . clone ( ) ;
2026-05-19 10:18:27 +01:00
let epiphany_state =
apply_epiphany_state_update_to_thread ( thread , acceptance_update . state_update ) . await ? ;
2026-05-19 14:56:46 +01:00
let epiphany_state = thread . client_visible_epiphany_state ( epiphany_state ) . await ;
2026-05-13 06:51:28 +01:00
Ok ( EpiphanyReorientAcceptApplied {
revision : epiphany_state . revision ,
changed_fields ,
epiphany_state ,
accepted_receipt_id ,
accepted_observation_id ,
accepted_evidence_id ,
2026-05-20 02:26:04 +01:00
finding ,
2026-05-13 06:51:28 +01:00
} )
}
2026-05-13 06:55:37 +01:00
pub async fn launch_thread_epiphany_role (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-13 06:55:37 +01:00
thread_id : & str ,
2026-05-20 02:44:47 +01:00
role_id : EpiphanyRoleResultRoleId ,
2026-05-13 06:55:37 +01:00
expected_revision : Option < u64 > ,
max_runtime_seconds : Option < u64 > ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyJobLaunchApplied > {
2026-05-13 06:55:37 +01:00
let state = thread . epiphany_state ( ) . await . ok_or_else ( | | {
2026-05-19 15:38:31 +01:00
EpiphanyBridgeError ::InvalidRequest (
2026-05-13 06:55:37 +01:00
" cannot launch an Epiphany role specialist without authoritative Epiphany state "
. to_string ( ) ,
)
} ) ? ;
let launch_request = build_epiphany_role_launch_request (
thread_id ,
role_id ,
expected_revision ,
max_runtime_seconds ,
& state ,
)
2026-05-19 15:38:31 +01:00
. map_err ( EpiphanyBridgeError ::InvalidRequest ) ? ;
2026-05-13 06:55:37 +01:00
launch_thread_epiphany_job (
thread ,
launch_request ,
CoreEpiphanyJobKind ::Specialist ,
" missing launched role projection " ,
)
. await
}
pub async fn launch_thread_epiphany_job (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-13 06:55:37 +01:00
launch_request : EpiphanyJobLaunchRequest ,
kind : CoreEpiphanyJobKind ,
missing_projection_reason : & str ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyJobLaunchApplied > {
2026-05-13 06:55:37 +01:00
let changed_fields = epiphany_job_launch_changed_fields ( ) ;
2026-05-19 10:18:27 +01:00
let launched = launch_epiphany_job_on_thread ( thread , launch_request ) . await ? ;
2026-05-19 14:56:46 +01:00
let epiphany_state = thread
. client_visible_epiphany_state ( launched . epiphany_state )
. await ;
2026-05-13 06:55:37 +01:00
let job = map_launched_epiphany_job (
& epiphany_state ,
launched . binding_id . as_str ( ) ,
launched . backend_job_id . as_str ( ) ,
kind ,
missing_projection_reason ,
) ;
Ok ( EpiphanyJobLaunchApplied {
2026-05-19 16:42:58 +01:00
launcher_job_id : launched . launcher_job_id ,
backend_job_id : launched . backend_job_id ,
2026-05-13 06:55:37 +01:00
revision : epiphany_state . revision ,
changed_fields ,
epiphany_state ,
job ,
} )
}
pub async fn interrupt_thread_epiphany_job (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-13 06:55:37 +01:00
expected_revision : Option < u64 > ,
binding_id : & str ,
reason : Option < String > ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyJobInterruptApplied > {
2026-05-20 02:37:10 +01:00
let changed_fields = vec! [ EpiphanyStateUpdatedField ::JobBindings ] ;
2026-05-19 10:18:27 +01:00
let interrupted = interrupt_epiphany_job_on_thread (
thread ,
EpiphanyJobInterruptRequest {
2026-05-13 06:55:37 +01:00
expected_revision ,
binding_id : binding_id . to_string ( ) ,
reason ,
2026-05-19 10:18:27 +01:00
} ,
)
. await ? ;
2026-05-19 14:56:46 +01:00
let epiphany_state = thread
. client_visible_epiphany_state ( interrupted . epiphany_state )
. await ;
2026-05-13 06:55:37 +01:00
let job = map_interrupted_epiphany_job ( & epiphany_state , binding_id ) ;
Ok ( EpiphanyJobInterruptApplied {
cancel_requested : interrupted . cancel_requested ,
interrupted_thread_ids : interrupted . interrupted_thread_ids ,
revision : epiphany_state . revision ,
changed_fields ,
epiphany_state ,
job ,
} )
}
2026-05-13 06:59:58 +01:00
pub async fn launch_thread_epiphany_reorient (
2026-05-19 14:56:46 +01:00
thread : & impl EpiphanyMutationHost ,
2026-05-13 06:59:58 +01:00
thread_id : & str ,
expected_revision : Option < u64 > ,
max_runtime_seconds : Option < u64 > ,
state : Option < & EpiphanyThreadState > ,
retrieval_override : Option < & EpiphanyRetrievalState > ,
watcher_snapshot : Option < EpiphanyFreshnessWatcherSnapshot < '_ > > ,
2026-05-19 15:33:45 +01:00
token_usage_info : Option < & EpiphanyTokenUsageSnapshot > ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < EpiphanyReorientLaunchApplied > {
2026-05-19 16:58:37 +01:00
let freshness = derive_epiphany_freshness_view ( state , retrieval_override , watcher_snapshot ) ;
let state_revision = freshness . state_revision ;
2026-05-19 16:47:28 +01:00
let pressure = derive_epiphany_pressure ( token_usage_info ) ;
2026-05-19 17:08:10 +01:00
let ( state_status , decision ) = derive_epiphany_reorient (
2026-05-19 17:05:26 +01:00
state ,
& pressure ,
& freshness . retrieval ,
& freshness . graph ,
& freshness . watcher ,
) ;
2026-05-13 06:59:58 +01:00
let state = state . ok_or_else ( | | {
2026-05-19 15:38:31 +01:00
EpiphanyBridgeError ::InvalidRequest ( format! (
2026-05-13 06:59:58 +01:00
" cannot launch a reorientation worker without authoritative Epiphany state: {} " ,
decision . note
) )
} ) ? ;
let checkpoint = state . investigation_checkpoint . as_ref ( ) . ok_or_else ( | | {
2026-05-19 15:38:31 +01:00
EpiphanyBridgeError ::InvalidRequest ( format! (
2026-05-13 06:59:58 +01:00
" cannot launch a reorientation worker without a durable investigation checkpoint: {} " ,
decision . note
) )
} ) ? ;
let launch_request = build_epiphany_reorient_launch_request (
thread_id ,
expected_revision ,
max_runtime_seconds ,
state ,
checkpoint ,
2026-05-19 17:08:10 +01:00
& decision ,
2026-05-13 06:59:58 +01:00
) ;
let changed_fields = epiphany_job_launch_changed_fields ( ) ;
2026-05-19 10:18:27 +01:00
let launched = launch_epiphany_job_on_thread ( thread , launch_request ) . await ? ;
2026-05-19 14:56:46 +01:00
let epiphany_state = thread
. client_visible_epiphany_state ( launched . epiphany_state )
. await ;
2026-05-19 16:42:58 +01:00
let job = derive_epiphany_jobs ( Some ( & epiphany_state ) , None )
2026-05-13 06:59:58 +01:00
. into_iter ( )
. find ( | job | job . id = = EPIPHANY_REORIENT_LAUNCH_BINDING_ID )
. unwrap_or_else ( | | {
epiphany_blocked_state_job (
EPIPHANY_REORIENT_LAUNCH_BINDING_ID ,
2026-05-19 16:42:58 +01:00
CoreEpiphanyJobKind ::Specialist ,
2026-05-13 06:59:58 +01:00
" reorient-guided checkpoint regather " ,
" Launched reorientation worker was not reflected in Epiphany state. " ,
)
} ) ;
Ok ( EpiphanyReorientLaunchApplied {
2026-05-19 16:42:58 +01:00
launcher_job_id : launched . launcher_job_id ,
backend_job_id : launched . backend_job_id ,
2026-05-20 02:46:58 +01:00
source : EpiphanySurfaceSource ::Live ,
2026-05-13 06:59:58 +01:00
state_status ,
state_revision ,
decision ,
revision : epiphany_state . revision ,
changed_fields ,
epiphany_state ,
job ,
} )
}
2026-05-19 10:18:27 +01:00
fn open_epiphany_runtime_spine_job (
store_path : & Path ,
state : & EpiphanyThreadState ,
request : & EpiphanyJobLaunchRequest ,
backend_job_id : & str ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < ( ) > {
2026-05-19 10:18:27 +01:00
let now = Utc ::now ( ) . to_rfc3339_opts ( SecondsFormat ::Secs , true ) ;
open_runtime_spine_heartbeat_job (
store_path ,
RuntimeSpineHeartbeatJobOptions {
runtime_id : " epiphany-local " . to_string ( ) ,
display_name : " Epiphany Local " . to_string ( ) ,
session_id : " epiphany-main " . to_string ( ) ,
objective : state
. objective
. clone ( )
. filter ( | objective | ! objective . trim ( ) . is_empty ( ) )
. unwrap_or_else ( | | " Epiphany heartbeat activation " . to_string ( ) ) ,
coordinator_note : " App-server launch opened this typed runtime session. " . to_string ( ) ,
job_id : backend_job_id . to_string ( ) ,
role : request . owner_role . clone ( ) ,
binding_id : request . binding_id . clone ( ) ,
authority_scope : request . authority_scope . clone ( ) ,
instruction : request . instruction . clone ( ) ,
launch_document : request . launch_document . clone ( ) ,
output_contract_id : request . output_contract_id . clone ( ) ,
created_at : now ,
} ,
)
. map_err ( | err | {
2026-05-19 15:38:31 +01:00
EpiphanyBridgeError ::Fatal ( format! (
2026-05-19 10:18:27 +01:00
" failed to open Epiphany runtime spine job {:?} in {}: {err} " ,
backend_job_id ,
store_path . display ( )
) )
} ) ? ;
Ok ( ( ) )
}
2026-05-13 06:51:28 +01:00
fn validate_expected_revision (
expected_revision : Option < u64 > ,
actual_revision : u64 ,
2026-05-19 15:38:31 +01:00
) -> BridgeResult < ( ) > {
2026-05-13 06:51:28 +01:00
if let Some ( expected_revision ) = expected_revision
& & actual_revision ! = expected_revision
{
2026-05-19 15:38:31 +01:00
return Err ( EpiphanyBridgeError ::InvalidRequest ( format! (
2026-05-13 06:51:28 +01:00
" epiphany state revision mismatch: expected {expected_revision}, found {actual_revision} "
) ) ) ;
}
Ok ( ( ) )
}