Remove Epiphany app-server compatibility surface

This commit is contained in:
Meta Vens 2026-07-12 07:30:03 +01:00
commit 5f6f2441c8
174 changed files with 8747 additions and 48296 deletions

View file

@ -10,26 +10,7 @@ name = "epiphany_codex_bridge"
path = "src/lib.rs"
[dependencies]
anyhow = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] }
codex-app-server-protocol = { path = "../vendor/codex/codex-rs/app-server-protocol" }
codex-utils-absolute-path = { path = "../vendor/codex/codex-rs/utils/absolute-path" }
# Keep standalone bridge checks aligned with the vendored Codex workspace lock.
# `starlark_map 0.13.0` does not compile against newer allocative/hashbrown
# resolver choices on this machine.
allocative = "=0.3.4"
epiphany-core = { path = "../epiphany-core" }
epiphany-state-model = { path = "../epiphany-state-model" }
notify = "8.2.0"
serde_json = "1"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["rt", "sync"] }
tracing = "0.1"
uuid = { version = "1", features = ["v4"] }
[patch.crates-io]
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "132f5b39c862e3a970f731d709608b3e6276d5f6" }
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }
[patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"]
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }

View file

@ -1,61 +0,0 @@
#[derive(Default)]
pub struct EpiphanyCheckpointInterventionState {
last_intervention_turn_id: Option<String>,
pending_compaction_turn_id: Option<String>,
}
impl EpiphanyCheckpointInterventionState {
pub fn record_intervention(&mut self, turn_id: &str) -> bool {
if self.last_intervention_turn_id.as_deref() == Some(turn_id) {
return false;
}
self.last_intervention_turn_id = Some(turn_id.to_string());
true
}
pub fn mark_pending_compaction(&mut self, turn_id: &str) {
self.pending_compaction_turn_id = Some(turn_id.to_string());
}
pub fn take_pending_compaction(&mut self, turn_id: &str) -> bool {
if self.pending_compaction_turn_id.as_deref() != Some(turn_id) {
return false;
}
self.pending_compaction_turn_id = None;
true
}
pub fn clear_pending_compaction(&mut self) {
self.pending_compaction_turn_id = None;
}
}
#[cfg(test)]
mod tests {
use super::EpiphanyCheckpointInterventionState;
#[test]
fn pending_compaction_is_turn_scoped() {
let mut state = EpiphanyCheckpointInterventionState::default();
assert!(state.record_intervention("turn-a"));
assert!(!state.record_intervention("turn-a"));
assert!(!state.take_pending_compaction("turn-a"));
state.mark_pending_compaction("turn-a");
assert!(!state.take_pending_compaction("turn-b"));
assert!(state.take_pending_compaction("turn-a"));
assert!(!state.take_pending_compaction("turn-a"));
}
#[test]
fn pending_compaction_can_be_cleared() {
let mut state = EpiphanyCheckpointInterventionState::default();
state.mark_pending_compaction("turn-a");
state.clear_pending_compaction();
assert!(!state.take_pending_compaction("turn-a"));
}
}

View file

@ -1,27 +0,0 @@
use epiphany_core::EpiphanyContextParams;
use epiphany_core::EpiphanyContextView;
use epiphany_core::EpiphanyGraphQuery;
use epiphany_core::EpiphanyGraphQueryView;
use epiphany_core::EpiphanyPlanningView;
use epiphany_core::derive_context;
use epiphany_core::derive_graph_query;
use epiphany_core::derive_planning_view;
use epiphany_state_model::EpiphanyThreadState;
pub fn derive_epiphany_context(
state: Option<&EpiphanyThreadState>,
params: &EpiphanyContextParams,
) -> EpiphanyContextView {
derive_context(state, params)
}
pub fn derive_epiphany_planning(state: Option<&EpiphanyThreadState>) -> EpiphanyPlanningView {
derive_planning_view(state)
}
pub fn derive_epiphany_graph_query(
state: Option<&EpiphanyThreadState>,
query: &EpiphanyGraphQuery,
) -> EpiphanyGraphQueryView {
derive_graph_query(state, query)
}

View file

@ -1,155 +0,0 @@
use codex_app_server_protocol::ThreadEpiphanyContext;
use codex_app_server_protocol::ThreadEpiphanyContextMissing;
use codex_app_server_protocol::ThreadEpiphanyContextStateStatus;
use codex_app_server_protocol::ThreadEpiphanyGraphContext;
use codex_app_server_protocol::ThreadEpiphanyGraphQueryMatched;
use codex_app_server_protocol::ThreadEpiphanyGraphQueryMissing;
use codex_app_server_protocol::ThreadEpiphanyPlanningSummary;
use epiphany_core::EpiphanyContext as CoreEpiphanyContext;
use epiphany_core::EpiphanyContextMissing as CoreEpiphanyContextMissing;
use epiphany_core::EpiphanyContextStateStatus as CoreEpiphanyContextStateStatus;
use epiphany_core::EpiphanyContextView;
use epiphany_core::EpiphanyGraphContext as CoreEpiphanyGraphContext;
use epiphany_core::EpiphanyGraphQueryMatched as CoreEpiphanyGraphQueryMatched;
use epiphany_core::EpiphanyGraphQueryMissing as CoreEpiphanyGraphQueryMissing;
use epiphany_core::EpiphanyGraphQueryView;
use epiphany_core::EpiphanyPlanningStateStatus as CoreEpiphanyPlanningStateStatus;
use epiphany_core::EpiphanyPlanningSummary as CoreEpiphanyPlanningSummary;
use epiphany_core::EpiphanyPlanningView;
use epiphany_state_model::EpiphanyGraphCheckpoint;
use epiphany_state_model::EpiphanyGraphFrontier;
use epiphany_state_model::EpiphanyPlanningState;
pub fn protocol_context_view(
view: EpiphanyContextView,
) -> (
ThreadEpiphanyContextStateStatus,
Option<u64>,
ThreadEpiphanyContext,
ThreadEpiphanyContextMissing,
) {
(
protocol_context_state_status(view.state_status),
view.state_revision,
protocol_context(view.context),
protocol_context_missing(view.missing),
)
}
pub fn protocol_context_state_status(
status: CoreEpiphanyContextStateStatus,
) -> ThreadEpiphanyContextStateStatus {
match status {
CoreEpiphanyContextStateStatus::Missing => ThreadEpiphanyContextStateStatus::Missing,
CoreEpiphanyContextStateStatus::Ready => ThreadEpiphanyContextStateStatus::Ready,
}
}
fn protocol_context(context: CoreEpiphanyContext) -> ThreadEpiphanyContext {
ThreadEpiphanyContext {
graph: protocol_graph_context(context.graph),
frontier: context.frontier,
checkpoint: context.checkpoint,
investigation_checkpoint: context.investigation_checkpoint,
observations: context.observations,
evidence: context.evidence,
}
}
pub fn protocol_graph_context(graph: CoreEpiphanyGraphContext) -> ThreadEpiphanyGraphContext {
ThreadEpiphanyGraphContext {
architecture_nodes: graph.architecture_nodes,
architecture_edges: graph.architecture_edges,
dataflow_nodes: graph.dataflow_nodes,
dataflow_edges: graph.dataflow_edges,
links: graph.links,
}
}
fn protocol_context_missing(missing: CoreEpiphanyContextMissing) -> ThreadEpiphanyContextMissing {
ThreadEpiphanyContextMissing {
graph_node_ids: missing.graph_node_ids,
graph_edge_ids: missing.graph_edge_ids,
observation_ids: missing.observation_ids,
evidence_ids: missing.evidence_ids,
}
}
pub fn protocol_planning_view(
view: EpiphanyPlanningView,
) -> (
ThreadEpiphanyContextStateStatus,
Option<u64>,
EpiphanyPlanningState,
ThreadEpiphanyPlanningSummary,
) {
(
match view.state_status {
CoreEpiphanyPlanningStateStatus::Missing => ThreadEpiphanyContextStateStatus::Missing,
CoreEpiphanyPlanningStateStatus::Ready => ThreadEpiphanyContextStateStatus::Ready,
},
view.state_revision,
view.planning,
protocol_planning_summary(view.summary),
)
}
fn protocol_planning_summary(
summary: CoreEpiphanyPlanningSummary,
) -> ThreadEpiphanyPlanningSummary {
ThreadEpiphanyPlanningSummary {
capture_count: summary.capture_count,
pending_capture_count: summary.pending_capture_count,
github_issue_capture_count: summary.github_issue_capture_count,
backlog_item_count: summary.backlog_item_count,
ready_backlog_item_count: summary.ready_backlog_item_count,
roadmap_stream_count: summary.roadmap_stream_count,
objective_draft_count: summary.objective_draft_count,
draft_objective_count: summary.draft_objective_count,
active_objective: summary.active_objective,
note: summary.note,
}
}
pub fn protocol_graph_query_view(
view: EpiphanyGraphQueryView,
) -> (
ThreadEpiphanyContextStateStatus,
Option<u64>,
ThreadEpiphanyGraphContext,
Option<EpiphanyGraphFrontier>,
Option<EpiphanyGraphCheckpoint>,
ThreadEpiphanyGraphQueryMatched,
ThreadEpiphanyGraphQueryMissing,
) {
(
protocol_context_state_status(view.state_status),
view.state_revision,
protocol_graph_context(view.graph),
view.frontier,
view.checkpoint,
protocol_graph_query_matched(view.matched),
protocol_graph_query_missing(view.missing),
)
}
fn protocol_graph_query_matched(
matched: CoreEpiphanyGraphQueryMatched,
) -> ThreadEpiphanyGraphQueryMatched {
ThreadEpiphanyGraphQueryMatched {
node_ids: matched.node_ids,
edge_ids: matched.edge_ids,
paths: matched.paths,
symbols: matched.symbols,
edge_kinds: matched.edge_kinds,
}
}
fn protocol_graph_query_missing(
missing: CoreEpiphanyGraphQueryMissing,
) -> ThreadEpiphanyGraphQueryMissing {
ThreadEpiphanyGraphQueryMissing {
node_ids: missing.node_ids,
edge_ids: missing.edge_ids,
}
}

View file

@ -1,335 +0,0 @@
use epiphany_core::EPIPHANY_IMAGINATION_OWNER_ROLE;
use epiphany_core::EPIPHANY_IMAGINATION_ROLE_BINDING_ID;
use epiphany_core::EPIPHANY_MODELING_ROLE_BINDING_ID;
use epiphany_core::EPIPHANY_REORIENT_OWNER_ROLE;
use epiphany_core::EPIPHANY_RESEARCH_ROLE_BINDING_ID;
use epiphany_core::EPIPHANY_VERIFICATION_ROLE_BINDING_ID;
use epiphany_core::EpiphanyCoordinatorDecision as CoreEpiphanyCoordinatorDecision;
use epiphany_core::EpiphanyCoordinatorRoleResultStatus as CoreEpiphanyCoordinatorRoleResultStatus;
use epiphany_core::EpiphanyCoordinatorStatus as CoreEpiphanyCoordinatorStatus;
use epiphany_core::EpiphanyCoordinatorStatusInput;
use epiphany_core::EpiphanyCrrcAction as CoreEpiphanyCrrcAction;
use epiphany_core::EpiphanyCrrcInput;
use epiphany_core::EpiphanyCrrcRecommendation as CoreEpiphanyCrrcRecommendation;
use epiphany_core::EpiphanyCrrcReorientAction as CoreEpiphanyCrrcReorientAction;
use epiphany_core::EpiphanyCrrcResultStatus as CoreEpiphanyCrrcResultStatus;
use epiphany_core::EpiphanyCrrcStateStatus as CoreEpiphanyCrrcStateStatus;
use epiphany_core::EpiphanyJobStatus as CoreEpiphanyJobStatus;
use epiphany_core::EpiphanyJobView;
use epiphany_core::EpiphanyReorientAction as CoreEpiphanyReorientAction;
use epiphany_core::EpiphanyReorientDecision as CoreEpiphanyReorientDecision;
use epiphany_core::EpiphanyReorientFindingInterpretation as CoreEpiphanyReorientFinding;
use epiphany_core::EpiphanyReorientStateStatus as CoreEpiphanyReorientStateStatus;
use epiphany_core::EpiphanyRoleBoardCheckpointSummary;
use epiphany_core::EpiphanyRoleBoardInput;
use epiphany_core::EpiphanyRoleBoardJob;
use epiphany_core::EpiphanyRoleBoardJobStatus;
use epiphany_core::EpiphanyRoleBoardLane;
use epiphany_core::EpiphanyRoleBoardPlanningSummary;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::derive_coordinator_finding_signals;
use epiphany_core::derive_coordinator_status;
use epiphany_core::derive_role_board;
use epiphany_core::recommend_crrc_action;
use epiphany_core::render_epiphany_coordinator_note;
use epiphany_core::render_role_board_note;
use epiphany_core::runtime_hands_receipt_chain_after;
use epiphany_state_model::EpiphanyThreadState;
use crate::runtime_results::load_core_epiphany_role_result_snapshot;
use std::path::Path;
pub fn map_epiphany_crrc_recommendation(
loaded: bool,
state_status: CoreEpiphanyReorientStateStatus,
pressure: &epiphany_core::EpiphanyPressure,
decision: &CoreEpiphanyReorientDecision,
result_status: CoreEpiphanyCrrcResultStatus,
checkpoint_present: bool,
finding_present: bool,
finding_accepted: bool,
) -> CoreEpiphanyCrrcRecommendation {
recommend_crrc_action(EpiphanyCrrcInput {
loaded,
state_status: map_core_crrc_state_status_from_reorient(state_status),
should_prepare_compaction: pressure.should_prepare_compaction,
reorient_action: map_core_crrc_reorient_action(decision.action),
result_status,
checkpoint_present,
finding_present,
finding_accepted,
})
}
fn map_core_crrc_state_status_from_reorient(
status: CoreEpiphanyReorientStateStatus,
) -> CoreEpiphanyCrrcStateStatus {
match status {
CoreEpiphanyReorientStateStatus::Missing => CoreEpiphanyCrrcStateStatus::Missing,
CoreEpiphanyReorientStateStatus::Ready => CoreEpiphanyCrrcStateStatus::Ready,
}
}
fn map_core_crrc_reorient_action(
action: CoreEpiphanyReorientAction,
) -> CoreEpiphanyCrrcReorientAction {
match action {
CoreEpiphanyReorientAction::Resume => CoreEpiphanyCrrcReorientAction::Resume,
CoreEpiphanyReorientAction::Regather => CoreEpiphanyCrrcReorientAction::Regather,
}
}
pub type EpiphanyCoordinatorDecision = CoreEpiphanyCoordinatorDecision;
pub struct EpiphanyCoordinatorStatus {
pub core: CoreEpiphanyCoordinatorStatus,
pub note: String,
}
pub async fn derive_epiphany_coordinator_status(
state: Option<&EpiphanyThreadState>,
runtime_store_path: Option<&Path>,
state_status: CoreEpiphanyReorientStateStatus,
pressure: &epiphany_core::EpiphanyPressure,
recommendation: &CoreEpiphanyCrrcRecommendation,
roles: Vec<EpiphanyRoleBoardLane>,
reorient_decision: Option<&CoreEpiphanyReorientDecision>,
reorient_result_status: CoreEpiphanyCrrcResultStatus,
reorient_finding: Option<&CoreEpiphanyReorientFinding>,
checkpoint_present: bool,
) -> EpiphanyCoordinatorStatus {
let (modeling_result_status, modeling_finding) = if let Some(state) = state {
let snapshot = load_core_epiphany_role_result_snapshot(
state,
runtime_store_path,
EpiphanyRoleResultRoleId::Modeling,
EPIPHANY_MODELING_ROLE_BINDING_ID,
)
.await;
(snapshot.status, snapshot.finding)
} else {
(CoreEpiphanyCoordinatorRoleResultStatus::MissingState, None)
};
let (research_result_status, research_finding) = if let Some(state) = state {
let snapshot = load_core_epiphany_role_result_snapshot(
state,
runtime_store_path,
EpiphanyRoleResultRoleId::Research,
EPIPHANY_RESEARCH_ROLE_BINDING_ID,
)
.await;
(snapshot.status, snapshot.finding)
} else {
(CoreEpiphanyCoordinatorRoleResultStatus::MissingState, None)
};
let (verification_result_status, verification_finding) = if let Some(state) = state {
let snapshot = load_core_epiphany_role_result_snapshot(
state,
runtime_store_path,
EpiphanyRoleResultRoleId::Verification,
EPIPHANY_VERIFICATION_ROLE_BINDING_ID,
)
.await;
(snapshot.status, snapshot.finding)
} else {
(CoreEpiphanyCoordinatorRoleResultStatus::MissingState, None)
};
let mut finding_signals = derive_coordinator_finding_signals(
state,
research_finding.as_ref(),
modeling_finding.as_ref(),
verification_finding.as_ref(),
reorient_finding,
);
if !finding_signals.implementation_evidence_after_verification
&& runtime_hands_receipts_after_verification(
state,
runtime_store_path,
verification_finding.as_ref(),
)
{
finding_signals.implementation_evidence_after_verification = true;
}
let core = derive_coordinator_status(EpiphanyCoordinatorStatusInput {
state_status: map_core_crrc_state_status_from_reorient(state_status),
checkpoint_present,
pressure: pressure.clone(),
recommendation: recommendation.clone(),
roles,
reorient_action: reorient_decision
.map(|decision| decision.action)
.unwrap_or(CoreEpiphanyReorientAction::Resume),
research_result_status,
modeling_result_status,
verification_result_status,
reorient_result_status,
research_result_accepted: finding_signals.research_result_accepted,
research_result_reviewable: finding_signals.research_result_reviewable,
modeling_result_requests_regather: finding_signals.modeling_result_requests_regather,
modeling_result_accepted: finding_signals.modeling_result_accepted,
modeling_result_reviewable: finding_signals.modeling_result_reviewable,
modeling_result_failure_reviewed: finding_signals.modeling_result_failure_reviewed,
modeling_result_accepted_after_verification: finding_signals
.modeling_result_accepted_after_verification,
implementation_evidence_after_verification: finding_signals
.implementation_evidence_after_verification,
verification_result_cites_implementation_evidence: finding_signals
.verification_result_cites_implementation_evidence,
verification_result_covers_current_modeling: finding_signals
.verification_result_covers_current_modeling,
verification_result_accepted: finding_signals.verification_result_accepted,
verification_result_failure_reviewed: finding_signals.verification_result_failure_reviewed,
verification_result_allows_implementation: finding_signals
.verification_result_allows_implementation,
verification_result_needs_evidence: finding_signals.verification_result_needs_evidence,
reorient_finding_accepted: finding_signals.reorient_finding_accepted,
});
let note = render_epiphany_coordinator_note(
recommendation.action,
pressure.level,
modeling_result_status,
verification_result_status,
core.source_signals.reorient_result_status,
core.decision.action,
);
EpiphanyCoordinatorStatus { core, note }
}
fn runtime_hands_receipts_after_verification(
state: Option<&EpiphanyThreadState>,
runtime_store_path: Option<&Path>,
verification_finding: Option<&epiphany_core::EpiphanyRoleFindingInterpretation>,
) -> bool {
let Some(state) = state else {
return false;
};
let Some(runtime_store_path) = runtime_store_path else {
return false;
};
let Some(verification_finding) = verification_finding else {
return false;
};
let Some(result_id) = verification_finding.runtime_result_id.as_deref() else {
return false;
};
let Some(accepted_at) = state
.acceptance_receipts
.iter()
.find(|receipt| {
receipt.result_id == result_id
&& receipt.role_id == "verification"
&& receipt.surface == "roleAccept"
&& receipt.status == "accepted"
})
.map(|receipt| receipt.accepted_at.as_str())
else {
return false;
};
runtime_hands_receipt_chain_after(runtime_store_path, accepted_at).unwrap_or(false)
}
#[derive(Debug, Clone)]
pub struct EpiphanyRoleBoardStatus {
pub roles: Vec<EpiphanyRoleBoardLane>,
pub(crate) source_jobs: Vec<EpiphanyJobView>,
}
pub fn map_epiphany_roles(
state: Option<&EpiphanyThreadState>,
jobs: &[EpiphanyJobView],
decision: &CoreEpiphanyReorientDecision,
pressure: &epiphany_core::EpiphanyPressure,
recommendation: &CoreEpiphanyCrrcRecommendation,
result_status: CoreEpiphanyCrrcResultStatus,
reorient_job: Option<&EpiphanyJobView>,
) -> EpiphanyRoleBoardStatus {
let planning = state.map(|state| &state.planning);
let checkpoint = state.and_then(|state| state.investigation_checkpoint.as_ref());
let mut source_jobs = jobs.to_vec();
if let Some(job) = reorient_job
&& !source_jobs
.iter()
.any(|source_job| source_job.id == job.id && source_job.owner_role == job.owner_role)
{
source_jobs.push(job.clone());
}
let roles = derive_role_board(EpiphanyRoleBoardInput {
state_present: state.is_some(),
planning: EpiphanyRoleBoardPlanningSummary {
capture_count: planning
.map(|planning| planning.captures.len())
.unwrap_or(0),
backlog_item_count: planning
.map(|planning| planning.backlog_items.len())
.unwrap_or(0),
roadmap_stream_count: planning
.map(|planning| planning.roadmap_streams.len())
.unwrap_or(0),
objective_draft_count: planning
.map(|planning| planning.objective_drafts.len())
.unwrap_or(0),
},
checkpoint: checkpoint.map(|checkpoint| EpiphanyRoleBoardCheckpointSummary {
disposition: Some(format!("{:?}", checkpoint.disposition)),
next_action: checkpoint.next_action.clone(),
}),
reorient_next_action: decision.next_action.clone(),
jobs: source_jobs.iter().map(map_core_role_board_job).collect(),
crrc_action: recommendation.action,
crrc_recommended_scene_action: recommendation
.recommended_scene_action
.map(epiphany_core::crrc_scene_action_to_coordinator_scene_action),
crrc_reason: recommendation.reason.clone(),
reorient_decision_action: format!("{:?}", decision.action),
pressure_level: format!("{:?}", pressure.level),
reorient_result_status: result_status,
reorient_job: reorient_job.map(map_core_role_board_job),
imagination_binding_id: EPIPHANY_IMAGINATION_ROLE_BINDING_ID.to_string(),
research_binding_id: EPIPHANY_RESEARCH_ROLE_BINDING_ID.to_string(),
modeling_binding_id: EPIPHANY_MODELING_ROLE_BINDING_ID.to_string(),
verification_binding_id: EPIPHANY_VERIFICATION_ROLE_BINDING_ID.to_string(),
reorient_owner_role: EPIPHANY_REORIENT_OWNER_ROLE.to_string(),
imagination_owner_role: EPIPHANY_IMAGINATION_OWNER_ROLE.to_string(),
research_owner_role: epiphany_core::EPIPHANY_RESEARCH_OWNER_ROLE.to_string(),
});
EpiphanyRoleBoardStatus { roles, source_jobs }
}
fn map_core_role_board_job(job: &EpiphanyJobView) -> EpiphanyRoleBoardJob {
EpiphanyRoleBoardJob {
id: job.id.clone(),
owner_role: job.owner_role.clone(),
status: map_core_role_board_job_status(job.status),
progress_note: job.progress_note.clone(),
blocking_reason: job.blocking_reason.clone(),
}
}
fn map_core_role_board_job_status(status: CoreEpiphanyJobStatus) -> EpiphanyRoleBoardJobStatus {
match status {
CoreEpiphanyJobStatus::Idle => EpiphanyRoleBoardJobStatus::Idle,
CoreEpiphanyJobStatus::Needed => EpiphanyRoleBoardJobStatus::Needed,
CoreEpiphanyJobStatus::Pending => EpiphanyRoleBoardJobStatus::Pending,
CoreEpiphanyJobStatus::Running => EpiphanyRoleBoardJobStatus::Running,
CoreEpiphanyJobStatus::Completed => EpiphanyRoleBoardJobStatus::Completed,
CoreEpiphanyJobStatus::Failed => EpiphanyRoleBoardJobStatus::Failed,
CoreEpiphanyJobStatus::Cancelled => EpiphanyRoleBoardJobStatus::Cancelled,
CoreEpiphanyJobStatus::Blocked => EpiphanyRoleBoardJobStatus::Blocked,
CoreEpiphanyJobStatus::Unavailable => EpiphanyRoleBoardJobStatus::Unavailable,
}
}
pub fn render_epiphany_roles_note(
roles: &[EpiphanyRoleBoardLane],
state_status: CoreEpiphanyReorientStateStatus,
recommendation: CoreEpiphanyCrrcAction,
) -> String {
render_role_board_note(
roles,
format!("{:?}", state_status).as_str(),
recommendation,
)
}

View file

@ -1,312 +0,0 @@
use codex_app_server_protocol::ThreadEpiphanyCoordinatorAction;
use codex_app_server_protocol::ThreadEpiphanyCoordinatorSignals;
use codex_app_server_protocol::ThreadEpiphanyCrrcAction;
use codex_app_server_protocol::ThreadEpiphanyCrrcRecommendation;
use codex_app_server_protocol::ThreadEpiphanyJob;
use codex_app_server_protocol::ThreadEpiphanyReorientAction;
use codex_app_server_protocol::ThreadEpiphanyRoleId;
use codex_app_server_protocol::ThreadEpiphanyRoleLane;
use codex_app_server_protocol::ThreadEpiphanyRoleStatus;
use codex_app_server_protocol::ThreadEpiphanyRolesSource;
use codex_app_server_protocol::ThreadEpiphanySceneAction;
use codex_app_server_protocol::ThreadEpiphanyViewCoordinator;
use epiphany_core::EpiphanyCoordinatorAction as CoreEpiphanyCoordinatorAction;
use epiphany_core::EpiphanyCoordinatorRoleId as CoreEpiphanyCoordinatorRoleId;
use epiphany_core::EpiphanyCoordinatorRoleStatus as CoreEpiphanyCoordinatorRoleStatus;
use epiphany_core::EpiphanyCoordinatorSceneAction as CoreEpiphanyCoordinatorSceneAction;
use epiphany_core::EpiphanyCoordinatorSourceSignals;
use epiphany_core::EpiphanyCrrcAction as CoreEpiphanyCrrcAction;
use epiphany_core::EpiphanyCrrcRecommendation as CoreEpiphanyCrrcRecommendation;
use epiphany_core::EpiphanyCrrcSceneAction as CoreEpiphanyCrrcSceneAction;
use epiphany_core::EpiphanyJobStatus as CoreEpiphanyJobStatus;
use epiphany_core::EpiphanyJobView;
use epiphany_core::EpiphanyReorientAction as CoreEpiphanyReorientAction;
use epiphany_core::EpiphanyReorientStateStatus as CoreEpiphanyReorientStateStatus;
use epiphany_core::EpiphanyRoleBoardJob;
use epiphany_core::EpiphanyRoleBoardJobStatus;
use epiphany_core::EpiphanyRoleBoardLane;
use epiphany_state_model::EpiphanyJobKind as CoreEpiphanyJobKind;
use crate::coordinator::EpiphanyCoordinatorStatus;
use crate::coordinator::EpiphanyRoleBoardStatus;
use crate::protocol_edge::protocol_job_from_surface;
use crate::protocol_edge::protocol_pressure_level;
use crate::protocol_edge::protocol_reorient_result_status;
use crate::protocol_edge::protocol_reorient_state_status;
use crate::protocol_edge::protocol_role_result_status;
fn protocol_coordinator_source_signals(
signals: EpiphanyCoordinatorSourceSignals,
) -> ThreadEpiphanyCoordinatorSignals {
ThreadEpiphanyCoordinatorSignals {
pressure_level: protocol_pressure_level(signals.pressure_level),
should_prepare_compaction: signals.should_prepare_compaction,
reorient_action: protocol_reorient_action(signals.reorient_action),
crrc_action: protocol_crrc_action(signals.crrc_action),
research_result_status: protocol_role_result_status(signals.research_result_status),
modeling_result_status: protocol_role_result_status(signals.modeling_result_status),
verification_result_status: protocol_role_result_status(signals.verification_result_status),
reorient_result_status: protocol_reorient_result_status(signals.reorient_result_status),
}
}
fn protocol_reorient_action(action: CoreEpiphanyReorientAction) -> ThreadEpiphanyReorientAction {
match action {
CoreEpiphanyReorientAction::Resume => ThreadEpiphanyReorientAction::Resume,
CoreEpiphanyReorientAction::Regather => ThreadEpiphanyReorientAction::Regather,
}
}
pub fn protocol_crrc_action(action: CoreEpiphanyCrrcAction) -> ThreadEpiphanyCrrcAction {
match action {
CoreEpiphanyCrrcAction::Continue => ThreadEpiphanyCrrcAction::Continue,
CoreEpiphanyCrrcAction::PrepareCheckpoint => ThreadEpiphanyCrrcAction::PrepareCheckpoint,
CoreEpiphanyCrrcAction::LaunchReorientWorker => {
ThreadEpiphanyCrrcAction::LaunchReorientWorker
}
CoreEpiphanyCrrcAction::WaitForReorientWorker => {
ThreadEpiphanyCrrcAction::WaitForReorientWorker
}
CoreEpiphanyCrrcAction::ReviewReorientResult => {
ThreadEpiphanyCrrcAction::ReviewReorientResult
}
CoreEpiphanyCrrcAction::AcceptReorientResult => {
ThreadEpiphanyCrrcAction::AcceptReorientResult
}
CoreEpiphanyCrrcAction::RegatherManually => ThreadEpiphanyCrrcAction::RegatherManually,
}
}
fn protocol_crrc_scene_action(action: CoreEpiphanyCrrcSceneAction) -> ThreadEpiphanySceneAction {
match action {
CoreEpiphanyCrrcSceneAction::Update => ThreadEpiphanySceneAction::Update,
CoreEpiphanyCrrcSceneAction::Reorient => ThreadEpiphanySceneAction::Reorient,
CoreEpiphanyCrrcSceneAction::ReorientLaunch => ThreadEpiphanySceneAction::ReorientLaunch,
CoreEpiphanyCrrcSceneAction::ReorientResult => ThreadEpiphanySceneAction::ReorientResult,
CoreEpiphanyCrrcSceneAction::ReorientAccept => ThreadEpiphanySceneAction::ReorientAccept,
}
}
pub fn protocol_crrc_recommendation(
recommendation: CoreEpiphanyCrrcRecommendation,
) -> ThreadEpiphanyCrrcRecommendation {
ThreadEpiphanyCrrcRecommendation {
action: protocol_crrc_action(recommendation.action),
recommended_scene_action: recommendation
.recommended_scene_action
.map(protocol_crrc_scene_action),
reason: recommendation.reason,
}
}
pub fn protocol_coordinator_view(
thread_id: String,
loaded: bool,
state_status: CoreEpiphanyReorientStateStatus,
state_revision: Option<u64>,
status: EpiphanyCoordinatorStatus,
roles: EpiphanyRoleBoardStatus,
) -> ThreadEpiphanyViewCoordinator {
ThreadEpiphanyViewCoordinator {
thread_id,
source: if loaded {
ThreadEpiphanyRolesSource::Live
} else {
ThreadEpiphanyRolesSource::Stored
},
state_status: protocol_reorient_state_status(state_status),
state_revision,
action: protocol_coordinator_action(status.core.decision.action),
target_role: status
.core
.decision
.target_role
.map(protocol_coordinator_role_id),
recommended_scene_action: status
.core
.decision
.recommended_scene_action
.map(protocol_coordinator_scene_action),
requires_review: status.core.decision.requires_review,
can_auto_run: status.core.decision.can_auto_run,
reason: status.core.decision.reason,
source_signals: protocol_coordinator_source_signals(status.core.source_signals),
roles: protocol_role_board_lanes(&roles),
note: status.note,
}
}
fn protocol_coordinator_role_id(role_id: CoreEpiphanyCoordinatorRoleId) -> ThreadEpiphanyRoleId {
match role_id {
CoreEpiphanyCoordinatorRoleId::Implementation => ThreadEpiphanyRoleId::Implementation,
CoreEpiphanyCoordinatorRoleId::Imagination => ThreadEpiphanyRoleId::Imagination,
CoreEpiphanyCoordinatorRoleId::Research => ThreadEpiphanyRoleId::Research,
CoreEpiphanyCoordinatorRoleId::Modeling => ThreadEpiphanyRoleId::Modeling,
CoreEpiphanyCoordinatorRoleId::Verification => ThreadEpiphanyRoleId::Verification,
CoreEpiphanyCoordinatorRoleId::Reorientation => ThreadEpiphanyRoleId::Reorientation,
}
}
fn protocol_coordinator_scene_action(
action: CoreEpiphanyCoordinatorSceneAction,
) -> ThreadEpiphanySceneAction {
match action {
CoreEpiphanyCoordinatorSceneAction::Update => ThreadEpiphanySceneAction::Update,
CoreEpiphanyCoordinatorSceneAction::Reorient => ThreadEpiphanySceneAction::Reorient,
CoreEpiphanyCoordinatorSceneAction::ReorientLaunch => {
ThreadEpiphanySceneAction::ReorientLaunch
}
CoreEpiphanyCoordinatorSceneAction::ReorientResult => {
ThreadEpiphanySceneAction::ReorientResult
}
CoreEpiphanyCoordinatorSceneAction::ReorientAccept => {
ThreadEpiphanySceneAction::ReorientAccept
}
CoreEpiphanyCoordinatorSceneAction::RoleLaunch => ThreadEpiphanySceneAction::RoleLaunch,
CoreEpiphanyCoordinatorSceneAction::RoleResult => ThreadEpiphanySceneAction::RoleResult,
}
}
fn protocol_coordinator_action(
action: CoreEpiphanyCoordinatorAction,
) -> ThreadEpiphanyCoordinatorAction {
match action {
CoreEpiphanyCoordinatorAction::PrepareCheckpoint => {
ThreadEpiphanyCoordinatorAction::PrepareCheckpoint
}
CoreEpiphanyCoordinatorAction::CompactRehydrateReorient => {
ThreadEpiphanyCoordinatorAction::CompactRehydrateReorient
}
CoreEpiphanyCoordinatorAction::LaunchReorientWorker => {
ThreadEpiphanyCoordinatorAction::LaunchReorientWorker
}
CoreEpiphanyCoordinatorAction::WaitForReorientWorker => {
ThreadEpiphanyCoordinatorAction::WaitForReorientWorker
}
CoreEpiphanyCoordinatorAction::ReviewReorientResult => {
ThreadEpiphanyCoordinatorAction::ReviewReorientResult
}
CoreEpiphanyCoordinatorAction::RegatherManually => {
ThreadEpiphanyCoordinatorAction::RegatherManually
}
CoreEpiphanyCoordinatorAction::LaunchResearch => {
ThreadEpiphanyCoordinatorAction::LaunchResearch
}
CoreEpiphanyCoordinatorAction::ReviewResearchResult => {
ThreadEpiphanyCoordinatorAction::ReviewResearchResult
}
CoreEpiphanyCoordinatorAction::LaunchModeling => {
ThreadEpiphanyCoordinatorAction::LaunchModeling
}
CoreEpiphanyCoordinatorAction::ReviewModelingResult => {
ThreadEpiphanyCoordinatorAction::ReviewModelingResult
}
CoreEpiphanyCoordinatorAction::LaunchVerification => {
ThreadEpiphanyCoordinatorAction::LaunchVerification
}
CoreEpiphanyCoordinatorAction::ReviewVerificationResult => {
ThreadEpiphanyCoordinatorAction::ReviewVerificationResult
}
CoreEpiphanyCoordinatorAction::ContinueImplementation => {
ThreadEpiphanyCoordinatorAction::ContinueImplementation
}
}
}
pub fn protocol_role_board_lanes(
role_board: &EpiphanyRoleBoardStatus,
) -> Vec<ThreadEpiphanyRoleLane> {
role_board
.roles
.iter()
.cloned()
.map(|lane| protocol_role_board_lane(lane, &role_board.source_jobs))
.collect()
}
fn protocol_role_board_lane(
lane: EpiphanyRoleBoardLane,
source_jobs: &[EpiphanyJobView],
) -> ThreadEpiphanyRoleLane {
ThreadEpiphanyRoleLane {
id: protocol_coordinator_role_id(lane.id),
title: lane.title,
owner_role: lane.owner_role,
status: protocol_coordinator_role_status(lane.status),
note: lane.note,
jobs: lane
.jobs
.iter()
.map(|job| protocol_role_board_job(job, source_jobs))
.collect(),
authority_scopes: lane.authority_scopes,
recommended_action: lane
.recommended_action
.map(protocol_coordinator_scene_action),
}
}
fn protocol_role_board_job(
job: &EpiphanyRoleBoardJob,
source_jobs: &[EpiphanyJobView],
) -> ThreadEpiphanyJob {
source_jobs
.iter()
.find(|source_job| source_job.id == job.id && source_job.owner_role == job.owner_role)
.cloned()
.map(|job| protocol_job_from_surface(job, None, None))
.unwrap_or_else(|| {
protocol_job_from_surface(
EpiphanyJobView {
id: job.id.clone(),
kind: CoreEpiphanyJobKind::Specialist,
scope: job.id.clone(),
owner_role: job.owner_role.clone(),
authority_scope: None,
runtime_job_id: None,
status: core_epiphany_job_status_from_role_board(job.status),
items_processed: None,
items_total: None,
progress_note: job.progress_note.clone(),
last_checkpoint_at_unix_seconds: None,
blocking_reason: job.blocking_reason.clone(),
active_thread_ids: Vec::new(),
linked_subgoal_ids: Vec::new(),
linked_graph_node_ids: Vec::new(),
},
None,
None,
)
})
}
fn core_epiphany_job_status_from_role_board(
status: EpiphanyRoleBoardJobStatus,
) -> CoreEpiphanyJobStatus {
match status {
EpiphanyRoleBoardJobStatus::Idle => CoreEpiphanyJobStatus::Idle,
EpiphanyRoleBoardJobStatus::Needed => CoreEpiphanyJobStatus::Needed,
EpiphanyRoleBoardJobStatus::Pending => CoreEpiphanyJobStatus::Pending,
EpiphanyRoleBoardJobStatus::Running => CoreEpiphanyJobStatus::Running,
EpiphanyRoleBoardJobStatus::Completed => CoreEpiphanyJobStatus::Completed,
EpiphanyRoleBoardJobStatus::Failed => CoreEpiphanyJobStatus::Failed,
EpiphanyRoleBoardJobStatus::Cancelled => CoreEpiphanyJobStatus::Cancelled,
EpiphanyRoleBoardJobStatus::Blocked => CoreEpiphanyJobStatus::Blocked,
EpiphanyRoleBoardJobStatus::Unavailable => CoreEpiphanyJobStatus::Unavailable,
}
}
fn protocol_coordinator_role_status(
status: CoreEpiphanyCoordinatorRoleStatus,
) -> ThreadEpiphanyRoleStatus {
match status {
CoreEpiphanyCoordinatorRoleStatus::Ready => ThreadEpiphanyRoleStatus::Ready,
CoreEpiphanyCoordinatorRoleStatus::Needed => ThreadEpiphanyRoleStatus::Needed,
CoreEpiphanyCoordinatorRoleStatus::Running => ThreadEpiphanyRoleStatus::Running,
CoreEpiphanyCoordinatorRoleStatus::Waiting => ThreadEpiphanyRoleStatus::Waiting,
CoreEpiphanyCoordinatorRoleStatus::Review => ThreadEpiphanyRoleStatus::Review,
CoreEpiphanyCoordinatorRoleStatus::Blocked => ThreadEpiphanyRoleStatus::Blocked,
CoreEpiphanyCoordinatorRoleStatus::Unavailable => ThreadEpiphanyRoleStatus::Unavailable,
CoreEpiphanyCoordinatorRoleStatus::Completed => ThreadEpiphanyRoleStatus::Completed,
}
}

View file

@ -1,42 +0,0 @@
use epiphany_core::EpiphanyGraphFreshness;
pub use epiphany_core::EpiphanyGraphFreshnessStatus;
use epiphany_core::EpiphanyInvalidationInput;
pub use epiphany_core::EpiphanyInvalidationStatus;
pub use epiphany_core::EpiphanyJobStatus;
pub use epiphany_core::EpiphanyJobView;
pub use epiphany_core::EpiphanyPressure;
pub use epiphany_core::EpiphanyPressureBasis;
pub use epiphany_core::EpiphanyPressureLevel;
pub use epiphany_core::EpiphanyPressureStatus;
pub use epiphany_core::EpiphanyReorientAction;
pub use epiphany_core::EpiphanyReorientCheckpointStatus;
pub use epiphany_core::EpiphanyReorientDecision;
pub use epiphany_core::EpiphanyReorientFreshnessStatus;
pub use epiphany_core::EpiphanyReorientPressureLevel;
pub use epiphany_core::EpiphanyReorientReason;
pub use epiphany_core::EpiphanyReorientStateStatus;
use epiphany_core::EpiphanyRetrievalFreshness;
pub use epiphany_core::EpiphanyRetrievalFreshnessStatus;
pub use epiphany_core::EpiphanyStateUpdatedField;
pub use epiphany_state_model::EpiphanyJobKind;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EpiphanySurfaceSource {
Stored,
Live,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EpiphanyFreshnessSurface {
pub thread_id: String,
pub source: EpiphanySurfaceSource,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state_revision: Option<u64>,
pub retrieval: EpiphanyRetrievalFreshness,
pub graph: EpiphanyGraphFreshness,
pub watcher: EpiphanyInvalidationInput,
}

View file

@ -1,20 +0,0 @@
use std::error::Error;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EpiphanyBridgeError {
InvalidRequest(String),
Fatal(String),
}
pub type Result<T> = std::result::Result<T, EpiphanyBridgeError>;
impl fmt::Display for EpiphanyBridgeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidRequest(message) | Self::Fatal(message) => f.write_str(message),
}
}
}
impl Error for EpiphanyBridgeError {}

View file

@ -11,8 +11,6 @@ use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tracing::warn;
use crate::reorient::EpiphanyFreshnessWatcherSnapshot;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EpiphanyInvalidationSnapshot {
pub available: bool,
@ -21,17 +19,6 @@ pub struct EpiphanyInvalidationSnapshot {
pub changed_paths: Vec<PathBuf>,
}
pub fn epiphany_freshness_watcher_snapshot(
snapshot: &EpiphanyInvalidationSnapshot,
) -> EpiphanyFreshnessWatcherSnapshot<'_> {
EpiphanyFreshnessWatcherSnapshot {
available: snapshot.available,
workspace_root: snapshot.workspace_root.as_ref().map(|path| path.as_path()),
observed_at_unix_seconds: snapshot.observed_at_unix_seconds,
changed_paths: snapshot.changed_paths.as_slice(),
}
}
#[derive(Clone)]
pub struct EpiphanyInvalidationManager {
state: Arc<AsyncMutex<HashMap<String, WatchEntry>>>,

View file

@ -1,95 +0,0 @@
use epiphany_core::EpiphanyJobStatus as CoreEpiphanyJobStatus;
use epiphany_core::EpiphanyJobView;
use epiphany_core::EpiphanyJobsInput;
use epiphany_core::derive_jobs;
use epiphany_state_model::EpiphanyJobKind as CoreEpiphanyJobKind;
use epiphany_state_model::EpiphanyRetrievalState;
use epiphany_state_model::EpiphanyThreadState;
pub fn derive_epiphany_jobs(
state: Option<&EpiphanyThreadState>,
retrieval_override: Option<&EpiphanyRetrievalState>,
) -> Vec<EpiphanyJobView> {
derive_jobs(EpiphanyJobsInput {
state,
retrieval_override,
})
}
pub fn map_epiphany_jobs(
state: Option<&EpiphanyThreadState>,
retrieval_override: Option<&EpiphanyRetrievalState>,
) -> Vec<EpiphanyJobView> {
derive_epiphany_jobs(state, retrieval_override)
}
pub fn map_launched_epiphany_job(
state: &EpiphanyThreadState,
binding_id: &str,
backend_job_id: &str,
fallback_kind: CoreEpiphanyJobKind,
fallback_scope: &str,
) -> EpiphanyJobView {
derive_epiphany_jobs(Some(state), None)
.into_iter()
.find(|job| job.id == binding_id)
.unwrap_or_else(|| EpiphanyJobView {
id: binding_id.to_string(),
kind: fallback_kind,
scope: fallback_scope.to_string(),
owner_role: "epiphany-harness".to_string(),
authority_scope: None,
runtime_job_id: Some(backend_job_id.to_string()),
status: CoreEpiphanyJobStatus::Pending,
items_processed: None,
items_total: None,
progress_note: None,
last_checkpoint_at_unix_seconds: None,
blocking_reason: None,
active_thread_ids: Vec::new(),
linked_subgoal_ids: Vec::new(),
linked_graph_node_ids: Vec::new(),
})
}
pub fn map_interrupted_epiphany_job(
state: &EpiphanyThreadState,
binding_id: &str,
) -> EpiphanyJobView {
derive_epiphany_jobs(Some(state), None)
.into_iter()
.find(|job| job.id == binding_id)
.unwrap_or_else(|| {
epiphany_blocked_state_job(
binding_id,
CoreEpiphanyJobKind::Specialist,
"role-scoped specialist work",
"Interrupted job binding was not reflected in Epiphany state.",
)
})
}
pub fn epiphany_blocked_state_job(
id: &str,
kind: CoreEpiphanyJobKind,
scope: &str,
blocking_reason: &str,
) -> EpiphanyJobView {
EpiphanyJobView {
id: id.to_string(),
kind,
scope: scope.to_string(),
owner_role: "epiphany-harness".to_string(),
authority_scope: None,
runtime_job_id: None,
status: CoreEpiphanyJobStatus::Blocked,
items_processed: None,
items_total: None,
progress_note: None,
last_checkpoint_at_unix_seconds: None,
blocking_reason: Some(blocking_reason.to_string()),
active_thread_ids: Vec::new(),
linked_subgoal_ids: Vec::new(),
linked_graph_node_ids: Vec::new(),
}
}

View file

@ -1,37 +0,0 @@
//! Compatibility facade for older bridge callers.
//!
//! Epiphany prompt doctrine, worker launch policy, role binding ids, and output
//! schemas live in `epiphany-core`. The bridge may translate those typed launch
//! requests to Codex JSON-RPC, but it does not own the agent instructions.
pub use epiphany_core::EPIPHANY_IMAGINATION_OWNER_ROLE;
pub use epiphany_core::EPIPHANY_IMAGINATION_ROLE_BINDING_ID;
pub use epiphany_core::EPIPHANY_MODELING_OWNER_ROLE;
pub use epiphany_core::EPIPHANY_MODELING_ROLE_BINDING_ID;
pub use epiphany_core::EPIPHANY_REORIENT_LAUNCH_BINDING_ID;
pub use epiphany_core::EPIPHANY_REORIENT_OWNER_ROLE;
pub use epiphany_core::EPIPHANY_RESEARCH_OWNER_ROLE;
pub use epiphany_core::EPIPHANY_RESEARCH_ROLE_BINDING_ID;
pub use epiphany_core::EPIPHANY_VERIFICATION_OWNER_ROLE;
pub use epiphany_core::EPIPHANY_VERIFICATION_ROLE_BINDING_ID;
pub use epiphany_core::EpiphanyCoordinatorPromptConfig;
pub use epiphany_core::EpiphanyCrrcPromptConfig;
pub use epiphany_core::EpiphanyImplementationPromptConfig;
pub use epiphany_core::EpiphanyReorientationPromptConfig;
pub use epiphany_core::EpiphanyRolePromptConfig;
pub use epiphany_core::EpiphanySharedPromptConfig;
pub use epiphany_core::EpiphanySpecialistPromptConfig;
pub use epiphany_core::build_epiphany_job_launch_request;
pub use epiphany_core::build_epiphany_reorient_launch_instruction;
pub use epiphany_core::build_epiphany_reorient_launch_request;
pub use epiphany_core::build_epiphany_role_launch_request;
pub use epiphany_core::epiphany_agent_prompt_with_memory;
pub use epiphany_core::epiphany_reorient_launch_output_schema;
pub use epiphany_core::epiphany_role_binding_id;
pub use epiphany_core::epiphany_role_label;
pub use epiphany_core::epiphany_role_launch_output_schema;
pub use epiphany_core::epiphany_role_owner;
pub use epiphany_core::epiphany_specialist_prompt_config;
pub use epiphany_core::epiphany_worker_prompt;
pub use epiphany_core::render_epiphany_coordinator_note;
pub use epiphany_core::unique_strings;

View file

@ -1,5 +0,0 @@
pub use epiphany_core::append_modeling_work_loop_telemetry_context;
pub use epiphany_core::append_verification_hands_receipt_context;
pub use epiphany_core::render_launch_dynamic_prompt_context;
pub use epiphany_core::reorient_launch_context_focus;
pub use epiphany_core::role_launch_context_focus;

View file

@ -1,40 +1,7 @@
//! Compatibility bridge between Epiphany's typed CultNet/CultCache-shaped
//! contracts and the vendored Codex JSON-RPC/app-server shell.
//! Codex-host watcher invalidation compatibility.
//!
//! This crate is a bridge, not an authority organ. Its job is to translate
//! Codex `ThreadEpiphany*` DTOs into Epiphany core documents, project typed
//! Epiphany surfaces back into legacy Codex responses, and call the narrow
//! host trait needed while Codex still owns thread persistence. Verdicts,
//! launch policy, reorientation policy, acceptance rules, runtime-spine
//! lifecycle semantics, and durable state invariants belong in `epiphany-core`
//! or `epiphany-state-model`.
//!
//! Host facts and side effects that still pass through this crate are
//! quarantine scaffolding for the current Codex shell. Do not let them become
//! a second policy throne. The long cut is to replace these adapters with
//! native CultNet intents and receipts, leaving Codex only as the OpenAI
//! subscription auth/model transport reliquary.
//! Epiphany state, process, and interface authority is native. This crate may
//! adapt file-watcher facts while the OpenAI/Codex transport reliquary remains,
//! but it does not publish an Epiphany protocol or own durable state.
pub mod checkpoint;
pub mod context;
pub mod context_protocol;
pub mod coordinator;
pub mod coordinator_protocol;
pub mod cultnet;
pub mod error;
pub mod invalidation;
pub mod jobs;
pub mod launch;
pub mod launch_context;
pub mod mutation;
pub mod mutation_service;
pub mod pressure;
pub mod protocol_edge;
pub mod reorient;
pub mod results;
pub mod retrieve;
pub mod runtime_results;
pub mod scene;
pub mod scene_protocol;
pub mod state;
pub mod view_protocol;

View file

@ -1,176 +0,0 @@
use epiphany_core::EpiphanyReorientFindingInterpretation as CoreEpiphanyReorientFinding;
use epiphany_core::EpiphanyRoleFindingInterpretation as CoreEpiphanyRoleFinding;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::EpiphanyRoleStatePatchDocument;
use epiphany_core::EpiphanyStateUpdate;
use epiphany_core::EpiphanyStateUpdatedField;
use epiphany_state_model::EpiphanyInvestigationCheckpoint;
pub type RoleAcceptanceUpdate = epiphany_core::EpiphanyRoleAcceptanceUpdate;
pub type ReorientAcceptanceUpdate = epiphany_core::EpiphanyReorientAcceptanceUpdate;
pub fn build_role_acceptance_update(
expected_revision: Option<u64>,
role_id: EpiphanyRoleResultRoleId,
binding_id: &str,
finding: &CoreEpiphanyRoleFinding,
accepted_evidence_id: String,
accepted_observation_id: String,
accepted_at: String,
) -> Result<RoleAcceptanceUpdate, String> {
epiphany_core::build_native_role_acceptance_update(
expected_revision,
role_id,
binding_id,
finding,
accepted_evidence_id,
accepted_observation_id,
accepted_at,
)
}
pub fn build_reorient_acceptance_update(
expected_revision: Option<u64>,
binding_id: &str,
finding: &CoreEpiphanyReorientFinding,
accepted_evidence_id: String,
accepted_observation_id: String,
accepted_at: String,
update_scratch: bool,
update_investigation_checkpoint: bool,
checkpoint: Option<EpiphanyInvestigationCheckpoint>,
) -> Result<ReorientAcceptanceUpdate, String> {
epiphany_core::build_native_reorient_acceptance_update(
expected_revision,
binding_id,
finding,
accepted_evidence_id,
accepted_observation_id,
accepted_at,
update_scratch,
update_investigation_checkpoint,
checkpoint,
)
}
pub fn state_update_from_core_patch(
expected_revision: Option<u64>,
patch: EpiphanyRoleStatePatchDocument,
) -> EpiphanyStateUpdate {
EpiphanyStateUpdate {
expected_revision,
objective: patch.objective,
active_subgoal_id: patch.active_subgoal_id,
subgoals: patch.subgoals,
invariants: patch.invariants,
graphs: patch.graphs,
graph_frontier: patch.graph_frontier,
graph_checkpoint: patch.graph_checkpoint,
scratch: patch.scratch,
investigation_checkpoint: patch.investigation_checkpoint,
job_bindings: patch.job_bindings,
acceptance_receipts: patch.acceptance_receipts,
runtime_links: patch.runtime_links,
observations: patch.observations,
evidence: patch.evidence,
churn: patch.churn,
mode: patch.mode,
planning: patch.planning,
}
}
pub fn epiphany_job_launch_changed_fields() -> Vec<EpiphanyStateUpdatedField> {
vec![
EpiphanyStateUpdatedField::JobBindings,
EpiphanyStateUpdatedField::RuntimeLinks,
]
}
pub fn thread_epiphany_patch_has_state_replacements(
patch: &EpiphanyRoleStatePatchDocument,
) -> bool {
patch.objective.is_some()
|| patch.active_subgoal_id.is_some()
|| patch.subgoals.is_some()
|| patch.invariants.is_some()
|| patch.graphs.is_some()
|| patch.graph_frontier.is_some()
|| patch.graph_checkpoint.is_some()
|| patch.scratch.is_some()
|| patch.investigation_checkpoint.is_some()
|| patch.job_bindings.is_some()
|| !patch.acceptance_receipts.is_empty()
|| !patch.runtime_links.is_empty()
|| patch.churn.is_some()
|| patch.mode.is_some()
|| patch.planning.is_some()
}
pub fn epiphany_update_patch_changed_fields(
patch: &EpiphanyRoleStatePatchDocument,
) -> Vec<EpiphanyStateUpdatedField> {
let update = state_update_from_core_patch(None, patch.clone());
let mut fields = Vec::new();
if update.objective.is_some() {
fields.push(EpiphanyStateUpdatedField::Objective);
}
if update.active_subgoal_id.is_some() {
fields.push(EpiphanyStateUpdatedField::ActiveSubgoalId);
}
if update.subgoals.is_some() {
fields.push(EpiphanyStateUpdatedField::Subgoals);
}
if update.invariants.is_some() {
fields.push(EpiphanyStateUpdatedField::Invariants);
}
if update.graphs.is_some() {
fields.push(EpiphanyStateUpdatedField::Graphs);
}
if update.graph_frontier.is_some() {
fields.push(EpiphanyStateUpdatedField::GraphFrontier);
}
if update.graph_checkpoint.is_some() {
fields.push(EpiphanyStateUpdatedField::GraphCheckpoint);
}
if update.scratch.is_some() {
fields.push(EpiphanyStateUpdatedField::Scratch);
}
if update.investigation_checkpoint.is_some() {
fields.push(EpiphanyStateUpdatedField::InvestigationCheckpoint);
}
if update.job_bindings.is_some() {
fields.push(EpiphanyStateUpdatedField::JobBindings);
}
if !update.acceptance_receipts.is_empty() {
fields.push(EpiphanyStateUpdatedField::AcceptanceReceipts);
}
if !update.runtime_links.is_empty() {
fields.push(EpiphanyStateUpdatedField::RuntimeLinks);
}
if !update.observations.is_empty() {
fields.push(EpiphanyStateUpdatedField::Observations);
}
if !update.evidence.is_empty() {
fields.push(EpiphanyStateUpdatedField::Evidence);
}
if update.churn.is_some() {
fields.push(EpiphanyStateUpdatedField::Churn);
}
if update.mode.is_some() {
fields.push(EpiphanyStateUpdatedField::Mode);
}
if update.planning.is_some() {
fields.push(EpiphanyStateUpdatedField::Planning);
}
fields
}
pub fn epiphany_promote_changed_fields(
patch: &EpiphanyRoleStatePatchDocument,
) -> Vec<EpiphanyStateUpdatedField> {
let mut fields = epiphany_update_patch_changed_fields(patch);
if !fields.contains(&EpiphanyStateUpdatedField::Evidence) {
fields.push(EpiphanyStateUpdatedField::Evidence);
}
fields
}

View file

@ -1,664 +0,0 @@
use chrono::SecondsFormat;
use chrono::Utc;
use std::path::Path;
use std::path::PathBuf;
use epiphany_core::EPIPHANY_REORIENT_LAUNCH_BINDING_ID;
use epiphany_core::EpiphanyJobInterruptRequest;
use epiphany_core::EpiphanyJobInterruptResult;
use epiphany_core::EpiphanyJobLaunchRequest;
use epiphany_core::EpiphanyJobLaunchResult;
use epiphany_core::EpiphanyJobView;
use epiphany_core::EpiphanyPromotionInput;
use epiphany_core::EpiphanyReorientDecision;
use epiphany_core::EpiphanyReorientFindingInterpretation;
use epiphany_core::EpiphanyReorientStateStatus;
use epiphany_core::EpiphanyRoleFindingInterpretation;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::EpiphanyRoleStatePatchDocument;
use epiphany_core::EpiphanyStateUpdate;
use epiphany_core::EpiphanyStateUpdatedField;
use epiphany_core::EpiphanyTokenUsageSnapshot;
use epiphany_core::apply_coordinator_state_update_to_state;
use epiphany_core::build_epiphany_reorient_launch_request_with_dynamic_context;
use epiphany_core::build_epiphany_role_launch_request_with_dynamic_context;
use epiphany_core::epiphany_role_label;
use epiphany_core::evaluate_promotion;
use epiphany_state_model::EpiphanyEvidenceRecord;
use epiphany_state_model::EpiphanyJobKind as CoreEpiphanyJobKind;
use epiphany_state_model::EpiphanyRetrievalState;
use epiphany_state_model::EpiphanyThreadState;
use crate::cultnet::EpiphanySurfaceSource;
use crate::error::EpiphanyBridgeError;
use crate::error::Result as BridgeResult;
use crate::jobs::derive_epiphany_jobs;
use crate::jobs::epiphany_blocked_state_job;
use crate::jobs::map_interrupted_epiphany_job;
use crate::jobs::map_launched_epiphany_job;
use crate::launch_context::append_modeling_work_loop_telemetry_context;
use crate::launch_context::append_verification_hands_receipt_context;
use crate::launch_context::render_launch_dynamic_prompt_context;
use crate::launch_context::reorient_launch_context_focus;
use crate::launch_context::role_launch_context_focus;
use crate::mutation::epiphany_job_launch_changed_fields;
use crate::mutation::epiphany_promote_changed_fields;
use crate::mutation::epiphany_update_patch_changed_fields;
use crate::mutation::thread_epiphany_patch_has_state_replacements;
use crate::pressure::derive_epiphany_pressure;
use crate::reorient::EpiphanyFreshnessWatcherSnapshot;
use crate::reorient::derive_epiphany_freshness_view;
use crate::reorient::derive_epiphany_reorient;
use uuid::Uuid;
#[allow(async_fn_in_trait)]
pub trait EpiphanyMutationHost {
async fn epiphany_thread_id(&self) -> String;
/// Read the Codex-hosted compatibility snapshot.
///
/// The bridge may request host state so core can evaluate typed policy. The
/// host snapshot is an input fact, not a bridge-owned source of truth.
async fn epiphany_state(&self) -> Option<EpiphanyThreadState>;
async fn epiphany_reference_turn_id(&self) -> Option<String>;
/// Locate the native runtime-spine store while Codex still hosts the turn.
async fn epiphany_runtime_spine_store_path(&self) -> PathBuf;
/// Project the already-typed state into Codex's current client-visible view.
async fn client_visible_epiphany_state(
&self,
fallback: EpiphanyThreadState,
) -> EpiphanyThreadState;
}
pub fn load_authoritative_accepted_state(
store_path: &Path,
) -> BridgeResult<Option<EpiphanyThreadState>> {
epiphany_core::read_accepted_coordinator_state(store_path)
.map_err(|error| EpiphanyBridgeError::Fatal(error.to_string()))
}
#[derive(Debug, Clone)]
pub struct EpiphanyThreadUpdateApplied {
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub epiphany_state: EpiphanyThreadState,
}
#[derive(Debug, Clone)]
pub enum EpiphanyThreadPromoteApplied {
Rejected { reasons: Vec<String> },
Accepted(EpiphanyThreadUpdateApplied),
}
#[derive(Debug, Clone)]
pub struct EpiphanyRoleAcceptApplied {
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub epiphany_state: EpiphanyThreadState,
pub accepted_receipt_id: String,
pub accepted_observation_id: String,
pub accepted_evidence_id: String,
pub applied_patch: EpiphanyRoleStatePatchDocument,
pub finding: EpiphanyRoleFindingInterpretation,
}
#[derive(Debug, Clone)]
pub struct EpiphanyReorientAcceptApplied {
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub epiphany_state: EpiphanyThreadState,
pub accepted_receipt_id: String,
pub accepted_observation_id: String,
pub accepted_evidence_id: String,
pub finding: EpiphanyReorientFindingInterpretation,
}
#[derive(Debug, Clone)]
pub struct EpiphanyJobLaunchApplied {
pub launcher_job_id: String,
pub backend_job_id: String,
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub epiphany_state: EpiphanyThreadState,
pub job: EpiphanyJobView,
}
#[derive(Debug, Clone)]
pub struct EpiphanyJobInterruptApplied {
pub cancel_requested: bool,
pub interrupted_thread_ids: Vec<String>,
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub epiphany_state: EpiphanyThreadState,
pub job: EpiphanyJobView,
}
#[derive(Debug, Clone)]
pub struct EpiphanyReorientLaunchApplied {
pub launcher_job_id: String,
pub backend_job_id: String,
pub source: EpiphanySurfaceSource,
pub state_status: EpiphanyReorientStateStatus,
pub state_revision: Option<u64>,
pub decision: EpiphanyReorientDecision,
pub revision: u64,
pub changed_fields: Vec<EpiphanyStateUpdatedField>,
pub epiphany_state: EpiphanyThreadState,
pub job: EpiphanyJobView,
}
pub async fn apply_epiphany_state_update_to_thread(
thread: &impl EpiphanyMutationHost,
update: EpiphanyStateUpdate,
) -> BridgeResult<EpiphanyThreadState> {
let current_state = thread.epiphany_state().await.unwrap_or_default();
let reference_turn_id = thread.epiphany_reference_turn_id().await;
let store = thread.epiphany_runtime_spine_store_path().await;
let thread_id = thread.epiphany_thread_id().await;
let applied = epiphany_core::EpiphanyCoordinatorService::new(&store, &store)
.apply_state_update_from(&thread_id, &current_state, update, reference_turn_id)
.map_err(|error| EpiphanyBridgeError::InvalidRequest(error.to_string()))?;
Ok(applied.state)
}
pub fn apply_epiphany_state_update_to_state(
current_state: &EpiphanyThreadState,
update: EpiphanyStateUpdate,
reference_turn_id: Option<String>,
) -> BridgeResult<EpiphanyThreadState> {
apply_coordinator_state_update_to_state(current_state, update, reference_turn_id)
.map_err(|error| EpiphanyBridgeError::InvalidRequest(error.to_string()))
}
pub async fn launch_epiphany_job_on_thread(
thread: &impl EpiphanyMutationHost,
request: EpiphanyJobLaunchRequest,
) -> BridgeResult<EpiphanyJobLaunchResult> {
// Compatibility choreography only: core validates the launch plan and
// runtime-spine opens the typed job. The bridge stitches those typed
// documents into Codex's JSON-RPC thread shell until CultNet owns the route.
let current_state = thread.epiphany_state().await.unwrap_or_default();
let runtime_store = thread.epiphany_runtime_spine_store_path().await;
let launch_plan = epiphany_core::plan_coordinator_job_launch(
&current_state,
&request,
runtime_store.as_path(),
format!("epiphany-heartbeat-launch-{}", Uuid::new_v4()),
Uuid::new_v4().to_string(),
)
.map_err(|err| EpiphanyBridgeError::InvalidRequest(err.to_string()))?;
let thread_id = thread.epiphany_thread_id().await;
epiphany_core::commit_coordinator_job_launch(
runtime_store.as_path(),
&thread_id,
&current_state,
&request,
&launch_plan,
Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
)
.map_err(|error| EpiphanyBridgeError::Fatal(error.to_string()))
}
pub async fn interrupt_epiphany_job_on_thread(
thread: &impl EpiphanyMutationHost,
request: EpiphanyJobInterruptRequest,
) -> BridgeResult<EpiphanyJobInterruptResult> {
let current_state = thread.epiphany_state().await.unwrap_or_default();
let store = thread.epiphany_runtime_spine_store_path().await;
let thread_id = thread.epiphany_thread_id().await;
epiphany_core::EpiphanyCoordinatorService::new(&store, &store)
.interrupt_job(&thread_id, &current_state, request)
.map_err(|error| EpiphanyBridgeError::InvalidRequest(error.to_string()))
}
pub async fn apply_thread_epiphany_update(
thread: &impl EpiphanyMutationHost,
expected_revision: Option<u64>,
patch: EpiphanyRoleStatePatchDocument,
) -> BridgeResult<EpiphanyThreadUpdateApplied> {
let changed_fields = epiphany_update_patch_changed_fields(&patch);
let update = crate::mutation::state_update_from_core_patch(expected_revision, patch);
let epiphany_state = apply_epiphany_state_update_to_thread(thread, update).await?;
let epiphany_state = thread.client_visible_epiphany_state(epiphany_state).await;
Ok(EpiphanyThreadUpdateApplied {
revision: epiphany_state.revision,
changed_fields,
epiphany_state,
})
}
pub async fn apply_thread_epiphany_promote(
thread: &impl EpiphanyMutationHost,
expected_revision: Option<u64>,
patch: EpiphanyRoleStatePatchDocument,
verifier_evidence: EpiphanyEvidenceRecord,
) -> BridgeResult<EpiphanyThreadPromoteApplied> {
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);
let update = crate::mutation::state_update_from_core_patch(expected_revision, patch);
let epiphany_state = apply_epiphany_state_update_to_thread(thread, update).await?;
let epiphany_state = thread.client_visible_epiphany_state(epiphany_state).await;
Ok(EpiphanyThreadPromoteApplied::Accepted(
EpiphanyThreadUpdateApplied {
revision: epiphany_state.revision,
changed_fields,
epiphany_state,
},
))
}
pub async fn apply_thread_epiphany_role_accept(
thread: &impl EpiphanyMutationHost,
role_id: EpiphanyRoleResultRoleId,
expected_revision: Option<u64>,
binding_id: &str,
) -> BridgeResult<EpiphanyRoleAcceptApplied> {
let state = thread.epiphany_state().await.ok_or_else(|| {
EpiphanyBridgeError::InvalidRequest(
"cannot accept an Epiphany role finding without authoritative Epiphany state"
.to_string(),
)
})?;
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let thread_id = thread.epiphany_thread_id().await;
let service = epiphany_core::EpiphanyCoordinatorService::new(
runtime_store_path.clone(),
runtime_store_path,
);
let accepted = service
.accept_role(
&thread_id,
&state,
role_id,
binding_id,
expected_revision,
thread.epiphany_reference_turn_id().await,
Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
Uuid::new_v4().to_string().as_str(),
)
.map_err(|error| EpiphanyBridgeError::InvalidRequest(error.to_string()))?;
Ok(EpiphanyRoleAcceptApplied {
revision: accepted.state.revision,
changed_fields: accepted.update.changed_fields,
epiphany_state: accepted.state,
accepted_receipt_id: accepted.update.accepted_receipt_id,
accepted_observation_id: accepted.update.accepted_observation_id,
accepted_evidence_id: accepted.update.accepted_evidence_id,
applied_patch: accepted.update.applied_patch,
finding: accepted.finding,
})
}
pub async fn apply_thread_epiphany_reorient_accept(
thread: &impl EpiphanyMutationHost,
expected_revision: Option<u64>,
binding_id: &str,
update_scratch: bool,
update_investigation_checkpoint: bool,
) -> BridgeResult<EpiphanyReorientAcceptApplied> {
let state = thread.epiphany_state().await.ok_or_else(|| {
EpiphanyBridgeError::InvalidRequest(
"cannot accept a reorientation finding without authoritative Epiphany state"
.to_string(),
)
})?;
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let thread_id = thread.epiphany_thread_id().await;
let service = epiphany_core::EpiphanyCoordinatorService::new(
runtime_store_path.clone(),
runtime_store_path,
);
let accepted = service
.accept_reorient(
&thread_id,
&state,
binding_id,
expected_revision,
thread.epiphany_reference_turn_id().await,
Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
Uuid::new_v4().to_string().as_str(),
update_scratch,
update_investigation_checkpoint,
)
.map_err(|error| EpiphanyBridgeError::InvalidRequest(error.to_string()))?;
Ok(EpiphanyReorientAcceptApplied {
revision: accepted.state.revision,
changed_fields: accepted.update.changed_fields,
epiphany_state: accepted.state,
accepted_receipt_id: accepted.update.accepted_receipt_id,
accepted_observation_id: accepted.update.accepted_observation_id,
accepted_evidence_id: accepted.update.accepted_evidence_id,
finding: accepted.finding,
})
}
pub async fn launch_thread_epiphany_role(
thread: &impl EpiphanyMutationHost,
thread_id: &str,
role_id: EpiphanyRoleResultRoleId,
expected_revision: Option<u64>,
max_runtime_seconds: Option<u64>,
) -> BridgeResult<EpiphanyJobLaunchApplied> {
let state = thread.epiphany_state().await.ok_or_else(|| {
EpiphanyBridgeError::InvalidRequest(
"cannot launch an Epiphany role specialist without authoritative Epiphany state"
.to_string(),
)
})?;
validate_expected_revision(expected_revision, state.revision)?;
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let role_label = epiphany_role_label(role_id);
let mut dynamic_prompt_context = render_launch_dynamic_prompt_context(
runtime_store_path.as_path(),
&state,
role_launch_context_focus(&state, role_label),
)
.map_err(EpiphanyBridgeError::Fatal)?;
if role_id == EpiphanyRoleResultRoleId::Verification {
dynamic_prompt_context = append_verification_hands_receipt_context(
dynamic_prompt_context,
runtime_store_path.as_path(),
&state,
)
.map_err(EpiphanyBridgeError::Fatal)?;
} else if role_id == EpiphanyRoleResultRoleId::Modeling {
dynamic_prompt_context = append_modeling_work_loop_telemetry_context(
dynamic_prompt_context,
runtime_store_path.as_path(),
&state,
)
.map_err(EpiphanyBridgeError::Fatal)?;
}
let launch_request = build_epiphany_role_launch_request_with_dynamic_context(
thread_id,
role_id,
expected_revision,
max_runtime_seconds,
&state,
Some(dynamic_prompt_context),
)
.map_err(EpiphanyBridgeError::InvalidRequest)?;
launch_thread_epiphany_job(
thread,
launch_request,
CoreEpiphanyJobKind::Specialist,
"missing launched role projection",
)
.await
}
pub async fn launch_thread_epiphany_job(
thread: &impl EpiphanyMutationHost,
launch_request: EpiphanyJobLaunchRequest,
kind: CoreEpiphanyJobKind,
missing_projection_reason: &str,
) -> BridgeResult<EpiphanyJobLaunchApplied> {
let changed_fields = epiphany_job_launch_changed_fields();
let launched = launch_epiphany_job_on_thread(thread, launch_request).await?;
let epiphany_state = thread
.client_visible_epiphany_state(launched.epiphany_state)
.await;
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 {
launcher_job_id: launched.launcher_job_id,
backend_job_id: launched.backend_job_id,
revision: epiphany_state.revision,
changed_fields,
epiphany_state,
job,
})
}
pub async fn interrupt_thread_epiphany_job(
thread: &impl EpiphanyMutationHost,
expected_revision: Option<u64>,
binding_id: &str,
reason: Option<String>,
) -> BridgeResult<EpiphanyJobInterruptApplied> {
let changed_fields = vec![EpiphanyStateUpdatedField::JobBindings];
let interrupted = interrupt_epiphany_job_on_thread(
thread,
EpiphanyJobInterruptRequest {
expected_revision,
binding_id: binding_id.to_string(),
reason,
},
)
.await?;
let epiphany_state = thread
.client_visible_epiphany_state(interrupted.epiphany_state)
.await;
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,
})
}
pub async fn launch_thread_epiphany_reorient(
thread: &impl EpiphanyMutationHost,
thread_id: &str,
expected_revision: Option<u64>,
max_runtime_seconds: Option<u64>,
state: Option<&EpiphanyThreadState>,
retrieval_override: Option<&EpiphanyRetrievalState>,
watcher_snapshot: Option<EpiphanyFreshnessWatcherSnapshot<'_>>,
token_usage_info: Option<&EpiphanyTokenUsageSnapshot>,
) -> BridgeResult<EpiphanyReorientLaunchApplied> {
let freshness = derive_epiphany_freshness_view(state, retrieval_override, watcher_snapshot);
let state_revision = freshness.state_revision;
let pressure = derive_epiphany_pressure(token_usage_info);
let (state_status, decision) = derive_epiphany_reorient(
state,
&pressure,
&freshness.retrieval,
&freshness.graph,
&freshness.watcher,
);
let state = state.ok_or_else(|| {
EpiphanyBridgeError::InvalidRequest(format!(
"cannot launch a reorientation worker without authoritative Epiphany state: {}",
decision.note
))
})?;
validate_expected_revision(expected_revision, state.revision)?;
let checkpoint = state.investigation_checkpoint.as_ref().ok_or_else(|| {
EpiphanyBridgeError::InvalidRequest(format!(
"cannot launch a reorientation worker without a durable investigation checkpoint: {}",
decision.note
))
})?;
let runtime_store_path = thread.epiphany_runtime_spine_store_path().await;
let dynamic_prompt_context = render_launch_dynamic_prompt_context(
runtime_store_path.as_path(),
state,
reorient_launch_context_focus(state, &decision.next_action),
)
.map_err(EpiphanyBridgeError::Fatal)?;
let launch_request = build_epiphany_reorient_launch_request_with_dynamic_context(
thread_id,
expected_revision,
max_runtime_seconds,
state,
checkpoint,
&decision,
Some(dynamic_prompt_context),
);
let changed_fields = epiphany_job_launch_changed_fields();
let launched = launch_epiphany_job_on_thread(thread, launch_request).await?;
let epiphany_state = thread
.client_visible_epiphany_state(launched.epiphany_state)
.await;
let job = derive_epiphany_jobs(Some(&epiphany_state), None)
.into_iter()
.find(|job| job.id == EPIPHANY_REORIENT_LAUNCH_BINDING_ID)
.unwrap_or_else(|| {
epiphany_blocked_state_job(
EPIPHANY_REORIENT_LAUNCH_BINDING_ID,
CoreEpiphanyJobKind::Specialist,
"reorient-guided checkpoint regather",
"Launched reorientation worker was not reflected in Epiphany state.",
)
});
Ok(EpiphanyReorientLaunchApplied {
launcher_job_id: launched.launcher_job_id,
backend_job_id: launched.backend_job_id,
source: EpiphanySurfaceSource::Live,
state_status,
state_revision,
decision,
revision: epiphany_state.revision,
changed_fields,
epiphany_state,
job,
})
}
fn validate_expected_revision(
expected_revision: Option<u64>,
actual_revision: u64,
) -> BridgeResult<()> {
if let Some(expected_revision) = expected_revision
&& actual_revision != expected_revision
{
return Err(EpiphanyBridgeError::InvalidRequest(format!(
"epiphany state revision mismatch: expected {expected_revision}, found {actual_revision}"
)));
}
Ok(())
}
#[cfg(test)]
mod acceptance_architecture_tests {
#[test]
fn generic_update_commits_native_state_without_rollout_mirror() {
let source = include_str!("mutation_service.rs");
let start = source
.find("pub async fn apply_epiphany_state_update_to_thread")
.unwrap();
let end = source
.find("pub fn apply_epiphany_state_update_to_state")
.unwrap();
let update = &source[start..end];
assert_eq!(update.matches(".apply_state_update_from(").count(), 1);
assert_eq!(update.matches("epiphany_persist_state(").count(), 0);
assert!(!update.contains("Ok(next_state)"));
assert!(update.contains("Ok(applied.state)"));
}
#[test]
fn interrupt_route_delegates_binding_mutation_to_native_service() {
let source = include_str!("mutation_service.rs");
let start = source
.find("pub async fn interrupt_epiphany_job_on_thread")
.unwrap();
let end = source
.find("pub async fn apply_thread_epiphany_update")
.unwrap();
let interrupt = &source[start..end];
assert_eq!(interrupt.matches(".interrupt_job(").count(), 1);
for forbidden in [
["clear", "epiphany", "job", "binding", "backend"].join("_"),
["job_bindings", "Some"].join(": "),
["apply", "epiphany", "state", "update", "to", "thread"].join("_"),
] {
assert!(
!interrupt.contains(&forbidden),
"interrupt route regrew binding policy {forbidden:?}"
);
}
}
#[test]
fn launch_route_delegates_planning_to_the_native_organ() {
let source = include_str!("mutation_service.rs");
let launch_start = source
.find("pub async fn launch_epiphany_job_on_thread")
.unwrap();
let interrupt_start = source
.find("pub async fn interrupt_epiphany_job_on_thread")
.unwrap();
let launch = &source[launch_start..interrupt_start];
assert_eq!(launch.matches("plan_coordinator_job_launch").count(), 1);
assert_eq!(launch.matches("commit_coordinator_job_launch").count(), 1);
for forbidden in [
["plan", "runtime", "spine", "heartbeat", "launch"].join("_"),
["replace", "or", "append", "epiphany", "job", "binding"].join("_"),
["runtime", "job", "snapshot"].join("_"),
["epiphany", "state", "update", "validation", "errors"].join("_"),
["open", "epiphany", "runtime", "spine", "job"].join("_"),
["maybe", "put", "substrate", "gate", "launch", "grant"].join("_"),
["apply", "epiphany", "state", "update", "to", "thread"].join("_"),
] {
assert!(
!launch.contains(&forbidden),
"launch route regrew native planning policy {forbidden:?}"
);
}
}
#[test]
fn acceptance_routes_have_no_individual_or_post_state_receipt_writes() {
let source = include_str!("mutation_service.rs");
let role_start = source
.find("pub async fn apply_thread_epiphany_role_accept")
.unwrap();
let launch_start = source
.find("pub async fn launch_thread_epiphany_role")
.unwrap();
let acceptance = &source[role_start..launch_start];
for forbidden in [
["put", "mind", "gateway", "review"].join("_"),
["put", "eyes", "evidence", "packet"].join("_"),
["put", "soul", "verdict", "receipt"].join("_"),
["put", "continuity", "recovery", "receipt"].join("_"),
["admit", "epiphany", "state", "with", "mind", "commit"].join("_"),
["epiphany", "persist", "state"].join("_"),
] {
assert!(
!acceptance.contains(&forbidden),
"acceptance route regrew obsolete writer {forbidden:?}"
);
}
assert_eq!(
acceptance.matches("commit_state_with_mind_witness").count(),
0
);
assert_eq!(acceptance.matches(".accept_role(").count(), 1);
assert_eq!(acceptance.matches(".accept_reorient(").count(), 1);
}
}

View file

@ -1,7 +0,0 @@
use epiphany_core::EpiphanyPressure;
pub use epiphany_core::EpiphanyTokenUsageSnapshot;
use epiphany_core::derive_pressure_view;
pub fn derive_epiphany_pressure(snapshot: Option<&EpiphanyTokenUsageSnapshot>) -> EpiphanyPressure {
derive_pressure_view(snapshot)
}

View file

@ -1,694 +0,0 @@
use crate::cultnet::EpiphanyFreshnessSurface;
use crate::cultnet::EpiphanyGraphFreshnessStatus;
use crate::cultnet::EpiphanyInvalidationStatus;
use crate::cultnet::EpiphanyJobKind;
use crate::cultnet::EpiphanyJobStatus;
use crate::cultnet::EpiphanyJobView;
use crate::cultnet::EpiphanyReorientAction;
use crate::cultnet::EpiphanyReorientCheckpointStatus;
use crate::cultnet::EpiphanyReorientDecision;
use crate::cultnet::EpiphanyReorientFreshnessStatus;
use crate::cultnet::EpiphanyReorientPressureLevel;
use crate::cultnet::EpiphanyReorientReason;
use crate::cultnet::EpiphanyReorientStateStatus;
use crate::cultnet::EpiphanyRetrievalFreshnessStatus;
use crate::cultnet::EpiphanySurfaceSource;
use codex_app_server_protocol::ThreadEpiphanyContextParams;
use codex_app_server_protocol::ThreadEpiphanyFreshnessResponse;
use codex_app_server_protocol::ThreadEpiphanyFreshnessSource;
use codex_app_server_protocol::ThreadEpiphanyGraphFreshness;
use codex_app_server_protocol::ThreadEpiphanyGraphFreshnessStatus;
use codex_app_server_protocol::ThreadEpiphanyGraphQuery;
use codex_app_server_protocol::ThreadEpiphanyGraphQueryDirection;
use codex_app_server_protocol::ThreadEpiphanyGraphQueryKind;
use codex_app_server_protocol::ThreadEpiphanyInvalidationInput;
use codex_app_server_protocol::ThreadEpiphanyInvalidationStatus;
use codex_app_server_protocol::ThreadEpiphanyJob;
use codex_app_server_protocol::ThreadEpiphanyJobKind;
use codex_app_server_protocol::ThreadEpiphanyJobStatus;
use codex_app_server_protocol::ThreadEpiphanyPressure;
use codex_app_server_protocol::ThreadEpiphanyPressureBasis;
use codex_app_server_protocol::ThreadEpiphanyPressureLevel;
use codex_app_server_protocol::ThreadEpiphanyPressureStatus;
use codex_app_server_protocol::ThreadEpiphanyReorientAction;
use codex_app_server_protocol::ThreadEpiphanyReorientCheckpointStatus;
use codex_app_server_protocol::ThreadEpiphanyReorientDecision;
use codex_app_server_protocol::ThreadEpiphanyReorientFinding;
use codex_app_server_protocol::ThreadEpiphanyReorientReason;
use codex_app_server_protocol::ThreadEpiphanyReorientResultStatus;
use codex_app_server_protocol::ThreadEpiphanyReorientSource;
use codex_app_server_protocol::ThreadEpiphanyReorientStateStatus;
use codex_app_server_protocol::ThreadEpiphanyRetrievalFreshness;
use codex_app_server_protocol::ThreadEpiphanyRetrievalFreshnessStatus;
use codex_app_server_protocol::ThreadEpiphanyRoleFinding;
use codex_app_server_protocol::ThreadEpiphanyRoleId;
use codex_app_server_protocol::ThreadEpiphanyRoleResultStatus;
use codex_app_server_protocol::ThreadEpiphanyRoleSelfPersistenceReview;
use codex_app_server_protocol::ThreadEpiphanyRoleSelfPersistenceStatus;
use codex_app_server_protocol::ThreadEpiphanyRolesSource;
use codex_app_server_protocol::ThreadEpiphanyStateUpdatedField;
use codex_app_server_protocol::ThreadEpiphanyStateUpdatedNotification;
use codex_app_server_protocol::ThreadEpiphanyStateUpdatedSource;
use codex_app_server_protocol::ThreadEpiphanyUpdatePatch;
use codex_app_server_protocol::ThreadEpiphanyViewLens;
use epiphany_core::EpiphanyContextParams;
use epiphany_core::EpiphanyCoordinatorRoleResultStatus;
use epiphany_core::EpiphanyCrrcResultStatus;
use epiphany_core::EpiphanyGraphQuery;
use epiphany_core::EpiphanyGraphQueryDirection;
use epiphany_core::EpiphanyGraphQueryKind;
use epiphany_core::EpiphanyPressure;
use epiphany_core::EpiphanyPressureBasis;
use epiphany_core::EpiphanyPressureLevel;
use epiphany_core::EpiphanyPressureStatus;
use epiphany_core::EpiphanyReorientFindingInterpretation;
use epiphany_core::EpiphanyRoleFindingInterpretation;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::EpiphanyRoleSelfPersistenceReview;
use epiphany_core::EpiphanyRoleSelfPersistenceStatus;
use epiphany_core::EpiphanyRoleStatePatchDocument;
use epiphany_core::EpiphanyStateUpdatedField;
use epiphany_core::EpiphanyViewLens;
use epiphany_core::default_epiphany_view_lenses;
use epiphany_core::epiphany_view_needs_jobs;
use epiphany_core::epiphany_view_needs_pressure;
use epiphany_core::epiphany_view_needs_reorientation_inputs;
use epiphany_core::epiphany_view_needs_runtime_store;
use epiphany_state_model::EpiphanyThreadState;
pub fn default_core_epiphany_view_lenses() -> Vec<EpiphanyViewLens> {
default_epiphany_view_lenses()
}
pub fn protocol_view_lenses_to_core(lenses: Vec<ThreadEpiphanyViewLens>) -> Vec<EpiphanyViewLens> {
lenses.into_iter().map(protocol_view_lens_to_core).collect()
}
pub fn protocol_view_lens_from_core(lens: EpiphanyViewLens) -> ThreadEpiphanyViewLens {
match lens {
EpiphanyViewLens::Scene => ThreadEpiphanyViewLens::Scene,
EpiphanyViewLens::Jobs => ThreadEpiphanyViewLens::Jobs,
EpiphanyViewLens::Roles => ThreadEpiphanyViewLens::Roles,
EpiphanyViewLens::Planning => ThreadEpiphanyViewLens::Planning,
EpiphanyViewLens::Pressure => ThreadEpiphanyViewLens::Pressure,
EpiphanyViewLens::Reorient => ThreadEpiphanyViewLens::Reorient,
EpiphanyViewLens::Crrc => ThreadEpiphanyViewLens::Crrc,
EpiphanyViewLens::Coordinator => ThreadEpiphanyViewLens::Coordinator,
}
}
pub fn core_epiphany_view_needs_jobs(lenses: &[EpiphanyViewLens]) -> bool {
epiphany_view_needs_jobs(lenses)
}
pub fn core_epiphany_view_needs_reorientation_inputs(lenses: &[EpiphanyViewLens]) -> bool {
epiphany_view_needs_reorientation_inputs(lenses)
}
pub fn core_epiphany_view_needs_pressure(lenses: &[EpiphanyViewLens]) -> bool {
epiphany_view_needs_pressure(lenses)
}
pub fn core_epiphany_view_needs_runtime_store(lenses: &[EpiphanyViewLens]) -> bool {
epiphany_view_needs_runtime_store(lenses)
}
pub fn protocol_context_params_to_core(
params: &ThreadEpiphanyContextParams,
) -> EpiphanyContextParams {
EpiphanyContextParams {
graph_node_ids: params.graph_node_ids.clone(),
graph_edge_ids: params.graph_edge_ids.clone(),
observation_ids: params.observation_ids.clone(),
evidence_ids: params.evidence_ids.clone(),
include_active_frontier: params.include_active_frontier,
include_linked_evidence: params.include_linked_evidence,
}
}
pub fn protocol_graph_query_to_core(query: &ThreadEpiphanyGraphQuery) -> EpiphanyGraphQuery {
EpiphanyGraphQuery {
kind: protocol_graph_query_kind_to_core(query.kind),
node_ids: query.node_ids.clone(),
edge_ids: query.edge_ids.clone(),
paths: query.paths.clone(),
symbols: query.symbols.clone(),
edge_kinds: query.edge_kinds.clone(),
direction: query.direction.map(protocol_graph_query_direction_to_core),
depth: query.depth,
include_links: query.include_links,
}
}
pub fn protocol_update_patch_to_core(
patch: &ThreadEpiphanyUpdatePatch,
) -> EpiphanyRoleStatePatchDocument {
EpiphanyRoleStatePatchDocument {
objective: patch.objective.clone(),
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(),
scratch: patch.scratch.clone(),
investigation_checkpoint: patch.investigation_checkpoint.clone(),
job_bindings: patch.job_bindings.clone(),
acceptance_receipts: patch.acceptance_receipts.clone(),
runtime_links: patch.runtime_links.clone(),
observations: patch.observations.clone(),
evidence: patch.evidence.clone(),
churn: patch.churn.clone(),
mode: patch.mode.clone(),
planning: patch.planning.clone(),
}
}
pub fn protocol_patch_from_core(
patch: EpiphanyRoleStatePatchDocument,
) -> ThreadEpiphanyUpdatePatch {
ThreadEpiphanyUpdatePatch {
objective: patch.objective,
active_subgoal_id: patch.active_subgoal_id,
subgoals: patch.subgoals,
invariants: patch.invariants,
graphs: patch.graphs,
graph_frontier: patch.graph_frontier,
graph_checkpoint: patch.graph_checkpoint,
scratch: patch.scratch,
investigation_checkpoint: patch.investigation_checkpoint,
job_bindings: patch.job_bindings,
acceptance_receipts: patch.acceptance_receipts,
runtime_links: patch.runtime_links,
observations: patch.observations,
evidence: patch.evidence,
churn: patch.churn,
mode: patch.mode,
planning: patch.planning,
}
}
pub fn protocol_role_id_to_core(role_id: ThreadEpiphanyRoleId) -> EpiphanyRoleResultRoleId {
match role_id {
ThreadEpiphanyRoleId::Implementation => EpiphanyRoleResultRoleId::Implementation,
ThreadEpiphanyRoleId::Imagination => EpiphanyRoleResultRoleId::Imagination,
ThreadEpiphanyRoleId::Research => EpiphanyRoleResultRoleId::Research,
ThreadEpiphanyRoleId::Modeling => EpiphanyRoleResultRoleId::Modeling,
ThreadEpiphanyRoleId::Verification => EpiphanyRoleResultRoleId::Verification,
ThreadEpiphanyRoleId::Reorientation => EpiphanyRoleResultRoleId::Reorientation,
}
}
pub fn protocol_role_id_from_core(role_id: EpiphanyRoleResultRoleId) -> ThreadEpiphanyRoleId {
match role_id {
EpiphanyRoleResultRoleId::Implementation => ThreadEpiphanyRoleId::Implementation,
EpiphanyRoleResultRoleId::Imagination => ThreadEpiphanyRoleId::Imagination,
EpiphanyRoleResultRoleId::Research => ThreadEpiphanyRoleId::Research,
EpiphanyRoleResultRoleId::Modeling => ThreadEpiphanyRoleId::Modeling,
EpiphanyRoleResultRoleId::Verification => ThreadEpiphanyRoleId::Verification,
EpiphanyRoleResultRoleId::Reorientation => ThreadEpiphanyRoleId::Reorientation,
}
}
pub fn protocol_reorient_finding(
finding: EpiphanyReorientFindingInterpretation,
) -> ThreadEpiphanyReorientFinding {
ThreadEpiphanyReorientFinding {
mode: finding.mode,
summary: finding.summary,
next_safe_move: finding.next_safe_move,
checkpoint_still_valid: finding.checkpoint_still_valid,
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,
job_error: finding.job_error,
item_error: finding.item_error,
}
}
pub fn protocol_role_finding(
role_id: ThreadEpiphanyRoleId,
finding: EpiphanyRoleFindingInterpretation,
) -> ThreadEpiphanyRoleFinding {
let state_patch = finding.state_patch.map(protocol_patch_from_core);
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.map(|patch| {
serde_json::to_value(patch)
.expect("AgentSelfPatch is a serializable protocol projection")
}),
self_persistence: finding
.self_persistence
.map(protocol_self_persistence_review),
job_error: finding.job_error,
item_error: finding.item_error,
}
}
pub fn protocol_state_updated_notification(
thread_id: String,
source: ThreadEpiphanyStateUpdatedSource,
revision: u64,
changed_fields: Vec<EpiphanyStateUpdatedField>,
epiphany_state: EpiphanyThreadState,
) -> ThreadEpiphanyStateUpdatedNotification {
ThreadEpiphanyStateUpdatedNotification {
thread_id,
source,
revision,
changed_fields: protocol_state_updated_fields(changed_fields),
epiphany_state,
}
}
pub fn protocol_state_updated_fields(
fields: Vec<EpiphanyStateUpdatedField>,
) -> Vec<ThreadEpiphanyStateUpdatedField> {
fields
.into_iter()
.map(protocol_state_updated_field)
.collect()
}
pub fn protocol_state_updated_field(
field: EpiphanyStateUpdatedField,
) -> ThreadEpiphanyStateUpdatedField {
match field {
EpiphanyStateUpdatedField::Objective => ThreadEpiphanyStateUpdatedField::Objective,
EpiphanyStateUpdatedField::ActiveSubgoalId => {
ThreadEpiphanyStateUpdatedField::ActiveSubgoalId
}
EpiphanyStateUpdatedField::Subgoals => ThreadEpiphanyStateUpdatedField::Subgoals,
EpiphanyStateUpdatedField::Invariants => ThreadEpiphanyStateUpdatedField::Invariants,
EpiphanyStateUpdatedField::Graphs => ThreadEpiphanyStateUpdatedField::Graphs,
EpiphanyStateUpdatedField::GraphFrontier => ThreadEpiphanyStateUpdatedField::GraphFrontier,
EpiphanyStateUpdatedField::GraphCheckpoint => {
ThreadEpiphanyStateUpdatedField::GraphCheckpoint
}
EpiphanyStateUpdatedField::Scratch => ThreadEpiphanyStateUpdatedField::Scratch,
EpiphanyStateUpdatedField::InvestigationCheckpoint => {
ThreadEpiphanyStateUpdatedField::InvestigationCheckpoint
}
EpiphanyStateUpdatedField::JobBindings => ThreadEpiphanyStateUpdatedField::JobBindings,
EpiphanyStateUpdatedField::AcceptanceReceipts => {
ThreadEpiphanyStateUpdatedField::AcceptanceReceipts
}
EpiphanyStateUpdatedField::RuntimeLinks => ThreadEpiphanyStateUpdatedField::RuntimeLinks,
EpiphanyStateUpdatedField::Observations => ThreadEpiphanyStateUpdatedField::Observations,
EpiphanyStateUpdatedField::Evidence => ThreadEpiphanyStateUpdatedField::Evidence,
EpiphanyStateUpdatedField::Churn => ThreadEpiphanyStateUpdatedField::Churn,
EpiphanyStateUpdatedField::Mode => ThreadEpiphanyStateUpdatedField::Mode,
EpiphanyStateUpdatedField::Planning => ThreadEpiphanyStateUpdatedField::Planning,
}
}
pub fn protocol_freshness_response_from_surface(
surface: EpiphanyFreshnessSurface,
) -> ThreadEpiphanyFreshnessResponse {
ThreadEpiphanyFreshnessResponse {
thread_id: surface.thread_id,
source: match surface.source {
EpiphanySurfaceSource::Stored => ThreadEpiphanyFreshnessSource::Stored,
EpiphanySurfaceSource::Live => ThreadEpiphanyFreshnessSource::Live,
},
state_revision: surface.state_revision,
retrieval: ThreadEpiphanyRetrievalFreshness {
status: match surface.retrieval.status {
EpiphanyRetrievalFreshnessStatus::Missing => {
ThreadEpiphanyRetrievalFreshnessStatus::Missing
}
EpiphanyRetrievalFreshnessStatus::Ready => {
ThreadEpiphanyRetrievalFreshnessStatus::Ready
}
EpiphanyRetrievalFreshnessStatus::Stale => {
ThreadEpiphanyRetrievalFreshnessStatus::Stale
}
EpiphanyRetrievalFreshnessStatus::Indexing => {
ThreadEpiphanyRetrievalFreshnessStatus::Indexing
}
EpiphanyRetrievalFreshnessStatus::Unavailable => {
ThreadEpiphanyRetrievalFreshnessStatus::Unavailable
}
},
semantic_available: surface.retrieval.semantic_available,
last_indexed_at_unix_seconds: surface.retrieval.last_indexed_at_unix_seconds,
indexed_file_count: surface.retrieval.indexed_file_count,
indexed_chunk_count: surface.retrieval.indexed_chunk_count,
dirty_paths: surface.retrieval.dirty_paths,
note: surface.retrieval.note,
},
graph: ThreadEpiphanyGraphFreshness {
status: match surface.graph.status {
EpiphanyGraphFreshnessStatus::Missing => {
ThreadEpiphanyGraphFreshnessStatus::Missing
}
EpiphanyGraphFreshnessStatus::Ready => ThreadEpiphanyGraphFreshnessStatus::Ready,
EpiphanyGraphFreshnessStatus::Stale => ThreadEpiphanyGraphFreshnessStatus::Stale,
},
graph_freshness: surface.graph.graph_freshness,
checkpoint_id: surface.graph.checkpoint_id,
dirty_path_count: surface.graph.dirty_path_count,
dirty_paths: surface.graph.dirty_paths,
open_question_count: surface.graph.open_question_count,
open_gap_count: surface.graph.open_gap_count,
note: surface.graph.note,
},
watcher: ThreadEpiphanyInvalidationInput {
status: match surface.watcher.status {
EpiphanyInvalidationStatus::Unavailable => {
ThreadEpiphanyInvalidationStatus::Unavailable
}
EpiphanyInvalidationStatus::Clean => ThreadEpiphanyInvalidationStatus::Clean,
EpiphanyInvalidationStatus::Changed => ThreadEpiphanyInvalidationStatus::Changed,
},
watched_root: surface.watcher.watched_root,
observed_at_unix_seconds: surface.watcher.observed_at_unix_seconds,
changed_path_count: surface.watcher.changed_path_count,
changed_paths: surface.watcher.changed_paths,
graph_node_ids: surface.watcher.graph_node_ids,
active_frontier_node_ids: surface.watcher.active_frontier_node_ids,
note: surface.watcher.note,
},
}
}
pub fn protocol_job_from_surface(
job: EpiphanyJobView,
launcher_job_id: Option<String>,
backend_job_id_override: Option<String>,
) -> ThreadEpiphanyJob {
ThreadEpiphanyJob {
id: job.id,
kind: match job.kind {
EpiphanyJobKind::Indexing => ThreadEpiphanyJobKind::Indexing,
EpiphanyJobKind::Remap => ThreadEpiphanyJobKind::Remap,
EpiphanyJobKind::Verification => ThreadEpiphanyJobKind::Verification,
EpiphanyJobKind::Specialist => ThreadEpiphanyJobKind::Specialist,
},
scope: job.scope,
owner_role: job.owner_role,
launcher_job_id,
authority_scope: job.authority_scope,
backend_job_id: backend_job_id_override.or(job.runtime_job_id),
status: match job.status {
EpiphanyJobStatus::Idle => ThreadEpiphanyJobStatus::Idle,
EpiphanyJobStatus::Needed => ThreadEpiphanyJobStatus::Needed,
EpiphanyJobStatus::Pending => ThreadEpiphanyJobStatus::Pending,
EpiphanyJobStatus::Running => ThreadEpiphanyJobStatus::Running,
EpiphanyJobStatus::Completed => ThreadEpiphanyJobStatus::Completed,
EpiphanyJobStatus::Failed => ThreadEpiphanyJobStatus::Failed,
EpiphanyJobStatus::Cancelled => ThreadEpiphanyJobStatus::Cancelled,
EpiphanyJobStatus::Blocked => ThreadEpiphanyJobStatus::Blocked,
EpiphanyJobStatus::Unavailable => ThreadEpiphanyJobStatus::Unavailable,
},
items_processed: job.items_processed,
items_total: job.items_total,
progress_note: job.progress_note,
last_checkpoint_at_unix_seconds: job.last_checkpoint_at_unix_seconds,
blocking_reason: job.blocking_reason,
active_thread_ids: job.active_thread_ids,
linked_subgoal_ids: job.linked_subgoal_ids,
linked_graph_node_ids: job.linked_graph_node_ids,
}
}
pub fn protocol_reorient_state_status(
status: EpiphanyReorientStateStatus,
) -> ThreadEpiphanyReorientStateStatus {
match status {
EpiphanyReorientStateStatus::Missing => ThreadEpiphanyReorientStateStatus::Missing,
EpiphanyReorientStateStatus::Ready => ThreadEpiphanyReorientStateStatus::Ready,
}
}
pub fn protocol_reorient_source(source: EpiphanySurfaceSource) -> ThreadEpiphanyReorientSource {
match source {
EpiphanySurfaceSource::Stored => ThreadEpiphanyReorientSource::Stored,
EpiphanySurfaceSource::Live => ThreadEpiphanyReorientSource::Live,
}
}
pub fn protocol_roles_source(source: EpiphanySurfaceSource) -> ThreadEpiphanyRolesSource {
match source {
EpiphanySurfaceSource::Stored => ThreadEpiphanyRolesSource::Stored,
EpiphanySurfaceSource::Live => ThreadEpiphanyRolesSource::Live,
}
}
pub fn protocol_reorient_decision(
decision: EpiphanyReorientDecision,
) -> ThreadEpiphanyReorientDecision {
ThreadEpiphanyReorientDecision {
action: match decision.action {
EpiphanyReorientAction::Resume => ThreadEpiphanyReorientAction::Resume,
EpiphanyReorientAction::Regather => ThreadEpiphanyReorientAction::Regather,
},
checkpoint_status: match decision.checkpoint_status {
EpiphanyReorientCheckpointStatus::Missing => {
ThreadEpiphanyReorientCheckpointStatus::Missing
}
EpiphanyReorientCheckpointStatus::ResumeReady => {
ThreadEpiphanyReorientCheckpointStatus::ResumeReady
}
EpiphanyReorientCheckpointStatus::RegatherRequired => {
ThreadEpiphanyReorientCheckpointStatus::RegatherRequired
}
},
checkpoint_id: decision.checkpoint_id,
pressure_level: match decision.pressure_level {
EpiphanyReorientPressureLevel::Unknown => ThreadEpiphanyPressureLevel::Unknown,
EpiphanyReorientPressureLevel::Low => ThreadEpiphanyPressureLevel::Low,
EpiphanyReorientPressureLevel::Medium => ThreadEpiphanyPressureLevel::Elevated,
EpiphanyReorientPressureLevel::High => ThreadEpiphanyPressureLevel::High,
EpiphanyReorientPressureLevel::Critical => ThreadEpiphanyPressureLevel::Critical,
},
retrieval_status: protocol_reorient_retrieval_status(decision.retrieval_status),
graph_status: protocol_reorient_graph_status(decision.graph_status),
watcher_status: protocol_reorient_watcher_status(decision.watcher_status),
reasons: decision
.reasons
.into_iter()
.map(protocol_reorient_reason)
.collect(),
checkpoint_dirty_paths: decision.checkpoint_dirty_paths,
checkpoint_changed_paths: decision.checkpoint_changed_paths,
active_frontier_node_ids: decision.active_frontier_node_ids,
next_action: decision.next_action,
note: decision.note,
}
}
pub fn protocol_pressure_from_core(pressure: EpiphanyPressure) -> ThreadEpiphanyPressure {
ThreadEpiphanyPressure {
status: match pressure.status {
EpiphanyPressureStatus::Unknown => ThreadEpiphanyPressureStatus::Unknown,
EpiphanyPressureStatus::Ready => ThreadEpiphanyPressureStatus::Ready,
},
level: protocol_pressure_level(pressure.level),
basis: match pressure.basis {
EpiphanyPressureBasis::Unknown => ThreadEpiphanyPressureBasis::Unknown,
EpiphanyPressureBasis::AutoCompactLimit => {
ThreadEpiphanyPressureBasis::AutoCompactLimit
}
EpiphanyPressureBasis::ModelContextWindow => {
ThreadEpiphanyPressureBasis::ModelContextWindow
}
},
used_tokens: pressure.used_tokens,
model_context_window: pressure.model_context_window,
model_auto_compact_token_limit: pressure.model_auto_compact_token_limit,
remaining_tokens: pressure.remaining_tokens,
ratio_per_mille: pressure.ratio_per_mille,
should_prepare_compaction: pressure.should_prepare_compaction,
note: pressure.note,
}
}
pub fn protocol_pressure_level(level: EpiphanyPressureLevel) -> ThreadEpiphanyPressureLevel {
match level {
EpiphanyPressureLevel::Unknown => ThreadEpiphanyPressureLevel::Unknown,
EpiphanyPressureLevel::Low => ThreadEpiphanyPressureLevel::Low,
EpiphanyPressureLevel::Elevated => ThreadEpiphanyPressureLevel::Elevated,
EpiphanyPressureLevel::High => ThreadEpiphanyPressureLevel::High,
EpiphanyPressureLevel::Critical => ThreadEpiphanyPressureLevel::Critical,
}
}
pub fn protocol_role_result_status(
status: EpiphanyCoordinatorRoleResultStatus,
) -> ThreadEpiphanyRoleResultStatus {
match status {
EpiphanyCoordinatorRoleResultStatus::MissingState => {
ThreadEpiphanyRoleResultStatus::MissingState
}
EpiphanyCoordinatorRoleResultStatus::MissingBinding => {
ThreadEpiphanyRoleResultStatus::MissingBinding
}
EpiphanyCoordinatorRoleResultStatus::BackendUnavailable => {
ThreadEpiphanyRoleResultStatus::BackendUnavailable
}
EpiphanyCoordinatorRoleResultStatus::BackendMissing => {
ThreadEpiphanyRoleResultStatus::BackendMissing
}
EpiphanyCoordinatorRoleResultStatus::Pending => ThreadEpiphanyRoleResultStatus::Pending,
EpiphanyCoordinatorRoleResultStatus::Running => ThreadEpiphanyRoleResultStatus::Running,
EpiphanyCoordinatorRoleResultStatus::Completed => ThreadEpiphanyRoleResultStatus::Completed,
EpiphanyCoordinatorRoleResultStatus::Failed => ThreadEpiphanyRoleResultStatus::Failed,
EpiphanyCoordinatorRoleResultStatus::Cancelled => ThreadEpiphanyRoleResultStatus::Cancelled,
}
}
pub fn protocol_reorient_result_status(
status: EpiphanyCrrcResultStatus,
) -> ThreadEpiphanyReorientResultStatus {
match status {
EpiphanyCrrcResultStatus::MissingState => ThreadEpiphanyReorientResultStatus::MissingState,
EpiphanyCrrcResultStatus::MissingBinding => {
ThreadEpiphanyReorientResultStatus::MissingBinding
}
EpiphanyCrrcResultStatus::BackendUnavailable => {
ThreadEpiphanyReorientResultStatus::BackendUnavailable
}
EpiphanyCrrcResultStatus::BackendMissing => {
ThreadEpiphanyReorientResultStatus::BackendMissing
}
EpiphanyCrrcResultStatus::Pending => ThreadEpiphanyReorientResultStatus::Pending,
EpiphanyCrrcResultStatus::Running => ThreadEpiphanyReorientResultStatus::Running,
EpiphanyCrrcResultStatus::Completed => ThreadEpiphanyReorientResultStatus::Completed,
EpiphanyCrrcResultStatus::Failed => ThreadEpiphanyReorientResultStatus::Failed,
EpiphanyCrrcResultStatus::Cancelled => ThreadEpiphanyReorientResultStatus::Cancelled,
}
}
fn protocol_view_lens_to_core(lens: ThreadEpiphanyViewLens) -> EpiphanyViewLens {
match lens {
ThreadEpiphanyViewLens::Scene => EpiphanyViewLens::Scene,
ThreadEpiphanyViewLens::Jobs => EpiphanyViewLens::Jobs,
ThreadEpiphanyViewLens::Roles => EpiphanyViewLens::Roles,
ThreadEpiphanyViewLens::Planning => EpiphanyViewLens::Planning,
ThreadEpiphanyViewLens::Pressure => EpiphanyViewLens::Pressure,
ThreadEpiphanyViewLens::Reorient => EpiphanyViewLens::Reorient,
ThreadEpiphanyViewLens::Crrc => EpiphanyViewLens::Crrc,
ThreadEpiphanyViewLens::Coordinator => EpiphanyViewLens::Coordinator,
}
}
fn protocol_graph_query_kind_to_core(kind: ThreadEpiphanyGraphQueryKind) -> EpiphanyGraphQueryKind {
match kind {
ThreadEpiphanyGraphQueryKind::Node => EpiphanyGraphQueryKind::Node,
ThreadEpiphanyGraphQueryKind::Path => EpiphanyGraphQueryKind::Path,
ThreadEpiphanyGraphQueryKind::FrontierNeighborhood => {
EpiphanyGraphQueryKind::FrontierNeighborhood
}
ThreadEpiphanyGraphQueryKind::Neighbors => EpiphanyGraphQueryKind::Neighbors,
}
}
fn protocol_graph_query_direction_to_core(
direction: ThreadEpiphanyGraphQueryDirection,
) -> EpiphanyGraphQueryDirection {
match direction {
ThreadEpiphanyGraphQueryDirection::Incoming => EpiphanyGraphQueryDirection::Incoming,
ThreadEpiphanyGraphQueryDirection::Outgoing => EpiphanyGraphQueryDirection::Outgoing,
ThreadEpiphanyGraphQueryDirection::Both => EpiphanyGraphQueryDirection::Both,
}
}
fn protocol_reorient_retrieval_status(
status: EpiphanyReorientFreshnessStatus,
) -> ThreadEpiphanyRetrievalFreshnessStatus {
match status {
EpiphanyReorientFreshnessStatus::Unknown => ThreadEpiphanyRetrievalFreshnessStatus::Missing,
EpiphanyReorientFreshnessStatus::Clean => ThreadEpiphanyRetrievalFreshnessStatus::Ready,
EpiphanyReorientFreshnessStatus::Dirty => ThreadEpiphanyRetrievalFreshnessStatus::Indexing,
EpiphanyReorientFreshnessStatus::Stale | EpiphanyReorientFreshnessStatus::Changed => {
ThreadEpiphanyRetrievalFreshnessStatus::Stale
}
}
}
fn protocol_reorient_graph_status(
status: EpiphanyReorientFreshnessStatus,
) -> ThreadEpiphanyGraphFreshnessStatus {
match status {
EpiphanyReorientFreshnessStatus::Unknown => ThreadEpiphanyGraphFreshnessStatus::Missing,
EpiphanyReorientFreshnessStatus::Clean => ThreadEpiphanyGraphFreshnessStatus::Ready,
EpiphanyReorientFreshnessStatus::Dirty
| EpiphanyReorientFreshnessStatus::Stale
| EpiphanyReorientFreshnessStatus::Changed => ThreadEpiphanyGraphFreshnessStatus::Stale,
}
}
fn protocol_reorient_watcher_status(
status: EpiphanyReorientFreshnessStatus,
) -> ThreadEpiphanyInvalidationStatus {
match status {
EpiphanyReorientFreshnessStatus::Unknown => ThreadEpiphanyInvalidationStatus::Unavailable,
EpiphanyReorientFreshnessStatus::Clean => ThreadEpiphanyInvalidationStatus::Clean,
EpiphanyReorientFreshnessStatus::Dirty
| EpiphanyReorientFreshnessStatus::Stale
| EpiphanyReorientFreshnessStatus::Changed => ThreadEpiphanyInvalidationStatus::Changed,
}
}
fn protocol_reorient_reason(reason: EpiphanyReorientReason) -> ThreadEpiphanyReorientReason {
match reason {
EpiphanyReorientReason::MissingState => ThreadEpiphanyReorientReason::MissingState,
EpiphanyReorientReason::MissingCheckpoint => {
ThreadEpiphanyReorientReason::MissingCheckpoint
}
EpiphanyReorientReason::CheckpointReady => ThreadEpiphanyReorientReason::CheckpointReady,
EpiphanyReorientReason::CheckpointRequestedRegather => {
ThreadEpiphanyReorientReason::CheckpointRequestedRegather
}
EpiphanyReorientReason::CheckpointPathsDirty => {
ThreadEpiphanyReorientReason::CheckpointPathsDirty
}
EpiphanyReorientReason::CheckpointPathsChanged => {
ThreadEpiphanyReorientReason::CheckpointPathsChanged
}
EpiphanyReorientReason::FrontierChanged => ThreadEpiphanyReorientReason::FrontierChanged,
EpiphanyReorientReason::UnanchoredCheckpointWhileStateStale => {
ThreadEpiphanyReorientReason::UnanchoredCheckpointWhileStateStale
}
}
}
fn protocol_self_persistence_review(
review: EpiphanyRoleSelfPersistenceReview,
) -> ThreadEpiphanyRoleSelfPersistenceReview {
ThreadEpiphanyRoleSelfPersistenceReview {
status: match review.status {
EpiphanyRoleSelfPersistenceStatus::Missing => {
ThreadEpiphanyRoleSelfPersistenceStatus::Missing
}
EpiphanyRoleSelfPersistenceStatus::Accepted => {
ThreadEpiphanyRoleSelfPersistenceStatus::Accepted
}
EpiphanyRoleSelfPersistenceStatus::Rejected => {
ThreadEpiphanyRoleSelfPersistenceStatus::Rejected
}
},
target_agent_id: review.target_agent_id,
target_path: review.target_path,
reasons: review.reasons,
}
}

View file

@ -1,121 +0,0 @@
use epiphany_core::EpiphanyFreshnessInput;
use epiphany_core::EpiphanyFreshnessView;
use epiphany_core::EpiphanyFreshnessWatcherInput;
use epiphany_core::EpiphanyGraphFreshness as CoreEpiphanyGraphFreshness;
use epiphany_core::EpiphanyGraphFreshnessStatus as CoreEpiphanyGraphFreshnessStatus;
use epiphany_core::EpiphanyInvalidationInput as CoreEpiphanyInvalidationInput;
use epiphany_core::EpiphanyInvalidationStatus as CoreEpiphanyInvalidationStatus;
use epiphany_core::EpiphanyPressure;
use epiphany_core::EpiphanyPressureLevel;
use epiphany_core::EpiphanyReorientDecision as CoreEpiphanyReorientDecision;
use epiphany_core::EpiphanyReorientFreshnessStatus as CoreEpiphanyReorientFreshnessStatus;
use epiphany_core::EpiphanyReorientInput;
use epiphany_core::EpiphanyReorientPressureLevel as CoreEpiphanyReorientPressureLevel;
use epiphany_core::EpiphanyReorientStateStatus as CoreEpiphanyReorientStateStatus;
use epiphany_core::EpiphanyRetrievalFreshness as CoreEpiphanyRetrievalFreshness;
use epiphany_core::EpiphanyRetrievalFreshnessStatus as CoreEpiphanyRetrievalFreshnessStatus;
use epiphany_core::derive_freshness;
use epiphany_core::recommend_reorientation;
use epiphany_state_model::EpiphanyRetrievalState;
use epiphany_state_model::EpiphanyThreadState;
use std::path::Path;
use std::path::PathBuf;
pub struct EpiphanyFreshnessWatcherSnapshot<'a> {
pub available: bool,
pub workspace_root: Option<&'a Path>,
pub observed_at_unix_seconds: Option<i64>,
pub changed_paths: &'a [PathBuf],
}
pub fn derive_epiphany_freshness_view(
state: Option<&EpiphanyThreadState>,
retrieval_override: Option<&EpiphanyRetrievalState>,
watcher_snapshot: Option<EpiphanyFreshnessWatcherSnapshot<'_>>,
) -> EpiphanyFreshnessView {
let watcher = watcher_snapshot.map(|snapshot| EpiphanyFreshnessWatcherInput {
available: snapshot.available,
workspace_root: snapshot.workspace_root,
observed_at_unix_seconds: snapshot.observed_at_unix_seconds,
changed_paths: snapshot.changed_paths,
});
derive_freshness(EpiphanyFreshnessInput {
state,
retrieval_override,
watcher,
})
}
pub fn derive_epiphany_reorient(
state: Option<&EpiphanyThreadState>,
pressure: &EpiphanyPressure,
retrieval: &CoreEpiphanyRetrievalFreshness,
graph: &CoreEpiphanyGraphFreshness,
watcher: &CoreEpiphanyInvalidationInput,
) -> (
CoreEpiphanyReorientStateStatus,
CoreEpiphanyReorientDecision,
) {
recommend_reorientation(EpiphanyReorientInput {
checkpoint: state.and_then(|state| state.investigation_checkpoint.as_ref()),
state_present: state.is_some(),
pressure_level: map_core_reorient_pressure_level(pressure.level),
retrieval_status: map_core_reorient_retrieval_status(retrieval.status),
retrieval_dirty_paths: retrieval.dirty_paths.clone(),
graph_status: map_core_reorient_graph_status(graph.status),
graph_dirty_paths: graph.dirty_paths.clone(),
watcher_status: map_core_reorient_watcher_status(watcher.status),
watcher_changed_paths: watcher.changed_paths.clone(),
watcher_graph_node_ids: watcher.graph_node_ids.clone(),
active_frontier_node_ids: watcher.active_frontier_node_ids.clone(),
watched_root: watcher.watched_root.clone(),
})
}
fn map_core_reorient_pressure_level(
level: EpiphanyPressureLevel,
) -> CoreEpiphanyReorientPressureLevel {
match level {
EpiphanyPressureLevel::Unknown => CoreEpiphanyReorientPressureLevel::Unknown,
EpiphanyPressureLevel::Low => CoreEpiphanyReorientPressureLevel::Low,
EpiphanyPressureLevel::Elevated => CoreEpiphanyReorientPressureLevel::Medium,
EpiphanyPressureLevel::High => CoreEpiphanyReorientPressureLevel::High,
EpiphanyPressureLevel::Critical => CoreEpiphanyReorientPressureLevel::Critical,
}
}
fn map_core_reorient_retrieval_status(
status: CoreEpiphanyRetrievalFreshnessStatus,
) -> CoreEpiphanyReorientFreshnessStatus {
match status {
CoreEpiphanyRetrievalFreshnessStatus::Missing
| CoreEpiphanyRetrievalFreshnessStatus::Unavailable => {
CoreEpiphanyReorientFreshnessStatus::Unknown
}
CoreEpiphanyRetrievalFreshnessStatus::Ready => CoreEpiphanyReorientFreshnessStatus::Clean,
CoreEpiphanyRetrievalFreshnessStatus::Stale => CoreEpiphanyReorientFreshnessStatus::Stale,
CoreEpiphanyRetrievalFreshnessStatus::Indexing => {
CoreEpiphanyReorientFreshnessStatus::Dirty
}
}
}
fn map_core_reorient_graph_status(
status: CoreEpiphanyGraphFreshnessStatus,
) -> CoreEpiphanyReorientFreshnessStatus {
match status {
CoreEpiphanyGraphFreshnessStatus::Missing => CoreEpiphanyReorientFreshnessStatus::Unknown,
CoreEpiphanyGraphFreshnessStatus::Ready => CoreEpiphanyReorientFreshnessStatus::Clean,
CoreEpiphanyGraphFreshnessStatus::Stale => CoreEpiphanyReorientFreshnessStatus::Stale,
}
}
fn map_core_reorient_watcher_status(
status: CoreEpiphanyInvalidationStatus,
) -> CoreEpiphanyReorientFreshnessStatus {
match status {
CoreEpiphanyInvalidationStatus::Unavailable => CoreEpiphanyReorientFreshnessStatus::Unknown,
CoreEpiphanyInvalidationStatus::Clean => CoreEpiphanyReorientFreshnessStatus::Clean,
CoreEpiphanyInvalidationStatus::Changed => CoreEpiphanyReorientFreshnessStatus::Changed,
}
}

View file

@ -1,137 +0,0 @@
use epiphany_core::EpiphanyCoordinatorRoleResultStatus as CoreEpiphanyCoordinatorRoleResultStatus;
use epiphany_core::EpiphanyCrrcResultStatus as CoreEpiphanyCrrcResultStatus;
use epiphany_core::EpiphanyReorientFindingInterpretation;
use epiphany_core::EpiphanyRoleFindingInterpretation;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::EpiphanyRoleSelfPersistenceReview as CoreEpiphanyRoleSelfPersistenceReview;
use epiphany_core::EpiphanyRoleSelfPersistenceStatus as CoreEpiphanyRoleSelfPersistenceStatus;
pub fn render_core_role_result_note(
role_id: EpiphanyRoleResultRoleId,
status: CoreEpiphanyCoordinatorRoleResultStatus,
finding: Option<&EpiphanyRoleFindingInterpretation>,
item_error: Option<&str>,
) -> String {
match status {
CoreEpiphanyCoordinatorRoleResultStatus::Completed => {
if let Some(finding) = finding {
let next = finding.next_safe_move.as_deref().unwrap_or("not supplied");
let self_note =
render_core_self_persistence_note(finding.self_persistence.as_ref())
.map(|note| format!(" {note}"))
.unwrap_or_default();
if let Some(item_error) = finding.item_error.as_deref().or(item_error) {
format!(
"{:?} role specialist completed, but the finding needs repair: {item_error}. Next safe move: {next}.{self_note}",
role_id
)
} else {
format!(
"{:?} role specialist completed. Next safe move: {next}.{self_note}",
role_id
)
}
} else {
format!(
"{:?} role specialist completed, but no structured result was recorded.",
role_id
)
}
}
CoreEpiphanyCoordinatorRoleResultStatus::Failed => item_error
.map(|error| format!("{:?} role specialist failed: {error}", role_id))
.unwrap_or_else(|| format!("{:?} role specialist failed.", role_id)),
CoreEpiphanyCoordinatorRoleResultStatus::Cancelled => {
format!(
"{:?} role specialist was cancelled before producing a result.",
role_id
)
}
CoreEpiphanyCoordinatorRoleResultStatus::Running => {
format!("{:?} role specialist is still running.", role_id)
}
CoreEpiphanyCoordinatorRoleResultStatus::Pending => {
format!(
"{:?} role specialist has not produced a result yet.",
role_id
)
}
CoreEpiphanyCoordinatorRoleResultStatus::MissingState => {
"No authoritative Epiphany state exists for this thread.".to_string()
}
CoreEpiphanyCoordinatorRoleResultStatus::MissingBinding => {
"No matching Epiphany role specialist binding exists.".to_string()
}
CoreEpiphanyCoordinatorRoleResultStatus::BackendUnavailable => {
"The bound runtime backend is unavailable.".to_string()
}
CoreEpiphanyCoordinatorRoleResultStatus::BackendMissing => {
"The bound runtime backend job or item is missing.".to_string()
}
}
}
fn render_core_self_persistence_note(
review: Option<&CoreEpiphanyRoleSelfPersistenceReview>,
) -> Option<String> {
let review = review?;
match review.status {
CoreEpiphanyRoleSelfPersistenceStatus::Missing => None,
CoreEpiphanyRoleSelfPersistenceStatus::Accepted => Some(format!(
"Self persistence request is acceptable for {}.",
review
.target_agent_id
.as_deref()
.unwrap_or("the role memory file")
)),
CoreEpiphanyRoleSelfPersistenceStatus::Rejected => {
let reasons = if review.reasons.is_empty() {
"no reason recorded".to_string()
} else {
review.reasons.join("; ")
};
Some(format!("Self persistence request was refused: {reasons}."))
}
}
}
pub fn render_core_reorient_result_note(
status: CoreEpiphanyCrrcResultStatus,
finding: Option<&EpiphanyReorientFindingInterpretation>,
item_error: Option<&str>,
) -> String {
match status {
CoreEpiphanyCrrcResultStatus::Completed => {
if let Some(finding) = finding {
let next = finding.next_safe_move.as_deref().unwrap_or("not supplied");
format!("Reorientation worker completed. Next safe move: {next}")
} else {
"Reorientation worker completed, but no structured result was recorded.".to_string()
}
}
CoreEpiphanyCrrcResultStatus::Failed => item_error
.map(|error| format!("Reorientation worker failed: {error}"))
.unwrap_or_else(|| "Reorientation worker failed.".to_string()),
CoreEpiphanyCrrcResultStatus::Cancelled => {
"Reorientation worker was cancelled before producing a result.".to_string()
}
CoreEpiphanyCrrcResultStatus::Running => {
"Reorientation worker is still running.".to_string()
}
CoreEpiphanyCrrcResultStatus::Pending => {
"Reorientation worker has not produced a result yet.".to_string()
}
CoreEpiphanyCrrcResultStatus::MissingState => {
"No authoritative Epiphany state exists for this thread.".to_string()
}
CoreEpiphanyCrrcResultStatus::MissingBinding => {
"No matching Epiphany reorientation worker binding exists.".to_string()
}
CoreEpiphanyCrrcResultStatus::BackendUnavailable => {
"The bound runtime backend is unavailable.".to_string()
}
CoreEpiphanyCrrcResultStatus::BackendMissing => {
"The bound runtime backend job or item is missing.".to_string()
}
}
}

View file

@ -1,63 +0,0 @@
use epiphany_core::EpiphanyRetrieveQuery;
use epiphany_core::EpiphanyRetrieveResponse as CoreEpiphanyRetrieveResponse;
use epiphany_core::index_workspace;
use epiphany_core::normalize_epiphany_retrieve_query;
use epiphany_core::retrieval_state_for_workspace;
use epiphany_core::retrieve_workspace;
use epiphany_state_model::EpiphanyRetrievalState;
use std::path::PathBuf;
pub async fn index_epiphany_retrieval_for_paths(
workspace_root: PathBuf,
codex_home: PathBuf,
force_full_rebuild: bool,
) -> anyhow::Result<EpiphanyRetrievalState> {
index_epiphany_retrieval_state_for_paths(workspace_root, codex_home, force_full_rebuild).await
}
pub fn normalize_thread_epiphany_retrieve_query(
query: String,
limit: Option<u32>,
path_prefixes: Vec<PathBuf>,
) -> Result<EpiphanyRetrieveQuery, String> {
normalize_epiphany_retrieve_query(query, limit, path_prefixes).map_err(str::to_string)
}
pub async fn epiphany_retrieval_state_for_paths(
workspace_root: PathBuf,
codex_home: PathBuf,
) -> EpiphanyRetrievalState {
let fallback_workspace_root = workspace_root.clone();
let fallback_codex_home = codex_home.clone();
tokio::task::spawn_blocking(move || {
retrieval_state_for_workspace(&workspace_root, codex_home.as_path())
})
.await
.unwrap_or_else(|_| {
retrieval_state_for_workspace(&fallback_workspace_root, fallback_codex_home.as_path())
})
}
pub async fn index_epiphany_retrieval_state_for_paths(
workspace_root: PathBuf,
codex_home: PathBuf,
force_full_rebuild: bool,
) -> anyhow::Result<EpiphanyRetrievalState> {
tokio::task::spawn_blocking(move || {
index_workspace(&workspace_root, codex_home.as_path(), force_full_rebuild)
})
.await
.map_err(|err| anyhow::anyhow!("epiphany index worker failed: {err}"))?
}
pub async fn retrieve_epiphany_for_paths(
workspace_root: PathBuf,
codex_home: PathBuf,
query: EpiphanyRetrieveQuery,
) -> anyhow::Result<CoreEpiphanyRetrieveResponse> {
tokio::task::spawn_blocking(move || {
retrieve_workspace(&workspace_root, codex_home.as_path(), query)
})
.await
.map_err(|err| anyhow::anyhow!("epiphany retrieval worker failed: {err}"))?
}

View file

@ -1,277 +0,0 @@
use std::path::Path;
use epiphany_core::EpiphanyLaunchOrganContract;
use epiphany_core::EpiphanyReorientFindingInterpretation;
use epiphany_core::EpiphanyRoleFindingInterpretation;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_state_model::EpiphanyRuntimeLink;
use epiphany_state_model::EpiphanyThreadState;
use crate::error::EpiphanyBridgeError;
use crate::error::Result as BridgeResult;
pub type EpiphanyRoleResultSnapshot = epiphany_core::EpiphanyCoordinatorRoleResultSnapshot;
pub type EpiphanyReorientResultSnapshot = epiphany_core::EpiphanyCoordinatorReorientResultSnapshot;
pub fn load_core_epiphany_role_result_from_runtime_spine_job(
job_id: &str,
runtime_store_path: Option<&Path>,
role_id: EpiphanyRoleResultRoleId,
) -> EpiphanyRoleResultSnapshot {
epiphany_core::read_runtime_role_result(runtime_store_path, job_id, role_id)
}
pub fn load_core_epiphany_reorient_result_from_runtime_spine_job(
job_id: &str,
runtime_store_path: Option<&Path>,
) -> EpiphanyReorientResultSnapshot {
epiphany_core::read_runtime_reorient_result(runtime_store_path, job_id)
}
pub async fn load_core_epiphany_role_result_snapshot(
state: &EpiphanyThreadState,
runtime_store_path: Option<&Path>,
role_id: EpiphanyRoleResultRoleId,
binding_id: &str,
) -> EpiphanyRoleResultSnapshot {
epiphany_core::read_role_result_snapshot(Some(state), runtime_store_path, role_id, binding_id)
}
pub fn load_completed_core_epiphany_role_finding(
runtime_store_path: Option<&Path>,
state: &EpiphanyThreadState,
role_id: EpiphanyRoleResultRoleId,
binding_id: &str,
) -> BridgeResult<EpiphanyRoleFindingInterpretation> {
epiphany_core::completed_role_finding(runtime_store_path, state, role_id, binding_id)
.map_err(map_admission_error)
}
pub async fn load_core_epiphany_reorient_result_snapshot(
state: Option<&EpiphanyThreadState>,
runtime_store_path: Option<&Path>,
binding_id: &str,
) -> EpiphanyReorientResultSnapshot {
epiphany_core::read_reorient_result_snapshot(state, runtime_store_path, binding_id)
}
pub fn load_completed_core_epiphany_reorient_finding(
runtime_store_path: Option<&Path>,
state: &EpiphanyThreadState,
binding_id: &str,
) -> BridgeResult<EpiphanyReorientFindingInterpretation> {
epiphany_core::completed_reorient_finding(runtime_store_path, state, binding_id)
.map_err(map_admission_error)
}
pub fn load_launch_organ_contract_for_runtime_job(
runtime_store_path: &Path,
job_id: &str,
expected_document_kind: &str,
) -> BridgeResult<EpiphanyLaunchOrganContract> {
epiphany_core::load_launch_organ_contract(runtime_store_path, job_id, expected_document_kind)
.map_err(map_admission_error)
}
fn map_admission_error(
error: epiphany_core::EpiphanyCoordinatorAdmissionError,
) -> EpiphanyBridgeError {
match error {
epiphany_core::EpiphanyCoordinatorAdmissionError::InvalidRequest(message) => {
EpiphanyBridgeError::InvalidRequest(message)
}
epiphany_core::EpiphanyCoordinatorAdmissionError::Store(message) => {
EpiphanyBridgeError::Fatal(message)
}
}
}
pub fn latest_epiphany_runtime_link_for_binding<'a>(
state: &'a EpiphanyThreadState,
binding_id: &str,
) -> Option<&'a EpiphanyRuntimeLink> {
state
.runtime_links
.iter()
.find(|link| link.binding_id == binding_id && !link.runtime_job_id.trim().is_empty())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use epiphany_core::EpiphanyCoordinatorRoleResultStatus as CoreEpiphanyCoordinatorRoleResultStatus;
use epiphany_core::EpiphanyCrrcResultStatus as CoreEpiphanyCrrcResultStatus;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::RuntimeSpineInitOptions;
use epiphany_core::RuntimeSpineJobOptions;
use epiphany_core::RuntimeSpineJobResultOptions;
use epiphany_core::RuntimeSpineSessionOptions;
use epiphany_core::complete_runtime_job;
use epiphany_core::create_runtime_job;
use epiphany_core::create_runtime_session;
use epiphany_core::initialize_runtime_spine;
use super::*;
const NOW: &str = "2026-05-13T00:00:00Z";
#[test]
fn role_result_requires_typed_worker_document() {
let store = temp_store_path();
seed_lifecycle_result(&store, "role-job", "modeling", "completed");
let result = load_core_epiphany_role_result_from_runtime_spine_job(
"role-job",
Some(store.as_path()),
EpiphanyRoleResultRoleId::Modeling,
);
assert_eq!(
result.status,
CoreEpiphanyCoordinatorRoleResultStatus::BackendUnavailable
);
assert!(result.finding.is_none());
assert!(
result
.note
.contains("EpiphanyRuntimeRoleWorkerResult typed document")
);
let _ = fs::remove_file(store);
}
#[test]
fn reorient_result_requires_typed_worker_document() {
let store = temp_store_path();
seed_lifecycle_result(&store, "reorient-job", "reorientation", "completed");
let result = load_core_epiphany_reorient_result_from_runtime_spine_job(
"reorient-job",
Some(store.as_path()),
);
assert_eq!(
result.status,
CoreEpiphanyCrrcResultStatus::BackendUnavailable
);
assert!(result.finding.is_none());
assert!(
result
.note
.contains("EpiphanyRuntimeReorientWorkerResult typed document")
);
let _ = fs::remove_file(store);
}
#[test]
fn role_result_projects_failed_lifecycle_receipt_as_terminal() {
let store = temp_store_path();
seed_lifecycle_result(&store, "role-job", "modeling", "failed");
let result = load_core_epiphany_role_result_from_runtime_spine_job(
"role-job",
Some(store.as_path()),
EpiphanyRoleResultRoleId::Modeling,
);
assert_eq!(
result.status,
CoreEpiphanyCoordinatorRoleResultStatus::Failed
);
let finding = result.finding.expect("failed receipt should be visible");
assert_eq!(finding.verdict.as_deref(), Some("failed"));
assert_eq!(finding.runtime_job_id.as_deref(), Some("role-job"));
assert!(
finding
.job_error
.as_deref()
.is_some_and(|error| error.contains("generic lifecycle result"))
);
assert!(result.note.contains("failed"));
let _ = fs::remove_file(store);
}
#[test]
fn reorient_result_projects_failed_lifecycle_receipt_as_terminal() {
let store = temp_store_path();
seed_lifecycle_result(&store, "reorient-job", "reorientation", "failed");
let result = load_core_epiphany_reorient_result_from_runtime_spine_job(
"reorient-job",
Some(store.as_path()),
);
assert_eq!(result.status, CoreEpiphanyCrrcResultStatus::Failed);
let finding = result.finding.expect("failed receipt should be visible");
assert_eq!(finding.runtime_job_id.as_deref(), Some("reorient-job"));
assert!(
finding
.job_error
.as_deref()
.is_some_and(|error| error.contains("generic lifecycle result"))
);
assert!(result.note.contains("failed"));
let _ = fs::remove_file(store);
}
fn temp_store_path() -> PathBuf {
std::env::temp_dir().join(format!(
"epiphany-runtime-results-{}.msgpack",
uuid::Uuid::new_v4()
))
}
fn seed_lifecycle_result(store: &Path, job_id: &str, role: &str, verdict: &str) {
initialize_runtime_spine(
store,
RuntimeSpineInitOptions {
runtime_id: "test-runtime".to_string(),
display_name: "Test Runtime".to_string(),
created_at: NOW.to_string(),
},
)
.expect("initialize runtime");
create_runtime_session(
store,
RuntimeSpineSessionOptions {
session_id: "session-1".to_string(),
objective: "test typed result boundary".to_string(),
created_at: NOW.to_string(),
coordinator_note: "test".to_string(),
},
)
.expect("create session");
create_runtime_job(
store,
RuntimeSpineJobOptions {
job_id: job_id.to_string(),
session_id: "session-1".to_string(),
role: role.to_string(),
created_at: NOW.to_string(),
summary: "generic lifecycle job".to_string(),
artifact_refs: Vec::new(),
},
)
.expect("create job");
complete_runtime_job(
store,
RuntimeSpineJobResultOptions {
result_id: format!("result-{job_id}"),
job_id: job_id.to_string(),
completed_at: NOW.to_string(),
verdict: verdict.to_string(),
summary: "generic lifecycle result".to_string(),
next_safe_move: "do not review generic lifecycle receipts".to_string(),
evidence_refs: Vec::new(),
artifact_refs: Vec::new(),
},
)
.expect("complete job");
}
}

View file

@ -1,16 +0,0 @@
use epiphany_core::EpiphanyScene;
use epiphany_core::EpiphanySceneInput;
use epiphany_core::derive_scene;
use epiphany_state_model::EpiphanyThreadState;
pub fn derive_epiphany_scene(
state: Option<&EpiphanyThreadState>,
loaded: bool,
reorient_binding_id: &str,
) -> EpiphanyScene {
derive_scene(EpiphanySceneInput {
state,
loaded,
reorient_binding_id,
})
}

View file

@ -1,189 +0,0 @@
use codex_app_server_protocol::ThreadEpiphanyScene;
use codex_app_server_protocol::ThreadEpiphanySceneAction;
use codex_app_server_protocol::ThreadEpiphanySceneChurn;
use codex_app_server_protocol::ThreadEpiphanySceneGraph;
use codex_app_server_protocol::ThreadEpiphanySceneInvestigationCheckpoint;
use codex_app_server_protocol::ThreadEpiphanySceneRecord;
use codex_app_server_protocol::ThreadEpiphanySceneRecords;
use codex_app_server_protocol::ThreadEpiphanySceneRetrieval;
use codex_app_server_protocol::ThreadEpiphanySceneSource;
use codex_app_server_protocol::ThreadEpiphanySceneStateStatus;
use codex_app_server_protocol::ThreadEpiphanySceneStatusCount;
use codex_app_server_protocol::ThreadEpiphanySceneSubgoal;
use epiphany_core::EpiphanyScene as CoreEpiphanyScene;
use epiphany_core::EpiphanySceneAction as CoreEpiphanySceneAction;
use epiphany_core::EpiphanySceneChurn as CoreEpiphanySceneChurn;
use epiphany_core::EpiphanySceneGraph as CoreEpiphanySceneGraph;
use epiphany_core::EpiphanySceneInvestigationCheckpoint as CoreEpiphanySceneInvestigationCheckpoint;
use epiphany_core::EpiphanySceneRecord as CoreEpiphanySceneRecord;
use epiphany_core::EpiphanySceneRecords as CoreEpiphanySceneRecords;
use epiphany_core::EpiphanySceneRetrieval as CoreEpiphanySceneRetrieval;
use epiphany_core::EpiphanySceneSource as CoreEpiphanySceneSource;
use epiphany_core::EpiphanySceneStateStatus as CoreEpiphanySceneStateStatus;
use epiphany_core::EpiphanySceneStatusCount as CoreEpiphanySceneStatusCount;
use epiphany_core::EpiphanySceneSubgoal as CoreEpiphanySceneSubgoal;
pub fn protocol_scene(scene: CoreEpiphanyScene) -> ThreadEpiphanyScene {
ThreadEpiphanyScene {
state_status: match scene.state_status {
CoreEpiphanySceneStateStatus::Missing => ThreadEpiphanySceneStateStatus::Missing,
CoreEpiphanySceneStateStatus::Ready => ThreadEpiphanySceneStateStatus::Ready,
},
source: match scene.source {
CoreEpiphanySceneSource::Stored => ThreadEpiphanySceneSource::Stored,
CoreEpiphanySceneSource::Live => ThreadEpiphanySceneSource::Live,
},
revision: scene.revision,
objective: scene.objective,
active_subgoal: scene.active_subgoal.map(protocol_scene_subgoal),
subgoals: scene
.subgoals
.into_iter()
.map(protocol_scene_subgoal)
.collect(),
invariant_status_counts: scene
.invariant_status_counts
.into_iter()
.map(protocol_scene_status_count)
.collect(),
graph: protocol_scene_graph(scene.graph),
retrieval: scene.retrieval.map(protocol_scene_retrieval),
investigation_checkpoint: scene
.investigation_checkpoint
.map(protocol_scene_investigation_checkpoint),
observations: protocol_scene_records(scene.observations),
evidence: protocol_scene_records(scene.evidence),
churn: scene.churn.map(protocol_scene_churn),
available_actions: scene
.available_actions
.into_iter()
.map(protocol_scene_action)
.collect(),
}
}
pub fn protocol_scene_action(action: CoreEpiphanySceneAction) -> ThreadEpiphanySceneAction {
match action {
CoreEpiphanySceneAction::Index => ThreadEpiphanySceneAction::Index,
CoreEpiphanySceneAction::Retrieve => ThreadEpiphanySceneAction::Retrieve,
CoreEpiphanySceneAction::Distill => ThreadEpiphanySceneAction::Distill,
CoreEpiphanySceneAction::Context => ThreadEpiphanySceneAction::Context,
CoreEpiphanySceneAction::Planning => ThreadEpiphanySceneAction::Planning,
CoreEpiphanySceneAction::GraphQuery => ThreadEpiphanySceneAction::GraphQuery,
CoreEpiphanySceneAction::Jobs => ThreadEpiphanySceneAction::Jobs,
CoreEpiphanySceneAction::Roles => ThreadEpiphanySceneAction::Roles,
CoreEpiphanySceneAction::Coordinator => ThreadEpiphanySceneAction::Coordinator,
CoreEpiphanySceneAction::RoleLaunch => ThreadEpiphanySceneAction::RoleLaunch,
CoreEpiphanySceneAction::RoleResult => ThreadEpiphanySceneAction::RoleResult,
CoreEpiphanySceneAction::RoleAccept => ThreadEpiphanySceneAction::RoleAccept,
CoreEpiphanySceneAction::JobLaunch => ThreadEpiphanySceneAction::JobLaunch,
CoreEpiphanySceneAction::JobInterrupt => ThreadEpiphanySceneAction::JobInterrupt,
CoreEpiphanySceneAction::Freshness => ThreadEpiphanySceneAction::Freshness,
CoreEpiphanySceneAction::Pressure => ThreadEpiphanySceneAction::Pressure,
CoreEpiphanySceneAction::Reorient => ThreadEpiphanySceneAction::Reorient,
CoreEpiphanySceneAction::Crrc => ThreadEpiphanySceneAction::Crrc,
CoreEpiphanySceneAction::ReorientLaunch => ThreadEpiphanySceneAction::ReorientLaunch,
CoreEpiphanySceneAction::ReorientResult => ThreadEpiphanySceneAction::ReorientResult,
CoreEpiphanySceneAction::ReorientAccept => ThreadEpiphanySceneAction::ReorientAccept,
CoreEpiphanySceneAction::Propose => ThreadEpiphanySceneAction::Propose,
CoreEpiphanySceneAction::Promote => ThreadEpiphanySceneAction::Promote,
CoreEpiphanySceneAction::Update => ThreadEpiphanySceneAction::Update,
}
}
fn protocol_scene_subgoal(subgoal: CoreEpiphanySceneSubgoal) -> ThreadEpiphanySceneSubgoal {
ThreadEpiphanySceneSubgoal {
id: subgoal.id,
title: subgoal.title,
status: subgoal.status,
summary: subgoal.summary,
active: subgoal.active,
}
}
fn protocol_scene_status_count(
count: CoreEpiphanySceneStatusCount,
) -> ThreadEpiphanySceneStatusCount {
ThreadEpiphanySceneStatusCount {
status: count.status,
count: count.count,
}
}
fn protocol_scene_graph(graph: CoreEpiphanySceneGraph) -> ThreadEpiphanySceneGraph {
ThreadEpiphanySceneGraph {
architecture_node_count: graph.architecture_node_count,
architecture_edge_count: graph.architecture_edge_count,
dataflow_node_count: graph.dataflow_node_count,
dataflow_edge_count: graph.dataflow_edge_count,
link_count: graph.link_count,
active_node_ids: graph.active_node_ids,
active_edge_ids: graph.active_edge_ids,
open_question_count: graph.open_question_count,
open_gap_count: graph.open_gap_count,
dirty_paths: graph.dirty_paths,
checkpoint_id: graph.checkpoint_id,
checkpoint_summary: graph.checkpoint_summary,
}
}
fn protocol_scene_retrieval(retrieval: CoreEpiphanySceneRetrieval) -> ThreadEpiphanySceneRetrieval {
ThreadEpiphanySceneRetrieval {
workspace_root: retrieval.workspace_root,
status: retrieval.status,
semantic_available: retrieval.semantic_available,
index_revision: retrieval.index_revision,
indexed_file_count: retrieval.indexed_file_count,
indexed_chunk_count: retrieval.indexed_chunk_count,
shard_count: retrieval.shard_count,
dirty_path_count: retrieval.dirty_path_count,
}
}
fn protocol_scene_investigation_checkpoint(
checkpoint: CoreEpiphanySceneInvestigationCheckpoint,
) -> ThreadEpiphanySceneInvestigationCheckpoint {
ThreadEpiphanySceneInvestigationCheckpoint {
checkpoint_id: checkpoint.checkpoint_id,
kind: checkpoint.kind,
disposition: checkpoint.disposition,
focus: checkpoint.focus,
summary: checkpoint.summary,
next_action: checkpoint.next_action,
captured_at_turn_id: checkpoint.captured_at_turn_id,
open_question_count: checkpoint.open_question_count,
code_ref_count: checkpoint.code_ref_count,
evidence_count: checkpoint.evidence_count,
}
}
fn protocol_scene_records(records: CoreEpiphanySceneRecords) -> ThreadEpiphanySceneRecords {
ThreadEpiphanySceneRecords {
total_count: records.total_count,
latest: records
.latest
.into_iter()
.map(protocol_scene_record)
.collect(),
}
}
fn protocol_scene_record(record: CoreEpiphanySceneRecord) -> ThreadEpiphanySceneRecord {
ThreadEpiphanySceneRecord {
id: record.id,
kind: record.kind,
status: record.status,
summary: record.summary,
code_ref_count: record.code_ref_count,
}
}
fn protocol_scene_churn(churn: CoreEpiphanySceneChurn) -> ThreadEpiphanySceneChurn {
ThreadEpiphanySceneChurn {
understanding_status: churn.understanding_status,
diff_pressure: churn.diff_pressure,
graph_freshness: churn.graph_freshness,
warning: churn.warning,
unexplained_writes: churn.unexplained_writes,
}
}

View file

@ -1,53 +0,0 @@
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use epiphany_core::write_thread_state;
use epiphany_state_model::EpiphanyThreadState;
use tracing::warn;
use crate::retrieve::epiphany_retrieval_state_for_paths;
pub async fn client_visible_epiphany_state_for_paths(
mut state: EpiphanyThreadState,
workspace_root: &Path,
codex_home: PathBuf,
mirror_thread_id: Option<&str>,
) -> EpiphanyThreadState {
if state.retrieval.is_none() {
state.retrieval = Some(
epiphany_retrieval_state_for_paths(workspace_root.to_path_buf(), codex_home).await,
);
}
if let Some(thread_id) = mirror_thread_id
&& let Err(err) = mirror_thread_state_to_workspace(workspace_root, thread_id, &state)
{
warn!("failed to mirror Epiphany thread state into native store: {err}");
}
state
}
pub fn thread_state_store_path(workspace_root: &Path) -> PathBuf {
workspace_root.join("state").join("thread-state.msgpack")
}
pub fn mirror_thread_state_to_workspace(
workspace_root: &Path,
thread_id: &str,
state: &EpiphanyThreadState,
) -> anyhow::Result<PathBuf> {
let store_path = thread_state_store_path(workspace_root);
if let Some(parent) = store_path.parent() {
fs::create_dir_all(parent)?;
}
write_thread_state(&store_path, thread_id, state)?;
Ok(store_path)
}
pub fn thread_state_mirror_id_from_rollout_path(rollout_path: Option<&Path>) -> String {
rollout_path
.and_then(|path| path.file_stem())
.and_then(|stem| stem.to_str())
.map(str::to_string)
.unwrap_or_else(|| "live-thread".to_string())
}

View file

@ -1,550 +0,0 @@
use std::path::Path;
use codex_app_server_protocol::*;
use epiphany_core::EPIPHANY_REORIENT_LAUNCH_BINDING_ID;
use epiphany_core::EpiphanyContextParams;
use epiphany_core::EpiphanyGraphQuery;
use epiphany_core::EpiphanyRoleResultRoleId;
use epiphany_core::EpiphanySceneInput;
use epiphany_core::EpiphanyTokenUsageSnapshot;
use epiphany_core::EpiphanyViewLens;
use epiphany_core::derive_scene;
use epiphany_core::epiphany_view_needs_jobs;
use epiphany_core::epiphany_view_needs_pressure;
use epiphany_core::epiphany_view_needs_reorientation_inputs;
use epiphany_core::reorient_finding_already_accepted;
use epiphany_state_model::EpiphanyRetrievalState;
use epiphany_state_model::EpiphanyThreadState;
use crate::context::derive_epiphany_context;
use crate::context::derive_epiphany_graph_query;
use crate::context::derive_epiphany_planning;
use crate::context_protocol::protocol_context_view;
use crate::context_protocol::protocol_graph_query_view;
use crate::context_protocol::protocol_planning_view;
use crate::coordinator::derive_epiphany_coordinator_status;
use crate::coordinator::map_epiphany_crrc_recommendation;
use crate::coordinator::map_epiphany_roles;
use crate::coordinator::render_epiphany_roles_note;
use crate::coordinator_protocol::protocol_coordinator_view;
use crate::coordinator_protocol::protocol_crrc_recommendation;
use crate::coordinator_protocol::protocol_role_board_lanes;
use crate::cultnet::EpiphanyFreshnessSurface;
use crate::cultnet::EpiphanySurfaceSource;
use crate::jobs::map_epiphany_jobs;
use crate::pressure::derive_epiphany_pressure;
use crate::protocol_edge::protocol_job_from_surface;
use crate::protocol_edge::protocol_pressure_from_core;
use crate::protocol_edge::protocol_reorient_decision;
use crate::protocol_edge::protocol_reorient_finding;
use crate::protocol_edge::protocol_reorient_result_status;
use crate::protocol_edge::protocol_reorient_source;
use crate::protocol_edge::protocol_reorient_state_status;
use crate::protocol_edge::protocol_role_finding;
use crate::protocol_edge::protocol_role_id_from_core;
use crate::protocol_edge::protocol_role_result_status;
use crate::protocol_edge::protocol_roles_source;
use crate::protocol_edge::protocol_view_lens_from_core;
use crate::reorient::EpiphanyFreshnessWatcherSnapshot;
use crate::reorient::derive_epiphany_freshness_view;
use crate::reorient::derive_epiphany_reorient;
use crate::runtime_results::load_core_epiphany_reorient_result_snapshot;
use crate::runtime_results::load_core_epiphany_role_result_snapshot;
use crate::scene::derive_epiphany_scene;
use crate::scene_protocol::protocol_scene;
use crate::scene_protocol::protocol_scene_action;
pub struct EpiphanyFreshnessResponseInput<'a> {
pub thread_id: String,
pub loaded: bool,
pub state: Option<&'a EpiphanyThreadState>,
pub retrieval_override: Option<&'a EpiphanyRetrievalState>,
pub watcher_snapshot: Option<EpiphanyFreshnessWatcherSnapshot<'a>>,
}
pub fn derive_epiphany_freshness_surface(
input: EpiphanyFreshnessResponseInput<'_>,
) -> EpiphanyFreshnessSurface {
let freshness = derive_epiphany_freshness_view(
input.state,
input.retrieval_override,
input.watcher_snapshot,
);
EpiphanyFreshnessSurface {
thread_id: input.thread_id,
source: if input.loaded {
EpiphanySurfaceSource::Live
} else {
EpiphanySurfaceSource::Stored
},
state_revision: freshness.state_revision,
retrieval: freshness.retrieval,
graph: freshness.graph,
watcher: freshness.watcher,
}
}
pub fn map_epiphany_context_response(
thread_id: String,
loaded: bool,
state: Option<&EpiphanyThreadState>,
params: &EpiphanyContextParams,
) -> ThreadEpiphanyContextResponse {
let (state_status, state_revision, context, missing) =
protocol_context_view(derive_epiphany_context(state, params));
ThreadEpiphanyContextResponse {
thread_id,
source: if loaded {
ThreadEpiphanyContextSource::Live
} else {
ThreadEpiphanyContextSource::Stored
},
state_status,
state_revision,
context,
missing,
}
}
pub fn map_epiphany_graph_query_response(
thread_id: String,
loaded: bool,
state: Option<&EpiphanyThreadState>,
query: &EpiphanyGraphQuery,
) -> ThreadEpiphanyGraphQueryResponse {
let (state_status, state_revision, graph, frontier, checkpoint, matched, missing) =
protocol_graph_query_view(derive_epiphany_graph_query(state, query));
ThreadEpiphanyGraphQueryResponse {
thread_id,
source: if loaded {
ThreadEpiphanyContextSource::Live
} else {
ThreadEpiphanyContextSource::Stored
},
state_status,
state_revision,
graph,
frontier,
checkpoint,
matched,
missing,
}
}
pub struct EpiphanyViewResponseInput<'a> {
pub thread_id: String,
pub lenses: Vec<EpiphanyViewLens>,
pub loaded: bool,
pub state: Option<&'a EpiphanyThreadState>,
pub retrieval_override: Option<&'a EpiphanyRetrievalState>,
pub watcher_snapshot: Option<EpiphanyFreshnessWatcherSnapshot<'a>>,
pub token_usage_info: Option<&'a EpiphanyTokenUsageSnapshot>,
pub runtime_store_path: Option<&'a Path>,
}
pub async fn map_epiphany_view_response(
input: EpiphanyViewResponseInput<'_>,
) -> ThreadEpiphanyViewResponse {
let EpiphanyViewResponseInput {
thread_id,
lenses,
loaded,
state,
retrieval_override,
watcher_snapshot,
token_usage_info,
runtime_store_path,
} = input;
let needs_jobs = epiphany_view_needs_jobs(&lenses);
let needs_reorientation_inputs = epiphany_view_needs_reorientation_inputs(&lenses);
let needs_pressure = epiphany_view_needs_pressure(&lenses);
let core_pressure = needs_pressure.then(|| derive_epiphany_pressure(token_usage_info));
let pressure = needs_pressure
.then(|| protocol_pressure_from_core(derive_epiphany_pressure(token_usage_info)));
let core_freshness = needs_reorientation_inputs
.then(|| derive_epiphany_freshness_view(state, retrieval_override, watcher_snapshot));
let (state_revision, core_reorient_state_status, core_reorient_decision) =
if let (Some(freshness), Some(core_pressure)) =
(core_freshness.as_ref(), core_pressure.as_ref())
{
let (state_status, decision) = derive_epiphany_reorient(
state,
core_pressure,
&freshness.retrieval,
&freshness.graph,
&freshness.watcher,
);
(freshness.state_revision, state_status, Some(decision))
} else {
(
None,
epiphany_core::EpiphanyReorientStateStatus::Missing,
None,
)
};
let reorient_state_status = protocol_reorient_state_status(core_reorient_state_status);
let reorient_decision = core_reorient_decision
.clone()
.map(protocol_reorient_decision);
let jobs = if needs_jobs {
map_epiphany_jobs(state, retrieval_override)
} else {
Vec::new()
};
let reorient_job = jobs
.iter()
.find(|job| job.id == EPIPHANY_REORIENT_LAUNCH_BINDING_ID)
.cloned();
let reorient_result = if runtime_store_path.is_some()
|| lenses.contains(&EpiphanyViewLens::Crrc)
|| lenses.contains(&EpiphanyViewLens::Coordinator)
{
load_core_epiphany_reorient_result_snapshot(
state,
runtime_store_path,
EPIPHANY_REORIENT_LAUNCH_BINDING_ID,
)
.await
} else {
crate::runtime_results::EpiphanyReorientResultSnapshot {
status: epiphany_core::EpiphanyCrrcResultStatus::MissingState,
finding: None,
note: "Reorient result was not requested.".to_string(),
}
};
let reorient_result_status = protocol_reorient_result_status(reorient_result.status);
let reorient_finding = reorient_result
.finding
.clone()
.map(protocol_reorient_finding);
let reorient_result_note = reorient_result.note.clone();
let checkpoint_present = state
.and_then(|state| state.investigation_checkpoint.as_ref())
.is_some();
let reorient_finding_accepted = reorient_result.finding.as_ref().is_some_and(|finding| {
state.is_some_and(|state| reorient_finding_already_accepted(state, finding))
});
let recommendation = if let (Some(core_pressure), Some(decision)) =
(core_pressure.as_ref(), core_reorient_decision.as_ref())
{
Some(map_epiphany_crrc_recommendation(
loaded,
core_reorient_state_status,
core_pressure,
decision,
reorient_result.status,
checkpoint_present,
reorient_finding.is_some(),
reorient_finding_accepted,
))
} else {
None
};
let roles = if let (Some(core_pressure), Some(decision), Some(recommendation)) = (
core_pressure.as_ref(),
core_reorient_decision.as_ref(),
recommendation.as_ref(),
) {
Some(map_epiphany_roles(
state,
&jobs,
decision,
core_pressure,
recommendation,
reorient_result.status,
reorient_job.as_ref(),
))
} else {
None
};
let coordinator_response = if lenses.contains(&EpiphanyViewLens::Coordinator) {
if let (Some(core_pressure), Some(recommendation), Some(roles)) = (
core_pressure.as_ref(),
recommendation.as_ref(),
roles.clone(),
) {
let status = derive_epiphany_coordinator_status(
state,
runtime_store_path,
core_reorient_state_status,
core_pressure,
recommendation,
roles.roles.clone(),
core_reorient_decision.as_ref(),
reorient_result.status,
reorient_result.finding.as_ref(),
checkpoint_present,
)
.await;
Some(protocol_coordinator_view(
thread_id.clone(),
loaded,
core_reorient_state_status,
state_revision,
status,
roles,
))
} else {
None
}
} else {
None
};
ThreadEpiphanyViewResponse {
thread_id: thread_id.clone(),
scene: lenses.contains(&EpiphanyViewLens::Scene).then(|| {
protocol_scene(derive_epiphany_scene(
state,
loaded,
EPIPHANY_REORIENT_LAUNCH_BINDING_ID,
))
}),
jobs: if lenses.contains(&EpiphanyViewLens::Jobs) {
jobs.iter()
.cloned()
.map(|job| protocol_job_from_surface(job, None, None))
.collect()
} else {
Vec::new()
},
roles: lenses.contains(&EpiphanyViewLens::Roles).then(|| {
let role_board = roles.clone();
let protocol_roles = role_board
.as_ref()
.map(protocol_role_board_lanes)
.unwrap_or_default();
ThreadEpiphanyViewRoles {
thread_id: thread_id.clone(),
source: if loaded {
ThreadEpiphanyRolesSource::Live
} else {
ThreadEpiphanyRolesSource::Stored
},
state_status: reorient_state_status,
state_revision,
note: render_epiphany_roles_note(
role_board
.as_ref()
.map(|role_board| role_board.roles.as_slice())
.unwrap_or(&[]),
core_reorient_state_status,
recommendation
.as_ref()
.map(|recommendation| recommendation.action)
.unwrap_or(epiphany_core::EpiphanyCrrcAction::Continue),
),
roles: protocol_roles,
}
}),
planning: lenses.contains(&EpiphanyViewLens::Planning).then(|| {
let (state_status, state_revision, planning, summary) =
protocol_planning_view(derive_epiphany_planning(state));
ThreadEpiphanyViewPlanning {
thread_id: thread_id.clone(),
source: if loaded {
ThreadEpiphanyContextSource::Live
} else {
ThreadEpiphanyContextSource::Stored
},
state_status,
state_revision,
planning,
summary,
}
}),
pressure: lenses
.contains(&EpiphanyViewLens::Pressure)
.then(|| pressure.clone())
.flatten(),
reorient: lenses
.contains(&EpiphanyViewLens::Reorient)
.then(|| {
reorient_decision
.clone()
.map(|decision| ThreadEpiphanyViewReorient {
thread_id: thread_id.clone(),
source: if loaded {
ThreadEpiphanyReorientSource::Live
} else {
ThreadEpiphanyReorientSource::Stored
},
state_status: reorient_state_status,
state_revision,
decision,
})
})
.flatten(),
crrc: lenses
.contains(&EpiphanyViewLens::Crrc)
.then(|| {
let pressure = pressure.clone()?;
let decision = reorient_decision.clone()?;
let recommendation = recommendation.clone()?;
let protocol_recommendation = protocol_crrc_recommendation(recommendation.clone());
let available_actions = derive_scene(EpiphanySceneInput {
state,
loaded,
reorient_binding_id: EPIPHANY_REORIENT_LAUNCH_BINDING_ID,
})
.available_actions
.into_iter()
.map(protocol_scene_action)
.collect();
let note = format!(
"{} Result status: {:?}. {}",
recommendation.reason, reorient_result_status, reorient_result_note
);
Some(ThreadEpiphanyViewCrrc {
thread_id: thread_id.clone(),
source: if loaded {
ThreadEpiphanyReorientSource::Live
} else {
ThreadEpiphanyReorientSource::Stored
},
state_status: reorient_state_status,
state_revision,
pressure,
decision,
recommendation: protocol_recommendation,
reorient_binding_id: EPIPHANY_REORIENT_LAUNCH_BINDING_ID.to_string(),
reorient_result_status,
reorient_job: reorient_job
.clone()
.map(|job| protocol_job_from_surface(job, None, None)),
reorient_finding: reorient_finding.clone(),
available_actions,
note,
})
})
.flatten(),
coordinator: coordinator_response,
lenses: lenses
.into_iter()
.map(protocol_view_lens_from_core)
.collect(),
}
}
pub struct EpiphanyRoleResultResponseInput<'a> {
pub thread_id: String,
pub role_id: EpiphanyRoleResultRoleId,
pub source: EpiphanySurfaceSource,
pub binding_id: String,
pub state: Option<&'a EpiphanyThreadState>,
pub runtime_store_path: Option<&'a Path>,
}
pub async fn map_epiphany_role_result_response(
input: EpiphanyRoleResultResponseInput<'_>,
) -> ThreadEpiphanyRoleResultResponse {
let EpiphanyRoleResultResponseInput {
thread_id,
role_id,
source,
binding_id,
state,
runtime_store_path,
} = input;
let protocol_role_id = protocol_role_id_from_core(role_id);
let protocol_source = protocol_roles_source(source);
let Some(state) = state else {
return ThreadEpiphanyRoleResultResponse {
thread_id,
role_id: protocol_role_id,
source: protocol_source,
state_status: protocol_reorient_state_status(
epiphany_core::EpiphanyReorientStateStatus::Missing,
),
state_revision: None,
binding_id,
status: ThreadEpiphanyRoleResultStatus::MissingState,
job: None,
finding: None,
note: "No authoritative Epiphany state exists for this thread.".to_string(),
};
};
let job = map_epiphany_jobs(Some(state), None)
.into_iter()
.find(|job| job.id == binding_id)
.map(|job| protocol_job_from_surface(job, None, None));
let result =
load_core_epiphany_role_result_snapshot(state, runtime_store_path, role_id, &binding_id)
.await;
ThreadEpiphanyRoleResultResponse {
thread_id,
role_id: protocol_role_id,
source: protocol_source,
state_status: protocol_reorient_state_status(
epiphany_core::EpiphanyReorientStateStatus::Ready,
),
state_revision: Some(state.revision),
binding_id,
status: protocol_role_result_status(result.status),
job,
finding: result
.finding
.map(|finding| protocol_role_finding(protocol_role_id, finding)),
note: result.note,
}
}
pub struct EpiphanyReorientResultResponseInput<'a> {
pub thread_id: String,
pub source: EpiphanySurfaceSource,
pub binding_id: String,
pub state: Option<&'a EpiphanyThreadState>,
pub runtime_store_path: Option<&'a Path>,
}
pub async fn map_epiphany_reorient_result_response(
input: EpiphanyReorientResultResponseInput<'_>,
) -> ThreadEpiphanyReorientResultResponse {
let EpiphanyReorientResultResponseInput {
thread_id,
source,
binding_id,
state,
runtime_store_path,
} = input;
let protocol_source = protocol_reorient_source(source);
let Some(state) = state else {
return ThreadEpiphanyReorientResultResponse {
thread_id,
source: protocol_source,
state_status: protocol_reorient_state_status(
epiphany_core::EpiphanyReorientStateStatus::Missing,
),
state_revision: None,
binding_id,
status: ThreadEpiphanyReorientResultStatus::MissingState,
job: None,
finding: None,
note: "No authoritative Epiphany state exists for this thread.".to_string(),
};
};
let job = map_epiphany_jobs(Some(state), None)
.into_iter()
.find(|job| job.id == binding_id)
.map(|job| protocol_job_from_surface(job, None, None));
let result =
load_core_epiphany_reorient_result_snapshot(Some(state), runtime_store_path, &binding_id)
.await;
ThreadEpiphanyReorientResultResponse {
thread_id,
source: protocol_source,
state_status: protocol_reorient_state_status(
epiphany_core::EpiphanyReorientStateStatus::Ready,
),
state_revision: Some(state.revision),
binding_id,
status: protocol_reorient_result_status(result.status),
job,
finding: result.finding.map(protocol_reorient_finding),
note: result.note,
}
}

View file

@ -1,472 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
rendered: PathBuf,
status_exe: Option<PathBuf>,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root.join(".epiphany-smoke").join("mvp-status-codex-home"),
result: root
.join(".epiphany-smoke")
.join("mvp-status-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("mvp-status-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("mvp-status-smoke-server.stderr.log"),
rendered: root
.join(".epiphany-smoke")
.join("mvp-status-smoke-rendered.txt"),
status_exe: None,
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
"--rendered" => parsed.rendered = take_path(&mut args, "--rendered")?,
"--status-exe" => parsed.status_exe = Some(take_path(&mut args, "--status-exe")?),
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = absolute_path(&args.codex_home)?;
let result_path = absolute_path(&args.result)?;
let transcript_path = absolute_path(&args.transcript)?;
let stderr_path = absolute_path(&args.stderr)?;
let rendered_path = absolute_path(&args.rendered)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
rendered_path.clone(),
],
)?;
let status_exe = match &args.status_exe {
Some(path) => absolute_path(path)?,
None => sibling_exe("epiphany-mvp-status")?,
};
ensure_status_built(&root, &status_exe)?;
let status = run_status_json(
&root,
&status_exe,
&app_server,
&codex_home,
&result_path,
&transcript_path,
&stderr_path,
)?;
let rendered = run_status_rendered(
&root,
&status_exe,
&app_server,
&codex_home,
&transcript_path.with_file_name("mvp-status-smoke-render-transcript.jsonl"),
&stderr_path.with_file_name("mvp-status-smoke-render-server.stderr.log"),
)?;
if let Some(parent) = rendered_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&rendered_path, &rendered)?;
validate_status(&status, &rendered)?;
let result = json!({
"threadId": status["threadId"],
"recommendation": status["crrc"]["recommendation"],
"roles": status["roles"],
"roleResults": status["roleResults"],
"planning": status["planning"],
"heartbeat": status["heartbeat"],
"Persona": status["persona"],
"bifrostBridge": status["bifrostBridge"],
"stateStatus": status["scene"]["scene"]["stateStatus"],
"availableActions": status["scene"]["scene"]["availableActions"],
"rendered": rendered,
});
write_json(&result_path, &result)?;
Ok(result)
}
fn run_status_json(
root: &Path,
status_exe: &Path,
app_server: &Path,
codex_home: &Path,
result_path: &Path,
transcript_path: &Path,
stderr_path: &Path,
) -> Result<Value> {
let output = Command::new(status_exe)
.current_dir(root)
.arg("--app-server")
.arg(app_server)
.arg("--codex-home")
.arg(codex_home)
.arg("--cwd")
.arg(root)
.arg("--transcript")
.arg(transcript_path)
.arg("--stderr")
.arg(stderr_path)
.arg("--result")
.arg(result_path)
.arg("--json")
.output()
.context("failed to run native status JSON command")?;
if !output.status.success() {
return Err(anyhow!(
"native status JSON command failed: {}{}",
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
));
}
serde_json::from_slice(&output.stdout).context("failed to decode native status JSON")
}
fn run_status_rendered(
root: &Path,
status_exe: &Path,
app_server: &Path,
codex_home: &Path,
transcript_path: &Path,
stderr_path: &Path,
) -> Result<String> {
let output = Command::new(status_exe)
.current_dir(root)
.arg("--app-server")
.arg(app_server)
.arg("--codex-home")
.arg(codex_home)
.arg("--cwd")
.arg(root)
.arg("--transcript")
.arg(transcript_path)
.arg("--stderr")
.arg(stderr_path)
.output()
.context("failed to run native status rendered command")?;
if !output.status.success() {
return Err(anyhow!(
"native status rendered command failed: {}{}",
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
));
}
String::from_utf8(output.stdout).context("rendered status was not UTF-8")
}
fn validate_status(status: &Value, rendered: &str) -> Result<()> {
require(
status
.pointer("/scene/scene/stateStatus")
.and_then(Value::as_str)
== Some("missing"),
"fresh status smoke should honestly report missing Epiphany state",
)?;
require(
status
.pointer("/crrc/recommendation/action")
.and_then(Value::as_str)
== Some("regatherManually"),
"fresh status smoke should recommend manual regather without state",
)?;
require(
array_contains(status.pointer("/scene/scene/availableActions"), "crrc"),
"status view should expose the CRRC action in the scene",
)?;
require(
array_contains(status.pointer("/scene/scene/availableActions"), "roles"),
"status view should expose the role ownership action in the scene",
)?;
require(
rendered.contains("Epiphany MVP Status") && rendered.contains("Recommendation"),
"rendered status should include the operator view headings",
)?;
require(
rendered.contains("regatherManually"),
"rendered status should expose the CRRC recommendation",
)?;
let lane_ids = status
.pointer("/roles/roles")
.and_then(Value::as_array)
.ok_or_else(|| anyhow!("roles surface missing roles"))?
.iter()
.filter_map(|lane| lane.get("id").and_then(Value::as_str))
.collect::<Vec<_>>();
require(
lane_ids
== [
"implementation",
"imagination",
"research",
"modeling",
"verification",
"reorientation",
],
"roles surface should expose the six MVP role lanes",
)?;
require(
status
.pointer("/roles/note")
.and_then(Value::as_str)
.is_some_and(|note| note.starts_with("Role ownership is derived read-only")),
"roles surface should declare read-only derived ownership",
)?;
require(
status
.pointer("/planning/stateStatus")
.and_then(Value::as_str)
== Some("missing")
&& status
.pointer("/planning/summary/captureCount")
.and_then(Value::as_u64)
== Some(0),
"fresh status smoke should expose empty planning state honestly",
)?;
require(
rendered.contains("Planning") && rendered.contains("captures: 0"),
"rendered status should expose the planning section",
)?;
require(
rendered.contains("Role Lanes") && rendered.contains("Verification / Review"),
"rendered status should expose the role lane section",
)?;
require(
rendered.contains("Role Findings")
&& status
.pointer("/roleResults/imagination/status")
.and_then(Value::as_str)
== Some("missingState")
&& status
.pointer("/roleResults/research/status")
.and_then(Value::as_str)
== Some("missingState")
&& status
.pointer("/roleResults/modeling/status")
.and_then(Value::as_str)
== Some("missingState")
&& status
.pointer("/roleResults/verification/status")
.and_then(Value::as_str)
== Some("missingState"),
"rendered status should expose fixed role result read-back status",
)?;
require(
status
.pointer("/heartbeat/schema_version")
.and_then(Value::as_str)
== Some("epiphany.agent_heartbeat_status.v0"),
"status view should expose heartbeat initiative status for Aquarium",
)?;
let persona_actions = status
.pointer("/persona/availableActions")
.and_then(Value::as_array);
require(
persona_actions.is_some_and(|items| {
items
.iter()
.any(|item| item.as_str() == Some("personaBubble"))
&& items
.iter()
.any(|item| item.as_str() == Some("characterTurn"))
&& items
.iter()
.any(|item| item.as_str() == Some("discordPersonaPost"))
&& items
.iter()
.any(|item| item.as_str() == Some("redditPersonaPost"))
&& items
.iter()
.any(|item| item.as_str() == Some("otherWorldPersonaRequest"))
}),
"status view should expose Persona bubble, character-turn, and Bifrost-routed public mouth actions for Aquarium",
)?;
require(
status
.pointer("/bifrostBridge/owner")
.and_then(Value::as_str)
== Some("Bifrost")
&& status
.pointer("/bifrostBridge/privateStateExposed")
.and_then(Value::as_bool)
== Some(false),
"status view should expose Bifrost bridge sight without private state",
)?;
require(
status
.pointer("/bifrostBridge/surfaceCount")
.and_then(Value::as_u64)
.is_some_and(|count| count >= 5),
"Bifrost bridge sight should include the governed external-world surfaces",
)?;
require(
surface_is(status, "github", &["live"])
&& surface_is(status, "other", &["live"])
&& surface_is(status, "patron", &["live"])
&& surface_is(status, "discord", &["live", "prepared"])
&& surface_is(status, "reddit", &["live", "prepared"]),
"Bifrost bridge sight should report GitHub/Other/Patron live and Discord/Reddit live or prepared",
)?;
require(
rendered.contains("Bifrost bridge")
&& rendered.contains("github=live")
&& rendered.contains("patron=live"),
"rendered status should expose compact Bifrost bridge rows",
)?;
require(
rendered.contains("Heartbeat") && rendered.contains("Persona"),
"rendered status should expose heartbeat and Persona sections",
)?;
Ok(())
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn ensure_status_built(root: &Path, status_exe: &Path) -> Result<()> {
if status_exe.exists() {
return Ok(());
}
let status = Command::new("cargo")
.current_dir(root)
.arg("build")
.arg("--manifest-path")
.arg(root.join("epiphany-core").join("Cargo.toml"))
.arg("--bin")
.arg("epiphany-mvp-status")
.status()
.context("failed to build epiphany-mvp-status")?;
require(
status.success() && status_exe.exists(),
&format!(
"native status binary was not built: {}",
status_exe.display()
),
)
}
fn sibling_exe(name: &str) -> Result<PathBuf> {
let mut exe = env::current_exe().context("failed to resolve current executable")?;
exe.set_file_name(format!("{name}{}", env::consts::EXE_SUFFIX));
Ok(exe)
}
fn array_contains(value: Option<&Value>, needle: &str) -> bool {
value
.and_then(Value::as_array)
.is_some_and(|items| items.iter().any(|item| item.as_str() == Some(needle)))
}
fn surface_is(status: &Value, id: &str, allowed: &[&str]) -> bool {
status
.pointer("/bifrostBridge/surfaces")
.and_then(Value::as_array)
.and_then(|surfaces| {
surfaces
.iter()
.find(|surface| surface.get("id").and_then(Value::as_str) == Some(id))
})
.and_then(|surface| surface.get("status").and_then(Value::as_str))
.is_some_and(|surface_status| allowed.contains(&surface_status))
}
fn absolute_path(path: &Path) -> Result<PathBuf> {
if path.is_absolute() {
Ok(path.to_path_buf())
} else {
Ok(env::current_dir()?.join(path))
}
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -47,19 +47,9 @@ use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
use std::process::Command;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
const DEFAULT_CARGO_TARGET_DIR: &str = r"C:\Users\Meta\.cargo-target-codex";
const DEFAULT_THREAD_STATE_STORE: &str = "state/thread-state.msgpack";
const DEFAULT_RUNTIME_STORE: &str = "state/runtime-spine.msgpack";
@ -91,15 +81,6 @@ fn main() -> Result<()> {
format!("{}\n", serde_json::to_string_pretty(&status)?),
)
.with_context(|| format!("failed to write {}", result.display()))?;
if args.source == StatusSource::Codex {
write_transcript_telemetry(&args.transcript, &result.with_extension("telemetry.json"))?;
}
}
if args.source == StatusSource::Codex {
write_transcript_telemetry(
&args.transcript,
&args.transcript.with_extension("telemetry.json"),
)?;
}
if args.json {
println!("{}", serde_json::to_string_pretty(&status)?);
@ -109,17 +90,8 @@ fn main() -> Result<()> {
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StatusSource {
Native,
Codex,
}
#[derive(Debug)]
struct Args {
source: StatusSource,
app_server: PathBuf,
codex_home: PathBuf,
thread_id: Option<String>,
cwd: PathBuf,
thread_state_store: PathBuf,
@ -138,11 +110,6 @@ impl Args {
let root = env::current_dir().context("failed to resolve current directory")?;
let mut args = env::args().skip(1);
let mut parsed = Args {
source: StatusSource::Native,
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: env::var_os("CODEX_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".codex")),
thread_id: None,
cwd: root.clone(),
thread_state_store: PathBuf::from(DEFAULT_THREAD_STATE_STORE),
@ -161,11 +128,6 @@ impl Args {
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--source" => parsed.source = take_source(&mut args, "--source")?,
"--native" => parsed.source = StatusSource::Native,
"--codex" => parsed.source = StatusSource::Codex,
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--thread-id" => parsed.thread_id = Some(take_string(&mut args, "--thread-id")?),
"--cwd" => parsed.cwd = take_path(&mut args, "--cwd")?,
"--thread-state-store" => {
@ -195,15 +157,9 @@ impl Args {
fn run_status(args: &Args) -> Result<Value> {
if args.interrupt_binding.is_some() {
return match args.source {
StatusSource::Native => run_native_interrupt(args),
StatusSource::Codex => run_codex_interrupt(args),
};
}
match args.source {
StatusSource::Native => run_native_status(args),
StatusSource::Codex => run_codex_status(args),
return run_native_interrupt(args);
}
run_native_status(args)
}
fn run_native_interrupt(args: &Args) -> Result<Value> {
@ -246,52 +202,6 @@ fn run_native_interrupt(args: &Args) -> Result<Value> {
}))
}
fn run_codex_interrupt(args: &Args) -> Result<Value> {
if args.source != StatusSource::Codex {
return Err(anyhow!(
"--interrupt-binding requires Codex/app-server status source"
));
}
let thread_id = args
.thread_id
.as_ref()
.ok_or_else(|| anyhow!("--interrupt-binding requires --thread-id"))?;
let binding_id = args
.interrupt_binding
.as_ref()
.ok_or_else(|| anyhow!("--interrupt-binding requires a binding id"))?;
let app_server = absolute_path(&args.app_server)?;
let codex_home = absolute_path(&args.codex_home)?;
let transcript = absolute_path(&args.transcript)?;
let stderr = absolute_path(&args.stderr)?;
let mut client = AppServerClient::start(&app_server, &codex_home, &transcript, &stderr)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-mvp-status",
"title": "Epiphany MVP Status",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
if !args.ephemeral {
client.send("thread/resume", Some(json!({"threadId": thread_id})), true)?;
}
client.send(
"thread/epiphany/jobInterrupt",
Some(json!({
"threadId": thread_id,
"bindingId": binding_id,
"reason": args.interrupt_reason,
})),
true,
)
}
fn run_native_status(args: &Args) -> Result<Value> {
let cwd = absolute_path(&args.cwd)?;
let store_path = absolute_path(&args.thread_state_store)?;
@ -571,123 +481,6 @@ fn run_native_status(args: &Args) -> Result<Value> {
Ok(sanitize_for_operator(status))
}
fn run_codex_status(args: &Args) -> Result<Value> {
let app_server = absolute_path(&args.app_server)?;
let codex_home = absolute_path(&args.codex_home)?;
let cwd = absolute_path(&args.cwd)?;
let transcript = absolute_path(&args.transcript)?;
let stderr = absolute_path(&args.stderr)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let mut client = AppServerClient::start(&app_server, &codex_home, &transcript, &stderr)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-mvp-status",
"title": "Epiphany MVP Status",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let thread_id = if let Some(thread_id) = &args.thread_id {
if !args.ephemeral {
client.send("thread/resume", Some(json!({"threadId": thread_id})), true)?;
}
thread_id.clone()
} else {
let started = client.send(
"thread/start",
Some(json!({"cwd": cwd, "ephemeral": args.ephemeral})),
true,
)?;
started["thread"]["id"]
.as_str()
.ok_or_else(|| anyhow!("thread/start returned no thread id"))?
.to_string()
};
let read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
let view = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["scene", "pressure", "jobs", "roles", "planning", "reorient", "crrc", "coordinator"]})),
true,
)?;
let scene = json!({
"threadId": thread_id,
"scene": view.get("scene").cloned().unwrap_or_else(|| json!(null)),
});
let pressure = json!({
"threadId": thread_id,
"source": "live",
"pressure": view.get("pressure").cloned().unwrap_or_else(|| json!(null)),
});
let reorient = view.get("reorient").cloned().unwrap_or_else(|| json!(null));
let jobs = json!({
"threadId": thread_id,
"source": "live",
"jobs": view.get("jobs").cloned().unwrap_or_else(|| json!([])),
});
let roles = view.get("roles").cloned().unwrap_or_else(|| json!(null));
let planning = view.get("planning").cloned().unwrap_or_else(|| json!(null));
let role_results = json!({
"imagination": client.send("thread/epiphany/roleResult", Some(json!({"threadId": thread_id, "roleId": "imagination"})), true)?,
"research": client.send("thread/epiphany/roleResult", Some(json!({"threadId": thread_id, "roleId": "research"})), true)?,
"modeling": client.send("thread/epiphany/roleResult", Some(json!({"threadId": thread_id, "roleId": "modeling"})), true)?,
"verification": client.send("thread/epiphany/roleResult", Some(json!({"threadId": thread_id, "roleId": "verification"})), true)?,
});
let reorient_result = client.send(
"thread/epiphany/reorientResult",
Some(json!({"threadId": thread_id})),
true,
)?;
let crrc = view.get("crrc").cloned().unwrap_or_else(|| json!(null));
let coordinator = view
.get("coordinator")
.cloned()
.unwrap_or_else(|| json!(null));
let runtime_store_path = absolute_path(&args.runtime_store)?;
let tool_invocations = native_tool_invocation_surface(&runtime_store_path)?;
let root = env::current_dir().context("failed to resolve current directory")?;
let native_aux = native_auxiliary_status(&root)?;
let status = json!({
"threadId": thread_id,
"read": read,
"view": view,
"scene": scene,
"pressure": pressure,
"reorient": reorient,
"jobs": jobs,
"roles": roles,
"planning": planning,
"roleResults": role_results,
"reorientResult": reorient_result,
"crrc": crrc,
"coordinator": coordinator,
"tools": tool_invocations,
"heartbeat": native_aux.heartbeat,
"persona": native_aux.persona,
"bifrostBridge": native_aux.bifrost_bridge,
"voidMemory": native_aux.void_memory,
});
Ok(sanitize_for_operator(status))
}
struct NativeAuxiliaryStatus {
heartbeat: Value,
persona: Value,
@ -1293,262 +1086,6 @@ fn role_job_status(status: epiphany_core::EpiphanyJobStatus) -> EpiphanyRoleBoar
}
}
pub struct AppServerClient {
child: Child,
stdin: ChildStdin,
rx: mpsc::Receiver<Value>,
transcript: Arc<Mutex<File>>,
notifications: Arc<Mutex<Vec<Value>>>,
next_id: u64,
}
impl AppServerClient {
pub fn start(
app_server: &Path,
codex_home: &Path,
transcript_path: &Path,
stderr_path: &Path,
) -> Result<Self> {
if let Some(parent) = transcript_path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
if let Some(parent) = stderr_path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
let transcript = Arc::new(Mutex::new(
File::create(transcript_path)
.with_context(|| format!("failed to create {}", transcript_path.display()))?,
));
let stderr_file = Arc::new(Mutex::new(
File::create(stderr_path)
.with_context(|| format!("failed to create {}", stderr_path.display()))?,
));
let mut command = Command::new(app_server);
command
.current_dir(
env::current_dir()?
.join("vendor")
.join("codex")
.join("codex-rs"),
)
.env("CODEX_HOME", codex_home)
.env(
"CARGO_TARGET_DIR",
env::var("CARGO_TARGET_DIR")
.unwrap_or_else(|_| DEFAULT_CARGO_TARGET_DIR.to_string()),
)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command
.spawn()
.context("failed to spawn codex app-server")?;
let stdin = child
.stdin
.take()
.ok_or_else(|| anyhow!("app-server stdin unavailable"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| anyhow!("app-server stdout unavailable"))?;
let stderr = child
.stderr
.take()
.ok_or_else(|| anyhow!("app-server stderr unavailable"))?;
let (tx, rx) = mpsc::channel();
let transcript_for_stdout = Arc::clone(&transcript);
let notifications = Arc::new(Mutex::new(Vec::new()));
let notifications_for_stdout = Arc::clone(&notifications);
thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if line.trim().is_empty() {
continue;
}
let message = serde_json::from_str::<Value>(&line).unwrap_or_else(
|error| json!({"_decode_error": error.to_string(), "raw": line}),
);
record(&transcript_for_stdout, "received", &message);
if message.get("method").is_some()
&& message.get("id").is_none()
&& let Ok(mut notifications) = notifications_for_stdout.lock()
{
notifications.push(message.clone());
}
let _ = tx.send(message);
}
});
thread::spawn(move || {
for line in BufReader::new(stderr).lines().map_while(Result::ok) {
if let Ok(mut file) = stderr_file.lock() {
let _ = writeln!(file, "{line}");
}
}
});
Ok(Self {
child,
stdin,
rx,
transcript,
notifications,
next_id: 1,
})
}
pub fn send(
&mut self,
method: &str,
params: Option<Value>,
expect_response: bool,
) -> Result<Value> {
let mut message = serde_json::Map::new();
message.insert("method".to_string(), json!(method));
let request_id = if expect_response {
let id = self.next_id;
self.next_id += 1;
message.insert("id".to_string(), json!(id));
Some(id)
} else {
None
};
if let Some(params) = params {
message.insert("params".to_string(), params);
}
let message = Value::Object(message);
record(&self.transcript, "sent", &message);
writeln!(
self.stdin,
"{}",
serde_json::to_string(&message).context("failed to encode request")?
)
.context("failed to write app-server request")?;
self.stdin
.flush()
.context("failed to flush app-server stdin")?;
let Some(request_id) = request_id else {
return Ok(Value::Null);
};
self.wait_for(request_id)
}
fn wait_for(&mut self, request_id: u64) -> Result<Value> {
let deadline = Instant::now() + Duration::from_secs(45);
while Instant::now() < deadline {
if let Some(status) = self.child.try_wait()? {
return Err(anyhow!(
"app-server exited with {} before response {}",
status,
request_id
));
}
match self.rx.recv_timeout(Duration::from_millis(500)) {
Ok(message) => {
if message.get("id").and_then(Value::as_u64) != Some(request_id) {
continue;
}
if let Some(error) = message.get("error") {
return Err(anyhow!("request {request_id} failed: {error}"));
}
let result = message
.get("result")
.cloned()
.ok_or_else(|| anyhow!("request {request_id} returned no result"))?;
if !result.is_object() {
return Err(anyhow!(
"request {request_id} returned non-object result: {result}"
));
}
return Ok(result);
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(error) => return Err(anyhow!("app-server response channel closed: {error}")),
}
}
Err(anyhow!("timed out waiting for response {request_id}"))
}
pub fn notification_count(&self, method: &str, start_index: usize) -> usize {
self.notifications
.lock()
.ok()
.map(|notifications| {
notifications
.iter()
.skip(start_index)
.filter(|message| message.get("method").and_then(Value::as_str) == Some(method))
.count()
})
.unwrap_or(0)
}
pub fn notification_len(&self) -> usize {
self.notifications
.lock()
.map(|notifications| notifications.len())
.unwrap_or(0)
}
pub fn require_no_notification(
&mut self,
method: &str,
start_index: usize,
timeout: Duration,
) -> Result<()> {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Some(status) = self.child.try_wait()? {
return Err(anyhow!(
"app-server exited with {} while checking notification {}",
status,
method
));
}
if self.notification_count(method, start_index) > 0 {
return Err(anyhow!("unexpected notification {method}"));
}
thread::sleep(Duration::from_millis(100));
}
Ok(())
}
pub fn wait_for_notification(
&mut self,
method: &str,
start_index: usize,
timeout: Duration,
) -> Result<Value> {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Some(status) = self.child.try_wait()? {
return Err(anyhow!(
"app-server exited with {} before notification {}",
status,
method
));
}
if let Ok(notifications) = self.notifications.lock()
&& let Some(message) = notifications
.iter()
.skip(start_index)
.find(|message| message.get("method").and_then(Value::as_str) == Some(method))
{
return Ok(message.clone());
}
thread::sleep(Duration::from_millis(100));
}
Err(anyhow!("timed out waiting for notification {method}"))
}
}
impl Drop for AppServerClient {
fn drop(&mut self) {
let _ = self.stdin.flush();
let _ = self.child.kill();
let _ = self.child.wait();
}
}
pub fn render_status(status: &Value) -> String {
let scene = &status["scene"]["scene"];
let pressure = &status["pressure"]["pressure"];
@ -1825,18 +1362,6 @@ fn sealed_long_text(key: &str, text: &str) -> Value {
})
}
pub fn write_transcript_telemetry(transcript: &Path, output: &Path) -> Result<()> {
let _ = native_json(
"epiphany-agent-telemetry",
&[
&transcript.to_string_lossy(),
"--output",
&output.to_string_lossy(),
],
)?;
Ok(())
}
pub fn native_json(bin_name: &str, args: &[&str]) -> Result<Value> {
let sibling = env::current_exe()
.ok()
@ -1876,12 +1401,6 @@ pub fn native_json(bin_name: &str, args: &[&str]) -> Result<Value> {
.with_context(|| format!("{bin_name} returned invalid JSON"))
}
fn record(transcript: &Arc<Mutex<File>>, kind: &str, payload: &Value) {
if let Ok(mut file) = transcript.lock() {
let _ = writeln!(file, "{}", json!({kind: payload}));
}
}
fn take_string(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
args.next()
.ok_or_else(|| anyhow!("{name} requires a value"))
@ -1891,23 +1410,6 @@ fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<Path
Ok(PathBuf::from(take_string(args, name)?))
}
fn take_source(args: &mut impl Iterator<Item = String>, name: &str) -> Result<StatusSource> {
match take_string(args, name)?.as_str() {
"native" => Ok(StatusSource::Native),
"codex" => Ok(StatusSource::Codex),
other => Err(anyhow!(
"{name} must be 'native' or 'codex', received {other:?}"
)),
}
}
fn home_dir() -> PathBuf {
env::var_os("USERPROFILE")
.or_else(|| env::var_os("HOME"))
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."))
}
#[cfg(test)]
mod native_interrupt_tests {
use super::*;
@ -1937,9 +1439,6 @@ mod native_interrupt_tests {
None,
)?;
let args = Args {
source: StatusSource::Native,
app_server: PathBuf::new(),
codex_home: PathBuf::new(),
thread_id: Some("thread-1".to_string()),
cwd: temp.path().to_path_buf(),
thread_state_store: store.clone(),

View file

@ -1,529 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root
.join(".epiphany-smoke")
.join("phase6-context-codex-home"),
result: root
.join(".epiphany-smoke")
.join("phase6-context-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("phase6-context-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("phase6-context-smoke-server.stderr.log"),
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = status_cli::absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let result_path = status_cli::absolute_path(&args.result)?;
let transcript_path = status_cli::absolute_path(&args.transcript)?;
let stderr_path = status_cli::absolute_path(&args.stderr)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
],
)?;
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-phase6-context-smoke",
"title": "Epiphany Phase 6 Context Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let started = client.send(
"thread/start",
Some(json!({"cwd": root.join("epiphany-core"), "ephemeral": true})),
true,
)?;
let thread_id = started
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("thread/start response missing thread.id"))?
.to_string();
let missing_notification_start = client.notification_len();
let missing_response = client.send(
"thread/epiphany/context",
Some(json!({"threadId": thread_id, "graphNodeIds": ["context-surface"]})),
true,
)?;
require(
missing_response.get("threadId").and_then(Value::as_str) == Some(&thread_id),
"context response should echo thread id",
)?;
assert_missing_context(&missing_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
missing_notification_start,
Duration::from_secs(1),
)?;
let update_notification_start = client.notification_len();
let update = client.send(
"thread/epiphany/update",
Some(json!({
"threadId": thread_id,
"expectedRevision": 0,
"patch": context_patch(),
})),
true,
)?;
require(
update.get("revision").and_then(Value::as_u64) == Some(1),
"context smoke patch should advance revision to 1",
)?;
client.wait_for_notification(
"thread/epiphany/stateUpdated",
update_notification_start,
Duration::from_secs(10),
)?;
let context_notification_start = client.notification_len();
let ready_response = client.send(
"thread/epiphany/context",
Some(json!({
"threadId": thread_id,
"graphNodeIds": ["missing-node"],
"graphEdgeIds": ["missing-edge"],
"observationIds": ["obs-context", "missing-observation"],
"evidenceIds": ["ev-context-extra", "missing-evidence"],
})),
true,
)?;
assert_ready_context(&ready_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
context_notification_start,
Duration::from_secs(1),
)?;
let final_read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
require(
final_read
.pointer("/thread/epiphanyState/revision")
.and_then(Value::as_u64)
== Some(1),
"context reflection should not mutate state revision",
)?;
let result = json!({
"threadId": thread_id,
"codexHome": codex_home,
"missingStateStatus": missing_response["stateStatus"],
"readyStateStatus": ready_response["stateStatus"],
"readyRevision": ready_response["stateRevision"],
"architectureNodeIds": ids(&ready_response["context"]["graph"]["architectureNodes"]),
"investigationCheckpointId": ready_response["context"]["investigationCheckpoint"]["checkpoint_id"],
"investigationDisposition": ready_response["context"]["investigationCheckpoint"]["disposition"],
"evidenceIds": ids(&ready_response["context"]["evidence"]),
"contextNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
context_notification_start,
),
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
});
write_json(&result_path, &result)?;
Ok(result)
}
fn context_patch() -> Value {
let code_ref = json!({
"path": "app-server/src/codex_message_processor.rs",
"start_line": 10791,
"end_line": 10989,
"symbol": "map_epiphany_context"
});
json!({
"objective": "Expose a read-only Epiphany context shard without returning the full state.",
"activeSubgoalId": "phase6-context-smoke",
"investigationCheckpoint": {
"checkpoint_id": "phase6-context-investigation",
"kind": "source_gathering",
"disposition": "regather_required",
"focus": "Make stale planning obvious when context is re-read after compaction.",
"summary": "Context reflection should expose the full durable checkpoint packet.",
"next_action": "Re-gather source before editing if the packet no longer matches reality.",
"captured_at_turn_id": "turn-phase6-context",
"open_questions": ["How much checkpoint detail belongs in scene versus context?"],
"code_refs": [code_ref.clone()],
"evidence_ids": ["ev-context-linked"]
},
"subgoals": [{
"id": "phase6-context-smoke",
"title": "Live-smoke context shard reflection",
"status": "active",
"summary": "The app-server context surface should return targeted graph/evidence state."
}],
"graphs": {
"architecture": {
"nodes": [{
"id": "context-surface",
"title": "Context shard surface",
"purpose": "Return bounded state context for clients without becoming a writer.",
"code_refs": [code_ref.clone()]
}],
"edges": [{
"id": "context-edge",
"source_id": "context-surface",
"target_id": "context-surface",
"kind": "reflects",
"code_refs": [code_ref.clone()]
}]
},
"dataflow": {
"nodes": [{
"id": "typed-state",
"title": "Typed Epiphany state",
"purpose": "Remain authoritative while context shards reflect a slice."
}]
},
"links": [{
"dataflow_node_id": "typed-state",
"architecture_node_id": "context-surface",
"relationship": "bounded-reflection"
}]
},
"graphFrontier": {
"active_node_ids": ["context-surface"],
"active_edge_ids": ["context-edge"]
},
"graphCheckpoint": {
"checkpoint_id": "phase6-context-smoke",
"graph_revision": 1,
"summary": "Context shard reflection is the active Phase 6 smoke target.",
"frontier_node_ids": ["context-surface"]
},
"evidence": [
{
"id": "ev-context-linked",
"kind": "smoke-test",
"status": "ok",
"summary": "Context smoke linked evidence should come along with the observation.",
"code_refs": [code_ref.clone()]
},
{
"id": "ev-context-extra",
"kind": "review",
"status": "ok",
"summary": "Context smoke direct evidence should be returned when requested.",
"code_refs": [code_ref]
}
],
"observations": [{
"id": "obs-context",
"summary": "Context smoke observation should be selected by id.",
"source_kind": "smoke",
"status": "ok",
"code_refs": [{
"path": "app-server/src/codex_message_processor.rs",
"start_line": 10791,
"end_line": 10989,
"symbol": "map_epiphany_context"
}],
"evidence_ids": ["ev-context-linked"]
}]
})
}
fn assert_missing_context(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"missing context should report live source",
)?;
require(
response.get("stateStatus").and_then(Value::as_str) == Some("missing"),
"missing context should report missing state",
)?;
require(
response.get("stateRevision").is_none(),
"missing context should not invent a revision",
)?;
require(
response.pointer("/context/graph") == Some(&json!({})),
"missing context should not invent graph records",
)?;
require(
string_array_eq(
response
.pointer("/missing/graphNodeIds")
.and_then(Value::as_array),
&["context-surface"],
),
"missing context should echo requested missing node ids",
)
}
fn assert_ready_context(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"ready context should report live source",
)?;
require(
response.get("stateStatus").and_then(Value::as_str) == Some("ready"),
"ready context should report ready state",
)?;
require(
response.get("stateRevision").and_then(Value::as_u64) == Some(1),
"ready context should preserve state revision identity",
)?;
require(
ids_eq(
response
.pointer("/context/graph/architectureNodes")
.and_then(Value::as_array),
&["context-surface"],
),
"context should include active frontier architecture node",
)?;
require(
ids_eq(
response
.pointer("/context/graph/architectureEdges")
.and_then(Value::as_array),
&["context-edge"],
),
"context should include active frontier architecture edge",
)?;
require(
response
.pointer("/context/graph/links/0/architecture_node_id")
.and_then(Value::as_str)
== Some("context-surface"),
"context should include links touching selected graph nodes",
)?;
require(
string_array_eq(
response
.pointer("/context/frontier/active_node_ids")
.and_then(Value::as_array),
&["context-surface"],
),
"context should include frontier when active frontier is requested by default",
)?;
require(
response
.pointer("/context/checkpoint/checkpoint_id")
.and_then(Value::as_str)
== Some("phase6-context-smoke"),
"context should expose the current graph checkpoint",
)?;
require(
response
.pointer("/context/investigationCheckpoint/checkpoint_id")
.and_then(Value::as_str)
== Some("phase6-context-investigation"),
"context should expose the investigation checkpoint id",
)?;
require(
response
.pointer("/context/investigationCheckpoint/disposition")
.and_then(Value::as_str)
== Some("regather_required"),
"context should expose the checkpoint disposition",
)?;
require(
ids_eq(
response
.pointer("/context/observations")
.and_then(Value::as_array),
&["obs-context"],
),
"context should include requested observation",
)?;
require(
ids_eq(
response
.pointer("/context/evidence")
.and_then(Value::as_array),
&["ev-context-linked", "ev-context-extra"],
),
"context should include linked and directly requested evidence",
)?;
require(
string_array_eq(
response
.pointer("/missing/graphNodeIds")
.and_then(Value::as_array),
&["missing-node"],
) && string_array_eq(
response
.pointer("/missing/graphEdgeIds")
.and_then(Value::as_array),
&["missing-edge"],
) && string_array_eq(
response
.pointer("/missing/observationIds")
.and_then(Value::as_array),
&["missing-observation"],
) && string_array_eq(
response
.pointer("/missing/evidenceIds")
.and_then(Value::as_array),
&["missing-evidence"],
),
"context should report unresolved requested ids",
)
}
fn ids(value: &Value) -> Value {
json!(
value
.as_array()
.map(|items| {
items
.iter()
.filter_map(|item| item.get("id").and_then(Value::as_str))
.collect::<Vec<_>>()
})
.unwrap_or_default()
)
}
fn ids_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.get("id").and_then(Value::as_str) == Some(*expected))
})
}
fn string_array_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.as_str() == Some(*expected))
})
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -1,389 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root
.join(".epiphany-smoke")
.join("phase6-freshness-codex-home"),
result: root
.join(".epiphany-smoke")
.join("phase6-freshness-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("phase6-freshness-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("phase6-freshness-smoke-server.stderr.log"),
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = status_cli::absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let result_path = status_cli::absolute_path(&args.result)?;
let transcript_path = status_cli::absolute_path(&args.transcript)?;
let stderr_path = status_cli::absolute_path(&args.stderr)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
],
)?;
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-phase6-freshness-smoke",
"title": "Epiphany Phase 6 Freshness Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let started = client.send(
"thread/start",
Some(json!({"cwd": root.join("epiphany-core"), "ephemeral": true})),
true,
)?;
let thread_id = started
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("thread/start response missing thread.id"))?
.to_string();
let missing_notification_start = client.notification_len();
let missing_response = client.send(
"thread/epiphany/freshness",
Some(json!({"threadId": thread_id})),
true,
)?;
require(
missing_response.get("threadId").and_then(Value::as_str) == Some(&thread_id),
"freshness response should echo thread id",
)?;
assert_missing_state_freshness(&missing_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
missing_notification_start,
Duration::from_secs(1),
)?;
let update_notification_start = client.notification_len();
let update = client.send(
"thread/epiphany/update",
Some(json!({
"threadId": thread_id,
"expectedRevision": 0,
"patch": freshness_patch(),
})),
true,
)?;
require(
update.get("revision").and_then(Value::as_u64) == Some(1),
"freshness smoke patch should advance revision to 1",
)?;
client.wait_for_notification(
"thread/epiphany/stateUpdated",
update_notification_start,
Duration::from_secs(10),
)?;
let ready_notification_start = client.notification_len();
let ready_response = client.send(
"thread/epiphany/freshness",
Some(json!({"threadId": thread_id})),
true,
)?;
assert_ready_freshness(&ready_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
ready_notification_start,
Duration::from_secs(1),
)?;
let final_read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
require(
final_read
.pointer("/thread/epiphanyState/revision")
.and_then(Value::as_u64)
== Some(1),
"freshness reflection should not mutate state revision",
)?;
let result = json!({
"threadId": thread_id,
"codexHome": codex_home,
"missingRetrievalStatus": missing_response["retrieval"]["status"],
"missingGraphStatus": missing_response["graph"]["status"],
"readyRevision": ready_response["stateRevision"],
"readyRetrievalStatus": ready_response["retrieval"]["status"],
"readyGraphStatus": ready_response["graph"]["status"],
"readyDirtyPathCount": ready_response["graph"]["dirtyPathCount"],
"freshnessNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
ready_notification_start,
),
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
});
write_json(&result_path, &result)?;
Ok(result)
}
fn freshness_patch() -> Value {
json!({
"objective": "Expose read-only Epiphany freshness reflection without inventing watcher-driven invalidation.",
"activeSubgoalId": "phase6-freshness-smoke",
"subgoals": [{
"id": "phase6-freshness-smoke",
"title": "Live-smoke freshness reflection",
"status": "active",
"summary": "The freshness surface should reflect graph staleness and live retrieval state without mutation."
}],
"graphs": {
"architecture": {
"nodes": [{
"id": "freshness-surface",
"title": "Freshness reflection surface",
"purpose": "Expose exact retrieval and graph freshness pressure without becoming a scheduler.",
"code_refs": [{
"path": "app-server/src/codex_message_processor.rs",
"start_line": 4200,
"end_line": 4340,
"symbol": "thread_epiphany_freshness"
}]
}]
},
"dataflow": {"nodes": []},
"links": []
},
"graphFrontier": {
"active_node_ids": ["freshness-surface"],
"dirty_paths": ["app-server/src/codex_message_processor.rs"],
"open_question_ids": ["q-freshness-gap"]
},
"graphCheckpoint": {
"checkpoint_id": "ck-freshness-1",
"graph_revision": 1,
"summary": "Freshness smoke checkpoint",
"frontier_node_ids": ["freshness-surface"],
"open_question_ids": ["q-freshness-gap"]
},
"churn": {
"understanding_status": "ready",
"diff_pressure": "low",
"graph_freshness": "stale",
"unexplained_writes": 0
}
})
}
fn assert_missing_state_freshness(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"freshness should report live source for a loaded thread",
)?;
require(
response.get("stateRevision").is_none(),
"missing-state freshness should not invent a revision",
)?;
let retrieval = &response["retrieval"];
require(
retrieval.get("status").and_then(Value::as_str) == Some("ready"),
"live retrieval freshness should be available",
)?;
require(
retrieval.get("note").and_then(Value::as_str) == Some("Retrieval catalog is ready."),
"fresh live retrieval should report ready note",
)?;
let graph = &response["graph"];
require(
graph.get("status").and_then(Value::as_str) == Some("missing"),
"missing Epiphany state should block graph freshness",
)?;
require(
graph.get("note").and_then(Value::as_str)
== Some("Epiphany state is missing, so graph freshness cannot be assessed."),
"missing graph freshness should explain itself",
)
}
fn assert_ready_freshness(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"ready freshness should report live source",
)?;
require(
response.get("stateRevision").and_then(Value::as_u64) == Some(1),
"freshness should preserve state revision identity",
)?;
let retrieval = &response["retrieval"];
require(
retrieval.get("status").and_then(Value::as_str) == Some("ready"),
"live retrieval freshness should stay ready for the smoke workspace",
)?;
require(
retrieval.get("semanticAvailable").and_then(Value::as_bool) == Some(true),
"live retrieval freshness should report semantic availability",
)?;
let graph = &response["graph"];
require(
graph.get("status").and_then(Value::as_str) == Some("stale"),
"dirty graph frontier should report stale freshness",
)?;
require(
graph.get("graphFreshness").and_then(Value::as_str) == Some("stale"),
"graph freshness should expose the churn hint",
)?;
require(
graph.get("checkpointId").and_then(Value::as_str) == Some("ck-freshness-1"),
"graph freshness should expose the checkpoint id",
)?;
require(
graph.get("dirtyPathCount").and_then(Value::as_u64) == Some(1),
"graph freshness should count dirty paths",
)?;
require(
string_array_eq(
graph.get("dirtyPaths").and_then(Value::as_array),
&["app-server/src/codex_message_processor.rs"],
),
"graph freshness should expose dirty paths",
)?;
require(
graph.get("openQuestionCount").and_then(Value::as_u64) == Some(1),
"graph freshness should count open questions",
)?;
require(
graph.get("openGapCount").and_then(Value::as_u64) == Some(0),
"graph freshness should count open gaps",
)
}
fn string_array_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.as_str() == Some(*expected))
})
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -1,540 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root
.join(".epiphany-smoke")
.join("phase6-graph-query-codex-home"),
result: root
.join(".epiphany-smoke")
.join("phase6-graph-query-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("phase6-graph-query-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("phase6-graph-query-smoke-server.stderr.log"),
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = status_cli::absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let result_path = status_cli::absolute_path(&args.result)?;
let transcript_path = status_cli::absolute_path(&args.transcript)?;
let stderr_path = status_cli::absolute_path(&args.stderr)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
],
)?;
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-phase6-graph-query-smoke",
"title": "Epiphany Phase 6 Graph Query Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let started = client.send(
"thread/start",
Some(json!({"cwd": root.join("epiphany-core"), "ephemeral": true})),
true,
)?;
let thread_id = started
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("thread/start response missing thread.id"))?
.to_string();
let missing_notification_start = client.notification_len();
let missing_response = client.send(
"thread/epiphany/graphQuery",
Some(json!({
"threadId": thread_id,
"query": {"kind": "node", "nodeIds": ["graph-query-surface"]},
})),
true,
)?;
assert_missing_graph_query(&missing_response, &thread_id)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
missing_notification_start,
Duration::from_secs(1),
)?;
let update_notification_start = client.notification_len();
let update = client.send(
"thread/epiphany/update",
Some(json!({
"threadId": thread_id,
"expectedRevision": 0,
"patch": graph_query_patch(),
})),
true,
)?;
require(
update.get("revision").and_then(Value::as_u64) == Some(1),
"graph query smoke patch should advance revision to 1",
)?;
client.wait_for_notification(
"thread/epiphany/stateUpdated",
update_notification_start,
Duration::from_secs(10),
)?;
let frontier_notification_start = client.notification_len();
let frontier_response = client.send(
"thread/epiphany/graphQuery",
Some(json!({
"threadId": thread_id,
"query": {
"kind": "frontierNeighborhood",
"direction": "outgoing",
"depth": 1,
},
})),
true,
)?;
assert_frontier_graph_query(&frontier_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
frontier_notification_start,
Duration::from_secs(1),
)?;
let path_notification_start = client.notification_len();
let path_response = client.send(
"thread/epiphany/graphQuery",
Some(json!({
"threadId": thread_id,
"query": {
"kind": "path",
"paths": ["app-server/src/codex_message_processor.rs"],
"symbols": ["map_epiphany_graph_query"],
},
})),
true,
)?;
assert_path_graph_query(&path_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
path_notification_start,
Duration::from_secs(1),
)?;
let final_read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
require(
final_read
.pointer("/thread/epiphanyState/revision")
.and_then(Value::as_u64)
== Some(1),
"graph query reflection should not mutate state revision",
)?;
let result = json!({
"threadId": thread_id,
"codexHome": codex_home,
"missingStateStatus": missing_response["stateStatus"],
"frontierStateStatus": frontier_response["stateStatus"],
"pathStateStatus": path_response["stateStatus"],
"readyRevision": frontier_response["stateRevision"],
"frontierArchitectureNodeIds": ids(&frontier_response["graph"]["architectureNodes"]),
"frontierDataflowNodeIds": ids(&frontier_response["graph"]["dataflowNodes"]),
"pathMatchedSymbols": path_response["matched"]["symbols"],
"frontierNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
frontier_notification_start,
),
"pathNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
path_notification_start,
),
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
});
write_json(&result_path, &result)?;
Ok(result)
}
fn graph_query_patch() -> Value {
let code_ref = json!({
"path": "app-server/src/codex_message_processor.rs",
"start_line": 15201,
"end_line": 15534,
"symbol": "map_epiphany_graph_query"
});
json!({
"objective": "Expose read-only graph traversal for implementation and verifier agents.",
"activeSubgoalId": "phase6-graph-query-smoke",
"subgoals": [{
"id": "phase6-graph-query-smoke",
"title": "Live-smoke graph query traversal",
"status": "active",
"summary": "The graph query surface should traverse typed graph state without mutating it."
}],
"graphs": {
"architecture": {
"nodes": [
{
"id": "graph-query-surface",
"title": "Graph query surface",
"purpose": "Return bounded graph neighborhoods and path matches for agents.",
"code_refs": [code_ref.clone()]
},
{
"id": "implementation-agent",
"title": "Implementation agent",
"purpose": "Uses graph neighborhoods to decide where to edit."
},
{
"id": "verifier-agent",
"title": "Verifier agent",
"purpose": "Uses graph neighborhoods to inspect blast radius."
}
],
"edges": [
{
"id": "edge-query-implementation",
"source_id": "graph-query-surface",
"target_id": "implementation-agent",
"kind": "guides",
"code_refs": [code_ref.clone()]
},
{
"id": "edge-query-verifier",
"source_id": "graph-query-surface",
"target_id": "verifier-agent",
"kind": "guides"
}
]
},
"dataflow": {
"nodes": [{
"id": "typed-graph-state",
"title": "Typed graph state",
"purpose": "Remain the authoritative model behind graph traversal.",
"code_refs": [code_ref.clone()]
}]
},
"links": [{
"dataflow_node_id": "typed-graph-state",
"architecture_node_id": "graph-query-surface",
"relationship": "authoritative-query-source",
"code_refs": [code_ref]
}]
},
"graphFrontier": {
"active_node_ids": ["graph-query-surface"],
"active_edge_ids": ["edge-query-implementation"]
},
"graphCheckpoint": {
"checkpoint_id": "phase6-graph-query-smoke",
"graph_revision": 1,
"summary": "Graph query traversal is the active Phase 6 smoke target.",
"frontier_node_ids": ["graph-query-surface"]
}
})
}
fn assert_missing_graph_query(response: &Value, thread_id: &str) -> Result<()> {
require(
response.get("threadId").and_then(Value::as_str) == Some(thread_id),
"graph query should echo thread id",
)?;
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"missing graph query should report live source",
)?;
require(
response.get("stateStatus").and_then(Value::as_str) == Some("missing"),
"missing graph query should report missing state",
)?;
require(
response.get("stateRevision").is_none(),
"missing graph query should not invent a revision",
)?;
require(
response.get("graph") == Some(&json!({})),
"missing graph query should not invent graph records",
)?;
require(
string_array_eq(
response
.pointer("/missing/nodeIds")
.and_then(Value::as_array),
&["graph-query-surface"],
),
"missing graph query should echo unresolved explicit node ids",
)
}
fn assert_frontier_graph_query(response: &Value) -> Result<()> {
require(
response.get("stateStatus").and_then(Value::as_str) == Some("ready"),
"frontier graph query should report ready state",
)?;
require(
response.get("stateRevision").and_then(Value::as_u64) == Some(1),
"frontier graph query should preserve revision",
)?;
require(
ids_eq(
response
.pointer("/graph/architectureNodes")
.and_then(Value::as_array),
&[
"graph-query-surface",
"implementation-agent",
"verifier-agent",
],
),
"frontier graph query should return one-hop architecture neighbors",
)?;
require(
ids_eq(
response
.pointer("/graph/dataflowNodes")
.and_then(Value::as_array),
&["typed-graph-state"],
),
"frontier graph query should preserve linked dataflow node",
)?;
require(
ids_eq(
response
.pointer("/graph/architectureEdges")
.and_then(Value::as_array),
&["edge-query-implementation", "edge-query-verifier"],
),
"frontier graph query should return active and incident architecture edges",
)?;
require(
response
.pointer("/graph/links/0/dataflow_node_id")
.and_then(Value::as_str)
== Some("typed-graph-state"),
"frontier graph query should return architecture/dataflow link",
)?;
require(
string_array_eq(
response
.pointer("/frontier/active_node_ids")
.and_then(Value::as_array),
&["graph-query-surface"],
),
"frontier graph query should include current frontier",
)?;
require(
response
.pointer("/checkpoint/checkpoint_id")
.and_then(Value::as_str)
== Some("phase6-graph-query-smoke"),
"frontier graph query should include graph checkpoint",
)?;
require(
response.get("missing") == Some(&json!({})),
"frontier graph query should have no missing records",
)
}
fn assert_path_graph_query(response: &Value) -> Result<()> {
require(
response.get("stateStatus").and_then(Value::as_str) == Some("ready"),
"path graph query should report ready state",
)?;
require(
string_array_eq(
response.pointer("/matched/paths").and_then(Value::as_array),
&["app-server/src/codex_message_processor.rs"],
),
"path graph query should report matched code ref path",
)?;
require(
string_array_eq(
response
.pointer("/matched/symbols")
.and_then(Value::as_array),
&["map_epiphany_graph_query"],
),
"path graph query should report matched symbol",
)?;
require(
string_array_contains(
response
.pointer("/matched/nodeIds")
.and_then(Value::as_array),
"graph-query-surface",
),
"path graph query should include graph query node in matches",
)?;
require(
string_array_contains(
response
.pointer("/matched/nodeIds")
.and_then(Value::as_array),
"typed-graph-state",
),
"path graph query should include linked dataflow node in matches",
)
}
fn ids(value: &Value) -> Value {
json!(
value
.as_array()
.map(|items| {
items
.iter()
.filter_map(|item| item.get("id").and_then(Value::as_str))
.collect::<Vec<_>>()
})
.unwrap_or_default()
)
}
fn ids_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.get("id").and_then(Value::as_str) == Some(*expected))
})
}
fn string_array_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.as_str() == Some(*expected))
})
}
fn string_array_contains(values: Option<&Vec<Value>>, expected: &str) -> bool {
values.is_some_and(|values| values.iter().any(|value| value.as_str() == Some(expected)))
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -1,529 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root
.join(".epiphany-smoke")
.join("phase6-planning-codex-home"),
result: root
.join(".epiphany-smoke")
.join("phase6-planning-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("phase6-planning-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("phase6-planning-smoke-server.stderr.log"),
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = status_cli::absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let result_path = status_cli::absolute_path(&args.result)?;
let transcript_path = status_cli::absolute_path(&args.transcript)?;
let stderr_path = status_cli::absolute_path(&args.stderr)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
],
)?;
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-phase6-planning-smoke",
"title": "Epiphany Phase 6 Planning Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let started = client.send(
"thread/start",
Some(json!({"cwd": root.join("epiphany-core"), "ephemeral": true})),
true,
)?;
let thread_id = started
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("thread/start response missing thread.id"))?
.to_string();
let missing_notification_start = client.notification_len();
let missing_view = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["planning"]})),
true,
)?;
let missing_response = missing_view
.get("planning")
.ok_or_else(|| anyhow!("view response missing planning lens"))?;
require(
missing_response.get("threadId").and_then(Value::as_str) == Some(&thread_id),
"planning response should echo thread id",
)?;
assert_missing_planning(&missing_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
missing_notification_start,
Duration::from_secs(1),
)?;
let update_notification_start = client.notification_len();
let update = client.send(
"thread/epiphany/update",
Some(json!({
"threadId": thread_id,
"expectedRevision": 0,
"patch": planning_patch(&root),
})),
true,
)?;
require(
update.get("revision").and_then(Value::as_u64) == Some(1),
"planning patch should advance revision to 1",
)?;
let update_notification = client.wait_for_notification(
"thread/epiphany/stateUpdated",
update_notification_start,
Duration::from_secs(10),
)?;
require(
string_array_contains(
update_notification
.pointer("/params/changedFields")
.and_then(Value::as_array),
"planning",
),
"planning update should report the planning changed field",
)?;
let planning_notification_start = client.notification_len();
let ready_view = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["planning"]})),
true,
)?;
let ready_response = ready_view
.get("planning")
.ok_or_else(|| anyhow!("view response missing planning lens"))?;
assert_ready_planning(&ready_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
planning_notification_start,
Duration::from_secs(1),
)?;
let final_read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
require(
final_read
.pointer("/thread/epiphanyState/revision")
.and_then(Value::as_u64)
== Some(1),
"planning reflection should not mutate state revision",
)?;
let result = json!({
"threadId": thread_id,
"codexHome": codex_home,
"missingStateStatus": missing_response["stateStatus"],
"readyStateStatus": ready_response["stateStatus"],
"readyRevision": ready_response["stateRevision"],
"captureCount": ready_response["summary"]["captureCount"],
"githubIssueCaptureCount": ready_response["summary"]["githubIssueCaptureCount"],
"backlogItemCount": ready_response["summary"]["backlogItemCount"],
"objectiveDraftCount": ready_response["summary"]["objectiveDraftCount"],
"planningNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
planning_notification_start,
),
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
});
write_json(&result_path, &result)?;
Ok(result)
}
fn planning_patch(root: &Path) -> Value {
let github_source = json!({
"kind": "github_issue",
"provider": "github",
"repo": "GameCult/EpiphanyAgent",
"issue_number": 42,
"url": "https://github.com/GameCult/EpiphanyAgent/issues/42",
"state": "open",
"labels": ["planning", "mvp"],
"assignees": ["Meta"],
"author": "Meta",
"created_at": "2026-05-01T10:00:00Z",
"updated_at": "2026-05-01T10:05:00Z",
"imported_at": "2026-05-01T10:10:00Z"
});
let chat_source = json!({
"kind": "chat",
"uri": "codex://threads/planning-smoke",
"external_id": "turn-planning-smoke"
});
json!({
"objective": "Keep planning state reviewable before adopting an implementation objective.",
"planning": {
"workspace_root": root,
"captures": [
{
"id": "capture-github-planning",
"title": "Import GitHub issue into planning inbox",
"body": "Issues should become planning captures before becoming objectives.",
"confidence": "observed",
"status": "inbox",
"speaker": "human",
"tags": ["github", "backlog"],
"source": github_source.clone(),
"created_at": "2026-05-01T10:10:00Z",
"updated_at": "2026-05-01T10:10:00Z"
},
{
"id": "capture-chat-planning",
"title": "Draft objectives from chat only after bounding them",
"body": "User discussion remains planning material until it becomes a firm artifact.",
"confidence": "medium",
"status": "triaged",
"speaker": "human",
"tags": ["chat", "objective"],
"source": chat_source.clone(),
"created_at": "2026-05-01T10:12:00Z",
"updated_at": "2026-05-01T10:12:00Z"
}
],
"backlog_items": [{
"id": "backlog-planning-dashboard",
"title": "Expose planning state in the Epiphany dashboard",
"kind": "feature",
"summary": "Show captures, backlog, roadmap streams, and objective drafts.",
"status": "ready",
"horizon": "near",
"priority": {
"value": "high",
"rationale": "Planning needs a visible user review loop before automation.",
"impact": "user-steering",
"urgency": "soon",
"confidence": "medium",
"effort": "small",
"unblocks": ["objective-adoption"]
},
"confidence": "medium",
"product_area": "epiphany-gui",
"lane_hints": ["imagination", "hands", "soul"],
"acceptance_sketch": ["Dashboard can render typed planning records."],
"source_refs": [github_source, chat_source],
"updated_at": "2026-05-01T10:15:00Z"
}],
"roadmap_streams": [{
"id": "stream-user-steering",
"title": "Human-steered planning",
"purpose": "Keep future work visible and bounded before implementation starts.",
"status": "active",
"item_ids": ["backlog-planning-dashboard"],
"near_term_focus": "backlog-planning-dashboard",
"review_cadence": "per objective"
}],
"objective_drafts": [{
"id": "draft-planning-dashboard",
"title": "Build the planning dashboard slice",
"summary": "Render planning records and let the user adopt one bounded objective.",
"source_item_ids": ["backlog-planning-dashboard"],
"scope": {
"includes": ["read-only planning projection", "objective draft review"],
"excludes": ["automatic objective adoption"]
},
"acceptance_criteria": [
"Planning records render without changing thread state.",
"A draft objective remains review-gated."
],
"evidence_required": ["live smoke", "GUI screenshot"],
"lane_plan": {
"imagination": "organize planning records into a bounded objective candidate",
"eyes": "check prior art and GitHub issue metadata shape",
"hands": "wire dashboard controls after the read-only surface is stable",
"soul": "verify no planning record silently becomes active objective"
},
"risks": ["accidental objective adoption"],
"review_gates": ["human adoption"],
"status": "draft"
}]
}
})
}
fn assert_missing_planning(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"missing planning should report live source",
)?;
require(
response.get("stateStatus").and_then(Value::as_str) == Some("missing"),
"missing planning should report missing state",
)?;
require(
response.get("stateRevision").is_none(),
"missing planning should not invent a revision",
)?;
require(
response.get("planning") == Some(&json!({})),
"missing planning should return empty planning",
)?;
let summary = &response["summary"];
require(
summary.get("captureCount").and_then(Value::as_u64) == Some(0),
"missing planning should not invent captures",
)?;
require(
summary.get("backlogItemCount").and_then(Value::as_u64) == Some(0),
"missing planning should not invent backlog",
)?;
require(
summary.get("activeObjective").is_none(),
"missing planning should not invent objective",
)
}
fn assert_ready_planning(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"ready planning should report live source",
)?;
require(
response.get("stateStatus").and_then(Value::as_str) == Some("ready"),
"ready planning should report ready state",
)?;
require(
response.get("stateRevision").and_then(Value::as_u64) == Some(1),
"ready planning should expose current revision",
)?;
let planning = &response["planning"];
require(
ids_eq(
planning.get("captures").and_then(Value::as_array),
&["capture-github-planning", "capture-chat-planning"],
),
"planning should preserve captures",
)?;
require(
planning
.pointer("/captures/0/source/kind")
.and_then(Value::as_str)
== Some("github_issue"),
"planning should preserve GitHub issue source kind",
)?;
require(
planning
.pointer("/captures/0/source/issue_number")
.and_then(Value::as_u64)
== Some(42),
"planning should preserve GitHub issue number",
)?;
require(
ids_eq(
planning.get("backlog_items").and_then(Value::as_array),
&["backlog-planning-dashboard"],
),
"planning should preserve backlog items",
)?;
require(
planning
.pointer("/roadmap_streams/0/near_term_focus")
.and_then(Value::as_str)
== Some("backlog-planning-dashboard"),
"planning should preserve roadmap near-term focus",
)?;
require(
planning
.pointer("/objective_drafts/0/status")
.and_then(Value::as_str)
== Some("draft"),
"planning should preserve draft objective state",
)?;
let summary = &response["summary"];
require(
summary.get("captureCount").and_then(Value::as_u64) == Some(2),
"planning summary should count captures",
)?;
require(
summary.get("pendingCaptureCount").and_then(Value::as_u64) == Some(1),
"planning summary should count inbox captures",
)?;
require(
summary
.get("githubIssueCaptureCount")
.and_then(Value::as_u64)
== Some(1),
"planning summary should count GitHub captures",
)?;
require(
summary.get("backlogItemCount").and_then(Value::as_u64) == Some(1),
"planning summary should count backlog",
)?;
require(
summary.get("readyBacklogItemCount").and_then(Value::as_u64) == Some(1),
"planning summary should count ready backlog",
)?;
require(
summary.get("roadmapStreamCount").and_then(Value::as_u64) == Some(1),
"planning summary should count roadmap streams",
)?;
require(
summary.get("objectiveDraftCount").and_then(Value::as_u64) == Some(1),
"planning summary should count drafts",
)?;
require(
summary.get("draftObjectiveCount").and_then(Value::as_u64) == Some(1),
"planning summary should count draft status",
)?;
require(
summary
.get("activeObjective")
.and_then(Value::as_str)
.is_some_and(|objective| objective.starts_with("Keep planning state reviewable")),
"planning summary should expose the active thread objective separately",
)?;
require(
summary
.get("note")
.and_then(Value::as_str)
.is_some_and(|note| note.contains("human explicitly adopts an objective")),
"planning summary should remind clients that adoption is explicit",
)
}
fn ids_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.get("id").and_then(Value::as_str) == Some(*expected))
})
}
fn string_array_contains(values: Option<&Vec<Value>>, expected: &str) -> bool {
values.is_some_and(|values| values.iter().any(|value| value.as_str() == Some(expected)))
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -1,241 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root
.join(".epiphany-smoke")
.join("phase6-pressure-codex-home"),
result: root
.join(".epiphany-smoke")
.join("phase6-pressure-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("phase6-pressure-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("phase6-pressure-smoke-server.stderr.log"),
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = status_cli::absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let result_path = status_cli::absolute_path(&args.result)?;
let transcript_path = status_cli::absolute_path(&args.transcript)?;
let stderr_path = status_cli::absolute_path(&args.stderr)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
],
)?;
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-phase6-pressure-smoke",
"title": "Epiphany Phase 6 Pressure Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let started = client.send(
"thread/start",
Some(json!({"cwd": root.join("epiphany-core"), "ephemeral": true})),
true,
)?;
let thread_id = started
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("thread/start response missing thread.id"))?
.to_string();
let notification_start = client.notification_len();
let response = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["pressure"]})),
true,
)?;
require(
response.get("threadId").and_then(Value::as_str) == Some(&thread_id),
"pressure response should echo thread id",
)?;
assert_unknown_pressure(&response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
notification_start,
Duration::from_secs(1),
)?;
let final_read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
require(
final_read.pointer("/thread/epiphanyState").is_none(),
"pressure reflection should not create Epiphany state",
)?;
let result = json!({
"threadId": thread_id,
"codexHome": codex_home,
"source": "thread/epiphany/view",
"status": response["pressure"]["status"],
"level": response["pressure"]["level"],
"basis": response["pressure"]["basis"],
"shouldPrepareCompaction": response["pressure"]["shouldPrepareCompaction"],
"stateUpdatedNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
notification_start,
),
"finalReadHasEpiphanyState": final_read.pointer("/thread/epiphanyState").is_some(),
});
write_json(&result_path, &result)?;
Ok(result)
}
fn assert_unknown_pressure(response: &Value) -> Result<()> {
let pressure = response
.get("pressure")
.ok_or_else(|| anyhow!("pressure response missing pressure object"))?;
require(
pressure.get("status").and_then(Value::as_str) == Some("unknown"),
"fresh pressure should be unknown",
)?;
require(
pressure.get("level").and_then(Value::as_str) == Some("unknown"),
"fresh pressure level should be unknown",
)?;
require(
pressure.get("basis").and_then(Value::as_str) == Some("unknown"),
"fresh pressure basis should be unknown",
)?;
require(
pressure
.get("shouldPrepareCompaction")
.and_then(Value::as_bool)
== Some(false),
"unknown pressure must not recommend compaction prep",
)?;
require(
pressure.get("usedTokens").is_none(),
"fresh pressure should not invent token usage",
)
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -1,498 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, Instant};
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
const WATCHED_RELATIVE_PATH: &str = "src/reorient_target.rs";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
workspace: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root
.join(".epiphany-smoke")
.join("phase6-reorient-codex-home"),
workspace: root
.join(".epiphany-smoke")
.join("phase6-reorient-workspace"),
result: root
.join(".epiphany-smoke")
.join("phase6-reorient-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("phase6-reorient-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("phase6-reorient-smoke-server.stderr.log"),
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--workspace" => parsed.workspace = take_path(&mut args, "--workspace")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = status_cli::absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let workspace = status_cli::absolute_path(&args.workspace)?;
let result_path = status_cli::absolute_path(&args.result)?;
let transcript_path = status_cli::absolute_path(&args.transcript)?;
let stderr_path = status_cli::absolute_path(&args.stderr)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
workspace.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
],
)?;
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let watched_file = prepare_workspace(&workspace)?;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-phase6-reorient-smoke",
"title": "Epiphany Phase 6 Reorient Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let started = client.send(
"thread/start",
Some(json!({"cwd": workspace, "ephemeral": true})),
true,
)?;
let thread_id = started
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("thread/start response missing thread.id"))?
.to_string();
let missing_notification_start = client.notification_len();
let missing_view = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["reorient"]})),
true,
)?;
let missing_response = missing_view
.get("reorient")
.ok_or_else(|| anyhow!("view response missing reorient lens"))?;
assert_missing_reorient(&missing_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
missing_notification_start,
Duration::from_secs(1),
)?;
let update_notification_start = client.notification_len();
let update = client.send(
"thread/epiphany/update",
Some(json!({
"threadId": thread_id,
"expectedRevision": 0,
"patch": reorient_patch(),
})),
true,
)?;
require(
update.get("revision").and_then(Value::as_u64) == Some(1),
"reorient smoke patch should advance revision to 1",
)?;
client.wait_for_notification(
"thread/epiphany/stateUpdated",
update_notification_start,
Duration::from_secs(10),
)?;
let ready_notification_start = client.notification_len();
let ready_view = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["reorient"]})),
true,
)?;
let ready_response = ready_view
.get("reorient")
.ok_or_else(|| anyhow!("view response missing reorient lens"))?;
assert_ready_reorient(&ready_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
ready_notification_start,
Duration::from_secs(1),
)?;
fs::write(
watched_file,
"pub fn reorient_target() -> &'static str {\n \"after\"\n}\n",
)?;
let regather_notification_start = client.notification_len();
let regather_response = wait_for_regather_reorient(&mut client, &thread_id)?;
assert_regather_reorient(&regather_response)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
regather_notification_start,
Duration::from_secs(1),
)?;
let final_read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
require(
final_read
.pointer("/thread/epiphanyState/revision")
.and_then(Value::as_u64)
== Some(1),
"reorient reflection should not mutate durable state",
)?;
let result = json!({
"threadId": thread_id,
"codexHome": codex_home,
"workspace": workspace,
"missingAction": missing_response["decision"]["action"],
"readyAction": ready_response["decision"]["action"],
"regatherAction": regather_response["decision"]["action"],
"regatherReasons": regather_response["decision"]["reasons"],
"checkpointChangedPaths": regather_response["decision"]["checkpointChangedPaths"],
"activeFrontierNodeIds": regather_response["decision"]["activeFrontierNodeIds"],
"stateUpdatedNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
regather_notification_start,
),
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
});
write_json(&result_path, &result)?;
Ok(result)
}
fn prepare_workspace(workspace: &Path) -> Result<PathBuf> {
fs::create_dir_all(workspace)?;
let watched_file = workspace.join(WATCHED_RELATIVE_PATH);
fs::create_dir_all(watched_file.parent().expect("watched path has parent"))?;
fs::write(
&watched_file,
"pub fn reorient_target() -> &'static str {\n \"before\"\n}\n",
)?;
Ok(watched_file)
}
fn reorient_patch() -> Value {
let code_ref = json!({
"path": WATCHED_RELATIVE_PATH,
"start_line": 1,
"end_line": 3,
"symbol": "reorient_target"
});
json!({
"objective": "Decide whether a durable checkpoint still deserves to be resumed after rehydrate.",
"activeSubgoalId": "phase6-reorient-smoke",
"subgoals": [{
"id": "phase6-reorient-smoke",
"title": "Live-smoke CRRC reorientation policy",
"status": "active",
"summary": "Resume when the checkpoint is still aligned; regather when the touched file proves it isn't."
}],
"graphs": {
"architecture": {
"nodes": [{
"id": "reorient-target",
"title": "Reorient target",
"purpose": "Map the file the watcher will touch so reorientation can notice drift.",
"code_refs": [code_ref.clone()]
}]
},
"dataflow": {"nodes": []},
"links": []
},
"graphFrontier": {
"active_node_ids": ["reorient-target"],
"dirty_paths": []
},
"graphCheckpoint": {
"checkpoint_id": "ck-reorient-1",
"graph_revision": 1,
"summary": "Reorientation smoke graph checkpoint",
"frontier_node_ids": ["reorient-target"]
},
"investigationCheckpoint": {
"checkpoint_id": "ix-reorient-1",
"kind": "source_gathering",
"disposition": "resume_ready",
"focus": "Verify the touched file before broad edits.",
"summary": "This checkpoint should remain resumable until the watched source moves.",
"next_action": "Resume the bounded slice if the watched source still matches the checkpoint.",
"captured_at_turn_id": "turn-phase6-reorient",
"code_refs": [code_ref]
},
"churn": {
"understanding_status": "ready",
"diff_pressure": "low",
"graph_freshness": "fresh",
"unexplained_writes": 0
}
})
}
fn assert_missing_reorient(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"missing reorient response should report live source",
)?;
require(
response.get("stateStatus").and_then(Value::as_str) == Some("missing"),
"missing reorient response should report missing state",
)?;
let decision = &response["decision"];
require(
decision.get("action").and_then(Value::as_str) == Some("regather"),
"missing reorient response should regather",
)?;
require(
decision.get("checkpointStatus").and_then(Value::as_str) == Some("missing"),
"missing reorient response should report missing checkpoint",
)?;
require(
string_array_eq(
decision.get("reasons").and_then(Value::as_array),
&["missingState", "missingCheckpoint"],
),
"missing reorient response should explain missing state and checkpoint",
)
}
fn assert_ready_reorient(response: &Value) -> Result<()> {
require(
response.get("source").and_then(Value::as_str) == Some("live"),
"ready reorient response should report live source",
)?;
require(
response.get("stateStatus").and_then(Value::as_str) == Some("ready"),
"ready reorient response should report ready state",
)?;
require(
response.get("stateRevision").and_then(Value::as_u64) == Some(1),
"ready reorient response should preserve revision identity",
)?;
let decision = &response["decision"];
require(
decision.get("action").and_then(Value::as_str) == Some("resume"),
"clean checkpoint should remain resumable",
)?;
require(
decision.get("checkpointStatus").and_then(Value::as_str) == Some("resumeReady"),
"ready reorient response should report resume-ready checkpoint status",
)?;
require(
string_array_eq(
decision.get("reasons").and_then(Value::as_array),
&["checkpointReady"],
),
"ready reorient response should explain that the checkpoint is still aligned",
)?;
require(
decision.get("checkpointId").and_then(Value::as_str) == Some("ix-reorient-1"),
"ready reorient response should expose the checkpoint id",
)?;
require(
decision.get("nextAction").and_then(Value::as_str)
== Some("Resume the bounded slice if the watched source still matches the checkpoint."),
"ready reorient response should preserve checkpoint next action",
)?;
require(
decision.get("watcherStatus").and_then(Value::as_str) == Some("clean"),
"ready reorient response should report a clean watcher before drift",
)
}
fn wait_for_regather_reorient(
client: &mut status_cli::AppServerClient,
thread_id: &str,
) -> Result<Value> {
let deadline = Instant::now() + Duration::from_secs(10);
let mut last_response = Value::Null;
while Instant::now() < deadline {
let response = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["reorient"]})),
true,
)?;
let reorient = response
.get("reorient")
.ok_or_else(|| anyhow!("view response missing reorient lens"))?;
if reorient.pointer("/decision/action").and_then(Value::as_str) == Some("regather") {
return Ok(reorient.clone());
}
last_response = response;
thread::sleep(Duration::from_millis(200));
}
Err(anyhow!(
"reorientation policy did not switch to regather before timeout; last response: {last_response}"
))
}
fn assert_regather_reorient(response: &Value) -> Result<()> {
let decision = &response["decision"];
require(
decision.get("action").and_then(Value::as_str) == Some("regather"),
"touched checkpoint path should force regather",
)?;
require(
decision.get("checkpointStatus").and_then(Value::as_str) == Some("resumeReady"),
"regather response should preserve the underlying checkpoint disposition",
)?;
require(
string_array_eq(
decision.get("reasons").and_then(Value::as_array),
&["checkpointPathsChanged", "frontierChanged"],
),
"regather response should explain watcher path and frontier drift",
)?;
let changed_paths = decision
.get("checkpointChangedPaths")
.and_then(Value::as_array)
.ok_or_else(|| anyhow!("regather response missing changed paths"))?;
require(
changed_paths
.iter()
.filter_map(Value::as_str)
.map(|path| path.replace('\\', "/"))
.any(|path| path == WATCHED_RELATIVE_PATH),
"regather response should report the changed checkpoint path",
)?;
require(
string_array_eq(
decision
.get("activeFrontierNodeIds")
.and_then(Value::as_array),
&["reorient-target"],
),
"regather response should report touched frontier nodes",
)?;
require(
decision
.get("note")
.and_then(Value::as_str)
.is_some_and(|note| note.starts_with("Re-gather before editing:")),
"regather response should explain why the checkpoint is no longer safe to resume",
)
}
fn string_array_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.as_str() == Some(*expected))
})
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -1,646 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use serde_json::json;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[allow(dead_code)]
#[path = "epiphany-mvp-status.rs"]
mod status_cli;
const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe";
fn main() -> Result<()> {
let args = Args::parse()?;
let result = run_smoke(&args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
#[derive(Debug)]
struct Args {
app_server: PathBuf,
codex_home: PathBuf,
result: PathBuf,
transcript: PathBuf,
stderr: PathBuf,
}
impl Args {
fn parse() -> Result<Self> {
let root = env::current_dir().context("failed to resolve current dir")?;
let mut parsed = Self {
app_server: PathBuf::from(DEFAULT_APP_SERVER),
codex_home: root.join(".epiphany-smoke").join("phase6-scene-codex-home"),
result: root
.join(".epiphany-smoke")
.join("phase6-scene-smoke-result.json"),
transcript: root
.join(".epiphany-smoke")
.join("phase6-scene-smoke-transcript.jsonl"),
stderr: root
.join(".epiphany-smoke")
.join("phase6-scene-smoke-server.stderr.log"),
};
let mut args = env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--app-server" => parsed.app_server = take_path(&mut args, "--app-server")?,
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
"--result" => parsed.result = take_path(&mut args, "--result")?,
"--transcript" => parsed.transcript = take_path(&mut args, "--transcript")?,
"--stderr" => parsed.stderr = take_path(&mut args, "--stderr")?,
other => return Err(anyhow!("unknown argument: {other}")),
}
}
Ok(parsed)
}
}
fn run_smoke(args: &Args) -> Result<Value> {
let root = env::current_dir().context("failed to resolve current dir")?;
let app_server = status_cli::absolute_path(&args.app_server)?;
if !app_server.exists() {
return Err(anyhow!(
"codex app-server binary not found: {}",
app_server.display()
));
}
let codex_home = status_cli::absolute_path(&args.codex_home)?;
let result_path = status_cli::absolute_path(&args.result)?;
let transcript_path = status_cli::absolute_path(&args.transcript)?;
let stderr_path = status_cli::absolute_path(&args.stderr)?;
reset_smoke_paths(
&root,
&[
codex_home.clone(),
result_path.clone(),
transcript_path.clone(),
stderr_path.clone(),
],
)?;
fs::create_dir_all(&codex_home)
.with_context(|| format!("failed to create {}", codex_home.display()))?;
let mut client = status_cli::AppServerClient::start(
&app_server,
&codex_home,
&transcript_path,
&stderr_path,
)?;
client.send(
"initialize",
Some(json!({
"clientInfo": {
"name": "epiphany-phase6-scene-smoke",
"title": "Epiphany Phase 6 Scene Smoke",
"version": "0.1.0",
},
"capabilities": {"experimentalApi": true},
})),
true,
)?;
client.send("initialized", None, false)?;
let started = client.send(
"thread/start",
Some(json!({"cwd": root.join("epiphany-core"), "ephemeral": true})),
true,
)?;
let thread_id = started
.pointer("/thread/id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("thread/start response missing thread.id"))?
.to_string();
let missing_response = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["scene"]})),
true,
)?;
assert_missing_scene(&missing_response["scene"])?;
let update_notification_start = client.notification_len();
let update = client.send(
"thread/epiphany/update",
Some(json!({
"threadId": thread_id,
"expectedRevision": 0,
"patch": initial_scene_patch(),
})),
true,
)?;
require(
update.get("revision").and_then(Value::as_u64) == Some(1),
"initial scene patch should advance revision to 1",
)?;
let update_notification = client.wait_for_notification(
"thread/epiphany/stateUpdated",
update_notification_start,
Duration::from_secs(10),
)?;
require(
update_notification
.pointer("/params/revision")
.and_then(Value::as_u64)
== Some(1),
"initial update notification should expose revision 1",
)?;
for index in 2..=6 {
let update_notification_start = client.notification_len();
let update = client.send(
"thread/epiphany/update",
Some(json!({
"threadId": thread_id,
"expectedRevision": index - 1,
"patch": {
"evidence": [evidence_record(index)],
"observations": [observation_record(index)],
},
})),
true,
)?;
require(
update.get("revision").and_then(Value::as_u64) == Some(index),
&format!("record update {index} should advance revision to {index}"),
)?;
let update_notification = client.wait_for_notification(
"thread/epiphany/stateUpdated",
update_notification_start as usize,
Duration::from_secs(10),
)?;
require(
update_notification
.pointer("/params/revision")
.and_then(Value::as_u64)
== Some(index),
&format!("record update {index} notification should expose revision {index}"),
)?;
}
let scene_notification_start = client.notification_len();
let ready_response = client.send(
"thread/epiphany/view",
Some(json!({"threadId": thread_id, "lenses": ["scene"]})),
true,
)?;
require(
ready_response.get("threadId").and_then(Value::as_str) == Some(&thread_id),
"scene response should echo thread id",
)?;
assert_ready_scene(&ready_response["scene"], 6)?;
client.require_no_notification(
"thread/epiphany/stateUpdated",
scene_notification_start,
Duration::from_secs(1),
)?;
let final_read = client.send(
"thread/read",
Some(json!({"threadId": thread_id, "includeTurns": false})),
true,
)?;
require(
final_read
.pointer("/thread/epiphanyState/revision")
.and_then(Value::as_u64)
== Some(6),
"scene should not mutate state revision",
)?;
let scene = &ready_response["scene"];
let result = json!({
"threadId": thread_id,
"codexHome": codex_home,
"missingStateStatus": missing_response["scene"]["stateStatus"],
"missingAvailableActions": missing_response["scene"]["availableActions"],
"readyStateStatus": scene["stateStatus"],
"readySource": scene["source"],
"readyRevision": scene["revision"],
"readyAvailableActions": scene["availableActions"],
"investigationCheckpointId": scene["investigationCheckpoint"]["checkpointId"],
"investigationDisposition": scene["investigationCheckpoint"]["disposition"],
"latestObservationIds": ids(&scene["observations"]["latest"]),
"latestEvidenceIds": ids(&scene["evidence"]["latest"]),
"retrievalStatus": scene["retrieval"]["status"],
"sceneNotificationCount": client.notification_count(
"thread/epiphany/stateUpdated",
scene_notification_start,
),
"finalReadRevision": final_read["thread"]["epiphanyState"]["revision"],
});
write_json(&result_path, &result)?;
Ok(result)
}
fn mapper_code_ref() -> Value {
json!({
"path": "app-server/src/codex_message_processor.rs",
"start_line": 10573,
"end_line": 10689,
"symbol": "map_epiphany_scene"
})
}
fn evidence_record(index: u64) -> Value {
json!({
"id": format!("ev-phase6-scene-{index}"),
"kind": "smoke-test",
"status": "ok",
"summary": format!("Scene smoke evidence {index} should appear newest-first."),
"code_refs": [mapper_code_ref()]
})
}
fn observation_record(index: u64) -> Value {
json!({
"id": format!("obs-phase6-scene-{index}"),
"summary": format!("Scene smoke observation {index} should appear newest-first."),
"source_kind": "smoke",
"status": "ok",
"code_refs": [mapper_code_ref()],
"evidence_ids": [format!("ev-phase6-scene-{index}")]
})
}
fn initial_scene_patch() -> Value {
json!({
"objective": "Expose live Epiphany scene reflection without creating a second source of truth.",
"activeSubgoalId": "phase6-scene-smoke",
"investigationCheckpoint": {
"checkpoint_id": "phase6-scene-investigation",
"kind": "slice_planning",
"disposition": "resume_ready",
"focus": "Bank the active scene-smoke packet before the lights go out.",
"summary": "Scene reflection should surface the durable investigation packet.",
"next_action": "Patch the remaining smoke coverage and rerun the focused verifier pass.",
"captured_at_turn_id": "turn-phase6-scene",
"open_questions": ["Should scene reflection compress checkpoint counts or expose full detail?"],
"code_refs": [mapper_code_ref()],
"evidence_ids": ["ev-phase6-scene-1"]
},
"subgoals": [
{
"id": "phase6-scene-smoke",
"title": "Live-smoke scene reflection",
"status": "active",
"summary": "The app-server scene surface should reflect the live typed state."
},
{
"id": "phase6-job-surface",
"title": "Design job/progress reflection",
"status": "queued",
"summary": "The next larger organ after scene smoke."
}
],
"invariants": [
{
"id": "inv-scene-read-only",
"description": "thread/epiphany/view scene lens must not mutate Epiphany state.",
"status": "ok"
},
{
"id": "inv-gui-not-source",
"description": "Scene projection may reflect state but must not become canonical understanding.",
"status": "ok"
}
],
"graphs": {
"architecture": {
"nodes": [{
"id": "scene-projection",
"title": "Scene projection",
"purpose": "Compress authoritative Epiphany state into a client-readable reflection.",
"code_refs": [mapper_code_ref()]
}]
},
"dataflow": {
"nodes": [{
"id": "typed-state",
"title": "Typed Epiphany state",
"purpose": "Remain the authoritative source behind scene reflection."
}]
},
"links": [{
"dataflow_node_id": "typed-state",
"architecture_node_id": "scene-projection",
"relationship": "derived-reflection"
}]
},
"graphFrontier": {
"active_node_ids": ["scene-projection"],
"dirty_paths": ["app-server/src/codex_message_processor.rs"]
},
"graphCheckpoint": {
"checkpoint_id": "phase6-scene-smoke",
"graph_revision": 1,
"summary": "Scene reflection is the active Phase 6 smoke target.",
"frontier_node_ids": ["scene-projection"]
},
"churn": {
"understanding_status": "ready",
"diff_pressure": "low",
"graph_freshness": "fresh",
"unexplained_writes": 0
},
"evidence": [evidence_record(1)],
"observations": [observation_record(1)]
})
}
fn assert_missing_scene(scene: &Value) -> Result<()> {
require(
scene.get("stateStatus").and_then(Value::as_str) == Some("missing"),
"initial scene should report missing state",
)?;
require(
scene.get("source").and_then(Value::as_str) == Some("live"),
"loaded missing scene should report live source",
)?;
require(
string_array_eq(
scene.get("availableActions").and_then(Value::as_array),
&[
"index",
"retrieve",
"distill",
"context",
"planning",
"graphQuery",
"jobs",
"roles",
"coordinator",
"roleLaunch",
"roleResult",
"roleAccept",
"jobLaunch",
"freshness",
"pressure",
"reorient",
"crrc",
"update",
],
),
"missing live scene should expose only bootstrap actions",
)?;
require(
scene
.pointer("/observations/totalCount")
.and_then(Value::as_u64)
== Some(0),
"missing scene should not report observations",
)?;
require(
scene
.pointer("/evidence/totalCount")
.and_then(Value::as_u64)
== Some(0),
"missing scene should not report evidence",
)
}
fn assert_ready_scene(scene: &Value, expected_revision: u64) -> Result<()> {
require(
scene.get("stateStatus").and_then(Value::as_str) == Some("ready"),
"scene should report ready state after update",
)?;
require(
scene.get("source").and_then(Value::as_str) == Some("live"),
"loaded scene should report live source",
)?;
require(
scene.get("revision").and_then(Value::as_u64) == Some(expected_revision),
"scene should expose current revision",
)?;
require(
scene
.get("objective")
.and_then(Value::as_str)
.is_some_and(|objective| {
objective.starts_with("Expose live Epiphany scene reflection")
}),
"scene should expose objective",
)?;
require(
scene.pointer("/activeSubgoal/id").and_then(Value::as_str) == Some("phase6-scene-smoke"),
"scene should expose active subgoal",
)?;
require(
scene.get("invariantStatusCounts") == Some(&json!([{"status": "ok", "count": 2}])),
"scene should summarize invariant status counts",
)?;
require(
scene
.pointer("/graph/architectureNodeCount")
.and_then(Value::as_u64)
== Some(1),
"scene should count architecture nodes",
)?;
require(
scene
.pointer("/graph/dataflowNodeCount")
.and_then(Value::as_u64)
== Some(1),
"scene should count dataflow nodes",
)?;
require(
scene.pointer("/graph/linkCount").and_then(Value::as_u64) == Some(1),
"scene should count graph links",
)?;
require(
string_array_eq(
scene
.pointer("/graph/activeNodeIds")
.and_then(Value::as_array),
&["scene-projection"],
),
"scene should expose graph frontier active nodes",
)?;
require(
scene.pointer("/graph/checkpointId").and_then(Value::as_str) == Some("phase6-scene-smoke"),
"scene should expose graph checkpoint",
)?;
require(
scene
.pointer("/investigationCheckpoint/checkpointId")
.and_then(Value::as_str)
== Some("phase6-scene-investigation"),
"scene should expose the investigation checkpoint id",
)?;
require(
scene
.pointer("/investigationCheckpoint/disposition")
.and_then(Value::as_str)
== Some("resume_ready"),
"scene should expose the checkpoint disposition",
)?;
require(
scene
.pointer("/retrieval/workspaceRoot")
.and_then(Value::as_str)
.is_some_and(|root| root.ends_with("epiphany-core")),
"scene should include live retrieval summary backfill",
)?;
require(
scene
.pointer("/observations/totalCount")
.and_then(Value::as_u64)
== Some(6),
"scene should count all observations",
)?;
require(
scene
.pointer("/evidence/totalCount")
.and_then(Value::as_u64)
== Some(6),
"scene should count all evidence",
)?;
require(
ids_eq(
scene
.pointer("/observations/latest")
.and_then(Value::as_array),
&[
"obs-phase6-scene-6",
"obs-phase6-scene-5",
"obs-phase6-scene-4",
"obs-phase6-scene-3",
"obs-phase6-scene-2",
],
),
"scene latest observations should be newest-first and bounded",
)?;
require(
ids_eq(
scene.pointer("/evidence/latest").and_then(Value::as_array),
&[
"ev-phase6-scene-6",
"ev-phase6-scene-5",
"ev-phase6-scene-4",
"ev-phase6-scene-3",
"ev-phase6-scene-2",
],
),
"scene latest evidence should be newest-first and bounded",
)?;
require(
scene.pointer("/churn/diffPressure").and_then(Value::as_str) == Some("low"),
"scene should expose churn pressure",
)?;
require(
string_array_eq(
scene.get("availableActions").and_then(Value::as_array),
&[
"index",
"retrieve",
"distill",
"context",
"planning",
"graphQuery",
"jobs",
"roles",
"coordinator",
"roleLaunch",
"roleResult",
"roleAccept",
"jobLaunch",
"freshness",
"pressure",
"reorient",
"crrc",
"reorientLaunch",
"update",
"jobInterrupt",
"propose",
"promote",
],
),
"ready live scene should expose full loaded-state actions",
)
}
fn ids(value: &Value) -> Value {
json!(
value
.as_array()
.map(|items| {
items
.iter()
.filter_map(|item| item.get("id").and_then(Value::as_str))
.collect::<Vec<_>>()
})
.unwrap_or_default()
)
}
fn ids_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.get("id").and_then(Value::as_str) == Some(*expected))
})
}
fn string_array_eq(values: Option<&Vec<Value>>, expected: &[&str]) -> bool {
values.is_some_and(|values| {
values.len() == expected.len()
&& values
.iter()
.zip(expected)
.all(|(value, expected)| value.as_str() == Some(*expected))
})
}
fn reset_smoke_paths(root: &Path, paths: &[PathBuf]) -> Result<()> {
let smoke_root = root.join(".epiphany-smoke").canonicalize().or_else(|_| {
let smoke_root = root.join(".epiphany-smoke");
fs::create_dir_all(&smoke_root)?;
smoke_root.canonicalize()
})?;
for path in paths {
if !path.exists() {
continue;
}
let resolved = path.canonicalize()?;
if resolved == smoke_root || !resolved.starts_with(&smoke_root) {
return Err(anyhow!(
"refusing to delete non-smoke path: {}",
path.display()
));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
} else {
fs::remove_file(path)?;
}
}
Ok(())
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?))?;
Ok(())
}
fn require(condition: bool, message: &str) -> Result<()> {
if condition {
Ok(())
} else {
Err(anyhow!("{message}"))
}
}
fn take_path(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
args.next()
.map(PathBuf::from)
.ok_or_else(|| anyhow!("{name} requires a value"))
}

View file

@ -206,7 +206,7 @@ mod tests {
let proposal = distill_observation(EpiphanyDistillInput {
source_kind: "smoke".to_string(),
status: "ok".to_string(),
subject: Some("thread/epiphany/update".to_string()),
subject: Some("native-state-update".to_string()),
text: " live smoke returned revision 1 ".to_string(),
code_refs: vec![EpiphanyCodeRef {
path: PathBuf::from("src/lib.rs"),
@ -229,7 +229,7 @@ mod tests {
assert_eq!(proposal.evidence.kind, "verification");
assert_eq!(
proposal.observation.summary,
"thread/epiphany/update: live smoke returned revision 1"
"native-state-update: live smoke returned revision 1"
);
assert_eq!(proposal.evidence.code_refs.len(), 1);
}

View file

@ -75,7 +75,7 @@ The current strategic north star is not local cleverness. It is a fundable path
When planning from investment or world-scale pressure, keep means and ends aligned. Capital is fuel, not a throne. Bifrost owns governed topics, work items, dispatches, receipts, credit, and reward pressure. Epiphany executes bounded work and produces reviewable artifacts. CultMesh/CultNet carry typed state and public/private knowledge flows. Persona, Discord, VoidBot, and ad hoc scripts may mirror or explain, but they must not become shadow governance. Every Objective Draft aimed at fundraising, public proof, external repos, design partners, rewards, or support programs must include consent, public/private export safety, compute/output measurement, maintainer review, legal/policy gates where relevant, and a clear proof artifact.
Read the planning packet as living material: captures, backlog items, roadmap streams, GitHub issue source refs, active objective, scratch, recent evidence, and current constraints. Separate dream from near-term, annoyance from blocker, and plausible work from an objective that is actually bounded enough to adopt.
Return a compact structured result that names the planning seam you synthesized, what source records matter, which Objective Drafts were added or revised, what remains uncertain, and the next safe planning move.
`statePatch` is part of the Imagination job. Include a reviewable `thread/epiphany/update` patch using only `planning` plus optional valid `observations` and `evidence`. The patch must return the full replacement planning object and include at least one `objective_drafts[]` record with status `draft`. Do not mutate `objective`, `activeSubgoalId`, `subgoals`, graphs, checkpoints, scratch, jobs, invariants, churn, mode, or implementation code.
`statePatch` is part of the Imagination job. Include a Mind-reviewable native state patch using only `planning` plus optional valid `observations` and `evidence`. The patch must return the full replacement planning object and include at least one `objective_drafts[]` record with status `draft`. Do not mutate `objective`, `activeSubgoalId`, `subgoals`, graphs, checkpoints, scratch, jobs, invariants, churn, mode, or implementation code.
Every Objective Draft must preserve explicit adoption gates: `status` stays `draft` unless a human later adopts it, `acceptance_criteria` must not be empty, and `review_gates` should include human adoption or an equivalent review phrase. Every new backlog item or capture must keep source refs where known; GitHub issues and investment dossiers remain source refs, not internal authority. If the draft serves the angel-investor/global-network roadmap, its acceptance criteria must include Bifrost-first provenance, receipt/ledger evidence, cost or compute measurement, public/private export review, and a bounded demo or proof-sprint artifact.
Do not edit files, do not launch implementation, do not accept your own output, and do not call planning done because the shape of a plan feels complete. The point is a future the user can inspect without being dragged into it.
'''
@ -88,7 +88,7 @@ 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.
`statePatch` is part of the modeling job. If you return `checkpoint-ready`, `checkpoint-update-needed`, or `regather-needed`, include a reviewable `thread/epiphany/update` patch using only modeling-safe fields (`graphs`, `graphFrontier`, `graphCheckpoint`, `scratch`, `investigationCheckpoint`, plus optional valid `observations` and `evidence`). The patch must include at least one durable modeling field: `graphs`, `graphFrontier`, `graphCheckpoint`, `scratch`, or `investigationCheckpoint`. Do not return an observations-only patch. Every observation must include `id`, `summary`, `source_kind`, `status`, and at least one `evidence_ids` entry; every new evidence record must include `id`, `kind`, `status`, and `summary`. For graph growth, return the full replacement graph object with the new or revised nodes/edges already woven into the current anatomy. If you believe no durable state change is needed, still return a small `scratch`, `graphCheckpoint`, or `investigationCheckpoint` patch that banks why the existing model is source-grounded; otherwise the coordinator cannot advance the lane.
`statePatch` is part of the modeling job. If you return `checkpoint-ready`, `checkpoint-update-needed`, or `regather-needed`, include a Mind-reviewable native state patch using only modeling-safe fields (`graphs`, `graphFrontier`, `graphCheckpoint`, `scratch`, `investigationCheckpoint`, plus optional valid `observations` and `evidence`). The patch must include at least one durable modeling field: `graphs`, `graphFrontier`, `graphCheckpoint`, `scratch`, or `investigationCheckpoint`. Do not return an observations-only patch. Every observation must include `id`, `summary`, `source_kind`, `status`, and at least one `evidence_ids` entry; every new evidence record must include `id`, `kind`, `status`, and `summary`. For graph growth, return the full replacement graph object with the new or revised nodes/edges already woven into the current anatomy. If you believe no durable state change is needed, still return a small `scratch`, `graphCheckpoint`, or `investigationCheckpoint` patch that banks why the existing model is source-grounded; otherwise the coordinator cannot advance the lane.
Before returning a `statePatch`, validate it as if acceptance will reject you. `graphs.architecture.nodes[].id` defines the only valid `architecture_node_id` values. `graphs.dataflow.nodes[].id` defines the only valid `dataflow_node_id` values. Every `graphs.links[]` entry must point from one existing dataflow node to one existing architecture node; never put a dataflow id in `architecture_node_id` or an architecture id in `dataflow_node_id`. If a concept needs to exist in both layers, create or reuse one node in each layer and link them explicitly. Every frontier/checkpoint node id you name must exist in the graph you return.
Do not confuse the modeling verdict with checkpoint enum values. `verdict` may be `checkpoint-ready`, but `statePatch.investigationCheckpoint.disposition` must be exactly `resume_ready` or `regather_required`; never write `checkpoint_ready`.
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.
@ -116,7 +116,7 @@ The Eyes improve themselves by seeing earlier and hallucinating less. Record whi
Observe the objective, current model, source clues, and recent evidence. Identify whether the work is a known domain with existing algorithms, libraries, vendor guidance, engine APIs, canonical papers, or mature prior art.
Search local source/docs first. Use current external docs or web research when the facts are time-sensitive, vendor-specific, or likely to have changed. Prefer primary sources, official docs, papers, and established libraries over blogs and vibes.
Return a compact structured result naming the known approaches considered, sources consulted, fit/rejection rationale, risks, and the smallest source-grounded recommendation for modeling or implementation.
`statePatch` is part of the Eyes job. Include a reviewable `thread/epiphany/update` patch using only `observations`, `evidence`, `scratch`, and optional `investigationCheckpoint`. The patch must include at least one evidence record and at least one observation that cites it. Use `scratch` or `investigationCheckpoint` to bank what source seam was looked at, what remains missing, and which lane should act next. Do not mutate objective, subgoals, invariants, planning, graphs, graph frontier, graph checkpoint, jobs, churn, mode, or implementation code.
`statePatch` is part of the Eyes job. Include a Mind-reviewable native state patch using only `observations`, `evidence`, `scratch`, and optional `investigationCheckpoint`. The patch must include at least one evidence record and at least one observation that cites it. Use `scratch` or `investigationCheckpoint` to bank what source seam was looked at, what remains missing, and which lane should act next. Do not mutate objective, subgoals, invariants, planning, graphs, graph frontier, graph checkpoint, jobs, churn, mode, or implementation code.
Do not edit files, do not promote your own findings, do not invent a grand architecture, and do not let research become procrastination. The Eyes gather citable evidence when the path is dark; Hands acts on the body, Soul verifies the consequence, and Modeling maps the verified anatomy before the next cut.
'''

View file

@ -7,20 +7,9 @@ handler itself do not count as clients.
## Living explicit compatibility clients
| Route | Executable consumer | Compatibility purpose |
|---|---|---|
| `view` | phase-6 scene/reorient/pressure/planning smokes; `epiphany-mvp-status --codex` | old aggregate read projection |
| `roleResult` | `epiphany-mvp-status --codex` | old worker-result read projection |
| `freshness` | phase-6 freshness smoke | old freshness projection |
| `context` | phase-6 context smoke | old context projection |
| `graphQuery` | phase-6 graph-query smoke | old graph projection |
| `reorientResult` | `epiphany-mvp-status --codex` | old reorientation-result projection |
| `jobInterrupt` | `epiphany-mvp-status --codex` | explicit delegated interruption fallback |
| `update` | phase-6 scene/context/freshness/graph/reorient/planning smokes | explicit delegated state-update fallback |
These are retained only while the named compatibility binaries remain. They do
not justify route-local policy, implicit triggers, Codex state ownership, or new
clients.
None. The phase-6 app-server smokes and `epiphany-mvp-status --codex` fallback
were the final clients and are deleted. MVP status and interruption now use the
native coordinator/state stores exclusively.
## Removed unconsumed routes

View file

@ -1963,6 +1963,14 @@ and TypeScript fixtures were regenerated; their two fixture-equivalence tests,
protocol/bridge compilation, and full app-server compilation pass. Next map the
real invariant behind each phase-6 smoke and `epiphany-mvp-status --codex`, then
migrate or retire those clients rather than preserving JSON-RPC for its own tests.
That cut is complete. All phase-6 app-server smokes plus the app-server MVP
status smoke are deleted; MVP status and interruption are native-only. The final
eight request methods, two notifications, dispatch/handlers, `ThreadEpiphany*`
DTO slab, generated exports, Codex thread-state projection, and legacy rollout
migration are gone. Schema fixture equivalence, full app-server compilation,
and native status interruption tests pass. `epiphany-codex-bridge` now contains
only the file-watcher invalidation manager; move that host-owned organ into
app-server and delete the bridge crate next.
## Immediate Re-entry Instruction

View file

@ -391,3 +391,13 @@ hierarchy and retrieval result/index projection shapes. Bridge-only distill,
propose, job-document, index, and retrieve conversions plus the entire
`retrieve_protocol` module are deleted. Regenerated JSON/TypeScript fixtures
contain none of those types; their in-memory fixture comparison passes.
The final eight-route compatibility surface is gone too. Seven phase-6
app-server smoke binaries and the app-server-backed MVP status smoke were
deleted; `epiphany-mvp-status` has one native status/interruption path and no
Codex transport client. App-server request/notification registrations,
dispatch, route modules, all `ThreadEpiphany*` DTOs, generated exports, generic
Codex `Thread.epiphanyState`, and legacy rollout-state migration are deleted.
`codex-app-server-protocol` no longer depends on `epiphany-state-model`.
`epiphany-codex-bridge` has collapsed to its only living consumer surface: the
Codex-hosted file-watcher invalidation manager.

Binary file not shown.

View file

@ -659,4 +659,4 @@ current_status:
- Service lifecycle receipt history is now event-only: `load_epiphany_cultmesh_daemon_service_lifecycle_receipts` filters out the `epiphany-local/daemon-service-lifecycle-receipt/latest` mirror, while `load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt` remains the latest-state reader. Focused unit test `service_lifecycle_receipt_history_excludes_latest_mirror` proves two per-receipt writes return exactly two history records and latest points at the second. Fresh smoke `verse-query-lifecycle-history-filter-smoke` and live overview/triage `local-20260618-145632-497-efac6f0d` / `local-20260618-145632-321-867947af` prove compact swarm sights still expose service lifecycle attention plus the present elevated runbook artifact without daemon pokes or service mutation. Do not use a broad unscoped cargo test filter for this check on Windows; it fans out across bin harnesses and hit a broken pipe during this pass.
- `epiphany-verse-query seed-compact` is the compact seed receipt for wrappers and read-only rites. The older `seed` command still prints the full local Verse context for explicit debugging, but compact wrapper modes now avoid full `seed`/final `query` readback after the combined overview proof exposed Windows debug stack overflow from full-context serialization pressure.
last_completed_repo_swarm_cut: Huginn live-fire has crossed the first real repo Body from Persona pressure to branch-local Hands commit and Soul/Mind closure, and now has repeatable closure and redacted-public-proof mouths. On `E:\Projects\Huginn` branch `epiphany/huginn/first-awakening`, `tools/epiphany_local_run.ps1 -Mode repo-persona-intake` accepted item `huginn-inspection-readback-livefire`, Weksa/Persona intake remained sealed, and `epiphany-work derive-plan` lowered it to model-authored safe family `repo.status_section` for `README.md` only. `tools/epiphany_local_run.ps1 -Mode repo-swarm-run` advanced four bounded pulses: run-from-plan, adopt-from-plan, execute-from-plan, and close-from-execute. Huginn commit `e9b07c38fceabbdc89ea35c2156326c80c0393a2` updated only `README.md`; closure receipt `.epiphany\work\work-close-huginn-inspection-readback-livefire.json` records status `closed`, Soul verdict `passed`, Mind state commit `repo-work-close-huginn-inspection-readback-livefire-mind-commit`, safe family `repo.status_section`, path scope `README.md`, Bifrost publication gate, and `privateStateExposed=false`. Verification also ran Huginn's TypeScript compiler through concrete Node path: `C:\Program Files\nodejs\node.exe E:\Projects\Huginn\node_modules\typescript\bin\tsc -p tsconfig.json` passed. Native verifier `epiphany-repo-livefire-closure-smoke --workspace E:\Projects\Huginn --item huginn-inspection-readback-livefire --expected-path README.md --expected-family repo.status_section --expected-gate awaiting-publication --expected-blocker bifrost-publication-missing` checks closure receipt, Mind map entry, overview gate/blocker, authority seals, and `git show` changed paths, returning `status=ok`, `soulVerdict=passed`, `publicationGate=Bifrost`, and `privateStateExposed=false`. Wrapper `tools/epiphany_local_run.ps1 -Mode repo-livefire-closure -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exposes the same read-only proof through the local operator mouth; artifact `local-20260621-190156-803-2f85ba15` printed commit, path, gate, blocker, Soul verdict, Mind commit receipt, and `privateStateExposed=False` without push, merge, publication, or target mutation. New wrapper `tools/epiphany_local_run.ps1 -Mode repo-work-public-proof -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exports the redacted proof bundle and repo-local Verse index without publishing; artifact `local-20260621-190645-345-4555b1dc` wrote `.epiphany\public\proof-bundles\repo-work-public-proof-huginn-inspection-readback-livefire.json`, proof id `repo-work-public-proof-huginn-inspection-readback-livefire`, SHA-256 `857545b199f3e37eb06c2e757e5cfc201958e46667bb1f8403fd333a22620f63`, nine artifact rows, zero publication rows, and `privateStateExposed=False`. Gjallar readback `local-20260621-190701-140-b9519ec6` sees the `REPO-WORK-PUBLIC-PROOF` row and action row from Huginn's repo-local Verse with the same SHA-256 while Bifrost publication remains missing. Launcher compact modes are now named compact operator-context modes instead of read-only modes, and `bifrost-public-proof` summaries print item, target public Verse, room, proof SHA-256, review receipts, and credit receipts so publication receipts are auditable without claiming upstream sync.
next_action: Migrate or retire the phase-6 smoke binaries and `epiphany-mvp-status --codex` fallback that are the only clients of the eight remaining Epiphany app-server methods. Map each smoke's real invariant to an existing native core/bridge test or native executable proof before deletion; do not preserve JSON-RPC merely to keep compatibility tests alive.
next_action: Move the sole surviving `epiphany-codex-bridge` organ, `EpiphanyInvalidationManager`, into the Codex app-server watcher lifecycle that owns it; then delete the bridge crate and dependency entirely. Update whitepaper/anatomy prose that still describes a general Codex translation layer. After that, audit native coordinator status for stale `/read/thread/epiphanyState` compatibility pointers.

769
vendor/codex/codex-rs/Cargo.lock generated vendored

File diff suppressed because it is too large Load diff

View file

@ -12,7 +12,6 @@ path = "src/lib.rs"
workspace = true
[dependencies]
epiphany-state-model = { path = "../../../../epiphany-state-model" }
anyhow = { workspace = true }
clap = { workspace = true, features = ["derive"] }
codex-experimental-api-macros = { workspace = true }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,160 +0,0 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"ThreadEpiphanyJob": {
"properties": {
"activeThreadIds": {
"items": {
"type": "string"
},
"type": "array"
},
"authorityScope": {
"type": [
"string",
"null"
]
},
"backendJobId": {
"type": [
"string",
"null"
]
},
"blockingReason": {
"type": [
"string",
"null"
]
},
"id": {
"type": "string"
},
"itemsProcessed": {
"format": "uint32",
"minimum": 0.0,
"type": [
"integer",
"null"
]
},
"itemsTotal": {
"format": "uint32",
"minimum": 0.0,
"type": [
"integer",
"null"
]
},
"kind": {
"$ref": "#/definitions/ThreadEpiphanyJobKind"
},
"lastCheckpointAtUnixSeconds": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"launcherJobId": {
"type": [
"string",
"null"
]
},
"linkedGraphNodeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"linkedSubgoalIds": {
"items": {
"type": "string"
},
"type": "array"
},
"ownerRole": {
"type": "string"
},
"progressNote": {
"type": [
"string",
"null"
]
},
"scope": {
"type": "string"
},
"status": {
"$ref": "#/definitions/ThreadEpiphanyJobStatus"
}
},
"required": [
"id",
"kind",
"ownerRole",
"scope",
"status"
],
"type": "object"
},
"ThreadEpiphanyJobKind": {
"enum": [
"indexing",
"remap",
"verification",
"specialist"
],
"type": "string"
},
"ThreadEpiphanyJobStatus": {
"enum": [
"idle",
"needed",
"pending",
"running",
"completed",
"failed",
"cancelled",
"blocked",
"unavailable"
],
"type": "string"
},
"ThreadEpiphanyJobsUpdatedSource": {
"enum": [
"runtimeProgress"
],
"type": "string"
}
},
"properties": {
"jobs": {
"items": {
"$ref": "#/definitions/ThreadEpiphanyJob"
},
"type": "array"
},
"source": {
"$ref": "#/definitions/ThreadEpiphanyJobsUpdatedSource"
},
"stateRevision": {
"format": "uint64",
"minimum": 0.0,
"type": [
"integer",
"null"
]
},
"threadId": {
"type": "string"
}
},
"required": [
"source",
"threadId"
],
"title": "ThreadEpiphanyJobsUpdatedNotification",
"type": "object"
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyAcceptanceReceipt = { id: string, result_id: string, job_id: string, binding_id: string, surface: string, role_id: string, status: string, accepted_at: string, accepted_observation_id?: string | null, accepted_evidence_id?: string | null, summary?: string | null, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyChurnState = { understanding_status: string, diff_pressure: string, graph_freshness?: string | null, warning?: string | null, unexplained_writes?: number | null, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyCodeRef = { path: string, start_line?: number | null, end_line?: number | null, symbol?: string | null, note?: string | null, };

View file

@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyCodeRef } from "./EpiphanyCodeRef";
export type EpiphanyEvidenceRecord = { id: string, kind: string, status: string, summary: string, code_refs?: Array<EpiphanyCodeRef>, };

View file

@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyGraphEdge } from "./EpiphanyGraphEdge";
import type { EpiphanyGraphNode } from "./EpiphanyGraphNode";
export type EpiphanyGraph = { nodes?: Array<EpiphanyGraphNode>, edges?: Array<EpiphanyGraphEdge>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyGraphCheckpoint = { checkpoint_id: string, graph_revision: bigint, summary?: string | null, frontier_node_ids?: Array<string>, open_question_ids?: Array<string>, open_gap_ids?: Array<string>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyGraphEdge = { source_id: string, target_id: string, kind: string, id?: string | null, label?: string | null, mechanism?: string | null, code_refs?: Array<EpiphanyCodeRef>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyGraphFrontier = { active_node_ids?: Array<string>, active_edge_ids?: Array<string>, open_question_ids?: Array<string>, open_gap_ids?: Array<string>, dirty_paths?: Array<string>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyGraphLink = { dataflow_node_id: string, architecture_node_id: string, relationship?: string | null, code_refs?: Array<EpiphanyCodeRef>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyGraphNode = { id: string, title: string, purpose: string, mechanism?: string | null, metaphor?: string | null, status?: string | null, code_refs?: Array<EpiphanyCodeRef>, };

View file

@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyGraph } from "./EpiphanyGraph";
import type { EpiphanyGraphLink } from "./EpiphanyGraphLink";
export type EpiphanyGraphs = { architecture?: EpiphanyGraph, dataflow?: EpiphanyGraph, links?: Array<EpiphanyGraphLink>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyInvariant = { id: string, description: string, status: string, rationale?: string | null, };

View file

@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyInvestigationDisposition } from "./EpiphanyInvestigationDisposition";
export type EpiphanyInvestigationCheckpoint = { checkpoint_id: string, kind: string, disposition: EpiphanyInvestigationDisposition, focus: string, summary?: string | null, next_action?: string | null, captured_at_turn_id?: string | null, open_questions?: Array<string>, code_refs?: Array<EpiphanyCodeRef>, evidence_ids?: Array<string>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyInvestigationDisposition = "resume_ready" | "regather_required";

View file

@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyJobKind } from "./EpiphanyJobKind";
export type EpiphanyJobBinding = { id: string, kind: EpiphanyJobKind, scope: string, owner_role: string, authority_scope?: string | null, linked_subgoal_ids?: Array<string>, linked_graph_node_ids?: Array<string>, blocking_reason?: string | null, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyJobKind = "indexing" | "remap" | "verification" | "specialist";

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyModeState = { name: string, kind?: ModeKind | null, };

View file

@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyCodeRef } from "./EpiphanyCodeRef";
export type EpiphanyObservation = { id: string, summary: string, source_kind: string, status: string, code_refs?: Array<EpiphanyCodeRef>, evidence_ids?: Array<string>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyPlanningState = { workspace_root?: string | null, captures?: Array<EpiphanyPlanningCapture>, backlog_items?: Array<EpiphanyBacklogItem>, roadmap_streams?: Array<EpiphanyRoadmapStream>, objective_drafts?: Array<EpiphanyObjectiveDraft>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyRetrievalStatus = "unavailable" | "ready" | "stale" | "indexing";

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyRuntimeLink = { id: string, binding_id: string, surface: string, role_id: string, authority_scope: string, runtime_job_id: string, runtime_result_id?: string | null, linked_subgoal_ids?: Array<string>, linked_graph_node_ids?: Array<string>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyScratchPad = { summary?: string | null, hypothesis?: string | null, next_probe?: string | null, notes?: Array<string>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanySubgoal = { id: string, title: string, status: string, summary?: string | null, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type EpiphanyThreadState = { revision: bigint, objective?: string | null, active_subgoal_id?: string | null, subgoals?: Array<EpiphanySubgoal>, invariants?: Array<EpiphanyInvariant>, graphs?: EpiphanyGraphs, graph_frontier?: EpiphanyGraphFrontier | null, graph_checkpoint?: EpiphanyGraphCheckpoint | null, retrieval?: EpiphanyRetrievalState | null, scratch?: EpiphanyScratchPad | null, investigation_checkpoint?: EpiphanyInvestigationCheckpoint | null, job_bindings?: Array<EpiphanyJobBinding>, acceptance_receipts?: Array<EpiphanyAcceptanceReceipt>, runtime_links?: Array<EpiphanyRuntimeLink>, observations?: Array<EpiphanyObservation>, recent_evidence?: Array<EpiphanyEvidenceRecord>, churn?: EpiphanyChurnState | null, mode?: EpiphanyModeState | null, planning?: EpiphanyPlanningState, last_updated_turn_id?: string | null, };

View file

@ -36,8 +36,6 @@ import type { ServerRequestResolvedNotification } from "./v2/ServerRequestResolv
import type { TerminalInteractionNotification } from "./v2/TerminalInteractionNotification";
import type { ThreadArchivedNotification } from "./v2/ThreadArchivedNotification";
import type { ThreadClosedNotification } from "./v2/ThreadClosedNotification";
import type { ThreadEpiphanyJobsUpdatedNotification } from "./v2/ThreadEpiphanyJobsUpdatedNotification";
import type { ThreadEpiphanyStateUpdatedNotification } from "./v2/ThreadEpiphanyStateUpdatedNotification";
import type { ThreadNameUpdatedNotification } from "./v2/ThreadNameUpdatedNotification";
import type { ThreadRealtimeClosedNotification } from "./v2/ThreadRealtimeClosedNotification";
import type { ThreadRealtimeErrorNotification } from "./v2/ThreadRealtimeErrorNotification";
@ -62,4 +60,4 @@ import type { WindowsWorldWritableWarningNotification } from "./v2/WindowsWorldW
/**
* Notification sent from the server to the client.
*/
export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/fileChange/patchUpdated", "params": FileChangePatchUpdatedNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "guardianWarning", "params": GuardianWarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "thread/epiphany/stateUpdated", "params": ThreadEpiphanyStateUpdatedNotification } | { "method": "thread/epiphany/jobsUpdated", "params": ThreadEpiphanyJobsUpdatedNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification };
export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/fileChange/patchUpdated", "params": FileChangePatchUpdatedNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "guardianWarning", "params": GuardianWarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification };

View file

@ -12,30 +12,6 @@ export type { CollaborationMode } from "./CollaborationMode";
export type { ContentItem } from "./ContentItem";
export type { ConversationGitInfo } from "./ConversationGitInfo";
export type { ConversationSummary } from "./ConversationSummary";
export type { EpiphanyAcceptanceReceipt } from "./EpiphanyAcceptanceReceipt";
export type { EpiphanyChurnState } from "./EpiphanyChurnState";
export type { EpiphanyCodeRef } from "./EpiphanyCodeRef";
export type { EpiphanyEvidenceRecord } from "./EpiphanyEvidenceRecord";
export type { EpiphanyGraph } from "./EpiphanyGraph";
export type { EpiphanyGraphCheckpoint } from "./EpiphanyGraphCheckpoint";
export type { EpiphanyGraphEdge } from "./EpiphanyGraphEdge";
export type { EpiphanyGraphFrontier } from "./EpiphanyGraphFrontier";
export type { EpiphanyGraphLink } from "./EpiphanyGraphLink";
export type { EpiphanyGraphNode } from "./EpiphanyGraphNode";
export type { EpiphanyGraphs } from "./EpiphanyGraphs";
export type { EpiphanyInvariant } from "./EpiphanyInvariant";
export type { EpiphanyInvestigationCheckpoint } from "./EpiphanyInvestigationCheckpoint";
export type { EpiphanyInvestigationDisposition } from "./EpiphanyInvestigationDisposition";
export type { EpiphanyJobBinding } from "./EpiphanyJobBinding";
export type { EpiphanyJobKind } from "./EpiphanyJobKind";
export type { EpiphanyModeState } from "./EpiphanyModeState";
export type { EpiphanyObservation } from "./EpiphanyObservation";
export type { EpiphanyPlanningState } from "./EpiphanyPlanningState";
export type { EpiphanyRetrievalStatus } from "./EpiphanyRetrievalStatus";
export type { EpiphanyRuntimeLink } from "./EpiphanyRuntimeLink";
export type { EpiphanyScratchPad } from "./EpiphanyScratchPad";
export type { EpiphanySubgoal } from "./EpiphanySubgoal";
export type { EpiphanyThreadState } from "./EpiphanyThreadState";
export type { ExecCommandApprovalParams } from "./ExecCommandApprovalParams";
export type { ExecCommandApprovalResponse } from "./ExecCommandApprovalResponse";
export type { ExecPolicyAmendment } from "./ExecPolicyAmendment";

View file

@ -2,7 +2,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
import type { EpiphanyThreadState } from "../EpiphanyThreadState";
import type { GitInfo } from "./GitInfo";
import type { SessionSource } from "./SessionSource";
import type { ThreadStatus } from "./ThreadStatus";
@ -69,11 +68,6 @@ gitInfo: GitInfo | null,
* Optional user-facing thread title.
*/
name: string | null,
/**
* Only populated on `thread/start`, `thread/resume`, `thread/fork`, `thread/read`,
* and notifications/responses that reuse those hydrated thread payloads.
*/
epiphanyState?: EpiphanyThreadState,
/**
* Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read`
* (when `includeTurns` is true) responses.

View file

@ -1,11 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyEvidenceRecord } from "../EpiphanyEvidenceRecord";
import type { EpiphanyGraphCheckpoint } from "../EpiphanyGraphCheckpoint";
import type { EpiphanyGraphFrontier } from "../EpiphanyGraphFrontier";
import type { EpiphanyInvestigationCheckpoint } from "../EpiphanyInvestigationCheckpoint";
import type { EpiphanyObservation } from "../EpiphanyObservation";
import type { ThreadEpiphanyGraphContext } from "./ThreadEpiphanyGraphContext";
export type ThreadEpiphanyContext = { graph: ThreadEpiphanyGraphContext, frontier?: EpiphanyGraphFrontier | null, checkpoint?: EpiphanyGraphCheckpoint | null, investigationCheckpoint?: EpiphanyInvestigationCheckpoint | null, observations?: Array<EpiphanyObservation>, evidence?: Array<EpiphanyEvidenceRecord>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyContextMissing = { graphNodeIds?: Array<string>, graphEdgeIds?: Array<string>, observationIds?: Array<string>, evidenceIds?: Array<string>, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyContextSource = "stored" | "live";

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyContextStateStatus = "missing" | "ready";

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyCoordinatorAction = "prepareCheckpoint" | "compactRehydrateReorient" | "launchReorientWorker" | "waitForReorientWorker" | "reviewReorientResult" | "regatherManually" | "launchResearch" | "reviewResearchResult" | "launchModeling" | "reviewModelingResult" | "launchVerification" | "reviewVerificationResult" | "continueImplementation";

View file

@ -1,10 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ThreadEpiphanyCrrcAction } from "./ThreadEpiphanyCrrcAction";
import type { ThreadEpiphanyPressureLevel } from "./ThreadEpiphanyPressureLevel";
import type { ThreadEpiphanyReorientAction } from "./ThreadEpiphanyReorientAction";
import type { ThreadEpiphanyReorientResultStatus } from "./ThreadEpiphanyReorientResultStatus";
import type { ThreadEpiphanyRoleResultStatus } from "./ThreadEpiphanyRoleResultStatus";
export type ThreadEpiphanyCoordinatorSignals = { pressureLevel: ThreadEpiphanyPressureLevel, shouldPrepareCompaction: boolean, reorientAction: ThreadEpiphanyReorientAction, crrcAction: ThreadEpiphanyCrrcAction, researchResultStatus: ThreadEpiphanyRoleResultStatus, modelingResultStatus: ThreadEpiphanyRoleResultStatus, verificationResultStatus: ThreadEpiphanyRoleResultStatus, reorientResultStatus: ThreadEpiphanyReorientResultStatus, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyCrrcAction = "continue" | "prepareCheckpoint" | "launchReorientWorker" | "waitForReorientWorker" | "reviewReorientResult" | "acceptReorientResult" | "regatherManually";

View file

@ -1,7 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ThreadEpiphanyCrrcAction } from "./ThreadEpiphanyCrrcAction";
import type { ThreadEpiphanySceneAction } from "./ThreadEpiphanySceneAction";
export type ThreadEpiphanyCrrcRecommendation = { action: ThreadEpiphanyCrrcAction, recommendedSceneAction?: ThreadEpiphanySceneAction | null, reason: string, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyFreshnessSource = "stored" | "live";

View file

@ -1,8 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { EpiphanyGraphEdge } from "../EpiphanyGraphEdge";
import type { EpiphanyGraphLink } from "../EpiphanyGraphLink";
import type { EpiphanyGraphNode } from "../EpiphanyGraphNode";
export type ThreadEpiphanyGraphContext = { architectureNodes?: Array<EpiphanyGraphNode>, architectureEdges?: Array<EpiphanyGraphEdge>, dataflowNodes?: Array<EpiphanyGraphNode>, dataflowEdges?: Array<EpiphanyGraphEdge>, links?: Array<EpiphanyGraphLink>, };

View file

@ -1,6 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ThreadEpiphanyGraphFreshnessStatus } from "./ThreadEpiphanyGraphFreshnessStatus";
export type ThreadEpiphanyGraphFreshness = { status: ThreadEpiphanyGraphFreshnessStatus, graphFreshness?: string | null, checkpointId?: string | null, dirtyPathCount: number, dirtyPaths?: Array<string>, openQuestionCount: number, openGapCount: number, note: string, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyGraphFreshnessStatus = "missing" | "ready" | "stale";

View file

@ -1,19 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ThreadEpiphanyGraphQueryDirection } from "./ThreadEpiphanyGraphQueryDirection";
import type { ThreadEpiphanyGraphQueryKind } from "./ThreadEpiphanyGraphQueryKind";
export type ThreadEpiphanyGraphQuery = { kind: ThreadEpiphanyGraphQueryKind, nodeIds?: Array<string>, edgeIds?: Array<string>, paths?: Array<string>, symbols?: Array<string>, edgeKinds?: Array<string>,
/**
* Defaults to `both`.
*/
direction?: ThreadEpiphanyGraphQueryDirection | null,
/**
* Defaults to 1 and is capped by the server.
*/
depth?: number | null,
/**
* Defaults to true so neighborhood queries preserve dataflow/architecture joins.
*/
includeLinks?: boolean | null, };

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyGraphQueryDirection = "incoming" | "outgoing" | "both";

View file

@ -1,5 +0,0 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanyGraphQueryKind = "node" | "path" | "frontierNeighborhood" | "neighbors";

Some files were not shown because too many files have changed in this diff Show more