use rmcp::model::{CallToolResult, ContentBlock, JsonObject, MetaObject};
use serde::{Deserialize, Serialize};
use std::future::Future;
pub const RESULT_STATUS_META_KEY: &str = "symforge/result_status";
pub const RESULT_STATUS_CONTRACT_VERSION: u8 = 1;
pub use crate::index_lifecycle::guidance::outcome::OutcomeClass;
#[cfg(test)]
pub(crate) use crate::index_lifecycle::guidance::outcome::read_outcome_cases;
pub const PROJECT_EVIDENCE_META_KEY: &str = "symforge/project_evidence";
pub const REPEAT_NOTICE_META_KEY: &str = "symforge/repeat_notice";
pub const REPEAT_NOTICE_CONTRACT_VERSION: u8 = 2;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepeatNoticeView {
pub contract_version: u8,
pub repeat_count: u32,
pub tool: String,
pub request_hash: String,
pub evidence_generation: u64,
}
pub fn observed_outcome_class(meta: Option<&MetaObject>) -> Option<OutcomeClass> {
#[derive(Deserialize)]
struct OutcomeClassOnly {
outcome_class: OutcomeClass,
}
let value = meta?.0.get(RESULT_STATUS_META_KEY)?;
serde_json::from_value::<OutcomeClassOnly>(value.clone())
.ok()
.map(|view| view.outcome_class)
}
pub const PROJECT_EVIDENCE_HEADER: &str = "x-symforge-project-evidence";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectEvidence {
pub project_id: String,
pub project_name: String,
pub canonical_root: Option<String>,
pub generation: u64,
pub index_state: String,
pub load_source: String,
pub index_files: usize,
pub index_symbols: usize,
}
pub fn project_evidence_matches_selector(
evidence: &ProjectEvidence,
selector: Option<&str>,
) -> bool {
let Some(root) = evidence.canonical_root.as_deref() else {
return false;
};
let computed = crate::daemon::project_key(std::path::Path::new(root));
if computed != evidence.project_id {
return false;
}
let Some(selector) = selector.filter(|value| !value.trim().is_empty()) else {
return true;
};
if selector.starts_with("project-v1-") {
evidence.project_id == selector
} else {
evidence.project_id == selector || evidence.project_name == selector
}
}
tokio::task_local! {
static PROJECT_EVIDENCE: std::cell::RefCell<Option<ProjectEvidence>>;
}
pub async fn with_project_evidence_scope<F, T>(seed: Option<ProjectEvidence>, future: F) -> T
where
F: Future<Output = T>,
{
PROJECT_EVIDENCE
.scope(std::cell::RefCell::new(seed), future)
.await
}
pub fn record_project_evidence(evidence: ProjectEvidence) {
let _ = PROJECT_EVIDENCE.try_with(|cell| *cell.borrow_mut() = Some(evidence));
}
pub fn clear_project_evidence() {
let _ = PROJECT_EVIDENCE.try_with(|cell| *cell.borrow_mut() = None);
}
pub fn current_project_evidence() -> Option<ProjectEvidence> {
PROJECT_EVIDENCE
.try_with(|cell| cell.borrow().clone())
.ok()
.flatten()
}
pub const READ_OUTCOME_HEADER: &str = "x-symforge-read-outcome";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReadOutcome {
Found,
Empty,
NotFound,
Ambiguous,
InvalidRequest,
Unavailable {
retryable: bool,
},
}
impl ReadOutcome {
pub fn from_class(class: OutcomeClass) -> Self {
match class {
OutcomeClass::Found => Self::Found,
OutcomeClass::EmptyResult => Self::Empty,
OutcomeClass::NotFound => Self::NotFound,
OutcomeClass::Ambiguous => Self::Ambiguous,
OutcomeClass::InvalidRequest => Self::InvalidRequest,
OutcomeClass::InternalFailure => Self::Unavailable { retryable: false },
}
}
pub fn class(self) -> OutcomeClass {
match self {
Self::Found => OutcomeClass::Found,
Self::Empty => OutcomeClass::EmptyResult,
Self::NotFound => OutcomeClass::NotFound,
Self::Ambiguous => OutcomeClass::Ambiguous,
Self::InvalidRequest => OutcomeClass::InvalidRequest,
Self::Unavailable { .. } => OutcomeClass::InternalFailure,
}
}
}
tokio::task_local! {
static READ_OUTCOME: std::cell::RefCell<Option<ReadOutcome>>;
}
pub async fn with_read_outcome_scope<F>(future: F) -> (F::Output, Option<ReadOutcome>)
where
F: Future,
{
READ_OUTCOME
.scope(std::cell::RefCell::new(None), async {
let output = future.await;
let outcome = READ_OUTCOME.with(|cell| *cell.borrow());
(output, outcome)
})
.await
}
pub async fn read_with_outcome<F>(future: F) -> (F::Output, Option<ReadOutcome>)
where
F: Future,
{
let (output, outcome) = with_read_outcome_scope(future).await;
if let Some(outcome) = outcome {
record_read_outcome(outcome);
}
(output, outcome)
}
pub fn record_read_outcome(outcome: ReadOutcome) {
let _ = READ_OUTCOME.try_with(|cell| *cell.borrow_mut() = Some(outcome));
}
pub fn attach_project_evidence_meta(meta: &mut Option<MetaObject>) {
let meta = meta.get_or_insert_with(|| MetaObject(JsonObject::new()));
if meta.0.contains_key(PROJECT_EVIDENCE_META_KEY) {
return;
}
let value = match current_project_evidence().map(|e| serde_json::to_value(&e)) {
Some(Ok(value)) => value,
_ => serde_json::json!({
"bound": false,
"reason": "project_evidence_unavailable",
}),
};
meta.0.insert(PROJECT_EVIDENCE_META_KEY.to_string(), value);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResultStatus {
pub contract_version: u8,
pub outcome_class: OutcomeClass,
}
impl ResultStatus {
pub const fn new(outcome_class: OutcomeClass) -> Self {
Self {
contract_version: RESULT_STATUS_CONTRACT_VERSION,
outcome_class,
}
}
pub fn into_mutation_call_tool_result(self, human_text: impl Into<String>) -> CallToolResult {
let is_error = !matches!(self.outcome_class, OutcomeClass::Found);
self.into_call_tool_result_with(human_text, is_error)
}
pub fn into_call_tool_result(self, human_text: impl Into<String>) -> CallToolResult {
let is_error = self.outcome_class.is_error();
self.into_call_tool_result_with(human_text, is_error)
}
fn into_call_tool_result_with(
self,
human_text: impl Into<String>,
is_error: bool,
) -> CallToolResult {
let mut meta = JsonObject::new();
meta.insert(
RESULT_STATUS_META_KEY.to_string(),
serde_json::to_value(self).expect("ResultStatus must serialize to JSON"),
);
if let Some(evidence) = current_project_evidence()
&& let Ok(value) = serde_json::to_value(&evidence)
{
meta.insert(PROJECT_EVIDENCE_META_KEY.to_string(), value);
}
if let Some(withheld) = crate::protocol::withheld::take_pending_withheld()
&& let Ok(value) = serde_json::to_value(&withheld)
{
meta.insert(
crate::protocol::withheld::WITHHELD_META_KEY.to_string(),
value,
);
}
let content = vec![ContentBlock::text(human_text.into())];
let result = if is_error {
CallToolResult::error(content)
} else {
CallToolResult::success(content)
};
result.with_meta(Some(MetaObject(meta)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_evidence_selector_matching_preserves_nonblank_whitespace() {
let root = std::path::Path::new("/work/repo");
let evidence = ProjectEvidence {
project_id: crate::daemon::project_key(root),
project_name: "repo".to_string(),
canonical_root: Some(root.display().to_string()),
generation: 1,
index_state: "ready".to_string(),
load_source: "memory".to_string(),
index_files: 1,
index_symbols: 1,
};
assert!(project_evidence_matches_selector(&evidence, Some("repo")));
assert!(
!project_evidence_matches_selector(&evidence, Some("repo ")),
"a legal trailing space must not be normalized onto another project name"
);
assert!(project_evidence_matches_selector(&evidence, Some(" ")));
}
#[test]
fn observed_outcome_class_reads_only_outcome_class_and_tolerates_unknown_fields() {
fn meta_with(value: serde_json::Value) -> MetaObject {
let mut meta = JsonObject::new();
meta.insert(RESULT_STATUS_META_KEY.to_string(), value);
MetaObject(meta)
}
let statused = ResultStatus::new(OutcomeClass::EmptyResult).into_call_tool_result("x");
assert_eq!(
observed_outcome_class(statused.meta.as_ref()),
Some(OutcomeClass::EmptyResult)
);
let wider = meta_with(serde_json::json!({
"contract_version": 1,
"outcome_class": "internal_failure",
"status": "failed",
"operations": [
{ "operation_index": 0, "status": "failed", "outcome_class": "internal_failure" }
],
}));
assert_eq!(
observed_outcome_class(Some(&wider)),
Some(OutcomeClass::InternalFailure)
);
assert_eq!(observed_outcome_class(None), None);
assert_eq!(
observed_outcome_class(Some(&MetaObject(JsonObject::new()))),
None
);
assert_eq!(
observed_outcome_class(Some(&meta_with(serde_json::json!("found")))),
None
);
assert_eq!(
observed_outcome_class(Some(&meta_with(serde_json::json!({
"contract_version": 1,
"outcome_class": "FOUND",
})))),
None,
"the enum's real serde spelling is snake_case; anything else is unobservable"
);
assert_eq!(
observed_outcome_class(Some(&meta_with(
serde_json::json!({ "contract_version": 1 })
))),
None
);
}
}