use serde::Serialize;
use serde_json::{Map, Value};
pub(crate) mod activity;
pub(crate) mod agents;
pub(crate) mod bus;
pub(crate) mod bus_presence;
pub(crate) mod capabilities;
pub(crate) mod context_part;
pub(crate) mod daemon;
pub(crate) mod docs;
pub(crate) mod evidence;
pub(crate) mod kinds;
pub(crate) mod knowledge;
pub(crate) mod knowledge_write;
pub(crate) mod leases;
pub(crate) mod link;
pub(crate) mod policies;
pub(crate) mod presence;
pub(crate) mod providers;
pub(crate) mod queens;
pub(crate) mod routes;
pub(crate) mod session;
pub(crate) mod status;
pub(crate) mod sync;
pub(crate) mod tasks;
pub(crate) mod tasks_part;
pub(crate) mod usage;
pub(crate) mod vaults;
#[cfg(test)]
mod tests;
pub(crate) const CONTRACT: &str = "local-read/1";
pub(crate) struct Part {
pub routes: &'static [routes::Route],
pub kinds: &'static [&'static str],
pub commands: &'static [(&'static str, &'static [&'static str])],
pub answer: fn(&str, &[String], Via) -> Answer,
}
pub(crate) const PARTS: &[Part] = &[
Part {
routes: tasks_part::ROUTES,
kinds: tasks_part::KINDS,
commands: tasks_part::COMMANDS,
answer: tasks_part::answer,
},
Part {
routes: sync::ROUTES,
kinds: sync::KINDS,
commands: sync::COMMANDS,
answer: sync::answer,
},
Part {
routes: context_part::ROUTES,
kinds: context_part::KINDS,
commands: context_part::COMMANDS,
answer: context_part::answer,
},
];
pub(crate) fn part_of(kind: &str) -> Option<&'static Part> {
PARTS.iter().find(|p| p.kinds.contains(&kind))
}
pub(crate) fn wants_json(args: &[String]) -> bool {
args.iter().any(|a| a == "--json")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Code {
InvalidArgument,
NoProject,
NotConnected,
NoVault,
NotFound,
Forbidden,
Withheld,
AnchorGone,
Conflict,
Unavailable,
RateLimited,
Internal,
}
impl Code {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::InvalidArgument => "invalid_argument",
Self::NoProject => "no_project",
Self::NotConnected => "not_connected",
Self::NoVault => "no_vault",
Self::NotFound => "not_found",
Self::Forbidden => "forbidden",
Self::Withheld => "withheld",
Self::AnchorGone => "anchor_gone",
Self::Conflict => "conflict",
Self::Unavailable => "unavailable",
Self::RateLimited => "rate_limited",
Self::Internal => "internal",
}
}
pub(crate) fn exit_status(self) -> i32 {
if self == Self::InvalidArgument { 2 } else { 1 }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Failure {
pub code: Code,
pub message: String,
}
impl Failure {
pub(crate) fn new(code: Code, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
pub(crate) fn invalid(message: impl Into<String>) -> Self {
Self::new(Code::InvalidArgument, message)
}
}
impl From<lean_ctx_hive::HiveError> for Failure {
fn from(error: lean_ctx_hive::HiveError) -> Self {
use lean_ctx_hive::HiveError as E;
let code = match &error {
E::NotConnected | E::LeaseLapsed | E::Revoked(_) | E::Unauthorized => {
Code::NotConnected
}
E::NotFound => Code::NotFound,
E::Forbidden | E::PlanRequired(_) => Code::Forbidden,
E::RateLimited { .. } => Code::RateLimited,
E::Offline(_) => Code::Unavailable,
_ if error.is_transient() => Code::Unavailable,
_ => Code::Internal,
};
Self::new(code, error.to_string())
}
}
pub(crate) fn document(kind: &str, body: &impl Serialize) -> String {
let mut out = Map::new();
out.insert("contract".into(), CONTRACT.into());
out.insert("kind".into(), kind.into());
if let Ok(Value::Object(fields)) = serde_json::to_value(body) {
for (key, value) in fields {
out.entry(key).or_insert(value);
}
}
Value::Object(out).to_string()
}
pub(crate) fn error_document(failure: &Failure) -> String {
document(
"error",
&serde_json::json!({
"error": { "code": failure.code.as_str(), "message": failure.message }
}),
)
}
pub(crate) fn fail(failure: &Failure) -> ! {
println!("{}", error_document(failure));
std::process::exit(failure.code.exit_status());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Via {
Cli,
#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
Socket,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Answer {
pub text: String,
pub failed: Option<Code>,
pub notice: Option<String>,
released: bool,
withheld: bool,
}
impl Answer {
pub(crate) fn failure(failure: &Failure) -> Self {
Self {
text: error_document(failure),
failed: Some(failure.code),
notice: None,
released: false,
withheld: false,
}
}
pub(crate) fn unreceipted() -> Self {
Self {
text: String::new(),
failed: Some(Code::Withheld),
notice: None,
released: true,
withheld: true,
}
}
#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
pub(crate) fn body(&self) -> Option<&str> {
(!self.withheld).then_some(self.text.as_str())
}
}
pub(crate) fn answer<T: Serialize>(
kind: &str,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
match build() {
Ok(body) => Answer {
text: document(kind, &body),
failed: None,
notice: None,
released: false,
withheld: false,
},
Err(failure) => Answer::failure(&failure),
}
}
pub(crate) const MASKED_NOTICE: &str = "[lean-ctx gateway: content redacted]";
const FOLDERLESS_ROOT: &str = std::path::MAIN_SEPARATOR_STR;
fn tool_run<'a>(tool: &'a str, project_root: &'a str, via: Via) -> super::common::CliToolRun<'a> {
let project_root = if project_root.is_empty() {
FOLDERLESS_ROOT
} else {
project_root
};
let run = super::common::CliToolRun::new(tool, project_root, None);
match via {
Via::Cli => run.refuse_with(withheld_document),
Via::Socket => run.to_transport().refuse_with(withheld_document),
}
}
fn withheld_document(reason: &str) -> String {
error_document(&Failure::new(Code::Withheld, reason))
}
pub(crate) fn answer_released<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
via: Via,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
answer_released_run(&tool_run(tool, project_root, via), kind, via, build)
}
pub(crate) fn answer_released_records<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
via: Via,
records: super::common::Records,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
let run = tool_run(tool, project_root, via).per_record(records);
answer_released_run(&run, kind, via, build)
}
fn answer_released_run<T: Serialize>(
run: &super::common::CliToolRun<'_>,
kind: &str,
via: Via,
build: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
let mut failed: Option<Code> = None;
let mut built: Option<String> = None;
let released = run.deliver_json(|| {
let text = match build() {
Ok(body) => document(kind, &body),
Err(failure) => {
failed = Some(failure.code);
error_document(&failure)
}
};
built = Some(text.clone());
text
});
released_answer(released, built.as_deref(), failed, via)
}
fn released_answer(
released: Result<String, String>,
built: Option<&str>,
failed: Option<Code>,
via: Via,
) -> Answer {
match released {
Ok(text) => Answer {
notice: (built != Some(text.as_str())).then(|| MASKED_NOTICE.to_owned()),
text,
failed,
released: true,
withheld: false,
},
Err(reason) => {
let unreceipted =
reason == lean_ctx::core::context_admission::receipt_store::not_persisted_notice();
if unreceipted {
return match via {
Via::Cli => Answer {
text: reason,
..Answer::unreceipted()
},
Via::Socket => Answer::unreceipted(),
};
}
Answer {
text: withheld_document(&reason),
failed: Some(Code::Withheld),
notice: None,
released: true,
withheld: false,
}
}
}
}
pub(crate) fn answer_released_write<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
via: Via,
preview: &Value,
write: impl FnOnce() -> Result<T, Failure>,
) -> Answer {
let run = tool_run(tool, project_root, via);
let mut failed: Option<Code> = None;
let mut built: Option<String> = None;
let released = run.deliver_json(|| {
let outcome = match run.would_release(document(kind, preview)) {
Err(reason) => Err(Failure::new(Code::Withheld, reason)),
Ok(()) => write(),
};
let text = match outcome {
Ok(body) => document(kind, &body),
Err(failure) => {
failed = Some(failure.code);
error_document(&failure)
}
};
built = Some(text.clone());
text
});
released_answer(released, built.as_deref(), failed, via)
}
pub(crate) fn release_text_write(
tool: &str,
project_root: &str,
kind: &str,
preview: &Value,
) -> Result<(), Failure> {
let run = tool_run(tool, project_root, Via::Cli);
let (released, _capture) = run.acquire(|| run.would_release(document(kind, preview)));
released.map_err(|reason| {
Failure::new(
Code::Withheld,
format!("withheld by the release check, nothing was written: {reason}"),
)
})
}
pub(crate) fn request_preview(args: &[String], names: &[&str]) -> Value {
let mut out = Map::new();
for name in names {
let values = flags(args, name).unwrap_or_default();
let key = name.trim_start_matches('-').replace('-', "_");
match values.as_slice() {
[] => {}
[one] => {
out.insert(key, Value::String((*one).to_owned()));
}
many => {
out.insert(
key,
Value::Array(
many.iter()
.map(|v| Value::String((*v).to_owned()))
.collect(),
),
);
}
}
}
Value::Object(out)
}
pub(crate) fn print(answer: &Answer) {
if answer.withheld {
super::common::exit_withheld(&answer.text);
}
if answer.released && answer.failed == Some(Code::Withheld) {
super::common::exit_refused(&answer.text);
}
if answer.released {
super::common::print_released(&answer.text);
} else {
println!("{}", answer.text);
}
if let Some(code) = answer.failed {
std::process::exit(code.exit_status());
}
}
pub(crate) fn emit<T: Serialize>(kind: &str, build: impl FnOnce() -> Result<T, Failure>) {
print(&answer(kind, build));
}
pub(crate) fn emit_released<T: Serialize>(
tool: &str,
project_root: &str,
kind: &str,
build: impl FnOnce() -> Result<T, Failure>,
) {
print(&answer_released(tool, project_root, kind, Via::Cli, build));
}
pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Result<Option<&'a str>, Failure> {
let attached = args
.iter()
.find_map(|a| a.strip_prefix(name).and_then(|rest| rest.strip_prefix('=')));
if let Some(value) = attached {
return if value.is_empty() {
Err(Failure::invalid(format!("{name} needs a value")))
} else {
Ok(Some(value))
};
}
match args.iter().position(|a| a == name) {
None => Ok(None),
Some(i) => args
.get(i + 1)
.filter(|v| !v.starts_with("--"))
.map(|v| Some(v.as_str()))
.ok_or_else(|| Failure::invalid(format!("{name} needs a value"))),
}
}
pub(crate) fn flags<'a>(args: &'a [String], name: &str) -> Result<Vec<&'a str>, Failure> {
let mut out = Vec::new();
for (i, arg) in args.iter().enumerate() {
if arg != name {
continue;
}
match args.get(i + 1).filter(|v| !v.starts_with("--")) {
Some(value) => out.push(value.as_str()),
None => return Err(Failure::invalid(format!("{name} needs a value"))),
}
}
Ok(out)
}
const VALUE_FLAGS: &[&str] = &[
"--depth",
"--direction",
"--findings",
"--by",
"--title",
"--goal",
"--acceptance",
"--reason",
"--summary",
"--evidence",
"--verdict",
"--tokens",
"--project-root",
"--path",
"--root",
"--state",
"--role",
"--category",
"--query",
"--limit",
"--since",
"--to",
"--thread",
"--message",
"--contract",
"--minutes",
"--session",
"--project",
"--kind",
"--from",
"--as",
"--priority",
"--labels",
"--session-id",
"--name",
"--expires-in-hours",
"--agent",
"--resource-kind",
"--resource",
"--lease",
"--days",
"--id",
"--key",
"--value",
"--confidence",
"--relation",
"--output",
"--request-id",
"--vault",
];
pub(crate) fn positionals(args: &[String]) -> Vec<&str> {
split_positionals(args).0
}
pub(crate) fn split_positionals(args: &[String]) -> (Vec<&str>, Vec<&str>) {
let (mut positional, mut flags) = (Vec::new(), Vec::new());
let mut value = false;
for arg in args {
if value {
value = false;
flags.push(arg.as_str());
} else if arg.starts_with("--") {
value = !arg.contains('=') && VALUE_FLAGS.contains(&arg.as_str());
flags.push(arg.as_str());
} else {
positional.push(arg.as_str());
}
}
(positional, flags)
}
pub(crate) fn limit(args: &[String], default: usize, max: usize) -> Result<usize, Failure> {
match flag(args, "--limit")? {
None => Ok(default),
Some(raw) => raw
.parse::<usize>()
.ok()
.filter(|n| (1..=max).contains(n))
.ok_or_else(|| Failure::invalid(format!("--limit is 1-{max}"))),
}
}
pub(crate) fn project_root(args: &[String]) -> Result<String, Failure> {
let root = super::common::detect_project_root(args);
if lean_ctx::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(&root)) {
return Err(Failure::new(
Code::NoProject,
format!("{root} is not a project"),
));
}
Ok(root)
}
pub(crate) use super::knowledge_shared::rfc3339;