use serde_json::{Value, json};
use super::helpers::{DashboardProjectSource, dashboard_project_binding};
pub(super) fn handle(
path: &str,
_query: &str,
method: &str,
_body: &str,
) -> Option<(&'static str, &'static str, String)> {
if path != "/api/scope" {
return None;
}
if !method.eq_ignore_ascii_case("GET") {
return Some((
"405 Method Not Allowed",
"application/json",
r#"{"error":"method not allowed"}"#.to_string(),
));
}
let (root, source) = dashboard_project_binding();
Some((
"200 OK",
"application/json",
scope(root.as_deref(), source).to_string(),
))
}
fn source_code(source: DashboardProjectSource) -> &'static str {
match source {
DashboardProjectSource::ExplicitFlag => "explicit_flag",
DashboardProjectSource::Env => "env",
DashboardProjectSource::Cwd => "cwd",
DashboardProjectSource::Request => "request",
DashboardProjectSource::Unbound => "unbound",
}
}
fn scope(root: Option<&str>, source: DashboardProjectSource) -> Value {
let Some(root) = root.filter(|root| !root.is_empty()) else {
return json!({
"schema_version": 1,
"binding_source": source_code(DashboardProjectSource::Unbound),
"reason_code": "project_unresolved",
"next_step": "bind_project",
});
};
let partition = lean_ctx::core::project_hash::hash_project_root(root);
let label = std::path::Path::new(root).file_name().map_or_else(
|| root.to_string(),
|name| name.to_string_lossy().into_owned(),
);
let git = |args: &[&str]| -> Option<String> {
let out = std::process::Command::new("git")
.args(args)
.current_dir(root)
.stderr(std::process::Stdio::null())
.output()
.ok()?;
let text = String::from_utf8(out.stdout).ok()?.trim().to_string();
(out.status.success() && !text.is_empty()).then_some(text)
};
let mut answer = json!({
"schema_version": 1,
"binding_source": source_code(source),
"partition_id": partition,
"workspace_root": root,
"project": {
"id": partition,
"label": label,
"kind": "local",
"mapping": lean_ctx::core::project_link::mapping_json(root),
},
"branch": git(&["rev-parse", "--abbrev-ref", "HEAD"]),
"revision": git(&["rev-parse", "HEAD"]),
});
if let Some(selection) = lean_ctx::core::root_selection::recorded_for(root) {
answer["selection"] = selection.scope_json();
}
if let Some(snapshot) = lean_ctx::core::workspace_authority::load_current().snapshot() {
answer["workspace"] = snapshot.to_json();
}
answer
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scope_names_the_binding_and_never_a_foreign_project() {
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let unbound = scope(None, DashboardProjectSource::Unbound);
assert_eq!(unbound["reason_code"], "project_unresolved");
assert_eq!(unbound["next_step"], "bind_project");
assert!(unbound.get("workspace_root").is_none());
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_str().unwrap();
let bound = scope(Some(root), DashboardProjectSource::ExplicitFlag);
assert_eq!(bound["binding_source"], "explicit_flag");
assert_eq!(bound["workspace_root"], root);
assert_eq!(
bound["partition_id"],
lean_ctx::core::project_hash::hash_project_root(root)
);
assert_eq!(bound["project"]["mapping"], "unmapped");
assert!(bound.get("selection").is_none());
}
#[test]
fn scope_reports_link_and_multi_root_selection() {
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let workspace = tempfile::tempdir().unwrap();
let canonical = |name: &str| {
let dir = workspace.path().join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::canonicalize(dir)
.unwrap()
.to_string_lossy()
.into_owned()
};
let (first, second) = (canonical("first"), canonical("second"));
lean_ctx::core::project_link::link(lean_ctx::core::project_link::ProjectLink {
workspace_root: first.clone(),
team_project_id: "gateway".to_owned(),
organization_id: None,
label: None,
linked_at: "2026-10-19T10:00:00Z".to_owned(),
})
.unwrap();
let alone = lean_ctx::core::root_selection::select(vec![first.clone()], &[]).unwrap();
lean_ctx::core::root_selection::record(&alone);
let linked = scope(Some(&first), DashboardProjectSource::ExplicitFlag);
assert_eq!(
linked["project"]["mapping"],
json!({
"state": "linked",
"team_project_id": "gateway",
"linked_at": "2026-10-19T10:00:00Z",
"change_with": "lean-ctx project link --project <id>",
"remove_with": "lean-ctx project unlink",
})
);
assert!(linked.get("selection").is_none());
let several =
lean_ctx::core::root_selection::select(vec![first.clone(), second.clone()], &[])
.unwrap();
lean_ctx::core::root_selection::record(&several);
let chosen = scope(Some(&first), DashboardProjectSource::ExplicitFlag);
assert_eq!(
chosen["selection"],
json!({
"rule": "first_root",
"chosen_root": first,
"candidates": [first, second],
"change_with": "lean-ctx project use <path>",
})
);
assert_eq!(
chosen.to_string(),
scope(Some(&first), DashboardProjectSource::ExplicitFlag).to_string()
);
assert!(
scope(Some(&second), DashboardProjectSource::ExplicitFlag)
.get("selection")
.is_none()
);
}
}