feat(review-story): generate stories progressively

This commit is contained in:
Felipe Coury
2026-05-24 13:48:34 -03:00
parent 5e8a5b2c7c
commit f4016e6829
4 changed files with 653 additions and 51 deletions
+1 -1
View File
@@ -167,7 +167,7 @@ Example with notification opt-out:
- `thread/realtime/appendText` — append text input to the active realtime session (experimental); returns `{}`.
- `thread/realtime/stop` — stop the active realtime session for the thread (experimental); returns `{}`.
- `review/start` — kick off Codex’s automated reviewer for a thread; responds like `turn/start` and emits `item/started`/`item/completed` notifications with `enteredReviewMode` and `exitedReviewMode` items, plus a final assistant `agentMessage` containing the review.
- `reviewStory/start` — build a persisted, read-only review story for a concrete source (`uncommittedChanges`, `baseBranch`, or `commit`). Codex collects stable change anchors from the diff, asks a constrained model task to group those anchors into cohesive story steps, validates that every model-referenced anchor exists, and falls back to file-level steps if model generation is unavailable. The response includes the initial `storySnapshot`, and the server emits `reviewStory/snapshot/updated` whenever a snapshot is written. Use `reviewStory/read` to fetch a snapshot by id and `reviewStory/list` to page saved stories for a thread.
- `reviewStory/start` — build a persisted, read-only review story for a concrete source (`uncommittedChanges`, `baseBranch`, or `commit`). Codex collects stable change anchors from the diff, asks a constrained model task to create a validated outline, and returns a `building` snapshot as soon as that ordered outline is useful. Background enrichment fills in richer step explanations in small batches while the server persists and emits full replacement snapshots through `reviewStory/snapshot/updated`; a failed batch leaves the outlined story usable with `partial` status. Empty diffs return `ready` immediately, and outline failures fall back to enrichable file-level steps. Use `reviewStory/read` to fetch the latest snapshot by id and `reviewStory/list` to page saved stories for a thread.
- `command/exec` — run a single command under the server sandbox without starting a thread/turn (handy for utilities and validation).
- `command/exec/write` — write base64-decoded stdin bytes to a running `command/exec` session or close stdin; returns `{}`.
- `command/exec/resize` — resize a running PTY-backed `command/exec` session by `processId`; returns `{}`.
@@ -466,6 +466,7 @@ mod mcp_processor;
mod plugins;
mod process_exec_processor;
mod remote_control_processor;
mod review_story_generation;
mod review_story_processor;
mod search;
mod thread_processor;
@@ -0,0 +1,485 @@
use std::collections::HashMap;
use std::sync::Arc;
use codex_app_server_protocol::ReviewStorySnapshot;
use codex_app_server_protocol::ReviewStorySnapshotStatus;
use codex_app_server_protocol::ReviewStorySnapshotUpdatedNotification;
use codex_app_server_protocol::ReviewStoryStepReadiness;
use codex_app_server_protocol::ServerNotification;
use codex_protocol::protocol::SubAgentSource;
use codex_rollout::state_db::StateDbHandle;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use serde::Deserialize;
use serde_json::json;
use crate::outgoing_message::OutgoingMessageSender;
use super::review_story_processor::snapshot_record;
const ENRICHMENT_BATCH_SIZE: usize = 2;
const ENRICHMENT_CONCURRENCY: usize = 2;
pub(super) fn spawn_enrichment(
thread: Arc<codex_core::CodexThread>,
snapshot: ReviewStorySnapshot,
outline_degraded: bool,
state_db: StateDbHandle,
outgoing: Arc<OutgoingMessageSender>,
) {
tokio::spawn(async move {
run_enrichment(thread, snapshot, outline_degraded, state_db, outgoing).await;
});
}
async fn run_enrichment(
thread: Arc<codex_core::CodexThread>,
mut snapshot: ReviewStorySnapshot,
outline_degraded: bool,
state_db: StateDbHandle,
outgoing: Arc<OutgoingMessageSender>,
) {
let batches = snapshot
.steps
.chunks(/*chunk_size*/ ENRICHMENT_BATCH_SIZE)
.map(|steps| {
steps
.iter()
.map(|step| step.step_id.clone())
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
for pending_batches in batches.chunks(/*chunk_size*/ ENRICHMENT_CONCURRENCY) {
for batch in pending_batches {
mark_batch_enriching(&mut snapshot, batch, outline_degraded);
if !publish_snapshot(&state_db, &outgoing, &mut snapshot).await {
return;
}
}
let mut running = FuturesUnordered::new();
for batch in pending_batches.iter().cloned() {
let thread = Arc::clone(&thread);
let prompt_snapshot = snapshot.clone();
running.push(async move {
let result = generate_batch_enrichment(&thread, &prompt_snapshot, &batch).await;
(batch, result)
});
}
while let Some((batch, result)) = running.next().await {
apply_batch_result(&mut snapshot, &batch, result, outline_degraded);
if !publish_snapshot(&state_db, &outgoing, &mut snapshot).await {
return;
}
}
}
}
async fn publish_snapshot(
state_db: &StateDbHandle,
outgoing: &OutgoingMessageSender,
snapshot: &mut ReviewStorySnapshot,
) -> bool {
snapshot.updated_at = chrono::Utc::now().timestamp();
let record = match snapshot_record(snapshot) {
Ok(record) => record,
Err(err) => {
tracing::warn!("failed to encode review story enrichment snapshot: {err:?}");
return false;
}
};
if let Err(err) = state_db.review_stories().upsert_snapshot(record).await {
tracing::warn!("failed to store review story enrichment snapshot: {err}");
return false;
}
outgoing
.send_server_notification(ServerNotification::ReviewStorySnapshotUpdated(
ReviewStorySnapshotUpdatedNotification {
thread_id: snapshot.thread_id.clone(),
snapshot: snapshot.clone(),
},
))
.await;
true
}
fn mark_batch_enriching(
snapshot: &mut ReviewStorySnapshot,
batch: &[String],
outline_degraded: bool,
) {
for step in &mut snapshot.steps {
if batch.contains(&step.step_id) {
step.readiness = ReviewStoryStepReadiness::Enriching;
step.error = None;
}
}
update_status(snapshot, outline_degraded);
}
fn apply_batch_result(
snapshot: &mut ReviewStorySnapshot,
batch: &[String],
result: Result<ModelEnrichmentOutput, String>,
outline_degraded: bool,
) {
let result = result.and_then(|output| enrichment_by_step_id(batch, output));
match result {
Ok(mut enrichments) => {
for step in &mut snapshot.steps {
if let Some(enrichment) = enrichments.remove(&step.step_id) {
step.goal = enrichment.goal;
step.summary = enrichment.summary;
step.dependency_rationale = enrichment.dependency_rationale;
step.review_focus = enrichment.review_focus;
step.readiness = ReviewStoryStepReadiness::Ready;
step.error = None;
}
}
}
Err(error) => {
for step in &mut snapshot.steps {
if batch.contains(&step.step_id) {
step.readiness = ReviewStoryStepReadiness::Failed;
step.error = Some(error.clone());
}
}
}
}
update_status(snapshot, outline_degraded);
}
fn update_status(snapshot: &mut ReviewStorySnapshot, outline_degraded: bool) {
if snapshot.steps.iter().any(|step| {
matches!(
step.readiness,
ReviewStoryStepReadiness::Outline | ReviewStoryStepReadiness::Enriching
)
}) {
snapshot.status = ReviewStorySnapshotStatus::Building;
} else if outline_degraded
|| snapshot
.steps
.iter()
.any(|step| step.readiness == ReviewStoryStepReadiness::Failed)
{
snapshot.status = ReviewStorySnapshotStatus::Partial;
} else {
snapshot.status = ReviewStorySnapshotStatus::Ready;
}
}
async fn generate_batch_enrichment(
thread: &codex_core::CodexThread,
snapshot: &ReviewStorySnapshot,
batch: &[String],
) -> Result<ModelEnrichmentOutput, String> {
let prompt = enrichment_prompt(snapshot, batch);
match thread
.run_structured_model_task(
prompt,
ENRICHMENT_MODEL_INSTRUCTIONS.to_string(),
enrichment_output_schema(),
SubAgentSource::Other("review_story_enrichment".to_string()),
)
.await
{
Ok(Some(output_text)) => parse_enrichment_output(&output_text)
.map_err(|err| format!("model returned invalid step enrichment: {err}")),
Ok(None) => Err("model did not return step enrichment".to_string()),
Err(err) => Err(format!("failed to enrich story step: {err}")),
}
}
const ENRICHMENT_MODEL_INSTRUCTIONS: &str = r#"You enrich ordered review story steps for code changes.
Write detailed reviewer-facing explanations only for the supplied step ids. Preserve each step's anchored scope: explain its changed evidence, its purpose, and its dependency on nearby steps without inventing files, anchors, or behavior."#;
fn enrichment_prompt(snapshot: &ReviewStorySnapshot, batch: &[String]) -> String {
let anchors = snapshot
.anchors
.iter()
.map(|anchor| (anchor.anchor_id.as_str(), anchor))
.collect::<HashMap<_, _>>();
let mut prompt = format!(
"Enrich the selected steps in this review story.\n\nStory title: {}\nOverview: {}\n\n",
snapshot.title, snapshot.overview
);
for step in snapshot
.steps
.iter()
.filter(|step| batch.contains(&step.step_id))
{
prompt.push_str(&format!(
"---\nstepId: {}\ntitle: {}\noutline goal: {}\nanchorIds: {}\n",
step.step_id,
step.title,
step.goal,
step.anchor_ids.join(", ")
));
for anchor_id in &step.anchor_ids {
if let Some(anchor) = anchors.get(anchor_id.as_str()) {
prompt.push_str(&format!(
"anchorId: {}\nfilePath: {}\ndiff:\n{}\n",
anchor.anchor_id,
anchor.file_path,
truncate_for_prompt(&anchor.diff, /*max_chars*/ 12_000)
));
}
}
}
prompt.push_str(
"\nReturn JSON only, with exactly one enriched object for each requested stepId.",
);
truncate_for_prompt(&prompt, /*max_chars*/ 80_000)
}
fn truncate_for_prompt(text: &str, max_chars: usize) -> String {
if text.chars().count() <= max_chars {
return text.to_string();
}
let mut truncated = text.chars().take(max_chars).collect::<String>();
truncated.push_str("\n[truncated]");
truncated
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModelEnrichmentOutput {
steps: Vec<ModelEnrichmentStep>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModelEnrichmentStep {
step_id: String,
goal: String,
summary: String,
dependency_rationale: String,
review_focus: Vec<String>,
}
fn enrichment_by_step_id(
batch: &[String],
output: ModelEnrichmentOutput,
) -> Result<HashMap<String, ModelEnrichmentStep>, String> {
let mut enrichments = HashMap::new();
for enrichment in output.steps {
if !batch.contains(&enrichment.step_id) {
return Err(format!(
"model referenced unrequested step id: {}",
enrichment.step_id
));
}
let step_id = enrichment.step_id.clone();
if enrichments.insert(step_id.clone(), enrichment).is_some() {
return Err(format!("model returned duplicate step id: {step_id}"));
}
}
if enrichments.len() != batch.len() {
return Err("model omitted one or more requested step ids".to_string());
}
Ok(enrichments)
}
fn enrichment_output_schema() -> serde_json::Value {
json!({
"type": "object",
"additionalProperties": false,
"properties": {
"steps": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"stepId": { "type": "string" },
"goal": { "type": "string" },
"summary": { "type": "string" },
"dependencyRationale": { "type": "string" },
"reviewFocus": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["stepId", "goal", "summary", "dependencyRationale", "reviewFocus"]
}
}
},
"required": ["steps"]
})
}
fn parse_enrichment_output(text: &str) -> Result<ModelEnrichmentOutput, serde_json::Error> {
if let Ok(output) = serde_json::from_str::<ModelEnrichmentOutput>(text) {
return Ok(output);
}
if let (Some(start), Some(end)) = (text.find('{'), text.rfind('}'))
&& start < end
&& let Some(slice) = text.get(start..=end)
{
return serde_json::from_str::<ModelEnrichmentOutput>(slice);
}
serde_json::from_str::<ModelEnrichmentOutput>(text)
}
#[cfg(test)]
mod tests {
use codex_app_server_protocol::ReviewStoryAnchor;
use codex_app_server_protocol::ReviewStoryAnchorKind;
use codex_app_server_protocol::ReviewStoryStep;
use codex_app_server_protocol::ReviewTarget;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn scheduling_changes_only_requested_steps_to_enriching() {
let mut snapshot = sample_snapshot();
mark_batch_enriching(
&mut snapshot,
&["step-1".to_string()],
/*outline_degraded*/ false,
);
assert_eq!(snapshot.status, ReviewStorySnapshotStatus::Building);
assert_eq!(
snapshot.steps[0].readiness,
ReviewStoryStepReadiness::Enriching
);
assert_eq!(
snapshot.steps[1].readiness,
ReviewStoryStepReadiness::Outline
);
}
#[test]
fn successful_batches_merge_without_losing_prior_completion() {
let mut snapshot = sample_snapshot();
mark_batch_enriching(
&mut snapshot,
&["step-1".to_string()],
/*outline_degraded*/ false,
);
mark_batch_enriching(
&mut snapshot,
&["step-2".to_string()],
/*outline_degraded*/ false,
);
apply_batch_result(
&mut snapshot,
&["step-2".to_string()],
Ok(enrichment("step-2", "second rich summary")),
/*outline_degraded*/ false,
);
apply_batch_result(
&mut snapshot,
&["step-1".to_string()],
Ok(enrichment("step-1", "first rich summary")),
/*outline_degraded*/ false,
);
assert_eq!(snapshot.status, ReviewStorySnapshotStatus::Ready);
assert_eq!(snapshot.steps[0].summary, "first rich summary");
assert_eq!(snapshot.steps[1].summary, "second rich summary");
assert_eq!(snapshot.steps[0].readiness, ReviewStoryStepReadiness::Ready);
assert_eq!(snapshot.steps[1].readiness, ReviewStoryStepReadiness::Ready);
}
#[test]
fn failed_or_degraded_enrichment_finishes_partial() {
let mut failed = sample_snapshot();
mark_batch_enriching(
&mut failed,
&["step-1".to_string()],
/*outline_degraded*/ false,
);
apply_batch_result(
&mut failed,
&["step-1".to_string()],
Err("generation failed".to_string()),
/*outline_degraded*/ false,
);
apply_batch_result(
&mut failed,
&["step-2".to_string()],
Ok(enrichment("step-2", "ready")),
/*outline_degraded*/ false,
);
assert_eq!(failed.status, ReviewStorySnapshotStatus::Partial);
assert_eq!(failed.steps[0].readiness, ReviewStoryStepReadiness::Failed);
let mut degraded = sample_snapshot();
apply_batch_result(
&mut degraded,
&["step-1".to_string(), "step-2".to_string()],
Ok(ModelEnrichmentOutput {
steps: vec![
enriched_step("step-1", "first"),
enriched_step("step-2", "second"),
],
}),
/*outline_degraded*/ true,
);
assert_eq!(degraded.status, ReviewStorySnapshotStatus::Partial);
}
fn enrichment(step_id: &str, summary: &str) -> ModelEnrichmentOutput {
ModelEnrichmentOutput {
steps: vec![enriched_step(step_id, summary)],
}
}
fn enriched_step(step_id: &str, summary: &str) -> ModelEnrichmentStep {
ModelEnrichmentStep {
step_id: step_id.to_string(),
goal: format!("goal {step_id}"),
summary: summary.to_string(),
dependency_rationale: "rationale".to_string(),
review_focus: vec!["focus".to_string()],
}
}
fn sample_snapshot() -> ReviewStorySnapshot {
ReviewStorySnapshot {
story_snapshot_id: "story-1".to_string(),
thread_id: "thread-1".to_string(),
title: "Story".to_string(),
overview: "Overview".to_string(),
target: ReviewTarget::UncommittedChanges,
source_fingerprint: "sha256:one".to_string(),
status: ReviewStorySnapshotStatus::Building,
created_at: 1,
updated_at: 1,
previous_story_snapshot_id: None,
stale: false,
steps: vec![step("step-1", /*index*/ 1), step("step-2", /*index*/ 2)],
anchors: vec![ReviewStoryAnchor {
anchor_id: "anchor-1".to_string(),
file_path: "src/lib.rs".to_string(),
change_kind: ReviewStoryAnchorKind::Modified,
summary: "Modified src/lib.rs".to_string(),
diff: "+line".to_string(),
}],
}
}
fn step(step_id: &str, index: u32) -> ReviewStoryStep {
ReviewStoryStep {
step_id: step_id.to_string(),
index,
title: step_id.to_string(),
goal: "outline goal".to_string(),
summary: "outline summary".to_string(),
dependency_rationale: "outline rationale".to_string(),
anchor_ids: vec!["anchor-1".to_string()],
review_focus: vec!["outline focus".to_string()],
readiness: ReviewStoryStepReadiness::Outline,
error: None,
}
}
}
@@ -73,15 +73,15 @@ impl ReviewStoryRequestProcessor {
let state_db = self.require_state_db()?;
let cwd = thread.config_snapshot().await.cwd;
let evidence = collect_evidence(cwd.as_path(), &target).await?;
let model_story = generate_model_story(&thread, &target, &evidence).await;
let model_outline = generate_model_outline(&thread, &target, &evidence).await;
let story_snapshot_id = Uuid::now_v7().to_string();
let now = chrono::Utc::now().timestamp();
let snapshot = build_snapshot(
let (snapshot, outline_degraded) = build_snapshot(
story_snapshot_id.clone(),
thread_id.clone(),
target,
evidence,
model_story,
model_outline,
now,
/*previous_story_snapshot_id*/ None,
);
@@ -101,6 +101,16 @@ impl ReviewStoryRequestProcessor {
))
.await;
if snapshot.status == ReviewStorySnapshotStatus::Building {
super::review_story_generation::spawn_enrichment(
Arc::clone(&thread),
snapshot.clone(),
outline_degraded,
state_db.clone(),
Arc::clone(&self.outgoing),
);
}
let turn = build_story_turn(
format!("review-story-{}", snapshot.story_snapshot_id),
"Create a review story for the selected changes.",
@@ -190,22 +200,22 @@ struct StoryEvidence {
anchors: Vec<ReviewStoryAnchor>,
}
struct ModelStoryResult {
output: Option<ModelReviewStoryOutput>,
struct ModelOutlineResult {
output: Option<ModelReviewStoryOutline>,
error: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModelReviewStoryOutput {
struct ModelReviewStoryOutline {
title: String,
overview: String,
steps: Vec<ModelReviewStoryStep>,
steps: Vec<ModelReviewStoryOutlineStep>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModelReviewStoryStep {
struct ModelReviewStoryOutlineStep {
title: String,
goal: String,
summary: String,
@@ -268,56 +278,59 @@ async fn collect_evidence(
})
}
async fn generate_model_story(
async fn generate_model_outline(
thread: &codex_core::CodexThread,
target: &ReviewTarget,
evidence: &StoryEvidence,
) -> ModelStoryResult {
) -> ModelOutlineResult {
if evidence.anchors.is_empty() {
return ModelStoryResult {
return ModelOutlineResult {
output: None,
error: None,
};
}
let prompt = review_story_prompt(target, evidence);
let schema = review_story_output_schema();
let prompt = review_story_outline_prompt(target, evidence);
let schema = review_story_outline_schema();
match thread
.run_structured_model_task(
prompt,
REVIEW_STORY_MODEL_INSTRUCTIONS.to_string(),
schema,
SubAgentSource::Other("review_story".to_string()),
SubAgentSource::Other("review_story_outline".to_string()),
)
.await
{
Ok(Some(output_text)) => match parse_model_review_story_output(&output_text) {
Ok(output) => ModelStoryResult {
Ok(Some(output_text)) => match parse_model_review_story_outline(&output_text) {
Ok(output) => ModelOutlineResult {
output: Some(output),
error: None,
},
Err(err) => ModelStoryResult {
Err(err) => ModelOutlineResult {
output: None,
error: Some(format!("model returned an invalid review story: {err}")),
error: Some(format!(
"model returned an invalid review story outline: {err}"
)),
},
},
Ok(None) => ModelStoryResult {
Ok(None) => ModelOutlineResult {
output: None,
error: Some("model did not return a review story".to_string()),
error: Some("model did not return a review story outline".to_string()),
},
Err(err) => ModelStoryResult {
Err(err) => ModelOutlineResult {
output: None,
error: Some(format!("failed to generate review story: {err}")),
error: Some(format!("failed to generate review story outline: {err}")),
},
}
}
const REVIEW_STORY_MODEL_INSTRUCTIONS: &str = r#"You create review stories for code changes.
const REVIEW_STORY_MODEL_INSTRUCTIONS: &str = r#"You create review story outlines for code changes.
Group the supplied change anchors into a small sequence of cohesive logic steps. Each step should help a reviewer understand why the change exists, what changed, and how that step depends on earlier steps. Use only the provided anchor ids. Do not invent files, commits, or anchor ids. Prefer semantic dependency order over file order when the evidence supports it."#;
Group the supplied change anchors into a small sequence of cohesive logic steps. Provide concise navigational values for every requested step field; a later enrichment pass will write detailed explanations. Use only the provided anchor ids. Do not invent files, commits, or anchor ids. Prefer semantic dependency order over file order when the evidence supports it."#;
fn review_story_prompt(target: &ReviewTarget, evidence: &StoryEvidence) -> String {
fn review_story_outline_prompt(target: &ReviewTarget, evidence: &StoryEvidence) -> String {
let mut prompt = String::new();
prompt.push_str("Create a dependency-aware review story for these changes.\n\n");
prompt
.push_str("Create a concise dependency-aware review story outline for these changes.\n\n");
prompt.push_str("Target:\n");
prompt.push_str(&target_description(target));
prompt.push_str("\n\nSource fingerprint:\n");
@@ -380,7 +393,7 @@ fn truncate_for_prompt(text: &str, max_chars: usize) -> String {
truncated
}
fn review_story_output_schema() -> serde_json::Value {
fn review_story_outline_schema() -> serde_json::Value {
json!({
"type": "object",
"additionalProperties": false,
@@ -441,19 +454,19 @@ fn review_story_output_schema() -> serde_json::Value {
})
}
fn parse_model_review_story_output(
fn parse_model_review_story_outline(
text: &str,
) -> Result<ModelReviewStoryOutput, serde_json::Error> {
if let Ok(output) = serde_json::from_str::<ModelReviewStoryOutput>(text) {
) -> Result<ModelReviewStoryOutline, serde_json::Error> {
if let Ok(output) = serde_json::from_str::<ModelReviewStoryOutline>(text) {
return Ok(output);
}
if let (Some(start), Some(end)) = (text.find('{'), text.rfind('}'))
&& start < end
&& let Some(slice) = text.get(start..=end)
{
return serde_json::from_str::<ModelReviewStoryOutput>(slice);
return serde_json::from_str::<ModelReviewStoryOutline>(slice);
}
serde_json::from_str::<ModelReviewStoryOutput>(text)
serde_json::from_str::<ModelReviewStoryOutline>(text)
}
async fn git_output(
@@ -560,33 +573,36 @@ fn build_snapshot(
thread_id: String,
target: ReviewTarget,
evidence: StoryEvidence,
model_story: ModelStoryResult,
model_outline: ModelOutlineResult,
created_at: i64,
previous_story_snapshot_id: Option<String>,
) -> ReviewStorySnapshot {
) -> (ReviewStorySnapshot, bool) {
let fallback_title = title_for_target(&target);
let (title, overview, steps, status) = if evidence.anchors.is_empty() {
let (title, overview, steps, status, outline_degraded) = if evidence.anchors.is_empty() {
(
fallback_title,
"No changes were detected for this review story source.".to_string(),
steps_from_anchors(&evidence.anchors),
ReviewStorySnapshotStatus::Ready,
false,
)
} else if let Some(output) = model_story.output {
} else if let Some(output) = model_outline.output {
let (steps, validation_error) = steps_from_model_output(output.steps, &evidence.anchors);
let status = if validation_error.is_some() {
ReviewStorySnapshotStatus::Partial
} else {
ReviewStorySnapshotStatus::Ready
};
let outline_degraded = validation_error.is_some();
let overview = if let Some(error) = validation_error {
format!("{}\n\n{error}", output.overview)
} else {
output.overview
};
(output.title, overview, steps, status)
(
output.title,
overview,
steps,
ReviewStorySnapshotStatus::Building,
outline_degraded,
)
} else {
let overview = model_story.error.map_or_else(
let overview = model_outline.error.map_or_else(
|| {
format!(
"This story groups {} changed file(s) into review steps based on the local change map.",
@@ -599,10 +615,11 @@ fn build_snapshot(
fallback_title,
overview,
steps_from_anchors(&evidence.anchors),
ReviewStorySnapshotStatus::Partial,
ReviewStorySnapshotStatus::Building,
true,
)
};
ReviewStorySnapshot {
let mut snapshot = ReviewStorySnapshot {
story_snapshot_id,
thread_id,
title,
@@ -616,7 +633,13 @@ fn build_snapshot(
stale: false,
steps,
anchors: evidence.anchors,
};
if snapshot.status == ReviewStorySnapshotStatus::Building {
for step in &mut snapshot.steps {
step.readiness = ReviewStoryStepReadiness::Outline;
}
}
(snapshot, outline_degraded)
}
fn title_for_target(target: &ReviewTarget) -> String {
@@ -665,7 +688,7 @@ fn steps_from_anchors(anchors: &[ReviewStoryAnchor]) -> Vec<ReviewStoryStep> {
}
fn steps_from_model_output(
model_steps: Vec<ModelReviewStoryStep>,
model_steps: Vec<ModelReviewStoryOutlineStep>,
anchors: &[ReviewStoryAnchor],
) -> (Vec<ReviewStoryStep>, Option<String>) {
let anchors_by_id = anchors
@@ -798,7 +821,7 @@ fn build_story_turn(turn_id: String, display_text: &str) -> Turn {
}
}
fn snapshot_record(
pub(super) fn snapshot_record(
snapshot: &ReviewStorySnapshot,
) -> Result<ReviewStoryRecord, codex_app_server_protocol::JSONRPCErrorError> {
let target_json = serde_json::to_value(&snapshot.target)
@@ -839,7 +862,7 @@ fn summary_from_record(
})
}
fn status_as_str(status: ReviewStorySnapshotStatus) -> &'static str {
pub(super) fn status_as_str(status: ReviewStorySnapshotStatus) -> &'static str {
match status {
ReviewStorySnapshotStatus::Building => "building",
ReviewStorySnapshotStatus::Ready => "ready",
@@ -914,7 +937,7 @@ new file mode 100644
#[test]
fn model_output_groups_anchors_into_cohesive_steps() {
let anchors = sample_anchors();
let model_steps = vec![ModelReviewStoryStep {
let model_steps = vec![ModelReviewStoryOutlineStep {
title: "Introduce review story state".to_string(),
goal: "Create the storage and protocol foundation.".to_string(),
summary: "Adds reusable state and API shapes for review stories.".to_string(),
@@ -947,7 +970,7 @@ new file mode 100644
#[test]
fn model_output_appends_missing_anchors_for_full_coverage() {
let anchors = sample_anchors();
let model_steps = vec![ModelReviewStoryStep {
let model_steps = vec![ModelReviewStoryOutlineStep {
title: "Add protocol".to_string(),
goal: "Define the API contract.".to_string(),
summary: "Adds the protocol file.".to_string(),
@@ -1001,6 +1024,99 @@ new file mode 100644
);
}
#[test]
fn initial_model_outline_is_a_building_snapshot() {
let evidence = StoryEvidence {
source_fingerprint: "sha256:one".to_string(),
anchors: sample_anchors(),
};
let model_outline = ModelOutlineResult {
output: Some(ModelReviewStoryOutline {
title: "Review story".to_string(),
overview: "Read this in order.".to_string(),
steps: vec![ModelReviewStoryOutlineStep {
title: "Foundation".to_string(),
goal: "Start with the API.".to_string(),
summary: "Outline summary.".to_string(),
dependency_rationale: "It supports later work.".to_string(),
anchor_ids: vec!["anchor-1".to_string(), "anchor-2".to_string()],
review_focus: vec!["Follow the API.".to_string()],
}],
}),
error: None,
};
let (snapshot, degraded) = build_snapshot(
"story-1".to_string(),
"thread-1".to_string(),
ReviewTarget::UncommittedChanges,
evidence,
model_outline,
/*created_at*/ 1,
/*previous_story_snapshot_id*/ None,
);
assert_eq!(snapshot.status, ReviewStorySnapshotStatus::Building);
assert_eq!(
snapshot.steps[0].readiness,
ReviewStoryStepReadiness::Outline
);
assert_eq!(degraded, false);
}
#[test]
fn fallback_outline_remains_enrichable_and_degraded() {
let evidence = StoryEvidence {
source_fingerprint: "sha256:one".to_string(),
anchors: sample_anchors(),
};
let (snapshot, degraded) = build_snapshot(
"story-1".to_string(),
"thread-1".to_string(),
ReviewTarget::UncommittedChanges,
evidence,
ModelOutlineResult {
output: None,
error: Some("outline failed".to_string()),
},
/*created_at*/ 1,
/*previous_story_snapshot_id*/ None,
);
assert_eq!(snapshot.status, ReviewStorySnapshotStatus::Building);
assert!(
snapshot
.steps
.iter()
.all(|step| step.readiness == ReviewStoryStepReadiness::Outline)
);
assert_eq!(degraded, true);
}
#[test]
fn empty_story_is_immediately_ready() {
let (snapshot, degraded) = build_snapshot(
"story-1".to_string(),
"thread-1".to_string(),
ReviewTarget::UncommittedChanges,
StoryEvidence {
source_fingerprint: "sha256:empty".to_string(),
anchors: Vec::new(),
},
ModelOutlineResult {
output: None,
error: None,
},
/*created_at*/ 1,
/*previous_story_snapshot_id*/ None,
);
assert_eq!(snapshot.status, ReviewStorySnapshotStatus::Ready);
assert_eq!(snapshot.steps[0].readiness, ReviewStoryStepReadiness::Ready);
assert_eq!(degraded, false);
}
fn sample_anchors() -> Vec<ReviewStoryAnchor> {
vec![
ReviewStoryAnchor {