use std::path::Path;
use anyhow::Result;
use brok_core::Workspace;
use brok_index::{Access, Index, PartitionStatus};
use brok_shard::{InstalledShard, Registry};
use console::style;
use serde_json::{Value, json};
use crate::{daemon, ui};
#[derive(Debug, clap::Args)]
pub struct Args {
#[arg(long)]
json: bool,
}
pub async fn run(cwd: &Path, args: Args) -> Result<()> {
if args.json {
let status = match Workspace::discover(cwd) {
Ok(workspace) => json_status(&workspace).await?,
Err(_) => json!({ "version": env!("CARGO_PKG_VERSION"), "initialized": false }),
};
println!("{status}");
return Ok(());
}
let workspace = super::workspace(cwd)?;
let config = workspace.config();
let running = daemon::is_running(&workspace).await;
ui::header("Workspace");
println!(" root: {}", workspace.root().display());
println!(
" daemon: {}",
if running { style("running").green().to_string() } else { style("stopped").dim().to_string() }
);
let features = brok_index::compiled_features();
println!(" backends: {}", if features.is_empty() { "none (lean build)".into() } else { features.join(", ") });
println!(
" embeddings: {}",
if config.embeddings.enabled {
format!(
"{} ({} dims, {:?})",
config.embeddings.model, config.embeddings.dimensions, config.embeddings.variant
)
} else {
"disabled (BM25 only)".into()
}
);
println!(" llm: {}", config.llm.default);
println!(" sync: {:?}", config.sync.backend);
println!();
ui::header("Index");
let partitions = partitions(&workspace).await?;
if partitions.is_empty() {
println!(" not indexed yet (run `brok index`)");
}
for p in partitions {
println!(
" {:<5} {:<28} {:>6} files {:>7} chunks {} {}",
tier(&p),
display_path(&p),
p.files,
p.chunks,
p.backend,
if p.semantic { "hybrid" } else { "bm25" }
);
}
let links = super::link::statuses(&workspace).await?;
if !links.is_empty() {
println!();
ui::header("Linked workspaces");
for link in &links {
let state = match &link.error {
Some(error) => style(error.clone()).yellow().to_string(),
None => format!("{} files, {} chunks", link.files, link.chunks),
};
println!(" {:<16} {:<28} {state}", link.name, link.git.as_deref().unwrap_or(&link.root));
}
}
let members = brok_core::members::Member::all(&workspace);
if !members.is_empty() {
println!();
ui::header("Meta Workspace members");
for member in &members {
let state = match member.state() {
brok_core::members::MemberState::Missing => style("missing").red().to_string(),
brok_core::members::MemberState::NotCloned => {
style("not cloned (brok workspace sync)").yellow().to_string()
}
_ if member.is_git() => "searchable (cloned by brok)".to_owned(),
_ if member.is_workspace() => "searchable (own brokspace)".to_owned(),
_ => style("no brokspace of its own").dim().to_string(),
};
println!(" {:<16} {:<28} {state}", member.id, member.root.display());
}
}
println!();
ui::header("Memory");
if config.memory.enabled {
let counts = memory_counts(&workspace);
println!(
" {} private, {} shared, {} global{}",
counts.0,
counts.1,
counts.2,
if config.memory.sessions { "" } else { " (chat sessions are not saved)" }
);
} else {
println!(" off (memory.enabled)");
}
println!();
ui::header("Shards");
let shards = Registry::new(workspace.paths()).list()?;
if shards.is_empty() {
println!(" none installed");
}
for shard in shards {
let state = match shard_state(&workspace, &shard) {
"disabled" => style("disabled").dim().to_string(),
"skills" => style("skills").cyan().to_string(),
"missing-binary" => style("missing binary").red().to_string(),
other => style(other).green().to_string(),
};
let source = shard.lock.as_ref().map(|l| l.source.to_string()).unwrap_or_default();
println!(" {:<24} {:<10} {:<16} {}", shard.manifest.name, shard.manifest.version, state, style(source).dim());
}
Ok(())
}
async fn json_status(workspace: &Workspace) -> Result<Value> {
let config = workspace.config();
let llm = config.llm.providers.get(&config.llm.default);
let index: Vec<Value> = partitions(workspace)
.await?
.iter()
.map(|p| {
json!({
"tier": tier(p), "path": display_path(p), "files": p.files, "chunks": p.chunks,
"backend": p.backend, "semantic": p.semantic,
})
})
.collect();
let shards: Vec<Value> = Registry::new(workspace.paths())
.list()?
.iter()
.map(|shard| {
json!({
"name": shard.manifest.name,
"version": shard.manifest.version.to_string(),
"description": shard.manifest.description,
"state": shard_state(workspace, shard),
"source": shard.lock.as_ref().map(|l| l.source.to_string()),
})
})
.collect();
let memories = memory_counts(workspace);
let members: Vec<Value> = brok_core::members::Member::all(workspace)
.iter()
.map(|m| json!({ "id": m.id, "root": m.root, "state": m.state(), "has_brokspace": m.is_workspace(), "git": m.config.git }))
.collect();
let mut status = json!({
"version": env!("CARGO_PKG_VERSION"),
"initialized": true,
"root": workspace.root(),
"daemon": { "running": daemon::is_running(workspace).await },
"backends": brok_index::compiled_features(),
"embeddings": {
"enabled": config.embeddings.enabled,
"model": config.embeddings.model,
"dimensions": config.embeddings.dimensions,
},
"llm": {
"provider": config.llm.default,
"model": llm.map(|p| p.model.as_str()),
"base_url": llm.map(|p| p.base_url.as_str()),
},
"index": index,
"shards": shards,
"links": super::link::statuses(workspace).await?,
"memory": {
"enabled": config.memory.enabled,
"sessions": config.memory.sessions,
"global": config.memory.global,
"counts": { "private": memories.0, "shared": memories.1, "global": memories.2 },
},
});
if !members.is_empty() {
status["members"] = json!(members);
}
Ok(status)
}
fn memory_counts(workspace: &Workspace) -> (usize, usize, usize) {
use brok_core::memory::Scope;
let memories = brok_core::MemoryDirs::of(workspace.paths(), workspace.config()).list();
let count = |scope| memories.iter().filter(|m| m.scope == scope).count();
(count(Scope::Private), count(Scope::Shared), count(Scope::Global))
}
async fn partitions(workspace: &Workspace) -> Result<Vec<PartitionStatus>> {
let index = Index::open(workspace, None, Access::ReadOnly).await?;
index.status().await
}
fn tier(p: &PartitionStatus) -> String {
format!("{:?}", p.tier).to_lowercase()
}
fn display_path(p: &PartitionStatus) -> &str {
if p.path.is_empty() { "." } else { p.path.as_str() }
}
fn shard_state(workspace: &Workspace, shard: &InstalledShard) -> &'static str {
match (workspace.config().shard_enabled(&shard.manifest.name), shard.manifest.has_process(), shard.is_runnable()) {
(false, _, _) => "disabled",
(true, false, _) => "skills",
(true, true, false) => "missing-binary",
(true, true, true) => "enabled",
}
}