use std::borrow::Cow;
use std::future::Future;
use std::sync::Arc;
use rmcp::model::Tool;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{Map, Value, json};
use super::SymForgeServer;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SurfaceProfile {
Full,
Compact,
Meta,
}
pub fn surface_profile_from_env() -> SurfaceProfile {
match std::env::var("SYMFORGE_SURFACE")
.ok()
.map(|v| v.to_ascii_lowercase())
{
Some(ref s) if s == "compact" => SurfaceProfile::Compact,
Some(ref s) if s == "meta" => SurfaceProfile::Meta,
_ => SurfaceProfile::Full,
}
}
pub fn surface_profile_label(profile: SurfaceProfile) -> &'static str {
match profile {
SurfaceProfile::Full => "full",
SurfaceProfile::Meta => "meta",
SurfaceProfile::Compact => "compact",
}
}
pub fn surface_label_from_str(value: &str) -> Option<&'static str> {
surface_profile_from_label(value).map(surface_profile_label)
}
pub const CONNECTION_SURFACE_HEADER: &str = "x-symforge-connection-surface";
pub fn surface_profile_from_label(value: &str) -> Option<SurfaceProfile> {
match value {
"full" => Some(SurfaceProfile::Full),
"meta" => Some(SurfaceProfile::Meta),
"compact" => Some(SurfaceProfile::Compact),
_ => None,
}
}
tokio::task_local! {
static CONNECTION_SURFACE: SurfaceProfile;
}
pub fn connection_surface_or_env() -> SurfaceProfile {
CONNECTION_SURFACE
.try_with(|profile| *profile)
.unwrap_or_else(|_| surface_profile_from_env())
}
pub async fn with_connection_surface<F, T>(profile: Option<SurfaceProfile>, future: F) -> T
where
F: Future<Output = T>,
{
match profile {
Some(profile) => CONNECTION_SURFACE.scope(profile, future).await,
None => future.await,
}
}
pub fn compact_surface_blocks(profile: SurfaceProfile, tool_name: &str) -> bool {
profile == SurfaceProfile::Compact
&& !crate::stel::surface::COMPACT_TOOL_NAMES.contains(&tool_name)
}
pub fn enforce_compact_surface(tool_name: &str) -> Result<(), rmcp::ErrorData> {
if compact_surface_blocks(surface_profile_from_env(), tool_name) {
return Err(rmcp::ErrorData::invalid_request(
format!(
"tool '{tool_name}' not available on compact surface; unset SYMFORGE_SURFACE or set SYMFORGE_SURFACE=full for the full tool surface"
),
None,
));
}
Ok(())
}
pub fn list_tools_for_profile(profile: SurfaceProfile) -> Vec<Tool> {
match profile {
SurfaceProfile::Full => SymForgeServer::tool_router()
.list_all()
.into_iter()
.filter(|tool| tool.name.as_ref() != "symforge")
.collect(),
SurfaceProfile::Compact => compact_probe_tools(),
SurfaceProfile::Meta => meta_probe_tools(),
}
}
fn schema_object(value: Value) -> Arc<Map<String, Value>> {
Arc::new(
value
.as_object()
.expect("compact probe schema must be a JSON object")
.clone(),
)
}
fn probe_tool(name: &'static str, description: &'static str, input_schema: Value) -> Tool {
let mut tool = Tool::default();
tool.name = Cow::Borrowed(name);
tool.description = Some(Cow::Borrowed(description));
tool.input_schema = schema_object(input_schema);
tool
}
fn symforge_facade_schema() -> Value {
json!({
"type": "object",
"properties": {
"query": { "type": "string" },
"intent": {
"type": "string",
"enum": ["auto", "orient", "find", "read", "trace", "impact", "meta"]
},
"path": { "type": "string" },
"symbol": { "type": "string" },
"max_tokens": { "type": "integer", "minimum": 64 },
"preview": { "type": "boolean" }
},
"required": ["query"]
})
}
#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct StelFacadeProbeInput {
pub query: String,
#[serde(default)]
pub intent: Option<String>,
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub symbol: Option<String>,
#[serde(default, rename = "_probe_legacy_tool")]
pub probe_legacy_tool: Option<String>,
#[serde(default, rename = "_probe_legacy_args")]
pub probe_legacy_args: Option<Value>,
}
pub fn resolve_facade_probe(input: &StelFacadeProbeInput) -> Result<(String, Value), String> {
let legacy_tool = input.probe_legacy_tool.as_deref().ok_or_else(|| {
"Phase 0 facade relay requires `_probe_legacy_tool` (A-019 battery harness only)"
.to_string()
})?;
let legacy_args = input.probe_legacy_args.clone().ok_or_else(|| {
"Phase 0 facade relay requires `_probe_legacy_args` (A-019 battery harness only)"
.to_string()
})?;
Ok((legacy_tool.to_string(), legacy_args))
}
pub fn meta_probe_tools() -> Vec<Tool> {
vec![probe_tool(
"symforge",
"STEL meta-tool facade (Phase 0 measurement probe)",
symforge_facade_schema(),
)]
}
pub fn compact_probe_tools() -> Vec<Tool> {
vec![
probe_tool(
"symforge",
"STEL read/explore facade (Phase 0 measurement probe)",
symforge_facade_schema(),
),
probe_tool(
"symforge_edit",
"STEL structural edit facade (Phase 0 measurement probe)",
json!({
"type": "object",
"properties": {
"path": { "type": "string" },
"symbol": { "type": "string" },
"body": { "type": "string" },
"intent": { "type": "string", "enum": ["edit"] }
},
"required": ["path"]
}),
),
probe_tool(
"status",
"STEL trust envelope / index health (Phase 0 measurement probe)",
json!({
"type": "object",
"properties": {
"detail": { "type": "string", "enum": ["compact", "full"] }
}
}),
),
]
}
pub fn symforge_edit_schema_bytes() -> usize {
let edit = compact_probe_tools()
.into_iter()
.find(|t| t.name == "symforge_edit")
.expect("symforge_edit probe tool");
serde_json::to_string(&edit.input_schema)
.expect("edit schema serializes")
.len()
}
pub fn list_tools_schema_bytes(profile: SurfaceProfile) -> (usize, usize) {
let tools = list_tools_for_profile(profile);
let payload = json!({ "tools": tools });
let bytes = serde_json::to_string(&payload)
.expect("compact probe tools must serialize")
.len();
(tools.len(), bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compact_surface_is_three_tools_under_h1_budget() {
let (count, bytes) = list_tools_schema_bytes(SurfaceProfile::Compact);
assert_eq!(count, 3, "compact probe must expose exactly 3 tools");
assert!(
bytes <= 5000,
"compact tools/list JSON must be <= 5000 B (H1); got {bytes} B"
);
}
#[test]
fn symforge_edit_schema_under_a025_budget() {
let tools = compact_probe_tools();
let edit = tools
.iter()
.find(|t| t.name == "symforge_edit")
.expect("symforge_edit must exist");
let bytes = serde_json::to_string(&edit.input_schema)
.expect("edit schema must serialize")
.len();
assert!(
bytes <= 1500,
"symforge_edit input_schema must be <= 1500 B (A-025); got {bytes} B"
);
}
#[test]
fn full_profile_lists_legacy_tool_count() {
let tools = list_tools_for_profile(SurfaceProfile::Full);
assert!(
tools.len() >= 30,
"full surface must expose legacy tool count; got {}",
tools.len()
);
assert!(
!tools.iter().any(|t| t.name == "symforge"),
"full surface must not advertise symforge facade"
);
}
#[test]
fn meta_surface_is_one_tool_under_h1_budget() {
let (count, bytes) = list_tools_schema_bytes(SurfaceProfile::Meta);
assert_eq!(count, 1, "meta-1 probe must expose exactly 1 tool");
assert!(
bytes <= 5000,
"meta tools/list JSON must be <= 5000 B (H1); got {bytes} B"
);
}
#[test]
fn facade_probe_requires_harness_fields() {
let input = StelFacadeProbeInput {
query: "x".to_string(),
intent: None,
path: None,
symbol: None,
probe_legacy_tool: None,
probe_legacy_args: None,
};
assert!(resolve_facade_probe(&input).is_err());
}
#[test]
fn surface_profile_from_label_roundtrips_canonical_and_rejects_junk() {
assert_eq!(
surface_profile_from_label("full"),
Some(SurfaceProfile::Full)
);
assert_eq!(
surface_profile_from_label("compact"),
Some(SurfaceProfile::Compact)
);
assert_eq!(
surface_profile_from_label("meta"),
Some(SurfaceProfile::Meta)
);
assert_eq!(surface_profile_from_label("FULL"), None);
assert_eq!(surface_profile_from_label("nonsense"), None);
assert_eq!(surface_profile_from_label(""), None);
}
#[tokio::test]
async fn connection_surface_scope_binds_then_unbinds() {
let bound = with_connection_surface(Some(SurfaceProfile::Compact), async {
connection_surface_or_env()
})
.await;
assert_eq!(bound, SurfaceProfile::Compact);
let unbound = with_connection_surface(None, async { connection_surface_or_env() }).await;
assert_eq!(unbound, surface_profile_from_env());
}
}