Add Phase 6 context shard reflection

This commit is contained in:
Meta Vens 2026-04-26 03:00:06 +01:00
commit aab3ae3334
21 changed files with 1459 additions and 47 deletions

View file

@ -14811,6 +14811,127 @@
"title": "ThreadCompactStartResponse",
"type": "object"
},
"ThreadEpiphanyContext": {
"properties": {
"checkpoint": {
"anyOf": [
{
"$ref": "#/definitions/v2/EpiphanyGraphCheckpoint"
},
{
"type": "null"
}
]
},
"evidence": {
"items": {
"$ref": "#/definitions/v2/EpiphanyEvidenceRecord"
},
"type": "array"
},
"frontier": {
"anyOf": [
{
"$ref": "#/definitions/v2/EpiphanyGraphFrontier"
},
{
"type": "null"
}
]
},
"graph": {
"$ref": "#/definitions/v2/ThreadEpiphanyGraphContext"
},
"observations": {
"items": {
"$ref": "#/definitions/v2/EpiphanyObservation"
},
"type": "array"
}
},
"required": [
"graph"
],
"type": "object"
},
"ThreadEpiphanyContextMissing": {
"properties": {
"evidenceIds": {
"items": {
"type": "string"
},
"type": "array"
},
"graphEdgeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"graphNodeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"observationIds": {
"items": {
"type": "string"
},
"type": "array"
}
},
"type": "object"
},
"ThreadEpiphanyContextSource": {
"enum": [
"stored",
"live"
],
"type": "string"
},
"ThreadEpiphanyContextStateStatus": {
"enum": [
"missing",
"ready"
],
"type": "string"
},
"ThreadEpiphanyGraphContext": {
"properties": {
"architectureEdges": {
"items": {
"$ref": "#/definitions/v2/EpiphanyGraphEdge"
},
"type": "array"
},
"architectureNodes": {
"items": {
"$ref": "#/definitions/v2/EpiphanyGraphNode"
},
"type": "array"
},
"dataflowEdges": {
"items": {
"$ref": "#/definitions/v2/EpiphanyGraphEdge"
},
"type": "array"
},
"dataflowNodes": {
"items": {
"$ref": "#/definitions/v2/EpiphanyGraphNode"
},
"type": "array"
},
"links": {
"items": {
"$ref": "#/definitions/v2/EpiphanyGraphLink"
},
"type": "array"
}
},
"type": "object"
},
"ThreadEpiphanyJob": {
"properties": {
"blockingReason": {
@ -15160,6 +15281,7 @@
"index",
"retrieve",
"distill",
"context",
"jobs",
"propose",
"promote",

View file

@ -12698,6 +12698,127 @@
"title": "ThreadCompactStartResponse",
"type": "object"
},
"ThreadEpiphanyContext": {
"properties": {
"checkpoint": {
"anyOf": [
{
"$ref": "#/definitions/EpiphanyGraphCheckpoint"
},
{
"type": "null"
}
]
},
"evidence": {
"items": {
"$ref": "#/definitions/EpiphanyEvidenceRecord"
},
"type": "array"
},
"frontier": {
"anyOf": [
{
"$ref": "#/definitions/EpiphanyGraphFrontier"
},
{
"type": "null"
}
]
},
"graph": {
"$ref": "#/definitions/ThreadEpiphanyGraphContext"
},
"observations": {
"items": {
"$ref": "#/definitions/EpiphanyObservation"
},
"type": "array"
}
},
"required": [
"graph"
],
"type": "object"
},
"ThreadEpiphanyContextMissing": {
"properties": {
"evidenceIds": {
"items": {
"type": "string"
},
"type": "array"
},
"graphEdgeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"graphNodeIds": {
"items": {
"type": "string"
},
"type": "array"
},
"observationIds": {
"items": {
"type": "string"
},
"type": "array"
}
},
"type": "object"
},
"ThreadEpiphanyContextSource": {
"enum": [
"stored",
"live"
],
"type": "string"
},
"ThreadEpiphanyContextStateStatus": {
"enum": [
"missing",
"ready"
],
"type": "string"
},
"ThreadEpiphanyGraphContext": {
"properties": {
"architectureEdges": {
"items": {
"$ref": "#/definitions/EpiphanyGraphEdge"
},
"type": "array"
},
"architectureNodes": {
"items": {
"$ref": "#/definitions/EpiphanyGraphNode"
},
"type": "array"
},
"dataflowEdges": {
"items": {
"$ref": "#/definitions/EpiphanyGraphEdge"
},
"type": "array"
},
"dataflowNodes": {
"items": {
"$ref": "#/definitions/EpiphanyGraphNode"
},
"type": "array"
},
"links": {
"items": {
"$ref": "#/definitions/EpiphanyGraphLink"
},
"type": "array"
}
},
"type": "object"
},
"ThreadEpiphanyJob": {
"properties": {
"blockingReason": {
@ -13047,6 +13168,7 @@
"index",
"retrieve",
"distill",
"context",
"jobs",
"propose",
"promote",

View file

@ -0,0 +1,10 @@
// 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 { EpiphanyObservation } from "../EpiphanyObservation";
import type { ThreadEpiphanyGraphContext } from "./ThreadEpiphanyGraphContext";
export type ThreadEpiphanyContext = { graph: ThreadEpiphanyGraphContext, frontier?: EpiphanyGraphFrontier | null, checkpoint?: EpiphanyGraphCheckpoint | null, observations?: Array<EpiphanyObservation>, evidence?: Array<EpiphanyEvidenceRecord>, };

View file

@ -0,0 +1,5 @@
// 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

@ -0,0 +1,5 @@
// 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

@ -0,0 +1,5 @@
// 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

@ -0,0 +1,8 @@
// 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

@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadEpiphanySceneAction = "index" | "retrieve" | "distill" | "jobs" | "propose" | "promote" | "update";
export type ThreadEpiphanySceneAction = "index" | "retrieve" | "distill" | "context" | "jobs" | "propose" | "promote" | "update";

View file

@ -317,6 +317,11 @@ export type { ThreadArchivedNotification } from "./ThreadArchivedNotification";
export type { ThreadClosedNotification } from "./ThreadClosedNotification";
export type { ThreadCompactStartParams } from "./ThreadCompactStartParams";
export type { ThreadCompactStartResponse } from "./ThreadCompactStartResponse";
export type { ThreadEpiphanyContext } from "./ThreadEpiphanyContext";
export type { ThreadEpiphanyContextMissing } from "./ThreadEpiphanyContextMissing";
export type { ThreadEpiphanyContextSource } from "./ThreadEpiphanyContextSource";
export type { ThreadEpiphanyContextStateStatus } from "./ThreadEpiphanyContextStateStatus";
export type { ThreadEpiphanyGraphContext } from "./ThreadEpiphanyGraphContext";
export type { ThreadEpiphanyJob } from "./ThreadEpiphanyJob";
export type { ThreadEpiphanyJobKind } from "./ThreadEpiphanyJobKind";
export type { ThreadEpiphanyJobStatus } from "./ThreadEpiphanyJobStatus";

View file

@ -346,6 +346,11 @@ client_request_definitions! {
params: v2::ThreadEpiphanyJobsParams,
response: v2::ThreadEpiphanyJobsResponse,
},
#[experimental("thread/epiphany/context")]
ThreadEpiphanyContext => "thread/epiphany/context" {
params: v2::ThreadEpiphanyContextParams,
response: v2::ThreadEpiphanyContextResponse,
},
#[experimental("thread/epiphany/index")]
ThreadEpiphanyIndex => "thread/epiphany/index" {
params: v2::ThreadEpiphanyIndexParams,
@ -1808,6 +1813,120 @@ mod tests {
Ok(())
}
#[test]
fn serialize_thread_epiphany_context_response() -> Result<()> {
let response = ClientResponse::ThreadEpiphanyContext {
request_id: RequestId::Integer(8),
response: v2::ThreadEpiphanyContextResponse {
thread_id: "thr_123".to_string(),
source: v2::ThreadEpiphanyContextSource::Live,
state_status: v2::ThreadEpiphanyContextStateStatus::Ready,
state_revision: Some(3),
context: v2::ThreadEpiphanyContext {
graph: v2::ThreadEpiphanyGraphContext {
architecture_nodes: vec![codex_protocol::protocol::EpiphanyGraphNode {
id: "state-spine".to_string(),
title: "State spine".to_string(),
purpose: "Keep understanding typed".to_string(),
..Default::default()
}],
architecture_edges: vec![codex_protocol::protocol::EpiphanyGraphEdge {
id: Some("edge-state-read".to_string()),
source_id: "state-spine".to_string(),
target_id: "client-read".to_string(),
kind: "projects".to_string(),
..Default::default()
}],
..Default::default()
},
frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier {
active_node_ids: vec!["state-spine".to_string()],
..Default::default()
}),
checkpoint: None,
observations: vec![codex_protocol::protocol::EpiphanyObservation {
id: "obs-1".to_string(),
summary: "Context shard is read-only.".to_string(),
source_kind: "smoke".to_string(),
status: "ok".to_string(),
evidence_ids: vec!["ev-1".to_string()],
..Default::default()
}],
evidence: vec![codex_protocol::protocol::EpiphanyEvidenceRecord {
id: "ev-1".to_string(),
kind: "test".to_string(),
status: "ok".to_string(),
summary: "Context shard serialized.".to_string(),
..Default::default()
}],
},
missing: v2::ThreadEpiphanyContextMissing {
graph_node_ids: vec!["missing-node".to_string()],
..Default::default()
},
},
};
assert_eq!(response.id(), &RequestId::Integer(8));
assert_eq!(response.method(), "thread/epiphany/context");
assert_eq!(
json!({
"method": "thread/epiphany/context",
"id": 8,
"response": {
"threadId": "thr_123",
"source": "live",
"stateStatus": "ready",
"stateRevision": 3,
"context": {
"graph": {
"architectureNodes": [
{
"id": "state-spine",
"title": "State spine",
"purpose": "Keep understanding typed"
}
],
"architectureEdges": [
{
"source_id": "state-spine",
"target_id": "client-read",
"kind": "projects",
"id": "edge-state-read"
}
]
},
"frontier": {
"active_node_ids": ["state-spine"]
},
"observations": [
{
"id": "obs-1",
"summary": "Context shard is read-only.",
"source_kind": "smoke",
"status": "ok",
"evidence_ids": ["ev-1"]
}
],
"evidence": [
{
"id": "ev-1",
"kind": "test",
"status": "ok",
"summary": "Context shard serialized."
}
]
},
"missing": {
"graphNodeIds": ["missing-node"]
}
}
}),
serde_json::to_value(&response)?,
);
Ok(())
}
#[test]
fn serialize_thread_epiphany_retrieve_response() -> Result<()> {
let response = ClientResponse::ThreadEpiphanyRetrieve {
@ -2690,6 +2809,24 @@ mod tests {
assert_eq!(reason, Some("thread/epiphany/jobs"));
}
#[test]
fn thread_epiphany_context_is_marked_experimental() {
let request = ClientRequest::ThreadEpiphanyContext {
request_id: RequestId::Integer(1),
params: v2::ThreadEpiphanyContextParams {
thread_id: "thr_123".to_string(),
graph_node_ids: vec!["state-spine".to_string()],
graph_edge_ids: Vec::new(),
observation_ids: Vec::new(),
evidence_ids: Vec::new(),
include_active_frontier: Some(true),
include_linked_evidence: Some(true),
},
};
let reason = crate::experimental_api::ExperimentalApi::experimental_reason(&request);
assert_eq!(reason, Some("thread/epiphany/context"));
}
#[test]
fn thread_epiphany_index_is_marked_experimental() {
let request = ClientRequest::ThreadEpiphanyIndex {

View file

@ -61,7 +61,10 @@ use codex_protocol::protocol::EpiphanyChurnState as CoreEpiphanyChurnState;
use codex_protocol::protocol::EpiphanyCodeRef as CoreEpiphanyCodeRef;
use codex_protocol::protocol::EpiphanyEvidenceRecord as CoreEpiphanyEvidenceRecord;
use codex_protocol::protocol::EpiphanyGraphCheckpoint as CoreEpiphanyGraphCheckpoint;
use codex_protocol::protocol::EpiphanyGraphEdge as CoreEpiphanyGraphEdge;
use codex_protocol::protocol::EpiphanyGraphFrontier as CoreEpiphanyGraphFrontier;
use codex_protocol::protocol::EpiphanyGraphLink as CoreEpiphanyGraphLink;
use codex_protocol::protocol::EpiphanyGraphNode as CoreEpiphanyGraphNode;
use codex_protocol::protocol::EpiphanyGraphs as CoreEpiphanyGraphs;
use codex_protocol::protocol::EpiphanyInvariant as CoreEpiphanyInvariant;
use codex_protocol::protocol::EpiphanyModeState as CoreEpiphanyModeState;
@ -3985,6 +3988,7 @@ pub enum ThreadEpiphanySceneAction {
Index,
Retrieve,
Distill,
Context,
Jobs,
Propose,
Promote,
@ -4172,6 +4176,107 @@ pub struct ThreadEpiphanyJob {
pub linked_graph_node_ids: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyContextParams {
pub thread_id: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_node_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_edge_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub observation_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub evidence_ids: Vec<String>,
/// Defaults to true so clients can request the current working slice with
/// only a thread id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub include_active_frontier: Option<bool>,
/// Defaults to true so selected observations bring their evidence anchors.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub include_linked_evidence: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyContextResponse {
pub thread_id: String,
pub source: ThreadEpiphanyContextSource,
pub state_status: ThreadEpiphanyContextStateStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub state_revision: Option<u64>,
pub context: ThreadEpiphanyContext,
pub missing: ThreadEpiphanyContextMissing,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyContextSource {
Stored,
Live,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum ThreadEpiphanyContextStateStatus {
Missing,
Ready,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, Default)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyContext {
pub graph: ThreadEpiphanyGraphContext,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub frontier: Option<CoreEpiphanyGraphFrontier>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional = nullable)]
pub checkpoint: Option<CoreEpiphanyGraphCheckpoint>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub observations: Vec<CoreEpiphanyObservation>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub evidence: Vec<CoreEpiphanyEvidenceRecord>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, Default)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyGraphContext {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub architecture_nodes: Vec<CoreEpiphanyGraphNode>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub architecture_edges: Vec<CoreEpiphanyGraphEdge>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dataflow_nodes: Vec<CoreEpiphanyGraphNode>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dataflow_edges: Vec<CoreEpiphanyGraphEdge>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub links: Vec<CoreEpiphanyGraphLink>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS, Default)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadEpiphanyContextMissing {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_node_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub graph_edge_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub observation_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub evidence_ids: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]

View file

@ -146,8 +146,15 @@ use codex_app_server_protocol::ThreadCompactStartParams;
use codex_app_server_protocol::ThreadCompactStartResponse;
use codex_app_server_protocol::ThreadDecrementElicitationParams;
use codex_app_server_protocol::ThreadDecrementElicitationResponse;
use codex_app_server_protocol::ThreadEpiphanyContext;
use codex_app_server_protocol::ThreadEpiphanyContextMissing;
use codex_app_server_protocol::ThreadEpiphanyContextParams;
use codex_app_server_protocol::ThreadEpiphanyContextResponse;
use codex_app_server_protocol::ThreadEpiphanyContextSource;
use codex_app_server_protocol::ThreadEpiphanyContextStateStatus;
use codex_app_server_protocol::ThreadEpiphanyDistillParams;
use codex_app_server_protocol::ThreadEpiphanyDistillResponse;
use codex_app_server_protocol::ThreadEpiphanyGraphContext;
use codex_app_server_protocol::ThreadEpiphanyIndexParams;
use codex_app_server_protocol::ThreadEpiphanyIndexResponse;
use codex_app_server_protocol::ThreadEpiphanyJob;
@ -1014,6 +1021,10 @@ impl CodexMessageProcessor {
self.thread_epiphany_jobs(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::ThreadEpiphanyContext { request_id, params } => {
self.thread_epiphany_context(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::ThreadEpiphanyIndex { request_id, params } => {
self.thread_epiphany_index(to_connection_request_id(request_id), params)
.await;
@ -4172,6 +4183,51 @@ impl CodexMessageProcessor {
self.outgoing.send_response(request_id, response).await;
}
async fn thread_epiphany_context(
&self,
request_id: ConnectionRequestId,
params: ThreadEpiphanyContextParams,
) {
let thread_id = params.thread_id.clone();
let thread_uuid = match ThreadId::from_string(&thread_id) {
Ok(id) => id,
Err(err) => {
self.send_invalid_request_error(request_id, format!("invalid thread id: {err}"))
.await;
return;
}
};
let loaded = self.thread_manager.get_thread(thread_uuid).await.is_ok();
let thread = match self.read_thread_view(thread_uuid, false).await {
Ok(thread) => thread,
Err(ThreadReadViewError::InvalidRequest(message)) => {
self.send_invalid_request_error(request_id, message).await;
return;
}
Err(ThreadReadViewError::Internal(message)) => {
self.send_internal_error(request_id, message).await;
return;
}
};
let (state_status, state_revision, context, missing) =
map_epiphany_context(thread.epiphany_state.as_ref(), &params);
let response = ThreadEpiphanyContextResponse {
thread_id,
source: if loaded {
ThreadEpiphanyContextSource::Live
} else {
ThreadEpiphanyContextSource::Stored
},
state_status,
state_revision,
context,
missing,
};
self.outgoing.send_response(request_id, response).await;
}
async fn thread_epiphany_retrieve(
&self,
request_id: ConnectionRequestId,
@ -10677,6 +10733,7 @@ fn epiphany_scene_available_actions(
ThreadEpiphanySceneAction::Index,
ThreadEpiphanySceneAction::Retrieve,
ThreadEpiphanySceneAction::Distill,
ThreadEpiphanySceneAction::Context,
ThreadEpiphanySceneAction::Jobs,
ThreadEpiphanySceneAction::Update,
];
@ -10731,6 +10788,207 @@ fn map_epiphany_scene_graph(state: &EpiphanyThreadState) -> ThreadEpiphanySceneG
}
}
fn map_epiphany_context(
state: Option<&EpiphanyThreadState>,
params: &ThreadEpiphanyContextParams,
) -> (
ThreadEpiphanyContextStateStatus,
Option<u64>,
ThreadEpiphanyContext,
ThreadEpiphanyContextMissing,
) {
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 (
ThreadEpiphanyContextStateStatus::Missing,
None,
ThreadEpiphanyContext::default(),
ThreadEpiphanyContextMissing {
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 {
if 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_epiphany_graph_edges(
&state.graphs.architecture.edges,
&graph_node_id_set,
&graph_edge_id_set,
);
let dataflow_edges = select_epiphany_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();
(
ThreadEpiphanyContextStateStatus::Ready,
Some(state.revision),
ThreadEpiphanyContext {
graph: ThreadEpiphanyGraphContext {
architecture_nodes,
architecture_edges,
dataflow_nodes,
dataflow_edges,
links,
},
frontier: include_active_frontier
.then(|| state.graph_frontier.clone())
.flatten(),
checkpoint: state.graph_checkpoint.clone(),
observations,
evidence,
},
ThreadEpiphanyContextMissing {
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(),
},
)
}
fn select_epiphany_graph_edges(
edges: &[codex_protocol::protocol::EpiphanyGraphEdge],
graph_node_id_set: &HashSet<&str>,
graph_edge_id_set: &HashSet<&str>,
) -> Vec<codex_protocol::protocol::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);
}
}
}
fn map_epiphany_jobs(
state: Option<&EpiphanyThreadState>,
retrieval_override: Option<&EpiphanyRetrievalState>,
@ -12526,6 +12784,7 @@ mod tests {
ThreadEpiphanySceneAction::Index,
ThreadEpiphanySceneAction::Retrieve,
ThreadEpiphanySceneAction::Distill,
ThreadEpiphanySceneAction::Context,
ThreadEpiphanySceneAction::Jobs,
ThreadEpiphanySceneAction::Update,
ThreadEpiphanySceneAction::Propose,
@ -12592,6 +12851,194 @@ mod tests {
assert_eq!(evidence_ids, vec!["ev-6", "ev-5", "ev-4", "ev-3", "ev-2"]);
}
#[test]
fn map_epiphany_context_projects_targeted_shard_without_mutation() {
let state = codex_protocol::protocol::EpiphanyThreadState {
revision: 7,
graphs: codex_protocol::protocol::EpiphanyGraphs {
architecture: codex_protocol::protocol::EpiphanyGraph {
nodes: vec![
codex_protocol::protocol::EpiphanyGraphNode {
id: "active-node".to_string(),
title: "Active node".to_string(),
purpose: "Current frontier focus".to_string(),
..Default::default()
},
codex_protocol::protocol::EpiphanyGraphNode {
id: "manual-node".to_string(),
title: "Manual node".to_string(),
purpose: "Explicit context selector".to_string(),
..Default::default()
},
codex_protocol::protocol::EpiphanyGraphNode {
id: "ignored-node".to_string(),
title: "Ignored node".to_string(),
purpose: "Outside the requested shard".to_string(),
..Default::default()
},
],
edges: vec![
codex_protocol::protocol::EpiphanyGraphEdge {
id: Some("edge-active".to_string()),
source_id: "active-node".to_string(),
target_id: "ignored-node".to_string(),
kind: "frontier".to_string(),
..Default::default()
},
codex_protocol::protocol::EpiphanyGraphEdge {
id: Some("edge-manual".to_string()),
source_id: "manual-node".to_string(),
target_id: "active-node".to_string(),
kind: "selected".to_string(),
..Default::default()
},
],
},
dataflow: codex_protocol::protocol::EpiphanyGraph {
nodes: vec![codex_protocol::protocol::EpiphanyGraphNode {
id: "data-node".to_string(),
title: "Data node".to_string(),
purpose: "Linked dataflow context".to_string(),
..Default::default()
}],
edges: Vec::new(),
},
links: vec![codex_protocol::protocol::EpiphanyGraphLink {
dataflow_node_id: "data-node".to_string(),
architecture_node_id: "active-node".to_string(),
relationship: Some("supports".to_string()),
code_refs: Vec::new(),
}],
},
graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier {
active_node_ids: vec!["active-node".to_string()],
active_edge_ids: vec!["edge-active".to_string()],
..Default::default()
}),
graph_checkpoint: Some(codex_protocol::protocol::EpiphanyGraphCheckpoint {
checkpoint_id: "ck-context".to_string(),
graph_revision: 7,
summary: Some("Context shard checkpoint".to_string()),
..Default::default()
}),
observations: vec![codex_protocol::protocol::EpiphanyObservation {
id: "obs-1".to_string(),
summary: "Observation carries linked evidence.".to_string(),
source_kind: "test".to_string(),
status: "ok".to_string(),
evidence_ids: vec!["ev-linked".to_string()],
..Default::default()
}],
recent_evidence: vec![
codex_protocol::protocol::EpiphanyEvidenceRecord {
id: "ev-linked".to_string(),
kind: "test".to_string(),
status: "ok".to_string(),
summary: "Linked from observation.".to_string(),
..Default::default()
},
codex_protocol::protocol::EpiphanyEvidenceRecord {
id: "ev-extra".to_string(),
kind: "review".to_string(),
status: "ok".to_string(),
summary: "Requested directly.".to_string(),
..Default::default()
},
],
..Default::default()
};
let params = ThreadEpiphanyContextParams {
thread_id: "thr_123".to_string(),
graph_node_ids: vec!["manual-node".to_string(), "missing-node".to_string()],
graph_edge_ids: vec!["edge-manual".to_string(), "missing-edge".to_string()],
observation_ids: vec!["obs-1".to_string(), "obs-missing".to_string()],
evidence_ids: vec!["ev-extra".to_string(), "ev-missing".to_string()],
include_active_frontier: None,
include_linked_evidence: None,
};
let (state_status, state_revision, context, missing) =
map_epiphany_context(Some(&state), &params);
assert_eq!(state_status, ThreadEpiphanyContextStateStatus::Ready);
assert_eq!(state_revision, Some(7));
assert_eq!(
context
.graph
.architecture_nodes
.iter()
.map(|node| node.id.as_str())
.collect::<Vec<_>>(),
vec!["active-node", "manual-node"]
);
assert_eq!(
context
.graph
.architecture_edges
.iter()
.filter_map(|edge| edge.id.as_deref())
.collect::<Vec<_>>(),
vec!["edge-active", "edge-manual"]
);
assert_eq!(context.graph.links.len(), 1);
assert_eq!(
context
.frontier
.as_ref()
.map(|frontier| frontier.active_node_ids.as_slice()),
Some(&["active-node".to_string()][..])
);
assert_eq!(
context
.checkpoint
.as_ref()
.map(|checkpoint| checkpoint.checkpoint_id.as_str()),
Some("ck-context")
);
assert_eq!(
context
.observations
.iter()
.map(|observation| observation.id.as_str())
.collect::<Vec<_>>(),
vec!["obs-1"]
);
assert_eq!(
context
.evidence
.iter()
.map(|evidence| evidence.id.as_str())
.collect::<Vec<_>>(),
vec!["ev-linked", "ev-extra"]
);
assert_eq!(missing.graph_node_ids, vec!["missing-node".to_string()]);
assert_eq!(missing.graph_edge_ids, vec!["missing-edge".to_string()]);
assert_eq!(missing.observation_ids, vec!["obs-missing".to_string()]);
assert_eq!(missing.evidence_ids, vec!["ev-missing".to_string()]);
}
#[test]
fn map_epiphany_context_reports_missing_state_without_inventing_context() {
let params = ThreadEpiphanyContextParams {
thread_id: "thr_123".to_string(),
graph_node_ids: vec!["node-1".to_string()],
graph_edge_ids: Vec::new(),
observation_ids: vec!["obs-1".to_string()],
evidence_ids: Vec::new(),
include_active_frontier: None,
include_linked_evidence: None,
};
let (state_status, state_revision, context, missing) = map_epiphany_context(None, &params);
assert_eq!(state_status, ThreadEpiphanyContextStateStatus::Missing);
assert_eq!(state_revision, None);
assert_eq!(context, ThreadEpiphanyContext::default());
assert_eq!(missing.graph_node_ids, vec!["node-1".to_string()]);
assert_eq!(missing.observation_ids, vec!["obs-1".to_string()]);
}
#[test]
fn map_epiphany_jobs_reflects_current_progress_without_scheduling_work() {
let state = codex_protocol::protocol::EpiphanyThreadState {