Remove global thread state model

This commit is contained in:
Meta Vens 2026-08-18 04:51:18 +02:00
commit ec1431fff8
23 changed files with 139 additions and 4547 deletions

View file

@ -1,638 +0,0 @@
use epiphany_state_model::EpiphanyRetrievalState;
use epiphany_state_model::EpiphanyRetrievalStatus;
use epiphany_state_model::EpiphanyThreadState;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EpiphanyRetrievalFreshnessStatus {
Missing,
Ready,
Stale,
Indexing,
Unavailable,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EpiphanyRetrievalFreshness {
pub status: EpiphanyRetrievalFreshnessStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub semantic_available: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_indexed_at_unix_seconds: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub indexed_file_count: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub indexed_chunk_count: Option<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dirty_paths: Vec<PathBuf>,
pub note: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EpiphanyGraphFreshnessStatus {
Missing,
Stale,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EpiphanyGraphFreshness {
pub status: EpiphanyGraphFreshnessStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub checkpoint_id: Option<String>,
pub dirty_path_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dirty_paths: Vec<PathBuf>,
pub open_question_count: u32,
pub open_gap_count: u32,
pub note: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EpiphanyInvalidationStatus {
Unavailable,
Clean,
Changed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EpiphanyInvalidationInput {
pub status: EpiphanyInvalidationStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub watched_root: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub observed_at_unix_seconds: Option<i64>,
pub changed_path_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub changed_paths: Vec<PathBuf>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_node_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub active_frontier_node_ids: Vec<String>,
pub note: String,
}
#[derive(Debug, Clone, Copy)]
pub struct EpiphanyFreshnessWatcherInput<'a> {
pub available: bool,
pub workspace_root: Option<&'a Path>,
pub observed_at_unix_seconds: Option<i64>,
pub changed_paths: &'a [PathBuf],
}
#[derive(Debug, Clone, Copy)]
pub struct EpiphanyFreshnessInput<'a> {
pub state: Option<&'a EpiphanyThreadState>,
pub retrieval_override: Option<&'a EpiphanyRetrievalState>,
pub watcher: Option<EpiphanyFreshnessWatcherInput<'a>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EpiphanyFreshnessView {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state_revision: Option<u64>,
pub retrieval: EpiphanyRetrievalFreshness,
pub graph: EpiphanyGraphFreshness,
pub watcher: EpiphanyInvalidationInput,
}
pub fn derive_freshness(input: EpiphanyFreshnessInput<'_>) -> EpiphanyFreshnessView {
let retrieval = retrieval_state_for_reflection(input.state, input.retrieval_override);
EpiphanyFreshnessView {
state_revision: input.state.map(|state| state.revision),
retrieval: retrieval_freshness(retrieval),
graph: graph_freshness(input.state),
watcher: invalidation_input(input.state, input.watcher),
}
}
fn retrieval_state_for_reflection<'a>(
state: Option<&'a EpiphanyThreadState>,
retrieval_override: Option<&'a EpiphanyRetrievalState>,
) -> Option<&'a EpiphanyRetrievalState> {
retrieval_override.or_else(|| state.and_then(|state| state.retrieval.as_ref()))
}
fn retrieval_freshness(retrieval: Option<&EpiphanyRetrievalState>) -> EpiphanyRetrievalFreshness {
let Some(retrieval) = retrieval else {
return EpiphanyRetrievalFreshness {
status: EpiphanyRetrievalFreshnessStatus::Missing,
semantic_available: None,
last_indexed_at_unix_seconds: None,
indexed_file_count: None,
indexed_chunk_count: None,
dirty_paths: Vec::new(),
note: "No retrieval freshness is available for this thread view.".to_string(),
};
};
let dirty_path_count = retrieval.dirty_paths.len();
let note = match retrieval.status {
EpiphanyRetrievalStatus::Ready if dirty_path_count == 0 => {
"Legacy retrieval reports Ready, but has no Body-bound coverage receipt.".to_string()
}
EpiphanyRetrievalStatus::Ready => {
format!("Retrieval catalog is stale because {dirty_path_count} dirty path(s) remain.")
}
EpiphanyRetrievalStatus::Stale => {
format!("Retrieval catalog is stale; {dirty_path_count} dirty path(s) need refresh.")
}
EpiphanyRetrievalStatus::Indexing => "Retrieval catalog is indexing.".to_string(),
EpiphanyRetrievalStatus::Unavailable => "Retrieval catalog is unavailable.".to_string(),
};
EpiphanyRetrievalFreshness {
status: match retrieval.status {
EpiphanyRetrievalStatus::Ready if dirty_path_count == 0 => {
EpiphanyRetrievalFreshnessStatus::Missing
}
EpiphanyRetrievalStatus::Ready => EpiphanyRetrievalFreshnessStatus::Stale,
EpiphanyRetrievalStatus::Stale => EpiphanyRetrievalFreshnessStatus::Stale,
EpiphanyRetrievalStatus::Indexing => EpiphanyRetrievalFreshnessStatus::Indexing,
EpiphanyRetrievalStatus::Unavailable => EpiphanyRetrievalFreshnessStatus::Unavailable,
},
semantic_available: Some(retrieval.semantic_available),
last_indexed_at_unix_seconds: retrieval.last_indexed_at_unix_seconds,
indexed_file_count: retrieval.indexed_file_count,
indexed_chunk_count: retrieval.indexed_chunk_count,
dirty_paths: retrieval.dirty_paths.clone(),
note,
}
}
pub(super) fn graph_freshness(state: Option<&EpiphanyThreadState>) -> EpiphanyGraphFreshness {
let Some(state) = state else {
return EpiphanyGraphFreshness {
status: EpiphanyGraphFreshnessStatus::Missing,
checkpoint_id: None,
dirty_path_count: 0,
dirty_paths: Vec::new(),
open_question_count: 0,
open_gap_count: 0,
note: "Epiphany state is missing, so graph freshness cannot be assessed.".to_string(),
};
};
let frontier = state.graph_frontier.as_ref();
let dirty_paths = frontier
.map(|frontier| frontier.dirty_paths.clone())
.unwrap_or_default();
let dirty_path_count = dirty_paths.len() as u32;
let open_question_count = frontier
.map(|frontier| frontier.open_question_ids.len() as u32)
.unwrap_or_default();
let open_gap_count = frontier
.map(|frontier| frontier.open_gap_ids.len() as u32)
.unwrap_or_default();
let has_pressure = dirty_path_count > 0 || open_question_count > 0 || open_gap_count > 0;
let checkpoint_id = state
.graph_checkpoint
.as_ref()
.map(|checkpoint| checkpoint.checkpoint_id.clone());
let status = if has_pressure {
EpiphanyGraphFreshnessStatus::Stale
} else {
EpiphanyGraphFreshnessStatus::Missing
};
let note = if status == EpiphanyGraphFreshnessStatus::Stale {
format!(
"Graph freshness is stale; frontier has {dirty_path_count} dirty path(s), {open_question_count} open question id(s), and {open_gap_count} open gap id(s)."
)
} else {
"Canonical RepoModel admission freshness is not available to this legacy thread projection; legacy checkpoint and churn hints cannot prove readiness."
.to_string()
};
EpiphanyGraphFreshness {
status,
checkpoint_id,
dirty_path_count,
dirty_paths,
open_question_count,
open_gap_count,
note,
}
}
fn invalidation_input(
state: Option<&EpiphanyThreadState>,
watcher: Option<EpiphanyFreshnessWatcherInput<'_>>,
) -> EpiphanyInvalidationInput {
let Some(watcher) = watcher else {
return EpiphanyInvalidationInput {
status: EpiphanyInvalidationStatus::Unavailable,
watched_root: None,
observed_at_unix_seconds: None,
changed_path_count: 0,
changed_paths: Vec::new(),
graph_node_ids: Vec::new(),
active_frontier_node_ids: Vec::new(),
note: "Watcher-backed invalidation inputs are only available for loaded threads."
.to_string(),
};
};
if !watcher.available {
return EpiphanyInvalidationInput {
status: EpiphanyInvalidationStatus::Unavailable,
watched_root: None,
observed_at_unix_seconds: None,
changed_path_count: 0,
changed_paths: Vec::new(),
graph_node_ids: Vec::new(),
active_frontier_node_ids: Vec::new(),
note: "The workspace watcher is unavailable for this app-server process.".to_string(),
};
}
let changed_paths = watcher.changed_paths.to_vec();
let changed_path_count = changed_paths.len() as u32;
let watched_root = watcher.workspace_root.map(Path::to_path_buf);
if changed_paths.is_empty() {
return EpiphanyInvalidationInput {
status: EpiphanyInvalidationStatus::Unavailable,
watched_root,
observed_at_unix_seconds: watcher.observed_at_unix_seconds,
changed_path_count,
changed_paths,
graph_node_ids: Vec::new(),
active_frontier_node_ids: Vec::new(),
note: "Watcher supplied no observation; absence of changed paths is not proof of a clean workspace."
.to_string(),
};
}
let graph_node_ids = state
.map(|state| {
graph_node_ids_for_changed_paths(state, &changed_paths, watcher.workspace_root)
})
.unwrap_or_default();
let active_frontier_node_ids = state
.map(|state| {
active_frontier_node_ids_for_changed_paths(
state,
&changed_paths,
watcher.workspace_root,
)
})
.unwrap_or_default();
let note = if graph_node_ids.is_empty() {
format!(
"Watcher observed {changed_path_count} recent changed path(s), but no mapped graph node code refs matched yet."
)
} else if active_frontier_node_ids.is_empty() {
format!(
"Watcher observed {changed_path_count} recent changed path(s) touching {} mapped graph node(s).",
graph_node_ids.len()
)
} else {
format!(
"Watcher observed {changed_path_count} recent changed path(s) touching {} mapped graph node(s), including {} active frontier node(s).",
graph_node_ids.len(),
active_frontier_node_ids.len()
)
};
EpiphanyInvalidationInput {
status: EpiphanyInvalidationStatus::Changed,
watched_root,
observed_at_unix_seconds: watcher.observed_at_unix_seconds,
changed_path_count,
changed_paths,
graph_node_ids,
active_frontier_node_ids,
note,
}
}
fn graph_node_ids_for_changed_paths(
state: &EpiphanyThreadState,
changed_paths: &[PathBuf],
workspace_root: Option<&Path>,
) -> Vec<String> {
let changed_path_keys: HashSet<String> = changed_paths
.iter()
.map(|path| epiphany_path_key(path.as_path()))
.collect();
let mut node_ids = Vec::new();
let mut seen = HashSet::new();
for node in state
.graphs
.architecture
.nodes
.iter()
.chain(state.graphs.dataflow.nodes.iter())
{
let matches_changed_path = node.code_refs.iter().any(|code_ref| {
changed_path_keys.contains(&code_ref_path_key(
Path::new(&code_ref.path),
workspace_root,
))
});
if matches_changed_path && seen.insert(node.id.as_str()) {
node_ids.push(node.id.clone());
}
}
node_ids
}
fn active_frontier_node_ids_for_changed_paths(
state: &EpiphanyThreadState,
changed_paths: &[PathBuf],
workspace_root: Option<&Path>,
) -> Vec<String> {
let graph_node_ids = graph_node_ids_for_changed_paths(state, changed_paths, workspace_root);
let frontier_node_ids = state
.graph_frontier
.as_ref()
.map(|frontier| frontier.active_node_ids.as_slice())
.unwrap_or_default();
let graph_node_ids: HashSet<&str> = graph_node_ids.iter().map(String::as_str).collect();
frontier_node_ids
.iter()
.filter(|node_id| graph_node_ids.contains(node_id.as_str()))
.cloned()
.collect()
}
fn code_ref_path_key(path: &Path, workspace_root: Option<&Path>) -> String {
if let Some(workspace_root) = workspace_root
&& let Ok(relative_path) = path.strip_prefix(workspace_root)
{
return epiphany_path_key(relative_path);
}
epiphany_path_key(path)
}
fn epiphany_path_key(path: &Path) -> String {
path.to_string_lossy()
.replace('\\', "/")
.trim_start_matches("./")
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use epiphany_state_model::EpiphanyCodeRef;
use epiphany_state_model::EpiphanyGraphCheckpoint;
use epiphany_state_model::EpiphanyGraphFrontier;
use epiphany_state_model::EpiphanyGraphNode;
use epiphany_state_model::EpiphanyGraphs;
#[test]
fn missing_state_reports_missing_freshness() {
let view = derive_freshness(EpiphanyFreshnessInput {
state: None,
retrieval_override: None,
watcher: None,
});
assert_eq!(view.state_revision, None);
assert_eq!(
view.retrieval.status,
EpiphanyRetrievalFreshnessStatus::Missing
);
assert_eq!(view.graph.status, EpiphanyGraphFreshnessStatus::Missing);
assert_eq!(view.watcher.status, EpiphanyInvalidationStatus::Unavailable);
}
#[test]
fn default_state_is_not_graph_ready() {
let state = EpiphanyThreadState::default();
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&state),
retrieval_override: None,
watcher: None,
});
assert_eq!(view.graph.status, EpiphanyGraphFreshnessStatus::Missing);
}
#[test]
fn legacy_checkpoint_cannot_authorize_graph_ready() {
let state = EpiphanyThreadState {
graph_checkpoint: Some(EpiphanyGraphCheckpoint {
checkpoint_id: "graph-1".to_string(),
..Default::default()
}),
..Default::default()
};
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&state),
retrieval_override: None,
watcher: None,
});
assert_eq!(view.graph.status, EpiphanyGraphFreshnessStatus::Missing);
assert!(view.graph.note.contains("Canonical RepoModel admission"));
}
#[test]
fn legacy_checkpoint_alone_is_missing() {
let checkpoint_only = EpiphanyThreadState {
graph_checkpoint: Some(EpiphanyGraphCheckpoint {
checkpoint_id: "graph-1".to_string(),
..Default::default()
}),
..Default::default()
};
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&checkpoint_only),
retrieval_override: None,
watcher: None,
});
assert_eq!(view.graph.status, EpiphanyGraphFreshnessStatus::Missing);
}
#[test]
fn graph_pressure_makes_legacy_checkpoint_stale() {
let state = EpiphanyThreadState {
graph_checkpoint: Some(EpiphanyGraphCheckpoint {
checkpoint_id: "graph-1".to_string(),
..Default::default()
}),
graph_frontier: Some(EpiphanyGraphFrontier {
open_question_ids: vec!["q-1".to_string()],
..Default::default()
}),
..Default::default()
};
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&state),
retrieval_override: None,
watcher: None,
});
assert_eq!(view.graph.status, EpiphanyGraphFreshnessStatus::Stale);
}
#[test]
fn available_watcher_without_observation_is_not_clean() {
let changed_paths = Vec::new();
let view = derive_freshness(EpiphanyFreshnessInput {
state: None,
retrieval_override: None,
watcher: Some(EpiphanyFreshnessWatcherInput {
available: true,
workspace_root: None,
observed_at_unix_seconds: None,
changed_paths: &changed_paths,
}),
});
assert_eq!(view.watcher.status, EpiphanyInvalidationStatus::Unavailable);
}
#[test]
fn stale_retrieval_and_frontier_make_graph_stale() {
let state = EpiphanyThreadState {
revision: 7,
retrieval: Some(EpiphanyRetrievalState {
workspace_root: PathBuf::from("E:/repo"),
status: EpiphanyRetrievalStatus::Stale,
semantic_available: true,
indexed_file_count: Some(12),
dirty_paths: vec![PathBuf::from("src/lib.rs")],
..Default::default()
}),
graph_frontier: Some(EpiphanyGraphFrontier {
dirty_paths: vec![PathBuf::from("src/lib.rs")],
open_gap_ids: vec!["gap-1".to_string()],
..Default::default()
}),
..Default::default()
};
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&state),
retrieval_override: None,
watcher: None,
});
assert_eq!(view.state_revision, Some(7));
assert_eq!(
view.retrieval.status,
EpiphanyRetrievalFreshnessStatus::Stale
);
assert_eq!(view.retrieval.indexed_file_count, Some(12));
assert_eq!(view.graph.status, EpiphanyGraphFreshnessStatus::Stale);
assert_eq!(view.graph.open_gap_count, 1);
}
#[test]
fn ready_retrieval_with_dirty_paths_is_stale() {
let state = EpiphanyThreadState {
retrieval: Some(EpiphanyRetrievalState {
workspace_root: PathBuf::from("E:/repo"),
status: EpiphanyRetrievalStatus::Ready,
dirty_paths: vec![PathBuf::from("src/dirty.rs")],
..Default::default()
}),
..Default::default()
};
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&state),
retrieval_override: None,
watcher: None,
});
assert_eq!(
view.retrieval.status,
EpiphanyRetrievalFreshnessStatus::Stale
);
}
#[test]
fn legacy_ready_retrieval_cannot_mint_body_coverage() {
let state = EpiphanyThreadState {
retrieval: Some(EpiphanyRetrievalState {
workspace_root: PathBuf::from("E:/repo"),
status: EpiphanyRetrievalStatus::Ready,
semantic_available: true,
dirty_paths: Vec::new(),
..Default::default()
}),
..Default::default()
};
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&state),
retrieval_override: None,
watcher: None,
});
assert_eq!(
view.retrieval.status,
EpiphanyRetrievalFreshnessStatus::Missing
);
assert!(view.retrieval.note.contains("Body-bound coverage receipt"));
}
#[test]
fn watcher_maps_changed_paths_to_graph_and_frontier() {
let state = EpiphanyThreadState {
graph_frontier: Some(EpiphanyGraphFrontier {
active_node_ids: vec!["node-1".to_string()],
..Default::default()
}),
graphs: EpiphanyGraphs {
architecture: epiphany_state_model::EpiphanyGraph {
nodes: vec![EpiphanyGraphNode {
id: "node-1".to_string(),
title: "node".to_string(),
purpose: "module".to_string(),
mechanism: None,
metaphor: None,
status: None,
code_refs: vec![EpiphanyCodeRef {
path: PathBuf::from("src/lib.rs"),
start_line: None,
end_line: None,
symbol: None,
note: None,
}],
}],
..Default::default()
},
..Default::default()
},
..Default::default()
};
let changed_paths = vec![PathBuf::from("./src/lib.rs")];
let view = derive_freshness(EpiphanyFreshnessInput {
state: Some(&state),
retrieval_override: None,
watcher: Some(EpiphanyFreshnessWatcherInput {
available: true,
workspace_root: None,
observed_at_unix_seconds: Some(42),
changed_paths: &changed_paths,
}),
});
assert_eq!(view.watcher.status, EpiphanyInvalidationStatus::Changed);
assert_eq!(view.watcher.graph_node_ids, vec!["node-1".to_string()]);
assert_eq!(
view.watcher.active_frontier_node_ids,
vec!["node-1".to_string()]
);
}
}

View file

@ -1,760 +0,0 @@
use epiphany_state_model::EpiphanyCodeRef;
use epiphany_state_model::EpiphanyEvidenceRecord;
use epiphany_state_model::EpiphanyGraphCheckpoint;
use epiphany_state_model::EpiphanyGraphEdge;
use epiphany_state_model::EpiphanyGraphFrontier;
use epiphany_state_model::EpiphanyGraphLink;
use epiphany_state_model::EpiphanyGraphNode;
use epiphany_state_model::EpiphanyInvestigationCheckpoint;
use epiphany_state_model::EpiphanyObservation;
use epiphany_state_model::EpiphanyThreadState;
use std::collections::HashSet;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EpiphanyContextStateStatus {
Missing,
Ready,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EpiphanyGraphContext {
pub architecture_nodes: Vec<EpiphanyGraphNode>,
pub architecture_edges: Vec<EpiphanyGraphEdge>,
pub dataflow_nodes: Vec<EpiphanyGraphNode>,
pub dataflow_edges: Vec<EpiphanyGraphEdge>,
pub links: Vec<EpiphanyGraphLink>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EpiphanyContext {
pub graph: EpiphanyGraphContext,
pub frontier: Option<EpiphanyGraphFrontier>,
pub checkpoint: Option<EpiphanyGraphCheckpoint>,
pub investigation_checkpoint: Option<EpiphanyInvestigationCheckpoint>,
pub observations: Vec<EpiphanyObservation>,
pub evidence: Vec<EpiphanyEvidenceRecord>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EpiphanyContextMissing {
pub graph_node_ids: Vec<String>,
pub graph_edge_ids: Vec<String>,
pub observation_ids: Vec<String>,
pub evidence_ids: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EpiphanyContextParams {
pub graph_node_ids: Vec<String>,
pub graph_edge_ids: Vec<String>,
pub observation_ids: Vec<String>,
pub evidence_ids: Vec<String>,
pub include_active_frontier: Option<bool>,
pub include_linked_evidence: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpiphanyContextView {
pub state_status: EpiphanyContextStateStatus,
pub state_revision: Option<u64>,
pub context: EpiphanyContext,
pub missing: EpiphanyContextMissing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EpiphanyGraphQueryKind {
Node,
Path,
FrontierNeighborhood,
Neighbors,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EpiphanyGraphQueryDirection {
Incoming,
Outgoing,
Both,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpiphanyGraphQuery {
pub kind: EpiphanyGraphQueryKind,
pub node_ids: Vec<String>,
pub edge_ids: Vec<String>,
pub paths: Vec<PathBuf>,
pub symbols: Vec<String>,
pub edge_kinds: Vec<String>,
pub direction: Option<EpiphanyGraphQueryDirection>,
pub depth: Option<u32>,
pub include_links: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EpiphanyGraphQueryMatched {
pub node_ids: Vec<String>,
pub edge_ids: Vec<String>,
pub paths: Vec<PathBuf>,
pub symbols: Vec<String>,
pub edge_kinds: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EpiphanyGraphQueryMissing {
pub node_ids: Vec<String>,
pub edge_ids: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpiphanyGraphQueryView {
pub state_status: EpiphanyContextStateStatus,
pub state_revision: Option<u64>,
pub graph: EpiphanyGraphContext,
pub frontier: Option<EpiphanyGraphFrontier>,
pub checkpoint: Option<EpiphanyGraphCheckpoint>,
pub matched: EpiphanyGraphQueryMatched,
pub missing: EpiphanyGraphQueryMissing,
}
pub fn derive_context(
state: Option<&EpiphanyThreadState>,
params: &EpiphanyContextParams,
) -> EpiphanyContextView {
let include_active_frontier = params.include_active_frontier.unwrap_or(true);
let include_linked_evidence = params.include_linked_evidence.unwrap_or(true);
let Some(state) = state else {
return EpiphanyContextView {
state_status: EpiphanyContextStateStatus::Missing,
state_revision: None,
context: EpiphanyContext::default(),
missing: EpiphanyContextMissing {
graph_node_ids: unique_strings(params.graph_node_ids.iter().cloned()),
graph_edge_ids: unique_strings(params.graph_edge_ids.iter().cloned()),
observation_ids: unique_strings(params.observation_ids.iter().cloned()),
evidence_ids: unique_strings(params.evidence_ids.iter().cloned()),
},
};
};
let mut graph_node_ids = unique_strings(params.graph_node_ids.iter().cloned());
let mut graph_edge_ids = unique_strings(params.graph_edge_ids.iter().cloned());
if include_active_frontier && let Some(frontier) = state.graph_frontier.as_ref() {
extend_unique_strings(
&mut graph_node_ids,
frontier.active_node_ids.iter().cloned(),
);
extend_unique_strings(
&mut graph_edge_ids,
frontier.active_edge_ids.iter().cloned(),
);
}
let graph_node_id_set: HashSet<&str> = graph_node_ids.iter().map(String::as_str).collect();
let graph_edge_id_set: HashSet<&str> = graph_edge_ids.iter().map(String::as_str).collect();
let architecture_nodes = state
.graphs
.architecture
.nodes
.iter()
.filter(|node| graph_node_id_set.contains(node.id.as_str()))
.cloned()
.collect::<Vec<_>>();
let dataflow_nodes = state
.graphs
.dataflow
.nodes
.iter()
.filter(|node| graph_node_id_set.contains(node.id.as_str()))
.cloned()
.collect::<Vec<_>>();
let found_node_ids: HashSet<String> = architecture_nodes
.iter()
.chain(dataflow_nodes.iter())
.map(|node| node.id.clone())
.collect();
let architecture_edges = select_graph_edges(
&state.graphs.architecture.edges,
&graph_node_id_set,
&graph_edge_id_set,
);
let dataflow_edges = select_graph_edges(
&state.graphs.dataflow.edges,
&graph_node_id_set,
&graph_edge_id_set,
);
let found_edge_ids: HashSet<String> = architecture_edges
.iter()
.chain(dataflow_edges.iter())
.filter_map(|edge| edge.id.clone())
.filter(|id| graph_edge_id_set.contains(id.as_str()))
.collect();
let links = state
.graphs
.links
.iter()
.filter(|link| {
graph_node_id_set.contains(link.architecture_node_id.as_str())
|| graph_node_id_set.contains(link.dataflow_node_id.as_str())
})
.cloned()
.collect();
let observation_ids = unique_strings(params.observation_ids.iter().cloned());
let observation_id_set: HashSet<&str> = observation_ids.iter().map(String::as_str).collect();
let observations = state
.observations
.iter()
.filter(|observation| observation_id_set.contains(observation.id.as_str()))
.cloned()
.collect::<Vec<_>>();
let found_observation_ids: HashSet<String> = observations
.iter()
.map(|observation| observation.id.clone())
.collect();
let mut evidence_ids = unique_strings(params.evidence_ids.iter().cloned());
if include_linked_evidence {
for observation in &observations {
extend_unique_strings(&mut evidence_ids, observation.evidence_ids.iter().cloned());
}
}
let evidence_id_set: HashSet<&str> = evidence_ids.iter().map(String::as_str).collect();
let evidence = state
.recent_evidence
.iter()
.filter(|evidence| evidence_id_set.contains(evidence.id.as_str()))
.cloned()
.collect::<Vec<_>>();
let found_evidence_ids: HashSet<String> = evidence
.iter()
.map(|evidence| evidence.id.clone())
.collect();
EpiphanyContextView {
state_status: EpiphanyContextStateStatus::Ready,
state_revision: Some(state.revision),
context: EpiphanyContext {
graph: EpiphanyGraphContext {
architecture_nodes,
architecture_edges,
dataflow_nodes,
dataflow_edges,
links,
},
frontier: include_active_frontier
.then(|| state.graph_frontier.clone())
.flatten(),
checkpoint: state.graph_checkpoint.clone(),
investigation_checkpoint: state.investigation_checkpoint.clone(),
observations,
evidence,
},
missing: EpiphanyContextMissing {
graph_node_ids: graph_node_ids
.iter()
.filter(|id| !found_node_ids.contains(*id))
.cloned()
.collect(),
graph_edge_ids: graph_edge_ids
.iter()
.filter(|id| !found_edge_ids.contains(*id))
.cloned()
.collect(),
observation_ids: observation_ids
.iter()
.filter(|id| !found_observation_ids.contains(*id))
.cloned()
.collect(),
evidence_ids: evidence_ids
.iter()
.filter(|id| !found_evidence_ids.contains(*id))
.cloned()
.collect(),
},
}
}
pub fn derive_graph_query(
state: Option<&EpiphanyThreadState>,
query: &EpiphanyGraphQuery,
) -> EpiphanyGraphQueryView {
let Some(state) = state else {
return EpiphanyGraphQueryView {
state_status: EpiphanyContextStateStatus::Missing,
state_revision: None,
graph: EpiphanyGraphContext::default(),
frontier: None,
checkpoint: None,
matched: EpiphanyGraphQueryMatched::default(),
missing: EpiphanyGraphQueryMissing {
node_ids: unique_strings(query.node_ids.iter().cloned()),
edge_ids: unique_strings(query.edge_ids.iter().cloned()),
},
};
};
let mut node_ids = unique_strings(query.node_ids.iter().cloned());
let mut edge_ids = unique_strings(query.edge_ids.iter().cloned());
let mut matched_paths = Vec::new();
let mut matched_symbols = Vec::new();
let mut matched_edge_kinds = Vec::new();
match query.kind {
EpiphanyGraphQueryKind::Node => {}
EpiphanyGraphQueryKind::Path => {
collect_graph_query_path_matches(
state,
query,
&mut node_ids,
&mut edge_ids,
&mut matched_paths,
&mut matched_symbols,
);
}
EpiphanyGraphQueryKind::FrontierNeighborhood => {
if let Some(frontier) = state.graph_frontier.as_ref() {
extend_unique_strings(&mut node_ids, frontier.active_node_ids.iter().cloned());
extend_unique_strings(&mut edge_ids, frontier.active_edge_ids.iter().cloned());
}
expand_graph_query_neighbors(state, query, &mut node_ids, &mut edge_ids);
}
EpiphanyGraphQueryKind::Neighbors => {
expand_graph_query_neighbors(state, query, &mut node_ids, &mut edge_ids);
}
}
collect_graph_query_edge_kind_matches(
state,
query,
&mut node_ids,
&mut edge_ids,
&mut matched_edge_kinds,
);
if query.include_links.unwrap_or(true) {
expand_graph_query_links(state, &mut node_ids);
}
let node_id_set: HashSet<&str> = node_ids.iter().map(String::as_str).collect();
let edge_id_set: HashSet<&str> = edge_ids.iter().map(String::as_str).collect();
let architecture_nodes = state
.graphs
.architecture
.nodes
.iter()
.filter(|node| node_id_set.contains(node.id.as_str()))
.cloned()
.collect::<Vec<_>>();
let dataflow_nodes = state
.graphs
.dataflow
.nodes
.iter()
.filter(|node| node_id_set.contains(node.id.as_str()))
.cloned()
.collect::<Vec<_>>();
let found_node_ids: HashSet<String> = architecture_nodes
.iter()
.chain(dataflow_nodes.iter())
.map(|node| node.id.clone())
.collect();
let matched_node_ids = architecture_nodes
.iter()
.chain(dataflow_nodes.iter())
.map(|node| node.id.clone())
.collect::<Vec<_>>();
let architecture_edges =
select_graph_edges(&state.graphs.architecture.edges, &node_id_set, &edge_id_set);
let dataflow_edges =
select_graph_edges(&state.graphs.dataflow.edges, &node_id_set, &edge_id_set);
let found_edge_ids: HashSet<String> = architecture_edges
.iter()
.chain(dataflow_edges.iter())
.filter_map(|edge| edge.id.clone())
.collect();
let matched_edge_ids = architecture_edges
.iter()
.chain(dataflow_edges.iter())
.filter_map(|edge| edge.id.clone())
.collect::<Vec<_>>();
let links = state
.graphs
.links
.iter()
.filter(|link| {
node_id_set.contains(link.architecture_node_id.as_str())
|| node_id_set.contains(link.dataflow_node_id.as_str())
})
.cloned()
.collect::<Vec<_>>();
EpiphanyGraphQueryView {
state_status: EpiphanyContextStateStatus::Ready,
state_revision: Some(state.revision),
graph: EpiphanyGraphContext {
architecture_nodes,
architecture_edges,
dataflow_nodes,
dataflow_edges,
links,
},
frontier: state.graph_frontier.clone(),
checkpoint: state.graph_checkpoint.clone(),
matched: EpiphanyGraphQueryMatched {
node_ids: matched_node_ids,
edge_ids: matched_edge_ids,
paths: matched_paths,
symbols: matched_symbols,
edge_kinds: matched_edge_kinds,
},
missing: EpiphanyGraphQueryMissing {
node_ids: node_ids
.iter()
.filter(|id| !found_node_ids.contains(*id))
.cloned()
.collect(),
edge_ids: edge_ids
.iter()
.filter(|id| !found_edge_ids.contains(*id))
.cloned()
.collect(),
},
}
}
fn collect_graph_query_path_matches(
state: &EpiphanyThreadState,
query: &EpiphanyGraphQuery,
node_ids: &mut Vec<String>,
edge_ids: &mut Vec<String>,
matched_paths: &mut Vec<PathBuf>,
matched_symbols: &mut Vec<String>,
) {
if query.paths.is_empty() && query.symbols.is_empty() {
return;
}
for node in state
.graphs
.architecture
.nodes
.iter()
.chain(state.graphs.dataflow.nodes.iter())
{
if code_refs_match_query(&node.code_refs, query, matched_paths, matched_symbols) {
extend_unique_strings(node_ids, [node.id.clone()]);
}
}
for edge in state
.graphs
.architecture
.edges
.iter()
.chain(state.graphs.dataflow.edges.iter())
{
if code_refs_match_query(&edge.code_refs, query, matched_paths, matched_symbols) {
if let Some(id) = edge.id.clone() {
extend_unique_strings(edge_ids, [id]);
}
extend_unique_strings(node_ids, [edge.source_id.clone(), edge.target_id.clone()]);
}
}
for link in &state.graphs.links {
if code_refs_match_query(&link.code_refs, query, matched_paths, matched_symbols) {
extend_unique_strings(
node_ids,
[
link.dataflow_node_id.clone(),
link.architecture_node_id.clone(),
],
);
}
}
}
fn collect_graph_query_edge_kind_matches(
state: &EpiphanyThreadState,
query: &EpiphanyGraphQuery,
node_ids: &mut Vec<String>,
edge_ids: &mut Vec<String>,
matched_edge_kinds: &mut Vec<String>,
) {
if query.edge_kinds.is_empty() {
return;
}
let wanted: HashSet<&str> = query.edge_kinds.iter().map(String::as_str).collect();
for edge in state
.graphs
.architecture
.edges
.iter()
.chain(state.graphs.dataflow.edges.iter())
{
if wanted.contains(edge.kind.as_str()) {
extend_unique_strings(matched_edge_kinds, [edge.kind.clone()]);
if let Some(id) = edge.id.clone() {
extend_unique_strings(edge_ids, [id]);
}
extend_unique_strings(node_ids, [edge.source_id.clone(), edge.target_id.clone()]);
}
}
}
fn expand_graph_query_neighbors(
state: &EpiphanyThreadState,
query: &EpiphanyGraphQuery,
node_ids: &mut Vec<String>,
edge_ids: &mut Vec<String>,
) {
let direction = query.direction.unwrap_or(EpiphanyGraphQueryDirection::Both);
let depth = query.depth.unwrap_or(1).clamp(1, 3);
for _ in 0..depth {
let current: HashSet<String> = node_ids.iter().cloned().collect();
let before = node_ids.len();
for edge in state
.graphs
.architecture
.edges
.iter()
.chain(state.graphs.dataflow.edges.iter())
{
let source_selected = current.contains(&edge.source_id);
let target_selected = current.contains(&edge.target_id);
let include_outgoing = matches!(
direction,
EpiphanyGraphQueryDirection::Outgoing | EpiphanyGraphQueryDirection::Both
) && source_selected;
let include_incoming = matches!(
direction,
EpiphanyGraphQueryDirection::Incoming | EpiphanyGraphQueryDirection::Both
) && target_selected;
if include_outgoing || include_incoming {
if let Some(id) = edge.id.clone() {
extend_unique_strings(edge_ids, [id]);
}
}
if include_outgoing {
extend_unique_strings(node_ids, [edge.target_id.clone()]);
}
if include_incoming {
extend_unique_strings(node_ids, [edge.source_id.clone()]);
}
}
if node_ids.len() == before {
break;
}
}
}
fn expand_graph_query_links(state: &EpiphanyThreadState, node_ids: &mut Vec<String>) {
let current: HashSet<&str> = node_ids.iter().map(String::as_str).collect();
let mut linked = Vec::new();
for link in &state.graphs.links {
if current.contains(link.dataflow_node_id.as_str()) {
linked.push(link.architecture_node_id.clone());
}
if current.contains(link.architecture_node_id.as_str()) {
linked.push(link.dataflow_node_id.clone());
}
}
extend_unique_strings(node_ids, linked);
}
fn code_refs_match_query(
code_refs: &[EpiphanyCodeRef],
query: &EpiphanyGraphQuery,
matched_paths: &mut Vec<PathBuf>,
matched_symbols: &mut Vec<String>,
) -> bool {
code_refs.iter().any(|code_ref| {
let path_matches = query.paths.is_empty()
|| query.paths.iter().any(|path| {
code_ref.path == *path
|| code_ref.path.ends_with(path)
|| path.ends_with(code_ref.path.as_path())
});
let symbol_matches = query.symbols.is_empty()
|| code_ref
.symbol
.as_deref()
.is_some_and(|symbol| query.symbols.iter().any(|wanted| wanted == symbol));
if path_matches && symbol_matches {
if !query.paths.is_empty() {
extend_unique_paths(matched_paths, [code_ref.path.clone()]);
}
if let Some(symbol) = code_ref.symbol.clone()
&& !query.symbols.is_empty()
{
extend_unique_strings(matched_symbols, [symbol]);
}
true
} else {
false
}
})
}
fn extend_unique_paths(target: &mut Vec<PathBuf>, values: impl IntoIterator<Item = PathBuf>) {
for value in values {
if !target.iter().any(|existing| existing == &value) {
target.push(value);
}
}
}
fn select_graph_edges(
edges: &[EpiphanyGraphEdge],
graph_node_id_set: &HashSet<&str>,
graph_edge_id_set: &HashSet<&str>,
) -> Vec<EpiphanyGraphEdge> {
edges
.iter()
.filter(|edge| {
edge.id
.as_deref()
.is_some_and(|id| graph_edge_id_set.contains(id))
|| graph_node_id_set.contains(edge.source_id.as_str())
|| graph_node_id_set.contains(edge.target_id.as_str())
})
.cloned()
.collect()
}
fn unique_strings(values: impl IntoIterator<Item = String>) -> Vec<String> {
let mut unique = Vec::new();
extend_unique_strings(&mut unique, values);
unique
}
fn extend_unique_strings(target: &mut Vec<String>, values: impl IntoIterator<Item = String>) {
for value in values {
if !target.iter().any(|existing| existing == &value) {
target.push(value);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn graph_state() -> EpiphanyThreadState {
EpiphanyThreadState {
revision: 9,
graphs: epiphany_state_model::EpiphanyGraphs {
architecture: epiphany_state_model::EpiphanyGraph {
nodes: vec![
EpiphanyGraphNode {
id: "a".to_string(),
title: "A".to_string(),
purpose: "source".to_string(),
mechanism: None,
metaphor: None,
status: None,
code_refs: vec![EpiphanyCodeRef {
path: PathBuf::from("src/a.rs"),
start_line: None,
end_line: None,
symbol: Some("Alpha".to_string()),
note: None,
}],
},
EpiphanyGraphNode {
id: "b".to_string(),
title: "B".to_string(),
purpose: "target".to_string(),
mechanism: None,
metaphor: None,
status: None,
code_refs: Vec::new(),
},
],
edges: vec![EpiphanyGraphEdge {
source_id: "a".to_string(),
target_id: "b".to_string(),
kind: "calls".to_string(),
id: Some("edge-1".to_string()),
label: None,
mechanism: None,
code_refs: Vec::new(),
}],
},
..Default::default()
},
graph_frontier: Some(EpiphanyGraphFrontier {
active_node_ids: vec!["a".to_string()],
..Default::default()
}),
..Default::default()
}
}
#[test]
fn context_includes_active_frontier() {
let state = graph_state();
let view = derive_context(
Some(&state),
&EpiphanyContextParams {
include_active_frontier: Some(true),
..Default::default()
},
);
assert_eq!(view.state_status, EpiphanyContextStateStatus::Ready);
assert_eq!(view.state_revision, Some(9));
assert_eq!(view.context.graph.architecture_nodes[0].id, "a");
assert!(view.missing.graph_node_ids.is_empty());
}
#[test]
fn graph_query_expands_neighbors() {
let state = graph_state();
let view = derive_graph_query(
Some(&state),
&EpiphanyGraphQuery {
kind: EpiphanyGraphQueryKind::Neighbors,
node_ids: vec!["a".to_string()],
edge_ids: Vec::new(),
paths: Vec::new(),
symbols: Vec::new(),
edge_kinds: Vec::new(),
direction: Some(EpiphanyGraphQueryDirection::Outgoing),
depth: Some(1),
include_links: Some(false),
},
);
assert_eq!(view.state_status, EpiphanyContextStateStatus::Ready);
assert_eq!(view.graph.architecture_nodes.len(), 2);
assert_eq!(view.matched.edge_ids, vec!["edge-1".to_string()]);
}
#[test]
fn graph_query_matches_paths_and_symbols() {
let state = graph_state();
let view = derive_graph_query(
Some(&state),
&EpiphanyGraphQuery {
kind: EpiphanyGraphQueryKind::Path,
node_ids: Vec::new(),
edge_ids: Vec::new(),
paths: vec![PathBuf::from("src/a.rs")],
symbols: vec!["Alpha".to_string()],
edge_kinds: Vec::new(),
direction: None,
depth: None,
include_links: Some(false),
},
);
assert_eq!(view.matched.node_ids, vec!["a".to_string()]);
assert_eq!(view.matched.symbols, vec!["Alpha".to_string()]);
}
}

View file

@ -1,7 +1,5 @@
mod coordinator_contract;
mod crrc;
mod freshness;
mod graph_context;
mod jobs;
mod planning;
mod pressure;
@ -22,30 +20,6 @@ pub use crrc::EpiphanyCrrcResultStatus;
pub use crrc::EpiphanyCrrcSceneAction;
pub use crrc::EpiphanyCrrcStateStatus;
pub use crrc::recommend_crrc_action;
pub use freshness::EpiphanyFreshnessInput;
pub use freshness::EpiphanyFreshnessView;
pub use freshness::EpiphanyFreshnessWatcherInput;
pub use freshness::EpiphanyGraphFreshness;
pub use freshness::EpiphanyGraphFreshnessStatus;
pub use freshness::EpiphanyInvalidationInput;
pub use freshness::EpiphanyInvalidationStatus;
pub use freshness::EpiphanyRetrievalFreshness;
pub use freshness::EpiphanyRetrievalFreshnessStatus;
pub use freshness::derive_freshness;
pub use graph_context::EpiphanyContext;
pub use graph_context::EpiphanyContextMissing;
pub use graph_context::EpiphanyContextParams;
pub use graph_context::EpiphanyContextStateStatus;
pub use graph_context::EpiphanyContextView;
pub use graph_context::EpiphanyGraphContext;
pub use graph_context::EpiphanyGraphQuery;
pub use graph_context::EpiphanyGraphQueryDirection;
pub use graph_context::EpiphanyGraphQueryKind;
pub use graph_context::EpiphanyGraphQueryMatched;
pub use graph_context::EpiphanyGraphQueryMissing;
pub use graph_context::EpiphanyGraphQueryView;
pub use graph_context::derive_context;
pub use graph_context::derive_graph_query;
pub use jobs::EpiphanyJobStatus;
pub use jobs::EpiphanyJobView;
pub use jobs::EpiphanyJobsInput;

View file

@ -87,7 +87,6 @@ impl EpiphanyWorkerLaunchDocument {
pub struct EpiphanyRoleWorkerLaunchDocument {
pub thread_id: String,
pub role_id: String,
pub state_revision: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub objective: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]