use std::path::{Path, PathBuf};
use crate::index_lifecycle::guidance::reference_read::symbol_candidate_paths;
use crate::live_index::{SearchFilesTier, SearchFilesView};
use super::calibration::CalibrationVerdict;
use super::ledger::SessionLedger;
use super::ledger_store::{StelLedgerStore, TunedEstimateConstants};
use super::status::{DurableLedgerState, StelStatusContext, format_stel_status};
use super::types::{StelDecision, StelLedgerEvent, StelPlan, StelStatusRequest};
pub fn active_tuning_for_economics(
store: Option<&StelLedgerStore>,
) -> Option<TunedEstimateConstants> {
use super::controller::active_tuning_in_force;
use super::ledger_store::CURRENT_ESTIMATOR_VERSION;
let store = store?;
let loaded = store.load_active_tuning(CURRENT_ESTIMATOR_VERSION).ok()?;
active_tuning_in_force(loaded, CURRENT_ESTIMATOR_VERSION)
}
pub fn durable_calibration_verdict(store: Option<&StelLedgerStore>) -> Option<CalibrationVerdict> {
use super::calibration::TUNING_MIN_CORPUS;
use super::ledger_store::{CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX};
let store = store?;
let records = match store.samples_for_estimator(CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX)
{
Ok(records) => records,
Err(_) => return Some(CalibrationVerdict::Deferred),
};
let n = records.len();
if let Some(active) = active_tuning_for_economics(Some(store))
&& active.error_before > active.error_after
{
return Some(CalibrationVerdict::Tuned {
sample_size: active.sample_size as usize,
error_before: active.error_before,
error_after: active.error_after,
});
}
if n == 0 {
Some(CalibrationVerdict::Deferred)
} else {
Some(CalibrationVerdict::Accumulating {
n,
min: TUNING_MIN_CORPUS,
})
}
}
pub fn reset_calibration(store: Option<&StelLedgerStore>) -> Option<usize> {
use super::ledger_store::CURRENT_ESTIMATOR_VERSION;
store?
.clear_calibration_for_estimator(CURRENT_ESTIMATOR_VERSION)
.ok()
}
pub fn calibration_reset_note(cleared: Option<usize>) -> String {
match cleared {
Some(cleared) => format!(
"calibration_reset: cleared {cleared} sample(s) + active tuning (state -> deferred)"
),
None => "calibration_reset: no durable store; in-memory calibration is already deferred"
.to_string(),
}
}
pub fn durable_ledger_state(store: Option<&StelLedgerStore>) -> DurableLedgerState {
use super::ledger_store::LedgerSubsystemState;
use super::status::DurableLedgerSummary;
let Some(store) = store else {
return DurableLedgerState::Unavailable;
};
match store.subsystem_state() {
LedgerSubsystemState::Durable { summary } => {
DurableLedgerState::Durable(DurableLedgerSummary {
total_events: summary.total_events,
total_net_vs_manual: summary.total_net_vs_manual,
session_count: summary.session_count,
})
}
LedgerSubsystemState::Disabled { reason } => DurableLedgerState::Disabled { reason },
}
}
pub fn maybe_persist_tuning(store: &StelLedgerStore) {
use super::calibration::{NO_CORRECTION_FACTOR, PredictionSample, compute_calibration_verdict};
use super::controller::active_tuning_in_force;
use super::ledger_store::{CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX};
let Ok(records) = store.samples_for_estimator(CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX)
else {
return;
};
let samples: Vec<PredictionSample> = records.iter().map(PredictionSample::from).collect();
let active = store
.load_active_tuning(CURRENT_ESTIMATOR_VERSION)
.ok()
.flatten();
let in_force = active_tuning_in_force(active.clone(), CURRENT_ESTIMATOR_VERSION);
let in_force_factor = in_force
.as_ref()
.map_or(NO_CORRECTION_FACTOR, |c| c.response_correction_factor);
let (verdict, candidate) = compute_calibration_verdict(&samples, in_force_factor);
if !matches!(verdict, CalibrationVerdict::Tuned { .. }) {
return;
}
let Some(mut candidate) = candidate else {
return;
};
if let Some(existing) = active.as_ref()
&& existing.response_correction_factor == candidate.response_correction_factor
{
return;
}
candidate.tuned_at_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
if let Err(error) = store.store_active_tuning(&candidate) {
tracing::warn!(error = %error, "stel tuning persist failed; keeping prior constants");
} else {
tracing::info!(
response_correction_factor = candidate.response_correction_factor,
sample_size = candidate.sample_size,
error_before = candidate.error_before,
error_after = candidate.error_after,
"stel auto-tune accepted: persisted calibrated correction (013 US2)"
);
}
}
pub fn record_durably_inline(store: &StelLedgerStore, event: &StelLedgerEvent) {
store.record(event);
maybe_persist_tuning(store);
}
pub struct StatusObservation<'a> {
pub surface: &'static str,
pub daemon_env_surface: Option<&'static str>,
pub orphaned_daemon_pid: Option<u32>,
pub project_name: &'a str,
pub project_root: Option<String>,
pub index_ready: bool,
pub index_files: usize,
pub index_symbols: usize,
pub ledger: &'a SessionLedger,
pub session_tokens: u64,
pub store: Option<&'a StelLedgerStore>,
pub trailing_lines: Vec<String>,
}
pub fn render_status_body(request: &StelStatusRequest, observed: StatusObservation<'_>) -> String {
let reset_note = (request.reset_calibration == Some(true))
.then(|| calibration_reset_note(reset_calibration(observed.store)));
let mut ctx = StelStatusContext::from_server(
observed.surface,
observed.project_name,
observed.project_root,
observed.index_ready,
observed.index_files,
observed.index_symbols,
observed.ledger,
observed.session_tokens,
)
.with_durable_ledger(durable_ledger_state(observed.store));
if let Some(verdict) = durable_calibration_verdict(observed.store) {
ctx = ctx.with_calibration_verdict(verdict);
}
ctx.daemon_env_surface = observed.daemon_env_surface;
ctx.orphaned_daemon_pid = observed.orphaned_daemon_pid;
let mut body = format_stel_status(request, &ctx);
for line in observed.trailing_lines {
body.push('\n');
body.push_str(&line);
}
match reset_note {
Some(note) => format!("{body}\n{note}"),
None => body,
}
}
pub struct FacadeLedgerInput<'a> {
pub surface: &'static str,
pub plan: &'a StelPlan,
pub decision: &'a StelDecision,
pub plan_summary: String,
pub session_tokens_served: i64,
pub body: &'a str,
pub legacy_executed: bool,
pub selected_tool: &'a str,
pub tools_called: Option<Vec<String>>,
pub tuned: Option<&'a TunedEstimateConstants>,
}
pub fn finalize_with_ledger(
ledger: &SessionLedger,
input: FacadeLedgerInput<'_>,
persist: impl FnOnce(&StelLedgerEvent),
) -> String {
let (output, event) = render_facade_answer(input);
ledger.push(event.clone());
persist(&event);
output
}
pub fn render_facade_answer(input: FacadeLedgerInput<'_>) -> (String, StelLedgerEvent) {
use super::handler::{self, finalize_symforge_output, metrics_for_decision_tuned};
use super::ledger::{LedgerCaptureInput, capture_ledger, format_ledger_envelope_line};
let response_tokens = handler::estimate_tokens(input.body);
let metrics = metrics_for_decision_tuned(
input.plan_summary,
input.decision,
input.plan,
response_tokens,
input.session_tokens_served,
input.tuned,
);
let (event, meta) = capture_ledger(&LedgerCaptureInput {
plan: input.plan,
decision: input.decision,
economics: &metrics.economics,
selected_tool: input.selected_tool,
tools_called: input.tools_called.as_deref(),
legacy_executed: input.legacy_executed,
output_body: input.body,
surface: input.surface,
});
let ledger_line = format_ledger_envelope_line(&event, &meta);
(
finalize_symforge_output(metrics, ledger_line, input.body),
event,
)
}
pub(crate) fn canonicalize_with_missing_tail(path: &Path) -> Option<PathBuf> {
let mut ancestor = path.to_path_buf();
let mut missing_tail = Vec::<std::ffi::OsString>::new();
loop {
match ancestor.canonicalize() {
Ok(mut canonical) => {
for component in missing_tail.iter().rev() {
canonical.push(component);
}
return Some(canonical);
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
match std::fs::symlink_metadata(&ancestor) {
Ok(_) => return None,
Err(metadata_error)
if metadata_error.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => return None,
}
missing_tail.push(ancestor.file_name()?.to_os_string());
if !ancestor.pop() {
return None;
}
}
Err(_) => return None,
}
}
}
pub(crate) fn path_is_within_bound_project(path: &str, root: &Path) -> bool {
let Ok(canonical_root) = root.canonicalize() else {
return false;
};
let raw = Path::new(path);
let resolved = if raw.is_absolute() {
raw.to_path_buf()
} else {
canonical_root.join(raw)
};
let Some(resolved) = canonicalize_with_missing_tail(&resolved) else {
return false;
};
let resolved_cmp = strip_verbatim_prefix(&resolved);
let root_cmp = strip_verbatim_prefix(&canonical_root);
resolved_cmp.starts_with(&root_cmp)
}
pub(crate) fn facade_path_is_repo_relative(path: &str) -> bool {
let bytes = path.as_bytes();
if path.starts_with('/')
|| path.starts_with('\\')
|| (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
{
return false;
}
!Path::new(path).components().any(|component| {
matches!(
component,
std::path::Component::Prefix(_) | std::path::Component::RootDir
)
})
}
pub(crate) fn strip_verbatim_prefix(path: &Path) -> PathBuf {
use std::path::{Component, Prefix};
let mut out = PathBuf::new();
let mut rebuilt_prefix_already_rooted = false;
for component in path.components() {
match component {
Component::Prefix(prefix) => match prefix.kind() {
Prefix::VerbatimDisk(disk) => {
out.push(format!("{}:\\", disk as char));
rebuilt_prefix_already_rooted = true;
}
Prefix::VerbatimUNC(server, share) => {
let mut unc = std::ffi::OsString::from(r"\\");
unc.push(server);
unc.push(r"\");
unc.push(share);
out.push(unc);
rebuilt_prefix_already_rooted = true;
}
_ => {
out.push(component.as_os_str());
rebuilt_prefix_already_rooted = false;
}
},
Component::RootDir => {
if !rebuilt_prefix_already_rooted {
out.push(component.as_os_str());
}
}
other => out.push(other.as_os_str()),
}
}
out
}
pub fn ground_plan_economics(guard: &crate::live_index::LiveIndex, plan: &mut StelPlan) {
if !guard.is_ready() {
return;
}
for step in &mut plan.steps {
if !step.index_refs.is_empty() {
continue;
}
let resolve_symbol = step.tool == "get_symbol";
if !matches!(
step.tool.as_str(),
"get_file_context" | "get_file_content" | "get_symbol"
) {
continue;
}
let resolved_path = step
.args
.get("path")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|path| !path.is_empty())
.map(str::to_string)
.or_else(|| {
if !resolve_symbol {
return None;
}
let name = step
.args
.get("name")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|name| !name.is_empty())?;
let candidates = symbol_candidate_paths(guard, name);
if candidates.len() == 1 {
candidates.into_iter().next()
} else {
None
}
});
let Some(path) = resolved_path else {
continue;
};
if let Some(file) = guard.capture_shared_file(&path) {
step.index_refs
.push(super::controller::index_ref_for_target(
path,
file.content.len() as u64,
));
}
}
}
pub fn resolve_find_fusion_cochange_anchor(
guard: &crate::live_index::LiveIndex,
query: &str,
) -> Option<String> {
let top_hit = |q: &str| -> Option<String> {
match guard.capture_search_files_view(q, 5, None, None) {
SearchFilesView::Found { hits, .. } => hits
.into_iter()
.find(|hit| hit.tier != SearchFilesTier::MetadataOnly)
.map(|hit| hit.path),
_ => None,
}
};
if let Some(hit) = top_hit(query) {
return Some(hit);
}
query
.split_whitespace()
.filter(|tok| tok.chars().any(char::is_alphanumeric))
.find_map(top_hit)
}
pub fn inject_find_fusion_cochange_anchor(
live: &crate::live_index::LiveIndex,
tool: &str,
args: &serde_json::Value,
may_use_local_project_state: bool,
) -> serde_json::Value {
let is_fusion_path_step = tool == "search_files"
&& args.get("rank_by").and_then(serde_json::Value::as_str) == Some("path+cochange")
&& args.get("anchor_path").is_none();
if !is_fusion_path_step {
return args.clone();
}
let query = args
.get("query")
.and_then(serde_json::Value::as_str)
.unwrap_or_default();
let mut args = args.clone();
let Some(map) = args.as_object_mut() else {
return args;
};
if !may_use_local_project_state {
map.remove("rank_by");
return args;
}
match resolve_find_fusion_cochange_anchor(live, query) {
Some(anchor) => {
let path_query = std::path::Path::new(&anchor)
.file_stem()
.and_then(|stem| stem.to_str())
.filter(|stem| stem.len() >= 3)
.map(str::to_string)
.unwrap_or_else(|| anchor.clone());
map.insert("query".to_string(), serde_json::Value::String(path_query));
map.insert("anchor_path".to_string(), serde_json::Value::String(anchor));
}
None => {
map.remove("rank_by");
}
}
args
}
pub fn append_impact_intent_cochanges(
temporal: &crate::live_index::git_temporal::GitTemporalIndex,
body: &mut String,
args: &serde_json::Value,
) {
const IMPACT_INTENT_COCHANGE_LIMIT: usize = 5;
let Some(path) = args.get("path").and_then(|p| p.as_str()) else {
return;
};
match temporal.state {
crate::live_index::git_temporal::GitTemporalState::Ready => {
let normalized = path.replace('\\', "/");
match temporal.files.get(&normalized) {
Some(history) => {
body.push_str("\n\n");
body.push_str(
&crate::index_lifecycle::guidance::file_impact::co_changes_result_view(
&normalized,
history,
IMPACT_INTENT_COCHANGE_LIMIT,
),
);
}
None => {
body.push_str("\n\nNo git co-change data found for this file.");
}
}
}
crate::live_index::git_temporal::GitTemporalState::Pending
| crate::live_index::git_temporal::GitTemporalState::Computing => {
body.push_str("\n\nGit temporal data is still loading. Co-changes unavailable.");
}
crate::live_index::git_temporal::GitTemporalState::Unavailable(ref reason) => {
body.push_str(&format!("\n\nGit temporal data unavailable: {reason}"));
}
}
}
pub fn single_project_routed_tool(tool_name: &str) -> bool {
matches!(
tool_name,
"get_symbol"
| "get_symbol_context"
| "get_file_context"
| "get_file_content"
| "get_repo_map"
| "search_files"
| "find_dependents"
| "diff_symbols"
| "what_changed"
| "analyze_file_impact"
| "validate_file_syntax"
| "explore"
| "ask"
| "conventions"
| "edit_plan"
| "investigation_suggest"
| "replace_symbol_body"
| "edit_within_symbol"
| "insert_symbol"
| "delete_symbol"
| "batch_edit"
| "batch_insert"
| "batch_rename"
| "symforge_edit"
| "curate_knowledge"
)
}
pub fn facade_step_accepts_project(tool: &str) -> bool {
single_project_routed_tool(tool)
|| matches!(
tool,
"search_symbols"
| "search_text"
| "search_knowledge"
| "find_references"
| "search_files"
)
}
pub fn mutation_refusal_outcome(
text: &str,
) -> crate::index_lifecycle::guidance::outcome::OutcomeClass {
let lower = text.to_ascii_lowercase();
if lower.contains("symbol not found")
|| lower.contains("file not found")
|| lower.contains("file not indexed:")
|| lower.contains(" not found within symbol ")
{
crate::index_lifecycle::guidance::outcome::OutcomeClass::NotFound
} else if text.contains("Ambiguous:") {
crate::index_lifecycle::guidance::outcome::OutcomeClass::Ambiguous
} else {
crate::index_lifecycle::guidance::outcome::OutcomeClass::InvalidRequest
}
}