use crate::agent::message_router::{self, AgentJob, MessageKind};
use crate::agent::{chat_request, role_tool_specs, run_default_agent};
use crate::prompt::{load_prompt, substitute};
use crate::providers::selection::ProviderSelection;
use crate::retry::FailureClass;
use crate::tools::analyze::{
AnalystFindings, Claim, RoundMember, VerificationResult, VerificationTarget,
await_round_members, dispatch_claim_verifiers, escape_fences, extract_query_telemetry,
extract_query_telemetry_from_history, load_analyst_angles, max_confidence, normalize_claim,
round_timeout,
};
use crate::tools::build_async_result_envelope;
use crate::{ChatMessage, ChatRequest, ChatRequestMeta, Role, ToolSpec, Workspace};
use anyhow::Result;
use futures_util::FutureExt;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fmt::Write as _;
use std::path::Path;
use std::time::{Duration, Instant};
const RESEARCH_MAX_ANALYSTS: usize = 30;
const DECOMPOSE_FAN_OUT: usize = 2;
const GAP_ROUND_WIDTHS: &[usize] = &[4, 3, 2];
const ANSWER_MIN_BYTES: usize = 10 * 1024;
const ANSWER_MAX_BYTES: usize = 20 * 1024;
const ANSWER_LIST_CAP: usize = 25;
const ANSWER_OPEN_CAP: usize = 10;
const ANSWER_LINE_MAX_BYTES: usize = 400;
const GAP_EXTRACTION_FAILED: &str = "gap extraction failed — remaining gaps unknown";
const PLAN_MERGE_FAILED: &str =
"plan merge failed — using all valid decomposition plans, fitted to the run's allowance";
const CLAIM_ANNOTATION_FAILED: &str = "claim annotation failed — all new claims treated as novel";
const CONFIRM_FAILED: &str =
"annotation link confirmation failed — mutating links treated as weak/unconfirmed";
const PLAN_LOST_MARKER: &str = "the plan was lost from the checkpoint — the answer is built from the \
evidence gathered so far";
const WORKER_MIN_REMAINING: Duration = Duration::from_mins(30);
const DEFAULT_WRAP_UP_TIMEOUT_SECS: u64 = 5 * 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
enum ResearchStage {
#[default]
Decompose,
Round1,
GapRounds,
#[serde(alias = "verification")]
Synthesis,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct ResearchState {
stage: ResearchStage,
plan: Option<MergedPlan>,
gap_list: Option<GapList>,
acc: AccumulatedEvidence,
ledger: QueryLedger,
markers: Vec<String>,
gap_outcome: GapRoundsOutcome,
budget_spent: usize,
round_index: usize,
verification: Vec<VerificationResult>,
#[serde(skip)]
commands: Vec<String>,
#[serde(skip)]
seen_commands: std::collections::HashSet<String>,
#[serde(default)]
worker_rounds_done: Vec<usize>,
#[serde(default)]
examined: Vec<usize>,
#[serde(skip)]
worker_reports: Vec<String>,
}
impl ResearchState {
async fn load(job_id: &str) -> Self {
let row = crate::session::store()
.conn
.query_optional(
"SELECT state FROM research_jobs WHERE id = ?1",
crate::db::params![job_id],
|r| r.get::<String>(0),
)
.await
.ok()
.flatten();
let Some(json) = row else {
return Self::default();
};
if json.trim().is_empty() || json == "{}" {
return Self::default();
}
match serde_json::from_str::<ResearchState>(&json) {
Ok(mut s) => {
s.acc.rebuild_keys();
let run_root = crate::research_cleanup::run_root_path(job_id);
s.commands = crate::research_cleanup::read_command_dump(&run_root).await;
s.seen_commands = s.commands.iter().cloned().collect();
s.worker_reports = crate::research_cleanup::read_worker_reports(&run_root).await;
s
}
Err(e) => {
tracing::warn!(job = %job_id, error = %e, "Research state unreadable — fresh run");
Self::default()
}
}
}
async fn save(&self, job_id: &str) {
let json = serde_json::to_string(self).unwrap_or_default();
let now = crate::db::now();
let conn = &crate::session::store().conn;
let tx = match conn.begin_tx().await {
Ok(tx) => tx,
Err(e) => {
tracing::warn!(job = %job_id, error = %e, "Research checkpoint: failed to begin transaction");
return;
}
};
let outcome: Result<()> = async {
tx.execute(
"UPDATE research_jobs SET state = ?1 WHERE id = ?2",
crate::db::params![json, job_id],
)
.await?;
tx.execute(
"UPDATE jobs SET status = ?1, updated_at = ?2 WHERE id = ?3",
crate::db::params![crate::jobs::RowStatus::Launched.as_str(), now, job_id],
)
.await?;
Ok(())
}
.await;
match outcome {
Ok(()) => {
if let Err(e) = tx.commit().await {
tracing::warn!(job = %job_id, error = %e, "Research checkpoint: failed to commit");
}
}
Err(e) => {
tracing::warn!(job = %job_id, error = %e, "Research checkpoint failed — state not persisted");
let _ = tx.rollback().await;
}
}
}
async fn capture_round(&mut self, job_id: &str, agent_ids: &[String], run_root: &Path) {
let fresh = crate::research_cleanup::collect_agent_shell_commands(agent_ids).await;
for cmd in fresh {
if self.seen_commands.insert(cmd.clone()) {
self.commands.push(cmd);
}
}
crate::research_cleanup::cap_command_dump(
&mut self.commands,
crate::research_cleanup::COMMAND_DUMP_CAP_BYTES,
);
self.seen_commands = self.commands.iter().cloned().collect();
crate::research_cleanup::write_command_dump(run_root, job_id, &self.commands).await;
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SubQuestion {
question: String,
evidence_needed: String,
risk: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct DecompositionPlan {
sub_questions: Vec<SubQuestion>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MergedSubQuestion {
from_id: usize,
#[serde(default)]
also_ids: Vec<usize>,
#[serde(default)]
question: String,
#[serde(default)]
evidence_needed: String,
#[serde(default)]
risk: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct DroppedSubQuestion {
id: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MergedPlan {
sub_questions: Vec<MergedSubQuestion>,
dropped: Vec<DroppedSubQuestion>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Gap {
#[serde(rename = "type")]
kind: String,
item: String,
traces_to: usize,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
struct GapList {
gaps: Vec<Gap>,
}
#[derive(Debug, Clone, Deserialize)]
struct AnswerabilityCheck {
answerable: bool,
reason: String,
}
#[derive(Debug)]
struct ResearchBudget {
spent: usize,
cap: usize,
}
impl ResearchBudget {
fn new(cap: usize) -> Self {
Self { spent: 0, cap }
}
fn try_reserve(&mut self, n: usize) -> Result<(), String> {
if self.spent + n > self.cap {
return Err(format!(
"research analyst budget exhausted ({}/{})",
self.spent + n,
self.cap
));
}
self.spent += n;
Ok(())
}
fn is_exhausted(&self) -> bool {
self.spent >= self.cap
}
}
fn sub_question_slots(sq: &MergedSubQuestion) -> usize {
1 + usize::from(sq.risk == "high")
}
fn plan_slot_cost(plan: &MergedPlan) -> usize {
plan.sub_questions.iter().map(sub_question_slots).sum()
}
fn plan_slot_reserve() -> usize {
crate::tools::analyze::VERIFY_MAX_ANALYSTS + GAP_ROUND_WIDTHS.iter().sum::<usize>()
}
fn plan_slot_budget(budget: &ResearchBudget) -> usize {
budget
.cap
.saturating_sub(budget.spent)
.saturating_sub(plan_slot_reserve())
}
fn fit_plan_to_slots(plan: &mut MergedPlan, max_slots: usize) {
while plan_slot_cost(plan) > max_slots && plan.sub_questions.len() > 1 {
let mut fitted = Vec::with_capacity(plan.sub_questions.len().div_ceil(2));
let mut items = std::mem::take(&mut plan.sub_questions).into_iter();
while let Some(first) = items.next() {
match items.next() {
Some(second) => fitted.push(merge_directions(first, second)),
None => fitted.push(first),
}
}
plan.sub_questions = fitted;
}
}
fn fold_text(
question: &mut String,
evidence: &mut String,
risk: &mut String,
other_question: &str,
other_evidence: &str,
other_risk: &str,
) {
question.push_str("; ");
question.push_str(other_question.trim_end_matches('.'));
evidence.push_str("; ");
evidence.push_str(other_evidence.trim_end_matches('.'));
*risk = max_confidence(risk, other_risk);
}
fn merge_directions(mut first: MergedSubQuestion, second: MergedSubQuestion) -> MergedSubQuestion {
fold_text(
&mut first.question,
&mut first.evidence_needed,
&mut first.risk,
&second.question,
&second.evidence_needed,
&second.risk,
);
first.also_ids.push(second.from_id);
first.also_ids.extend(second.also_ids);
first
}
fn plan_prefix(costs: &[usize], slots: usize) -> (usize, usize) {
let mut spent = 0usize;
for (i, &cost) in costs.iter().enumerate() {
if spent + cost > slots {
return (i, spent);
}
spent += cost;
}
(costs.len(), spent)
}
pub(crate) fn dispatch_deep_analysis(ws: &Workspace, question: &str, caller_role: Role) -> String {
let ws = ws.clone();
let question = question.to_string();
let user_name = crate::agent::tool_user_name();
let channel = crate::agent::tool_channel();
let custom = crate::agent::tool_delegation_launch();
let job_id = crate::generate_id();
let ack = format!(
"Deep analysis dispatched (job {job_id}). A compact answer will arrive when the run \
completes, with the full detail delivered alongside it."
);
tokio::spawn(async move {
let run = std::panic::AssertUnwindSafe(async {
dispatch_durable_research(
&ws,
&question,
caller_role,
user_name.clone(),
channel.clone(),
&job_id,
custom.clone(),
)
.await
})
.catch_unwind()
.await;
let envelope = match run {
Ok(Some(envelope)) => envelope,
Ok(None) => {
tracing::info!(
"Deep analysis run ended without delivery (aborted or manually cancelled)"
);
return;
}
Err(panic) => {
let panic = crate::util::panic_message(&*panic);
tracing::error!(panic = %panic, "deep analysis dispatch panicked");
AgentJob {
content: build_async_research_message(
&job_id,
&Err(anyhow::anyhow!("deep analysis dispatch panicked: {panic}")),
),
workspace_name: ws.name.clone(),
user_name,
channel,
kind: MessageKind::ResearchResult,
role: caller_role.for_launch(custom.as_ref()),
reply_target: None,
pending_job_id: Some(job_id),
originating_workspace: None,
custom_role: custom,
reply_to_custom: None,
urgent: false,
extract: None,
}
}
};
message_router::route(&crate::jobs::envelope_target(&envelope), envelope);
});
ack
}
async fn dispatch_durable_research(
ws: &Workspace,
question: &str,
caller_role: Role,
user_name: String,
channel: String,
job_id: &str,
custom: Option<crate::Launch>,
) -> Option<AgentJob> {
let _cancel_guard = crate::round_cancel::register(job_id, None);
let caller_role = caller_role.for_launch(custom.as_ref());
let spawn = async {
crate::jobs::spawn_job(
&crate::session::store().conn,
job_id,
question,
&ws.name,
&user_name,
&channel,
caller_role,
&[],
&crate::jobs::SpawnChild::Research,
None,
None,
custom.as_ref(),
)
.await
};
let spawn_out = spawn.await;
let spawned = spawn_out.is_ok();
let exit = match spawn_out {
Ok(()) => run_deep_research(ws, question, job_id, false).await,
Err(e) => ResearchExit::Terminal(Err(e)),
};
let result = match exit {
ResearchExit::Aborted => {
tracing::info!(
job = %job_id,
"Research run aborted by shutdown/drain — resumes at next boot"
);
return None;
}
ResearchExit::Cancelled => {
tracing::info!(
job = %job_id,
"Research run manually cancelled — permanent stop, nothing delivered"
);
hand_off_cancelled_or_warn(job_id, ws, question).await;
return None;
}
ResearchExit::Terminal(result) => result,
};
terminalize_research(
job_id,
ws,
&result,
caller_role,
question,
&user_name,
&channel,
spawned,
custom,
)
.await
}
struct ResearchOutput {
answer: String,
detail: String,
}
async fn write_terminalization_artifacts(
job_id: &str,
answer: &str,
detail: &str,
state: &ResearchState,
) -> String {
let answer = match crate::research_cleanup::write_detail_md(job_id, detail).await {
Some(detail_path) => format!("{answer}{}", detail_reference(&detail_path)),
None => answer.to_string(),
};
crate::research_cleanup::write_results_md(job_id, &answer).await;
let run_root = crate::research_cleanup::ensure_run_root(job_id).await;
crate::research_cleanup::write_command_dump(&run_root, job_id, &state.commands).await;
answer
}
#[expect(clippy::too_many_arguments)]
async fn terminalize_research(
job_id: &str,
ws: &Workspace,
result: &anyhow::Result<ResearchOutput>,
caller_role: Role,
question: &str,
user_name: &str,
channel: &str,
spawned: bool,
custom: Option<crate::Launch>,
) -> Option<AgentJob> {
if crate::round_cancel::is_cancelled(job_id) {
tracing::info!(job = %job_id, "Research terminalization suppressed by manual cancel");
hand_off_cancelled_or_warn(job_id, ws, question).await;
return None;
}
let delivered = match result {
Ok(out) => {
let answer = if spawned {
let state = ResearchState::load(job_id).await;
write_terminalization_artifacts(job_id, &out.answer, &out.detail, &state).await
} else {
out.answer.clone()
};
build_async_research_message(job_id, &Ok(answer))
}
Err(e) => {
let delivered = build_async_research_message(job_id, &Err(anyhow::anyhow!("{e:#}")));
if spawned {
let state = ResearchState::load(job_id).await;
write_terminalization_artifacts(job_id, &delivered, "", &state).await;
}
delivered
}
};
let envelope = crate::jobs::complete_durable_job(
job_id,
delivered,
MessageKind::ResearchResult,
caller_role,
user_name,
channel,
&ws.name,
custom,
)
.await;
if crate::round_cancel::is_cancelled(job_id) {
tracing::info!(job = %job_id, "Research completion suppressed by manual cancel — not routed");
hand_off_cancelled_or_warn(job_id, ws, question).await;
return None;
}
if spawned
&& let Err(e) =
crate::research_cleanup::dispatch_research_cleanup(job_id, question, ws).await
{
tracing::warn!(
job = %job_id,
error = %e,
"Research cleanup dispatch failed — run folder left for the periodic temp cleaner"
);
}
Some(envelope)
}
async fn hand_off_cancelled_or_warn(job_id: &str, ws: &Workspace, question: &str) {
if let Err(e) = crate::research_cancel::hand_off_cancelled_run(job_id, ws, question).await {
tracing::warn!(job = %job_id, error = %e, "cancelled-run cleanup handoff failed — rows stay for boot resume");
}
}
pub(crate) async fn resume_research_run(job_id: &str, ws: &Workspace) {
let _cancel_guard = crate::round_cancel::register(job_id, None);
let Some((caller, caller_role)) = crate::jobs::resume_job_preamble(
&crate::session::store().conn,
job_id,
"Research resume",
"Research resume",
)
.await
else {
return;
};
let custom = caller.custom_launch.as_deref().cloned();
let result = match run_deep_research(ws, &caller.task, job_id, true).await {
ResearchExit::Aborted => {
tracing::info!(
job = %job_id,
"Research resume aborted after run — job stays for next boot",
);
return;
}
ResearchExit::Cancelled => {
tracing::info!(
job = %job_id,
"Research resume manually cancelled — permanent stop, nothing delivered",
);
hand_off_cancelled_or_warn(job_id, ws, &caller.task).await;
return;
}
ResearchExit::Terminal(result) => result,
};
let Some(envelope) = terminalize_research(
job_id,
ws,
&result,
caller_role,
&caller.task,
&caller.user_name,
&caller.channel,
true,
custom,
)
.await
else {
return;
};
crate::agent::message_router::route(&crate::jobs::envelope_target(&envelope), envelope);
}
fn build_async_research_message(job_id: &str, answer: &anyhow::Result<String>) -> String {
build_async_result_envelope(job_id, answer, "analyze-tool-result", None)
}
#[derive(Debug, Default)]
struct EvidenceRound {
urls: Vec<String>,
claims: Vec<Claim>,
unanswered: Vec<String>,
queries: usize,
repeat_queries: usize,
raw_reports: Vec<String>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct AccumulatedEvidence {
urls: HashSet<String>,
claims: Vec<Claim>,
unanswered: Vec<String>,
#[serde(skip)]
unanswered_keys: HashSet<String>,
raw_reports: Vec<String>,
weak: WeakLinks,
}
impl AccumulatedEvidence {
fn rebuild_keys(&mut self) {
self.unanswered_keys = self
.unanswered
.iter()
.filter_map(|u| {
let key = crate::tools::analyze::normalize_claim(u);
(!key.is_empty()).then_some(key)
})
.collect();
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct WeakLinks {
duplicates: Vec<(usize, usize)>,
contradictions: Vec<(usize, usize)>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ClaimAnnotation {
new_id: usize,
verdict: String,
existing_id: Option<usize>,
contradiction: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct AnnotationPass {
annotations: Vec<ClaimAnnotation>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfirmLink {
new_id: usize,
verdict: String,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfirmPass {
links: Vec<ConfirmLink>,
}
enum ConfirmOutcome {
Passed(ConfirmPass),
Failed,
}
impl AccumulatedEvidence {
fn absorb(&mut self, round: &EvidenceRound) -> (usize, Vec<Claim>) {
let novel_urls = round
.urls
.iter()
.filter(|u| self.urls.insert((*u).clone()))
.count();
for u in &round.unanswered {
let key = normalize_claim(u);
if !key.is_empty() && self.unanswered_keys.insert(key) {
self.unanswered.push(u.clone());
}
}
for r in &round.raw_reports {
if !self.raw_reports.contains(r) {
self.raw_reports.push(r.clone());
}
}
(novel_urls, round.claims.clone())
}
fn apply_annotations(
&mut self,
pass: &AnnotationPass,
pending: &[Claim],
confirm: &ConfirmOutcome,
) -> usize {
let confirmed: HashSet<usize> = match confirm {
ConfirmOutcome::Passed(p) => p
.links
.iter()
.filter(|l| l.verdict == "confirm")
.map(|l| l.new_id)
.collect(),
ConfirmOutcome::Failed => HashSet::new(),
};
let mut novel = 0usize;
for a in &pass.annotations {
let pending_claim = &pending[a.new_id];
match a.verdict.as_str() {
"novel" => {
self.claims.push(pending_claim.clone());
novel += 1;
}
"duplicate" => {
let existing_id = a.existing_id.expect("duplicate cites an existing claim");
if confirmed.contains(&a.new_id) {
let existing = &mut self.claims[existing_id];
existing.confidence =
max_confidence(&existing.confidence, &pending_claim.confidence);
for c in &pending_claim.contradictions {
if !existing.contradictions.contains(c) {
existing.contradictions.push(c.clone());
}
}
let mut merged: Vec<String> = existing
.source
.split("; ")
.filter(|s| !s.trim().is_empty())
.map(|s| s.trim().to_string())
.collect();
for s in pending_claim.source.split("; ") {
let s = s.trim();
if !s.is_empty() && !merged.iter().any(|m| m == s) {
merged.push(s.to_string());
}
}
existing.source = merged.join("; ");
} else {
let id = self.claims.len();
self.claims.push(pending_claim.clone());
self.weak.duplicates.push((id, existing_id));
}
}
"contradicts" => {
let existing_id = a.existing_id.expect("contradicts cites an existing claim");
let note = a.contradiction.as_deref().unwrap_or_default();
let existing = &mut self.claims[existing_id];
if !existing.contradictions.iter().any(|c| c == note) {
existing.contradictions.push(note.to_string());
}
let mut new_claim = pending_claim.clone();
if !new_claim
.contradictions
.iter()
.any(|c| c == &existing.claim)
{
new_claim.contradictions.push(existing.claim.clone());
}
let id = self.claims.len();
self.claims.push(new_claim);
novel += 1;
if !confirmed.contains(&a.new_id) {
self.weak.contradictions.push((id, existing_id));
}
}
_ => unreachable!("validator guarantees the verdict vocabulary"),
}
}
novel
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct QueryLedger {
queries: HashSet<String>,
}
impl QueryLedger {
fn register(&mut self, query: &str) -> bool {
let norm = normalize_claim(query);
!norm.is_empty() && self.queries.insert(norm)
}
fn render(&self) -> String {
if self.queries.is_empty() {
return "none yet".to_string();
}
let mut v: Vec<String> = self.queries.iter().cloned().collect();
v.sort();
v.join("\n")
}
}
#[derive(Debug, Default)]
struct RunStats {
tool_calls: usize,
searches: usize,
repeat_queries: usize,
failed_analysts: usize,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct GapRoundsOutcome {
abstention: Option<String>,
unresolved: Vec<String>,
rounds_dispatched: usize,
incomplete: Option<String>,
}
#[derive(Clone)]
struct WrapUpEntry {
agent_id: String,
params: ChatRequest,
}
struct WrapUpPrepared {
params: ChatRequest,
history: Vec<ChatMessage>,
}
fn wrap_up_timeout() -> Duration {
crate::util::env_duration_secs("MAHBOT_WRAP_UP_TIMEOUT_SECS", DEFAULT_WRAP_UP_TIMEOUT_SECS)
}
fn research_params(
ws: &Workspace,
purpose: &'static str,
agent_id: String,
tool_specs: Option<Vec<ToolSpec>>,
) -> ChatRequest {
let mut request = chat_request(Role::Analyst, tool_specs, Vec::new());
request.meta = Some(ChatRequestMeta {
purpose,
agent_id,
role: Role::Analyst.as_str().to_string(),
workspace: ws.name.clone(),
ticket_id: None,
});
request
}
fn wrap_up_params(ws: &Workspace, agent_id: &str, tool_specs: Vec<ToolSpec>) -> ChatRequest {
research_params(
ws,
"research_wrap_up",
agent_id.to_string(),
Some(tool_specs),
)
}
fn research_call_guard(
kind: &'static str,
ws_name: &str,
run_key: &str,
run_lifetime: bool,
question: &str,
) -> crate::agent::registry::NonAgentCallGuard {
crate::agent::registry::NON_AGENT_CALLS.register(
kind,
ws_name,
Some(crate::agent::registry::ParentKey::Research(
run_key.to_string(),
)),
run_lifetime,
Some(question.to_string()),
)
}
async fn wrap_up_timed_out(
ws: &Workspace,
timed_out: Vec<WrapUpEntry>,
ledger: &mut QueryLedger,
run_stats: &mut RunStats,
run_key: &str,
question: &str,
) -> Vec<AnalystFindings> {
if timed_out.is_empty() || crate::shutdown::aborting() {
return Vec::new();
}
let stage_deadline = std::time::Instant::now() + wrap_up_timeout();
let mut prepared = Vec::new();
for entry in timed_out {
if crate::shutdown::aborting() {
break;
}
let history = crate::session::store().load(&entry.agent_id).await;
let (tool_calls, searches, queries) = extract_query_telemetry_from_history(&history);
run_stats.tool_calls += tool_calls;
run_stats.searches += searches;
for q in &queries {
if !ledger.register(q) {
run_stats.repeat_queries += 1;
}
}
let has_success = session_has_successful_tool_result(&history);
if has_success {
let stored = crate::session::store().get_provider(&entry.agent_id).await;
let mut params = entry.params;
ProviderSelection::resolve(¶ms.model, stored.as_ref()).pin(&mut params);
prepared.push(WrapUpPrepared { params, history });
}
}
if prepared.is_empty() || crate::shutdown::aborting() {
return Vec::new();
}
let _wrap_up_call = research_call_guard("research_wrap_up", &ws.name, run_key, false, question);
let wrap_up_prompt = load_prompt("research/wrap_up.md");
let handles: Vec<_> = prepared
.into_iter()
.map(|p| {
let wrap_up_prompt = wrap_up_prompt.clone();
tokio::spawn(async move {
let mut messages = p.history;
messages.push(ChatMessage::user(&wrap_up_prompt));
crate::agent::extraction::retry_extract_structured_scoped::<AnalystFindings>(
&messages,
"",
&p.params,
None,
Some(&crate::retry::RetryPolicy::comment()),
)
.await
.ok()
})
})
.collect();
await_wrap_up_batch(handles, stage_deadline)
.await
.into_iter()
.flatten()
.filter(|f| !f.claims.is_empty() || !f.unanswered.is_empty())
.collect()
}
fn session_has_successful_tool_result(history: &[ChatMessage]) -> bool {
history.iter().any(|m| {
matches!(
crate::session::decode_native_history_message(m),
Some(crate::session::DecodedNativeHistoryMessage::ToolResult { content, .. })
if !content.starts_with(crate::tools::TOOL_FAILURE_MARKER)
)
})
}
async fn await_wrap_up_batch(
handles: Vec<tokio::task::JoinHandle<Option<AnalystFindings>>>,
deadline: std::time::Instant,
) -> Vec<Option<AnalystFindings>> {
use futures_util::StreamExt;
use futures_util::stream::FuturesUnordered;
let cancel = tokio_util::sync::CancellationToken::new();
let drain = crate::shutdown::drain_wait();
tokio::pin!(drain);
let mut pending: FuturesUnordered<_> = handles
.into_iter()
.enumerate()
.map(|(i, mut handle)| {
let cancel = cancel.clone();
async move {
tokio::select! {
biased;
r = &mut handle => (i, match r {
Ok(v) => v,
Err(e) if e.is_panic() => {
let panic = crate::util::panic_message(&*e.into_panic());
tracing::warn!(member = i, %panic, "wrap-up task panicked");
None
}
Err(_) => {
tracing::warn!(member = i, "wrap-up task cancelled externally");
None
}
}),
() = cancel.cancelled() => {
handle.abort();
(i, None)
}
}
}
})
.collect();
let mut out: Vec<Option<AnalystFindings>> = (0..pending.len()).map(|_| None).collect();
let mut drain_fired = false;
let mut deadline_fired = false;
while !pending.is_empty() {
tokio::select! {
biased;
() = drain.as_mut(), if !drain_fired => {
drain_fired = true;
cancel.cancel();
}
Some((i, result)) = pending.next() => out[i] = result,
() = tokio::time::sleep_until(deadline.into()), if !deadline_fired => {
deadline_fired = true;
cancel.cancel();
}
}
}
out
}
fn resolve_round_members_with_timeouts<T>(
members: Vec<RoundMember<AnalystRun<T>>>,
snapshots: &[WrapUpEntry],
) -> (Vec<AnalystRun<T>>, Vec<WrapUpEntry>) {
debug_assert!(snapshots.is_empty() || snapshots.len() == members.len());
let mut runs = Vec::with_capacity(members.len());
let mut timed_out = Vec::new();
for (i, m) in members.into_iter().enumerate() {
match m {
RoundMember::Done(run) => runs.push(run),
RoundMember::TimedOut => {
runs.push(AnalystRun::NoResponse);
if let Some(entry) = snapshots.get(i) {
timed_out.push(entry.clone());
} else if !snapshots.is_empty() {
tracing::warn!(
member = i,
"timed-out member has no wrap-up snapshot — findings unrecoverable"
);
}
}
RoundMember::Panicked | RoundMember::Cancelled => runs.push(AnalystRun::NoResponse),
}
}
(runs, timed_out)
}
async fn dispatch_analyst_round<T, Fut, F>(
members: Vec<F>,
resume: bool,
deadline: std::time::Instant,
snapshots: &[WrapUpEntry],
) -> (Vec<AnalystRun<T>>, Vec<WrapUpEntry>)
where
T: serde::de::DeserializeOwned + Send + 'static,
Fut: std::future::Future<Output = AnalystRun<T>> + Send + 'static,
F: FnOnce(crate::agent::RoundOpts) -> Fut + Send + 'static,
{
let handles = crate::agent::spawn_staggered_round(members, resume).await;
let members_out = await_round_members(handles, deadline).await;
resolve_round_members_with_timeouts(members_out, snapshots)
}
enum AnalystRun<T> {
NoResponse,
Findings(AnalystRunOutcome<T>),
ParseFailed {
raw: String,
tool_calls: usize,
searches: usize,
queries: Vec<String>,
},
}
struct AnalystRunOutcome<T> {
value: T,
tool_calls: usize,
searches: usize,
queries: Vec<String>,
}
async fn run_structured_analyst<T: serde::de::DeserializeOwned>(
ws: &Workspace,
agent_id: &str,
task: &str,
extraction_prompt: &str,
round: crate::agent::RoundOpts,
run_key: &str,
question: &str,
) -> AnalystRun<T> {
let (mut agent, response) = run_default_agent(
agent_id,
Role::Analyst,
ws,
task,
false,
Some(round),
Some(crate::agent::registry::ParentKey::Research(
run_key.to_string(),
)),
Some(question.to_string()),
)
.await;
let Some(raw) = response else {
return AnalystRun::NoResponse;
};
if raw.trim().is_empty() {
return AnalystRun::NoResponse;
}
let (tool_calls, searches, queries) = extract_query_telemetry(&agent);
match agent
.extract_verdict::<T>(extraction_prompt, None, None)
.await
{
Ok(value) => AnalystRun::Findings(AnalystRunOutcome {
value,
tool_calls,
searches,
queries,
}),
Err(_) => AnalystRun::ParseFailed {
raw,
tool_calls,
searches,
queries,
},
}
}
fn make_round_member<T: serde::de::DeserializeOwned + Send>(
ws: Workspace,
agent_id: String,
task: String,
extraction_prompt: String,
run_key: String,
question: String,
) -> impl FnOnce(crate::agent::RoundOpts) -> futures_util::future::BoxFuture<'static, AnalystRun<T>> + Send
{
move |round| {
Box::pin(async move {
run_structured_analyst::<T>(
&ws,
&agent_id,
&task,
&extraction_prompt,
round,
&run_key,
&question,
)
.await
})
}
}
fn collect_evidence(
runs: &[AnalystRun<AnalystFindings>],
ledger: &mut QueryLedger,
run_stats: &mut RunStats,
) -> EvidenceRound {
let mut round = EvidenceRound::default();
for run in runs {
let run = match run {
AnalystRun::NoResponse => {
run_stats.failed_analysts += 1;
continue;
}
AnalystRun::ParseFailed {
raw,
tool_calls,
searches,
queries,
} => {
run_stats.failed_analysts += 1;
run_stats.tool_calls += tool_calls;
run_stats.searches += searches;
for q in queries {
if !ledger.register(q) {
run_stats.repeat_queries += 1;
}
}
round.raw_reports.push(raw.clone());
continue;
}
AnalystRun::Findings(run) => run,
};
run_stats.tool_calls += run.tool_calls;
run_stats.searches += run.searches;
for q in &run.queries {
round.queries += 1;
if !ledger.register(q) {
round.repeat_queries += 1;
run_stats.repeat_queries += 1;
}
}
for claim in &run.value.claims {
round.claims.push(claim.clone());
if !claim.source.is_empty() {
round.urls.push(claim.source.clone());
}
}
round
.unanswered
.extend(run.value.unanswered.iter().cloned());
}
round
}
fn orchestrator_params(
ws: &Workspace,
purpose: &'static str,
held: &mut ProviderSelection,
) -> ChatRequest {
let mut request = research_params(
ws,
purpose,
format!("research_{}_orchestrator", ws.name),
None,
);
held.apply(&mut request);
request
}
async fn orchestrator_extract<T: serde::de::DeserializeOwned>(
ws: &Workspace,
purpose: &'static str,
prompt: &str,
validate: Option<&crate::ExtractionValidator<T>>,
run_key: &str,
question: &str,
held: &mut ProviderSelection,
) -> Result<T> {
let _call = research_call_guard(purpose, &ws.name, run_key, false, question);
let params = orchestrator_params(ws, purpose, held);
let mut messages = Vec::with_capacity(2);
crate::prompt::prepend_general_context(&mut messages, ws).await;
messages.push(ChatMessage::user(prompt));
crate::agent::extraction::retry_extract_structured_scoped::<T>(
&messages, "", ¶ms, validate, None,
)
.await
.map_err(|e| anyhow::anyhow!("orchestrator extraction '{purpose}' failed: {e}"))
}
#[expect(clippy::too_many_arguments)]
async fn round0_decompose(
ws: &Workspace,
question: &str,
budget: &mut ResearchBudget,
run_stats: &mut RunStats,
deadline: std::time::Instant,
resume: bool,
run_root: &str,
captured: &mut Vec<String>,
run_key: &str,
held: &mut ProviderSelection,
) -> Result<(MergedPlan, Option<String>)> {
budget
.try_reserve(DECOMPOSE_FAN_OUT)
.map_err(anyhow::Error::msg)?;
let max_slots = plan_slot_budget(budget);
let max_slots_arg = max_slots.to_string();
let task_template = load_prompt("research/decompose.md");
let extraction_prompt = load_prompt("extraction/decompose.md");
let members: Vec<_> = (0..DECOMPOSE_FAN_OUT)
.map(|i| {
let ws = ws.clone();
let question = question.to_string();
let task = substitute(
&task_template,
&[
("{{question}}", &question),
("{{run_root}}", run_root),
("{{max_slots}}", &max_slots_arg),
],
);
let agent_id = crate::session::research_agent_id(&ws.name, &format!("decompose_{i}"));
captured.push(agent_id.clone());
make_round_member::<DecompositionPlan>(
ws,
agent_id,
task,
extraction_prompt.clone(),
run_key.to_string(),
question.clone(),
)
})
.collect();
let plans: Vec<_> = dispatch_analyst_round(members, resume, deadline, &[])
.await
.0;
let mut valid = Vec::new();
for run in plans {
match run {
AnalystRun::Findings(o) => valid.push(o.value),
AnalystRun::NoResponse | AnalystRun::ParseFailed { .. } => {
run_stats.failed_analysts += 1;
}
}
}
if valid.is_empty() {
anyhow::bail!("all decomposition analysts failed — no research plan produced");
}
if let Ok(mut plan) =
merge_decomposition_plans(ws, question, &valid, max_slots, run_key, held).await
{
resolve_merged_plan_ids(&mut plan, &valid);
fit_plan_to_slots(&mut plan, max_slots);
Ok((plan, None))
} else {
let mut plan = concatenated_plan(&valid);
if plan.sub_questions.is_empty() {
anyhow::bail!("all decomposition plans were empty — no research plan produced");
}
fit_plan_to_slots(&mut plan, max_slots);
Ok((plan, Some(PLAN_MERGE_FAILED.to_string())))
}
}
fn concatenated_plan(plans: &[DecompositionPlan]) -> MergedPlan {
let mut seen: Vec<String> = Vec::new();
let mut sub_questions = Vec::new();
for (id, sq) in plans
.iter()
.flat_map(|p| p.sub_questions.iter())
.enumerate()
{
let key = normalize_claim(sq.question.trim_end_matches('.'));
if seen.contains(&key) {
continue;
}
seen.push(key);
sub_questions.push(MergedSubQuestion {
question: sq.question.clone(),
evidence_needed: sq.evidence_needed.clone(),
risk: sq.risk.clone(),
from_id: id,
also_ids: Vec::new(),
});
}
MergedPlan {
sub_questions,
dropped: Vec::new(),
}
}
fn render_plans_with_ids(plans: &[DecompositionPlan]) -> String {
let mut out = String::new();
let mut id = 0usize;
for (p, plan) in plans.iter().enumerate() {
let _ = writeln!(out, "Plan {p}:");
for sq in &plan.sub_questions {
let _ = writeln!(
out,
"- {id}: {} [evidence: {}, risk: {}]",
sq.question, sq.evidence_needed, sq.risk
);
id += 1;
}
}
out
}
async fn merge_decomposition_plans(
ws: &Workspace,
question: &str,
plans: &[DecompositionPlan],
max_slots: usize,
run_key: &str,
held: &mut ProviderSelection,
) -> Result<MergedPlan> {
let max_slots_arg = max_slots.to_string();
let prompt = substitute(
&load_prompt("research/decompose_merge.md"),
&[
("{{question}}", question),
("{{plans}}", &render_plans_with_ids(plans)),
("{{max_slots}}", &max_slots_arg),
],
);
let plans_owned = plans.to_vec();
orchestrator_extract::<MergedPlan>(
ws,
"decompose_merge",
&prompt,
Some(&move |p| validate_merged_plan(p, &plans_owned, max_slots)),
run_key,
question,
held,
)
.await
}
fn plan_item_table(plans: &[DecompositionPlan]) -> Vec<Vec<String>> {
plans
.iter()
.map(|p| p.sub_questions.iter().map(|s| s.question.clone()).collect())
.collect()
}
fn resolve_merged_plan_ids(plan: &mut MergedPlan, plans: &[DecompositionPlan]) {
let items = plan_item_table(plans);
let table = crate::consensus::ItemTable::new(&items);
for sq in &mut plan.sub_questions {
let Some((p, i)) = table.resolve_index(sq.from_id) else {
continue;
};
let first = &plans[p].sub_questions[i];
let mut question = first.question.trim_end_matches('.').to_string();
let mut evidence = first.evidence_needed.trim_end_matches('.').to_string();
let mut seen = vec![normalize_claim(&question)];
let mut risk = first.risk.clone();
for &id in &sq.also_ids {
let Some((p, i)) = table.resolve_index(id) else {
continue;
};
let other = &plans[p].sub_questions[i];
let key = normalize_claim(other.question.trim_end_matches('.'));
if seen.contains(&key) {
risk = max_confidence(&risk, &other.risk);
continue;
}
seen.push(key);
fold_text(
&mut question,
&mut evidence,
&mut risk,
&other.question,
&other.evidence_needed,
&other.risk,
);
}
sq.question = question;
sq.evidence_needed = evidence;
sq.risk = risk;
}
}
fn validate_merged_plan(
plan: &MergedPlan,
plans: &[DecompositionPlan],
max_slots: usize,
) -> Result<(), String> {
let items = plan_item_table(plans);
let table = crate::consensus::ItemTable::new(&items);
let mut covered = HashSet::new();
let mut mark = |id: usize, where_: &str| -> Result<(), String> {
if id >= table.len() {
return Err(format!("{where_}: out-of-range item id {id}"));
}
if !covered.insert(id) {
return Err(format!("{where_}: item {id} covered more than once"));
}
Ok(())
};
for (i, sq) in plan.sub_questions.iter().enumerate() {
mark(sq.from_id, &format!("merged sub-question {i}"))?;
for &id in &sq.also_ids {
mark(id, &format!("merged sub-question {i} also_ids"))?;
}
}
for (i, d) in plan.dropped.iter().enumerate() {
mark(d.id, &format!("dropped entry {i}"))?;
}
for id in 0..table.len() {
if !covered.contains(&id) {
return Err(format!(
"silent dropout: input plan item {id} is never covered by the merged plan or dropped list"
));
}
}
if plan.sub_questions.is_empty() {
return Err(
"the merged plan has no directions — the question's scope must be split into \
researchable sub-questions"
.to_string(),
);
}
let mut resolved = plan.clone();
resolve_merged_plan_ids(&mut resolved, plans);
let kept: Vec<String> = resolved
.sub_questions
.iter()
.map(|sq| sq.question.clone())
.collect();
for d in &plan.dropped {
let Some((p, i)) = table.resolve_index(d.id) else {
continue; };
let dropped = &plans[p].sub_questions[i].question;
if !is_duplicate_drop(dropped, &kept) {
return Err(format!(
"dropped item {} ({dropped}) is not a duplicate of any kept direction — fold it \
into the direction it belongs to instead; the split stays complete, only genuine \
duplicates may be dropped",
d.id
));
}
}
let cost = plan_slot_cost(&resolved);
if cost > max_slots {
return Err(format!(
"plan too wide: {} directions cost {cost} analyst slots (a high-risk direction costs \
two), but the run can spend {max_slots} on the plan and must keep the rest for gap \
rounds and verification — fold closely related directions into one",
plan.sub_questions.len()
));
}
Ok(())
}
fn is_duplicate_drop(dropped: &str, kept: &[String]) -> bool {
fn words(text: &str) -> HashSet<String> {
normalize_claim(text)
.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty())
.map(str::to_string)
.collect()
}
let dropped = words(dropped);
!dropped.is_empty() && kept.iter().any(|k| dropped.is_subset(&words(k)))
}
struct Round1Output {
round: EvidenceRound,
timed_out: Vec<WrapUpEntry>,
examined: Vec<usize>,
}
#[expect(clippy::too_many_arguments)]
async fn round1_research(
ws: &Workspace,
question: &str,
plan: &MergedPlan,
budget: &mut ResearchBudget,
ledger: &mut QueryLedger,
run_stats: &mut RunStats,
deadline: std::time::Instant,
resume: bool,
run_root: &str,
captured: &mut Vec<String>,
run_key: &str,
) -> Round1Output {
let costs: Vec<usize> = plan.sub_questions.iter().map(sub_question_slots).collect();
let (dispatch, cost) = plan_prefix(&costs, plan_slot_budget(budget));
let mut out = Round1Output {
round: EvidenceRound::default(),
timed_out: Vec::new(),
examined: Vec::new(),
};
if dispatch == 0 {
tracing::warn!(
spent = %budget.spent,
cap = %budget.cap,
first_direction_cost = costs.first().copied().unwrap_or_default(),
"research allowance left for the plan cannot carry the first direction — no plan \
direction dispatched"
);
return out;
}
if std::time::Instant::now() >= deadline
|| crate::shutdown::aborting()
|| crate::round_cancel::is_cancelled(run_key)
{
return out;
}
budget.spent += cost;
let task_template = load_prompt("research/round1.md");
let extraction_prompt = load_prompt("extraction/findings.md");
let angles = load_analyst_angles();
let wrap_up_specs = role_tool_specs(Role::Analyst, ws, false);
let mut settled = vec![false; plan.sub_questions.len()];
let mut idx = 0usize;
let ledger_snapshot = ledger.render();
let mut members = Vec::new();
let mut member_dirs: Vec<usize> = Vec::new();
let mut snapshots: Vec<WrapUpEntry> = Vec::new();
for i in 0..dispatch {
let sq = &plan.sub_questions[i];
for k in 0..=usize::from(sq.risk == "high") {
let ws = ws.clone();
let question = question.to_string();
let mut task = substitute(
&task_template,
&[
("{{question}}", &question),
("{{sub_question}}", &sq.question),
("{{evidence_needed}}", &sq.evidence_needed),
("{{query_ledger}}", &ledger_snapshot),
("{{run_root}}", run_root),
],
);
if k == 1 && !angles.is_empty() {
task.push_str("\n\nResearch angle:\n");
task.push_str(&angles[idx % angles.len()]);
}
let agent_id = crate::session::research_agent_id(&ws.name, &format!("r1_{idx}"));
captured.push(agent_id.clone());
snapshots.push(WrapUpEntry {
agent_id: agent_id.clone(),
params: wrap_up_params(&ws, &agent_id, wrap_up_specs.clone()),
});
idx += 1;
member_dirs.push(i);
members.push(make_round_member::<AnalystFindings>(
ws,
agent_id,
task,
extraction_prompt.clone(),
run_key.to_string(),
question.clone(),
));
}
}
let (runs, timed_out) = dispatch_analyst_round(members, resume, deadline, &snapshots).await;
for (dir, run) in member_dirs.iter().zip(&runs) {
if !matches!(run, AnalystRun::NoResponse) {
settled[*dir] = true;
}
}
out.round = collect_evidence(&runs, ledger, run_stats);
out.timed_out = timed_out;
out.examined = settled
.iter()
.enumerate()
.filter(|(_, settled)| **settled)
.map(|(i, _)| i)
.collect();
out
}
async fn extract_gap_list(
ws: &Workspace,
question: &str,
acc: &AccumulatedEvidence,
plan: &MergedPlan,
run_key: &str,
held: &mut ProviderSelection,
) -> Option<GapList> {
let evidence = render_accumulated_evidence(acc, true);
let plan_json = serde_json::to_string(plan).unwrap_or_default();
let prompt = substitute(
&load_prompt("research/gap_extract.md"),
&[
("{{question}}", question),
("{{plan}}", &plan_json),
("{{evidence}}", &evidence),
],
);
let plan_owned = plan.clone();
orchestrator_extract::<GapList>(
ws,
"gap_extract",
&prompt,
Some(&move |g| validate_gap_list(g, &plan_owned)),
run_key,
question,
held,
)
.await
.ok()
}
fn validate_gap_list(gaps: &GapList, plan: &MergedPlan) -> Result<(), String> {
for g in &gaps.gaps {
if g.traces_to >= plan.sub_questions.len() {
return Err(format!(
"gap '{}' traces to plan sub-question {} but the merged plan has only {} sub-questions",
g.item,
g.traces_to,
plan.sub_questions.len()
));
}
}
Ok(())
}
fn gap_items(gaps: &[Gap]) -> Vec<String> {
gaps.iter().map(|g| g.item.clone()).collect()
}
#[expect(clippy::too_many_arguments)]
async fn run_gap_round(
ws: &Workspace,
question: &str,
gaps: &[&Gap],
ledger: &QueryLedger,
deadline: std::time::Instant,
resume: bool,
run_root: &str,
captured: &mut Vec<String>,
run_key: &str,
) -> (Vec<AnalystRun<AnalystFindings>>, Vec<WrapUpEntry>) {
let task_template = load_prompt("research/gap.md");
let extraction_prompt = load_prompt("extraction/findings.md");
let ledger_snapshot = ledger.render();
let mut members: Vec<_> = Vec::new();
let mut snapshots: Vec<WrapUpEntry> = Vec::new();
let wrap_up_specs = role_tool_specs(Role::Analyst, ws, false);
for (i, gap) in gaps.iter().enumerate() {
let ws = ws.clone();
let question = question.to_string();
let task = substitute(
&task_template,
&[
("{{question}}", &question),
(
"{{gaps}}",
&format!(
"- [{}] {} (traces to: plan sub-question {})",
gap.kind, gap.item, gap.traces_to
),
),
("{{query_ledger}}", &ledger_snapshot),
("{{run_root}}", run_root),
],
);
let agent_id = crate::session::research_agent_id(&ws.name, &format!("gap_{i}"));
captured.push(agent_id.clone());
snapshots.push(WrapUpEntry {
agent_id: agent_id.clone(),
params: wrap_up_params(&ws, &agent_id, wrap_up_specs.clone()),
});
members.push(make_round_member::<AnalystFindings>(
ws,
agent_id,
task,
extraction_prompt.clone(),
run_key.to_string(),
question.clone(),
));
}
dispatch_analyst_round(members, resume, deadline, &snapshots).await
}
fn set_worker_marker(state: &mut ResearchState, round_key: usize, suffix: &str) {
let marker = format!("worker round {round_key} {suffix}");
clear_worker_markers(state, round_key);
state.markers.push(marker);
}
fn clear_worker_markers(state: &mut ResearchState, round_key: usize) {
state
.markers
.retain(|m| !m.starts_with(&format!("worker round {round_key} ")));
}
fn claim_worker_round(state: &mut ResearchState, round_key: usize) {
if !state.worker_rounds_done.contains(&round_key) {
state.worker_rounds_done.push(round_key);
}
clear_worker_markers(state, round_key);
}
fn unclaim_worker_round(state: &mut ResearchState, round_key: usize) {
state.worker_rounds_done.retain(|k| *k != round_key);
}
#[expect(clippy::too_many_arguments)]
async fn run_worker_round(
job_id: &str,
run_root: &str,
ws: &Workspace,
question: &str,
budget: &ResearchBudget,
gap_list: &GapList,
deadline: std::time::Instant,
state: &mut ResearchState,
round_key: usize,
) {
if budget.is_exhausted() {
set_worker_marker(state, round_key, "skipped — analyst budget exhausted");
return;
}
if std::time::Instant::now() >= deadline {
set_worker_marker(state, round_key, "skipped — round deadline expired");
return;
}
if crate::shutdown::aborting() {
set_worker_marker(state, round_key, "skipped — shutdown/drain");
return;
}
if crate::round_cancel::is_cancelled(job_id) {
set_worker_marker(state, round_key, "skipped — run cancelled");
return;
}
if std::time::Instant::now() + WORKER_MIN_REMAINING >= deadline {
set_worker_marker(
state,
round_key,
"skipped — less than 30 minutes remaining until the round deadline",
);
return;
}
claim_worker_round(state, round_key);
let evidence = render_accumulated_evidence(&state.acc, true);
let gaps = gap_items(&gap_list.gaps).join("\n");
let task = substitute(
&load_prompt("synthesis/worker_brief.md"),
&[
("{{question}}", question),
("{{evidence}}", &evidence),
("{{gaps}}", &gaps),
("{{run_root}}", run_root),
],
);
let worker_ws = Workspace::ephemeral_run(job_id, Path::new(run_root));
let agent_id = crate::session::research_agent_id(&ws.name, "worker");
let (agent, response) = run_default_agent(
&agent_id,
Role::Worker,
&worker_ws,
&task,
false,
None,
Some(crate::agent::registry::ParentKey::Research(
job_id.to_string(),
)),
Some(question.to_string()),
)
.await;
state
.capture_round(job_id, &[agent_id], Path::new(run_root))
.await;
if let Some(text) = response {
tracing::info!(job = %job_id, worker_round = round_key, "Worker round completed");
if !text.trim().is_empty() {
state.worker_reports.push(text);
crate::research_cleanup::write_worker_reports(
Path::new(run_root),
job_id,
&state.worker_reports,
)
.await;
}
} else {
let cancelled = agent.is_cancelled() || crate::shutdown::aborting();
let outcome = if cancelled { "cancelled" } else { "failed" };
unclaim_worker_round(state, round_key);
set_worker_marker(state, round_key, outcome);
}
}
#[expect(clippy::too_many_arguments, clippy::too_many_lines)]
async fn gap_rounds(
ws: &Workspace,
question: &str,
plan: &MergedPlan,
budget: &mut ResearchBudget,
state: &mut ResearchState,
run_stats: &mut RunStats,
deadline: std::time::Instant,
job_id: &str,
run_root: &str,
resume: bool,
recovered: &mut Vec<AnalystFindings>,
held: &mut ProviderSelection,
) -> GapRoundsOutcome {
let mut outcome = GapRoundsOutcome {
abstention: None,
unresolved: Vec::new(),
rounds_dispatched: state.gap_outcome.rounds_dispatched,
incomplete: None,
};
if crate::round_cancel::is_cancelled(job_id) {
return GapRoundsOutcome::default();
}
let initial_list = match state.gap_list.take() {
Some(list) => Some(list),
None => extract_gap_list(ws, question, &state.acc, plan, job_id, held).await,
};
let Some(mut gap_list) = initial_list else {
outcome.incomplete = Some(GAP_EXTRACTION_FAILED.to_string());
return outcome;
};
if !gap_list.gaps.is_empty() && !state.worker_rounds_done.contains(&0) {
run_worker_round(
job_id, run_root, ws, question, budget, &gap_list, deadline, state, 0,
)
.await;
}
let mut round_index = state.round_index;
loop {
if crate::shutdown::aborting()
|| crate::round_cancel::is_cancelled(job_id)
|| budget.is_exhausted()
|| std::time::Instant::now() >= deadline
{
outcome.unresolved = gap_items(&gap_list.gaps);
return outcome;
}
let gaps = &gap_list.gaps;
if gaps.is_empty() {
return outcome;
}
let width = GAP_ROUND_WIDTHS[round_index.min(GAP_ROUND_WIDTHS.len() - 1)];
let targeted: Vec<&Gap> = gaps.iter().take(width).collect();
if budget.cap.saturating_sub(budget.spent)
< targeted.len() + crate::tools::analyze::VERIFY_MAX_ANALYSTS
{
outcome.unresolved = gap_items(gaps);
return outcome;
}
round_index += 1;
if budget.try_reserve(targeted.len()).is_err() {
outcome.unresolved = gap_items(gaps);
return outcome;
}
let mut round_agents: Vec<String> = Vec::new();
let (runs, timed_out) = run_gap_round(
ws,
question,
&targeted,
&state.ledger,
deadline,
resume,
run_root,
&mut round_agents,
job_id,
)
.await;
state
.capture_round(job_id, &round_agents, Path::new(run_root))
.await;
let round = collect_evidence(&runs, &mut state.ledger, run_stats);
recovered.extend(
wrap_up_timed_out(
ws,
timed_out,
&mut state.ledger,
run_stats,
job_id,
question,
)
.await,
);
let (new_urls, pending) = state.acc.absorb(&round);
let novel_claims = annotate_round(
ws,
&mut state.acc,
&pending,
&mut state.markers,
job_id,
question,
held,
)
.await;
outcome.rounds_dispatched += 1;
let all_repeat_queries = round.queries > 0 && round.queries == round.repeat_queries;
if (new_urls == 0 && novel_claims == 0) || all_repeat_queries {
if let Some(reason) = check_answerability(ws, question, &state.acc, job_id, held).await
{
outcome.abstention = Some(reason);
outcome.unresolved = gap_items(gaps);
return outcome;
}
}
if new_urls != 0 || novel_claims != 0 {
let Some(next_gap_list) =
extract_gap_list(ws, question, &state.acc, plan, job_id, held).await
else {
outcome.incomplete = Some(GAP_EXTRACTION_FAILED.to_string());
outcome.unresolved = gap_items(gaps);
return outcome;
};
gap_list = next_gap_list;
if !gap_list.gaps.is_empty() && !state.worker_rounds_done.contains(&round_index) {
run_worker_round(
job_id,
run_root,
ws,
question,
budget,
&gap_list,
deadline,
state,
round_index,
)
.await;
}
}
state.round_index = round_index;
state.gap_outcome.rounds_dispatched = outcome.rounds_dispatched;
state.budget_spent = budget.spent;
state.gap_list = Some(gap_list.clone());
state.save(job_id).await;
}
}
async fn annotate_claims(
ws: &Workspace,
existing: &[Claim],
weak: &WeakLinks,
pending: &[Claim],
run_key: &str,
question: &str,
held: &mut ProviderSelection,
) -> Result<AnnotationPass> {
let mut existing_claims = String::new();
for (i, c) in existing.iter().enumerate() {
let _ = writeln!(existing_claims, "{i}: {}", c.claim);
existing_claims.push_str(&render_weak_hints(weak, i));
}
let mut pending_claims = String::new();
for (i, c) in pending.iter().enumerate() {
let _ = writeln!(pending_claims, "{i}: {}", c.claim);
}
let mut user = substitute(
&load_prompt("research/annotate.md"),
&[
("{{existing_claims}}", &existing_claims),
("{{pending_claims}}", &pending_claims),
],
);
user.push_str("\n\n");
user.push_str(&load_prompt("extraction/annotate.md"));
let existing_owned = existing.to_vec();
let pending_owned = pending.to_vec();
orchestrator_extract::<AnnotationPass>(
ws,
"claim_annotate",
&user,
Some(&move |a| validate_annotations(a, &existing_owned, &pending_owned)),
run_key,
question,
held,
)
.await
}
fn validate_annotations(
pass: &AnnotationPass,
existing: &[Claim],
pending: &[Claim],
) -> Result<(), String> {
let mut ids: Vec<usize> = pass.annotations.iter().map(|a| a.new_id).collect();
ids.sort_unstable();
let expected: Vec<usize> = (0..pending.len()).collect();
if ids != expected {
return Err(format!(
"annotation pass must annotate every new claim exactly once: ids {ids:?} != 0..{}",
pending.len()
));
}
for a in &pass.annotations {
let verdict = a.verdict.as_str();
if !matches!(verdict, "novel" | "duplicate" | "contradicts") {
return Err(format!(
"verdict '{verdict}' not in [novel, duplicate, contradicts]"
));
}
let has_note = a
.contradiction
.as_deref()
.is_some_and(|c| !c.trim().is_empty());
if (verdict == "contradicts") != has_note {
return Err(format!(
"verdict '{verdict}' for new claim {} must carry the contradiction note exactly when it contradicts",
a.new_id
));
}
if verdict == "novel" {
if a.existing_id.is_some() {
return Err(format!(
"novel annotation for new claim {} must not cite an existing claim",
a.new_id
));
}
continue;
}
let Some(existing_id) = a.existing_id else {
return Err(format!(
"{verdict} annotation for new claim {} must cite an existing claim",
a.new_id
));
};
if existing_id >= existing.len() {
return Err(format!(
"existing_id {existing_id} out of range ({} existing claims)",
existing.len()
));
}
}
Ok(())
}
async fn confirm_links(
ws: &Workspace,
existing: &[Claim],
pending: &[Claim],
pass: &AnnotationPass,
run_key: &str,
question: &str,
held: &mut ProviderSelection,
) -> Result<ConfirmPass> {
let mut links = String::new();
for a in pass.annotations.iter().filter(|a| a.verdict != "novel") {
let existing_id = a
.existing_id
.expect("mutating verdict cites an existing claim");
let p = &pending[a.new_id];
let e = &existing[existing_id];
let _ = writeln!(
links,
"- new claim {}: \"{}\" [{}] ↔ existing claim {}: \"{}\" (annotation: {})",
a.new_id, p.claim, p.confidence, existing_id, e.claim, a.verdict
);
}
let mut user = substitute(
&load_prompt("research/confirm.md"),
&[("{{links}}", &links)],
);
user.push_str("\n\n");
user.push_str(&load_prompt("extraction/confirm.md"));
let mutating: Vec<usize> = pass
.annotations
.iter()
.filter(|a| a.verdict != "novel")
.map(|a| a.new_id)
.collect();
orchestrator_extract::<ConfirmPass>(
ws,
"confirm_links",
&user,
Some(&move |c| validate_confirm(c, &mutating)),
run_key,
question,
held,
)
.await
}
fn validate_confirm(pass: &ConfirmPass, mutating: &[usize]) -> Result<(), String> {
let mut ids: Vec<usize> = pass.links.iter().map(|l| l.new_id).collect();
ids.sort_unstable();
let mut expected = mutating.to_vec();
expected.sort_unstable();
if ids != expected {
return Err(format!(
"confirm pass must judge exactly the mutating links (new_ids {expected:?}), got {ids:?}"
));
}
for l in &pass.links {
if !matches!(l.verdict.as_str(), "confirm" | "reject") {
return Err(format!("verdict '{}' not in [confirm, reject]", l.verdict));
}
}
Ok(())
}
async fn annotate_round(
ws: &Workspace,
acc: &mut AccumulatedEvidence,
pending: &[Claim],
markers: &mut Vec<String>,
run_key: &str,
question: &str,
held: &mut ProviderSelection,
) -> usize {
if pending.is_empty() {
return 0;
}
if acc.claims.is_empty() {
acc.claims.extend(pending.iter().cloned());
return pending.len();
}
let Ok(pass) =
annotate_claims(ws, &acc.claims, &acc.weak, pending, run_key, question, held).await
else {
acc.claims.extend(pending.iter().cloned());
if !markers.iter().any(|m| m == CLAIM_ANNOTATION_FAILED) {
markers.push(CLAIM_ANNOTATION_FAILED.to_string());
}
return pending.len();
};
let confirm = if pass.annotations.iter().any(|a| a.verdict != "novel") {
if let Ok(c) = confirm_links(ws, &acc.claims, pending, &pass, run_key, question, held).await
{
ConfirmOutcome::Passed(c)
} else {
if !markers.iter().any(|m| m == CONFIRM_FAILED) {
markers.push(CONFIRM_FAILED.to_string());
}
ConfirmOutcome::Failed
}
} else {
ConfirmOutcome::Passed(ConfirmPass::default())
};
acc.apply_annotations(&pass, pending, &confirm)
}
async fn check_answerability(
ws: &Workspace,
question: &str,
acc: &AccumulatedEvidence,
run_key: &str,
held: &mut ProviderSelection,
) -> Option<String> {
let evidence = render_accumulated_evidence(acc, true);
let prompt = substitute(
&load_prompt("research/abstain.md"),
&[("{{question}}", question), ("{{evidence}}", &evidence)],
);
let verdict = orchestrator_extract::<AnswerabilityCheck>(
ws,
"abstain_check",
&prompt,
None,
run_key,
question,
held,
)
.await
.ok()?;
(!verdict.answerable).then_some(verdict.reason)
}
#[derive(Debug)]
enum SynthesisOutcome {
Answer {
text: String,
undelivered: Option<String>,
},
Undelivered {
reason: String,
output: Option<String>,
},
}
fn record_synthesis_failure(
loop_state: &mut crate::retry::RetryLoop,
class: FailureClass,
resp: &crate::ChatResponse,
reason: &str,
) {
let err = anyhow::anyhow!("{reason}");
loop_state.record(crate::retry::RetryFailureRecord::with_metadata(
class,
&err,
resp.finish_reason.clone(),
None,
));
}
fn reject_answer_size(
loop_state: &mut crate::retry::RetryLoop,
resp: &crate::ChatResponse,
bytes: usize,
floor: usize,
ceiling: usize,
feedback_key: &str,
) -> String {
let reason = format!(
"synthesis answer is {bytes} bytes (target {}–{} KB)",
floor / 1024,
ceiling / 1024
);
record_synthesis_failure(loop_state, FailureClass::ValidationOther, resp, &reason);
substitute(
&load_prompt(feedback_key),
&[
("{{bytes}}", &bytes.to_string()),
("{{min}}", &(floor / 1024).to_string()),
("{{max}}", &(ceiling / 1024).to_string()),
],
)
}
#[expect(clippy::too_many_lines, clippy::too_many_arguments)]
async fn synthesize(
ws: &Workspace,
question: &str,
acc: &AccumulatedEvidence,
recovered: &[AnalystFindings],
abstention: Option<&str>,
open: &[String],
ceiling: usize,
run_key: &str,
held: &mut ProviderSelection,
) -> Result<SynthesisOutcome> {
let _call = research_call_guard("synthesize", &ws.name, run_key, false, question);
let mut evidence = render_accumulated_evidence(acc, false);
evidence.push_str(&render_recovered_findings(recovered, RenderTarget::Prompt));
let mut open_list = String::new();
for q in open {
let _ = writeln!(open_list, "- {q}");
}
if open_list.is_empty() {
open_list.push_str("- none recorded");
}
let floor = ANSWER_MIN_BYTES.min(ceiling);
let mut base_user = substitute(
&load_prompt("research/synthesize.md"),
&[
("{{question}}", question),
("{{evidence}}", &evidence),
("{{open_questions}}", &open_list),
("{{min}}", &(floor / 1024).to_string()),
("{{max}}", &(ceiling / 1024).to_string()),
],
);
if let Some(abstain) = abstention {
let _ = writeln!(
base_user,
"\n\n# Answerability Note\n\nThe research team determined the question is not \
answerable with the available evidence: {abstain}\n\
State this clearly and explain what evidence would be needed."
);
}
let policy = crate::retry::RetryPolicy::synthesis();
let mut params = orchestrator_params(ws, "synthesize", held);
let mut loop_state = crate::retry::RetryLoop::new_scoped(&policy, ¶ms);
let operation_started = Instant::now();
let mut prefix = Vec::with_capacity(2);
crate::prompt::prepend_general_context(&mut prefix, ws).await;
let mut last: Option<String> = None;
let mut last_problem: Option<String> = None;
let mut short: Option<String> = None;
let mut asked_for_more = false;
let mut any_truncated = false;
let mut feedback = String::new();
let mut transport_failures = 0u32;
for attempt in 1..=policy.max_attempts {
loop_state.begin_attempt(Instant::now());
let mut user = base_user.clone();
if !feedback.is_empty() {
let _ = writeln!(user, "\n\n# Previous Attempt Feedback\n\n{feedback}");
}
let mut messages = prefix.clone();
messages.push(ChatMessage::user(&user));
params.messages = messages;
match crate::providers::chat_scoped(params.clone()).await {
Ok(resp) => {
let text = resp.text_or_empty().to_string();
let truncated = resp.finish_reason.as_deref() == Some("length");
if truncated {
any_truncated = true;
record_synthesis_failure(
&mut loop_state,
FailureClass::TruncatedOutput,
&resp,
"synthesis truncated by the provider (finish_reason=length)",
);
feedback = load_prompt("research/synthesize_feedback_truncated.md");
if !text.trim().is_empty() {
last = Some(text);
last_problem = Some("the provider truncated the last attempt".to_string());
}
continue;
}
if text.trim().is_empty() {
record_synthesis_failure(
&mut loop_state,
FailureClass::NoResponse,
&resp,
"synthesis attempt returned empty text",
);
feedback = load_prompt("research/synthesize_feedback_empty.md");
continue;
}
if text.len() > ceiling {
feedback = reject_answer_size(
&mut loop_state,
&resp,
text.len(),
floor,
ceiling,
"research/synthesize_feedback_over_length.md",
);
last = Some(text);
last_problem = Some(format!(
"the last attempt was over the {} KB answer ceiling",
ceiling / 1024
));
continue;
}
if text.len() < floor && !asked_for_more && evidence.len() >= floor {
asked_for_more = true;
feedback = reject_answer_size(
&mut loop_state,
&resp,
text.len(),
floor,
ceiling,
"research/synthesize_feedback_below_target.md",
);
short = Some(text);
continue;
}
crate::stats::record_llm_success(¶ms, operation_started, attempt, &resp);
return Ok(SynthesisOutcome::Answer {
text,
undelivered: last,
});
}
Err(err) => {
let non_retryable = !err.class.is_retryable();
loop_state.record(err.record);
if non_retryable {
break;
}
loop_state.switch_after_failure(err.class, held, &mut params);
transport_failures += 1;
if attempt < policy.max_attempts
&& let Err(FailureClass::Shutdown) =
loop_state.sleep_between(transport_failures).await
{
break;
}
}
}
}
let final_class = loop_state.final_class();
let exhausted = crate::retry::RetryExhausted::with_last_raw(
loop_state.into_failures(),
final_class,
last.clone(),
);
crate::stats::record_llm_failure(¶ms, operation_started, &exhausted);
let undeliverable = last.zip(last_problem);
match (short, undeliverable) {
(Some(text), undelivered) => Ok(SynthesisOutcome::Answer {
text,
undelivered: undelivered.map(|(text, _)| text),
}),
(None, Some((text, reason))) => Ok(SynthesisOutcome::Undelivered {
reason,
output: Some(text),
}),
(None, None) if any_truncated => Err(anyhow::anyhow!(
"final synthesis was truncated with no usable output"
)),
(None, None) => Err(anyhow::anyhow!(
"final synthesis produced no usable output after {} attempts",
policy.max_attempts
)),
}
}
fn verification_targets(acc: &AccumulatedEvidence) -> (Vec<VerificationTarget>, usize) {
let mut seen = HashSet::new();
let mut targets = Vec::new();
for (i, c) in acc.claims.iter().enumerate() {
if !c.contradictions.is_empty() || c.confidence == "low" {
seen.insert(i);
targets.push(VerificationTarget::new(
&c.claim,
&c.source,
&c.contradictions.join("; "),
));
}
}
let primary_count = targets.len();
for &(claim_id, _) in &acc.weak.duplicates {
if seen.insert(claim_id) {
let c = &acc.claims[claim_id];
targets.push(VerificationTarget::new(&c.claim, &c.source, ""));
}
}
(targets, primary_count)
}
#[expect(clippy::too_many_arguments)]
async fn research_verification_pass(
ws: &Workspace,
acc: &AccumulatedEvidence,
budget: &mut ResearchBudget,
ledger: &mut QueryLedger,
run_stats: &mut RunStats,
deadline: std::time::Instant,
resume: bool,
run_root: &str,
captured: &mut Vec<String>,
run_key: &str,
question: &str,
) -> Vec<VerificationResult> {
let (targets, primary_count) = verification_targets(acc);
if targets.is_empty() {
return Vec::new();
}
let cap = targets
.len()
.min(crate::tools::analyze::VERIFY_MAX_ANALYSTS);
let n = cap.min(budget.cap.saturating_sub(budget.spent));
let mut results = Vec::new();
if n > 0 && std::time::Instant::now() < deadline && budget.try_reserve(n).is_ok() {
let ledger_snapshot = ledger.render();
let task_extra = format!(
"\n# Queries Already Asked (do not repeat these verbatim)\n\n{ledger_snapshot}\n\n\
# Scratch Workspace\n\nTemporary per-run folder (wiped after the run):\n\n{run_root}"
);
let prefix = format!("research_{}_verify", ws.name);
let (verify_results, verify_ids) = dispatch_claim_verifiers(
ws,
&prefix,
&targets[..n],
&task_extra,
deadline,
resume,
Some(crate::agent::registry::ParentKey::Research(
run_key.to_string(),
)),
question,
)
.await;
captured.extend(verify_ids);
results = verify_results;
}
for v in &results {
run_stats.tool_calls += v.tool_calls;
run_stats.searches += v.searches;
for q in &v.queries {
if !ledger.register(q) {
run_stats.repeat_queries += 1;
}
}
}
for t in targets
.iter()
.skip(results.len())
.take(primary_count.saturating_sub(results.len()))
{
results.push(VerificationResult::unresolved(
&t.claim,
"verification skipped — budget exhausted or round deadline expired",
0,
0,
Vec::new(),
));
}
results
}
fn render_weak_hints(weak: &WeakLinks, id: usize) -> String {
let mut out = String::new();
for &(claim, target) in &weak.duplicates {
if claim == id {
let _ = writeln!(
out,
" weak: possibly duplicate of #{target} (unconfirmed)"
);
}
}
for &(claim, target) in &weak.contradictions {
if claim == id {
let _ = writeln!(out, " weak: possibly contradicts #{target} (unconfirmed)");
}
if target == id {
let _ = writeln!(out, " weak: possibly contradicts #{claim} (unconfirmed)");
}
}
out
}
fn source_or_na(source: &str) -> &str {
if source.is_empty() { "n/a" } else { source }
}
fn render_unanswered(out: &mut String, unanswered: &[String]) {
if unanswered.is_empty() {
return;
}
let _ = writeln!(out, "\nAnalysts reported these as still unanswered:");
for u in unanswered {
let _ = writeln!(out, "- {u}");
}
}
fn render_raw_reports(out: &mut String, raw_reports: &[String]) {
if raw_reports.is_empty() {
return;
}
let _ = writeln!(out, "\n## Failed Analyst Reports");
for (i, raw) in raw_reports.iter().enumerate() {
let _ = writeln!(out, "### Report from Analyst {}", i + 1);
let _ = writeln!(out, "{}", escape_fences(raw));
}
}
#[derive(Clone, Copy)]
enum RenderTarget {
Delivered,
Prompt,
}
impl RenderTarget {
fn text(self, s: &str) -> String {
match self {
RenderTarget::Delivered => escape_fences(s),
RenderTarget::Prompt => s.to_string(),
}
}
}
fn render_claim_line(
out: &mut String,
c: &Claim,
number: Option<usize>,
with_contradictions: bool,
target: RenderTarget,
) {
let confidence = &c.confidence;
let claim = target.text(&c.claim);
let source = target.text(source_or_na(&c.source));
match number {
Some(n) => {
let _ = writeln!(out, "{n}. [{confidence}] {claim} — source: {source}");
}
None => {
let _ = writeln!(out, "- [{confidence}] {claim} — source: {source}");
}
}
if with_contradictions && !c.contradictions.is_empty() {
let _ = writeln!(
out,
" contradictions: {}",
target.text(&c.contradictions.join("; "))
);
}
}
fn render_claims(out: &mut String, acc: &AccumulatedEvidence, target: RenderTarget) {
for (i, c) in acc.claims.iter().enumerate() {
render_claim_line(out, c, Some(i), true, target);
out.push_str(&render_weak_hints(&acc.weak, i));
}
}
fn render_accumulated_evidence(acc: &AccumulatedEvidence, with_unanswered: bool) -> String {
let mut out = String::new();
render_claims(&mut out, acc, RenderTarget::Prompt);
if with_unanswered {
render_unanswered(&mut out, &acc.unanswered);
}
if !acc.raw_reports.is_empty() {
let _ = writeln!(
out,
"\nRaw notes from analysts whose structured extraction failed (preserve any \
usable content):"
);
for raw in &acc.raw_reports {
let _ = writeln!(out, "- {raw}");
}
}
out
}
#[expect(clippy::too_many_arguments)]
fn render_run_summary(
run_stats: &RunStats,
budget: &ResearchBudget,
rounds_used: usize,
acc: &AccumulatedEvidence,
abstention: Option<&str>,
incomplete: Option<&str>,
markers: &[String],
wall: Duration,
) -> String {
let mut out = String::new();
let _ = writeln!(out, "## Run Summary");
let _ = writeln!(out, "- rounds used: {rounds_used}");
if let Some(reason) = incomplete {
let _ = writeln!(out, "- gap rounds incomplete: {reason}");
}
if !markers.is_empty() {
let _ = writeln!(out, "- markers:");
for m in markers {
let _ = writeln!(out, " - {m}");
}
}
let _ = writeln!(out, "- agents spawned: {} / {}", budget.spent, budget.cap);
let _ = writeln!(out, "- tool calls: {}", run_stats.tool_calls);
let _ = writeln!(out, "- searches: {}", run_stats.searches);
let _ = writeln!(
out,
"- repeat queries (no-progress): {}",
run_stats.repeat_queries
);
if run_stats.failed_analysts > 0 {
let _ = writeln!(
out,
"- analysts failed (no response / extraction failure): {}",
run_stats.failed_analysts
);
}
let _ = writeln!(out, "- wall time: {:.0}s", wall.as_secs_f64());
let _ = writeln!(
out,
"- evidence: {} claims, {} unique sources",
acc.claims.len(),
acc.urls.len()
);
let weak_links = acc.weak.duplicates.len() + acc.weak.contradictions.len();
if weak_links > 0 {
let _ = writeln!(out, "- weak/unconfirmed links: {weak_links}");
}
if let Some(a) = abstention {
let _ = writeln!(out, "- answerability: QUESTION ABSTAINED — {a}");
}
out
}
fn render_recovered_findings(recovered: &[AnalystFindings], target: RenderTarget) -> String {
if recovered.is_empty() {
return String::new();
}
let mut out = String::new();
let _ = writeln!(out, "\n## Recovered from timed-out analysts");
let _ = writeln!(
out,
"Findings recovered from analysts whose work was cut short by the round \
deadline (deadline exceeded, unverified — not subject to verification; each \
analyst's final in-flight turn could not be recovered):"
);
for r in recovered {
for c in &r.claims {
render_claim_line(&mut out, c, None, true, target);
}
}
out
}
enum AnswerSource {
Synthesized(String),
ProductBuilt(String),
}
struct RunReport<'a> {
state: &'a ResearchState,
recovered: &'a [AnalystFindings],
verification: &'a [VerificationResult],
run_stats: &'a RunStats,
budget: &'a ResearchBudget,
open: &'a [String],
open_section: &'a str,
rounds_used: usize,
wall: Duration,
}
impl RunReport<'_> {
fn output(&self, source: AnswerSource, job_id: &str) -> ResearchOutput {
let mut answer = match source {
AnswerSource::Synthesized(text) => text,
AnswerSource::ProductBuilt(reason) => {
self.answer(&reason, answer_text_ceiling(self.open_section, job_id))
}
};
answer.push_str(self.open_section);
ResearchOutput {
answer,
detail: self.detail(),
}
}
fn answer(&self, reason: &str, ceiling: usize) -> String {
let acc = &self.state.acc;
let mut out = String::new();
let header = format!("## Deep Analysis Answer (incomplete — {reason})");
push_answer_line(
&mut out,
&cap_answer_line(&header, ANSWER_LINE_MAX_BYTES),
ceiling,
);
push_answer_line(&mut out, "\n### Evidence Gathered So Far\n\n", ceiling);
let claims: Vec<&Claim> = acc
.claims
.iter()
.chain(self.recovered.iter().flat_map(|r| r.claims.iter()))
.collect();
if claims.is_empty() {
let line = if acc.raw_reports.is_empty() {
"- nothing was established before the run stopped\n"
} else {
"- structured findings could not be extracted; the analysts' raw reports are in the \
detail file\n"
};
push_answer_line(&mut out, line, ceiling);
} else {
render_capped_answer_list(&mut out, &claims, ANSWER_LIST_CAP, Some(ceiling), |c| {
let mut line = String::new();
render_claim_line(&mut line, c, None, false, RenderTarget::Delivered);
line
});
}
out
}
fn detail(&self) -> String {
let state = self.state;
let acc = &state.acc;
let mut out = String::new();
let _ = writeln!(out, "# Deep Analysis Detail\n");
let _ = writeln!(out, "## Full Evidence\n");
if acc.claims.is_empty() {
let _ = writeln!(out, "- no structured claims were collected");
}
render_claims(&mut out, acc, RenderTarget::Delivered);
out.push_str(&render_recovered_findings(
self.recovered,
RenderTarget::Delivered,
));
render_raw_reports(&mut out, &acc.raw_reports);
if !self.verification.is_empty() {
let _ = writeln!(out, "\n## Verification");
for v in self.verification {
let _ = writeln!(
out,
"- {} → **{}** — {}",
escape_fences(&v.claim),
v.verdict,
escape_fences(&v.evidence),
);
}
}
if !state.worker_reports.is_empty() {
let _ = writeln!(out, "\n## Tested in Practice");
for report in &state.worker_reports {
let _ = writeln!(out, "\n{}", escape_fences(report));
}
}
let _ = writeln!(out, "\n## Open Questions");
if self.open.is_empty() {
let _ = writeln!(out, "- no open questions were recorded");
}
for q in self.open {
let _ = writeln!(out, "- {}", escape_fences(q));
}
let _ = writeln!(out);
out.push_str(&render_run_summary(
self.run_stats,
self.budget,
self.rounds_used,
acc,
state.gap_outcome.abstention.as_deref(),
state.gap_outcome.incomplete.as_deref(),
&state.markers,
self.wall,
));
out
}
}
fn render_capped_answer_list<T>(
out: &mut String,
items: &[T],
cap: usize,
bound: Option<usize>,
render: impl Fn(&T) -> String,
) {
let ceiling = bound.unwrap_or(usize::MAX);
let mut shown = 0usize;
for item in items.iter().take(cap) {
if !push_answer_line(
out,
&cap_answer_line(&render(item), ANSWER_LINE_MAX_BYTES),
ceiling,
) {
break;
}
shown += 1;
}
if items.len() > shown {
push_answer_line(
out,
&format!(
"- …and {} more, listed in full in the detail file\n",
items.len() - shown
),
ceiling,
);
}
}
fn push_answer_line(out: &mut String, line: &str, ceiling: usize) -> bool {
if out.len() + line.len() > ceiling {
return false;
}
out.push_str(line);
true
}
fn cap_answer_line(line: &str, max: usize) -> String {
let mut capped = crate::util::cut_bytes(line.trim_end_matches('\n'), max.saturating_sub(1));
capped.push('\n');
capped
}
fn detail_reference(path: &Path) -> String {
format!(
"\n---\n\nFull detail — every finding with its sources, the failed analysts' reports, the \
verification results, what was tested in practice and the run bookkeeping — is delivered \
alongside this answer in:\n\n`{}`\n",
path.display()
)
}
fn detail_reference_len(job_id: &str) -> usize {
crate::research_cleanup::detail_archive_path(job_id)
.map_or(0, |path| detail_reference(&path).len())
}
fn render_open_section(open: &[String]) -> String {
let mut out = String::new();
let _ = writeln!(out, "\n### Questions This Run Could Not Settle\n");
if open.is_empty() {
let _ = writeln!(out, "- no open questions were recorded");
return out;
}
render_capped_answer_list(&mut out, open, ANSWER_OPEN_CAP, None, |q| {
format!("- {}", escape_fences(q))
});
out
}
fn answer_text_ceiling(open_section: &str, job_id: &str) -> usize {
ANSWER_MAX_BYTES.saturating_sub(open_section.len() + detail_reference_len(job_id))
}
fn open_questions(
state: &ResearchState,
recovered: &[AnalystFindings],
question: &str,
) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
match &state.plan {
Some(plan) => out.extend(
plan.sub_questions
.iter()
.enumerate()
.filter(|(i, _)| !state.examined.contains(i))
.map(|(_, sq)| sq.question.clone()),
),
None => out.push(question.to_string()),
}
let recovered_unanswered = recovered.iter().flat_map(|r| r.unanswered.iter());
for q in state
.gap_outcome
.unresolved
.iter()
.chain(state.acc.unanswered.iter())
.chain(recovered_unanswered)
{
if !out.contains(q) {
out.push(q.clone());
}
}
out
}
enum ResearchExit {
Terminal(anyhow::Result<ResearchOutput>),
Aborted,
Cancelled,
}
#[expect(clippy::too_many_lines)]
async fn run_deep_research(
ws: &Workspace,
question: &str,
job_id: &str,
resume: bool,
) -> ResearchExit {
let _orchestrator_guard =
research_call_guard("research_orchestrator", &ws.name, job_id, true, question);
let start = Instant::now();
let deadline = std::time::Instant::now() + round_timeout();
let mut state = ResearchState::load(job_id).await;
let mut budget = ResearchBudget::new(RESEARCH_MAX_ANALYSTS);
budget.spent = state.budget_spent;
let mut run_stats = RunStats::default();
let run_root = crate::research_cleanup::ensure_run_root(job_id).await;
let run_root_str = run_root.to_string_lossy().to_string();
let mut recovered: Vec<AnalystFindings> = Vec::new();
if crate::round_cancel::is_cancelled(job_id) {
return ResearchExit::Cancelled;
}
let mut held = ProviderSelection::default();
let mut round_agents: Vec<String> = Vec::new();
if state.stage == ResearchStage::Decompose {
let round0 = round0_decompose(
ws,
question,
&mut budget,
&mut run_stats,
deadline,
resume,
&run_root_str,
&mut round_agents,
job_id,
&mut held,
)
.await;
state.capture_round(job_id, &round_agents, &run_root).await;
round_agents.clear();
let plan = match round0 {
Ok((plan, marker)) => {
if let Some(m) = marker {
state.markers.push(m);
}
plan
}
Err(_) if crate::shutdown::aborting() => {
state.save(job_id).await;
return ResearchExit::Aborted;
}
Err(_) if crate::round_cancel::is_cancelled(job_id) => {
return ResearchExit::Cancelled;
}
Err(e) => {
state.save(job_id).await;
let open = open_questions(&state, &recovered, question);
let open_section = render_open_section(&open);
let report = RunReport {
state: &state,
recovered: &recovered,
verification: &[],
run_stats: &run_stats,
budget: &budget,
open: &open,
open_section: &open_section,
rounds_used: 0,
wall: start.elapsed(),
};
let output = report.output(
AnswerSource::ProductBuilt(format!(
"the question could not be decomposed: {e:#}"
)),
job_id,
);
return ResearchExit::Terminal(Ok(output));
}
};
state.plan = Some(plan);
state.budget_spent = budget.spent;
state.stage = ResearchStage::Round1;
state.save(job_id).await;
}
if crate::shutdown::aborting() {
return ResearchExit::Aborted;
}
if crate::round_cancel::is_cancelled(job_id) {
return ResearchExit::Cancelled;
}
if state.stage == ResearchStage::Round1 {
if let Some(plan) = state.plan.as_ref() {
let r1 = round1_research(
ws,
question,
plan,
&mut budget,
&mut state.ledger,
&mut run_stats,
deadline,
resume,
&run_root_str,
&mut round_agents,
job_id,
)
.await;
state.capture_round(job_id, &round_agents, &run_root).await;
round_agents.clear();
let (_, pending) = state.acc.absorb(&r1.round);
annotate_round(
ws,
&mut state.acc,
&pending,
&mut state.markers,
job_id,
question,
&mut held,
)
.await;
state.examined = r1.examined;
state.budget_spent = budget.spent;
state.stage = ResearchStage::GapRounds;
state.save(job_id).await;
recovered.extend(
wrap_up_timed_out(
ws,
r1.timed_out,
&mut state.ledger,
&mut run_stats,
job_id,
question,
)
.await,
);
} else {
state.markers.push(PLAN_LOST_MARKER.to_string());
state.stage = ResearchStage::Synthesis;
state.save(job_id).await;
}
}
if state.stage == ResearchStage::GapRounds {
if let Some(plan) = state.plan.clone() {
let gap_outcome = gap_rounds(
ws,
question,
&plan,
&mut budget,
&mut state,
&mut run_stats,
deadline,
job_id,
&run_root_str,
resume,
&mut recovered,
&mut held,
)
.await;
if crate::shutdown::aborting() {
state.gap_outcome = gap_outcome;
state.budget_spent = budget.spent;
state.save(job_id).await;
return ResearchExit::Aborted;
}
if crate::round_cancel::is_cancelled(job_id) {
return ResearchExit::Cancelled;
}
state.gap_outcome = gap_outcome;
state.budget_spent = budget.spent;
state.stage = ResearchStage::Synthesis;
state.save(job_id).await;
} else {
state.markers.push(PLAN_LOST_MARKER.to_string());
state.stage = ResearchStage::Synthesis;
state.save(job_id).await;
}
}
let rounds_used = 2 + state.gap_outcome.rounds_dispatched;
if crate::shutdown::aborting() {
return ResearchExit::Aborted;
}
if crate::round_cancel::is_cancelled(job_id) {
return ResearchExit::Cancelled;
}
let open = open_questions(&state, &recovered, question);
let open_section = render_open_section(&open);
let established =
!state.acc.claims.is_empty() || !state.acc.raw_reports.is_empty() || !recovered.is_empty();
let mut undelivered_synthesis: Option<String> = None;
let source = if established {
match synthesize(
ws,
question,
&state.acc,
&recovered,
state.gap_outcome.abstention.as_deref(),
&open,
answer_text_ceiling(&open_section, job_id),
job_id,
&mut held,
)
.await
{
Ok(SynthesisOutcome::Answer { text, undelivered }) => {
undelivered_synthesis = undelivered;
AnswerSource::Synthesized(text)
}
Ok(SynthesisOutcome::Undelivered { reason, output }) => {
undelivered_synthesis = output;
let marker = format!("synthesis answer not delivered: {reason}");
if !state.markers.contains(&marker) {
state.markers.push(marker);
}
AnswerSource::ProductBuilt(reason)
}
Err(_) if crate::shutdown::aborting() => {
return ResearchExit::Aborted;
}
Err(_) if crate::round_cancel::is_cancelled(job_id) => {
return ResearchExit::Cancelled;
}
Err(e) => AnswerSource::ProductBuilt(format!("synthesis failed: {e:#}")),
}
} else {
AnswerSource::ProductBuilt(if budget.is_exhausted() {
"analyst allowance exhausted before any evidence was gathered".to_string()
} else {
"no analyst produced usable findings".to_string()
})
};
let verification = if crate::shutdown::aborting() {
Vec::new()
} else if crate::round_cancel::is_cancelled(job_id) {
return ResearchExit::Cancelled;
} else if !state.verification.is_empty() {
std::mem::take(&mut state.verification)
} else {
state.verification = research_verification_pass(
ws,
&state.acc,
&mut budget,
&mut state.ledger,
&mut run_stats,
deadline,
resume,
&run_root_str,
&mut round_agents,
job_id,
question,
)
.await;
state.capture_round(job_id, &round_agents, &run_root).await;
round_agents.clear();
state.budget_spent = budget.spent;
state.save(job_id).await;
std::mem::take(&mut state.verification)
};
let report = RunReport {
state: &state,
recovered: &recovered,
verification: &verification,
run_stats: &run_stats,
budget: &budget,
open: &open,
open_section: &open_section,
rounds_used,
wall: start.elapsed(),
};
let mut output = report.output(source, job_id);
if let Some(text) = undelivered_synthesis {
let _ = writeln!(
output.detail,
"\n## Synthesis Output Not Delivered as the Answer\n\nThe answer is held to its size \
and completeness target, so this output was kept here whole instead:\n\n{text}"
);
}
if crate::jobs::job_retry_count(&crate::session::store().conn, job_id).await > 0 {
let _ = writeln!(
output.detail,
"\n> Run telemetry is best-effort: this run resumed from a checkpoint, so tool-call \
and query counts reflect only the post-resume segment."
);
}
ResearchExit::Terminal(Ok(output))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
async fn seed_research_run(job_id: &str, ws: &Workspace, state: &ResearchState) {
let conn = &crate::session::store().conn;
crate::util::test::JobRowBuilder::new(conn, job_id, "research", "assistant", &ws.name)
.task("question?")
.user_name("caller-user")
.channel("telegram")
.timestamps(crate::db::now())
.insert()
.await
.unwrap();
conn.execute(
"INSERT INTO research_jobs (id, state) VALUES (?1, ?2)",
crate::db::params![job_id, serde_json::to_string(state).unwrap()],
)
.await
.unwrap();
}
async fn finish_research_run(job_id: &str) {
let _ = tokio::fs::remove_dir_all(crate::research_cleanup::run_root_path(job_id)).await;
crate::session::store()
.conn
.execute("DELETE FROM jobs WHERE id = ?1", crate::db::params![job_id])
.await
.unwrap();
}
fn claim(claim: &str, source: &str, confidence: &str) -> Claim {
Claim {
claim: claim.into(),
source: source.into(),
confidence: confidence.into(),
contradictions: Vec::new(),
}
}
fn synthesis_answer(outcome: SynthesisOutcome) -> String {
match outcome {
SynthesisOutcome::Answer { text, .. } => text,
SynthesisOutcome::Undelivered { reason, .. } => {
panic!("expected a delivered answer, got: {reason}")
}
}
}
#[test]
fn test_budget_cap_enforced() {
let mut budget = ResearchBudget::new(RESEARCH_MAX_ANALYSTS);
assert!(budget.try_reserve(RESEARCH_MAX_ANALYSTS - 1).is_ok());
assert!(budget.try_reserve(1).is_ok());
assert!(
budget.try_reserve(1).is_err(),
"spawn cap is unconditional and never refunded"
);
assert_eq!(budget.spent, RESEARCH_MAX_ANALYSTS);
assert!(budget.is_exhausted());
let mut budget = ResearchBudget::new(RESEARCH_MAX_ANALYSTS);
budget.try_reserve(DECOMPOSE_FAN_OUT).unwrap();
assert_eq!(
plan_slot_budget(&budget),
RESEARCH_MAX_ANALYSTS - DECOMPOSE_FAN_OUT - plan_slot_reserve()
);
assert!(
plan_slot_budget(&budget) > 0,
"a fresh run always has room for a plan"
);
assert_eq!(
plan_slot_budget(&ResearchBudget::new(plan_slot_reserve())),
0
);
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn resume_research_run_continues_at_synthesis_stage() {
let legacy: ResearchStage =
serde_json::from_str(r#""verification""#).expect("the old stage reads");
assert_eq!(
legacy,
ResearchStage::Synthesis,
"the collapsed stage is Synthesis"
);
assert_eq!(
serde_json::to_string(&legacy).expect("the stage serializes"),
r#""synthesis""#,
"new checkpoints write the collapsed name"
);
crate::util::test::init_management_test_stores().await;
let report = format!(
"final synthesized report for the resumed run {}",
"r".repeat(ANSWER_MIN_BYTES)
);
let fake = crate::util::test::FakeProvider::new().ok(&report);
let _seam = crate::util::test::install_retry_seam(fake);
let ws = crate::workspace::test_ws("/tmp/test_ws_research_resume");
let job_id = "research_job_resume_1";
let conn = &crate::session::store().conn;
let mut state = ResearchState {
stage: ResearchStage::Synthesis,
plan: None,
gap_list: None,
acc: AccumulatedEvidence {
urls: std::collections::HashSet::new(),
claims: vec![claim("alpha is a real project", "s1", "high")],
unanswered: vec![],
unanswered_keys: std::collections::HashSet::new(),
raw_reports: vec![],
weak: WeakLinks::default(),
},
ledger: QueryLedger::default(),
markers: vec![],
gap_outcome: GapRoundsOutcome::default(),
budget_spent: 0,
round_index: 0,
verification: vec![crate::tools::analyze::VerificationResult {
claim: "alpha is a real project".into(),
verdict: "confirmed".into(),
evidence: "primary source".into(),
tool_calls: 0,
searches: 0,
queries: vec![],
}],
commands: vec![],
seen_commands: std::collections::HashSet::new(),
worker_rounds_done: vec![],
examined: vec![],
worker_reports: vec![],
};
state.acc.rebuild_keys();
seed_research_run(job_id, &ws, &state).await;
resume_research_run(job_id, &ws).await;
let job_rows = conn
.query(
"SELECT kind FROM jobs WHERE id = ?1",
crate::db::params![job_id],
)
.await
.unwrap();
assert_eq!(
job_rows.len(),
1,
"research job terminalized; the research_cleanup durability row remains"
);
assert_eq!(
job_rows[0].get::<String>(0).unwrap(),
"research_cleanup",
"the surviving row is the cleanup durability row, not the research job"
);
let pending = conn
.query(
"SELECT envelope FROM pending_jobs WHERE id = ?1",
crate::db::params![job_id],
)
.await
.unwrap();
assert_eq!(pending.len(), 1, "resume envelope persisted");
let envelope_json: String = pending[0].get(0).unwrap();
let envelope: crate::agent::message_router::AgentJob =
serde_json::from_str(&envelope_json).unwrap();
assert_eq!(
envelope.role,
crate::Role::Assistant,
"delivered to the original caller role, not Manager"
);
assert_eq!(envelope.user_name, "caller-user");
assert!(
envelope.content.contains("final synthesized report"),
"the resume envelope must carry the synthesized report: {envelope_json}"
);
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn an_over_long_synthesis_is_kept_in_the_detail_file_and_the_answer_still_ships() {
crate::util::test::init_management_test_stores().await;
let over_long = format!("{} OVER-LONG-SYNTHESIS", "z".repeat(ANSWER_MAX_BYTES));
let fake = crate::util::test::FakeProvider::new()
.ok(&over_long)
.ok(&over_long)
.ok(&over_long);
let _seam = crate::util::test::install_retry_seam(fake);
let ws = crate::workspace::test_ws("/tmp/test_ws_research_overlong");
let job_id = "research_job_overlong_1";
let conn = &crate::session::store().conn;
let mut state = ResearchState {
stage: ResearchStage::Synthesis,
acc: AccumulatedEvidence {
claims: vec![claim("alpha is a real project", "s1", "high")],
..AccumulatedEvidence::default()
},
verification: vec![crate::tools::analyze::VerificationResult {
claim: "alpha is a real project".into(),
verdict: "confirmed".into(),
evidence: "primary source".into(),
tool_calls: 0,
searches: 0,
queries: vec![],
}],
..ResearchState::default()
};
state.acc.rebuild_keys();
seed_research_run(job_id, &ws, &state).await;
resume_research_run(job_id, &ws).await;
let pending = conn
.query(
"SELECT envelope FROM pending_jobs WHERE id = ?1",
crate::db::params![job_id],
)
.await
.unwrap();
let envelope_json: String = pending[0].get(0).unwrap();
let envelope: crate::agent::message_router::AgentJob =
serde_json::from_str(&envelope_json).unwrap();
assert!(
envelope.content.contains("over the")
&& envelope.content.contains("KB answer ceiling")
&& envelope
.content
.contains("### Questions This Run Could Not Settle"),
"the answer names why synthesis was unavailable and what stayed open: {}",
envelope.content
);
assert!(
!envelope.content.contains("OVER-LONG-SYNTHESIS"),
"an over-ceiling synthesis is never delivered as the answer"
);
assert!(
envelope.content.len() <= ANSWER_MAX_BYTES + 256,
"the delivered answer stays within its ceiling, framing aside: {} bytes",
envelope.content.len()
);
let detail_path = crate::research_cleanup::detail_archive_path(job_id)
.expect("the detail file is written next to the answer");
let detail = tokio::fs::read_to_string(&detail_path).await.unwrap();
assert!(
detail.contains("## Synthesis Output Not Delivered as the Answer")
&& detail.contains("OVER-LONG-SYNTHESIS"),
"the undelivered synthesis is kept whole in the detail file"
);
assert!(
detail.contains("alpha is a real project"),
"the established finding is in the detail file"
);
let _ = tokio::fs::remove_file(&detail_path).await;
finish_research_run(job_id).await;
}
#[tokio::test]
async fn terminalization_spawn_failure_delivers_error_envelope_without_artifacts() {
crate::util::test::init_management_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/test_ws_research_spawn_fail");
let envelope = terminalize_research(
"research_job_spawn_fail_1",
&ws,
&Err(anyhow::anyhow!("spawn failed")),
crate::Role::Assistant,
"question?",
"caller-user",
"telegram",
false,
None,
)
.await
.expect("spawn failure still delivers an error envelope");
assert!(
envelope.content.contains("An error occurred: spawn failed"),
"{}",
envelope.content
);
let conn = &crate::session::store().conn;
let jobs = conn
.query(
"SELECT id FROM jobs WHERE id = ?1",
crate::db::params!["research_job_spawn_fail_1"],
)
.await
.unwrap();
assert!(
jobs.is_empty(),
"no cleanup durability row without a spawned run"
);
let archive =
crate::research_cleanup::results_archive_path("research_job_spawn_fail_1").unwrap();
assert!(!archive.exists(), "spawn failure must not write results.md");
}
#[tokio::test]
async fn cancelled_run_exits_cancelled_at_stage_boundary() {
crate::util::test::init_management_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/test_ws_research_cancel_boundary");
let job_id = "research_job_cancel_boundary_1";
let _guard = crate::round_cancel::register(job_id, None);
crate::round_cancel::cancel(job_id);
let exit = run_deep_research(&ws, "question?", job_id, true).await;
assert!(
matches!(exit, ResearchExit::Cancelled),
"fired cancel signal must yield Cancelled at the boundary"
);
}
enum FailOpenStage {
Synthesize,
Annotate,
}
struct FailOpenCase {
name: &'static str,
stage: FailOpenStage,
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn provider_failure_fail_open_cases() {
for case in [
FailOpenCase {
name: "synthesis never delivers a truncated or over-long answer",
stage: FailOpenStage::Synthesize,
},
FailOpenCase {
name: "a failed confirm pass keeps every mutating claim as weak",
stage: FailOpenStage::Annotate,
},
] {
let _policy_guard =
crate::util::test::install_test_retry_policy(crate::retry::tiny_test_policy());
match case.stage {
FailOpenStage::Synthesize => {
let ws =
crate::workspace::test_ws_named("/tmp/test_ws", "research_synth_truncated");
let acc = AccumulatedEvidence {
claims: (0..60)
.map(|i| claim(&format!("{i} {}", "e".repeat(200)), "s", "high"))
.collect(),
..AccumulatedEvidence::default()
};
let compact = "y".repeat(ANSWER_MIN_BYTES);
let fake = crate::util::test::FakeProvider::new()
.ok_with_finish("report part one", Some("length"))
.ok_with_finish("report part two", Some("length"))
.ok_with_finish("compressed final", Some("length"));
let provider: std::sync::Arc<dyn crate::Provider> = std::sync::Arc::new(fake);
let _provider_guard = crate::util::test::install_fake_provider(provider);
let out = synthesize(
&ws,
"q",
&acc,
&[],
None,
&[],
ANSWER_MAX_BYTES,
"test_run",
&mut ProviderSelection::default(),
)
.await
.expect("truncated output is reported, not errored");
let SynthesisOutcome::Undelivered { reason, output } = out else {
panic!("[{}] a truncated output is not the answer", case.name);
};
assert_eq!(
output.as_deref(),
Some("compressed final"),
"[{}] the last produced output is kept for the detail file",
case.name
);
assert!(
reason.contains("truncated"),
"[{}] the product-built answer says why: {reason}",
case.name
);
let fake = crate::util::test::FakeProvider::new()
.ok_with_finish("part one", Some("length"))
.ok(&compact);
let provider: std::sync::Arc<dyn crate::Provider> = std::sync::Arc::new(fake);
let _provider_guard = crate::util::test::install_fake_provider(provider);
let out = synthesize(
&ws,
"q",
&acc,
&[],
None,
&[],
ANSWER_MAX_BYTES,
"test_run",
&mut ProviderSelection::default(),
)
.await
.expect("clean completion wins");
let SynthesisOutcome::Answer { text, undelivered } = out else {
panic!("[{}] a clean attempt is the answer", case.name);
};
assert_eq!(text, compact, "[{}]", case.name);
assert_eq!(
undelivered.as_deref(),
Some("part one"),
"[{}] the truncated earlier attempt is kept for the detail file, not lost",
case.name
);
let fake = crate::util::test::FakeProvider::new()
.err(crate::retry::FailureClass::Transport, "outage")
.err(crate::retry::FailureClass::Transport, "outage")
.err(crate::retry::FailureClass::Transport, "outage");
let provider: std::sync::Arc<dyn crate::Provider> = std::sync::Arc::new(fake);
let _provider_guard = crate::util::test::install_fake_provider(provider);
let err = synthesize(
&ws,
"q",
&acc,
&[],
None,
&[],
ANSWER_MAX_BYTES,
"test_run",
&mut ProviderSelection::default(),
)
.await
.expect_err("transport exhaustion must error into the product-built answer");
assert!(
err.to_string().contains("no usable output"),
"[{}] {err}",
case.name
);
let long = "x".repeat(ANSWER_MAX_BYTES + 1);
let fake = crate::util::test::FakeProvider::new()
.ok(&long)
.ok(&compact);
let provider: std::sync::Arc<dyn crate::Provider> = std::sync::Arc::new(fake);
let _provider_guard = crate::util::test::install_fake_provider(provider);
let out = synthesize(
&ws,
"q",
&acc,
&[],
None,
&[],
ANSWER_MAX_BYTES,
"test_run",
&mut ProviderSelection::default(),
)
.await
.expect("the retried answer is delivered");
assert_eq!(
synthesis_answer(out),
compact,
"[{}] the compliant retry is the answer",
case.name
);
let fake = crate::util::test::FakeProvider::new()
.ok(&long)
.ok(&long)
.ok(&long);
let provider: std::sync::Arc<dyn crate::Provider> = std::sync::Arc::new(fake);
let _provider_guard = crate::util::test::install_fake_provider(provider);
let out = synthesize(
&ws,
"q",
&acc,
&[],
None,
&[],
ANSWER_MAX_BYTES,
"test_run",
&mut ProviderSelection::default(),
)
.await
.expect("the over-long output is reported, not errored");
let SynthesisOutcome::Undelivered { reason, output } = out else {
panic!("[{}] an over-long answer is never delivered", case.name);
};
assert_eq!(
output.as_deref(),
Some(long.as_str()),
"[{}] the over-long output is kept whole, never cut",
case.name
);
assert!(
reason.contains("ceiling"),
"[{}] the product-built answer says why: {reason}",
case.name
);
let fake = std::sync::Arc::new(
crate::util::test::FakeProvider::new()
.ok("brief answer")
.ok("still brief"),
);
let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
let _provider_guard = crate::util::test::install_fake_provider(provider);
let out = synthesize(
&ws,
"q",
&acc,
&[],
None,
&[],
ANSWER_MAX_BYTES,
"test_run",
&mut ProviderSelection::default(),
)
.await
.expect("a short answer is still an answer");
assert_eq!(
synthesis_answer(out),
"still brief",
"[{}] a below-target answer is delivered, never padded",
case.name
);
assert!(
fake.request_messages.lock().unwrap()[1].contains("below the"),
"[{}] the re-ask names the target",
case.name
);
let recovered = vec![AnalystFindings {
claims: vec![claim("recovered fact", "https://r", "medium")],
unanswered: Vec::new(),
}];
let fake =
std::sync::Arc::new(crate::util::test::FakeProvider::new().ok(&compact));
let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
let _provider_guard = crate::util::test::install_fake_provider(provider);
synthesize(
&ws,
"q",
&acc,
&recovered,
None,
&[],
ANSWER_MAX_BYTES,
"test_run",
&mut ProviderSelection::default(),
)
.await
.expect("clean completion wins");
assert!(
fake.request_messages.lock().unwrap()[0].contains("recovered fact"),
"[{}] the synthesis prompt carries the recovered findings",
case.name
);
}
FailOpenStage::Annotate => {
let ws = crate::workspace::test_ws_named(
"/tmp/test_ws",
"research_annotate_fail_open",
);
let mut acc = AccumulatedEvidence::default();
acc.claims.push(claim("alpha is true", "u1", "medium"));
let pending = vec![
claim("alpha is true (restated)", "u2", "high"),
claim("beta contradicts alpha", "u3", "high"),
];
let annotation_json = r#"{"annotations": [{"new_id": 0, "verdict": "duplicate", "existing_id": 0}, {"new_id": 1, "verdict": "contradicts", "existing_id": 0, "contradiction": "alpha vs beta differ"}]}"#;
let fake = crate::util::test::FakeProvider::new()
.ok(annotation_json)
.err(crate::retry::FailureClass::Transport, "confirm outage")
.err(crate::retry::FailureClass::Transport, "confirm outage")
.err(crate::retry::FailureClass::Transport, "confirm outage");
let provider: std::sync::Arc<dyn crate::Provider> = std::sync::Arc::new(fake);
let _provider_guard = crate::util::test::install_fake_provider(provider);
let mut markers = Vec::new();
let novel = annotate_round(
&ws,
&mut acc,
&pending,
&mut markers,
"test_run",
"question",
&mut ProviderSelection::default(),
)
.await;
assert_eq!(
novel, 1,
"[{}] only the weak contradiction counts as novel — the weak duplicate never does",
case.name
);
assert_eq!(
acc.claims.len(),
3,
"[{}] both mutating claims stay standalone — never dropped",
case.name
);
assert_eq!(acc.weak.duplicates, vec![(1, 0)], "[{}]", case.name);
assert_eq!(acc.weak.contradictions, vec![(2, 0)], "[{}]", case.name);
assert!(
acc.claims[0]
.contradictions
.contains(&"alpha vs beta differ".to_string()),
"[{}] the weak contradiction keeps its note — verification still qualifies it",
case.name
);
assert!(
markers.iter().any(|m| m.contains("confirmation failed")),
"[{}] the confirm failure is never silent: {markers:?}",
case.name
);
}
}
}
}
enum ValidationGate {
GapTracesToPlan,
MergedPlanCoverage,
}
struct ValidationGateCase {
name: &'static str,
gate: ValidationGate,
}
#[expect(clippy::too_many_lines)]
#[test]
fn validation_gate_cases() {
for case in [
ValidationGateCase {
name: "a gap's traces_to must index the merged plan",
gate: ValidationGate::GapTracesToPlan,
},
ValidationGateCase {
name: "every sub-question is placed exactly once",
gate: ValidationGate::MergedPlanCoverage,
},
] {
match case.gate {
ValidationGate::GapTracesToPlan => {
let plan = MergedPlan {
sub_questions: vec![
MergedSubQuestion {
question: "What is the price of X?".into(),
evidence_needed: "pricing page".into(),
risk: "low".into(),
from_id: 0,
also_ids: vec![],
},
MergedSubQuestion {
question: "Who maintains X?".into(),
evidence_needed: "repo metadata".into(),
risk: "medium".into(),
from_id: 1,
also_ids: vec![],
},
],
dropped: vec![],
};
let in_range = GapList {
gaps: vec![Gap {
kind: "unanswered".into(),
item: "exact price".into(),
traces_to: 0,
}],
};
assert!(
validate_gap_list(&in_range, &plan).is_ok(),
"[{}]",
case.name
);
let out_of_range = GapList {
gaps: vec![Gap {
kind: "unanswered".into(),
item: "unrelated".into(),
traces_to: 5,
}],
};
assert!(
validate_gap_list(&out_of_range, &plan).is_err(),
"[{}] out-of-range traces_to is rejected — index-range validation guarantees traceability",
case.name
);
}
ValidationGate::MergedPlanCoverage => {
let sq = |q: &str| SubQuestion {
question: q.into(),
evidence_needed: "e".into(),
risk: "low".into(),
};
let plans = vec![
DecompositionPlan {
sub_questions: vec![sq("q1"), sq("q2")],
},
DecompositionPlan {
sub_questions: vec![sq("q1"), sq("q3")],
},
];
let entry = |from_id: usize, also_ids: Vec<usize>| MergedSubQuestion {
question: String::new(),
evidence_needed: String::new(),
risk: String::new(),
from_id,
also_ids,
};
let accepted = MergedPlan {
sub_questions: vec![entry(0, vec![2]), entry(1, vec![]), entry(3, vec![])],
dropped: vec![],
};
assert!(
validate_merged_plan(&accepted, &plans, 8).is_ok(),
"[{}] full coverage via from_id + also_ids",
case.name
);
let duplicate_drop = MergedPlan {
sub_questions: vec![entry(0, vec![]), entry(1, vec![]), entry(3, vec![])],
dropped: vec![DroppedSubQuestion { id: 2 }],
};
assert!(
validate_merged_plan(&duplicate_drop, &plans, 8).is_ok(),
"[{}] dropping a duplicate is the merge's normal job",
case.name
);
let distinct_drop = MergedPlan {
sub_questions: vec![entry(0, vec![2]), entry(1, vec![])],
dropped: vec![DroppedSubQuestion { id: 3 }],
};
let err = validate_merged_plan(&distinct_drop, &plans, 8)
.expect_err("a size-driven drop is rejected");
assert!(
err.contains("not a duplicate"),
"[{}] the rejection says why: {err}",
case.name
);
let dropout = MergedPlan {
sub_questions: vec![entry(0, vec![]), entry(1, vec![])],
dropped: vec![],
};
assert!(
validate_merged_plan(&dropout, &plans, 8).is_err(),
"[{}] silent dropout: plan 1's q1 (id 2) is never covered",
case.name
);
let mut bad = accepted.clone();
bad.sub_questions[0].from_id = 9;
assert!(
validate_merged_plan(&bad, &plans, 8).is_err(),
"[{}] out-of-range from_id is rejected",
case.name
);
let mut bad = accepted.clone();
bad.sub_questions[1].from_id = 0;
assert!(
validate_merged_plan(&bad, &plans, 8).is_err(),
"[{}] duplicate placement (id 0 twice) is rejected",
case.name
);
assert!(
validate_merged_plan(&accepted, &plans, 2).is_err(),
"[{}] an over-wide plan is rejected",
case.name
);
let too_wide =
validate_merged_plan(&accepted, &plans, 2).expect_err("over-wide plan");
assert!(
too_wide.contains("plan too wide"),
"[{}] the rejection says why: {too_wide}",
case.name
);
}
}
}
}
#[test]
fn test_evidence_absorb_counts_novelty() {
let mut acc = AccumulatedEvidence::default();
let round1 = EvidenceRound {
urls: vec!["u1".into(), "u2".into()],
claims: vec![
claim("alpha is true", "u1", "high"),
claim("beta is true", "u2", "medium"),
],
unanswered: vec!["how beta relates to alpha".into()],
..Default::default()
};
let (urls, pending) = acc.absorb(&round1);
assert_eq!((urls, pending.len()), (2, 2));
let round2 = EvidenceRound {
urls: vec!["u1".into(), "u3".into()],
claims: vec![
claim("alpha is true", "u1", "high"),
claim("gamma is true", "u3", "low"),
],
unanswered: vec!["how beta relates to alpha".into(), "delta timeline".into()],
..Default::default()
};
let (urls, pending) = acc.absorb(&round2);
assert_eq!(
(urls, pending.len()),
(1, 2),
"only new URL (u3); every claim stays pending for annotation"
);
assert_eq!(
acc.unanswered,
vec!["how beta relates to alpha", "delta timeline"],
"unanswered aspects accumulate deduplicated across rounds"
);
}
struct AnnotationsMatrix {
acc: AccumulatedEvidence,
pending: Vec<Claim>,
pass: AnnotationPass,
confirm: ConfirmOutcome,
}
fn annotations_matrix(
existing: Claim,
pending: Claim,
verdict: &str,
contradiction: Option<&str>,
confirm_verdict: &str,
) -> AnnotationsMatrix {
let mut acc = AccumulatedEvidence::default();
acc.claims.push(existing);
AnnotationsMatrix {
acc,
pending: vec![pending],
pass: AnnotationPass {
annotations: vec![ClaimAnnotation {
new_id: 0,
verdict: verdict.into(),
existing_id: Some(0),
contradiction: contradiction.map(Into::into),
}],
},
confirm: ConfirmOutcome::Passed(ConfirmPass {
links: vec![ConfirmLink {
new_id: 0,
verdict: confirm_verdict.into(),
}],
}),
}
}
struct AnnotationsCase {
name: &'static str,
existing: Claim,
pending: Claim,
verdict: &'static str,
contradiction: Option<&'static str>,
confirm: &'static str,
novel: usize,
claims_len: usize,
existing_contradictions: &'static [&'static str],
links_back_to: Option<&'static str>,
weak_duplicates: &'static [(usize, usize)],
weak_contradictions: &'static [(usize, usize)],
merged_confidence: Option<&'static str>,
merged_source: Option<&'static str>,
}
#[expect(clippy::too_many_lines)]
#[test]
fn apply_annotations_cases() {
for case in [
AnnotationsCase {
name: "a contradiction is appended and linked to the existing claim",
existing: claim("alpha costs $100 in 2024", "u1", "medium"),
pending: claim("alpha costs $200 in 2024", "u2", "high"),
verdict: "contradicts",
contradiction: Some("price differs: $200 vs $100"),
confirm: "confirm",
novel: 1,
claims_len: 2,
existing_contradictions: &["price differs: $200 vs $100"],
links_back_to: Some("alpha costs $100 in 2024"),
weak_duplicates: &[],
weak_contradictions: &[],
merged_confidence: None,
merged_source: None,
},
AnnotationsCase {
name: "a duplicate merges sources and upgrades confidence",
existing: claim("alpha is true", "u1; u2", "low"),
pending: claim("alpha is true", "u2; u3", "high"),
verdict: "duplicate",
contradiction: None,
confirm: "confirm",
novel: 0,
claims_len: 1,
existing_contradictions: &[],
links_back_to: None,
weak_duplicates: &[],
weak_contradictions: &[],
merged_confidence: Some("high"),
merged_source: Some("u1; u2; u3"),
},
AnnotationsCase {
name: "a weak duplicate stays standalone with a side-structure hint",
existing: claim("alpha is true", "u1", "medium"),
pending: claim("alpha is true (restated)", "u2", "high"),
verdict: "duplicate",
contradiction: None,
confirm: "reject",
novel: 0,
claims_len: 2,
existing_contradictions: &[],
links_back_to: None,
weak_duplicates: &[(1, 0)],
weak_contradictions: &[],
merged_confidence: None,
merged_source: None,
},
AnnotationsCase {
name: "a weak contradiction keeps both notes and is recorded unconfirmed",
existing: claim("alpha costs $100 in 2024", "u1", "medium"),
pending: claim("alpha costs $200 in 2024", "u2", "high"),
verdict: "contradicts",
contradiction: Some("price differs: $200 vs $100"),
confirm: "reject",
novel: 1,
claims_len: 2,
existing_contradictions: &["price differs: $200 vs $100"],
links_back_to: Some("alpha costs $100 in 2024"),
weak_duplicates: &[],
weak_contradictions: &[(1, 0)],
merged_confidence: None,
merged_source: None,
},
] {
let mut m = annotations_matrix(
case.existing,
case.pending,
case.verdict,
case.contradiction,
case.confirm,
);
let novel = m.acc.apply_annotations(&m.pass, &m.pending, &m.confirm);
assert_eq!(novel, case.novel, "[{}] novel count", case.name);
assert_eq!(
m.acc.claims.len(),
case.claims_len,
"[{}] claim count",
case.name
);
let expected_notes: Vec<String> = case
.existing_contradictions
.iter()
.map(|note| (*note).to_string())
.collect();
assert_eq!(
m.acc.claims[0].contradictions, expected_notes,
"[{}] the existing claim's notes",
case.name
);
if let Some(existing) = case.links_back_to {
assert!(
m.acc.claims[1]
.contradictions
.contains(&existing.to_string()),
"[{}] the new claim must link back to the existing one",
case.name
);
}
assert_eq!(
m.acc.weak.duplicates, case.weak_duplicates,
"[{}] weak duplicates",
case.name
);
assert_eq!(
m.acc.weak.contradictions, case.weak_contradictions,
"[{}] weak contradictions",
case.name
);
if let Some(confidence) = case.merged_confidence {
assert_eq!(
m.acc.claims[0].confidence, confidence,
"[{}] merged confidence",
case.name
);
}
if let Some(source) = case.merged_source {
assert_eq!(
m.acc.claims[0].source, source,
"[{}] merged sources",
case.name
);
}
assert!(
m.acc
.claims
.iter()
.all(|c| c.contradictions.iter().all(|n| !n.contains("unconfirmed"))),
"[{}] weakness never leaks into note text",
case.name
);
}
}
#[test]
fn test_verification_targets_primaries_first_weak_dups_fill_empty_slots() {
let mut acc = AccumulatedEvidence::default();
acc.claims.push(claim("a", "u1", "low"));
acc.claims.push(Claim {
claim: "b".into(),
source: "u2".into(),
confidence: "high".into(),
contradictions: vec!["b vs c".into()],
});
acc.claims.push(claim("a restated", "u3", "high"));
acc.claims.push(claim("b restated", "u4", "low"));
acc.weak.duplicates.push((2, 0));
acc.weak.duplicates.push((3, 1));
acc.weak.contradictions.push((1, 2));
let (targets, primary_count) = verification_targets(&acc);
assert_eq!(
primary_count, 3,
"claims 0, 1 and 3 qualify as primary — the weak contradiction is not appended"
);
assert_eq!(targets.len(), 4, "claim 2 fills the only empty slot");
assert_eq!(targets[0].claim, "a");
assert_eq!(targets[1].claim, "b");
assert_eq!(targets[2].claim, "b restated", "primary targets come first");
assert_eq!(
targets[3].claim, "a restated",
"weak duplicate appended last"
);
assert_eq!(
targets[3].contradictions, "",
"weakness never leaks toward verifiers"
);
}
#[test]
fn test_resolve_round_members_with_timeouts_preserves_timed_out() {
let snapshots: Vec<WrapUpEntry> = (0..4)
.map(|i| WrapUpEntry {
agent_id: format!("a{i}"),
params: wrap_up_params(&crate::workspace::test_ws("/tmp/test_ws"), "a", vec![]),
})
.collect();
let members: Vec<RoundMember<AnalystRun<AnalystFindings>>> = vec![
RoundMember::Done(AnalystRun::NoResponse),
RoundMember::TimedOut,
RoundMember::Panicked,
RoundMember::Cancelled,
];
let (runs, timed_out) = resolve_round_members_with_timeouts(members, &snapshots);
assert_eq!(runs.len(), 4);
assert!(runs.iter().all(|r| matches!(r, AnalystRun::NoResponse)));
assert_eq!(timed_out.len(), 1, "only the TimedOut member is recovered");
assert_eq!(timed_out[0].agent_id, "a1", "snapshot is index-parallel");
assert_eq!(
render_recovered_findings(&[], RenderTarget::Delivered),
"",
"an empty set renders nothing"
);
let recovered = vec![AnalystFindings {
claims: vec![Claim {
claim: "found claim".into(),
source: "u1".into(),
confidence: "medium".into(),
contradictions: vec!["counter".into()],
}],
unanswered: vec!["still open".into()],
}];
let out = render_recovered_findings(&recovered, RenderTarget::Delivered);
assert!(
out.starts_with("\n## Recovered from timed-out analysts"),
"recovered findings get their own section: {out}"
);
assert!(
!out.contains("### Evidence Gathered So Far"),
"never merged into the evidence list: {out}"
);
assert!(
out.contains("deadline exceeded, unverified"),
"the section is marked unverified: {out}"
);
assert!(out.contains("found claim"), "the claim is carried: {out}");
assert!(
out.contains("contradictions: counter"),
"the contradiction is carried: {out}"
);
let state = ResearchState::default();
let open = open_questions(&state, &recovered, "the original question");
assert!(
open.iter().any(|q| q == "still open")
&& open.iter().any(|q| q == "the original question"),
"recovered unanswered aspects are named among the questions the run could not settle: {open:?}"
);
assert!(
!out.contains("still open"),
"the recovered section does not repeat them: {out}"
);
}
#[test]
fn test_session_has_successful_tool_result_gates_wrap_up_llm_call() {
assert!(!session_has_successful_tool_result(&[]));
assert!(!session_has_successful_tool_result(&[ChatMessage::user(
"task"
)]));
let failed =
crate::tools::format_tool_failure_feedback("search", &json!({"query": "q"}), "boom");
assert!(!session_has_successful_tool_result(&[
ChatMessage::tool_result("t1", &failed)
]));
assert!(session_has_successful_tool_result(&[
ChatMessage::tool_result("t1", "search results")
]));
let mixed = vec![
ChatMessage::tool_result("t1", &failed),
ChatMessage::tool_result("t2", "results ok"),
];
assert!(session_has_successful_tool_result(&mixed));
}
#[tokio::test]
#[serial_test::serial(config_persist, provider, drain)] async fn the_wrap_up_continues_on_the_analysts_own_provider() {
crate::util::test::init_test_stores().await;
let model = "research/wrap-up-provider";
let _order = crate::config::test_routing_order(model, "first, second");
let agent_id = "research-wrap-up-analyst";
let fake = std::sync::Arc::new(crate::util::test::FakeProvider::new().ok(
r#"{"claims":[{"claim":"found","source":"u1","confidence":"high","contradictions":[]}],"unanswered":[]}"#,
));
let body = {
let fake = fake.clone();
tokio::spawn(async move {
let mut session = crate::session::Session::default();
session.init(agent_id).await.expect("session init");
session.push_messages_unpersisted(&[
ChatMessage::user("research the question"),
ChatMessage::tool_result("t1", "results ok"),
]);
session.finalize(agent_id).await.expect("create the row");
let stored = crate::providers::selection::StoredProvider {
model: model.to_string(),
provider: "second".into(),
};
assert!(
crate::session::store()
.set_provider(agent_id, Some(&stored))
.await
.expect("record the conversation's provider"),
);
let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
let _guard = crate::util::test::install_fake_provider(provider);
let ws = crate::workspace::test_ws("/tmp/test_ws");
let mut params = wrap_up_params(&ws, agent_id, vec![]);
params.model = model.to_string();
let findings = wrap_up_timed_out(
&ws,
vec![WrapUpEntry {
agent_id: agent_id.to_string(),
params,
}],
&mut QueryLedger::default(),
&mut RunStats::default(),
"run-key",
"the question",
)
.await;
let fingerprints = fake.request_fingerprints.lock().unwrap().clone();
(findings.len(), fingerprints)
})
};
let outcome = body.await;
let _ = crate::session::store().delete(agent_id).await;
let (found, fingerprints) = match outcome {
Ok(result) => result,
Err(panic) => std::panic::resume_unwind(panic.into_panic()),
};
assert_eq!(found, 1, "the wrap-up extracted the findings");
assert!(
fingerprints[0].contains(r#"provider: Some("second")"#),
"the wrap-up continues on the conversation's own provider, not the top of the list: {}",
fingerprints[0]
);
}
#[test]
fn worker_round_lifecycle_skip_vs_claim_vs_unclaim() {
let mut state = ResearchState::default();
set_worker_marker(&mut state, 0, "skipped — analyst budget exhausted");
assert!(
state
.markers
.iter()
.any(|m| m == "worker round 0 skipped — analyst budget exhausted")
);
assert!(!state.worker_rounds_done.contains(&0));
claim_worker_round(&mut state, 0);
assert!(state.worker_rounds_done.contains(&0));
assert!(!state.markers.iter().any(|m| m.contains("worker round 0 ")));
unclaim_worker_round(&mut state, 0);
set_worker_marker(&mut state, 0, "failed");
assert!(!state.worker_rounds_done.contains(&0));
assert!(state.markers.iter().any(|m| m == "worker round 0 failed"));
assert!(
!state
.markers
.iter()
.any(|m| m.contains("worker round 0 skipped")),
"outcome marker supersedes the stale skip marker"
);
claim_worker_round(&mut state, 0);
assert!(!state.markers.iter().any(|m| m.contains("worker round 0 ")));
set_worker_marker(&mut state, 1, "skipped — round deadline expired");
claim_worker_round(&mut state, 0);
assert!(
state
.markers
.iter()
.any(|m| m == "worker round 1 skipped — round deadline expired")
);
assert!(!state.markers.iter().any(|m| m.contains("worker round 0 ")));
set_worker_marker(&mut state, 1, "skipped — round deadline expired");
assert_eq!(
state
.markers
.iter()
.filter(|m| m.starts_with("worker round 1 "))
.count(),
1,
"skip re-push dedupes per key"
);
}
#[tokio::test]
async fn load_seeds_commands_from_dump_after_crash() {
crate::util::test::init_management_test_stores().await;
let job_id = "research_dump_reload";
let conn = &crate::session::store().conn;
let now = crate::db::now();
crate::util::test::JobRowBuilder::new(conn, job_id, "research", "assistant", "ws")
.task("question?")
.user_name("caller-user")
.channel("telegram")
.timestamps(now.clone())
.insert()
.await
.unwrap();
let json = serde_json::to_string(&ResearchState::default()).unwrap();
conn.execute(
"INSERT INTO research_jobs (id, state) VALUES (?1, ?2)",
crate::db::params![job_id, json],
)
.await
.unwrap();
let run_root = crate::research_cleanup::ensure_run_root(job_id).await;
crate::research_cleanup::write_command_dump(
&run_root,
job_id,
&["pre-crash cmd".to_string()],
)
.await;
let loaded = ResearchState::load(job_id).await;
assert_eq!(
loaded.commands,
vec!["pre-crash cmd".to_string()],
"load() must seed commands from the dump"
);
assert!(
loaded.seen_commands.contains("pre-crash cmd"),
"seen-set rebuilt from the dump — post-resume dedup keeps the pre-crash capture"
);
finish_research_run(job_id).await;
}
fn plan_of(risks: &[&str]) -> MergedPlan {
MergedPlan {
sub_questions: risks
.iter()
.enumerate()
.map(|(i, risk)| MergedSubQuestion {
question: format!("direction {i}"),
evidence_needed: format!("evidence {i}"),
risk: (*risk).to_string(),
from_id: i,
also_ids: Vec::new(),
})
.collect(),
dropped: Vec::new(),
}
}
#[test]
fn test_plan_prefix_dispatches_what_the_allowance_carries() {
assert_eq!(plan_prefix(&[1, 1, 2, 1], 10), (4, 5));
assert_eq!(
plan_prefix(&[1, 1, 1, 1, 1], 3),
(3, 3),
"round 1 spends at most the allowance in total"
);
assert_eq!(
plan_prefix(&[2, 2, 2], 3),
(1, 2),
"a high-risk direction costs two slots"
);
assert_eq!(plan_prefix(&[1, 1], 0), (0, 0));
assert_eq!(plan_prefix(&[], 10), (0, 0));
}
#[test]
fn test_fit_plan_to_slots_merges_instead_of_dropping() {
let mut plan = plan_of(&["low"; 10]);
fit_plan_to_slots(&mut plan, 4);
assert!(
plan_slot_cost(&plan) <= 4,
"the fitted plan fits the allowance: {}",
plan_slot_cost(&plan)
);
assert_eq!(plan.sub_questions.len(), 3, "pairing halves until it fits");
let provenance: Vec<usize> = plan
.sub_questions
.iter()
.flat_map(|sq| std::iter::once(sq.from_id).chain(sq.also_ids.iter().copied()))
.collect();
let mut sorted = provenance.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(
sorted,
(0..10).collect::<Vec<_>>(),
"every direction stays accounted for — merged, never dropped"
);
assert_eq!(
provenance.len(),
10,
"no direction is cited twice by the fitted plan"
);
assert!(
plan.sub_questions[0].question.contains("direction 0")
&& plan.sub_questions[0].question.contains("direction 1"),
"a merged direction carries both: {}",
plan.sub_questions[0].question
);
assert_eq!(
plan.sub_questions[0].risk, "low",
"the merged risk is the higher of the two"
);
let mut plan = plan_of(&["high", "high"]);
fit_plan_to_slots(&mut plan, 2);
assert_eq!(plan_slot_cost(&plan), 2);
assert_eq!(plan.sub_questions.len(), 1);
assert_eq!(plan.sub_questions[0].risk, "high");
let mut plan = plan_of(&["low", "high"]);
fit_plan_to_slots(&mut plan, 3);
assert_eq!(plan.sub_questions.len(), 2);
}
#[test]
fn resolve_merged_plan_ids_composes_a_fold_without_losing_a_direction() {
let sq = |q: &str, e: &str, r: &str| SubQuestion {
question: q.into(),
evidence_needed: e.into(),
risk: r.into(),
};
let plans = vec![
DecompositionPlan {
sub_questions: vec![
sq("how widgets are styled", "css docs", "low"),
sq("widget accessibility", "a11y guide", "medium"),
],
},
DecompositionPlan {
sub_questions: vec![sq("how widgets are styled", "css docs", "low")],
},
];
let mut plan = MergedPlan {
sub_questions: vec![MergedSubQuestion {
from_id: 0,
also_ids: vec![1, 2],
question: String::new(),
evidence_needed: String::new(),
risk: String::new(),
}],
dropped: Vec::new(),
};
resolve_merged_plan_ids(&mut plan, &plans);
let resolved = &plan.sub_questions[0];
assert_eq!(
resolved.question, "how widgets are styled; widget accessibility",
"the folded-in direction keeps its text"
);
assert_eq!(
resolved.question.matches("how widgets are styled").count(),
1,
"an identical duplicate is named once"
);
assert_eq!(resolved.evidence_needed, "css docs; a11y guide");
assert_eq!(
resolved.risk, "medium",
"a fold carries the highest cited risk — width is never understated"
);
}
#[test]
fn merge_failure_fallback_keeps_every_decomposer_scope() {
let sq = |q: &str| SubQuestion {
question: q.into(),
evidence_needed: "e".into(),
risk: "low".into(),
};
let plans = vec![
DecompositionPlan {
sub_questions: vec![sq("a"), sq("b")],
},
DecompositionPlan {
sub_questions: vec![sq("b"), sq("c")],
},
];
let mut plan = concatenated_plan(&plans);
let questions: Vec<&str> = plan
.sub_questions
.iter()
.map(|s| s.question.as_str())
.collect();
assert_eq!(
questions,
vec!["a", "b", "c"],
"both plans' directions are kept, the exact duplicate once"
);
assert_eq!(
plan.sub_questions
.iter()
.map(|s| s.from_id)
.collect::<Vec<_>>(),
vec![0, 1, 3],
"provenance stays the input item's global flat id"
);
fit_plan_to_slots(&mut plan, 2);
assert_eq!(plan_slot_cost(&plan), 2, "the fallback is fitted too");
}
#[tokio::test]
async fn exhausted_run_still_delivers_an_answer_naming_the_unsettled_directions() {
crate::util::test::init_management_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/test_ws_research_exhausted");
let job_id = "research_job_exhausted_1";
let state = ResearchState {
stage: ResearchStage::Round1,
plan: Some(plan_of(&["low", "high"])),
gap_list: Some(GapList::default()),
budget_spent: RESEARCH_MAX_ANALYSTS,
..ResearchState::default()
};
seed_research_run(job_id, &ws, &state).await;
let exit = run_deep_research(&ws, "question?", job_id, true).await;
let ResearchExit::Terminal(Ok(output)) = exit else {
panic!("an exhausted run still terminalizes with an answer");
};
assert!(
output.answer.contains("analyst allowance exhausted"),
"the answer names why it is incomplete: {}",
output.answer
);
assert!(
output.answer.contains("direction 0") && output.answer.contains("direction 1"),
"every unsettled direction is named as an open question: {}",
output.answer
);
assert!(
!output.answer.contains("\n- none"),
"an empty report is never a valid outcome: {}",
output.answer
);
let state = ResearchState::load(job_id).await;
let answer =
write_terminalization_artifacts(job_id, &output.answer, &output.detail, &state).await;
assert!(
answer.contains(".detail.md"),
"the delivered answer refers to the detail file: {answer}"
);
assert!(
output.detail.contains("## Open Questions")
&& output.detail.contains("direction 0")
&& output.detail.contains("direction 1"),
"the detail file carries the full open-question list: {}",
output.detail
);
assert!(
output.detail.contains("## Run Summary"),
"run bookkeeping is detail, not answer: {}",
output.detail
);
assert!(
!output.answer.contains("## Run Summary"),
"the answer stays compact: {}",
output.answer
);
finish_research_run(job_id).await;
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn an_over_wide_plan_is_worked_as_far_as_the_allowance_carries_and_still_answers() {
crate::util::test::init_management_test_stores().await;
let ws = crate::workspace::test_ws("/tmp/test_ws_research_allowance");
let job_id = "research_job_allowance_1";
let findings = r#"{"claims":[{"claim":"alpha is true","source":"https://a","confidence":"high","contradictions":[]}],"unanswered":[]}"#;
let fake = std::sync::Arc::new(
crate::util::test::FakeProvider::new()
.ok("alpha is true") .ok(findings) .ok("the synthesized answer"), );
let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
let _seam = crate::util::test::install_retry_seam_dyn(provider);
let state = ResearchState {
stage: ResearchStage::Round1,
plan: Some(plan_of(&["low", "low"])),
gap_list: Some(GapList::default()),
budget_spent: RESEARCH_MAX_ANALYSTS - plan_slot_reserve() - 1,
..ResearchState::default()
};
seed_research_run(job_id, &ws, &state).await;
let exit = run_deep_research(&ws, "question?", job_id, true).await;
let ResearchExit::Terminal(Ok(output)) = exit else {
panic!("the over-wide plan must still terminalize with an answer");
};
assert!(
output.answer.contains("the synthesized answer"),
"the run reached synthesis from the direction it could work: {}",
output.answer
);
assert!(
output.detail.contains("alpha is true"),
"the dispatched direction's evidence reached the run: {}",
output.detail
);
assert!(
output.detail.contains("direction 1"),
"the direction the allowance could not carry stays open: {}",
output.detail
);
assert_eq!(
fake.request_messages.lock().unwrap().len(),
3,
"only the direction the allowance covers was dispatched"
);
finish_research_run(job_id).await;
}
#[test]
fn a_long_failure_reason_is_named_in_a_capped_header() {
let state = ResearchState {
acc: AccumulatedEvidence {
claims: vec![claim("alpha holds", "s", "high")],
..AccumulatedEvidence::default()
},
..ResearchState::default()
};
let open: Vec<String> = Vec::new();
let open_section = render_open_section(&open);
let budget = ResearchBudget::new(RESEARCH_MAX_ANALYSTS);
let report = RunReport {
state: &state,
recovered: &[],
verification: &[],
run_stats: &RunStats::default(),
budget: &budget,
open: &open,
open_section: &open_section,
rounds_used: 1,
wall: Duration::ZERO,
};
let reason = format!("synthesis failed: {}", "x".repeat(ANSWER_MAX_BYTES));
let out = report.output(AnswerSource::ProductBuilt(reason), "job");
let header = out.answer.lines().next().expect("the header is present");
assert!(
header.starts_with("## Deep Analysis Answer (incomplete — synthesis failed: ")
&& header.len() <= ANSWER_LINE_MAX_BYTES,
"the reason is named in a capped header: {} bytes",
header.len()
);
assert!(
out.answer.contains("alpha holds"),
"the established finding is still reported"
);
}
#[test]
fn product_built_answer_respects_the_size_ceiling() {
let mut state = ResearchState {
plan: Some(MergedPlan {
sub_questions: (0..200)
.map(|i| MergedSubQuestion {
question: format!("open question {i} {}", "y".repeat(500)),
evidence_needed: String::new(),
risk: "low".to_string(),
from_id: i,
also_ids: Vec::new(),
})
.collect(),
dropped: Vec::new(),
}),
..ResearchState::default()
};
state.acc.claims = (0..200)
.map(|i| claim(&format!("{i} {}", "x".repeat(2000)), "s", "high"))
.collect();
let open = open_questions(&state, &[], "the question");
let open_section = render_open_section(&open);
let budget = ResearchBudget::new(RESEARCH_MAX_ANALYSTS);
let report = RunReport {
state: &state,
recovered: &[],
verification: &[],
run_stats: &RunStats::default(),
budget: &budget,
open: &open,
open_section: &open_section,
rounds_used: 1,
wall: Duration::ZERO,
};
let out = report.output(
AnswerSource::ProductBuilt("no evidence was gathered".to_string()),
"job",
);
let delivered_len = out.answer.len() + detail_reference_len("job");
assert!(
delivered_len <= ANSWER_MAX_BYTES,
"the answer stays at its own size, reference included: {delivered_len} bytes"
);
assert!(
out.answer
.contains("more, listed in full in the detail file"),
"what the answer leaves out is named: {}",
out.answer
);
assert!(
out.answer.contains("0 xxxx")
&& !out.answer.contains(&"x".repeat(ANSWER_LINE_MAX_BYTES)),
"every shown line is capped"
);
assert!(
out.answer
.contains("### Questions This Run Could Not Settle")
&& out.answer.contains("open question 0"),
"the open questions are named compactly, the rest deferred"
);
assert!(
out.detail.contains("open question 199") && out.detail.contains("199 xxxx"),
"the detail file keeps everything"
);
}
#[test]
fn detail_file_carries_verification_and_the_worker_output() {
let mut state = ResearchState::default();
state
.worker_reports
.push("prototype built and ran".to_string());
let verification = vec![VerificationResult {
claim: "alpha is true".to_string(),
verdict: "confirmed".to_string(),
evidence: "two sources agree".to_string(),
tool_calls: 1,
searches: 1,
queries: Vec::new(),
}];
let open = open_questions(&state, &[], "the question");
let open_section = render_open_section(&open);
let budget = ResearchBudget::new(RESEARCH_MAX_ANALYSTS);
let report = RunReport {
state: &state,
recovered: &[],
verification: &verification,
run_stats: &RunStats::default(),
budget: &budget,
open: &open,
open_section: &open_section,
rounds_used: 1,
wall: Duration::ZERO,
};
let out = report.output(AnswerSource::Synthesized("the answer".to_string()), "job");
assert_eq!(out.answer.lines().next(), Some("the answer"));
assert!(
!out.answer.contains("## Verification") && !out.answer.contains("Tested in Practice"),
"detail material never enters the answer: {}",
out.answer
);
assert!(
out.detail.contains("## Verification")
&& out
.detail
.contains("alpha is true → **confirmed** — two sources agree"),
"verification verdicts are detail: {}",
out.detail
);
assert!(
out.detail.contains("## Tested in Practice")
&& out.detail.contains("prototype built and ran"),
"the worker round's output is detail: {}",
out.detail
);
}
#[tokio::test]
async fn terminalization_writes_the_answer_and_its_detail_side_by_side() {
crate::util::test::init_management_test_stores().await;
let job_id = "research_job_artifacts_1";
let state = ResearchState::default();
let delivered =
write_terminalization_artifacts(job_id, "the answer", "the detail", &state).await;
let answer = crate::research_cleanup::results_archive_path(job_id).unwrap();
let detail = crate::research_cleanup::detail_archive_path(job_id).unwrap();
assert_eq!(
answer.parent(),
detail.parent(),
"the detail sits in the same place the answer is kept"
);
assert!(
delivered.contains(&detail.display().to_string()),
"the answer refers to the detail file it was written with: {delivered}"
);
let answer_text = tokio::fs::read_to_string(&answer).await.unwrap();
assert!(
answer_text.starts_with("# Research research_job_artifacts_1")
&& answer_text.contains("the answer")
&& answer_text.contains(&detail.display().to_string()),
"{answer_text}"
);
assert_eq!(
tokio::fs::read_to_string(&detail).await.unwrap().trim_end(),
"the detail"
);
write_terminalization_artifacts(job_id, "the answer", "the detail", &state).await;
assert_eq!(
tokio::fs::read_to_string(&detail)
.await
.unwrap()
.matches("the detail")
.count(),
1,
"the detail file is rewritten, not appended to"
);
let other = "research_job_artifacts_2";
write_terminalization_artifacts(other, "the answer", "", &state).await;
assert!(
crate::research_cleanup::results_archive_path(other)
.unwrap()
.exists()
);
assert!(
!crate::research_cleanup::detail_archive_path(other)
.unwrap()
.exists(),
"empty detail content writes nothing"
);
for id in [job_id, other] {
for path in [
crate::research_cleanup::results_archive_path(id),
crate::research_cleanup::detail_archive_path(id),
] {
let _ = tokio::fs::remove_file(path.unwrap()).await;
}
let _ = tokio::fs::remove_dir_all(crate::research_cleanup::run_root_path(id)).await;
}
}
#[test]
fn duplicate_drop_is_word_coverage() {
let kept = vec!["How widgets are styled in CSS".to_string()];
assert!(is_duplicate_drop("how widgets are styled", &kept));
assert!(
is_duplicate_drop("Widgets, styled how?", &kept),
"case, punctuation and word order do not matter"
);
assert!(
!is_duplicate_drop("grid layout for widgets", &kept),
"distinct scope is never a duplicate drop"
);
assert!(
!is_duplicate_drop(" ", &kept),
"an empty drop is not a duplicate"
);
}
#[test]
fn open_questions_follow_the_plan_and_what_was_examined() {
let state = ResearchState {
plan: Some(plan_of(&["low", "high"])),
..ResearchState::default()
};
assert_eq!(
open_questions(&state, &[], "q"),
vec!["direction 0", "direction 1"],
"an unexamined direction is always named"
);
let state = ResearchState {
examined: vec![0],
..state
};
assert_eq!(
open_questions(&state, &[], "q"),
vec!["direction 1"],
"an examined direction is no longer open"
);
let state = ResearchState {
examined: vec![0, 1],
..state
};
assert!(open_questions(&state, &[], "q").is_empty());
assert_eq!(
open_questions(&ResearchState::default(), &[], "the question"),
vec!["the question"],
"without a plan the question itself is what stayed open"
);
}
#[test]
fn a_synthesized_answer_carries_the_product_built_open_section() {
let state = ResearchState {
plan: Some(plan_of(&["low", "low"])),
examined: vec![0],
..ResearchState::default()
};
let open = open_questions(&state, &[], "q");
let open_section = render_open_section(&open);
let budget = ResearchBudget::new(RESEARCH_MAX_ANALYSTS);
let report = RunReport {
state: &state,
recovered: &[],
verification: &[],
run_stats: &RunStats::default(),
budget: &budget,
open: &open,
open_section: &open_section,
rounds_used: 1,
wall: Duration::ZERO,
};
let text = "y".repeat(answer_text_ceiling(&open_section, "job"));
let out = report.output(AnswerSource::Synthesized(text), "job");
assert!(
out.answer.starts_with("yyyy")
&& out
.answer
.contains("### Questions This Run Could Not Settle")
&& out.answer.contains("direction 1"),
"the synthesized answer names what stayed open: {}",
&out.answer[out.answer.len() - 500..]
);
assert!(
!out.answer.contains("direction 0"),
"an examined direction is not reported open"
);
assert!(
out.answer.len() + detail_reference_len("job") <= ANSWER_MAX_BYTES,
"text + section + reference fit the ceiling: {} bytes",
out.answer.len() + detail_reference_len("job")
);
}
#[test]
fn claim_lines_are_verbatim_for_prompts_and_escaped_for_the_reader() {
let acc = AccumulatedEvidence {
claims: vec![claim("uses ``` fences", "s", "high")],
..AccumulatedEvidence::default()
};
let mut prompt = String::new();
render_claims(&mut prompt, &acc, RenderTarget::Prompt);
assert!(prompt.contains("uses ``` fences"), "{prompt}");
let mut delivered = String::new();
render_claims(&mut delivered, &acc, RenderTarget::Delivered);
assert!(!delivered.contains("```"), "{delivered}");
let capped = cap_answer_line("- 0123456789\n", 6);
assert!(
capped.len() <= 6 && capped.ends_with('\n'),
"{capped:?} is {} bytes, newline included",
capped.len()
);
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn a_checkpoint_without_a_plan_still_delivers_an_answer() {
crate::util::test::init_management_test_stores().await;
let fake =
crate::util::test::FakeProvider::new().ok("answer from the accumulated evidence");
let _seam = crate::util::test::install_retry_seam(fake);
let ws = crate::workspace::test_ws("/tmp/test_ws_research_plan_lost");
let job_id = "research_job_plan_lost_1";
let mut state = ResearchState {
stage: ResearchStage::Round1,
acc: AccumulatedEvidence {
claims: vec![claim("alpha is a real project", "s1", "high")],
..AccumulatedEvidence::default()
},
verification: vec![crate::tools::analyze::VerificationResult {
claim: "alpha is a real project".into(),
verdict: "confirmed".into(),
evidence: "primary source".into(),
tool_calls: 0,
searches: 0,
queries: vec![],
}],
..ResearchState::default()
};
state.acc.rebuild_keys();
seed_research_run(job_id, &ws, &state).await;
let exit = run_deep_research(&ws, "question?", job_id, true).await;
let ResearchExit::Terminal(Ok(output)) = exit else {
panic!("a plan-less checkpoint still ends with an answer");
};
assert!(
output
.answer
.contains("answer from the accumulated evidence"),
"the answer is built from what the run established: {}",
output.answer
);
assert!(
output.answer.contains("question?") && output.answer.contains("Could Not Settle"),
"the question itself is named as what stayed open: {}",
output.answer
);
let state = ResearchState::load(job_id).await;
assert!(
state.markers.iter().any(|m| m == PLAN_LOST_MARKER),
"the lost plan is recorded: {:?}",
state.markers
);
finish_research_run(job_id).await;
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn an_accepted_merge_is_worked_through_to_an_answer() {
crate::util::test::init_management_test_stores().await;
let _policy_guard =
crate::util::test::install_test_retry_policy(crate::retry::tiny_test_policy());
let ws = crate::workspace::test_ws("/tmp/test_ws_research_merge_ok");
let job_id = "research_job_merge_ok_1";
let decomposed = r#"{"sub_questions":[{"question":"alpha direction","evidence_needed":"a docs","risk":"low"}]}"#;
let merged = r#"{"sub_questions":[{"from_id":0,"also_ids":[1]}],"dropped":[]}"#;
let findings = r#"{"claims":[{"claim":"alpha holds","source":"https://a","confidence":"high","contradictions":[]}],"unanswered":[]}"#;
let fake = std::sync::Arc::new(
crate::util::test::FakeProvider::new()
.ok(decomposed)
.ok(decomposed)
.ok(decomposed)
.ok(decomposed)
.ok(merged)
.ok(findings)
.ok(findings)
.ok("{\"gaps\":[]}")
.ok("the synthesized answer"),
);
let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
let _seam = crate::util::test::install_retry_seam_dyn(provider);
let state = ResearchState::default();
seed_research_run(job_id, &ws, &state).await;
let exit = run_deep_research(&ws, "question?", job_id, true).await;
let ResearchExit::Terminal(Ok(output)) = exit else {
panic!("an accepted merge must reach an answer");
};
assert!(
output.answer.contains("the synthesized answer"),
"the run worked the merged plan and reached synthesis: {}",
output.answer
);
assert!(
output.answer.contains("- no open questions were recorded"),
"the merged direction was examined: {}",
output.answer
);
assert!(
output.detail.contains("alpha holds"),
"the finding is in the detail file"
);
let state = ResearchState::load(job_id).await;
assert!(
!state.markers.iter().any(|m| m == PLAN_MERGE_FAILED),
"the merge was accepted, not fallen back from: {:?}",
state.markers
);
let plan = state.plan.expect("the plan is checkpointed");
assert_eq!(
plan.sub_questions.len(),
1,
"the merge's fold is the plan the run carried: {:?}",
plan.sub_questions
);
assert_eq!(plan.sub_questions[0].from_id, 0);
assert_eq!(
plan.sub_questions[0].also_ids,
vec![1],
"both proposed directions are accounted for by the fold"
);
finish_research_run(job_id).await;
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn merge_failure_fits_the_plan_to_the_allowance_and_still_answers() {
crate::util::test::init_management_test_stores().await;
let _policy_guard =
crate::util::test::install_test_retry_policy(crate::retry::tiny_test_policy());
let ws = crate::workspace::test_ws("/tmp/test_ws_research_round0");
let job_id = "research_job_round0_1";
let plan = r#"{"sub_questions":[
{"question":"alpha direction","evidence_needed":"a docs","risk":"low"},
{"question":"beta direction","evidence_needed":"b docs","risk":"low"},
{"question":"gamma direction","evidence_needed":"c docs","risk":"low"},
{"question":"delta direction","evidence_needed":"d docs","risk":"low"}]}"#;
let findings = r#"{"claims":[{"claim":"alpha holds","source":"https://a","confidence":"high","contradictions":[]}],"unanswered":[]}"#;
let fake = std::sync::Arc::new(
crate::util::test::FakeProvider::new()
.ok(plan)
.ok(plan)
.ok(plan)
.ok(plan)
.ok("not a plan")
.ok("not a plan")
.ok("not a plan")
.ok(findings)
.ok(findings)
.ok(findings)
.ok(findings)
.ok("{\"gaps\":[]}")
.ok("the synthesized answer"),
);
let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
let _seam = crate::util::test::install_retry_seam_dyn(provider);
let state = ResearchState {
stage: ResearchStage::Decompose,
budget_spent: RESEARCH_MAX_ANALYSTS - plan_slot_reserve() - DECOMPOSE_FAN_OUT - 2,
..ResearchState::default()
};
seed_research_run(job_id, &ws, &state).await;
let exit = run_deep_research(&ws, "question?", job_id, true).await;
let ResearchExit::Terminal(Ok(output)) = exit else {
panic!("a failed merge must still end with an answer");
};
assert!(
output.answer.contains("the synthesized answer"),
"the run worked the fitted plan and reached synthesis: {}",
output.answer
);
assert!(
output.answer.contains("- no open questions were recorded"),
"every fitted direction was examined: {}",
output.answer
);
let state = ResearchState::load(job_id).await;
assert!(
state.markers.iter().any(|m| m == PLAN_MERGE_FAILED),
"the fallback is recorded: {:?}",
state.markers
);
let plan = state.plan.expect("the plan is checkpointed");
assert_eq!(
plan.sub_questions.len(),
2,
"the fallback is fitted to the two plan slots: {:?}",
plan.sub_questions
);
assert!(
plan.sub_questions[0].question.contains("alpha direction")
&& plan.sub_questions[0].question.contains("beta direction")
&& plan.sub_questions[1].question.contains("gamma direction")
&& plan.sub_questions[1].question.contains("delta direction"),
"no direction is dropped to fit: {:?}",
plan.sub_questions
);
assert_eq!(
fake.request_messages.lock().unwrap().len(),
13,
"the run worked exactly the plan the allowance covers"
);
finish_research_run(job_id).await;
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn a_total_decomposition_failure_still_delivers_an_answer() {
crate::util::test::init_management_test_stores().await;
let _policy_guard =
crate::util::test::install_test_retry_policy(crate::retry::tiny_test_policy());
let ws = crate::workspace::test_ws("/tmp/test_ws_research_nodecompose");
let job_id = "research_job_nodecompose_1";
let fake = crate::util::test::FakeProvider::new()
.ok("not a plan")
.ok("not a plan")
.ok("not a plan")
.ok("not a plan")
.ok("not a plan")
.ok("not a plan")
.ok("not a plan")
.ok("not a plan");
let provider: std::sync::Arc<dyn crate::Provider> = std::sync::Arc::new(fake);
let _seam = crate::util::test::install_retry_seam_dyn(provider);
let conn = &crate::session::store().conn;
let now = crate::db::now();
crate::util::test::JobRowBuilder::new(conn, job_id, "research", "assistant", &ws.name)
.task("why is the sky blue?")
.user_name("caller-user")
.channel("telegram")
.timestamps(now.clone())
.insert()
.await
.unwrap();
let exit = run_deep_research(&ws, "why is the sky blue?", job_id, true).await;
let ResearchExit::Terminal(Ok(output)) = exit else {
panic!("a total decomposition failure still ends with an answer");
};
assert!(
output.answer.contains("could not be decomposed")
&& output.answer.contains("nothing was established"),
"the answer reports what it did establish: {}",
output.answer
);
assert!(
output.answer.contains("why is the sky blue?"),
"the question itself is named as what stayed open: {}",
output.answer
);
assert!(
!output.answer.contains("- none"),
"an empty report is never a valid outcome: {}",
output.answer
);
assert!(
output.detail.contains("## Open Questions"),
"the detail file carries the open-question list: {}",
output.detail
);
finish_research_run(job_id).await;
}
}