Base: codex-main originale (prima del fork aKode)
This commit is contained in:
283
codex-rs/ext/guardian-v3/tests/evidence.rs
Normal file
283
codex-rs/ext/guardian-v3/tests/evidence.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
//! Captured originals preserve attribution, complete contents and a fixed history boundary.
|
||||
|
||||
use codex_context_fragments::AdditionalContextUserFragment;
|
||||
use codex_context_fragments::AnnotatedContent;
|
||||
use codex_context_fragments::ContextualUserFragment;
|
||||
use codex_context_fragments::message_from_parts;
|
||||
use codex_guardian_v3::EvidenceCursor;
|
||||
use codex_guardian_v3::OriginalEvidence;
|
||||
use codex_history::AcceptedFileAudio;
|
||||
use codex_history::CodexHarnessMetadata;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_history::RetainedContextEvent;
|
||||
use codex_history::RetainedUserMessage;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_history::UserInputOrigin;
|
||||
use codex_history::VerifiedAnswer;
|
||||
use codex_history::VerifiedQuestionAnswer;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::ContentItemKind;
|
||||
use codex_protocol::models::ContentItemMetadata;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_state::SqliteConfig;
|
||||
use codex_thread_store::AppendThreadItemsParams;
|
||||
use codex_thread_store::CreateThreadParams;
|
||||
use codex_thread_store::LocalThreadStore;
|
||||
use codex_thread_store::LocalThreadStoreConfig;
|
||||
use codex_thread_store::PersistContext;
|
||||
use codex_thread_store::ThreadPersistenceMetadata;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test]
|
||||
async fn captures_originals_without_generated_context_or_later_appends() -> anyhow::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let owner = ThreadId::new();
|
||||
let store = LocalThreadStore::new(
|
||||
LocalThreadStoreConfig {
|
||||
codex_home: dir.path().to_path_buf(),
|
||||
sqlite: SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into()?),
|
||||
default_model_provider_id: "test-provider".into(),
|
||||
},
|
||||
/*state_db*/ None,
|
||||
);
|
||||
store
|
||||
.create_thread(CreateThreadParams {
|
||||
attached_thread: false,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
session_id: owner.into(),
|
||||
thread_id: owner,
|
||||
extra_config: None,
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
source: SessionSource::Exec,
|
||||
thread_source: None,
|
||||
originator: "test-originator".into(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
multi_agent_version: None,
|
||||
history_mode: ThreadHistoryMode::Paginated,
|
||||
history_base: None,
|
||||
subagent_history_start_ordinal: None,
|
||||
initial_window_id: "window-1".into(),
|
||||
runtime_workspace_roots: None,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(dir.path().to_path_buf()),
|
||||
model_provider: "test-provider".into(),
|
||||
memory_mode: ThreadMemoryMode::Disabled,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let user = ResponseItemEnvelope {
|
||||
item: serde_json::from_value(json!({"type":"message","id":"user-1","role":"user",
|
||||
"content":[{"type":"input_text","text":"é🙂".repeat(15_000)}]}))?,
|
||||
metadata: Some(CodexHarnessMetadata {
|
||||
user_input_order: Some(1),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let assistant = ResponseItemEnvelope::new(serde_json::from_value(json!({
|
||||
"type":"message","id":"assistant-1","role":"assistant",
|
||||
"content":[{"type":"output_text","text":"I will inspect the directory."}]
|
||||
}))?);
|
||||
let call = ResponseItemEnvelope::new(serde_json::from_value(json!({
|
||||
"type":"function_call","id":"call-1","call_id":"call-1","name":"shell","arguments":"{\"cmd\":\"pwd\"}"
|
||||
}))?);
|
||||
let result = ResponseItemEnvelope::new(serde_json::from_value(json!({
|
||||
"type":"function_call_output","call_id":"call-1","output":"/workspace"
|
||||
}))?);
|
||||
let generated = ResponseItemEnvelope::new(ContextualUserFragment::into(
|
||||
AdditionalContextUserFragment::new("environment".into(), "Generated context".into()),
|
||||
));
|
||||
let mut summary = assistant.clone();
|
||||
summary.metadata = Some(CodexHarnessMetadata {
|
||||
compaction_output: true,
|
||||
..Default::default()
|
||||
});
|
||||
let approved_action = r#"The user has manually approved a specific action that was previously `Rejected`.
|
||||
Treat this as approval to perform that exact action in the same context in which it was originally requested.
|
||||
Do not assume this also authorizes similar operations with different payloads.
|
||||
Approved action: {"action":{"command":"write /workspace/report.txt"},"outcome":"allowed"}"#;
|
||||
let approval = ResponseItemEnvelope::new(message_from_parts(
|
||||
"developer",
|
||||
vec![AnnotatedContent::text(
|
||||
approved_action,
|
||||
ContentItemKind("guardian.approved_action".into()),
|
||||
ContentItemMetadata::harness(),
|
||||
)],
|
||||
));
|
||||
// Identical words without the host's approval annotation must not be promoted.
|
||||
let ordinary_developer = ResponseItemEnvelope::new(serde_json::from_value(json!({
|
||||
"type":"message","role":"developer","content":[{"type":"input_text","text":approved_action}]
|
||||
}))?);
|
||||
let answer = RolloutItem::RetainedContext(RetainedContextEvent::VerifiedAnswer {
|
||||
answer: VerifiedAnswer {
|
||||
turn_id: "turn-1".into(),
|
||||
call_id: "question-1".into(),
|
||||
questions: vec![VerifiedQuestionAnswer {
|
||||
question: "May I publish the report?".into(),
|
||||
answer: "Only the draft; do not publish the final report.".into(),
|
||||
}],
|
||||
},
|
||||
acceptance_order: Some(2),
|
||||
});
|
||||
let delivered = RolloutItem::RetainedContext(RetainedContextEvent::DeliveredAssistantMessage {
|
||||
message: RetainedUserMessage {
|
||||
turn_id: "turn-1".into(),
|
||||
message_id: Some("delivered-1".into()),
|
||||
text: "I will write the draft only.".into(),
|
||||
complete: true,
|
||||
origin: UserInputOrigin::User,
|
||||
phase: None,
|
||||
},
|
||||
acceptance_order: 3,
|
||||
});
|
||||
let response =
|
||||
|item: &ResponseItemEnvelope| json!({"type":"response_item","payload":item.item});
|
||||
let expected = [
|
||||
json!({
|
||||
"type":"response_item",
|
||||
"payload":user.item,
|
||||
"metadata":{"client_authored":false,"user_input_order":1}
|
||||
}),
|
||||
response(&assistant),
|
||||
response(&call),
|
||||
response(&result),
|
||||
serde_json::to_value(&answer)?,
|
||||
response(&approval),
|
||||
json!({
|
||||
"type":"response_item",
|
||||
"payload":{
|
||||
"type":"message","id":"delivered-1","role":"assistant",
|
||||
"content":[{"type":"output_text","text":"I will write the draft only."}],
|
||||
"internal_chat_message_metadata_passthrough":{"turn_id":"turn-1"}
|
||||
},
|
||||
"metadata":{
|
||||
"client_authored":false,
|
||||
"delivered_assistant_message":"codex:code-mode-delivery:v1:complete",
|
||||
"user_input_order":3
|
||||
}
|
||||
}),
|
||||
];
|
||||
let mut items = vec![
|
||||
RolloutItem::ResponseItem(user.clone()),
|
||||
RolloutItem::ResponseItem(assistant),
|
||||
RolloutItem::ResponseItem(call),
|
||||
RolloutItem::ResponseItem(result),
|
||||
answer,
|
||||
RolloutItem::ResponseItem(approval),
|
||||
delivered,
|
||||
];
|
||||
let mut old = user.clone();
|
||||
old.item = serde_json::from_value(json!({"type":"message","id":"old","role":"user",
|
||||
"content":[{"type":"input_text","text":"Before board activation"}]}))?;
|
||||
store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: owner,
|
||||
items: vec![RolloutItem::ResponseItem(old)],
|
||||
})
|
||||
.await?;
|
||||
store
|
||||
.persist_thread(owner, PersistContext::Standard)
|
||||
.await?;
|
||||
store.flush_thread(owner).await?;
|
||||
let mut cursor = EvidenceCursor::from_now(&store, owner).await?;
|
||||
assert!(cursor.capture(&store).await?.records().is_empty());
|
||||
|
||||
for item in &mut items {
|
||||
if let RolloutItem::ResponseItem(envelope) = item {
|
||||
envelope
|
||||
.metadata
|
||||
.get_or_insert_default()
|
||||
.sampled_through_sequence = Some(99);
|
||||
}
|
||||
}
|
||||
items.insert(1, RolloutItem::ResponseItem(generated));
|
||||
items.extend([
|
||||
RolloutItem::ResponseItem(summary),
|
||||
RolloutItem::ResponseItem(ordinary_developer),
|
||||
RolloutItem::RetainedContext(RetainedContextEvent::AcceptedFileAudio {
|
||||
evidence: Arc::new(AcceptedFileAudio {
|
||||
turn_id: "turn-1".into(),
|
||||
model: "test-model".into(),
|
||||
provider: "test-provider".into(),
|
||||
file_ids: ["file-audio-1".into()].into(),
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: owner,
|
||||
items,
|
||||
})
|
||||
.await?;
|
||||
store
|
||||
.persist_thread(owner, PersistContext::Standard)
|
||||
.await?;
|
||||
store.flush_thread(owner).await?;
|
||||
let captured = cursor.capture(&store).await?;
|
||||
// Check the serialized board post, independently of the rollout serializer.
|
||||
let board_originals = |records: &[OriginalEvidence]| -> serde_json::Result<Vec<_>> {
|
||||
records
|
||||
.iter()
|
||||
.map(|record| Ok(serde_json::to_value(record)?["original"].take()))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(board_originals(captured.records())?, expected);
|
||||
|
||||
let mut later = user.clone();
|
||||
later.item = serde_json::from_value(json!({"type":"message","id":"user-2","role":"user",
|
||||
"content":[{"type":"input_text","text":"Do not publish."}]}))?;
|
||||
later.metadata = Some(CodexHarnessMetadata {
|
||||
user_input_order: Some(4),
|
||||
..Default::default()
|
||||
});
|
||||
store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: owner,
|
||||
items: vec![RolloutItem::ResponseItem(later.clone())],
|
||||
})
|
||||
.await?;
|
||||
store.flush_thread(owner).await?;
|
||||
// Reads do not acknowledge delivery, and a later append cannot enter the old capture.
|
||||
assert_eq!(cursor.pending(&captured)?.len(), expected.len());
|
||||
cursor.acknowledge(&captured, /*count*/ 2)?;
|
||||
assert_eq!(board_originals(cursor.pending(&captured)?)?, expected[2..]);
|
||||
cursor.acknowledge(&captured, expected.len() - 2)?;
|
||||
assert!(cursor.pending(&captured)?.is_empty());
|
||||
let latest = cursor.capture(&store).await?;
|
||||
assert_eq!(
|
||||
board_originals(latest.records())?,
|
||||
[json!({
|
||||
"type":"response_item",
|
||||
"payload":later.item,
|
||||
"metadata":{"client_authored":false,"user_input_order":4}
|
||||
})]
|
||||
);
|
||||
assert_eq!(captured.records().len(), expected.len());
|
||||
cursor.acknowledge(&latest, /*count*/ 1)?;
|
||||
assert!(cursor.capture(&store).await?.records().is_empty());
|
||||
assert!(cursor.acknowledge(&captured, /*count*/ 0).is_err());
|
||||
|
||||
let mut ambiguous = later;
|
||||
ambiguous.metadata = None;
|
||||
store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: owner,
|
||||
items: vec![RolloutItem::ResponseItem(ambiguous)],
|
||||
})
|
||||
.await?;
|
||||
store.flush_thread(owner).await?;
|
||||
let before = cursor.clone();
|
||||
assert!(cursor.capture(&store).await.is_err());
|
||||
assert_eq!(cursor, before);
|
||||
store.shutdown_thread(owner).await?;
|
||||
Ok(())
|
||||
}
|
||||
330
codex-rs/ext/guardian-v3/tests/housekeeping.rs
Normal file
330
codex-rs/ext/guardian-v3/tests/housekeeping.rs
Normal file
@@ -0,0 +1,330 @@
|
||||
//! Original evidence is routed as data through an isolated runtime into a real board.
|
||||
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
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::EvidenceCursor;
|
||||
use codex_guardian_v3::HOUSEKEEPER_INSTRUCTIONS;
|
||||
use codex_guardian_v3::HOUSEKEEPER_TIMEOUT;
|
||||
use codex_guardian_v3::Housekeeper;
|
||||
use codex_guardian_v3::local_board;
|
||||
use codex_history::CodexHarnessMetadata;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_message_board::AgentMessageBoard;
|
||||
use codex_message_board::ChannelQuery;
|
||||
use codex_message_board::PageRequest;
|
||||
use codex_message_board::PostQuery;
|
||||
use codex_message_board::ReadPostRequest;
|
||||
use codex_message_board::SortDirection;
|
||||
use codex_message_board::UpsertChannelRequest;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::openai_models::TruncationPolicyConfig;
|
||||
use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_state::SqliteConfig;
|
||||
use codex_thread_store::AppendThreadItemsParams;
|
||||
use codex_thread_store::PersistContext;
|
||||
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 pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tokio::time::Instant;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[path = "../../../message-board/tests/common/mod.rs"]
|
||||
mod board_host;
|
||||
|
||||
#[test_case::test_case(false; "successful_writes")]
|
||||
#[test_case::test_case(true; "write_failure")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn routes_captured_originals_and_updates_descriptions(
|
||||
fail_writes: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let server = start_mock_server().await;
|
||||
let input_policy = TruncationPolicyConfig::bytes(/*limit*/ 1024);
|
||||
let test = test_codex()
|
||||
.with_history_mode(ThreadHistoryMode::Paginated)
|
||||
.with_model_info_override("test-gpt-5.1-codex", move |model| {
|
||||
model.auto_review_model_override = Some(model.slug.clone());
|
||||
model.truncation_policy = input_policy;
|
||||
})
|
||||
.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;
|
||||
test.thread_store
|
||||
.persist_thread(owner, PersistContext::Standard)
|
||||
.await?;
|
||||
test.thread_store.flush_thread(owner).await?;
|
||||
let cursor = EvidenceCursor::from_now(test.thread_store.as_ref(), owner).await?;
|
||||
let initial_cursor = cursor.clone();
|
||||
let original = ResponseItemEnvelope {
|
||||
item: serde_json::from_value(json!({"type":"message","id":"msg-policy","role":"user",
|
||||
"content":[{"type":"input_text","text":"Do not publish the release."}]}))?,
|
||||
metadata: Some(CodexHarnessMetadata {
|
||||
user_input_order: Some(1),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
test.thread_store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: owner,
|
||||
items: vec![RolloutItem::ResponseItem(original.clone())],
|
||||
})
|
||||
.await?;
|
||||
test.thread_store
|
||||
.persist_thread(owner, PersistContext::Standard)
|
||||
.await?;
|
||||
test.thread_store.flush_thread(owner).await?;
|
||||
let snapshot = cursor.capture(test.thread_store.as_ref()).await?;
|
||||
assert_eq!(snapshot.records().len(), 1);
|
||||
for user_input_order in 2..=3 {
|
||||
let later = ResponseItemEnvelope {
|
||||
item: serde_json::from_value(
|
||||
json!({"type":"message","id":format!("msg-later-{user_input_order}"),"role":"user",
|
||||
"content":[{"type":"input_text","text":"The later message is outside this capture.".repeat(8)}]}),
|
||||
)?,
|
||||
metadata: Some(CodexHarnessMetadata {
|
||||
user_input_order: Some(user_input_order),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
test.thread_store
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: owner,
|
||||
items: vec![RolloutItem::ResponseItem(later)],
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
test.thread_store.flush_thread(owner).await?;
|
||||
let dir = tempfile::tempdir()?;
|
||||
let host = Arc::new(board_host::Host {
|
||||
clock: AtomicI64::default(),
|
||||
fail_clock: AtomicBool::new(false),
|
||||
agent_path_calls: AtomicUsize::default(),
|
||||
members: [(owner, AgentPath::root())].into(),
|
||||
active: AtomicBool::new(true),
|
||||
fail_notifications: AtomicBool::new(false),
|
||||
notifications: Mutex::default(),
|
||||
});
|
||||
let board = Arc::new(
|
||||
local_board(
|
||||
SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into()?),
|
||||
owner.into(),
|
||||
)
|
||||
.read_write()
|
||||
.open(host.clone())
|
||||
.await?,
|
||||
);
|
||||
board
|
||||
.upsert_channel(
|
||||
owner,
|
||||
UpsertChannelRequest {
|
||||
channel_name: "release".into(),
|
||||
description: "Release procedure".to_owned().try_into()?,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let board_handle: Arc<dyn AgentMessageBoard> = board.clone();
|
||||
let mut housekeeper = Housekeeper::new(board_handle, cursor, input_policy.into())?;
|
||||
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(HOUSEKEEPER_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 response = mount_sse_once(&server, sse(vec![
|
||||
ev_assistant_message("routing", r#"{"routes":[["release","_audit"]],"descriptions":{"release":"Release policy","_audit":""}}"#),
|
||||
ev_completed("routing"),
|
||||
])).await;
|
||||
let deadline = ReviewDeadline::At(Instant::now() + HOUSEKEEPER_TIMEOUT);
|
||||
host.fail_clock.store(fail_writes, Ordering::SeqCst);
|
||||
let routed = housekeeper
|
||||
.route_next(&snapshot, &runtime, deadline, &cancellation)
|
||||
.await;
|
||||
insta::assert_snapshot!(
|
||||
"guardian_housekeeping_originals",
|
||||
context_snapshot::format_request_history_snapshot(
|
||||
"Housekeeper routes captured originals and updates discovery descriptions.",
|
||||
&response.requests(),
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
)
|
||||
);
|
||||
assert_eq!(routed.disposition, SessionDisposition::Reusable);
|
||||
if fail_writes {
|
||||
assert!(routed.result.is_err());
|
||||
assert_eq!(housekeeper.cursor(), &initial_cursor);
|
||||
assert_eq!(housekeeper.cursor().pending(&snapshot)?.len(), 1);
|
||||
spawned.thread.shutdown_and_wait().await?;
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
return Ok(());
|
||||
}
|
||||
assert_eq!(routed.result?, 1);
|
||||
assert_eq!(
|
||||
housekeeper
|
||||
.route_next(&snapshot, &runtime, deadline, &cancellation)
|
||||
.await
|
||||
.result?,
|
||||
0
|
||||
);
|
||||
assert!(housekeeper.cursor().pending(&snapshot)?.is_empty());
|
||||
let next = housekeeper
|
||||
.cursor()
|
||||
.capture(test.thread_store.as_ref())
|
||||
.await?;
|
||||
assert_eq!(next.records().len(), 2);
|
||||
let request = response.single_request();
|
||||
let input = request.inputs_of_type("function_call_output");
|
||||
assert_eq!(input.len(), 1);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
input[0]["output"].as_str().expect("operation input")
|
||||
)?,
|
||||
json!({"catalog":{"release":"Release procedure"},"sources":[serde_json::to_value(&snapshot.records()[0])?]})
|
||||
);
|
||||
assert!(
|
||||
request
|
||||
.message_input_texts("developer")
|
||||
.iter()
|
||||
.any(|text| text.contains(HOUSEKEEPER_INSTRUCTIONS))
|
||||
);
|
||||
assert!(request.message_input_texts("user").is_empty());
|
||||
let channels = board
|
||||
.list_channels(
|
||||
owner,
|
||||
ChannelQuery {
|
||||
query: None,
|
||||
direction: SortDirection::OldestFirst,
|
||||
page: PageRequest::default(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
channels
|
||||
.channels
|
||||
.results
|
||||
.into_iter()
|
||||
.map(|channel| (
|
||||
channel.channel_name,
|
||||
channel.description,
|
||||
channel.message_count
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("release".into(), Some("Release policy".into()), 1),
|
||||
("_audit".into(), Some("".into()), 1)
|
||||
]
|
||||
);
|
||||
for channel in ["release", "_audit"] {
|
||||
let posts = board
|
||||
.search_posts(
|
||||
owner,
|
||||
PostQuery {
|
||||
channel_name: Some(channel.into()),
|
||||
query: None,
|
||||
after_message_id: None,
|
||||
author: None,
|
||||
page: PageRequest::default(),
|
||||
max_chars_per_post: NonZeroU32::MAX,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(posts.results.len(), 1);
|
||||
let post = board
|
||||
.read_post(
|
||||
owner,
|
||||
ReadPostRequest {
|
||||
message_id: posts.results[0].metadata.message_id,
|
||||
offset_chars: 0,
|
||||
limit_chars: NonZeroU32::MAX,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&post.text)?,
|
||||
serde_json::to_value(&snapshot.records()[0])?
|
||||
);
|
||||
}
|
||||
// The next capture needs two batches; each request retains the full original
|
||||
// and current catalog within the selected model's tool-output budget.
|
||||
let catalog = json!({"release":"Release policy","_audit":""});
|
||||
assert!(
|
||||
serde_json::to_string(&json!({"catalog":catalog,"sources":next.records()}))?.len()
|
||||
> input_policy.limit as usize
|
||||
);
|
||||
for (index, source) in next.records().iter().enumerate() {
|
||||
let response = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_assistant_message(
|
||||
"routing-later",
|
||||
r#"{"routes":[["release"]],"descriptions":{"release":"Release policy"}}"#,
|
||||
),
|
||||
ev_completed("routing-later"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let routed = housekeeper
|
||||
.route_next(&next, &runtime, deadline, &cancellation)
|
||||
.await;
|
||||
assert_eq!(routed.disposition, SessionDisposition::Reusable);
|
||||
assert_eq!(routed.result?, 1);
|
||||
assert_eq!(
|
||||
housekeeper.cursor().pending(&next)?.len(),
|
||||
next.records().len() - index - 1
|
||||
);
|
||||
let request = response.single_request();
|
||||
let input = request.inputs_of_type("function_call_output");
|
||||
let input = input.last().expect("latest operation input")["output"]
|
||||
.as_str()
|
||||
.expect("operation input");
|
||||
assert!(input.len() <= input_policy.limit as usize);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(input)?,
|
||||
json!({"catalog":catalog,"sources":[source]})
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
host.notifications
|
||||
.lock()
|
||||
.expect("notifications lock")
|
||||
.is_empty()
|
||||
);
|
||||
spawned.thread.shutdown_and_wait().await?;
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
Ok(())
|
||||
}
|
||||
198
codex-rs/ext/guardian-v3/tests/retrieval.rs
Normal file
198
codex-rs/ext/guardian-v3/tests/retrieval.rs
Normal file
@@ -0,0 +1,198 @@
|
||||
//! Reviewer tools search routed posts from their capture, including unsubscribed channels.
|
||||
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
use codex_guardian_v3::RetrievalBinding;
|
||||
use codex_guardian_v3::local_board;
|
||||
use codex_message_board::AgentMessageBoard;
|
||||
use codex_message_board::AppendRequest;
|
||||
use codex_message_board::PageRequest;
|
||||
use codex_message_board::PostDestination;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::openai_models::TruncationPolicyConfig;
|
||||
use codex_state::SqliteConfig;
|
||||
use codex_tools::ToolCall;
|
||||
use codex_tools::ToolCallSource;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolPayload;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
#[path = "../../../message-board/tests/common/mod.rs"]
|
||||
mod board_host;
|
||||
#[path = "retrieval/delivery.rs"]
|
||||
mod delivery;
|
||||
#[path = "retrieval/evidence_board.rs"]
|
||||
mod evidence_board;
|
||||
#[path = "retrieval/planning.rs"]
|
||||
mod planning;
|
||||
#[path = "retrieval/selection.rs"]
|
||||
mod selection;
|
||||
|
||||
fn retrieval_host(
|
||||
members: impl IntoIterator<Item = (ThreadId, AgentPath)>,
|
||||
) -> Arc<board_host::Host> {
|
||||
Arc::new(board_host::Host {
|
||||
clock: AtomicI64::default(),
|
||||
fail_clock: AtomicBool::default(),
|
||||
agent_path_calls: AtomicUsize::default(),
|
||||
members: members.into_iter().collect(),
|
||||
active: AtomicBool::new(true),
|
||||
fail_notifications: AtomicBool::default(),
|
||||
notifications: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn searches_unsubscribed_guardian_posts_only_through_the_review_cutoff() -> anyhow::Result<()>
|
||||
{
|
||||
let owner = ThreadId::new();
|
||||
let dir = tempfile::tempdir()?;
|
||||
let host = retrieval_host([(owner, AgentPath::root())]);
|
||||
let board = local_board(
|
||||
SqliteConfig::new_for_testing(dir.path().to_path_buf().try_into()?),
|
||||
owner.into(),
|
||||
)
|
||||
.read_write()
|
||||
.open(host)
|
||||
.await?;
|
||||
let routed = |ordinal: u64, text: &str| {
|
||||
json!({
|
||||
"id": {"ordinal": ordinal},
|
||||
"original": {"type": "response_item", "payload": {
|
||||
"type": "message", "role": "user",
|
||||
"content": [{"type": "input_text", "text": text}]
|
||||
}}
|
||||
})
|
||||
.to_string()
|
||||
};
|
||||
let earlier = routed(1, r#"Do not publish "prod" from C:\work\draft."#);
|
||||
let first = board
|
||||
.append(
|
||||
owner,
|
||||
AppendRequest {
|
||||
request_id: "first".into(),
|
||||
destination: PostDestination::NewChannel("release".into()),
|
||||
text: earlier.clone(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let call = json!({
|
||||
"id": {"ordinal": 2},
|
||||
"original": {"type": "response_item", "payload": {
|
||||
"type": "function_call",
|
||||
"name": "exec_command",
|
||||
"call_id": "call-2",
|
||||
"arguments": r#"{"recipient":"Alice","cmd":"publish \"prod\" from C:\\work\\draft","paths":["C:\\tmp","C:\\work\\plan-\u00c9"]}"#
|
||||
}}
|
||||
})
|
||||
.to_string();
|
||||
let second = board
|
||||
.append(
|
||||
owner,
|
||||
AppendRequest {
|
||||
request_id: "second".into(),
|
||||
destination: PostDestination::Channel("release".into()),
|
||||
text: call.clone(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let view = board.read_view(owner).await?;
|
||||
let binding = RetrievalBinding::new(view.as_ref(), owner, AgentPath::root())?;
|
||||
board
|
||||
.append(
|
||||
owner,
|
||||
AppendRequest {
|
||||
request_id: "later".into(),
|
||||
destination: PostDestination::Channel("release".into()),
|
||||
text: routed(3, r#"Publish "prod" from C:\work\draft now."#),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
board
|
||||
.subscribed_channels(owner, PageRequest::default())
|
||||
.await?
|
||||
.results
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let tools = binding.tools();
|
||||
assert_eq!(
|
||||
tools
|
||||
.iter()
|
||||
.map(|tool| tool.tool_name())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"get_channels",
|
||||
"list_threads",
|
||||
"search_posts",
|
||||
"read_thread",
|
||||
"read_post"
|
||||
]
|
||||
.map(|name| ToolName::namespaced("guardian_board", name))
|
||||
);
|
||||
let tool_name = ToolName::namespaced("guardian_board", "search_posts");
|
||||
let search = tools
|
||||
.iter()
|
||||
.find(|tool| tool.tool_name() == tool_name)
|
||||
.expect("board search");
|
||||
let both = [(&second, &call), (&first, &earlier)];
|
||||
for (query, expected) in [
|
||||
(r#"publish "prod""#, both.as_slice()),
|
||||
(r"C:\work\draft", both.as_slice()),
|
||||
(r"C:\work\plan-é", &both[..1]),
|
||||
("plan-é", &both[..1]),
|
||||
(r#""recipient":"Alice""#, &both[..1]),
|
||||
(r#""type":"function_call""#, &both[..1]),
|
||||
("\t", &both[..0]),
|
||||
] {
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: json!({"query":query}).to_string(),
|
||||
};
|
||||
let result = search
|
||||
.handle(ToolCall {
|
||||
turn_id: "review".into(),
|
||||
call_id: "search".into(),
|
||||
tool_name: tool_name.clone(),
|
||||
model: "test".into(),
|
||||
codex_turn_metadata: None,
|
||||
truncation_policy: TruncationPolicyConfig::bytes(/*limit*/ 8_000).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: payload.clone(),
|
||||
})
|
||||
.await?;
|
||||
let output = result.code_mode_result(&payload);
|
||||
assert_eq!(result.log_output(), output.to_string());
|
||||
let page: codex_message_board::Page<codex_message_board::PostPreview> =
|
||||
serde_json::from_value(output)?;
|
||||
assert_eq!(
|
||||
page,
|
||||
codex_message_board::Page {
|
||||
results: expected
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|(metadata, text)| codex_message_board::PostPreview {
|
||||
metadata: metadata.clone(),
|
||||
text_preview: text.clone(),
|
||||
n_chars: text.chars().count(),
|
||||
truncated: false,
|
||||
})
|
||||
.collect(),
|
||||
next_cursor: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
246
codex-rs/ext/guardian-v3/tests/retrieval/delivery.rs
Normal file
246
codex-rs/ext/guardian-v3/tests/retrieval/delivery.rs
Normal 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(())
|
||||
}
|
||||
101
codex-rs/ext/guardian-v3/tests/retrieval/evidence_board.rs
Normal file
101
codex-rs/ext/guardian-v3/tests/retrieval/evidence_board.rs
Normal 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(),
|
||||
),
|
||||
}
|
||||
}
|
||||
102
codex-rs/ext/guardian-v3/tests/retrieval/planning.rs
Normal file
102
codex-rs/ext/guardian-v3/tests/retrieval/planning.rs
Normal 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)?)
|
||||
}
|
||||
380
codex-rs/ext/guardian-v3/tests/retrieval/selection.rs
Normal file
380
codex-rs/ext/guardian-v3/tests/retrieval/selection.rs
Normal 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(())
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: ext/guardian-v3/tests/housekeeping.rs
|
||||
expression: 'context_snapshot::format_request_history_snapshot("Housekeeper routes captured originals and updates discovery descriptions.", &response.requests(), &ContextSnapshotOptions::default().rewrite_known_segments(),)'
|
||||
---
|
||||
Scenario: Housekeeper routes captured originals and updates discovery descriptions.
|
||||
|
||||
## Window 1
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
01:message/developer:
|
||||
<PERMISSIONS_INSTRUCTIONS>
|
||||
02:function_call_output/guardian.guardian_housekeeper_input:{"catalog":{"release":"Release procedure"},"sources":[{"id":{"ordinal":1},"original":{"type":"response_i...a":{"client_authored":false,"user_input_order":1}}}]} [hash=6fdbbcb4f9522d4c]
|
||||
Reference in New Issue
Block a user