use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use serde::Serialize;
use crate::cli::harness::{AttachEntry, HarnessRegistry, HarnessState, HarnessStatus};
use crate::protocol::surface_probe::{
SurfaceProfile, list_tools_for_profile, surface_profile_from_env,
};
use crate::server::ServerRuntime;
use crate::server::aap::{AapDetection, AapPresets, EmbedPinComparison, IntegrationMode};
use crate::stel::ledger::{Run, collapse_runs, stored_record_identity};
use crate::stel::ledger_store::{StelLedgerStore, StoredLedgerRecord};
const RECENT_RUNS_WINDOW: usize = 50;
#[derive(Debug, Clone, Serialize)]
pub struct CompressionHeuristicView {
pub cache_hits: u32,
pub ccr_offloads: u32,
pub ccr_bytes_stored: u64,
pub ccr_bytes_retrieved: u64,
}
impl CompressionHeuristicView {
pub fn from_runtime(runtime: &ServerRuntime) -> Self {
let h = runtime.protocol().session_compression_heuristic();
Self {
cache_hits: h.cache_hits,
ccr_offloads: h.ccr_offloads,
ccr_bytes_stored: h.ccr_bytes_stored,
ccr_bytes_retrieved: h.ccr_bytes_retrieved,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct LedgerSummaryView {
pub available: bool,
pub total_events: Option<u64>,
pub total_net_vs_manual: Option<i64>,
pub accepted_count: Option<u64>,
pub session_count: Option<u64>,
pub compression_heuristic: CompressionHeuristicView,
pub recent_runs: Vec<LedgerRunView>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recent_runs_window: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct LedgerRunView {
pub count: u64,
pub first_ts_ms: u64,
pub last_ts_ms: u64,
pub window_clipped: bool,
pub session_id: String,
pub surface: String,
pub intent: String,
pub decision: String,
pub tools_called: Option<Vec<String>>,
pub route_confidence: String,
pub pff_bypass: Option<bool>,
pub cache_hit: Option<bool>,
pub degrade_flags: Option<Vec<String>>,
}
impl LedgerSummaryView {
pub fn from_runtime(runtime: &ServerRuntime) -> Self {
let compression_heuristic = CompressionHeuristicView::from_runtime(runtime);
if let Some(store) = runtime.ledger_store()
&& let Some(summary) = store.summary()
{
let (recent_runs, recent_runs_window) = Self::recent_runs(store);
Self {
available: true,
total_events: Some(summary.total_events),
total_net_vs_manual: Some(summary.total_net_vs_manual),
accepted_count: Some(summary.accepted_count),
session_count: Some(summary.session_count),
compression_heuristic,
recent_runs,
recent_runs_window,
}
} else {
Self {
available: false,
total_events: None,
total_net_vs_manual: None,
accepted_count: None,
session_count: None,
compression_heuristic,
recent_runs: Vec::new(),
recent_runs_window: None,
}
}
}
fn recent_runs(store: &StelLedgerStore) -> (Vec<LedgerRunView>, Option<u64>) {
let mut rows = match store.recent(RECENT_RUNS_WINDOW + 1) {
Ok(rows) => rows,
Err(err) => {
tracing::warn!(
error = %err,
"stel ledger recent rows unreadable; admin recent_runs withheld"
);
return (Vec::new(), None);
}
};
let sentinel = if rows.len() > RECENT_RUNS_WINDOW {
rows.pop()
} else {
None
};
rows.reverse();
let runs = collapse_runs(&rows, stored_record_identity, |row| row.ts_ms)
.iter()
.enumerate()
.map(|(index, run)| {
let window_clipped = index == 0
&& sentinel.as_ref().is_some_and(|sentinel| {
stored_record_identity(sentinel) == stored_record_identity(&run.canonical)
});
LedgerRunView::from_run(run, window_clipped)
})
.collect();
(runs, Some(RECENT_RUNS_WINDOW as u64))
}
}
impl LedgerRunView {
fn from_run(run: &Run<StoredLedgerRecord>, window_clipped: bool) -> Self {
let StoredLedgerRecord {
id: _,
ts_ms: _,
session_id,
plan_id: _,
surface,
intent,
decision,
tools_called_json,
predicted_response_tokens: _,
actual_response_tokens: _,
manual_baseline_tokens: _,
net_vs_manual: _,
route_confidence,
pff_bypass,
cache_hit,
degrade_flags_json,
} = &run.canonical;
Self {
count: run.count,
first_ts_ms: run.first_ts_ms,
last_ts_ms: run.last_ts_ms,
window_clipped,
session_id: session_id.clone(),
surface: surface.clone(),
intent: intent.clone(),
decision: decision.clone(),
tools_called: serde_json::from_str(tools_called_json).ok(),
route_confidence: route_confidence.clone(),
pff_bypass: *pff_bypass,
cache_hit: *cache_hit,
degrade_flags: serde_json::from_str(degrade_flags_json).ok(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SurfaceView {
pub profile: String,
pub tool_count: usize,
pub tools: Vec<String>,
}
impl SurfaceView {
pub fn from_env() -> Self {
let profile = surface_profile_from_env();
let tools: Vec<String> = list_tools_for_profile(profile)
.into_iter()
.map(|t| t.name.to_string())
.collect();
Self {
profile: profile_label(profile).to_string(),
tool_count: tools.len(),
tools,
}
}
}
fn profile_label(profile: SurfaceProfile) -> &'static str {
match profile {
SurfaceProfile::Core => "core",
SurfaceProfile::Full => "full",
SurfaceProfile::Compact => "compact",
SurfaceProfile::Meta => "meta",
}
}
#[derive(Debug, Clone, Serialize)]
pub struct HarnessEntryView {
pub id: String,
pub name: String,
pub config_path: String,
pub state: String,
pub detail: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct HarnessStatusView {
pub available: bool,
pub entries: Vec<HarnessEntryView>,
}
impl HarnessStatusView {
pub fn from_runtime(runtime: &ServerRuntime) -> Self {
let bearer = runtime.auth().api_key.clone();
let desired = AttachEntry::new(crate::server::serve::DEFAULT_LISTEN.to_string(), bearer);
match HarnessRegistry::known() {
Ok(registry) => {
let entries = registry
.scan(&desired)
.into_iter()
.map(entry_view)
.collect();
Self {
available: true,
entries,
}
}
Err(err) => {
tracing::warn!(error = %err, "harness registry unavailable for admin scan");
Self {
available: false,
entries: vec![],
}
}
}
}
}
fn entry_view(status: HarnessStatus) -> HarnessEntryView {
let (state, detail) = match &status.state {
HarnessState::NotInstalled => ("not_installed".to_string(), None),
HarnessState::Absent => ("absent".to_string(), None),
HarnessState::PresentCurrent => ("present_current".to_string(), None),
HarnessState::PresentStale(fields) => (
"present_stale".to_string(),
Some(fields.description().to_string()),
),
HarnessState::Malformed(msg) => ("malformed".to_string(), Some(msg.clone())),
};
HarnessEntryView {
id: status.id.slug().to_string(),
name: status.id.display_name().to_string(),
config_path: status.config_path.display().to_string(),
state,
detail,
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SystemSnapshot {
pub pid: u32,
pub uptime_secs: u64,
pub active_sessions: u64,
pub indexed_projects: Vec<String>,
pub indexed_file_count: usize,
pub indexed_symbol_count: usize,
pub index_generation: u64,
}
impl SystemSnapshot {
pub fn from_runtime(runtime: &ServerRuntime) -> Self {
let published = runtime.index().data_plane().published_state();
let project = runtime.project_name().to_string();
let indexed_projects = if published.file_count > 0 || project != "project" {
vec![project]
} else {
vec![]
};
Self {
pid: std::process::id(),
uptime_secs: runtime.uptime().as_secs(),
active_sessions: 1,
indexed_projects,
indexed_file_count: published.file_count,
indexed_symbol_count: published.symbol_count,
index_generation: published.generation,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AapPresetsView {
pub embed_snippet: String,
pub serve_url_snippet: Option<String>,
}
impl From<AapPresets> for AapPresetsView {
fn from(p: AapPresets) -> Self {
Self {
embed_snippet: p.embed_snippet,
serve_url_snippet: p.serve_url_snippet,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AapView {
pub detected: bool,
pub root: Option<String>,
pub source: Option<String>,
pub mode: String,
pub pinned_version: Option<String>,
pub running_version: String,
pub drift: String,
pub drifted: bool,
pub indexed_roots: Vec<String>,
pub presets: AapPresetsView,
}
impl AapView {
pub fn from_runtime(runtime: &ServerRuntime) -> Self {
let detection = AapDetection::resolve();
let bearer = runtime.auth().api_key.clone();
Self::from_parts(&detection, true, bearer.as_deref())
}
pub fn from_parts(detection: &AapDetection, serve_active: bool, bearer: Option<&str>) -> Self {
let comparison = match detection.root.as_deref() {
Some(root) => EmbedPinComparison::for_root(root),
None => EmbedPinComparison::evaluate(None, crate::server::aap::running_version()),
};
let attach_url = format!(
"http://{}{}",
crate::server::serve::DEFAULT_LISTEN,
crate::server::mcp_http::MCP_PATH
);
let offer_serve = detection.detected && serve_active;
let presets = AapPresets::build_for_admin_panel(offer_serve, &attach_url, bearer.is_some());
let mode = IntegrationMode::classify(detection.detected, serve_active);
Self {
detected: detection.detected,
root: detection.root.as_ref().map(|p| p.display().to_string()),
source: detection.source.map(|s| s.label().to_string()),
mode: mode.label().to_string(),
pinned_version: comparison.pinned_version().map(str::to_string),
running_version: comparison.running_version().to_string(),
drift: comparison.label().to_string(),
drifted: comparison.is_drift(),
indexed_roots: detection
.root
.as_ref()
.map(|p| vec![p.display().to_string()])
.unwrap_or_default(),
presets: presets.into(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct KeyRecordView {
pub id: i64,
pub label: String,
pub fingerprint: String,
pub created_ms: u64,
pub rotated_ms: Option<u64>,
pub revoked_ms: Option<u64>,
pub active: bool,
}
impl From<crate::server::ApiKeyRecord> for KeyRecordView {
fn from(r: crate::server::ApiKeyRecord) -> Self {
let active = r.is_active();
Self {
id: r.id,
label: r.label,
fingerprint: r.fingerprint,
created_ms: r.created_ms,
rotated_ms: r.rotated_ms,
revoked_ms: r.revoked_ms,
active,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct KeyListView {
pub available: bool,
pub keys: Vec<KeyRecordView>,
}
#[derive(Debug, Clone, Serialize)]
pub struct MintedKeyView {
pub key: KeyRecordView,
pub raw_secret: String,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct MintRequest {
#[serde(default)]
pub label: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ApiError {
pub error: String,
}
fn api_error(status: StatusCode, message: impl Into<String>) -> axum::response::Response {
(
status,
Json(ApiError {
error: message.into(),
}),
)
.into_response()
}
pub async fn get_summary(State(runtime): State<ServerRuntime>) -> Json<LedgerSummaryView> {
Json(LedgerSummaryView::from_runtime(&runtime))
}
pub async fn get_surface(State(_runtime): State<ServerRuntime>) -> Json<SurfaceView> {
Json(SurfaceView::from_env())
}
pub async fn get_harness(State(runtime): State<ServerRuntime>) -> Json<HarnessStatusView> {
Json(HarnessStatusView::from_runtime(&runtime))
}
pub async fn get_system(State(runtime): State<ServerRuntime>) -> Json<SystemSnapshot> {
Json(SystemSnapshot::from_runtime(&runtime))
}
pub async fn get_aap(State(runtime): State<ServerRuntime>) -> Json<AapView> {
Json(AapView::from_runtime(&runtime))
}
pub async fn list_keys(State(runtime): State<ServerRuntime>) -> Json<KeyListView> {
match runtime.key_store() {
Some(store) => {
let keys = store
.list()
.unwrap_or_default()
.into_iter()
.map(KeyRecordView::from)
.collect();
Json(KeyListView {
available: store.is_enabled(),
keys,
})
}
None => Json(KeyListView {
available: false,
keys: vec![],
}),
}
}
pub async fn mint_key(
State(runtime): State<ServerRuntime>,
body: Option<Json<MintRequest>>,
) -> axum::response::Response {
let label = body
.and_then(|Json(req)| req.label)
.unwrap_or_else(|| "api key".to_string());
let Some(store) = runtime.key_store() else {
return api_error(StatusCode::SERVICE_UNAVAILABLE, "api-key store unavailable");
};
match store.mint(&label) {
Ok(minted) => (
StatusCode::CREATED,
Json(MintedKeyView {
key: KeyRecordView::from(minted.record),
raw_secret: minted.raw_secret,
}),
)
.into_response(),
Err(err) => api_error(StatusCode::SERVICE_UNAVAILABLE, err.to_string()),
}
}
pub async fn rotate_key(
State(runtime): State<ServerRuntime>,
Path(id): Path<i64>,
) -> axum::response::Response {
let Some(store) = runtime.key_store() else {
return api_error(StatusCode::SERVICE_UNAVAILABLE, "api-key store unavailable");
};
match store.rotate(id) {
Ok(minted) => Json(MintedKeyView {
key: KeyRecordView::from(minted.record),
raw_secret: minted.raw_secret,
})
.into_response(),
Err(err) => api_error(StatusCode::NOT_FOUND, err.to_string()),
}
}
pub async fn revoke_key(
State(runtime): State<ServerRuntime>,
Path(id): Path<i64>,
) -> axum::response::Response {
let Some(store) = runtime.key_store() else {
return api_error(StatusCode::SERVICE_UNAVAILABLE, "api-key store unavailable");
};
match store.revoke(id) {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(err) => api_error(StatusCode::NOT_FOUND, err.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::live_index::LiveIndex;
use crate::protocol::SymForgeServer;
use crate::sidecar::governor::RequestGovernor;
use crate::stel::ledger_store::StelLedgerStore;
use crate::watcher::WatcherInfo;
use parking_lot::Mutex;
use std::sync::Arc;
fn runtime_with_ledger(ledger: Option<StelLedgerStore>) -> ServerRuntime {
let index = LiveIndex::empty();
let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
let protocol = Arc::new(SymForgeServer::new(
Arc::clone(&index),
"admin-view-test".to_string(),
watcher_info,
None,
None,
));
let governor = Arc::new(RequestGovernor::new());
ServerRuntime::build_runtime(
index,
protocol,
governor,
crate::server::AuthConfig::new(None),
ledger,
)
}
#[test]
fn ledger_view_unavailable_when_no_store() {
let view = LedgerSummaryView::from_runtime(&runtime_with_ledger(None));
assert!(!view.available);
assert!(view.total_events.is_none());
assert!(view.total_net_vs_manual.is_none());
}
#[test]
fn ledger_view_unavailable_when_disabled() {
let view =
LedgerSummaryView::from_runtime(&runtime_with_ledger(Some(StelLedgerStore::Disabled)));
assert!(!view.available, "Disabled store renders unavailable");
assert!(view.total_events.is_none());
}
#[test]
fn ledger_view_reports_real_values_when_seeded() {
let store = StelLedgerStore::open_in_memory("admin-seed").expect("store");
store.record(&crate::stel::types::StelLedgerEvent {
ts_ms: 1,
plan_id: "p".into(),
surface: "symforge".into(),
intent: crate::stel::types::IntentBucket::Trace,
decision: crate::stel::types::AdmissionDecision::Serve,
tools_called: vec!["find_references".into()],
predicted_response_tokens: 100,
actual_response_tokens: 90,
manual_baseline_tokens: 300,
net_vs_manual: 210,
equivalence: None,
route_confidence: crate::stel::types::RouteConfidence::Exact,
pff_bypass: None,
cache_hit: None,
degrade_flags: vec![],
});
let view = LedgerSummaryView::from_runtime(&runtime_with_ledger(Some(store)));
assert!(view.available);
assert_eq!(view.total_events, Some(1));
assert_eq!(view.total_net_vs_manual, Some(210));
assert_eq!(view.compression_heuristic.cache_hits, 0);
}
#[test]
fn ledger_run_view_withholds_unparseable_stored_arrays() {
let row = |tools_called_json: &str, degrade_flags_json: &str| StoredLedgerRecord {
id: 1,
ts_ms: 1,
session_id: "s".into(),
plan_id: "p".into(),
surface: "symforge".into(),
intent: "trace".into(),
decision: "serve".into(),
tools_called_json: tools_called_json.into(),
predicted_response_tokens: 1,
actual_response_tokens: 1,
manual_baseline_tokens: 1,
net_vs_manual: 0,
route_confidence: "exact".into(),
pff_bypass: None,
cache_hit: None,
degrade_flags_json: degrade_flags_json.into(),
};
let run = |canonical: StoredLedgerRecord| Run {
canonical,
count: 2,
first_ts_ms: 1,
last_ts_ms: 2,
};
let parsed = LedgerRunView::from_run(&run(row(r#"["find_references"]"#, "[]")), false);
assert_eq!(
parsed.tools_called,
Some(vec!["find_references".to_string()])
);
assert_eq!(parsed.degrade_flags, Some(vec![]));
assert!(!parsed.window_clipped);
let truncated = LedgerRunView::from_run(&run(row(r#"["find_refer"#, r#"["outl"#)), true);
assert_eq!(truncated.tools_called, None, "unparseable → withheld");
assert_eq!(truncated.degrade_flags, None, "unparseable → withheld");
assert!(truncated.window_clipped);
assert_eq!(truncated.count, 2);
}
#[test]
fn ledger_view_includes_compression_heuristic_from_protocol() {
let runtime = runtime_with_ledger(None);
let view = LedgerSummaryView::from_runtime(&runtime);
assert_eq!(view.compression_heuristic.cache_hits, 0);
assert_eq!(view.compression_heuristic.ccr_offloads, 0);
}
#[test]
fn surface_view_lists_active_surface() {
let view = SurfaceView::from_env();
assert!(!view.tools.is_empty());
assert_eq!(view.tool_count, view.tools.len());
assert!(["core", "full", "compact", "meta"].contains(&view.profile.as_str()));
}
#[test]
fn system_snapshot_reports_real_pid() {
let runtime = runtime_with_ledger(None);
let snap = SystemSnapshot::from_runtime(&runtime);
assert_eq!(snap.pid, std::process::id());
assert_eq!(snap.active_sessions, 1);
}
#[test]
fn key_record_view_omits_raw_secret() {
let store = crate::server::ApiKeyStore::open_in_memory().expect("store");
let minted = store.mint("k").expect("mint");
let view = KeyRecordView::from(minted.record);
let json = serde_json::to_string(&view).expect("serialize");
assert!(
!json.contains(&minted.raw_secret),
"raw secret must not leak"
);
assert!(json.contains("fingerprint"));
}
#[test]
fn aap_view_serve_preset_redacts_bootstrap_key() {
use crate::server::aap::{ADMIN_SERVE_KEY_PLACEHOLDER, AapDetection, DetectionSource};
let detection = AapDetection {
detected: true,
root: Some(std::path::PathBuf::from("/tmp/aap")),
source: Some(DetectionSource::EnvVar),
};
let view = AapView::from_parts(&detection, true, Some("bootstrap-secret-never-echo"));
let serve = view
.presets
.serve_url_snippet
.expect("serve preset when detected + serve active");
assert!(
serve.contains(ADMIN_SERVE_KEY_PLACEHOLDER),
"preset must use placeholder: {serve}"
);
assert!(
!serve.contains("bootstrap-secret-never-echo"),
"bootstrap secret must not appear in JSON: {serve}"
);
}
}