Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,246 @@
//! Whole originals enter a real retained conversation without scheduling inference.
use codex_analytics::GuardianReviewSessionKind;
use codex_core::guardian_review::prepare_review_prewarm;
use codex_extension_api::SessionIsolation;
use codex_extension_api::ToolPolicy;
use codex_guardian_v3::DeliveryState;
use codex_message_board::AgentMessageBoard;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::HistoryPosition;
use codex_protocol::protocol::InternalSessionSource;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TruncationPolicy;
use codex_protocol::turn_input::TurnInputRequest;
use codex_protocol::user_input::UserInput;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::responses::*;
use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeSet;
use std::sync::atomic::Ordering;
use crate::evidence_board::EvidenceBoard;
use crate::evidence_board::routed_original;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn delivers_ordered_originals_once_after_admission_and_keeps_older_channel_evidence()
-> anyhow::Result<()> {
core_test_support::skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let test = test_codex()
.with_model_info_override("test-gpt-5.1-codex", |model| {
model.auto_review_model_override = Some(model.slug.clone());
model.truncation_policy = TruncationPolicyConfig::bytes(/*limit*/ 64 * 1024);
})
.with_config(|config| {
config.approvals_reviewer = ApprovalsReviewer::User;
config.include_environment_context = false;
})
.build_with_auto_env(&server)
.await?;
let owner = test.session_configured.thread_id;
let prepared = prepare_review_prewarm(&test.codex).await?;
let (mut options, _state) = prepared
.thread_options(GuardianReviewSessionKind::TrunkNew, /*snapshot*/ None)
.await;
options.config.base_instructions = Some("Inspect the supplied original evidence.".into());
options.session_source = Some(SessionSource::Internal(InternalSessionSource::Guardian));
options
.thread_extension_init
.insert(SessionIsolation::Isolated);
options.thread_extension_init.insert(ToolPolicy {
allowed_tools: Some(Vec::new()),
..Default::default()
});
let spawned = test.thread_manager.start_thread(options).await?;
let reviewer = spawned.thread_id;
let board = EvidenceBoard::new(owner, reviewer, &["a", "b", "older", "large"]).await?;
let large = "é".repeat(20_001);
// The housekeeper can route one source to several channels and post out of source order.
for (ordinal, channel, output) in [
(3, "a", "two"),
(2, "b", "one"),
(2, "a", "one"),
(1, "older", "older"),
(4, "large", large.as_str()),
] {
board.append(ordinal, channel, output).await?;
}
let evidence = board.writer.read_view(reviewer).await?;
let cutoff = HistoryPosition {
thread_id: owner,
end_ordinal_exclusive: 6,
end_byte_offset: 64 * 1024,
};
let mut state = DeliveryState::new(reviewer, owner.into());
let before_admission = state.clone();
let selected = BTreeSet::from(["a".into(), "b".into()]);
let mut plan = state.plan(evidence.as_ref(), &selected, cutoff).await?;
let small = TruncationPolicy::Bytes(160);
assert!(
plan.deliver(small, |_| async { anyhow::bail!("admission unavailable") })
.await
.is_err()
);
drop(plan);
assert_eq!(state, before_admission);
let mut plan = state.plan(evidence.as_ref(), &selected, cutoff).await?;
let response = mount_sse_once(
&server,
sse(vec![
ev_assistant_message("review", "Evidence received."),
ev_completed("review"),
]),
)
.await;
let reads = board.host.agent_path_calls.load(Ordering::SeqCst);
for _ in 0..2 {
assert_eq!(
plan.deliver(small, |items| async {
Ok(spawned.thread.inject_response_items(items).await?)
})
.await?,
1
);
}
// Two admissions share one page of board reads.
assert_eq!(
board.host.agent_path_calls.load(Ordering::SeqCst) - reads,
1
);
assert!(response.requests().is_empty());
spawned
.thread
.start_turn_if_idle(TurnInputRequest::user_input(vec![UserInput::Text {
text: "Assess.".into(),
text_elements: Vec::new(),
}]))
.await?;
wait_for_event(&spawned.thread, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
insta::assert_snapshot!(context_snapshot::format_request_history_snapshot(
"Selected originals arrive once in source order before a later reviewer turn.", &response.requests(),
&ContextSnapshotOptions::default().rewrite_known_segments(),
), @r###"
Scenario: Selected originals arrive once in source order before a later reviewer turn.
## Window 1
-- request 1 (turn) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer:
<PERMISSIONS_INSTRUCTIONS>
02:function_call_output/guardian.guardian_original_evidence:{"sources":[{"id":{"ordinal":2},"original":{"type":"response_item","payload":{"type":"function_call_output","output":"one"}}}]}
03:function_call_output/guardian.guardian_original_evidence:{"sources":[{"id":{"ordinal":3},"original":{"type":"response_item","payload":{"type":"function_call_output","output":"two"}}}]}
04:message/user:
Assess.
"###);
// A later subscription can add an older source without resetting delivered progress.
let mut older = state
.plan(evidence.as_ref(), &BTreeSet::from(["older".into()]), cutoff)
.await?;
assert_eq!(
older
.deliver(small, |items| async {
Ok(spawned.thread.inject_response_items(items).await?)
})
.await?,
1
);
let checkpoint = state.clone();
// A whole source larger than the admission budget can be retried with more room.
let mut long = state
.plan(evidence.as_ref(), &BTreeSet::from(["large".into()]), cutoff)
.await?;
assert!(
long.deliver(small, |_| async {
panic!("oversized originals must not reach admission")
})
.await
.is_err()
);
drop(long);
assert_eq!(state, checkpoint);
let mut long = state
.plan(evidence.as_ref(), &BTreeSet::from(["large".into()]), cutoff)
.await?;
assert_eq!(
long.deliver(TruncationPolicy::Bytes(64 * 1024), |items| async {
Ok(spawned.thread.inject_response_items(items).await?)
})
.await?,
1
);
// A backdated post and a newly routed copy both arrive after the board capture.
board.host.clock.store(-1000, Ordering::SeqCst);
for (ordinal, channel, output) in [(5, "a", "late"), (3, "b", "two")] {
board.append(ordinal, channel, output).await?;
}
let mut repeated = state.plan(evidence.as_ref(), &selected, cutoff).await?;
assert_eq!(
repeated
.deliver(small, |_| async {
panic!("the old view has no additional evidence")
})
.await?,
0
);
let changed = board.writer.read_view(reviewer).await?;
let mut fresh = state.plan(changed.as_ref(), &selected, cutoff).await?;
assert_eq!(
fresh
.deliver(small, |items| async {
Ok(spawned.thread.inject_response_items(items).await?)
})
.await?,
1
);
assert_eq!(
fresh
.deliver(small, |_| async {
panic!("the duplicate source must not be admitted again")
})
.await?,
0
);
let history = spawned.thread.conversation_history_snapshot().await;
let mut delivered = Vec::new();
for item in history.items() {
if let ResponseItem::FunctionCallOutput {
name: Some(name),
output,
..
} = item
&& name == "guardian_original_evidence"
{
let text = output
.text_content()
.ok_or_else(|| anyhow::anyhow!("expected evidence text"))?;
delivered.push(serde_json::from_str::<serde_json::Value>(text)?);
}
}
let expected = [
(2, "one"),
(3, "two"),
(1, "older"),
(4, large.as_str()),
(5, "late"),
]
.map(|(ordinal, output)| json!({"sources":[routed_original(ordinal, output)]}));
assert_eq!(delivered.as_slice(), expected.as_slice());
assert_eq!(response.requests().len(), 1);
spawned.thread.shutdown_and_wait().await?;
test.codex.shutdown_and_wait().await?;
Ok(())
}

View File

@@ -0,0 +1,101 @@
//! A Guardian board seeded with the same routed originals the housekeeper writes.
use crate::board_host::Host;
use crate::retrieval_host;
use codex_guardian_v3::EvidenceId;
use codex_guardian_v3::local_board;
use codex_history::RolloutItem;
use codex_message_board::AppendRequest;
use codex_message_board::LocalAgentMessageBoard;
use codex_message_board::PostDestination;
use codex_message_board::UpsertChannelRequest;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseItem;
use codex_state::SqliteConfig;
use serde::Serialize;
use std::sync::Arc;
use tempfile::TempDir;
pub(super) struct EvidenceBoard {
pub host: Arc<Host>,
pub writer: LocalAgentMessageBoard,
owner: ThreadId,
_directory: TempDir,
}
impl EvidenceBoard {
pub async fn new(
owner: ThreadId,
reviewer: ThreadId,
channels: &[&str],
) -> anyhow::Result<Self> {
let path = AgentPath::root()
.join("reviewer")
.map_err(anyhow::Error::msg)?;
let host = retrieval_host([(owner, AgentPath::root()), (reviewer, path)]);
let directory = tempfile::tempdir()?;
let writer = local_board(
SqliteConfig::new_for_testing(directory.path().to_path_buf().try_into()?),
owner.into(),
)
.read_write()
.open(host.clone())
.await?;
for &channel in channels {
writer
.upsert_channel(
owner,
UpsertChannelRequest {
channel_name: channel.into(),
description: String::new().try_into()?,
},
)
.await?;
}
Ok(Self {
host,
writer,
owner,
_directory: directory,
})
}
pub async fn append(&self, ordinal: u64, channel: &str, output: &str) -> anyhow::Result<()> {
self.writer
.append(
self.owner,
AppendRequest {
request_id: serde_json::to_string(&(ordinal, channel))?,
destination: PostDestination::Channel(channel.into()),
text: serde_json::to_string(&routed_original(ordinal, output))?,
},
)
.await?;
Ok(())
}
}
pub(super) fn routed_original(ordinal: u64, output: &str) -> impl Serialize {
// Preserve the housekeeper's field order as well as the original wire contents.
#[derive(Serialize)]
struct RoutedSource {
id: EvidenceId,
original: RolloutItem,
}
RoutedSource {
id: EvidenceId { ordinal },
original: RolloutItem::ResponseItem(
ResponseItem::FunctionCallOutput {
id: None,
call_id: None,
name: None,
namespace: None,
output: FunctionCallOutputPayload::from_text(output.to_owned()),
internal_chat_message_metadata_passthrough: None,
}
.into(),
),
}
}

View File

@@ -0,0 +1,102 @@
//! Planning reads only the selected channels and respects both the board and history cutoffs.
use crate::evidence_board::EvidenceBoard;
use crate::evidence_board::routed_original;
use anyhow::Context;
use codex_guardian_v3::DeliveryPlan;
use codex_guardian_v3::DeliveryState;
use codex_message_board::AgentMessageBoard;
use codex_message_board::PageRequest;
use codex_protocol::ThreadId;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::HistoryPosition;
use codex_protocol::protocol::TruncationPolicy;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::BTreeSet;
use std::sync::atomic::Ordering;
#[tokio::test]
async fn plans_unique_originals_in_source_order_from_a_fixed_view() -> anyhow::Result<()> {
let owner = ThreadId::new();
let reviewer = ThreadId::new();
let board = EvidenceBoard::new(owner, reviewer, &["a", "b", "unselected"]).await?;
board.append(/*ordinal*/ 3, "a", "three").await?;
board.append(/*ordinal*/ 1, "a", "one").await?;
board.append(/*ordinal*/ 1, "b", "one").await?;
board
.append(/*ordinal*/ 0, "unselected", "unselected")
.await?;
let view = board.writer.read_view(reviewer).await?;
board.host.clock.store(-1000, Ordering::SeqCst);
board.append(/*ordinal*/ 4, "b", "after capture").await?;
let cutoff = HistoryPosition {
thread_id: owner,
end_ordinal_exclusive: 4,
end_byte_offset: 64 * 1024,
};
let selected = BTreeSet::from(["a".into(), "b".into()]);
let mut state = DeliveryState::new(reviewer, owner.into());
let reads = board.host.agent_path_calls.load(Ordering::SeqCst);
let mut plan = state.plan(view.as_ref(), &selected, cutoff).await?;
// One short ID page per selected channel completes the scan.
assert_eq!(
board.host.agent_path_calls.load(Ordering::SeqCst) - reads,
2
);
assert_eq!(
admit_batch(&mut plan).await?,
json!({"sources": [
routed_original(/*ordinal*/ 1, "one"),
routed_original(/*ordinal*/ 3, "three"),
]}),
);
let later = board.writer.read_view(reviewer).await?;
assert!(state.plan(later.as_ref(), &selected, cutoff).await.is_err());
Ok(())
}
#[tokio::test]
async fn plans_across_storage_pages_in_reverse_insertion_order() -> anyhow::Result<()> {
let owner = ThreadId::new();
let reviewer = ThreadId::new();
let board = EvidenceBoard::new(owner, reviewer, &["a"]).await?;
let count = u64::from(PageRequest::default().limit.get()) + 1;
for ordinal in (0..count).rev() {
board.append(ordinal, "a", "next review").await?;
}
let view = board.writer.read_view(reviewer).await?;
let selected = BTreeSet::from(["a".into()]);
let cutoff = HistoryPosition {
thread_id: owner,
end_ordinal_exclusive: count,
end_byte_offset: 64 * 1024,
};
let mut state = DeliveryState::new(reviewer, owner.into());
let mut plan = state.plan(view.as_ref(), &selected, cutoff).await?;
let reads = board.host.agent_path_calls.load(Ordering::SeqCst);
let expected: Vec<_> = (0..count)
.map(|ordinal| routed_original(ordinal, "next review"))
.collect();
assert_eq!(admit_batch(&mut plan).await?, json!({"sources": expected}));
assert_eq!(
board.host.agent_path_calls.load(Ordering::SeqCst) - reads,
2
);
Ok(())
}
async fn admit_batch(plan: &mut DeliveryPlan<'_>) -> anyhow::Result<Value> {
let mut batch = Vec::new();
plan.deliver(TruncationPolicy::Bytes(64 * 1024), |items| {
batch = items;
std::future::ready(Ok(()))
})
.await?;
let [ResponseItem::FunctionCallOutput { output, .. }] = batch.as_slice() else {
anyhow::bail!("expected a single evidence batch");
};
let text = output.text_content().context("expected evidence text")?;
Ok(serde_json::from_str(text)?)
}

View File

@@ -0,0 +1,380 @@
//! Reviewer tools and model-driven selection share a fixed Guardian catalog.
use codex_analytics::GuardianReviewSessionKind;
use codex_core::guardian_review::prepare_review_prewarm;
use codex_extension_api::SessionIsolation;
use codex_extension_api::ToolPolicy;
use codex_guardian_reviewer::ReviewDeadline;
use codex_guardian_reviewer::SessionDisposition;
use codex_guardian_v3::CHANNEL_SELECTION_INSTRUCTIONS;
use codex_guardian_v3::DeliveryState;
use codex_guardian_v3::RetrievalBinding;
use codex_guardian_v3::ReviewerSubscriptions;
use codex_guardian_v3::local_board;
use codex_message_board::AgentMessageBoard;
use codex_message_board::AppendRequest;
use codex_message_board::LocalBoard;
use codex_message_board::PostDestination;
use codex_message_board::SubscriptionChange::Subscribe;
use codex_message_board::SubscriptionRequest;
use codex_message_board::SubscriptionState;
use codex_message_board::SubscriptionTarget;
use codex_message_board::UpsertChannelRequest;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::protocol::HistoryPosition;
use codex_protocol::protocol::InternalSessionSource;
use codex_protocol::protocol::SessionSource;
use codex_state::SqliteConfig;
use codex_tools::ToolCall;
use codex_tools::ToolCallSource;
use codex_tools::ToolName;
use codex_tools::ToolPayload;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::context_snapshot::SnapshotEntry;
use core_test_support::responses::*;
use core_test_support::test_codex::test_codex;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use crate::retrieval_host;
#[tokio::test]
async fn subscription_tools_only_change_the_caller_and_return_captured_post_ids()
-> anyhow::Result<()> {
let policy = TruncationPolicyConfig::bytes(/*limit*/ 1024);
let owner = ThreadId::new();
let reviewer = ThreadId::new();
let path = AgentPath::root()
.join("reviewer")
.map_err(anyhow::Error::msg)?;
let host = retrieval_host([(owner, AgentPath::root()), (reviewer, path.clone())]);
let dir = tempfile::tempdir()?;
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into()?);
let agent_board = LocalBoard::new(sqlite.clone(), owner.into())
.read_only()
.open(host.clone())
.await?;
// All three reviewer entry points must reject the ordinary board, even for the same root.
let agent_view = agent_board.read_view(reviewer).await?;
assert!(RetrievalBinding::new(agent_view.as_ref(), reviewer, path.clone()).is_err());
let cutoff = HistoryPosition {
thread_id: owner,
end_ordinal_exclusive: 0,
end_byte_offset: 0,
};
assert!(
DeliveryState::new(reviewer, owner.into())
.plan(agent_view.as_ref(), &BTreeSet::new(), cutoff)
.await
.is_err()
);
assert!(
ReviewerSubscriptions::capture(Arc::new(agent_board), reviewer, path.clone())
.await
.is_err()
);
let storage = local_board(sqlite, owner.into());
let writer = storage.read_write().open(host.clone()).await?;
let original = writer
.append(
owner,
AppendRequest {
request_id: "original".into(),
destination: PostDestination::NewChannel("release".into()),
text: "Original".into(),
},
)
.await?;
let board: Arc<dyn AgentMessageBoard> = Arc::new(storage.read_only().open(host.clone()).await?);
board
.set_subscription(
owner,
SubscriptionRequest {
target: SubscriptionTarget::Channel("release".into()),
change: Subscribe,
target_agent: None,
},
)
.await?;
let subscriptions =
Arc::new(ReviewerSubscriptions::capture(Arc::clone(&board), reviewer, path.clone()).await?);
writer
.upsert_channel(
owner,
UpsertChannelRequest {
channel_name: "later".into(),
description: "Later channel".to_owned().try_into()?,
},
)
.await?;
let later = writer
.append(
owner,
AppendRequest {
request_id: "later".into(),
destination: PostDestination::Channel("release".into()),
text: "Later evidence".into(),
},
)
.await?;
assert_ne!(original.message_id, later.message_id);
// Tool calls reuse the real backend but return only the captured catalog boundary.
let tools = subscriptions.tools(Some("guardian"), "Guardian evidence");
for (name, arguments, succeeds) in [
("subscribe", json!({"channel_name":"release"}), true),
("unsubscribe", json!({"channel_name":"release"}), true),
("subscribe", json!({"channel_name":"release"}), true),
("subscribe", json!({"channel_name":"later"}), false),
(
"unsubscribe",
json!({"channel_name":"release","target_agent":"/"}),
false,
),
] {
let tool = tools
.iter()
.find(|tool| tool.tool_name().name == name && tool.exposure().is_direct())
.ok_or_else(|| anyhow::anyhow!("missing direct subscription tool {name}"))?;
let call = ToolCall {
turn_id: "review".into(),
call_id: name.into(),
tool_name: ToolName::namespaced("guardian", name),
model: "test".into(),
codex_turn_metadata: None,
truncation_policy: policy.into(),
source: ToolCallSource::Direct,
conversation_history: Default::default(),
turn_item_emitter: Arc::new(codex_tools::NoopTurnItemEmitter),
attachment_store: Arc::new(codex_attachment_store::InlineAttachmentStore),
ephemeral: false,
environments: Vec::new(),
payload: ToolPayload::Function {
arguments: arguments.to_string(),
},
};
let result = tool.handle(call.clone()).await;
if succeeds {
let result = result?;
let response = result.code_mode_result(&call.payload);
assert_eq!(result.log_output(), response.to_string());
let output: SubscriptionState = serde_json::from_value(response)?;
assert_eq!(
output,
SubscriptionState {
channel_name: "release".into(),
thread_id: None,
target_agent: path.clone(),
enabled: name == "subscribe",
last_message_id: Some(original.message_id),
}
);
if name == "unsubscribe" {
assert!(subscriptions.channels().await?.is_empty());
}
} else {
assert!(result.is_err());
}
}
assert_eq!(
subscriptions.channels().await?,
BTreeSet::from(["release".into()])
);
assert_eq!(
board
.subscribed_channels(owner, Default::default())
.await?
.results,
vec!["release".to_owned()]
);
assert!(
host.notifications
.lock()
.map_err(|_| anyhow::anyhow!("notifications poisoned"))?
.is_empty()
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn preparation_commits_only_valid_selections_from_the_captured_catalog() -> anyhow::Result<()>
{
core_test_support::skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let policy = TruncationPolicyConfig::bytes(/*limit*/ 1024);
let test = test_codex()
.with_model_info_override("test-gpt-5.1-codex", move |model| {
model.auto_review_model_override = Some(model.slug.clone());
model.truncation_policy = policy;
})
.with_config(|config| {
config.approvals_reviewer = ApprovalsReviewer::User;
config.include_environment_context = false;
})
.build_with_auto_env(&server)
.await?;
let prepared = prepare_review_prewarm(&test.codex).await?;
let key = prepared.reuse_key(/*previous*/ None);
let (mut options, state) = prepared
.thread_options(GuardianReviewSessionKind::TrunkNew, /*snapshot*/ None)
.await;
options.config.base_instructions = Some(CHANNEL_SELECTION_INSTRUCTIONS.into());
options.session_source = Some(SessionSource::Internal(InternalSessionSource::Guardian));
options
.thread_extension_init
.insert(SessionIsolation::Isolated);
options.thread_extension_init.insert(ToolPolicy {
allowed_tools: Some(Vec::new()),
..Default::default()
});
let spawned = test.thread_manager.start_thread(options).await?;
let cancellation = CancellationToken::new();
let runtime = prepared
.bind_thread(&spawned.thread, key, state, cancellation.clone())
.await;
let owner = test.session_configured.thread_id;
let reviewer = spawned.thread_id;
let path = AgentPath::root()
.join("reviewer")
.map_err(anyhow::Error::msg)?;
let host = retrieval_host([(owner, AgentPath::root()), (reviewer, path.clone())]);
let dir = tempfile::tempdir()?;
let sqlite = SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into()?);
let storage = local_board(sqlite, owner.into());
let writer = storage.read_write().open(host.clone()).await?;
for (name, description) in [("build", "Build"), ("release", "Release policy")] {
writer
.upsert_channel(
owner,
UpsertChannelRequest {
channel_name: name.into(),
description: description.to_owned().try_into()?,
},
)
.await?;
}
let board: Arc<dyn AgentMessageBoard> = Arc::new(storage.read_only().open(host.clone()).await?);
writer
.set_subscriptions(owner, &BTreeMap::from([("release", Subscribe)]))
.await?;
board
.set_subscriptions(reviewer, &BTreeMap::from([("build", Subscribe)]))
.await?;
let subscriptions =
Arc::new(ReviewerSubscriptions::capture(Arc::clone(&board), reviewer, path.clone()).await?);
// A newer channel can gain a subscription after capture, before this selection commits.
writer
.upsert_channel(
owner,
UpsertChannelRequest {
channel_name: "later".into(),
description: "Later channel".to_owned().try_into()?,
},
)
.await?;
board
.set_subscriptions(reviewer, &BTreeMap::from([("later", Subscribe)]))
.await?;
let response = mount_sse_once(
&server,
sse(vec![
ev_assistant_message("selection", r#"{"channels":["release"]}"#),
ev_completed("selection"),
]),
)
.await;
let selected = subscriptions
.prepare(
&runtime,
"Publish?",
policy.into(),
ReviewDeadline::Unlimited,
&cancellation,
)
.await;
assert_eq!(selected.disposition, SessionDisposition::Reusable);
let expected = BTreeSet::from(["release".into()]);
assert_eq!(selected.result?, expected);
assert_eq!(
board
.subscribed_channels(reviewer, Default::default())
.await?
.results,
vec!["later".to_owned(), "release".to_owned()]
);
assert_eq!(
board
.subscribed_channels(owner, Default::default())
.await?
.results,
vec!["release".to_owned()]
);
assert_eq!(subscriptions.channels().await?, expected);
let mut request = response.single_request().body_json();
for item in request["input"].as_array_mut().expect("request input") {
if let Some(Value::String(output)) = item.get_mut("output") {
*output = context_snapshot::normalize_json_lines(output);
}
}
insta::assert_snapshot!(context_snapshot::format_context_snapshot(
"Reviewer replaces a previous subscription with the relevant channel.",
&[SnapshotEntry::body(&request)], &ContextSnapshotOptions::default().rewrite_known_segments(),
), @r###"
Scenario: Reviewer replaces a previous subscription with the relevant channel.
## Window 1
-- request 1 (request) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer:
<PERMISSIONS_INSTRUCTIONS>
02:function_call_output/guardian.guardian_channel_selection_input:{"catalog":{"build":"Build","release":"Release policy"},"subscriptions":["build"],"task":"Publish?"}
"###);
let cancelled = CancellationToken::new();
cancelled.cancel();
let stopped = subscriptions
.prepare(
&runtime,
"Publish?",
policy.into(),
ReviewDeadline::Unlimited,
&cancelled,
)
.await;
assert!(stopped.result.is_err());
assert_eq!(stopped.disposition, SessionDisposition::Reusable);
assert_eq!(response.requests().len(), 1);
assert_eq!(subscriptions.channels().await?, expected);
let invalid = mount_sse_once(
&server,
sse(vec![
ev_assistant_message("invalid", r#"{"channels":["build","later"]}"#),
ev_completed("invalid"),
]),
)
.await;
let selected = subscriptions
.prepare(
&runtime,
"Publish?",
policy.into(),
ReviewDeadline::Unlimited,
&cancellation,
)
.await;
assert_eq!(selected.disposition, SessionDisposition::Rollback);
assert!(selected.result.is_err());
assert_eq!(subscriptions.channels().await?, expected);
assert_eq!(invalid.requests().len(), 1);
spawned.thread.shutdown_and_wait().await?;
test.codex.shutdown_and_wait().await?;
Ok(())
}