use super::calibration::{
StelCalibrationSummary, format_calibration_section, summarize_calibration,
};
use super::ledger::{SessionLedger, collapse_runs, ledger_event_identity};
use super::types::{StelStatusDetail, StelStatusRequest};
pub const PHASE0_GO_COMMIT: &str = "07b42a8";
pub const PHASE0_EVIDENCE_COMMIT: &str = "08f7d14";
pub const DEFERRED_ITEMS: &str = "b_results";
pub const SUPERSEDED_ITEMS: &str = "multi_step_planner";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DurableLedgerSummary {
pub total_events: u64,
pub total_net_vs_manual: i64,
pub session_count: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DurableLedgerState {
Durable(DurableLedgerSummary),
Disabled { reason: String },
Unavailable,
}
#[derive(Clone, Debug, PartialEq)]
pub struct StelStatusContext<'a> {
pub surface: &'static str,
pub version: &'static str,
pub project_name: &'a str,
pub project_root: Option<String>,
pub index_ready: bool,
pub index_files: usize,
pub index_symbols: usize,
pub ledger_events: usize,
pub session_tokens: u64,
pub last_ledger_decision: Option<String>,
pub last_ledger_route: Option<String>,
pub trailing_run: Option<(u64, u64, u64)>,
pub calibration: StelCalibrationSummary,
pub durable_ledger: DurableLedgerState,
pub daemon_env_surface: Option<&'static str>,
pub orphaned_daemon_pid: Option<u32>,
}
impl<'a> StelStatusContext<'a> {
#[allow(clippy::too_many_arguments)]
pub fn from_server(
surface: &'static str,
project_name: &'a str,
project_root: Option<String>,
index_ready: bool,
index_files: usize,
index_symbols: usize,
ledger: &SessionLedger,
session_tokens: u64,
) -> Self {
let events = ledger.events();
let calibration = summarize_calibration(&events);
let last = events.last();
let last_ledger_decision = last
.as_ref()
.map(|event| event.decision.as_str().to_string());
let last_ledger_route = last.and_then(|event| event.tools_called.first().cloned());
let trailing_run = collapse_runs(&events, ledger_event_identity, |event| event.ts_ms)
.last()
.filter(|run| run.count >= 2)
.map(|run| (run.count, run.first_ts_ms, run.last_ts_ms));
Self {
surface,
version: env!("CARGO_PKG_VERSION"),
project_name,
project_root,
index_ready,
index_files,
index_symbols,
ledger_events: ledger.len(),
session_tokens,
last_ledger_decision,
last_ledger_route,
trailing_run,
calibration,
durable_ledger: DurableLedgerState::Unavailable,
daemon_env_surface: None,
orphaned_daemon_pid: None,
}
}
pub fn with_durable_ledger(mut self, state: DurableLedgerState) -> Self {
let readable = matches!(state, DurableLedgerState::Durable(_));
self.durable_ledger = state;
if !readable {
self = self
.with_calibration_verdict(crate::stel::calibration::CalibrationVerdict::Deferred);
}
self
}
pub fn with_calibration_verdict(
mut self,
verdict: crate::stel::calibration::CalibrationVerdict,
) -> Self {
self.calibration.tuning_note =
crate::stel::calibration::render_calibration_verdict(&verdict);
self.calibration.verdict = verdict;
self
}
}
pub fn format_durable_ledger_line(state: &DurableLedgerState) -> String {
match state {
DurableLedgerState::Durable(summary) => format!(
"durable_ledger: events={} net_vs_manual={} sessions={}",
summary.total_events, summary.total_net_vs_manual, summary.session_count
),
DurableLedgerState::Disabled { reason } => {
format!("durable_ledger: disabled ({reason})")
}
DurableLedgerState::Unavailable => "durable_ledger: unavailable".to_string(),
}
}
pub fn format_last_ledger_lines(ctx: &StelStatusContext<'_>) -> [String; 2] {
match (&ctx.last_ledger_decision, &ctx.last_ledger_route) {
(Some(decision), route) => {
let route = route.as_deref().unwrap_or("none");
let run_suffix = match ctx.trailing_run {
Some((count, first_ts_ms, last_ts_ms)) => {
format!(" ×{count} (first={first_ts_ms}, last={last_ts_ms})")
}
None => String::new(),
};
[
format!("last_ledger_decision: {decision}{run_suffix}"),
format!("last_ledger_route: {route}"),
]
}
(None, _) => [
"last_ledger_decision: none".to_string(),
"last_ledger_route: none".to_string(),
],
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProxyOwnedStatusLines {
pub ledger_events: String,
pub last_ledger_decision: String,
pub last_ledger_route: String,
pub durable_ledger: String,
pub calibration_section: String,
}
pub fn render_proxy_owned_lines(ctx: &StelStatusContext<'_>) -> ProxyOwnedStatusLines {
let [last_ledger_decision, last_ledger_route] = format_last_ledger_lines(ctx);
ProxyOwnedStatusLines {
ledger_events: format!("ledger_events: {}", ctx.ledger_events),
last_ledger_decision,
last_ledger_route,
durable_ledger: format_durable_ledger_line(&ctx.durable_ledger),
calibration_section: format_calibration_section(&ctx.calibration),
}
}
pub fn format_stel_status(request: &StelStatusRequest, ctx: &StelStatusContext<'_>) -> String {
let detail = request.detail.unwrap_or(StelStatusDetail::Compact);
match detail {
StelStatusDetail::Compact => format_compact_status(ctx),
StelStatusDetail::Full => format_full_status(ctx),
StelStatusDetail::Projects => format_projects_status(ctx),
}
}
fn format_projects_status(ctx: &StelStatusContext<'_>) -> String {
let mut lines = vec!["── projects ──".to_string()];
lines.push(format!(
"name={} root={} home=yes files={} symbols={} index_ready={}",
ctx.project_name,
ctx.project_root.as_deref().unwrap_or("(unbound)"),
ctx.index_files,
ctx.index_symbols,
ctx.index_ready,
));
lines.join(
"
",
)
}
fn format_compact_status(ctx: &StelStatusContext<'_>) -> String {
let mut lines = vec![
"── stel status ──".to_string(),
format!("surface: {}", ctx.surface),
format!("symforge_version: {}", ctx.version),
format!("phase0_go: {PHASE0_GO_COMMIT}"),
format!("phase0_evidence: {PHASE0_EVIDENCE_COMMIT}"),
"l1_planner: wired".to_string(),
"l2_economics: wired".to_string(),
"l3_bypass: wired".to_string(),
"l4_ledger: in_memory".to_string(),
"handler_symforge: wired".to_string(),
"handler_status: wired".to_string(),
"handler_symforge_edit: preview-and-apply".to_string(),
format!("ledger_events: {}", ctx.ledger_events),
format!(
"project_root: {}",
ctx.project_root.as_deref().unwrap_or("(unbound)")
),
format!("index_ready: {}", ctx.index_ready),
format!("index_files: {}", ctx.index_files),
format!("deferred: {DEFERRED_ITEMS}"),
format!("superseded: {SUPERSEDED_ITEMS} (client agentic loop + find-fusion)"),
"──".to_string(),
];
if let Some(env_label) = ctx.daemon_env_surface {
lines.insert(
2,
format!(
"daemon_env_surface: {env_label} (serving connection: {})",
ctx.surface
),
);
}
if let Some(pid) = ctx.orphaned_daemon_pid {
lines.insert(
2,
format!(
"daemon_instance: ORPHANED pid={pid} — this daemon is no longer the recorded one; \
new clients reach a different daemon whose index may differ. Every figure below \
describes THIS process only. Restart the client, or stop this pid, before \
trusting anchors from it."
),
);
}
lines.join("\n")
}
fn format_full_status(ctx: &StelStatusContext<'_>) -> String {
let mut body = format_compact_status(ctx);
let mut extra = vec![
format!("project: {}", ctx.project_name),
format!("index_symbols: {}", ctx.index_symbols),
format!("session_tokens: {}", ctx.session_tokens),
];
extra.extend(format_last_ledger_lines(ctx));
extra.push(format_durable_ledger_line(&ctx.durable_ledger));
extra.push(format_calibration_section(&ctx.calibration));
if let Some(pos) = body.rfind("\n──\n") {
let (head, tail) = body.split_at(pos);
body = format!("{head}\n{}\n{tail}", extra.join("\n"));
} else {
body.push('\n');
body.push_str(&extra.join("\n"));
}
body
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_context() -> StelStatusContext<'static> {
StelStatusContext {
surface: "compact",
version: "0.0.0-test",
project_name: "symforge-test",
project_root: Some("E:/project/symforge-test".to_string()),
index_ready: true,
index_files: 12,
index_symbols: 48,
ledger_events: 2,
session_tokens: 128,
last_ledger_decision: Some("serve".to_string()),
last_ledger_route: Some("search_text".to_string()),
trailing_run: None,
calibration: summarize_calibration(&[]),
durable_ledger: DurableLedgerState::Unavailable,
daemon_env_surface: None,
orphaned_daemon_pid: None,
}
}
#[test]
fn orphaned_daemon_is_disclosed_and_silent_otherwise() {
let mut ctx = sample_context();
let healthy = format_stel_status(&StelStatusRequest::default(), &ctx);
assert!(
!healthy.contains("daemon_instance:"),
"the recorded daemon must not carry an orphan disclosure:\n{healthy}"
);
ctx.orphaned_daemon_pid = Some(41228);
let orphaned = format_stel_status(&StelStatusRequest::default(), &ctx);
assert!(
orphaned.contains("daemon_instance: ORPHANED pid=41228"),
"an orphaned daemon must name itself:\n{orphaned}"
);
assert!(
orphaned.contains("THIS process only"),
"the disclosure must invalidate the figures below it, not merely \
note the orphaning:\n{orphaned}"
);
}
#[test]
fn compact_status_reports_required_operational_fields() {
let body = format_stel_status(&StelStatusRequest::default(), &sample_context());
for needle in [
"── stel status ──",
"surface: compact",
"phase0_go: 07b42a8",
"phase0_evidence: 08f7d14",
"l1_planner: wired",
"l2_economics: wired",
"l3_bypass: wired",
"l4_ledger: in_memory",
"handler_symforge: wired",
"handler_status: wired",
"handler_symforge_edit: preview-and-apply",
"ledger_events: 2",
"project_root: E:/project/symforge-test",
"index_ready: true",
"index_files: 12",
"deferred: b_results",
"superseded: multi_step_planner (client agentic loop + find-fusion)",
"──",
] {
assert!(body.contains(needle), "missing `{needle}` in:\n{body}");
}
assert!(
!body.contains(": active"),
"no subsystem may report a blanket `active` in:\n{body}"
);
assert!(
!body.contains("ledger_persistence"),
"ledger_persistence ships in serve mode; not deferred:\n{body}"
);
assert!(
!body.contains("calibration_auto_tune"),
"calibration_auto_tune ships in 013 US2; not deferred:\n{body}"
);
assert!(
!body.contains("── calibration (observational) ──"),
"compact detail must not include calibration section"
);
}
#[test]
fn full_status_adds_session_and_ledger_summary() {
let body = format_stel_status(
&StelStatusRequest {
detail: Some(StelStatusDetail::Full),
reset_calibration: None,
connection_surface: None,
},
&sample_context(),
);
for needle in [
"project: symforge-test",
"index_symbols: 48",
"session_tokens: 128",
"last_ledger_decision: serve",
"last_ledger_route: search_text",
"── calibration (observational) ──",
"tuning:",
] {
assert!(body.contains(needle), "missing `{needle}` in:\n{body}");
}
}
#[test]
fn full_status_renders_durable_ledger_summary_when_present() {
let ctx = sample_context().with_durable_ledger(DurableLedgerState::Durable(
DurableLedgerSummary {
total_events: 7,
total_net_vs_manual: 4200,
session_count: 3,
},
));
let body = format_stel_status(
&StelStatusRequest {
detail: Some(StelStatusDetail::Full),
reset_calibration: None,
connection_surface: None,
},
&ctx,
);
assert!(
body.contains("durable_ledger: events=7 net_vs_manual=4200 sessions=3"),
"durable ledger summary line missing in:\n{body}"
);
}
#[test]
fn full_status_reports_durable_ledger_unavailable_when_absent() {
let body = format_stel_status(
&StelStatusRequest {
detail: Some(StelStatusDetail::Full),
reset_calibration: None,
connection_surface: None,
},
&sample_context(),
);
assert!(
body.contains("durable_ledger: unavailable"),
"expected durable_ledger unavailable line in:\n{body}"
);
}
#[test]
fn full_status_reports_disabled_distinct_from_unavailable() {
let ctx = sample_context().with_durable_ledger(DurableLedgerState::Disabled {
reason: "summary query failed: no such table".to_string(),
});
let body = format_stel_status(
&StelStatusRequest {
detail: Some(StelStatusDetail::Full),
reset_calibration: None,
connection_surface: None,
},
&ctx,
);
assert!(
body.contains("durable_ledger: disabled (summary query failed: no such table)"),
"expected durable_ledger disabled(reason) line in:\n{body}"
);
assert!(
!body.contains("durable_ledger: unavailable"),
"a disabled (broken) store must not read as unavailable (off):\n{body}"
);
}
#[test]
fn from_server_reflects_empty_ledger() {
let ledger = SessionLedger::new();
let ctx = StelStatusContext::from_server("compact", "proj", None, false, 0, 0, &ledger, 0);
assert_eq!(ctx.ledger_events, 0);
assert_eq!(ctx.last_ledger_decision, None);
assert_eq!(ctx.project_root, None);
let body = format_stel_status(&StelStatusRequest::default(), &ctx);
assert!(body.contains("ledger_events: 0"));
assert!(body.contains("index_ready: false"));
}
#[test]
fn unbound_project_root_reads_loudly_not_silently() {
let ledger = SessionLedger::new();
let ctx = StelStatusContext::from_server("compact", "proj", None, false, 0, 0, &ledger, 0);
let body = format_stel_status(&StelStatusRequest::default(), &ctx);
assert!(
body.contains("project_root: (unbound)"),
"an unbound session must surface `project_root: (unbound)`:\n{body}"
);
}
#[test]
fn bound_project_root_is_surfaced() {
let ledger = SessionLedger::new();
let ctx = StelStatusContext::from_server(
"compact",
"proj",
Some("/home/u/repo".to_string()),
true,
10,
40,
&ledger,
0,
);
let body = format_stel_status(&StelStatusRequest::default(), &ctx);
assert!(
body.contains("project_root: /home/u/repo"),
"bound root must be surfaced verbatim:\n{body}"
);
}
}