Land Phase 2 Epiphany prompt integration
This commit is contained in:
parent
c823815811
commit
efd1420ef6
10 changed files with 1426 additions and 24 deletions
|
|
@ -1,5 +1,20 @@
|
|||
# Codex Epiphany Phase 2 Implementation Plan
|
||||
|
||||
## Status
|
||||
|
||||
Implemented and verified in vendored Codex on 2026-04-23.
|
||||
|
||||
What landed:
|
||||
|
||||
- `EpiphanyStateInstructions` as a dedicated developer-context fragment
|
||||
- a bounded `EpiphanyThreadState` renderer wrapped in `<epiphany_state> ... </epiphany_state>`
|
||||
- prompt injection from `Session::build_initial_context` whenever `SessionState.epiphany_state` is present
|
||||
- prompt-facing inclusion, omission, resume, bounded-rendering, and snapshot coverage
|
||||
|
||||
Next likely slice:
|
||||
|
||||
- Phase 3 typed app-server/protocol exposure so GUI clients can read Epiphany thread state directly instead of inferring it from prompt text
|
||||
|
||||
This is the actionable implementation note for the second Epiphany patch slice against the real `openai/codex` tree now vendored directly under `vendor/codex`.
|
||||
|
||||
Phase 1 landed in parent commit `2042687e3035c5a86d7f6aa66306d87abcc10f2d`. The durable state seam exists. Codex can now persist and replay structured Epiphany thread state. The next job is to make that state actually matter to the turn loop without pretending we already have GUI, retrieval, or operator ergonomics solved.
|
||||
|
|
|
|||
|
|
@ -15,15 +15,18 @@ The project target is now the vendored Codex core harness itself, not a sidecar
|
|||
|
||||
## Current Repo State
|
||||
|
||||
Latest pushed parent commit:
|
||||
|
||||
- `2042687e3035c5a86d7f6aa66306d87abcc10f2d`
|
||||
|
||||
Important consequence:
|
||||
|
||||
- `vendor/codex` is now tracked directly in the parent repo as ordinary files
|
||||
- it is **not** a submodule anymore
|
||||
|
||||
Recent anchor commits before the current in-flight work:
|
||||
|
||||
- `2042687e3035c5a86d7f6aa66306d87abcc10f2d` - vendored Codex and landed the Phase 1 Epiphany core state slice
|
||||
- `c823815` - persisted the Phase 2 implementation plan and refreshed the project handoff/state
|
||||
|
||||
Do not trust this note for the exact current HEAD; use `git log --oneline -1` if you need the live commit.
|
||||
|
||||
Canonical project state still lives in:
|
||||
|
||||
- `state/map.yaml`
|
||||
|
|
@ -62,6 +65,25 @@ Main touched files:
|
|||
- `vendor/codex/codex-rs/core/src/session/rollout_reconstruction_tests.rs`
|
||||
- plus rollout/state/app-server compatibility readers
|
||||
|
||||
Phase 2 is now done too.
|
||||
|
||||
The Phase 2 prompt-integration slice was implemented inside vendored Codex:
|
||||
|
||||
- `EpiphanyStateInstructions` renders a bounded developer fragment from `EpiphanyThreadState`
|
||||
- the fragment is wrapped in `<epiphany_state> ... </epiphany_state>`
|
||||
- `Session::build_initial_context` injects it immediately after collaboration-mode instructions when `SessionState.epiphany_state` exists
|
||||
- resumed sessions now pull the restored Epiphany state back into the prompt path instead of leaving it inert in rollout
|
||||
- prompt-facing inclusion, omission, resume, bounded-rendering, and snapshot tests were added
|
||||
|
||||
Main touched files for Phase 2:
|
||||
|
||||
- `vendor/codex/codex-rs/core/src/context/mod.rs`
|
||||
- `vendor/codex/codex-rs/core/src/context/epiphany_state_instructions.rs`
|
||||
- `vendor/codex/codex-rs/core/src/session/mod.rs`
|
||||
- `vendor/codex/codex-rs/core/src/session/tests.rs`
|
||||
- `vendor/codex/codex-rs/core/src/session/snapshots/codex_core__session__build_initial_context_epiphany_state.snap`
|
||||
- `vendor/codex/codex-rs/protocol/src/protocol.rs`
|
||||
|
||||
## Verification That Already Happened
|
||||
|
||||
Rust and VS Build Tools were installed specifically so this would stop being interpretive dance.
|
||||
|
|
@ -75,6 +97,8 @@ Verified:
|
|||
- `codex-rollout`
|
||||
- `codex-state`
|
||||
- targeted new `codex-core` Epiphany persistence/replay tests passed
|
||||
- targeted `codex-core` `epiphany` tests passed after Phase 2
|
||||
- broader `codex-core` `build_initial_context_*` coverage passed after Phase 2
|
||||
|
||||
Important Windows footgun:
|
||||
|
||||
|
|
@ -86,25 +110,23 @@ Without that, you get to learn about `symlink_dir failed: ... A required privile
|
|||
|
||||
## Recommended Next Implementation
|
||||
|
||||
Do **Phase 2 prompt integration** next.
|
||||
Do **Phase 3 typed state exposure** next.
|
||||
|
||||
The durable state seam exists. Now Codex needs to actually read it during turns.
|
||||
The durable state seam exists and the turn loop now reads it. The next clean move is to expose that state to clients without forcing GUI code to scrape prompt text.
|
||||
|
||||
Planned slice:
|
||||
|
||||
1. add a dedicated `EpiphanyStateInstructions` developer-context fragment
|
||||
2. render a compact, bounded summary from `EpiphanyThreadState`
|
||||
3. inject it from `Session::build_initial_context`
|
||||
4. activate it only when `SessionState.epiphany_state` is present
|
||||
5. add prompt-facing tests and one snapshot
|
||||
1. add typed app-server/protocol read surfaces for Epiphany thread state
|
||||
2. keep the new surface additive and internal/dev-usable first
|
||||
3. avoid making transcript text the canonical source for GUI state
|
||||
4. leave retrieval, invalidation, and specialist-agent scheduling for later slices
|
||||
|
||||
Main files for the next slice:
|
||||
|
||||
- `vendor/codex/codex-rs/core/src/context/mod.rs`
|
||||
- `vendor/codex/codex-rs/core/src/context/epiphany_state_instructions.rs` (new)
|
||||
- `vendor/codex/codex-rs/core/src/session/mod.rs`
|
||||
- `vendor/codex/codex-rs/core/src/session/tests.rs`
|
||||
- `vendor/codex/codex-rs/core/src/session/snapshots/`
|
||||
- `vendor/codex/codex-rs/app-server/src/`
|
||||
- `vendor/codex/codex-rs/app-server-protocol/src/`
|
||||
- `vendor/codex/codex-rs/protocol/src/`
|
||||
- `vendor/codex/codex-rs/core/src/session/`
|
||||
|
||||
## What Not To Do Next
|
||||
|
||||
|
|
@ -117,10 +139,10 @@ Not yet:
|
|||
- specialist-agent scheduling
|
||||
- user-facing activation flows
|
||||
|
||||
The next slice should be small and mean:
|
||||
The next slice should stay small and mean:
|
||||
|
||||
- make the state matter to prompts
|
||||
- keep the rest dark
|
||||
- expose typed state reads
|
||||
- keep GUI, retrieval, and mutation logic dark
|
||||
|
||||
## Verification Commands
|
||||
|
||||
|
|
@ -142,4 +164,4 @@ cmd /c "\"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxi
|
|||
|
||||
The repo is in a good state.
|
||||
|
||||
Phase 1 is landed, verified, committed, and pushed. `vendor/codex` is first-class in the parent repo now. The next clean move is Phase 2 prompt integration, not GUI paint and not another architectural detour.
|
||||
Phase 1 and Phase 2 are landed and verified. `vendor/codex` is first-class in the parent repo now. The next clean move is typed state exposure for clients, not GUI paint and not another architectural detour.
|
||||
|
|
|
|||
|
|
@ -30,3 +30,4 @@
|
|||
{"ts": "2026-04-23T23:12:00+01:00", "type": "verification", "status": "ok", "note": "Installed Rust and Visual Studio Build Tools to verify the Phase 1 slice in a real toolchain. cargo fmt completed; codex-protocol, codex-app-server-protocol, codex-rollout, and codex-state lib test suites passed; and the new codex-core tests for Epiphany persistence and reconstruction passed when CARGO_TARGET_DIR was moved to C: to avoid the v8 crate's Windows cross-drive symlink privilege failure."}
|
||||
{"ts": "2026-04-23T23:19:29+01:00", "type": "decision", "status": "ok", "note": "Flattened vendor/codex into the parent repository by removing the gitlink/submodule wiring and nested .git metadata so the Codex Phase 1 Epiphany harness changes can be reviewed and committed as ordinary tracked files alongside the project state."}
|
||||
{"ts": "2026-04-23T23:25:52+01:00", "type": "decision", "status": "ok", "note": "Replaced the stale Phase 1 plan and stale workspace handoff with current persisted guidance. The new notes pin the next slice as Phase 2 prompt integration: render a bounded Epiphany developer-context summary from SessionState.epiphany_state, inject it during Session::build_initial_context, keep activation internal-only via state presence, and verify it with prompt-facing tests and a snapshot before touching GUI or retrieval."}
|
||||
{"ts": "2026-04-23T22:48:30+00:00", "type": "implementation", "status": "ok", "note": "Implemented the Phase 2 prompt-integration slice in vendored Codex. Added a dedicated EpiphanyStateInstructions developer fragment, rendered a bounded summary from SessionState.epiphany_state, injected it into Session::build_initial_context after collaboration-mode instructions, and added prompt-facing inclusion/omission/resume coverage plus a stable snapshot."}
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ data_flow:
|
|||
- commit or backtrack
|
||||
|
||||
active_subgoals:
|
||||
- Implement the Phase 2 prompt-integration slice in vendored Codex: render a compact Epiphany summary from SessionState and inject it into build_initial_context when epiphany_state is present.
|
||||
- Decide and slice the Phase 3 typed app-server/protocol exposure for Epiphany thread state now that Phase 2 prompt integration is landed and verified.
|
||||
- Use the tiny CLI and typed state files on a small real task.
|
||||
- Decide whether the next executable artifact should be a patch runner or a verifier helper.
|
||||
- Run the protocol on a small real task.
|
||||
|
|
@ -73,6 +73,7 @@ accepted_design:
|
|||
- keep the Codex algorithmic map honest about auxiliary side channels and limitations: file watching, unified diffs, compaction, subagent messaging, and memory summarization are real substrate, but they do not by themselves amount to semantic repo understanding
|
||||
- vendor Codex directly into the parent repo instead of keeping it as a gitlink/submodule so Epiphany harness changes can be reviewed and committed atomically with the surrounding project state
|
||||
- for Phase 2, treat the presence of SessionState.epiphany_state as the internal activation signal and inject a bounded Epiphany summary into the developer-context path during build_initial_context rather than inventing a public operator surface early
|
||||
- Phase 2 is landed: a dedicated EpiphanyStateInstructions fragment now renders bounded Epiphany thread state into the developer prompt path during build_initial_context, with omission/inclusion/resume coverage and a stable snapshot
|
||||
|
||||
rejected_paths:
|
||||
- name: pinned_map_only
|
||||
|
|
@ -89,5 +90,5 @@ rejected_paths:
|
|||
reason: audited candidates were either terminal-only, stale/aspirational, or incoherent wrappers; the comparison clones were removed from vendor to avoid building on untrusted drift
|
||||
|
||||
current_status:
|
||||
summary: Workspace initialized with protocol files, typed state, a tiny CLI, a git repo, fresh-workspace handoff notes, architecture rationale, a Codex algorithmic map note, an Epiphany core-harness surface spec, and an actionable prompt-integration plan against vendored Codex. The Phase 1 internal/dev-usable Epiphany core state slice is implemented and verified with a real Rust/MSVC toolchain, vendored Codex is tracked directly in the parent repo, and the next slice is now pinned down as Phase 2 prompt integration rather than more architectural wandering.
|
||||
next_action: Implement Phase 2 in vendored Codex: add a dedicated EpiphanyStateInstructions renderer, inject its bounded summary from Session::build_initial_context when epiphany_state exists, and add prompt-facing omission/inclusion coverage plus one snapshot before touching GUI, retrieval, or public operator surfaces.
|
||||
summary: Workspace initialized with protocol files, typed state, a tiny CLI, a git repo, fresh-workspace handoff notes, architecture rationale, a Codex algorithmic map note, an Epiphany core-harness surface spec, and a rolling implementation plan against vendored Codex. The Phase 1 internal/dev-usable Epiphany core state slice and the Phase 2 prompt-integration slice are both implemented and verified with a real Rust/MSVC toolchain; vendored Codex is tracked directly in the parent repo; and the next move is to expose typed Epiphany state to clients without making prompt text the source of truth.
|
||||
next_action: Decide and plan the Phase 3 typed app-server/protocol exposure slice so clients can read Epiphany thread state directly, keeping the surface additive and internal/dev-usable before GUI ergonomics or retrieval work.
|
||||
|
|
|
|||
801
vendor/codex/codex-rs/core/src/context/epiphany_state_instructions.rs
vendored
Normal file
801
vendor/codex/codex-rs/core/src/context/epiphany_state_instructions.rs
vendored
Normal file
|
|
@ -0,0 +1,801 @@
|
|||
use super::ContextualUserFragment;
|
||||
use codex_protocol::protocol::EPIPHANY_STATE_CLOSE_TAG;
|
||||
use codex_protocol::protocol::EPIPHANY_STATE_OPEN_TAG;
|
||||
use codex_protocol::protocol::EpiphanyChurnState;
|
||||
use codex_protocol::protocol::EpiphanyCodeRef;
|
||||
use codex_protocol::protocol::EpiphanyEvidenceRecord;
|
||||
use codex_protocol::protocol::EpiphanyGraph;
|
||||
use codex_protocol::protocol::EpiphanyGraphCheckpoint;
|
||||
use codex_protocol::protocol::EpiphanyGraphEdge;
|
||||
use codex_protocol::protocol::EpiphanyGraphFrontier;
|
||||
use codex_protocol::protocol::EpiphanyGraphLink;
|
||||
use codex_protocol::protocol::EpiphanyGraphNode;
|
||||
use codex_protocol::protocol::EpiphanyModeState;
|
||||
use codex_protocol::protocol::EpiphanyObservation;
|
||||
use codex_protocol::protocol::EpiphanyScratchPad;
|
||||
use codex_protocol::protocol::EpiphanyThreadState;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
const SUBGOAL_LIMIT: usize = 4;
|
||||
const INVARIANT_LIMIT: usize = 4;
|
||||
const NODE_LIMIT: usize = 3;
|
||||
const EDGE_LIMIT: usize = 2;
|
||||
const LINK_LIMIT: usize = 3;
|
||||
const OBSERVATION_LIMIT: usize = 3;
|
||||
const EVIDENCE_LIMIT: usize = 3;
|
||||
const CODE_REF_LIMIT: usize = 2;
|
||||
const DIRTY_PATH_LIMIT: usize = 4;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct EpiphanyStateInstructions {
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl EpiphanyStateInstructions {
|
||||
pub(crate) fn from_state(state: &EpiphanyThreadState) -> Self {
|
||||
Self {
|
||||
text: render_epiphany_state(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextualUserFragment for EpiphanyStateInstructions {
|
||||
const ROLE: &'static str = "developer";
|
||||
const START_MARKER: &'static str = EPIPHANY_STATE_OPEN_TAG;
|
||||
const END_MARKER: &'static str = EPIPHANY_STATE_CLOSE_TAG;
|
||||
|
||||
fn body(&self) -> String {
|
||||
self.text.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn render_epiphany_state(state: &EpiphanyThreadState) -> String {
|
||||
let mut sections = vec![concat!(
|
||||
"\n## Epiphany State\n",
|
||||
"Treat this as the current structured thread understanding. Use it to stay oriented during this turn. ",
|
||||
"If your planned edits conflict with it or expose a gap, surface that before broad edits. ",
|
||||
"Do not silently rewrite this state in prose."
|
||||
)
|
||||
.to_string()];
|
||||
|
||||
sections.push(render_overview(state));
|
||||
|
||||
if let Some(subgoals) = render_subgoals(state) {
|
||||
sections.push(subgoals);
|
||||
}
|
||||
if let Some(invariants) = render_invariants(state) {
|
||||
sections.push(invariants);
|
||||
}
|
||||
if let Some(graphs) = render_graphs(state) {
|
||||
sections.push(graphs);
|
||||
}
|
||||
if let Some(scratch) = render_scratch(state.scratch.as_ref()) {
|
||||
sections.push(scratch);
|
||||
}
|
||||
if let Some(observations) = render_observations(&state.observations) {
|
||||
sections.push(observations);
|
||||
}
|
||||
if let Some(evidence) = render_evidence(&state.recent_evidence) {
|
||||
sections.push(evidence);
|
||||
}
|
||||
if let Some(churn) = render_churn(state.churn.as_ref()) {
|
||||
sections.push(churn);
|
||||
}
|
||||
if let Some(mode) = render_mode(state.mode.as_ref()) {
|
||||
sections.push(mode);
|
||||
}
|
||||
|
||||
format!("{}\n", sections.join("\n\n"))
|
||||
}
|
||||
|
||||
fn render_overview(state: &EpiphanyThreadState) -> String {
|
||||
let mut lines = vec![format!("- Revision: {}", state.revision)];
|
||||
if let Some(objective) = state.objective.as_deref() {
|
||||
lines.push(format!("- Objective: {}", compact_text(objective)));
|
||||
}
|
||||
if let Some(active_subgoal_id) = state.active_subgoal_id.as_deref() {
|
||||
lines.push(format!("- Active subgoal: `{active_subgoal_id}`"));
|
||||
}
|
||||
if let Some(last_updated_turn_id) = state.last_updated_turn_id.as_deref() {
|
||||
lines.push(format!("- Last updated turn: `{last_updated_turn_id}`"));
|
||||
}
|
||||
if let Some(frontier) = state.graph_frontier.as_ref() {
|
||||
let focus_ids = collect_focus_node_ids(Some(frontier), state.graph_checkpoint.as_ref());
|
||||
if !focus_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Frontier focus: {}",
|
||||
render_inline_ids(&focus_ids)
|
||||
));
|
||||
}
|
||||
}
|
||||
format!("## Overview\n{}", lines.join("\n"))
|
||||
}
|
||||
|
||||
fn render_subgoals(state: &EpiphanyThreadState) -> Option<String> {
|
||||
if state.subgoals.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for subgoal in state.subgoals.iter().take(SUBGOAL_LIMIT) {
|
||||
let active_suffix = state
|
||||
.active_subgoal_id
|
||||
.as_deref()
|
||||
.filter(|active_id| *active_id == subgoal.id)
|
||||
.map(|_| "; active")
|
||||
.unwrap_or("");
|
||||
lines.push(format!(
|
||||
"- `{}` [{}{}]: {}",
|
||||
subgoal.id,
|
||||
subgoal.status,
|
||||
active_suffix,
|
||||
compact_text(&subgoal.title)
|
||||
));
|
||||
if let Some(summary) = subgoal.summary.as_deref() {
|
||||
lines.push(format!(" summary: {}", compact_text(summary)));
|
||||
}
|
||||
}
|
||||
push_omitted_count(&mut lines, state.subgoals.len(), SUBGOAL_LIMIT, "subgoals");
|
||||
|
||||
Some(format!("## Subgoals\n{}", lines.join("\n")))
|
||||
}
|
||||
|
||||
fn render_invariants(state: &EpiphanyThreadState) -> Option<String> {
|
||||
if state.invariants.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for invariant in state.invariants.iter().take(INVARIANT_LIMIT) {
|
||||
lines.push(format!(
|
||||
"- `{}` [{}]: {}",
|
||||
invariant.id,
|
||||
invariant.status,
|
||||
compact_text(&invariant.description)
|
||||
));
|
||||
if let Some(rationale) = invariant.rationale.as_deref() {
|
||||
lines.push(format!(" rationale: {}", compact_text(rationale)));
|
||||
}
|
||||
}
|
||||
push_omitted_count(
|
||||
&mut lines,
|
||||
state.invariants.len(),
|
||||
INVARIANT_LIMIT,
|
||||
"invariants",
|
||||
);
|
||||
|
||||
Some(format!("## Invariants\n{}", lines.join("\n")))
|
||||
}
|
||||
|
||||
fn render_graphs(state: &EpiphanyThreadState) -> Option<String> {
|
||||
if state.graphs.is_empty() && state.graph_frontier.is_none() && state.graph_checkpoint.is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut lines = Vec::new();
|
||||
let focus_node_ids = collect_focus_node_ids(
|
||||
state.graph_frontier.as_ref(),
|
||||
state.graph_checkpoint.as_ref(),
|
||||
);
|
||||
|
||||
if let Some(frontier) = state.graph_frontier.as_ref() {
|
||||
append_frontier_lines(&mut lines, frontier);
|
||||
}
|
||||
if let Some(checkpoint) = state.graph_checkpoint.as_ref() {
|
||||
append_checkpoint_lines(&mut lines, checkpoint);
|
||||
}
|
||||
|
||||
append_graph_lines(
|
||||
&mut lines,
|
||||
"Architecture graph",
|
||||
&state.graphs.architecture,
|
||||
&focus_node_ids,
|
||||
state.graph_frontier.as_ref(),
|
||||
);
|
||||
append_graph_lines(
|
||||
&mut lines,
|
||||
"Dataflow graph",
|
||||
&state.graphs.dataflow,
|
||||
&focus_node_ids,
|
||||
state.graph_frontier.as_ref(),
|
||||
);
|
||||
|
||||
if !state.graphs.links.is_empty() {
|
||||
for link in select_links(&state.graphs.links, &focus_node_ids)
|
||||
.into_iter()
|
||||
.take(LINK_LIMIT)
|
||||
{
|
||||
let relationship = link
|
||||
.relationship
|
||||
.as_deref()
|
||||
.map(|value| format!(" ({})", compact_text(value)))
|
||||
.unwrap_or_default();
|
||||
let code_refs = render_code_refs(&link.code_refs);
|
||||
lines.push(format!(
|
||||
"- Link: `{}` -> `{}`{}{}",
|
||||
link.dataflow_node_id,
|
||||
link.architecture_node_id,
|
||||
relationship,
|
||||
render_ref_suffix(&code_refs)
|
||||
));
|
||||
}
|
||||
push_omitted_count(
|
||||
&mut lines,
|
||||
state.graphs.links.len(),
|
||||
LINK_LIMIT,
|
||||
"graph links",
|
||||
);
|
||||
}
|
||||
|
||||
Some(format!("## Graphs\n{}", lines.join("\n")))
|
||||
}
|
||||
|
||||
fn append_frontier_lines(lines: &mut Vec<String>, frontier: &EpiphanyGraphFrontier) {
|
||||
if !frontier.active_node_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Frontier active nodes: {}",
|
||||
render_inline_ids(&frontier.active_node_ids)
|
||||
));
|
||||
}
|
||||
if !frontier.active_edge_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Frontier active edges: {}",
|
||||
render_inline_ids(&frontier.active_edge_ids)
|
||||
));
|
||||
}
|
||||
if !frontier.open_question_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Open questions: {}",
|
||||
render_inline_ids(&frontier.open_question_ids)
|
||||
));
|
||||
}
|
||||
if !frontier.open_gap_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Open gaps: {}",
|
||||
render_inline_ids(&frontier.open_gap_ids)
|
||||
));
|
||||
}
|
||||
if !frontier.dirty_paths.is_empty() {
|
||||
let dirty_paths = frontier
|
||||
.dirty_paths
|
||||
.iter()
|
||||
.take(DIRTY_PATH_LIMIT)
|
||||
.map(|path| format!("`{}`", normalize_path(path)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let omitted_suffix =
|
||||
omitted_suffix(frontier.dirty_paths.len(), DIRTY_PATH_LIMIT, "dirty paths");
|
||||
lines.push(format!("- Dirty paths: {dirty_paths}{omitted_suffix}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn append_checkpoint_lines(lines: &mut Vec<String>, checkpoint: &EpiphanyGraphCheckpoint) {
|
||||
lines.push(format!(
|
||||
"- Checkpoint: `{}` (graph revision {})",
|
||||
checkpoint.checkpoint_id, checkpoint.graph_revision
|
||||
));
|
||||
if let Some(summary) = checkpoint.summary.as_deref() {
|
||||
lines.push(format!("- Checkpoint summary: {}", compact_text(summary)));
|
||||
}
|
||||
if !checkpoint.frontier_node_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Checkpoint frontier nodes: {}",
|
||||
render_inline_ids(&checkpoint.frontier_node_ids)
|
||||
));
|
||||
}
|
||||
if !checkpoint.open_question_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Checkpoint open questions: {}",
|
||||
render_inline_ids(&checkpoint.open_question_ids)
|
||||
));
|
||||
}
|
||||
if !checkpoint.open_gap_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
"- Checkpoint open gaps: {}",
|
||||
render_inline_ids(&checkpoint.open_gap_ids)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn append_graph_lines(
|
||||
lines: &mut Vec<String>,
|
||||
label: &str,
|
||||
graph: &EpiphanyGraph,
|
||||
focus_node_ids: &[String],
|
||||
frontier: Option<&EpiphanyGraphFrontier>,
|
||||
) {
|
||||
if graph.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let selected_nodes = select_nodes(graph, focus_node_ids);
|
||||
let selected_node_ids = selected_nodes
|
||||
.iter()
|
||||
.map(|node| node.id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let active_edge_ids = frontier
|
||||
.map(|graph_frontier| {
|
||||
graph_frontier
|
||||
.active_edge_ids
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
lines.push(format!(
|
||||
"- {label}: {} nodes, {} edges",
|
||||
graph.nodes.len(),
|
||||
graph.edges.len()
|
||||
));
|
||||
|
||||
for node in &selected_nodes {
|
||||
let status = node
|
||||
.status
|
||||
.as_deref()
|
||||
.map(|value| format!(" [{}]", compact_text(value)))
|
||||
.unwrap_or_default();
|
||||
lines.push(format!(
|
||||
" - Focus node `{}`{}: {}",
|
||||
node.id,
|
||||
status,
|
||||
compact_text(&node.title)
|
||||
));
|
||||
lines.push(format!(" purpose: {}", compact_text(&node.purpose)));
|
||||
if let Some(mechanism) = node.mechanism.as_deref() {
|
||||
lines.push(format!(" mechanism: {}", compact_text(mechanism)));
|
||||
}
|
||||
if let Some(metaphor) = node.metaphor.as_deref() {
|
||||
lines.push(format!(" metaphor: {}", compact_text(metaphor)));
|
||||
}
|
||||
let code_refs = render_code_refs(&node.code_refs);
|
||||
if !code_refs.is_empty() {
|
||||
lines.push(format!(" code refs: {}", code_refs.join(", ")));
|
||||
}
|
||||
}
|
||||
push_omitted_count(lines, graph.nodes.len(), NODE_LIMIT, "graph nodes");
|
||||
|
||||
let selected_edges = select_edges(graph, &selected_node_ids, &active_edge_ids);
|
||||
for edge in selected_edges.iter().take(EDGE_LIMIT) {
|
||||
let edge_id = edge
|
||||
.id
|
||||
.as_deref()
|
||||
.map(|value| format!(" `{value}`"))
|
||||
.unwrap_or_default();
|
||||
let label_suffix = edge
|
||||
.label
|
||||
.as_deref()
|
||||
.map(|value| format!(" [{}]", compact_text(value)))
|
||||
.unwrap_or_default();
|
||||
let mechanism_suffix = edge
|
||||
.mechanism
|
||||
.as_deref()
|
||||
.map(|value| format!("; {}", compact_text(value)))
|
||||
.unwrap_or_default();
|
||||
let code_refs = render_code_refs(&edge.code_refs);
|
||||
lines.push(format!(
|
||||
" - Edge{edge_id}{label_suffix}: `{}` -> `{}` ({}){}{}",
|
||||
edge.source_id,
|
||||
edge.target_id,
|
||||
edge.kind,
|
||||
mechanism_suffix,
|
||||
render_ref_suffix(&code_refs)
|
||||
));
|
||||
}
|
||||
push_omitted_count(
|
||||
lines,
|
||||
selected_edges.len(),
|
||||
EDGE_LIMIT,
|
||||
"focused graph edges",
|
||||
);
|
||||
}
|
||||
|
||||
fn render_scratch(scratch: Option<&EpiphanyScratchPad>) -> Option<String> {
|
||||
let scratch = scratch?;
|
||||
let mut lines = Vec::new();
|
||||
if let Some(summary) = scratch.summary.as_deref() {
|
||||
lines.push(format!("- Summary: {}", compact_text(summary)));
|
||||
}
|
||||
if let Some(hypothesis) = scratch.hypothesis.as_deref() {
|
||||
lines.push(format!("- Hypothesis: {}", compact_text(hypothesis)));
|
||||
}
|
||||
if let Some(next_probe) = scratch.next_probe.as_deref() {
|
||||
lines.push(format!("- Next probe: {}", compact_text(next_probe)));
|
||||
}
|
||||
|
||||
if lines.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(format!("## Scratch\n{}", lines.join("\n")))
|
||||
}
|
||||
}
|
||||
|
||||
fn render_observations(observations: &[EpiphanyObservation]) -> Option<String> {
|
||||
if observations.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for observation in observations.iter().take(OBSERVATION_LIMIT) {
|
||||
lines.push(format!(
|
||||
"- `{}` [{} via {}]: {}",
|
||||
observation.id,
|
||||
observation.status,
|
||||
observation.source_kind,
|
||||
compact_text(&observation.summary)
|
||||
));
|
||||
if !observation.evidence_ids.is_empty() {
|
||||
lines.push(format!(
|
||||
" evidence: {}",
|
||||
render_inline_ids(&observation.evidence_ids)
|
||||
));
|
||||
}
|
||||
let code_refs = render_code_refs(&observation.code_refs);
|
||||
if !code_refs.is_empty() {
|
||||
lines.push(format!(" code refs: {}", code_refs.join(", ")));
|
||||
}
|
||||
}
|
||||
push_omitted_count(
|
||||
&mut lines,
|
||||
observations.len(),
|
||||
OBSERVATION_LIMIT,
|
||||
"observations",
|
||||
);
|
||||
|
||||
Some(format!("## Recent Observations\n{}", lines.join("\n")))
|
||||
}
|
||||
|
||||
fn render_evidence(evidence: &[EpiphanyEvidenceRecord]) -> Option<String> {
|
||||
if evidence.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for record in evidence.iter().take(EVIDENCE_LIMIT) {
|
||||
let code_refs = render_code_refs(&record.code_refs);
|
||||
lines.push(format!(
|
||||
"- `{}` [{} / {}]: {}{}",
|
||||
record.id,
|
||||
record.kind,
|
||||
record.status,
|
||||
compact_text(&record.summary),
|
||||
render_ref_suffix(&code_refs)
|
||||
));
|
||||
}
|
||||
push_omitted_count(
|
||||
&mut lines,
|
||||
evidence.len(),
|
||||
EVIDENCE_LIMIT,
|
||||
"evidence records",
|
||||
);
|
||||
|
||||
Some(format!("## Recent Evidence\n{}", lines.join("\n")))
|
||||
}
|
||||
|
||||
fn render_churn(churn: Option<&EpiphanyChurnState>) -> Option<String> {
|
||||
let churn = churn?;
|
||||
let mut lines = vec![
|
||||
format!(
|
||||
"- Understanding status: {}",
|
||||
compact_text(&churn.understanding_status)
|
||||
),
|
||||
format!("- Diff pressure: {}", compact_text(&churn.diff_pressure)),
|
||||
];
|
||||
if let Some(graph_freshness) = churn.graph_freshness.as_deref() {
|
||||
lines.push(format!(
|
||||
"- Graph freshness: {}",
|
||||
compact_text(graph_freshness)
|
||||
));
|
||||
}
|
||||
if let Some(warning) = churn.warning.as_deref() {
|
||||
lines.push(format!("- Warning: {}", compact_text(warning)));
|
||||
}
|
||||
if let Some(unexplained_writes) = churn.unexplained_writes {
|
||||
lines.push(format!("- Unexplained writes: {unexplained_writes}"));
|
||||
}
|
||||
|
||||
Some(format!("## Churn\n{}", lines.join("\n")))
|
||||
}
|
||||
|
||||
fn render_mode(mode: Option<&EpiphanyModeState>) -> Option<String> {
|
||||
let mode = mode?;
|
||||
let mut line = format!("- Name: {}", compact_text(&mode.name));
|
||||
if let Some(kind) = mode.kind {
|
||||
line.push_str(&format!(" ({kind:?})"));
|
||||
}
|
||||
Some(format!("## Mode\n{line}"))
|
||||
}
|
||||
|
||||
fn collect_focus_node_ids(
|
||||
frontier: Option<&EpiphanyGraphFrontier>,
|
||||
checkpoint: Option<&EpiphanyGraphCheckpoint>,
|
||||
) -> Vec<String> {
|
||||
let mut focus_node_ids = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for node_id in frontier
|
||||
.into_iter()
|
||||
.flat_map(|value| value.active_node_ids.iter())
|
||||
.chain(
|
||||
checkpoint
|
||||
.into_iter()
|
||||
.flat_map(|value| value.frontier_node_ids.iter()),
|
||||
)
|
||||
{
|
||||
if seen.insert(node_id.as_str()) {
|
||||
focus_node_ids.push(node_id.clone());
|
||||
}
|
||||
}
|
||||
focus_node_ids
|
||||
}
|
||||
|
||||
fn select_nodes<'a>(
|
||||
graph: &'a EpiphanyGraph,
|
||||
focus_node_ids: &[String],
|
||||
) -> Vec<&'a EpiphanyGraphNode> {
|
||||
let mut selected = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let focus_set = focus_node_ids
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
for node in &graph.nodes {
|
||||
if focus_set.contains(node.id.as_str()) && seen.insert(node.id.as_str()) {
|
||||
selected.push(node);
|
||||
if selected.len() == NODE_LIMIT {
|
||||
return selected;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for node in &graph.nodes {
|
||||
if seen.insert(node.id.as_str()) {
|
||||
selected.push(node);
|
||||
if selected.len() == NODE_LIMIT {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
selected
|
||||
}
|
||||
|
||||
fn select_edges<'a>(
|
||||
graph: &'a EpiphanyGraph,
|
||||
selected_node_ids: &HashSet<&'a str>,
|
||||
active_edge_ids: &HashSet<&str>,
|
||||
) -> Vec<&'a EpiphanyGraphEdge> {
|
||||
graph
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|edge| {
|
||||
edge.id
|
||||
.as_deref()
|
||||
.is_some_and(|edge_id| active_edge_ids.contains(edge_id))
|
||||
|| selected_node_ids.contains(edge.source_id.as_str())
|
||||
|| selected_node_ids.contains(edge.target_id.as_str())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn select_links<'a>(
|
||||
links: &'a [EpiphanyGraphLink],
|
||||
focus_node_ids: &[String],
|
||||
) -> Vec<&'a EpiphanyGraphLink> {
|
||||
let focus_set = focus_node_ids
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>();
|
||||
let mut focused = Vec::new();
|
||||
let mut fallback = Vec::new();
|
||||
for link in links {
|
||||
if focus_set.contains(link.dataflow_node_id.as_str())
|
||||
|| focus_set.contains(link.architecture_node_id.as_str())
|
||||
{
|
||||
focused.push(link);
|
||||
} else {
|
||||
fallback.push(link);
|
||||
}
|
||||
}
|
||||
focused.extend(fallback);
|
||||
focused
|
||||
}
|
||||
|
||||
fn render_code_refs(code_refs: &[EpiphanyCodeRef]) -> Vec<String> {
|
||||
let mut rendered = code_refs
|
||||
.iter()
|
||||
.take(CODE_REF_LIMIT)
|
||||
.map(render_code_ref)
|
||||
.collect::<Vec<_>>();
|
||||
if code_refs.len() > CODE_REF_LIMIT {
|
||||
rendered.push(format!(
|
||||
"... {} more refs",
|
||||
code_refs.len() - CODE_REF_LIMIT
|
||||
));
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
fn render_code_ref(code_ref: &EpiphanyCodeRef) -> String {
|
||||
let mut location = normalize_path(&code_ref.path);
|
||||
match (code_ref.start_line, code_ref.end_line) {
|
||||
(Some(start_line), Some(end_line)) if end_line != start_line => {
|
||||
location.push_str(&format!(":{start_line}-{end_line}"));
|
||||
}
|
||||
(Some(start_line), _) => {
|
||||
location.push_str(&format!(":{start_line}"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let mut metadata = Vec::new();
|
||||
if let Some(symbol) = code_ref.symbol.as_deref() {
|
||||
metadata.push(format!("symbol: {}", compact_text(symbol)));
|
||||
}
|
||||
if let Some(note) = code_ref.note.as_deref() {
|
||||
metadata.push(compact_text(note));
|
||||
}
|
||||
|
||||
if metadata.is_empty() {
|
||||
format!("`{location}`")
|
||||
} else {
|
||||
format!("`{location}` ({})", metadata.join("; "))
|
||||
}
|
||||
}
|
||||
|
||||
fn render_ref_suffix(code_refs: &[String]) -> String {
|
||||
if code_refs.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("; refs: {}", code_refs.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
fn render_inline_ids(ids: &[String]) -> String {
|
||||
ids.iter()
|
||||
.map(|id| format!("`{id}`"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
fn normalize_path(path: &Path) -> String {
|
||||
path.to_string_lossy().replace('\\', "/")
|
||||
}
|
||||
|
||||
fn compact_text(value: &str) -> String {
|
||||
value.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn omitted_suffix(total: usize, shown: usize, label: &str) -> String {
|
||||
if total > shown {
|
||||
format!("; ... {} more {label} not shown", total - shown)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn push_omitted_count(lines: &mut Vec<String>, total: usize, shown: usize, label: &str) {
|
||||
if total > shown {
|
||||
lines.push(format!("- ... {} more {label} not shown", total - shown));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::EpiphanyStateInstructions;
|
||||
use crate::context::ContextualUserFragment;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::protocol::EpiphanyChurnState;
|
||||
use codex_protocol::protocol::EpiphanyCodeRef;
|
||||
use codex_protocol::protocol::EpiphanyGraph;
|
||||
use codex_protocol::protocol::EpiphanyGraphCheckpoint;
|
||||
use codex_protocol::protocol::EpiphanyGraphEdge;
|
||||
use codex_protocol::protocol::EpiphanyGraphFrontier;
|
||||
use codex_protocol::protocol::EpiphanyGraphNode;
|
||||
use codex_protocol::protocol::EpiphanyGraphs;
|
||||
use codex_protocol::protocol::EpiphanyModeState;
|
||||
use codex_protocol::protocol::EpiphanyThreadState;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn render_prefers_frontier_focus_and_omits_empty_sections() {
|
||||
let state = EpiphanyThreadState {
|
||||
revision: 7,
|
||||
objective: Some("Map the actual turn loop.".to_string()),
|
||||
graphs: EpiphanyGraphs {
|
||||
architecture: EpiphanyGraph {
|
||||
nodes: vec![
|
||||
EpiphanyGraphNode {
|
||||
id: "arch-overview".to_string(),
|
||||
title: "Overview".to_string(),
|
||||
purpose: "Loose context nobody is touching.".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
EpiphanyGraphNode {
|
||||
id: "arch-session".to_string(),
|
||||
title: "Session".to_string(),
|
||||
purpose: "Owns prompt assembly.".to_string(),
|
||||
mechanism: Some("Builds the initial context bundle.".to_string()),
|
||||
metaphor: Some("The foreman keeping the queue honest.".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/session/mod.rs"),
|
||||
start_line: Some(2433),
|
||||
end_line: Some(2617),
|
||||
symbol: Some("build_initial_context".to_string()),
|
||||
note: None,
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
EpiphanyGraphNode {
|
||||
id: "arch-rollout".to_string(),
|
||||
title: "Rollout".to_string(),
|
||||
purpose: "Persists thread state.".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
EpiphanyGraphNode {
|
||||
id: "arch-extra".to_string(),
|
||||
title: "Extra".to_string(),
|
||||
purpose: "Should be trimmed.".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
edges: vec![EpiphanyGraphEdge {
|
||||
source_id: "arch-session".to_string(),
|
||||
target_id: "arch-rollout".to_string(),
|
||||
kind: "writes".to_string(),
|
||||
id: Some("edge-session-rollout".to_string()),
|
||||
label: Some("persists".to_string()),
|
||||
mechanism: Some("Writes baseline state after a turn.".to_string()),
|
||||
..Default::default()
|
||||
}],
|
||||
},
|
||||
dataflow: EpiphanyGraph {
|
||||
nodes: vec![EpiphanyGraphNode {
|
||||
id: "flow-build-context".to_string(),
|
||||
title: "Build context".to_string(),
|
||||
purpose: "Turns state into prompt context.".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
graph_frontier: Some(EpiphanyGraphFrontier {
|
||||
active_node_ids: vec!["arch-session".to_string(), "flow-build-context".to_string()],
|
||||
active_edge_ids: vec!["edge-session-rollout".to_string()],
|
||||
dirty_paths: vec![PathBuf::from("core/src/session/mod.rs")],
|
||||
..Default::default()
|
||||
}),
|
||||
graph_checkpoint: Some(EpiphanyGraphCheckpoint {
|
||||
checkpoint_id: "cp-7".to_string(),
|
||||
graph_revision: 7,
|
||||
frontier_node_ids: vec!["arch-session".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
churn: Some(EpiphanyChurnState {
|
||||
understanding_status: "stable".to_string(),
|
||||
diff_pressure: "low".to_string(),
|
||||
graph_freshness: Some("fresh".to_string()),
|
||||
warning: None,
|
||||
unexplained_writes: Some(0),
|
||||
}),
|
||||
mode: Some(EpiphanyModeState {
|
||||
name: "epiphany".to_string(),
|
||||
kind: Some(ModeKind::Default),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let rendered = EpiphanyStateInstructions::from_state(&state).render();
|
||||
|
||||
assert!(rendered.contains("<epiphany_state>"));
|
||||
assert!(rendered.contains("`arch-session`"));
|
||||
assert!(rendered.contains("`flow-build-context`"));
|
||||
assert!(!rendered.contains("## Scratch"));
|
||||
assert!(!rendered.contains("## Invariants"));
|
||||
assert!(rendered.contains("`core/src/session/mod.rs:2433-2617`"));
|
||||
assert!(rendered.contains("... 1 more graph nodes not shown"));
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ mod available_skills_instructions;
|
|||
mod collaboration_mode_instructions;
|
||||
mod contextual_user_message;
|
||||
mod environment_context;
|
||||
mod epiphany_state_instructions;
|
||||
mod fragment;
|
||||
mod guardian_followup_review_reminder;
|
||||
mod hook_additional_context;
|
||||
|
|
@ -35,6 +36,7 @@ pub(crate) use contextual_user_message::is_contextual_user_fragment;
|
|||
pub(crate) use contextual_user_message::is_memory_excluded_contextual_user_fragment;
|
||||
pub(crate) use contextual_user_message::parse_visible_hook_prompt_message;
|
||||
pub(crate) use environment_context::EnvironmentContext;
|
||||
pub(crate) use epiphany_state_instructions::EpiphanyStateInstructions;
|
||||
pub use fragment::ContextualUserFragment;
|
||||
pub(crate) use fragment::FragmentRegistration;
|
||||
pub(crate) use fragment::FragmentRegistrationProxy;
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ use crate::context::AvailablePluginsInstructions;
|
|||
use crate::context::AvailableSkillsInstructions;
|
||||
use crate::context::CollaborationModeInstructions;
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context::EpiphanyStateInstructions;
|
||||
use crate::context::NetworkRuleSaved;
|
||||
use crate::context::PermissionsInstructions;
|
||||
use crate::context::PersonalitySpecInstructions;
|
||||
|
|
@ -2434,7 +2435,7 @@ impl Session {
|
|||
&self,
|
||||
turn_context: &TurnContext,
|
||||
) -> Vec<ResponseItem> {
|
||||
let mut developer_sections = Vec::<String>::with_capacity(8);
|
||||
let mut developer_sections = Vec::<String>::with_capacity(9);
|
||||
let mut contextual_user_sections = Vec::<String>::with_capacity(2);
|
||||
let shell = self.user_shell();
|
||||
let (
|
||||
|
|
@ -2443,6 +2444,7 @@ impl Session {
|
|||
collaboration_mode,
|
||||
base_instructions,
|
||||
session_source,
|
||||
epiphany_state,
|
||||
) = {
|
||||
let state = self.state.lock().await;
|
||||
(
|
||||
|
|
@ -2451,6 +2453,7 @@ impl Session {
|
|||
state.session_configuration.collaboration_mode.clone(),
|
||||
state.session_configuration.base_instructions.clone(),
|
||||
state.session_configuration.session_source.clone(),
|
||||
state.epiphany_state(),
|
||||
)
|
||||
};
|
||||
if let Some(model_switch_message) =
|
||||
|
|
@ -2503,6 +2506,9 @@ impl Session {
|
|||
{
|
||||
developer_sections.push(collab_instructions.render());
|
||||
}
|
||||
if let Some(epiphany_state) = epiphany_state.as_ref() {
|
||||
developer_sections.push(EpiphanyStateInstructions::from_state(epiphany_state).render());
|
||||
}
|
||||
if let Some(realtime_update) = crate::context_manager::updates::build_initial_realtime_item(
|
||||
reference_context_item.as_ref(),
|
||||
previous_turn_settings.as_ref(),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,191 @@
|
|||
---
|
||||
source: core/src/session/tests.rs
|
||||
expression: developer_text
|
||||
---
|
||||
<permissions instructions>
|
||||
Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `read-only`: The sandbox only permits reading files. Network access is restricted.
|
||||
# Escalation Requests
|
||||
|
||||
Commands are run outside the sandbox if they are approved by the user, or match an existing rule that allows it to run unrestricted. The command string is split into independent command segments at shell control operators, including but not limited to:
|
||||
|
||||
- Pipes: |
|
||||
- Logical operators: &&, ||
|
||||
- Command separators: ;
|
||||
- Subshell boundaries: (...), $(...)
|
||||
|
||||
Each resulting segment is evaluated independently for sandbox restrictions and approval requirements.
|
||||
|
||||
Example:
|
||||
|
||||
git pull | tee output.txt
|
||||
|
||||
This is treated as two command segments:
|
||||
|
||||
["git", "pull"]
|
||||
|
||||
["tee", "output.txt"]
|
||||
|
||||
Commands that use more advanced shell features like redirection (>, >>, <), substitutions ($(...), ...), environment variables (FOO=bar), or wildcard patterns (*, ?) will not be evaluated against rules, to limit the scope of what an approved rule allows.
|
||||
|
||||
## How to request escalation
|
||||
|
||||
IMPORTANT: To request approval to execute a command that will require escalated privileges:
|
||||
|
||||
- Provide the `sandbox_permissions` parameter with the value `"require_escalated"`
|
||||
- Include a short question asking the user if they want to allow the action in `justification` parameter. e.g. "Do you want to download and install dependencies for this project?"
|
||||
- Optionally suggest a `prefix_rule` - this will be shown to the user with an option to persist the rule approval for future sessions.
|
||||
|
||||
If you run a command that is important to solving the user's query, but it fails because of sandboxing or with a likely sandbox-related network error (for example DNS/host resolution, registry/index access, or dependency download failure), rerun the command with "require_escalated". ALWAYS proceed to use the `justification` parameter - do not message the user before requesting approval for the command.
|
||||
|
||||
## When to request escalation
|
||||
|
||||
While commands are running inside the sandbox, here are some scenarios that will require escalation outside the sandbox:
|
||||
|
||||
- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /var)
|
||||
- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.
|
||||
- If you run a command that is important to solving the user's query, but it fails because of sandboxing or with a likely sandbox-related network error (for example DNS/host resolution, registry/index access, or dependency download failure), rerun the command with `require_escalated`. ALWAYS proceed to use the `sandbox_permissions` and `justification` parameters. do not message the user before requesting approval for the command.
|
||||
- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for.
|
||||
- Be judicious with escalating, but if completing the user's request requires it, you should do so - don't try and circumvent approvals by using other tools.
|
||||
|
||||
## prefix_rule guidance
|
||||
|
||||
When choosing a `prefix_rule`, request one that will allow you to fulfill similar requests from the user in the future without re-requesting escalation. It should be categorical and reasonably scoped to similar capabilities. You should rarely pass the entire command into `prefix_rule`.
|
||||
|
||||
### Banned prefix_rules
|
||||
Avoid requesting overly broad prefixes that the user would be ill-advised to approve. For example, do not request ["python3"], ["python", "-"], or other similar prefixes that would allow arbitrary scripting.
|
||||
NEVER provide a prefix_rule argument for destructive commands like rm.
|
||||
NEVER provide a prefix_rule if your command uses a heredoc or herestring.
|
||||
|
||||
### Examples
|
||||
Good examples of prefixes:
|
||||
- ["npm", "run", "dev"]
|
||||
- ["gh", "pr", "check"]
|
||||
- ["cargo", "test"]
|
||||
</permissions instructions>
|
||||
|
||||
<epiphany_state>
|
||||
## Epiphany State
|
||||
Treat this as the current structured thread understanding. Use it to stay oriented during this turn. If your planned edits conflict with it or expose a gap, surface that before broad edits. Do not silently rewrite this state in prose.
|
||||
|
||||
## Overview
|
||||
- Revision: 7
|
||||
- Objective: Keep the prompt path oriented around the real thread state.
|
||||
- Active subgoal: `phase2-prompt`
|
||||
- Last updated turn: `phase2-turn`
|
||||
- Frontier focus: `arch-session`, `flow-prompt`
|
||||
|
||||
## Subgoals
|
||||
- `phase2-prompt` [in_progress; active]: Inject the structured state into build_initial_context.
|
||||
summary: Wire a compact developer fragment into the initial prompt bundle.
|
||||
- `phase2-tests` [pending]: Add tests that catch prompt sludge.
|
||||
summary: Prove inclusion, omission, and bounded rendering.
|
||||
|
||||
## Invariants
|
||||
- `canon` [active]: Prompt text must not silently redefine the durable state.
|
||||
rationale: We want the model reading state, not cosplaying authorship of it.
|
||||
- `bounded` [active]: The injected summary must stay compact and deterministic.
|
||||
rationale: The whole point is to avoid turning the prompt into another haunted attic.
|
||||
|
||||
## Graphs
|
||||
- Frontier active nodes: `arch-session`, `flow-prompt`
|
||||
- Frontier active edges: `edge-session-context`
|
||||
- Open questions: `q-boundary`
|
||||
- Open gaps: `gap-resume-proof`
|
||||
- Dirty paths: `core/src/session/mod.rs`, `core/src/context/epiphany_state_instructions.rs`
|
||||
- Checkpoint: `phase2-checkpoint` (graph revision 7)
|
||||
- Checkpoint summary: Prompt integration is the current frontier; GUI and retrieval stay dark.
|
||||
- Checkpoint frontier nodes: `arch-session`, `flow-prompt`
|
||||
- Checkpoint open questions: `q-boundary`
|
||||
- Checkpoint open gaps: `gap-resume-proof`
|
||||
- Architecture graph: 2 nodes, 1 edges
|
||||
- Focus node `arch-session` [verified]: Session loop
|
||||
purpose: Owns the turn setup and initial prompt bundle.
|
||||
mechanism: Builds developer/contextual-user fragments before the first model request.
|
||||
metaphor: The foreman lining tools up before the crew starts swinging.
|
||||
code refs: `core/src/session/mod.rs:2433-2617` (symbol: build_initial_context; Phase 2 injection seam)
|
||||
- Focus node `arch-context` [verified]: Context fragments
|
||||
purpose: Render marked developer and contextual-user fragments.
|
||||
mechanism: Small typed renderers turn state into bounded prompt sections.
|
||||
metaphor: The bins on the wall where the right parts live.
|
||||
code refs: `core/src/context/epiphany_state_instructions.rs:1-220` (symbol: EpiphanyStateInstructions; New renderer)
|
||||
- Edge `edge-session-context` [injects]: `arch-session` -> `arch-context` (renders); Calls the Epiphany renderer when thread state exists.; refs: `core/src/session/mod.rs:2502-2510` (symbol: build_initial_context; Epiphany insertion slot)
|
||||
- Dataflow graph: 2 nodes, 1 edges
|
||||
- Focus node `flow-prompt` [in_progress]: Prompt fragment
|
||||
purpose: Turns the durable state into a bounded developer instruction block.
|
||||
mechanism: Summarizes only active and recent state with line-anchored refs.
|
||||
metaphor: A folded field guide, not the entire filing cabinet.
|
||||
code refs: `core/src/context/epiphany_state_instructions.rs:1-220` (symbol: render_epiphany_state; Summary shaping)
|
||||
- Focus node `flow-state` [verified]: Epiphany state snapshot
|
||||
purpose: Carries durable objective, graph, evidence, and churn state across turns.
|
||||
mechanism: Lives on SessionState and comes back during resume.
|
||||
metaphor: The map pinned to the workshop wall so nobody wanders off whistling.
|
||||
code refs: `core/src/state/session.rs:36-121` (symbol: SessionState::epiphany_state; Stored thread state)
|
||||
- Edge `edge-state-prompt` [bounded summary]: `flow-state` -> `flow-prompt` (summarized-as); Keep frontier, evidence, and churn in view without dumping raw JSON.; refs: `core/src/context/epiphany_state_instructions.rs:32-220` (symbol: render_epiphany_state; Prompt shaping)
|
||||
- Link: `flow-prompt` -> `arch-context` (implemented-by); refs: `core/src/context/epiphany_state_instructions.rs:1-220` (symbol: EpiphanyStateInstructions; Renderer implementation)
|
||||
|
||||
## Scratch
|
||||
- Summary: Inject the state as a developer fragment, not as a user message.
|
||||
- Hypothesis: Keeping the block bounded will help resume without making prompt sludge.
|
||||
- Next probe: Verify resumed sessions still inject the latest surviving snapshot.
|
||||
|
||||
## Recent Observations
|
||||
- `obs-session-seam` [accepted via code-read]: build_initial_context already composes developer fragments in one place.
|
||||
evidence: `ev-session-read`
|
||||
code refs: `core/src/session/mod.rs:2433-2617` (symbol: build_initial_context; Prompt assembly)
|
||||
- `obs-state-seam` [accepted via test]: Phase 1 already restores Epiphany state before future turns build context.
|
||||
evidence: `ev-resume-read`
|
||||
code refs: `core/src/session/rollout_reconstruction.rs:1-220` (symbol: RolloutReconstruction; Resume path)
|
||||
|
||||
## Recent Evidence
|
||||
- `ev-session-read` [research / ok]: Confirmed the prompt builder already has a clean insertion point after collaboration-mode instructions.; refs: `core/src/session/mod.rs:2498-2511` (symbol: build_initial_context; Insertion window)
|
||||
- `ev-resume-read` [test / ok]: Phase 1 tests already prove the latest surviving Epiphany snapshot is restored on resume.; refs: `core/src/session/rollout_reconstruction_tests.rs:110-191` (symbol: record_initial_history_resumed_hydrates_epiphany_state_from_latest_surviving_turn; Resume proof)
|
||||
|
||||
## Churn
|
||||
- Understanding status: stable
|
||||
- Diff pressure: low
|
||||
- Graph freshness: fresh
|
||||
- Warning: Keep the fragment bounded; do not turn it into another transcript dump.
|
||||
- Unexplained writes: 0
|
||||
|
||||
## Mode
|
||||
- Name: epiphany (Default)
|
||||
</epiphany_state>
|
||||
|
||||
<skills_instructions>
|
||||
## Skills
|
||||
A skill is a set of local instructions to follow that is stored in a `SKILL.md` file. Below is the list of skills that can be used. Each entry includes a name, description, and file path so you can open the source for full instructions when using a specific skill.
|
||||
### Available skills
|
||||
- imagegen: Generate or edit raster images when the task benefits from AI-created bitmap visuals such as photos, illustrations, textures, sprites, mockups, or transparent-background cutouts. Use when Codex should create a brand-new image, transform an existing image, or derive visual variants from references, and the output should be a bitmap asset rather than repo-native code or vector. Do not use when the task is better handled by editing existing SVG/vector/code-native assets, extending an established icon or logo system, or building the visual directly in HTML/CSS/canvas. (file: <temp-skills-root>/.system/imagegen/SKILL.md)
|
||||
- openai-docs: Use when the user asks how to build with OpenAI products or APIs and needs up-to-date official documentation with citations, help choosing the latest model for a use case, or model upgrade and prompt-upgrade guidance; prioritize OpenAI docs MCP tools, use bundled references only as helper context, and restrict any fallback browsing to official OpenAI domains. (file: <temp-skills-root>/.system/openai-docs/SKILL.md)
|
||||
- plugin-creator: Create and scaffold plugin directories for Codex with a required `.codex-plugin/plugin.json`, optional plugin folders/files, and baseline placeholders you can edit before publishing or testing. Use when Codex needs to create a new local plugin, add optional plugin structure, or generate or update repo-root `.agents/plugins/marketplace.json` entries for plugin ordering and availability metadata. (file: <temp-skills-root>/.system/plugin-creator/SKILL.md)
|
||||
- skill-creator: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Codex's capabilities with specialized knowledge, workflows, or tool integrations. (file: <temp-skills-root>/.system/skill-creator/SKILL.md)
|
||||
- skill-installer: Install Codex skills into $CODEX_HOME/skills from a curated list or a GitHub repo path. Use when a user asks to list installable skills, install a curated skill, or install a skill from another repo (including private repos). (file: <temp-skills-root>/.system/skill-installer/SKILL.md)
|
||||
- babysit-pr: Babysit a GitHub pull request after creation by continuously polling review comments, CI checks/workflow runs, and mergeability state until the PR is merged/closed or user help is required. Diagnose failures, retry likely flaky failures up to 3 times, auto-fix/push branch-related issues when appropriate, and keep watching open PRs so fresh review feedback is surfaced promptly. Use when the user asks Codex to monitor a PR, watch CI, handle review comments, or keep an eye on failures and feedback on an open PR. (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/babysit-pr/SKILL.md)
|
||||
- code-breaking-changes: Breaking changes (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/code-review-breaking-changes/SKILL.md)
|
||||
- code-review: Run a final code review on a pull request (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/code-review/SKILL.md)
|
||||
- code-review-change-size: Change size guidance (800 lines) (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/code-review-change-size/SKILL.md)
|
||||
- code-review-context: Model visible context (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/code-review-context/SKILL.md)
|
||||
- code-review-testing: Test authoring guidance (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/code-review-testing/SKILL.md)
|
||||
- codex-bug: Diagnose GitHub bug reports in openai/codex. Use when given a GitHub issue URL from openai/codex and asked to decide next steps such as verifying against the repo, requesting more info, or explaining why it is not a bug; follow any additional user-provided instructions. (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/codex-bug/SKILL.md)
|
||||
- codex-pr-body: Update the title and body of one or more pull requests. (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/codex-pr-body/SKILL.md)
|
||||
- remote-tests: How to run tests using remote executor. (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/remote-tests/SKILL.md)
|
||||
- test-tui: Guide for testing Codex TUI interactively (file: E:/Projects/EpiphanyAgent/vendor/codex/.codex/skills/test-tui/SKILL.md)
|
||||
### How to use skills
|
||||
- Discovery: The list above is the skills available in this session (name + description + file path). Skill bodies live on disk at the listed paths.
|
||||
- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.
|
||||
- Missing/blocked: If a named skill isn't in the list or the path can't be read, say so briefly and continue with the best fallback.
|
||||
- How to use a skill (progressive disclosure):
|
||||
1) After deciding to use a skill, open its `SKILL.md`. Read only enough to follow the workflow.
|
||||
2) When `SKILL.md` references relative paths (e.g., `scripts/foo.py`), resolve them relative to the skill directory listed above first, and only consider other paths if needed.
|
||||
3) If `SKILL.md` points to extra folders such as `references/`, load only the specific files needed for the request; don't bulk-load everything.
|
||||
4) If `scripts/` exist, prefer running or patching them instead of retyping large code blocks.
|
||||
5) If `assets/` or templates exist, reuse them instead of recreating from scratch.
|
||||
- Coordination and sequencing:
|
||||
- If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.
|
||||
- Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why.
|
||||
- Context hygiene:
|
||||
- Keep context small: summarize long sections instead of pasting them; only load extra files when needed.
|
||||
- Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked.
|
||||
- When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice.
|
||||
- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue.
|
||||
</skills_instructions>
|
||||
361
vendor/codex/codex-rs/core/src/session/tests.rs
vendored
361
vendor/codex/codex-rs/core/src/session/tests.rs
vendored
|
|
@ -84,7 +84,22 @@ use codex_protocol::protocol::AskForApproval;
|
|||
use codex_protocol::protocol::CompactedItem;
|
||||
use codex_protocol::protocol::ConversationAudioParams;
|
||||
use codex_protocol::protocol::CreditsSnapshot;
|
||||
use codex_protocol::protocol::EpiphanyChurnState;
|
||||
use codex_protocol::protocol::EpiphanyCodeRef;
|
||||
use codex_protocol::protocol::EpiphanyEvidenceRecord;
|
||||
use codex_protocol::protocol::EpiphanyGraph;
|
||||
use codex_protocol::protocol::EpiphanyGraphCheckpoint;
|
||||
use codex_protocol::protocol::EpiphanyGraphEdge;
|
||||
use codex_protocol::protocol::EpiphanyGraphFrontier;
|
||||
use codex_protocol::protocol::EpiphanyGraphLink;
|
||||
use codex_protocol::protocol::EpiphanyGraphNode;
|
||||
use codex_protocol::protocol::EpiphanyGraphs;
|
||||
use codex_protocol::protocol::EpiphanyInvariant;
|
||||
use codex_protocol::protocol::EpiphanyModeState;
|
||||
use codex_protocol::protocol::EpiphanyObservation;
|
||||
use codex_protocol::protocol::EpiphanyScratchPad;
|
||||
use codex_protocol::protocol::EpiphanyStateItem;
|
||||
use codex_protocol::protocol::EpiphanySubgoal;
|
||||
use codex_protocol::protocol::EpiphanyThreadState;
|
||||
use codex_protocol::protocol::GranularApprovalConfig;
|
||||
use codex_protocol::protocol::InitialHistory;
|
||||
|
|
@ -139,6 +154,7 @@ use tracing_opentelemetry::OpenTelemetrySpanExt;
|
|||
|
||||
use codex_protocol::mcp::CallToolResult as McpCallToolResult;
|
||||
use pretty_assertions::assert_eq;
|
||||
use regex_lite::Regex;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
|
|
@ -157,6 +173,251 @@ fn sample_epiphany_state_for_persistence() -> EpiphanyThreadState {
|
|||
}
|
||||
}
|
||||
|
||||
fn sample_epiphany_state_for_prompt() -> EpiphanyThreadState {
|
||||
EpiphanyThreadState {
|
||||
revision: 7,
|
||||
objective: Some("Keep the prompt path oriented around the real thread state.".to_string()),
|
||||
active_subgoal_id: Some("phase2-prompt".to_string()),
|
||||
subgoals: vec![
|
||||
EpiphanySubgoal {
|
||||
id: "phase2-prompt".to_string(),
|
||||
title: "Inject the structured state into build_initial_context.".to_string(),
|
||||
status: "in_progress".to_string(),
|
||||
summary: Some("Wire a compact developer fragment into the initial prompt bundle.".to_string()),
|
||||
},
|
||||
EpiphanySubgoal {
|
||||
id: "phase2-tests".to_string(),
|
||||
title: "Add tests that catch prompt sludge.".to_string(),
|
||||
status: "pending".to_string(),
|
||||
summary: Some("Prove inclusion, omission, and bounded rendering.".to_string()),
|
||||
},
|
||||
],
|
||||
invariants: vec![
|
||||
EpiphanyInvariant {
|
||||
id: "canon".to_string(),
|
||||
description: "Prompt text must not silently redefine the durable state.".to_string(),
|
||||
status: "active".to_string(),
|
||||
rationale: Some("We want the model reading state, not cosplaying authorship of it.".to_string()),
|
||||
},
|
||||
EpiphanyInvariant {
|
||||
id: "bounded".to_string(),
|
||||
description: "The injected summary must stay compact and deterministic.".to_string(),
|
||||
status: "active".to_string(),
|
||||
rationale: Some("The whole point is to avoid turning the prompt into another haunted attic.".to_string()),
|
||||
},
|
||||
],
|
||||
graphs: EpiphanyGraphs {
|
||||
architecture: EpiphanyGraph {
|
||||
nodes: vec![
|
||||
EpiphanyGraphNode {
|
||||
id: "arch-session".to_string(),
|
||||
title: "Session loop".to_string(),
|
||||
purpose: "Owns the turn setup and initial prompt bundle.".to_string(),
|
||||
mechanism: Some("Builds developer/contextual-user fragments before the first model request.".to_string()),
|
||||
metaphor: Some("The foreman lining tools up before the crew starts swinging.".to_string()),
|
||||
status: Some("verified".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/session/mod.rs"),
|
||||
start_line: Some(2433),
|
||||
end_line: Some(2617),
|
||||
symbol: Some("build_initial_context".to_string()),
|
||||
note: Some("Phase 2 injection seam".to_string()),
|
||||
}],
|
||||
},
|
||||
EpiphanyGraphNode {
|
||||
id: "arch-context".to_string(),
|
||||
title: "Context fragments".to_string(),
|
||||
purpose: "Render marked developer and contextual-user fragments.".to_string(),
|
||||
mechanism: Some("Small typed renderers turn state into bounded prompt sections.".to_string()),
|
||||
metaphor: Some("The bins on the wall where the right parts live.".to_string()),
|
||||
status: Some("verified".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/context/epiphany_state_instructions.rs"),
|
||||
start_line: Some(1),
|
||||
end_line: Some(220),
|
||||
symbol: Some("EpiphanyStateInstructions".to_string()),
|
||||
note: Some("New renderer".to_string()),
|
||||
}],
|
||||
},
|
||||
],
|
||||
edges: vec![EpiphanyGraphEdge {
|
||||
source_id: "arch-session".to_string(),
|
||||
target_id: "arch-context".to_string(),
|
||||
kind: "renders".to_string(),
|
||||
id: Some("edge-session-context".to_string()),
|
||||
label: Some("injects".to_string()),
|
||||
mechanism: Some("Calls the Epiphany renderer when thread state exists.".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/session/mod.rs"),
|
||||
start_line: Some(2502),
|
||||
end_line: Some(2510),
|
||||
symbol: Some("build_initial_context".to_string()),
|
||||
note: Some("Epiphany insertion slot".to_string()),
|
||||
}],
|
||||
}],
|
||||
},
|
||||
dataflow: EpiphanyGraph {
|
||||
nodes: vec![
|
||||
EpiphanyGraphNode {
|
||||
id: "flow-state".to_string(),
|
||||
title: "Epiphany state snapshot".to_string(),
|
||||
purpose: "Carries durable objective, graph, evidence, and churn state across turns.".to_string(),
|
||||
mechanism: Some("Lives on SessionState and comes back during resume.".to_string()),
|
||||
metaphor: Some("The map pinned to the workshop wall so nobody wanders off whistling.".to_string()),
|
||||
status: Some("verified".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/state/session.rs"),
|
||||
start_line: Some(36),
|
||||
end_line: Some(121),
|
||||
symbol: Some("SessionState::epiphany_state".to_string()),
|
||||
note: Some("Stored thread state".to_string()),
|
||||
}],
|
||||
},
|
||||
EpiphanyGraphNode {
|
||||
id: "flow-prompt".to_string(),
|
||||
title: "Prompt fragment".to_string(),
|
||||
purpose: "Turns the durable state into a bounded developer instruction block.".to_string(),
|
||||
mechanism: Some("Summarizes only active and recent state with line-anchored refs.".to_string()),
|
||||
metaphor: Some("A folded field guide, not the entire filing cabinet.".to_string()),
|
||||
status: Some("in_progress".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/context/epiphany_state_instructions.rs"),
|
||||
start_line: Some(1),
|
||||
end_line: Some(220),
|
||||
symbol: Some("render_epiphany_state".to_string()),
|
||||
note: Some("Summary shaping".to_string()),
|
||||
}],
|
||||
},
|
||||
],
|
||||
edges: vec![EpiphanyGraphEdge {
|
||||
source_id: "flow-state".to_string(),
|
||||
target_id: "flow-prompt".to_string(),
|
||||
kind: "summarized-as".to_string(),
|
||||
id: Some("edge-state-prompt".to_string()),
|
||||
label: Some("bounded summary".to_string()),
|
||||
mechanism: Some("Keep frontier, evidence, and churn in view without dumping raw JSON.".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/context/epiphany_state_instructions.rs"),
|
||||
start_line: Some(32),
|
||||
end_line: Some(220),
|
||||
symbol: Some("render_epiphany_state".to_string()),
|
||||
note: Some("Prompt shaping".to_string()),
|
||||
}],
|
||||
}],
|
||||
},
|
||||
links: vec![EpiphanyGraphLink {
|
||||
dataflow_node_id: "flow-prompt".to_string(),
|
||||
architecture_node_id: "arch-context".to_string(),
|
||||
relationship: Some("implemented-by".to_string()),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/context/epiphany_state_instructions.rs"),
|
||||
start_line: Some(1),
|
||||
end_line: Some(220),
|
||||
symbol: Some("EpiphanyStateInstructions".to_string()),
|
||||
note: Some("Renderer implementation".to_string()),
|
||||
}],
|
||||
}],
|
||||
},
|
||||
graph_frontier: Some(EpiphanyGraphFrontier {
|
||||
active_node_ids: vec!["arch-session".to_string(), "flow-prompt".to_string()],
|
||||
active_edge_ids: vec!["edge-session-context".to_string()],
|
||||
open_question_ids: vec!["q-boundary".to_string()],
|
||||
open_gap_ids: vec!["gap-resume-proof".to_string()],
|
||||
dirty_paths: vec![
|
||||
PathBuf::from("core/src/session/mod.rs"),
|
||||
PathBuf::from("core/src/context/epiphany_state_instructions.rs"),
|
||||
],
|
||||
}),
|
||||
graph_checkpoint: Some(EpiphanyGraphCheckpoint {
|
||||
checkpoint_id: "phase2-checkpoint".to_string(),
|
||||
graph_revision: 7,
|
||||
summary: Some("Prompt integration is the current frontier; GUI and retrieval stay dark.".to_string()),
|
||||
frontier_node_ids: vec!["arch-session".to_string(), "flow-prompt".to_string()],
|
||||
open_question_ids: vec!["q-boundary".to_string()],
|
||||
open_gap_ids: vec!["gap-resume-proof".to_string()],
|
||||
}),
|
||||
scratch: Some(EpiphanyScratchPad {
|
||||
summary: Some("Inject the state as a developer fragment, not as a user message.".to_string()),
|
||||
hypothesis: Some("Keeping the block bounded will help resume without making prompt sludge.".to_string()),
|
||||
next_probe: Some("Verify resumed sessions still inject the latest surviving snapshot.".to_string()),
|
||||
notes: vec![
|
||||
"Do not dump raw JSON.".to_string(),
|
||||
"Do not invent a public toggle yet.".to_string(),
|
||||
],
|
||||
}),
|
||||
observations: vec![
|
||||
EpiphanyObservation {
|
||||
id: "obs-session-seam".to_string(),
|
||||
summary: "build_initial_context already composes developer fragments in one place.".to_string(),
|
||||
source_kind: "code-read".to_string(),
|
||||
status: "accepted".to_string(),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/session/mod.rs"),
|
||||
start_line: Some(2433),
|
||||
end_line: Some(2617),
|
||||
symbol: Some("build_initial_context".to_string()),
|
||||
note: Some("Prompt assembly".to_string()),
|
||||
}],
|
||||
evidence_ids: vec!["ev-session-read".to_string()],
|
||||
},
|
||||
EpiphanyObservation {
|
||||
id: "obs-state-seam".to_string(),
|
||||
summary: "Phase 1 already restores Epiphany state before future turns build context.".to_string(),
|
||||
source_kind: "test".to_string(),
|
||||
status: "accepted".to_string(),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/session/rollout_reconstruction.rs"),
|
||||
start_line: Some(1),
|
||||
end_line: Some(220),
|
||||
symbol: Some("RolloutReconstruction".to_string()),
|
||||
note: Some("Resume path".to_string()),
|
||||
}],
|
||||
evidence_ids: vec!["ev-resume-read".to_string()],
|
||||
},
|
||||
],
|
||||
recent_evidence: vec![
|
||||
EpiphanyEvidenceRecord {
|
||||
id: "ev-session-read".to_string(),
|
||||
kind: "research".to_string(),
|
||||
status: "ok".to_string(),
|
||||
summary: "Confirmed the prompt builder already has a clean insertion point after collaboration-mode instructions.".to_string(),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/session/mod.rs"),
|
||||
start_line: Some(2498),
|
||||
end_line: Some(2511),
|
||||
symbol: Some("build_initial_context".to_string()),
|
||||
note: Some("Insertion window".to_string()),
|
||||
}],
|
||||
},
|
||||
EpiphanyEvidenceRecord {
|
||||
id: "ev-resume-read".to_string(),
|
||||
kind: "test".to_string(),
|
||||
status: "ok".to_string(),
|
||||
summary: "Phase 1 tests already prove the latest surviving Epiphany snapshot is restored on resume.".to_string(),
|
||||
code_refs: vec![EpiphanyCodeRef {
|
||||
path: PathBuf::from("core/src/session/rollout_reconstruction_tests.rs"),
|
||||
start_line: Some(110),
|
||||
end_line: Some(191),
|
||||
symbol: Some("record_initial_history_resumed_hydrates_epiphany_state_from_latest_surviving_turn".to_string()),
|
||||
note: Some("Resume proof".to_string()),
|
||||
}],
|
||||
},
|
||||
],
|
||||
churn: Some(EpiphanyChurnState {
|
||||
understanding_status: "stable".to_string(),
|
||||
diff_pressure: "low".to_string(),
|
||||
graph_freshness: Some("fresh".to_string()),
|
||||
warning: Some("Keep the fragment bounded; do not turn it into another transcript dump.".to_string()),
|
||||
unexplained_writes: Some(0),
|
||||
}),
|
||||
mode: Some(EpiphanyModeState {
|
||||
name: "epiphany".to_string(),
|
||||
kind: Some(ModeKind::Default),
|
||||
}),
|
||||
last_updated_turn_id: Some("phase2-turn".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
struct InstructionsTestCase {
|
||||
slug: &'static str,
|
||||
expects_apply_patch_description: bool,
|
||||
|
|
@ -369,6 +630,10 @@ fn developer_input_texts(items: &[ResponseItem]) -> Vec<&str> {
|
|||
.collect()
|
||||
}
|
||||
|
||||
fn joined_developer_input_text(items: &[ResponseItem]) -> String {
|
||||
developer_input_texts(items).join("\n\n")
|
||||
}
|
||||
|
||||
fn user_input_texts(items: &[ResponseItem]) -> Vec<&str> {
|
||||
items
|
||||
.iter()
|
||||
|
|
@ -5637,6 +5902,102 @@ async fn build_initial_context_prepends_model_switch_message() {
|
|||
assert!(text.contains("<model_switch>"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_initial_context_includes_epiphany_state_block_when_present() {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
session
|
||||
.set_epiphany_state(Some(sample_epiphany_state_for_prompt()))
|
||||
.await;
|
||||
|
||||
let initial_context = session.build_initial_context(&turn_context).await;
|
||||
let developer_text = joined_developer_input_text(&initial_context);
|
||||
|
||||
assert!(developer_text.contains("<epiphany_state>"));
|
||||
assert!(developer_text.contains("## Epiphany State"));
|
||||
assert!(developer_text.contains("Keep the prompt path oriented around the real thread state."));
|
||||
assert!(developer_text.contains("`phase2-prompt`"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_initial_context_omits_epiphany_state_block_when_absent() {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
|
||||
let initial_context = session.build_initial_context(&turn_context).await;
|
||||
let developer_text = joined_developer_input_text(&initial_context);
|
||||
|
||||
assert!(!developer_text.contains("<epiphany_state>"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_initial_context_includes_resumed_epiphany_state_block() {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
let turn_context_item = turn_context.to_turn_context_item();
|
||||
let turn_id = turn_context_item
|
||||
.turn_id
|
||||
.clone()
|
||||
.expect("turn context should have turn_id");
|
||||
let epiphany_state = sample_epiphany_state_for_prompt();
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
conversation_id: ThreadId::default(),
|
||||
history: vec![
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: turn_id.clone(),
|
||||
started_at: None,
|
||||
model_context_window: Some(128_000),
|
||||
collaboration_mode_kind: ModeKind::Default,
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
message: "resume the thread".to_string(),
|
||||
images: None,
|
||||
local_images: Vec::new(),
|
||||
text_elements: Vec::new(),
|
||||
})),
|
||||
RolloutItem::TurnContext(turn_context_item),
|
||||
RolloutItem::EpiphanyState(EpiphanyStateItem {
|
||||
turn_id: Some(turn_id),
|
||||
state: epiphany_state,
|
||||
}),
|
||||
],
|
||||
rollout_path: PathBuf::from("/tmp/phase2-resume.jsonl"),
|
||||
}))
|
||||
.await;
|
||||
|
||||
let initial_context = session.build_initial_context(&turn_context).await;
|
||||
let developer_text = joined_developer_input_text(&initial_context);
|
||||
|
||||
assert!(developer_text.contains("<epiphany_state>"));
|
||||
assert!(developer_text.contains("Checkpoint: `phase2-checkpoint` (graph revision 7)"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_initial_context_epiphany_state_snapshot() {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
session
|
||||
.set_epiphany_state(Some(sample_epiphany_state_for_prompt()))
|
||||
.await;
|
||||
|
||||
let initial_context = session.build_initial_context(&turn_context).await;
|
||||
let developer_text = Regex::new(r"C:/Users/Meta/AppData/Local/Temp/\.tmp[^/]+/skills")
|
||||
.expect("valid temp skills root regex")
|
||||
.replace_all(
|
||||
&joined_developer_input_text(&initial_context),
|
||||
"<temp-skills-root>",
|
||||
)
|
||||
.into_owned();
|
||||
|
||||
let mut settings = insta::Settings::clone_current();
|
||||
settings.set_snapshot_path("snapshots");
|
||||
settings.set_prepend_module_to_snapshot(false);
|
||||
settings.bind(|| {
|
||||
insta::assert_snapshot!(
|
||||
"codex_core__session__build_initial_context_epiphany_state",
|
||||
developer_text
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_context_updates_and_set_reference_context_item_persists_full_reinjection_to_rollout()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -100,6 +100,8 @@ pub const PLUGINS_INSTRUCTIONS_OPEN_TAG: &str = "<plugins_instructions>";
|
|||
pub const PLUGINS_INSTRUCTIONS_CLOSE_TAG: &str = "</plugins_instructions>";
|
||||
pub const COLLABORATION_MODE_OPEN_TAG: &str = "<collaboration_mode>";
|
||||
pub const COLLABORATION_MODE_CLOSE_TAG: &str = "</collaboration_mode>";
|
||||
pub const EPIPHANY_STATE_OPEN_TAG: &str = "<epiphany_state>";
|
||||
pub const EPIPHANY_STATE_CLOSE_TAG: &str = "</epiphany_state>";
|
||||
pub const REALTIME_CONVERSATION_OPEN_TAG: &str = "<realtime_conversation>";
|
||||
pub const REALTIME_CONVERSATION_CLOSE_TAG: &str = "</realtime_conversation>";
|
||||
pub const USER_MESSAGE_BEGIN: &str = "## My request for Codex:";
|
||||
|
|
|
|||
Reference in a new issue