mod burn;
mod codex;
mod cursor;
mod detect;
mod device;
mod gemini;
mod ingest;
mod metrics;
mod onboarding;
mod pricing;
mod service;
mod session_import;
#[allow(dead_code, unused_imports)]
mod skillgen;
mod sources;
mod sync_cmd;
mod workspace;
mod worktree;
const DEFAULT_NAMESPACE: &str = "default";
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{Shell, generate};
use serde_json::Value;
use std::path::PathBuf;
#[allow(dead_code)]
const EMBEDDED_AGENTS_MD: &str = include_str!("../assets/AGENTS.md");
const AGENTS_SOURCE: &str = "ctxone-agents";
const PERSONAL_NAMESPACE: &str = "_personal";
const PERSONAL_REF: &str = "main";
fn in_personal(url: &str) -> String {
in_namespace(url, PERSONAL_NAMESPACE)
}
fn in_namespace(url: &str, namespace: &str) -> String {
let sep = if url.contains('?') { '&' } else { '?' };
format!("{url}{sep}namespace={}", urlencoding(namespace))
}
#[allow(dead_code)]
const EX_OK: i32 = 0;
#[allow(dead_code)]
const EX_USAGE: i32 = 64; const EX_DATAERR: i32 = 65; const EX_NOINPUT: i32 = 66; const EX_UNAVAILABLE: i32 = 69; const EX_SOFTWARE: i32 = 70; const EX_IOERR: i32 = 74; const EX_TEMPFAIL: i32 = 75; const EX_PROTOCOL: i32 = 76;
#[derive(Copy, Clone, Debug, ValueEnum, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
Text,
Json,
Id,
}
#[derive(Parser)]
#[command(name = "ctx", about = "CtxOne — AI agent memory CLI", version)]
#[command(disable_help_subcommand = true)]
struct RawCli {
#[arg(long, env = "CTX_SERVER", global = true)]
server: Option<String>,
#[arg(long, env = "CTX_BRANCH", global = true)]
branch: Option<String>,
#[arg(long, env = "CTX_FORMAT", value_enum, global = true)]
format: Option<OutputFormat>,
#[arg(long, env = "CTX_SESSION", global = true)]
session: Option<String>,
#[arg(long, env = "CTX_NAMESPACE", global = true)]
namespace: Option<String>,
#[arg(long, env = "CTX_TOKEN", global = true)]
token: Option<String>,
#[command(subcommand)]
command: Commands,
}
struct Cli {
server: String,
branch: String,
branch_explicit: bool,
format: OutputFormat,
session: Option<String>,
namespace: Option<String>,
token: Option<String>,
command: Commands,
}
impl Cli {
fn from_raw(raw: RawCli, config: &CtxConfig) -> Self {
let branch_explicit = raw.branch.is_some();
Self {
server: raw
.server
.or_else(|| config.server.clone())
.unwrap_or_else(|| "http://localhost:3001".to_string()),
branch: raw
.branch
.or_else(|| config.branch.clone())
.unwrap_or_else(|| "main".to_string()),
branch_explicit,
format: raw.format.or(config.format).unwrap_or(OutputFormat::Text),
session: raw.session,
namespace: raw.namespace,
token: raw.token,
command: raw.command,
}
}
async fn resolve_namespace(&self) -> Result<Option<String>, detect::DetectFailure> {
if let Some(ns) = &self.namespace {
return Ok(Some(ns.clone()));
}
let cwd = std::env::current_dir().map_err(|e| {
detect::DetectFailure::new(
detect::FailureKind::NoCwd,
"the current directory",
format!("it is unavailable ({e})"),
)
})?;
let cwd = cwd.to_string_lossy();
let mut headers = reqwest::header::HeaderMap::new();
if let Some(ref token) = self.token
&& let Ok(mut val) = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
{
val.set_sensitive(true);
headers.insert(reqwest::header::AUTHORIZATION, val);
}
let client = reqwest::Client::builder()
.timeout(detect::DETECT_TIMEOUT)
.default_headers(headers)
.build()
.map_err(|e| {
detect::DetectFailure::new(
detect::FailureKind::Hub,
&cwd,
format!("couldn't build an HTTP client ({e})"),
)
})?;
detect::detect(&client, &self.server, &cwd).await
}
fn client_factory(&self) -> ClientFactory {
ClientFactory {
session: self.session.clone(),
token: self.token.clone(),
}
}
fn effective_namespace(namespace: Option<&str>) -> &str {
namespace.unwrap_or(DEFAULT_NAMESPACE)
}
fn http_client(&self, namespace: Option<&str>) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
if let Some(ref sid) = self.session
&& let Ok(val) = reqwest::header::HeaderValue::from_str(sid)
{
headers.insert("X-CTXone-Session", val);
}
if let Ok(val) =
reqwest::header::HeaderValue::from_str(Self::effective_namespace(namespace))
{
headers.insert("X-CTXone-Namespace", val);
}
if let Some(ref token) = self.token
&& let Ok(mut val) = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
{
val.set_sensitive(true);
headers.insert(reqwest::header::AUTHORIZATION, val);
}
let builder = reqwest::Client::builder().default_headers(headers);
builder.build().unwrap_or_default()
}
}
#[derive(Clone, Default)]
struct ClientFactory {
session: Option<String>,
token: Option<String>,
}
impl ClientFactory {
fn build(&self, namespace: Option<&str>) -> reqwest::Client {
let mut headers = reqwest::header::HeaderMap::new();
if let Some(ref sid) = self.session
&& let Ok(val) = reqwest::header::HeaderValue::from_str(sid)
{
headers.insert("X-CTXone-Session", val);
}
if let Ok(val) = reqwest::header::HeaderValue::from_str(Cli::effective_namespace(namespace))
{
headers.insert("X-CTXone-Namespace", val);
}
if let Some(ref token) = self.token
&& let Ok(mut val) = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
{
val.set_sensitive(true);
headers.insert(reqwest::header::AUTHORIZATION, val);
}
reqwest::Client::builder()
.default_headers(headers)
.build()
.unwrap_or_default()
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
struct CtxConfig {
#[serde(skip_serializing_if = "Option::is_none")]
server: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
branch: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
format: Option<OutputFormat>,
#[serde(skip_serializing_if = "Option::is_none")]
import_since: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
scan_dirs: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
remote_turns: Option<bool>,
}
impl CtxConfig {
fn path() -> PathBuf {
if cfg!(target_os = "windows") {
dirs::config_dir()
.map(|d| d.join("ctxone").join("config.toml"))
.unwrap_or_else(|| PathBuf::from("./ctxone-config.toml"))
} else {
dirs::home_dir()
.map(|h| h.join(".ctxone").join("config.toml"))
.unwrap_or_else(|| PathBuf::from("./ctxone-config.toml"))
}
}
fn load() -> Self {
let path = Self::path();
if !path.exists() {
return Self::default();
}
let content = match std::fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => return Self::default(),
};
toml::from_str(&content).unwrap_or_default()
}
fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
let path = Self::path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let toml_str = toml::to_string_pretty(self)?;
std::fs::write(&path, toml_str)?;
Ok(())
}
fn set_key(&mut self, key: &str, value: &str) -> Result<(), String> {
match key {
"server" => self.server = Some(value.to_string()),
"branch" => self.branch = Some(value.to_string()),
"format" => {
let f = match value.to_lowercase().as_str() {
"text" => OutputFormat::Text,
"json" => OutputFormat::Json,
"id" => OutputFormat::Id,
_ => return Err(format!("unknown format: {} (expected text|json|id)", value)),
};
self.format = Some(f);
}
"import_since" => self.import_since = Some(value.to_string()),
"scan_dirs" => {
self.scan_dirs = value
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
"remote_turns" => {
self.remote_turns =
Some(parse_bool(value).ok_or_else(|| {
format!("remote_turns must be true or false, not {value:?}")
})?);
}
_ => {
return Err(format!(
"unknown key: {} (expected server|branch|format|import_since|scan_dirs|remote_turns)",
key
));
}
}
Ok(())
}
fn get_key(&self, key: &str) -> Result<String, String> {
match key {
"server" => Ok(self.server.clone().unwrap_or_default()),
"branch" => Ok(self.branch.clone().unwrap_or_default()),
"format" => Ok(self
.format
.map(|f| match f {
OutputFormat::Text => "text",
OutputFormat::Json => "json",
OutputFormat::Id => "id",
})
.unwrap_or("")
.to_string()),
"import_since" => Ok(self.import_since.clone().unwrap_or_default()),
"scan_dirs" => Ok(self.scan_dirs.join(",")),
"remote_turns" => Ok(self.remote_turns.map(|b| b.to_string()).unwrap_or_default()),
_ => Err(format!(
"unknown key: {} (expected server|branch|format|import_since|scan_dirs|remote_turns)",
key
)),
}
}
fn unset_key(&mut self, key: &str) -> Result<(), String> {
match key {
"server" => self.server = None,
"branch" => self.branch = None,
"format" => self.format = None,
"import_since" => self.import_since = None,
"scan_dirs" => self.scan_dirs.clear(),
"remote_turns" => self.remote_turns = None,
_ => {
return Err(format!(
"unknown key: {} (expected server|branch|format|import_since|scan_dirs|remote_turns)",
key
));
}
}
Ok(())
}
}
fn parse_bool(value: &str) -> Option<bool> {
match value.trim().to_ascii_lowercase().as_str() {
"true" | "1" | "yes" | "on" => Some(true),
"false" | "0" | "no" | "off" => Some(false),
_ => None,
}
}
fn remote_turns_opted_in(env: Option<&str>, cfg: &CtxConfig) -> bool {
match env {
Some(v) if !v.trim().is_empty() => parse_bool(v).unwrap_or(false),
_ => cfg.remote_turns.unwrap_or(false),
}
}
fn turns_allowed(server: &str) -> bool {
crate::ingest::hub_is_local(server)
|| remote_turns_opted_in(
std::env::var("CTX_REMOTE_TURNS").ok().as_deref(),
&CtxConfig::load(),
)
}
#[derive(Subcommand)]
enum BranchAction {
Create {
name: String,
#[arg(long, default_value = "main", value_name = "REF")]
from: String,
},
List,
Rm {
name: String,
},
Reset {
name: String,
#[arg(long, value_name = "REF")]
to: String,
#[arg(long)]
backup: bool,
},
}
#[derive(Subcommand)]
enum ConfigAction {
Show,
Path,
Get {
key: String,
},
Set {
key: String,
value: String,
},
Unset {
key: String,
},
}
#[derive(Subcommand)]
enum Commands {
Skill {
#[arg(long)]
project: bool,
#[arg(long)]
tool: Option<String>,
#[arg(long)]
remove: bool,
#[arg(long)]
status: bool,
#[arg(long)]
no_nudge: bool,
#[arg(long)]
emit_spec: bool,
#[arg(long)]
dry_run: bool,
},
Bootstrap,
Remember {
fact: String,
#[arg(short, long, default_value = "medium")]
importance: String,
#[arg(short, long)]
context: Option<String>,
#[arg(short, long)]
tags: Option<Vec<String>>,
#[arg(long)]
personal: bool,
},
Recall {
topic: String,
#[arg(short, long, default_value_t = 1500)]
budget: usize,
#[arg(long)]
exact: bool,
},
Tokens {
#[arg(default_value = "-")]
text: String,
},
Help {
topic: Option<String>,
#[arg(long)]
manifest: bool,
#[arg(long)]
publish: bool,
#[arg(long, hide = true)]
no_proxy: bool,
},
Context {
project: String,
},
Status,
Stats,
Serve {
#[arg(short, long, default_value_t = 3001)]
port: u16,
#[arg(long, default_value = "sqlite")]
storage: String,
#[arg(long)]
path: Option<String>,
#[arg(long)]
http: bool,
#[arg(long)]
lens: bool,
},
IngestSession {
#[arg(long)]
file: Option<String>,
#[arg(long, default_value = "claude")]
source: String,
#[arg(long)]
all: bool,
#[arg(long)]
since: Option<String>,
#[arg(long = "scan-dir")]
scan_dir: Vec<String>,
#[arg(long)]
last: Option<usize>,
#[arg(long)]
tokens_only: bool,
#[arg(long)]
dry_run: bool,
#[arg(long)]
full_turn: bool,
#[arg(long, conflicts_with = "full_turn")]
no_full_turn: bool,
#[arg(long)]
no_auto_register: bool,
#[arg(long)]
dir_workspaces: bool,
#[arg(long)]
reingest: bool,
},
Session {
#[command(subcommand)]
action: SessionAction,
},
CaptureTurn {
#[arg(long)]
transcript: Option<String>,
#[arg(long, env = "CTX_SESSION")]
session: Option<String>,
#[arg(long, default_value = "1")]
turns: usize,
#[arg(long)]
tokens_only: bool,
#[arg(long)]
no_full_turn: bool,
},
Demo,
Pinned,
#[command(visible_alias = "import-doc")]
Prime {
file: String,
#[arg(long)]
pin: bool,
#[arg(long)]
source: Option<String>,
},
Completion {
shell: Shell,
},
Doctor,
Diff {
ref_a: String,
ref_b: String,
},
Merge {
source: String,
#[arg(long, default_value = "main")]
into: String,
#[arg(short = 'm', long)]
message: Option<String>,
#[arg(long)]
dry_run: bool,
#[arg(long)]
allow_deletions: bool,
#[arg(long)]
allow_regressions: bool,
},
Forget {
path: String,
#[arg(long)]
reason: Option<String>,
#[arg(long)]
personal: bool,
},
WhyDidWe {
decision: String,
},
SummarizeSession {
#[arg(long = "point", short = 'p', required = true)]
points: Vec<String>,
#[arg(long = "decision", short = 'd')]
decisions: Vec<String>,
},
RecordUsage {
#[arg(long = "input")]
input_tokens: u64,
#[arg(long = "output")]
output_tokens: u64,
#[arg(long = "cache-read", default_value_t = 0)]
cache_read_tokens: u64,
#[arg(long = "cache-create", default_value_t = 0)]
cache_create_tokens: u64,
#[arg(long)]
model: Option<String>,
#[arg(long)]
provider: Option<String>,
},
Search {
query: String,
#[arg(short = 'n', long, default_value_t = 50)]
max: usize,
},
Ls {
#[arg(default_value = "/")]
prefix: String,
#[arg(long, default_value_t = 50)]
max_depth: usize,
},
Get {
path: String,
},
Log {
#[arg(short = 'n', long, default_value_t = 20)]
limit: usize,
},
Blame {
path: String,
},
Tail {
#[arg(long, default_value_t = 2000)]
interval: u64,
},
#[command(hide = true)]
Branches,
Branch {
#[command(subcommand)]
action: BranchAction,
},
Config {
#[command(subcommand)]
action: ConfigAction,
},
Init {
#[arg(long)]
global: bool,
#[arg(long)]
project: bool,
#[arg(long)]
tool: Option<String>,
#[arg(long)]
config_path: Option<String>,
#[arg(long)]
dry_run: bool,
#[arg(long)]
no_agents: bool,
#[arg(long)]
no_mcp: bool,
#[arg(long, value_enum, default_value_t = McpTransport::Http)]
transport: McpTransport,
#[arg(long, default_value = "http://localhost:3001/mcp")]
mcp_url: String,
#[arg(long)]
auth_token: Option<String>,
#[arg(long)]
auth_token_env: Option<String>,
},
Agents {
#[command(subcommand)]
action: AgentsAction,
},
Secrets {
#[command(subcommand)]
action: SecretsAction,
},
Plan {
#[command(subcommand)]
action: PlanAction,
},
Analyze {
#[command(subcommand)]
action: AnalyzeAction,
},
Worktree {
#[command(subcommand)]
action: worktree::WorktreeAction,
},
Taint {
#[command(subcommand)]
action: TaintAction,
},
Db {
#[command(subcommand)]
action: DbAction,
},
Docs {
#[command(subcommand)]
action: DocsAction,
},
Project {
#[command(subcommand)]
action: ProjectAction,
},
Workspace {
#[command(subcommand)]
action: WorkspaceAction,
},
Service {
#[command(subcommand)]
action: ServiceAction,
},
Reminder {
#[command(subcommand)]
action: ReminderAction,
},
Remote {
#[command(subcommand)]
action: sync_cmd::RemoteAction,
},
Push {
#[arg(long = "allow", value_name = "FINDING=REASON")]
allow: Vec<String>,
},
Pull,
Sync {
#[command(subcommand)]
action: Option<sync_cmd::SyncAction>,
#[arg(long = "allow", value_name = "FINDING=REASON")]
allow: Vec<String>,
},
Move {
path: String,
#[arg(long)]
to_namespace: String,
#[arg(long)]
from_namespace: Option<String>,
#[arg(long)]
to_branch: Option<String>,
#[arg(long)]
no_delete: bool,
#[arg(long)]
dry_run: bool,
},
}
#[derive(Subcommand, Debug)]
enum AnalyzeAction {
List,
Estimate {
#[arg(long)]
provider: Option<String>,
#[arg(long)]
model: Option<String>,
},
}
#[derive(Subcommand, Debug)]
enum ServiceAction {
Install {
#[arg(long, default_value_t = 3001)]
port: u16,
#[arg(long)]
path: Option<String>,
#[arg(long)]
no_lens: bool,
#[arg(long)]
auth_token: Option<String>,
#[arg(long)]
dry_run: bool,
#[arg(long)]
force: bool,
},
Uninstall {
#[arg(long)]
dry_run: bool,
},
Status,
Tick {
#[command(subcommand)]
action: TickAction,
},
}
#[derive(Subcommand, Debug)]
enum TickAction {
Install {
#[arg(long, default_value_t = 3600)]
interval: u64,
#[arg(long, default_value = "~/.ctxone/reminder-tick.allow")]
allowlist: String,
#[arg(long = "skip")]
skip: Vec<String>,
#[arg(long)]
dry_run: bool,
#[arg(long)]
force: bool,
},
Uninstall {
#[arg(long)]
dry_run: bool,
},
Status,
}
#[derive(Subcommand, Debug)]
enum ProjectAction {
Add {
id: String,
#[arg(long)]
display_name: Option<String>,
#[arg(long)]
path: Option<String>,
#[arg(long)]
no_marker: bool,
},
List,
Use {
id: String,
#[arg(long)]
no_marker: bool,
},
Detect,
}
#[derive(Subcommand, Debug)]
enum WorkspaceAction {
List {
#[arg(long)]
json: bool,
},
}
#[derive(clap::Subcommand)]
enum SessionAction {
Move {
session_id: String,
#[arg(long)]
to: String,
},
Metrics {
#[arg(long)]
project: Option<String>,
#[arg(long)]
session: Option<String>,
#[arg(long)]
list: bool,
#[arg(long)]
all: bool,
#[arg(long)]
json: bool,
#[arg(long, default_value_t = 5.0)]
gap: f64,
#[arg(long)]
verbose: bool,
},
Reattribute {
#[arg(long)]
dry_run: bool,
#[arg(long)]
auto_register: bool,
},
Segments {
session_id: String,
#[arg(long, default_value_t = 30)]
gap: i64,
},
List {
#[arg(long)]
source: Option<String>,
#[arg(long, default_value_t = 1)]
page: usize,
#[arg(long)]
all: bool,
#[arg(long)]
json: bool,
},
Import {
selectors: Vec<String>,
#[arg(long)]
source: Option<String>,
#[arg(long)]
to: Option<String>,
#[arg(long)]
include_ignored: bool,
#[arg(long)]
quiet: bool,
#[arg(long)]
dry_run: bool,
},
Ignore {
selectors: Vec<String>,
#[arg(long)]
source: Option<String>,
},
Unignore {
selectors: Vec<String>,
#[arg(long)]
source: Option<String>,
},
}
#[derive(Subcommand, Debug)]
enum TaintAction {
List {
#[arg(long)]
path_prefix: Option<String>,
#[arg(long)]
kind: Option<String>,
#[arg(long)]
include_resolved: bool,
},
Check {
path: String,
#[arg(long = "as")]
agent_id: Option<String>,
#[arg(long, default_value_t = 1.0)]
confidence: f64,
},
Apply {
path: String,
#[arg(long)]
name: String,
#[arg(long, default_value = "taint")]
kind: String,
#[arg(long)]
effect: Option<String>,
#[arg(long, default_value = "medium")]
severity: String,
#[arg(long, short)]
reason: String,
#[arg(long, value_delimiter = ',')]
authorized: Vec<String>,
},
Remove {
taint_id: String,
#[arg(long, short)]
reason: String,
},
}
#[derive(Subcommand, Debug)]
enum DbAction {
Backup {
#[arg(long)]
suffix: Option<String>,
},
Restore {
snapshot: String,
#[arg(long)]
to: String,
#[arg(long)]
yes: bool,
},
Export {
#[arg(long)]
out: Option<String>,
},
Import {
file: String,
},
Fsck {
#[arg(long)]
repair: bool,
#[arg(long)]
yes: bool,
},
Upgrade {
#[arg(long)]
check: bool,
},
}
#[derive(Subcommand)]
enum DocsAction {
Add {
path: String,
#[arg(long)]
status: Option<String>,
#[arg(long)]
scope: Option<String>,
#[arg(long)]
owner: Option<String>,
#[arg(long)]
answers: Option<String>,
#[arg(long)]
supersedes: Option<String>,
#[arg(long = "verified-commit")]
verified_commit: Option<String>,
},
List,
Find { query: String },
}
#[derive(Subcommand)]
enum ReminderAction {
Tick {
#[arg(long, default_value = "~/.ctxone/reminder-tick.allow")]
allowlist: String,
#[arg(long = "skip")]
skip: Vec<String>,
#[arg(long, default_value_t = 12)]
defer_hours: i64,
#[arg(long)]
dry_run: bool,
},
Approve {
id: String,
},
}
const PROOF_EXAMPLES: &str =
"commit:abc1234 | test:cargo test foo | file:src/lib.rs | text:manually verified in staging";
fn parse_proof_spec(raw: &str) -> Result<(String, String, Option<String>), String> {
let parts: Vec<&str> = raw.splitn(3, ':').collect();
if parts.len() < 2 {
return Err(format!(
"invalid proof '{raw}': expected <kind>:<value>[:<note>]. Examples: {PROOF_EXAMPLES}"
));
}
let kind = parts[0].to_string();
let value = parts[1].to_string();
let note = parts.get(2).map(|s| s.to_string());
match kind.as_str() {
"commit" | "file" | "test" | "text" => Ok((kind, value, note)),
_ => Err(format!(
"unknown proof kind '{kind}' (expected commit|file|test|text). Examples: {PROOF_EXAMPLES}"
)),
}
}
#[derive(Subcommand)]
enum PlanAction {
New {
name: String,
#[arg(long, short)]
description: Option<String>,
},
Relocate {
name: String,
#[arg(long)]
to: String,
},
Add {
plan_id: String,
title: String,
#[arg(long, short = 'd', visible_alias = "description")]
notes: Option<String>,
#[arg(long, default_value = "medium")]
priority: String,
#[arg(long)]
parent: Option<String>,
#[arg(long = "assigned-to")]
assigned_to: Option<String>,
#[arg(long = "blocks", short = 'b')]
blocks: Vec<String>,
#[arg(long)]
force: bool,
},
Start {
plan_id: String,
task_id: String,
#[arg(long)]
reason: Option<String>,
},
Done {
plan_id: String,
task_id: String,
#[arg(long, short)]
proof: String,
#[arg(long)]
reason: Option<String>,
},
Abandon {
plan_id: String,
task_id: String,
#[arg(long, short)]
reason: String,
},
Edit {
plan_id: String,
task_id: String,
#[arg(long)]
title: Option<String>,
#[arg(long, short = 'd', visible_alias = "description")]
notes: Option<String>,
#[arg(long)]
priority: Option<String>,
#[arg(long = "blocks", short = 'b', conflicts_with = "clear_blockers")]
blocks: Vec<String>,
#[arg(long = "clear-blockers")]
clear_blockers: bool,
#[arg(long)]
force: bool,
},
Next {
plan_id: String,
#[arg(long = "assigned-to")]
assigned_to: Option<String>,
#[arg(long)]
me: bool,
#[arg(long = "include-unassigned", default_value_t = true)]
include_unassigned: bool,
#[arg(long = "assigned-only")]
assigned_only: bool,
#[arg(long = "in-order")]
in_order: bool,
},
List {
#[arg(long)]
status: Option<String>,
#[arg(long = "all-namespaces")]
all_namespaces: bool,
},
Link {
plan_id: String,
task_id: String,
target: String,
},
Stale {
#[arg(long, default_value_t = 7)]
days: i64,
#[arg(long = "all-namespaces")]
all_namespaces: bool,
},
Show { plan_id: String },
Tasks {
plan_id: String,
#[arg(long = "task")]
task_id: Option<String>,
},
Unpack {
#[arg(required_unless_present = "all", conflicts_with = "all")]
plan_id: Option<String>,
#[arg(long)]
all: bool,
#[arg(long = "dry-run")]
dry_run: bool,
},
Archive { plan_id: String },
Close {
plan_id: String,
#[arg(long, short)]
summary: String,
},
Complete {
plan_id: String,
#[arg(long, short)]
summary: String,
#[arg(long, short)]
reason: Option<String>,
},
Move {
plan_id: String,
#[arg(long = "to")]
target: String,
#[arg(long)]
replace_archived: bool,
},
}
#[derive(Subcommand)]
enum SecretsAction {
Scan {
#[arg(long)]
turns: bool,
#[arg(long)]
all: bool,
},
}
#[derive(Subcommand)]
enum AgentsAction {
Install {
#[arg(long)]
file: Option<String>,
#[arg(long)]
yes: bool,
#[arg(long)]
show: bool,
},
Show,
Status,
Remove,
Migrate {
#[arg(long)]
apply: bool,
},
}
fn extract_id(v: &Value) -> Option<&str> {
for key in ["name", "commit_id", "id", "path"] {
if let Some(s) = v.get(key).and_then(|x| x.as_str()) {
return Some(s);
}
}
None
}
fn help_index_path() -> Option<std::path::PathBuf> {
if let Some(p) = std::env::var_os("AGENTSTATE_HELP_INDEX") {
return Some(std::path::PathBuf::from(p));
}
std::env::var_os("HOME")
.map(|h| std::path::PathBuf::from(h).join(".config/agentstate/help-index.json"))
}
async fn publish_help_index(
server: &str,
client: &reqwest::Client,
) -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
let url = format!("{}/api/help/manifest", server);
let resp = client.get(&url).send().await?;
if !resp.status().is_success() {
return Err(format!("hub returned {} for {}", resp.status(), url).into());
}
let manifest: Value = resp.json().await?;
let tool = manifest
.get("tool")
.and_then(|t| t.as_str())
.ok_or("manifest missing `tool`")?
.to_string();
let path = help_index_path().ok_or("cannot resolve HOME")?;
let mut index = std::fs::read_to_string(&path)
.ok()
.and_then(|s| serde_json::from_str::<Value>(&s).ok())
.filter(|v| v.is_object())
.unwrap_or_else(|| serde_json::json!({ "schema": 1, "tools": {} }));
if !index.get("tools").map(|t| t.is_object()).unwrap_or(false) {
index["tools"] = serde_json::json!({});
}
index["schema"] = serde_json::json!(1);
index["tools"][&tool] = serde_json::json!({
"version": manifest.get("version").cloned().unwrap_or(Value::Null),
"features": manifest.get("features").cloned().unwrap_or_else(|| serde_json::json!([])),
});
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(
&path,
format!("{}\n", serde_json::to_string_pretty(&index)?),
)?;
Ok(path)
}
fn render_help(v: &Value) {
if let Some(groups) = v.get("groups").and_then(|g| g.as_object()) {
println!(
"ctx help — {} features (v{}). Call `ctx help <feature>` for details.\n",
v.get("feature_count").and_then(|c| c.as_u64()).unwrap_or(0),
v.get("version").and_then(|s| s.as_str()).unwrap_or("?"),
);
for (group, feats) in groups {
println!("{}:", group);
if let Some(arr) = feats.as_array() {
for f in arr {
println!(
" {:<22} {}",
f.get("feature").and_then(|s| s.as_str()).unwrap_or(""),
f.get("synopsis").and_then(|s| s.as_str()).unwrap_or(""),
);
}
}
println!();
}
return;
}
if let Some(matches) = v.get("matches").and_then(|m| m.as_array()) {
println!(
"No exact match for '{}'. Did you mean:",
v.get("query").and_then(|s| s.as_str()).unwrap_or(""),
);
for m in matches {
println!(
" {:<22} {}",
m.get("feature").and_then(|s| s.as_str()).unwrap_or(""),
m.get("synopsis").and_then(|s| s.as_str()).unwrap_or(""),
);
}
return;
}
if let Some(nf) = v.get("not_found").and_then(|s| s.as_str()) {
println!("No ctx feature matched '{}'.", nf);
if let Some(hint) = v.get("hint").and_then(|s| s.as_str()) {
println!("{}", hint);
}
if let Some(arr) = v.get("did_you_mean").and_then(|d| d.as_array()) {
let names: Vec<&str> = arr.iter().filter_map(|x| x.as_str()).collect();
println!("Available: {}", names.join(", "));
}
return;
}
let get = |k: &str| v.get(k).and_then(|s| s.as_str()).unwrap_or("");
if let Some(from) = v.get("proxied_from").and_then(|s| s.as_str()) {
println!("(via {from})");
}
println!("{} — {}", get("feature"), get("synopsis"));
println!(" syntax: {}", get("syntax"));
if let Some(params) = v.get("params").and_then(|p| p.as_array())
&& !params.is_empty()
{
println!(" params:");
for p in params {
let req = if p.get("required").and_then(|b| b.as_bool()).unwrap_or(false) {
"(required)"
} else {
"(optional)"
};
println!(
" {:<16} {} {}",
p.get("name").and_then(|s| s.as_str()).unwrap_or(""),
req,
p.get("desc").and_then(|s| s.as_str()).unwrap_or(""),
);
}
}
let list = |label: &str, key: &str| {
if let Some(arr) = v.get(key).and_then(|a| a.as_array())
&& !arr.is_empty()
{
println!(" {}:", label);
for item in arr {
if let Some(s) = item.as_str() {
println!(" - {}", s);
}
}
}
};
list("examples", "examples");
list("gotchas", "gotchas");
list("related", "related");
if let Some(also) = v.get("also").and_then(|a| a.as_array())
&& !also.is_empty()
{
let names: Vec<&str> = also.iter().filter_map(|x| x.as_str()).collect();
println!(" see also: {}", names.join(", "));
}
println!(
" (~{} tokens, v{})",
v.get("help_tokens").and_then(|t| t.as_u64()).unwrap_or(0),
get("version"),
);
}
fn emit<F: FnOnce(&Value)>(format: OutputFormat, value: &Value, text_fn: F) {
match format {
OutputFormat::Json => {
println!(
"{}",
serde_json::to_string_pretty(value).unwrap_or_default()
);
}
OutputFormat::Text => text_fn(value),
OutputFormat::Id => {
if let Some(arr) = value.as_array() {
for item in arr {
if let Some(s) = item.as_str() {
println!("{}", s);
} else if let Some(id) = extract_id(item) {
println!("{}", id);
}
}
return;
}
if let Some(s) = value.as_str() {
println!("{}", s);
return;
}
if let Some(id) = extract_id(value) {
println!("{}", id);
}
}
}
}
fn count_tokens_cl100k(text: &str) -> usize {
thread_local! {
static BPE: std::cell::OnceCell<tiktoken_rs::CoreBPE> = const { std::cell::OnceCell::new() };
}
BPE.with(|cell| {
let bpe = cell.get_or_init(|| tiktoken_rs::cl100k_base().expect("cl100k_base encoding"));
bpe.encode_with_special_tokens(text).len()
})
}
async fn http_error_exit(resp: reqwest::Response, context: &str) -> ! {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
eprintln!("{}: {} — {}", context, status, body);
let code = if status.is_server_error() {
EX_PROTOCOL
} else if status.as_u16() == 404 {
EX_NOINPUT
} else if status.is_client_error() {
EX_DATAERR
} else {
EX_SOFTWARE
};
std::process::exit(code);
}
fn unreachable_exit(server: &str, e: reqwest::Error) -> ! {
eprintln!("Hub unreachable ({}): {}", server, e);
std::process::exit(EX_UNAVAILABLE);
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let raw = RawCli::parse();
let config = CtxConfig::load();
let cli = Cli::from_raw(raw, &config);
let mut status_detect_failure: Option<detect::DetectFailure> = None;
let namespace = match &cli.command {
Commands::Init { global: true, .. } => {
Some(global_init_namespace(cli.namespace.as_deref()))
}
Commands::Init { .. } => match cli.resolve_namespace().await {
Ok(ns) => ns,
Err(f) if f.kind == detect::FailureKind::Unreachable => {
eprintln!(" \u{26A0} {}", f.headline());
eprintln!(
" The configs below won't name a workspace. Re-run `ctx init` once \
the hub is running, or pass --namespace <workspace>."
);
None
}
Err(f) => f.exit(),
},
Commands::Status => match cli.resolve_namespace().await {
Ok(ns) => ns,
Err(f) => {
status_detect_failure = Some(f);
None
}
},
Commands::IngestSession { all: true, .. } => None,
Commands::Db { .. } => cli.namespace.clone(),
Commands::Remote { .. }
| Commands::Push { .. }
| Commands::Pull
| Commands::Sync { .. } => cli.namespace.clone(),
Commands::Skill { .. }
| Commands::Bootstrap
| Commands::Completion { .. }
| Commands::Config { .. }
| Commands::Serve { .. }
| Commands::Session { .. }
| Commands::Service { .. }
| Commands::Tokens { .. }
| Commands::Worktree { .. }
| Commands::Doctor => None,
_ => match cli.resolve_namespace().await {
Ok(ns) => ns,
Err(f) => f.exit(),
},
};
let client = cli.http_client(namespace.as_deref());
let client_factory = cli.client_factory();
let global_init = matches!(cli.command, Commands::Init { global: true, .. });
let mut cli = cli;
if namespace.is_some()
&& !global_init
&& !cli.branch_explicit
&& let Ok(cwd) = std::env::current_dir()
&& let Some(raw_branch) = read_git_branch(&cwd)
{
let mirrored = sanitize_branch_name(&raw_branch);
cli.branch = mirrored.clone();
if mirrored != "main" {
let _ = client
.post(format!("{}/api/branches", cli.server))
.json(&serde_json::json!({
"name": mirrored,
"from": "main",
"if_missing": true,
"git_branch": raw_branch,
}))
.send()
.await;
}
}
let cli = cli;
match cli.command {
Commands::Skill {
project,
tool,
remove,
status,
no_nudge,
emit_spec,
dry_run,
} => {
onboarding::run_skill(
project,
tool.as_deref(),
remove,
status,
no_nudge,
emit_spec,
dry_run,
)?;
}
Commands::Bootstrap => {
onboarding::run_bootstrap();
}
Commands::Remember {
fact,
importance,
context,
tags,
personal,
} => {
let fact = if fact == "-" {
use std::io::Read;
let mut buf = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut buf) {
eprintln!("Failed to read stdin: {}", e);
std::process::exit(EX_IOERR);
}
buf.trim().to_string()
} else {
fact
};
if fact.is_empty() {
eprintln!("Refusing to store an empty fact");
std::process::exit(EX_DATAERR);
}
let mut body = serde_json::json!({
"fact": fact.clone(),
"importance": importance,
"ref": if personal { PERSONAL_REF } else { cli.branch.as_str() },
});
if let Some(ctx) = context {
body["context"] = serde_json::json!(ctx);
}
if let Some(tags) = tags {
body["tags"] = serde_json::json!(tags);
}
let url = format!("{}/api/memory/remember", cli.server);
let resp = match client
.clone()
.post(if personal { in_personal(&url) } else { url })
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "remember failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
println!("Remembered: {}", fact);
if let Some(path) = v.get("path").and_then(|x| x.as_str()) {
println!(" path: {}", path);
}
if let Some(id) = v.get("commit_id").and_then(|x| x.as_str()) {
println!(" commit: {}", id);
}
});
}
Commands::Help {
topic,
manifest,
publish,
no_proxy,
} => {
if publish {
let path = publish_help_index(&cli.server, &client).await?;
println!("Published ctx help manifest to {}", path.display());
return Ok(());
}
let np = if no_proxy { "&no_proxy=true" } else { "" };
let url = if manifest {
format!("{}/api/help/manifest", cli.server)
} else {
match &topic {
Some(t) => {
format!("{}/api/help?topic={}{}", cli.server, urlencoding(t), np)
}
None => format!("{}/api/help", cli.server),
}
};
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "help failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| render_help(v));
}
Commands::Recall {
topic,
budget,
exact,
} => {
let url = format!(
"{}/api/memory/recall?topic={}&budget={}&ref={}",
cli.server,
urlencoding(&topic),
budget,
encode_ref(&cli.branch),
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "recall failed").await;
}
let mut parsed: Value = resp.json().await?;
if exact {
let results_text = parsed
.get("results")
.map(|r| serde_json::to_string(r).unwrap_or_default())
.unwrap_or_default();
let exact_sent = count_tokens_cl100k(&results_text);
let flat_url = format!(
"{}/api/state/{}?path=/",
cli.server,
encode_ref(&cli.branch)
);
let exact_flat = match client.get(&flat_url).send().await {
Ok(r) if r.status().is_success() => {
let body = r.text().await.unwrap_or_default();
count_tokens_cl100k(&body)
}
_ => 0,
};
let exact_ratio = if exact_sent > 0 {
exact_flat as f64 / exact_sent as f64
} else {
0.0
};
if let Some(obj) = parsed.as_object_mut() {
obj.insert(
"ctx_tokens_sent_exact".to_string(),
serde_json::json!(exact_sent),
);
obj.insert(
"ctx_tokens_estimated_flat_exact".to_string(),
serde_json::json!(exact_flat),
);
obj.insert(
"ctx_savings_ratio_exact".to_string(),
serde_json::json!(exact_ratio),
);
obj.insert("tokenizer".to_string(), serde_json::json!("cl100k_base"));
}
}
emit(cli.format, &parsed, |v| {
let empty_vec = vec![];
let results = v
.get("results")
.and_then(|x| x.as_array())
.unwrap_or(&empty_vec);
if results.is_empty() {
println!("No memories found for '{}'", topic);
return;
}
let mut printed_divider = false;
for r in results {
let is_pinned = r.get("pinned").and_then(|x| x.as_bool()).unwrap_or(false);
let path = r.get("path").and_then(|x| x.as_str()).unwrap_or("");
let personal =
r.get("namespace").and_then(|x| x.as_str()) == Some(PERSONAL_NAMESPACE);
if is_pinned {
let title = r.get("title").and_then(|x| x.as_str()).unwrap_or("");
let body = r.get("body").and_then(|x| x.as_str()).unwrap_or("");
if personal {
println!("[PINNED, personal] {}", title);
} else {
println!("[PINNED] {}", title);
}
for line in body.lines().take(3) {
println!(" {}", line);
}
if body.lines().count() > 3 {
println!(" ...");
}
} else {
if !printed_divider {
println!("\n--- topic matches ---");
printed_divider = true;
}
let value = r.get("value").and_then(|x| x.as_str()).unwrap_or("");
println!("{}", value);
if personal {
println!(" ({}, personal)", path);
} else {
println!(" ({})", path);
}
}
}
let pinned_count = v.get("pinned_count").and_then(|x| x.as_u64()).unwrap_or(0);
let topic_matches = v.get("topic_matches").and_then(|x| x.as_u64()).unwrap_or(0);
let sent = v
.get("ctx_tokens_sent")
.and_then(|x| x.as_u64())
.unwrap_or(0);
println!(
"\n{} pinned + {} topic matches, {} tokens injected",
pinned_count, topic_matches, sent
);
if let (Some(exact_sent), Some(exact_flat)) = (
v.get("ctx_tokens_sent_exact").and_then(|x| x.as_u64()),
v.get("ctx_tokens_estimated_flat_exact")
.and_then(|x| x.as_u64()),
) {
println!(
" exact (cl100k_base): {} injected, {} full-graph",
exact_sent, exact_flat
);
}
});
}
Commands::Context { project } => {
let url = format!(
"{}/api/memory/context/{}?ref={}",
cli.server,
urlencoding(&project),
encode_ref(&cli.branch),
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "context failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
if let Some(ctx) = v.get("context") {
println!("{}", serde_json::to_string_pretty(ctx).unwrap_or_default());
} else {
println!("No context found for '{}'", project);
}
});
}
Commands::Status => {
let health_url = format!("{}/api/health", cli.server);
let reachable = client
.get(&health_url)
.send()
.await
.map(|r| r.status().is_success())
.unwrap_or(false);
if !reachable {
emit(
cli.format,
&serde_json::json!({
"connected": false,
"server": cli.server,
}),
|_| println!("Hub: unreachable ({})", cli.server),
);
std::process::exit(EX_UNAVAILABLE);
}
let mut out = serde_json::json!({
"connected": true,
"server": cli.server,
"namespace": namespace.as_deref().unwrap_or("default"),
});
if let Some(f) = &status_detect_failure {
out["namespace"] = Value::Null;
out["namespace_error"] = serde_json::json!(f.detail);
}
let cwd = std::env::current_dir()
.map(|d| d.to_string_lossy().into_owned())
.unwrap_or_default();
if let Some(ns) = &namespace
&& let Ok(query) = detect::query_for(&cwd).await
&& let Ok(r) = client
.get(format!("{}/api/projects/detect", cli.server))
.query(&query)
.send()
.await
&& let Ok(det) = r.json::<Value>().await
&& det["status"] == "found"
&& det["namespace"].as_str() == Some(ns.as_str())
{
out["project"] = det["project_id"].clone();
out["project_via"] = det["via"].clone();
}
if let Ok(r) = client
.get(format!("{}/api/stats/tokens", cli.server))
.send()
.await
&& let Ok(parsed) = r.json::<Value>().await
{
out["tokens"] = parsed;
}
emit(cli.format, &out, |v| {
println!("Hub: connected ({})", cli.server);
match v.get("project").and_then(|p| p.as_str()) {
Some(p) => println!(
"Project: {} (namespace: {}, via {})",
p,
v["namespace"].as_str().unwrap_or("default"),
v["project_via"].as_str().unwrap_or("?"),
),
None => match &status_detect_failure {
Some(f) => {
println!("Namespace: unknown — {}", f.detail);
println!(
" Commands here will stop until detection works. Pass \
--namespace <workspace> (or set CTX_NAMESPACE) to choose one."
);
}
None => println!(
"Namespace: {}",
v["namespace"].as_str().unwrap_or("default")
),
},
}
if let Some(t) = v.get("tokens") {
let used = t
.get("session_tokens_used")
.and_then(|x| x.as_u64())
.unwrap_or(0);
let saved = t
.get("session_tokens_saved")
.and_then(|x| x.as_u64())
.unwrap_or(0);
let ratio = t
.get("cumulative_ratio")
.and_then(|x| x.as_f64())
.unwrap_or(0.0);
println!(
"Session: {} tokens used, {} saved ({:.1}x)",
used, saved, ratio
);
}
});
if let Some(f) = &status_detect_failure {
std::process::exit(f.exit_code());
}
}
Commands::Stats => {
let resp = match client
.get(format!("{}/api/stats/tokens", cli.server))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "stats failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let used = v
.get("session_tokens_used")
.and_then(|x| x.as_u64())
.unwrap_or(0);
let saved = v
.get("session_tokens_saved")
.and_then(|x| x.as_u64())
.unwrap_or(0);
let graph_tokens = v
.get("total_graph_size_tokens")
.and_then(|x| x.as_u64())
.unwrap_or(0);
let ratio = v
.get("cumulative_ratio")
.and_then(|x| x.as_f64())
.unwrap_or(0.0);
println!("CtxOne Token Savings");
println!(" graph size: {} tokens", graph_tokens);
println!(" tokens sent: {}", used);
println!(" tokens saved: {}", saved);
println!(" savings: {:.1}x", ratio);
});
}
Commands::Serve {
port,
storage,
path,
http,
lens,
} => {
let db_path = path.unwrap_or_else(canonical_db_path);
if let Some(parent) = std::path::Path::new(&db_path).parent() {
std::fs::create_dir_all(parent).ok();
}
let hub_bin = find_hub_binary();
let mut args = vec![];
if http {
args.push("--http".to_string());
}
if lens {
args.push("--lens".to_string());
}
args.extend(["--port".to_string(), port.to_string()]);
args.extend(["--storage".to_string(), storage]);
args.extend(["--path".to_string(), db_path.clone()]);
println!("Starting CtxOne Hub on port {} (db: {})", port, db_path);
let status = std::process::Command::new(&hub_bin).args(&args).status()?;
std::process::exit(status.code().unwrap_or(1));
}
Commands::Demo => {
run_demo(&cli.server, client.clone()).await?;
}
Commands::Session { action } => {
run_session_action(action, &cli.server, &cli.branch, client_factory).await?;
}
Commands::IngestSession {
file,
source,
all,
since,
scan_dir,
last,
tokens_only,
dry_run,
full_turn,
no_full_turn,
no_auto_register,
dir_workspaces,
reingest,
} => {
let full_turn_effective = full_turn || !no_full_turn;
let mut cfg = CtxConfig::load();
let mut cfg_dirty = false;
let effective_since: Option<String> = match since {
Some(ref s) if s.trim().is_empty() => {
if cfg.import_since.take().is_some() {
cfg_dirty = true;
}
None
}
Some(s) => {
if cfg.import_since.as_deref() != Some(s.as_str()) {
cfg.import_since = Some(s.clone());
cfg_dirty = true;
}
Some(s)
}
None => cfg.import_since.clone(),
};
let effective_scan_dirs: Vec<String> = if scan_dir.is_empty() {
cfg.scan_dirs.clone()
} else {
let mut merged = cfg.scan_dirs.clone();
for d in scan_dir {
if !merged.contains(&d) {
merged.push(d);
}
}
if merged != cfg.scan_dirs {
cfg.scan_dirs = merged.clone();
cfg_dirty = true;
}
merged
};
if cfg_dirty {
let _ = cfg.save();
}
let effective_since = if file.is_some() {
None
} else {
effective_since
};
if let Some(s) = &effective_since {
eprintln!("Importing sessions last active on/after {s} (remembered in config).");
}
run_ingest_session(
&cli.server,
&cli.branch,
cli.session.as_deref(),
file,
&source,
all,
effective_since,
effective_scan_dirs,
last,
tokens_only,
dry_run,
full_turn_effective,
client_factory,
all && !no_auto_register,
if all { None } else { namespace.clone() },
reingest,
dir_workspaces,
None,
None,
)
.await?;
}
Commands::CaptureTurn {
transcript,
session,
turns,
tokens_only,
no_full_turn,
} => {
let sid = session
.or(cli.session.clone())
.or_else(|| std::env::var("CTX_SESSION").ok());
run_capture_turn(
&cli.server,
&cli.branch,
sid.as_deref(),
transcript,
turns,
tokens_only,
!no_full_turn,
client.clone(),
)
.await?;
}
Commands::Pinned => {
let resp = match client
.get(format!("{}/api/memory/pinned", cli.server))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "pinned failed").await;
}
let items: Vec<Value> = resp.json().await?;
use std::collections::BTreeMap;
type Section = (Option<String>, Option<String>);
let mut grouped: BTreeMap<String, BTreeMap<String, Section>> = BTreeMap::new();
for item in &items {
let path = item.get("path").and_then(|v| v.as_str()).unwrap_or("");
let value = item.get("value");
let parts: Vec<&str> = path.split('/').collect();
if parts.len() < 6 {
continue;
}
let source = parts[3].to_string();
let slug = parts[4].to_string();
let field = parts[5];
let text = value.and_then(|v| v.as_str()).unwrap_or("").to_string();
let section_entry = grouped
.entry(source)
.or_default()
.entry(slug)
.or_insert((None, None));
match field {
"title" => section_entry.0 = Some(text),
"body" => section_entry.1 = Some(text),
_ => {}
}
}
let mut json_sources: Vec<Value> = Vec::new();
for (source, sections) in &grouped {
let mut json_sections: Vec<Value> = Vec::new();
for (slug, (title, body)) in sections {
if let (Some(t), Some(b)) = (title, body) {
json_sections.push(serde_json::json!({
"slug": slug,
"title": t,
"body": b,
}));
}
}
json_sources.push(serde_json::json!({
"source": source,
"sections": json_sections,
}));
}
let total_sections: usize = json_sources
.iter()
.filter_map(|s| s.get("sections").and_then(|x| x.as_array()))
.map(|a| a.len())
.sum();
let out = serde_json::json!({
"total_sections": total_sections,
"sources": json_sources,
});
emit(cli.format, &out, |_| {
if grouped.is_empty() {
println!("No pinned memories.");
println!("Add some with: ctx prime <file.md> --pin");
return;
}
for (source, sections) in &grouped {
println!("[{}]", source);
for (title, body) in sections.values() {
if let (Some(t), Some(b)) = (title, body) {
println!(" {}", t);
for line in b.lines().take(2) {
println!(" {}", line);
}
if b.lines().count() > 2 {
println!(" ...");
}
}
}
println!();
}
println!(
"{} pinned sections across {} sources",
total_sections,
grouped.len()
);
});
}
Commands::Prime { file, pin, source } => {
let (content, display_name) = if file == "-" {
use std::io::Read;
let mut buf = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut buf) {
eprintln!("Failed to read stdin: {}", e);
std::process::exit(EX_IOERR);
}
(buf, "<stdin>".to_string())
} else {
match std::fs::read_to_string(&file) {
Ok(c) => (c, file.clone()),
Err(e) => {
eprintln!("Cannot read {}: {}", file, e);
std::process::exit(EX_NOINPUT);
}
}
};
let sections = parse_markdown_sections(&content);
if sections.is_empty() {
eprintln!(
"No sections found in {}. Add H1 or H2 headings to structure the content.",
display_name
);
std::process::exit(EX_DATAERR);
}
let source_name = source.unwrap_or_else(|| {
if file == "-" {
"stdin".to_string()
} else {
std::path::Path::new(&file)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("default")
.to_string()
}
});
let body = serde_json::json!({
"source": source_name,
"pinned": pin,
"sections": sections,
"ref": cli.branch,
});
let resp = match client
.clone()
.post(format!("{}/api/memory/prime", cli.server))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "prime failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let count = v
.get("sections_written")
.and_then(|x| x.as_u64())
.unwrap_or(0);
let kind = if pin { "pinned" } else { "primed" };
println!(
"{} {} sections from {} under source '{}'",
kind, count, display_name, source_name
);
if pin {
println!("These facts will be included in every recall response.");
}
});
}
Commands::Completion { shell } => {
let mut cmd = RawCli::command();
let name = cmd.get_name().to_string();
generate(shell, &mut cmd, name, &mut std::io::stdout());
}
Commands::Doctor => {
run_doctor(&cli).await?;
}
Commands::Diff { ref_a, ref_b } => {
let url = format!(
"{}/api/diff?ref_a={}&ref_b={}",
cli.server,
urlencoding(&ref_a),
urlencoding(&ref_b),
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "diff failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let empty_vec = vec![];
let ops = v
.get("ops")
.and_then(|x| x.as_array())
.unwrap_or(&empty_vec);
if ops.is_empty() {
println!("No differences between {} and {}", ref_a, ref_b);
return;
}
for op in ops {
let tag = op.get("op").and_then(|x| x.as_str()).unwrap_or("?");
let path = op.get("path").and_then(|x| x.as_str()).unwrap_or("");
let key = op.get("key").and_then(|x| x.as_str()).unwrap_or("");
let marker = match tag {
"SetValue" => "~",
"AddKey" | "AppendItem" => "+",
"RemoveKey" | "RemoveItem" => "-",
_ => "?",
};
if key.is_empty() {
println!("{} {:12} {}", marker, tag, path);
} else {
println!("{} {:12} {}/{}", marker, tag, path, key);
}
}
println!(
"\n{} change{}",
ops.len(),
if ops.len() == 1 { "" } else { "s" }
);
});
}
Commands::Merge {
source,
into,
message,
dry_run,
allow_deletions,
allow_regressions,
} => {
let mut body = serde_json::json!({
"source": source,
"target": into,
"dry_run": dry_run,
"allow_deletions": allow_deletions,
"allow_regressions": allow_regressions,
});
if let Some(m) = message {
body["description"] = serde_json::json!(m);
}
let resp = match client
.clone()
.post(format!("{}/api/merge", cli.server))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if resp.status() == reqwest::StatusCode::CONFLICT {
let text = resp.text().await?;
if let Ok(parsed) = serde_json::from_str::<Value>(&text) {
let status = parsed.get("status").and_then(|x| x.as_str());
emit(cli.format, &parsed, |v| {
if status == Some("would_delete") {
let empty_vec = vec![];
let removed = v
.get("removed")
.and_then(|x| x.as_array())
.unwrap_or(&empty_vec);
let names: Vec<&str> =
removed.iter().filter_map(|x| x.as_str()).collect();
eprintln!(
"Refusing merge: would remove {} — {}",
names.join(", "),
"re-run with --allow-deletions to proceed"
);
} else if status == Some("regression") {
let empty_vec = vec![];
let regs = v
.get("regressions")
.and_then(|x| x.as_array())
.unwrap_or(&empty_vec);
eprintln!(
"Refusing merge: would regress {} completed task{}:",
regs.len(),
if regs.len() == 1 { "" } else { "s" }
);
for r in regs {
let plan = r.get("plan").and_then(|x| x.as_str()).unwrap_or("?");
let task = r.get("task").and_then(|x| x.as_str()).unwrap_or("?");
let from = r
.get("target_status")
.and_then(|x| x.as_str())
.unwrap_or("?");
let to = r
.get("source_status")
.and_then(|x| x.as_str())
.unwrap_or("?");
eprintln!(" {plan}/{task}: {from} → {to}");
}
} else {
let empty_vec = vec![];
let conflicts = v
.get("conflicts")
.and_then(|x| x.as_array())
.unwrap_or(&empty_vec);
eprintln!(
"Merge conflict: {} conflict{}",
conflicts.len(),
if conflicts.len() == 1 { "" } else { "s" }
);
for c in conflicts {
eprintln!(
" {}",
serde_json::to_string_pretty(c).unwrap_or_default()
);
}
}
});
} else {
eprintln!("Merge conflict: {}", text);
}
std::process::exit(EX_DATAERR);
}
if !resp.status().is_success() {
http_error_exit(resp, "merge failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
if v.get("status").and_then(|x| x.as_str()) == Some("dry_run") {
let fmt = |key: &str| -> String {
v.get(key)
.and_then(|x| x.as_array())
.map(|a| {
a.iter()
.filter_map(|x| x.as_str())
.collect::<Vec<_>>()
.join(", ")
})
.unwrap_or_default()
};
let ff = v
.get("fast_forward")
.and_then(|x| x.as_bool())
.unwrap_or(false);
println!(
"Dry run: merge '{}' into '{}'{}",
source,
into,
if ff { " (fast-forward)" } else { "" }
);
println!(" added: [{}]", fmt("added"));
println!(" changed: [{}]", fmt("changed"));
println!(" removed: [{}]", fmt("removed"));
if v.get("would_delete")
.and_then(|x| x.as_bool())
.unwrap_or(false)
{
println!(" ⚠ would remove entries — merge needs --allow-deletions");
}
if let Some(regs) = v.get("regressions").and_then(|x| x.as_array()) {
if !regs.is_empty() {
println!(
" ⚠ would regress {} completed task(s) — merge needs --allow-regressions",
regs.len()
);
}
}
let conflicts = v.get("conflicts").and_then(|x| x.as_array());
if let Some(c) = conflicts {
if !c.is_empty() {
println!(" conflicts: {}", c.len());
}
}
} else {
let commit = v.get("commit_id").and_then(|x| x.as_str()).unwrap_or("");
println!("Merged '{}' into '{}' at {}", source, into, commit);
}
});
}
Commands::Forget {
path,
reason,
personal,
} => {
let mut body = serde_json::json!({
"path": path.clone(),
"ref": if personal { PERSONAL_REF } else { cli.branch.as_str() },
});
if let Some(r) = reason {
body["reason"] = serde_json::json!(r);
}
let url = format!("{}/api/memory/forget", cli.server);
let resp = match client
.clone()
.post(if personal { in_personal(&url) } else { url })
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "forget failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let id = v.get("commit_id").and_then(|x| x.as_str()).unwrap_or("");
println!("Forgot: {}", path);
println!(" commit: {}", id);
});
}
Commands::WhyDidWe { decision } => {
let url = format!(
"{}/api/memory/why_did_we?decision={}",
cli.server,
urlencoding(&decision),
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "why-did-we failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let traces = v["traces"].as_array().cloned().unwrap_or_default();
if traces.is_empty() {
println!("No traced decisions for '{}'", decision);
return;
}
println!(
"Found {} trace{} for '{}':",
traces.len(),
if traces.len() == 1 { "" } else { "s" },
decision
);
for t in &traces {
let path = t["path"].as_str().unwrap_or("");
let blame = &t["blame"];
println!();
println!(" {}", path);
let by = blame["agent_id"].as_str().unwrap_or("?");
let at = blame["timestamp"].as_str().unwrap_or("?");
let why = blame["intent_description"].as_str().unwrap_or("");
let category = blame["intent_category"].as_str().unwrap_or("");
println!(" {} @ {} [{}]", by, at, category);
if !why.is_empty() {
println!(" {}", why);
}
}
});
}
Commands::SummarizeSession { points, decisions } => {
let session_id = cli.session.clone().ok_or_else(|| {
"no session id (pass --session <id> or set CTX_SESSION)".to_string()
})?;
let body = serde_json::json!({
"session_id": session_id,
"key_points": points,
"decisions": decisions,
});
let url = format!("{}/api/memory/summarize_session", cli.server);
let resp = match client.post(&url).json(&body).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "summarize-session failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let kp = v["key_points"].as_u64().unwrap_or(0);
let de = v["decisions"].as_u64().unwrap_or(0);
println!(
"Captured {} key point{}, {} decision{} for session {}",
kp,
if kp == 1 { "" } else { "s" },
de,
if de == 1 { "" } else { "s" },
session_id
);
});
}
Commands::RecordUsage {
input_tokens,
output_tokens,
cache_read_tokens,
cache_create_tokens,
model,
provider,
} => {
let mut body = serde_json::json!({
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"cache_read_tokens": cache_read_tokens,
"cache_create_tokens": cache_create_tokens,
});
if let Some(m) = model {
body["model"] = serde_json::json!(m);
}
if let Some(p) = provider {
body["provider"] = serde_json::json!(p);
}
let url = format!("{}/api/stats/llm_usage", cli.server);
let resp = match client.post(&url).json(&body).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "record-usage failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let total = v["total_tokens"]
.as_u64()
.or_else(|| v["llm_total_tokens"].as_u64())
.unwrap_or(0);
let session = v["session_id"].as_str().unwrap_or("?");
println!(
"Recorded {} in / {} out (session totals: {} tokens) for session {}",
input_tokens, output_tokens, total, session
);
});
}
Commands::Search { query, max } => {
let url = format!(
"{}/api/state/{}/search?query={}&max_results={}",
cli.server,
encode_ref(&cli.branch),
urlencoding(&query),
max,
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "search failed").await;
}
let results: Vec<Value> = resp.json().await?;
let value = Value::Array(results.clone());
emit(cli.format, &value, |_| {
if results.is_empty() {
println!("No matches for '{}'", query);
} else {
for r in &results {
let path = r.get("path").and_then(|v| v.as_str()).unwrap_or("");
let val = r.get("value").and_then(|v| v.as_str()).unwrap_or("");
println!("{}", path);
println!(" {}", val);
}
println!(
"\n{} match{}",
results.len(),
if results.len() == 1 { "" } else { "es" }
);
}
});
}
Commands::Ls { prefix, max_depth } => {
let url = format!(
"{}/api/state/{}/paths?prefix={}&max_depth={}",
cli.server,
encode_ref(&cli.branch),
urlencoding(&prefix),
max_depth,
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "ls failed").await;
}
let paths: Vec<String> = resp.json().await?;
let value = serde_json::json!(paths);
emit(cli.format, &value, |_| {
if paths.is_empty() {
println!("No paths under {}", prefix);
} else {
for p in &paths {
println!("{}", p);
}
println!("\n{} paths", paths.len());
}
});
}
Commands::Get { path } => {
let url = format!(
"{}/api/state/{}?path={}",
cli.server,
encode_ref(&cli.branch),
urlencoding(&path),
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "get failed").await;
}
let value: Value = resp.json().await?;
emit(cli.format, &value, |v| {
println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());
});
}
Commands::Log { limit } => {
let url = format!(
"{}/api/log/{}?limit={}",
cli.server,
encode_ref(&cli.branch),
limit,
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "log failed").await;
}
let commits: Vec<Value> = resp.json().await?;
let value = Value::Array(commits.clone());
emit(cli.format, &value, |_| print_commits(&commits));
}
Commands::Blame { path } => {
let url = format!(
"{}/api/blame/{}?path={}",
cli.server,
encode_ref(&cli.branch),
urlencoding(&path),
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "blame failed").await;
}
let value: Value = resp.json().await?;
emit(cli.format, &value, |v| {
println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());
});
}
Commands::Tail { interval } => {
run_tail(&cli.server, &cli.branch, interval, client.clone()).await?;
}
Commands::Branches => {
branch_list(&cli.server, cli.format, &cli.branch, &client).await?;
}
Commands::Branch { action } => match action {
BranchAction::List => {
branch_list(&cli.server, cli.format, &cli.branch, &client).await?;
}
BranchAction::Create { name, from } => {
let body = serde_json::json!({ "name": name, "from": from });
let resp = match client
.clone()
.post(format!("{}/api/branches", cli.server))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "branch create failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let commit = v.get("commit_id").and_then(|x| x.as_str()).unwrap_or("");
println!("Branch '{}' created from '{}' at {}", name, from, commit);
});
}
BranchAction::Rm { name } => {
let resp = match client
.delete(format!(
"{}/api/branches/{}",
cli.server,
urlencoding(&name)
))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "branch rm failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
if v.get("deleted").and_then(|d| d.as_bool()).unwrap_or(false) {
println!("Branch '{}' deleted", name);
} else {
println!("Branch '{}' did not exist", name);
}
});
}
BranchAction::Reset { name, to, backup } => {
let body = serde_json::json!({ "name": name, "to": to, "backup": backup });
let resp = match client
.clone()
.post(format!("{}/api/branches/reset", cli.server))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&cli.server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "branch reset failed").await;
}
let parsed: Value = resp.json().await?;
emit(cli.format, &parsed, |v| {
let commit = v.get("commit_id").and_then(|x| x.as_str()).unwrap_or("");
println!("Branch '{}' reset to '{}' at {}", name, to, commit);
if let Some(b) = v.get("backup_ref").and_then(|x| x.as_str()) {
println!(" old target backed up as '{}'", b);
}
});
}
},
Commands::Config { action } => {
handle_config(action, cli.format)?;
}
Commands::Tokens { text } => {
let content = if text == "-" {
use std::io::Read;
let mut buf = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut buf) {
eprintln!("Failed to read stdin: {}", e);
std::process::exit(EX_IOERR);
}
buf
} else {
text
};
let exact = count_tokens_cl100k(&content);
let estimate = content.len() / 4;
let out = serde_json::json!({
"chars": content.len(),
"tokens_exact": exact,
"tokens_estimate_4char": estimate,
"tokenizer": "cl100k_base",
});
emit(cli.format, &out, |_| {
println!("{} chars", content.len());
println!("{} tokens (cl100k_base, exact)", exact);
println!("{} tokens (4-char estimate)", estimate);
});
}
Commands::Init {
global,
project: _,
tool,
config_path,
dry_run,
no_agents,
no_mcp,
transport,
mcp_url,
auth_token,
auth_token_env,
} => {
let server = cli.server.clone();
let branch = cli.branch.clone();
let format = cli.format;
if !dry_run && crate::device::device_id().is_none() {
eprintln!(
" \u{26A0} couldn't keep a device id in {}",
crate::device::path()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "~/.ctxone/device_id".to_string())
);
}
if no_mcp {
println!("MCP config step skipped (--no-mcp).");
} else {
if transport == McpTransport::Http
&& !dry_run
&& let Some(health) = hub_health_url(&mcp_url)
{
let reachable = client
.get(&health)
.timeout(std::time::Duration::from_millis(1500))
.send()
.await
.map(|r| r.status().is_success())
.unwrap_or(false);
if !reachable {
eprintln!(
" \u{26A0} hub not reachable at {health} — the configs below will \
point at a hub that isn't running yet. Start it with \
`ctxone-hub --http --lens` or `ctx service install`."
);
}
}
init_mcp(
global,
tool,
config_path,
dry_run,
transport,
&mcp_url,
namespace.clone(),
auth_token.as_deref(),
auth_token_env.as_deref(),
cli.session.as_deref(),
)?;
}
if !dry_run && !no_agents {
println!();
if let Err(e) =
agents_install_after_init(&server, &branch, format, client.clone()).await
{
eprintln!(" \u{2717} agents: {}", e);
}
}
if no_mcp && no_agents {
println!("Nothing to do: both --no-mcp and --no-agents were passed.");
}
if !dry_run {
match publish_help_index(&server, &client).await {
Ok(path) => println!(" \u{2713} help index: {}", path.display()),
Err(e) => eprintln!(" \u{26A0} help index skipped: {}", e),
}
}
}
Commands::Agents { action } => {
let server = cli.server.clone();
let branch = cli.branch.clone();
let format = cli.format;
handle_agents(action, &server, &branch, format, client.clone()).await?;
}
Commands::Secrets { action } => match action {
SecretsAction::Scan { turns, all } => {
let only = cli.branch_explicit.then(|| cli.branch.clone());
let scan = SecretsScan {
workspace: namespace.as_deref().unwrap_or("default"),
branch: &cli.branch,
only: only.as_deref(),
turns,
all,
};
secrets_scan(&cli.server, &client, cli.format, &scan).await?;
}
},
Commands::Worktree { action } => {
worktree::run(action)?;
}
Commands::Plan { action } => {
let server = cli.server.clone();
let branch = cli.branch.clone();
let format = cli.format;
handle_plan(action, &server, &branch, format, client.clone()).await?;
}
Commands::Analyze { action } => {
let server = cli.server.clone();
let format = cli.format;
handle_analyze(action, &server, format, client.clone()).await?;
}
Commands::Taint { action } => {
let server = cli.server.clone();
let branch = cli.branch.clone();
let format = cli.format;
handle_taint(action, &server, &branch, format, client.clone()).await?;
}
Commands::Db { action } => {
let server = cli.server.clone();
let branch = cli.branch.clone();
let format = cli.format;
handle_db(action, &server, &branch, format, client.clone()).await?;
}
Commands::Docs { action } => {
let server = cli.server.clone();
let branch = cli.branch.clone();
let format = cli.format;
handle_docs(action, &server, &branch, format, client.clone()).await?;
}
Commands::Project { action } => {
let server = cli.server.clone();
let format = cli.format;
handle_project(action, &server, format, client.clone()).await?;
}
Commands::Workspace { action } => {
handle_workspace(action, &cli.server, cli.format, client.clone()).await?;
}
Commands::Service { action } => {
handle_service(action)?;
}
Commands::Remote { action } => {
sync_cmd::remote(action, &cli.server, &client, cli.format).await?;
}
Commands::Push { allow } => {
let clean = sync_cmd::run(
&cli.server,
&client,
cli.format,
"push",
namespace.as_deref(),
&allow,
)
.await?;
if !clean {
std::process::exit(1);
}
}
Commands::Pull => {
let clean = sync_cmd::run(
&cli.server,
&client,
cli.format,
"pull",
namespace.as_deref(),
&[],
)
.await?;
if !clean {
std::process::exit(1);
}
}
Commands::Sync { action, allow } => match action {
Some(sync_cmd::SyncAction::Status) => {
sync_cmd::status(&cli.server, &client, cli.format).await?;
}
None => {
let clean = sync_cmd::run(
&cli.server,
&client,
cli.format,
"both",
namespace.as_deref(),
&allow,
)
.await?;
if !clean {
std::process::exit(1);
}
}
},
Commands::Reminder { action } => {
let server = cli.server.clone();
let format = cli.format;
handle_reminder(action, &server, format, client.clone()).await?;
}
Commands::Move {
path,
to_namespace,
from_namespace,
to_branch,
no_delete,
dry_run,
} => {
let server = cli.server.clone();
let branch = cli.branch.clone();
let format = cli.format;
let agent_id = std::env::var("CTX_AGENT_ID").unwrap_or_else(|_| "ctx-cli".to_string());
let mut body = serde_json::json!({
"path": path,
"to_namespace": to_namespace,
"ref": branch,
"delete_source": !no_delete,
"dry_run": dry_run,
});
if let Some(fns) = &from_namespace {
body["from_namespace"] = serde_json::json!(fns);
}
if let Some(tb) = &to_branch {
body["to_ref"] = serde_json::json!(tb);
}
let resp = match client
.post(format!("{}/api/move", server))
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(&server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "move failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
if v["status"] == "dry_run" {
println!(
"dry run: {} leaf(s) at {} would move → {} ({})",
v["src_leaves"],
v["path"].as_str().unwrap_or(&path),
v["to"].as_str().unwrap_or(&to_namespace),
if v["would_delete_source"].as_bool().unwrap_or(false) {
"source deleted"
} else {
"copy"
},
);
} else {
println!(
"Moved {} ({} leaves) → {}{}",
v["path"].as_str().unwrap_or(&path),
v["dst_leaves"],
v["to"].as_str().unwrap_or(&to_namespace),
if v["deleted_source"].as_bool().unwrap_or(false) {
""
} else {
" (copy; source kept)"
},
);
}
});
}
}
Ok(())
}
async fn handle_reminder(
action: ReminderAction,
server: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
use serde_json::json;
match action {
ReminderAction::Approve { id } => {
let resp = match client
.post(format!(
"{server}/api/reminders/{}/approve",
urlencoding(&id)
))
.json(&json!({}))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "reminder approve failed").await;
}
let r: Value = resp.json().await?;
emit(format, &r, |r| {
println!(
"approved {} ({}): {}",
r["title"].as_str().unwrap_or("?"),
r["status"].as_str().unwrap_or("?"),
if trusted_here(r) {
"it may run its commands on this machine"
} else {
"the Hub didn't confirm it may run here; is it older than this ctx?"
}
);
});
}
ReminderAction::Tick {
allowlist,
skip,
defer_hours,
dry_run,
} => {
let allow = load_tick_allowlist(&allowlist);
let skip: std::collections::HashSet<String> = skip.into_iter().collect();
let resp = match client
.get(format!("{server}/api/reminders/due"))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "reminder tick: fetch due failed").await;
}
let due: Value = resp.json().await?;
let due = due.as_array().cloned().unwrap_or_default();
let (mut acted, mut deferred, mut skipped, mut needs_approval, mut no_cmds) =
(0u32, 0u32, 0u32, 0u32, 0u32);
let mut not_here = 0u32;
let mut results: Vec<Value> = Vec::new();
for r in &due {
let id = r["id"].as_str().unwrap_or("").to_string();
let title = r["title"].as_str().unwrap_or("?").to_string();
let status = r["status"].as_str().unwrap_or("");
let autonomous = r["autonomous"].as_bool().unwrap_or(false);
if !autonomous || status == "awaiting_permission" {
needs_approval += 1;
continue;
}
if !trusted_here(r) {
not_here += 1;
results.push(json!({
"reminder": title,
"action": "not-trusted-here",
"detail": format!(
"made on another machine; to let it run here: ctx reminder approve {id}"
),
}));
continue;
}
if id.is_empty() || skip.contains(&id) {
skipped += 1;
continue;
}
let cmds: Vec<String> = r["commands"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|c| c.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty() && !s.starts_with('#'))
.collect()
})
.unwrap_or_default();
if cmds.is_empty() {
no_cmds += 1;
continue;
}
let disallowed: Vec<String> = cmds
.iter()
.filter(|c| !allow.contains(*c))
.cloned()
.collect();
if !disallowed.is_empty() {
deferred += 1;
let note = format!(
"not in allowlist — needs approval: {}",
disallowed.join(" ; ")
);
results.push(json!({"reminder": title, "action": "deferred", "detail": note}));
if !dry_run {
let _ = reminder_record(&client, server, &id, "deferred", vec![note]).await;
let until = (chrono::Utc::now() + chrono::Duration::hours(defer_hours))
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let _ = client
.post(format!("{server}/api/reminders/{id}/snooze"))
.json(&json!({"id": id, "until": until}))
.send()
.await;
}
continue;
}
if dry_run {
acted += 1;
results
.push(json!({"reminder": title, "action": "would-run", "commands": cmds}));
continue;
}
let _ = client
.post(format!("{server}/api/reminders/{id}/start"))
.json(&json!({}))
.send()
.await;
let mut ok = true;
let mut outs: Vec<String> = Vec::new();
for c in &cmds {
match std::process::Command::new("bash")
.arg("-lc")
.arg(c)
.output()
{
Ok(out) => {
let code = out.status.code().unwrap_or(-1);
let mut combined = String::from_utf8_lossy(&out.stdout).into_owned();
combined.push_str(&String::from_utf8_lossy(&out.stderr));
let last: String = combined
.lines()
.last()
.unwrap_or("")
.chars()
.take(120)
.collect();
outs.push(format!("$ {c} -> exit {code}: {last}"));
if !out.status.success() {
ok = false;
}
}
Err(e) => {
outs.push(format!("$ {c} -> spawn error: {e}"));
ok = false;
}
}
}
let result = if ok { "success" } else { "failed" };
let _ = reminder_record(&client, server, &id, result, outs.clone()).await;
acted += 1;
results.push(json!({"reminder": title, "action": result, "output": outs}));
}
let summary = json!({
"due": due.len(),
"acted": acted,
"deferred": deferred,
"skipped": skipped,
"needs_approval": needs_approval,
"not_trusted_here": not_here,
"no_commands": no_cmds,
"dry_run": dry_run,
"results": results,
});
emit(format, &summary, |_| {
println!(
"reminder tick: due={} acted={} deferred={} skipped={} awaiting_approval={} not_trusted_here={} no_commands={}{}",
due.len(),
acted,
deferred,
skipped,
needs_approval,
not_here,
no_cmds,
if dry_run { " (dry-run)" } else { "" }
);
for r in &results {
println!(
" {} — {}",
r["reminder"].as_str().unwrap_or("?"),
r["action"].as_str().unwrap_or("?")
);
}
});
}
}
Ok(())
}
fn trusted_here(reminder: &Value) -> bool {
reminder["trusted_here"].as_bool().unwrap_or(false)
}
async fn reminder_record(
client: &reqwest::Client,
server: &str,
id: &str,
result: &str,
notes: Vec<String>,
) -> Result<(), reqwest::Error> {
client
.post(format!("{server}/api/reminders/{id}/record"))
.json(&serde_json::json!({"id": id, "result": result, "notes": notes}))
.send()
.await
.map(|_| ())
}
fn load_tick_allowlist(path: &str) -> std::collections::HashSet<String> {
let expanded = match path.strip_prefix("~/") {
Some(rest) => std::env::var_os("HOME")
.map(|h| std::path::PathBuf::from(h).join(rest))
.unwrap_or_else(|| std::path::PathBuf::from(path)),
None => std::path::PathBuf::from(path),
};
std::fs::read_to_string(&expanded)
.map(|s| {
s.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|l| l.to_string())
.collect()
})
.unwrap_or_default()
}
fn handle_service(action: ServiceAction) -> Result<(), Box<dyn std::error::Error>> {
match action {
ServiceAction::Install {
port,
path,
no_lens,
auth_token,
dry_run,
force,
} => {
let spec = service::ServiceSpec {
hub_bin: find_hub_binary(),
ctx_bin: current_ctx_bin(),
db_path: path.unwrap_or_else(canonical_db_path),
port,
lens: !no_lens,
auth_token,
log_path: service::default_log_path(),
};
service::install(&spec, dry_run, force)
}
ServiceAction::Uninstall { dry_run } => service::uninstall(dry_run),
ServiceAction::Status => service::status(),
ServiceAction::Tick { action } => match action {
TickAction::Install {
interval,
allowlist,
skip,
dry_run,
force,
} => {
let spec = service::TickSpec {
ctx_bin: current_ctx_bin(),
interval_secs: interval,
allowlist: Some(allowlist),
skip,
server: None,
log_path: service::tick_log_path(),
};
service::tick_install(&spec, dry_run, force)
}
TickAction::Uninstall { dry_run } => service::tick_uninstall(dry_run),
TickAction::Status => service::tick_status(),
},
}
}
fn current_ctx_bin() -> String {
std::env::current_exe()
.ok()
.and_then(|p| p.to_str().map(str::to_string))
.unwrap_or_else(|| "ctx".to_string())
}
fn find_git_root(start: &std::path::Path) -> Option<PathBuf> {
let output = std::process::Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.current_dir(start)
.output()
.ok()?;
if !output.status.success() {
return None;
}
let raw = String::from_utf8_lossy(&output.stdout);
let path = raw.trim();
(!path.is_empty()).then(|| PathBuf::from(path))
}
fn read_git_branch(dir: &std::path::Path) -> Option<String> {
let output = std::process::Command::new("git")
.args(["symbolic-ref", "--short", "HEAD"])
.current_dir(dir)
.output()
.ok()?;
if !output.status.success() {
return None;
}
let raw = String::from_utf8_lossy(&output.stdout);
let branch = raw.trim().to_string();
(!branch.is_empty()).then_some(branch)
}
fn sanitize_branch_name(raw: &str) -> String {
let stripped = raw.strip_prefix("refs/heads/").unwrap_or(raw);
let replaced: String = stripped
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
c
} else {
'-'
}
})
.collect();
let mut out = String::with_capacity(replaced.len());
let mut last_was_dash = false;
for c in replaced.chars() {
if c == '-' {
if !last_was_dash {
out.push(c);
}
last_was_dash = true;
} else {
out.push(c);
last_was_dash = false;
}
}
let trimmed = out.trim_matches('-');
if trimmed.is_empty() {
"work".to_string()
} else {
trimmed.to_string()
}
}
fn read_git_remote(dir: &std::path::Path) -> Option<String> {
let output = std::process::Command::new("git")
.args(["remote", "get-url", "origin"])
.current_dir(dir)
.output()
.ok()?;
if !output.status.success() {
return None;
}
let raw = String::from_utf8_lossy(&output.stdout);
let url = raw.trim().to_string();
(!url.is_empty()).then_some(url)
}
fn write_ctxproject(root: &std::path::Path, id: &str) -> std::io::Result<PathBuf> {
let path = root.join(".ctxproject");
std::fs::write(&path, format!("{}\n", id))?;
Ok(path)
}
async fn handle_workspace(
action: WorkspaceAction,
server: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
match action {
WorkspaceAction::List { json } => {
let url = format!("{server}/api/namespaces");
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "workspace list failed").await;
}
let parsed: Value = resp.json().await?;
let fmt = if json { OutputFormat::Json } else { format };
emit(fmt, &parsed, |v| {
let empty = vec![];
let ns = v["namespaces"].as_array().unwrap_or(&empty);
if ns.is_empty() {
println!("No workspaces.");
return;
}
println!("{:<28} {}", "WORKSPACE", "SESSIONS");
for n in ns {
println!(
"{:<28} {}",
n["namespace"].as_str().unwrap_or("?"),
n["sessions"].as_u64().unwrap_or(0),
);
}
});
}
}
Ok(())
}
async fn handle_project(
action: ProjectAction,
server: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
match action {
ProjectAction::Add {
id,
display_name,
path,
no_marker,
} => {
let cwd = std::env::current_dir()?;
let root = path
.map(PathBuf::from)
.or_else(|| find_git_root(&cwd))
.unwrap_or(cwd);
let mut body = serde_json::json!({
"id": id,
"local_path": root.to_string_lossy(),
});
if let Some(d) = display_name {
body["display_name"] = serde_json::json!(d);
}
if let Some(remote) = read_git_remote(&root) {
body["remote_url"] = serde_json::json!(remote);
}
let resp = match client
.post(format!("{}/api/projects", server))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "project add failed").await;
}
let mut parsed: Value = resp.json().await?;
if !no_marker {
let marker = write_ctxproject(&root, &id)?;
parsed["marker"] = serde_json::json!(marker.to_string_lossy());
}
emit(format, &parsed, |v| {
println!(
"Registered project {} (namespace: {})",
v["id"].as_str().unwrap_or("?"),
v["namespace"].as_str().unwrap_or("?"),
);
println!(" path: {}", root.display());
if let Some(m) = v.get("marker").and_then(|m| m.as_str()) {
println!(" marker: {} (commit this so agents auto-detect)", m);
}
});
}
ProjectAction::List => {
let resp = match client.get(format!("{}/api/projects", server)).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "project list failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let items = v.as_array().cloned().unwrap_or_default();
if items.is_empty() {
println!("No projects registered. Run `ctx project add <id>` in a repo.");
return;
}
for p in items {
println!(
"{:<24} ns:{:<24} {}",
p["id"].as_str().unwrap_or("?"),
p["namespace"].as_str().unwrap_or("?"),
p["remote_url"].as_str().unwrap_or("-"),
);
}
});
}
ProjectAction::Use { id, no_marker } => {
let resp = match client
.get(format!("{}/api/projects/{}", server, id))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "project use failed").await;
}
let cwd = std::env::current_dir()?;
let root = find_git_root(&cwd).unwrap_or(cwd);
let _ = client
.post(format!("{}/api/projects/{}/paths", server, id))
.json(&serde_json::json!({ "local_path": root.to_string_lossy() }))
.send()
.await;
let mut parsed: Value = resp.json().await?;
if !no_marker {
let marker = write_ctxproject(&root, &id)?;
parsed["marker"] = serde_json::json!(marker.to_string_lossy());
}
emit(format, &parsed, |v| {
println!(
"This checkout now uses project {} (namespace: {})",
v["id"].as_str().unwrap_or("?"),
v["namespace"].as_str().unwrap_or("?"),
);
});
}
ProjectAction::Detect => {
let cwd = std::env::current_dir()?.to_string_lossy().into_owned();
let query = match detect::query_for(&cwd).await {
Ok(q) => q,
Err(f) => f.exit(),
};
let resp = match client
.get(format!("{}/api/projects/detect", server))
.query(&query)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "project detect failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| match v["status"].as_str() {
Some("found") => println!(
"Project {} (namespace: {}, via {})",
v["project_id"].as_str().unwrap_or("?"),
v["namespace"].as_str().unwrap_or("?"),
v["via"].as_str().unwrap_or("?"),
),
_ => println!(
"No project here — operating in the 'default' namespace. \
Run `ctx project add <id>` to give this repo its own."
),
});
}
}
Ok(())
}
struct SecretsScan<'a> {
workspace: &'a str,
branch: &'a str,
only: Option<&'a str>,
turns: bool,
all: bool,
}
async fn secrets_scan(
server: &str,
client: &reqwest::Client,
format: OutputFormat,
scan: &SecretsScan<'_>,
) -> Result<(), Box<dyn std::error::Error>> {
let mut url = format!(
"{server}/api/secrets/scan?turns={}&all={}",
scan.turns, scan.all
);
if let Some(branch) = scan.only {
url.push_str(&format!("&ref={}", urlencoding(branch)));
}
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "secrets scan failed").await;
}
let parsed: Value = resp.json().await?;
let found = parsed["findings"].as_array().is_some_and(|f| !f.is_empty());
emit(format, &parsed, |v| print_secrets_report(v, scan));
if found {
std::process::exit(1);
}
Ok(())
}
fn print_secrets_report(v: &Value, scan: &SecretsScan<'_>) {
let empty = Vec::new();
let scanned = v["scanned"].as_array().unwrap_or(&empty);
let findings = v["findings"].as_array().unwrap_or(&empty);
let namespaces: std::collections::BTreeSet<&str> = scanned
.iter()
.filter_map(|s| s["namespace"].as_str())
.collect();
let mut summary = format!(
"Scanned {} in {} ({} strings).",
plural(scanned.len(), "branch", "branches"),
plural(namespaces.len(), "namespace", "namespaces"),
v["strings"].as_u64().unwrap_or(0),
);
if !scan.turns {
summary.push_str(" Raw session turns were skipped; --turns scans them too.");
}
println!("{summary}");
if findings.is_empty() {
println!("No credential-shaped strings found.");
return;
}
let mut groups: Vec<(&Value, Vec<&Value>)> = Vec::new();
for f in findings {
let same = |g: &&mut (&Value, Vec<&Value>)| {
["namespace", "path", "rule", "masked"]
.iter()
.all(|k| g.0[*k] == f[*k])
};
match groups.iter_mut().find(same) {
Some(g) => g.1.push(f),
None => groups.push((f, vec![f])),
}
}
let high = groups
.iter()
.filter(|g| g.0["confidence"] == "high")
.count();
println!(
"Found {} ({high} high confidence, {} medium).",
plural(
groups.len(),
"credential-shaped string",
"credential-shaped strings"
),
groups.len() - high,
);
for (f, on) in &groups {
let ns = f["namespace"].as_str().unwrap_or("?");
let path = f["path"].as_str().unwrap_or("?");
let refs: Vec<&str> = on.iter().filter_map(|g| g["ref"].as_str()).collect();
println!();
println!(
"{:<7} {} {}",
f["confidence"].as_str().unwrap_or("?"),
f["name"].as_str().unwrap_or("?"),
f["masked"].as_str().unwrap_or("?"),
);
println!(" {path} ({ns}: {})", refs.join(", "));
match f["forget"].as_str() {
Some(target) => {
for r in &refs {
println!(" {}", forget_command(ns, r, target, scan));
}
}
None => println!(" not a memory entry or session part: edit it to remove it"),
}
}
println!();
println!(
"Forgetting removes a value from the branch as it is now; earlier commits keep it. \
Sync's first push is shallow, so those commits don't go with it."
);
}
fn plural(n: usize, one: &str, many: &str) -> String {
format!("{n} {}", if n == 1 { one } else { many })
}
fn forget_command(ns: &str, ref_name: &str, path: &str, scan: &SecretsScan<'_>) -> String {
let path = shell_quote(path);
if ns == PERSONAL_NAMESPACE {
return format!("ctx forget --personal {path}");
}
let mut cmd = String::from("ctx");
if ns != scan.workspace {
cmd.push_str(&format!(" --namespace {}", shell_quote(ns)));
}
if ref_name != scan.branch {
cmd.push_str(&format!(" --branch {}", shell_quote(ref_name)));
}
format!("{cmd} forget {path}")
}
fn shell_quote(s: &str) -> String {
if s.chars()
.all(|c| c.is_ascii_alphanumeric() || "/._-:@%+=,".contains(c))
{
s.to_string()
} else {
format!("'{}'", s.replace('\'', r"'\''"))
}
}
async fn handle_agents(
action: AgentsAction,
server: &str,
branch: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
match action {
AgentsAction::Show => agents_show()?,
AgentsAction::Status => agents_status(server, branch, format, client.clone()).await?,
AgentsAction::Remove => agents_remove(server, branch, client.clone()).await?,
AgentsAction::Migrate { apply } => {
agents_migrate(server, apply, format, client.clone()).await?
}
AgentsAction::Install { file, yes, show } => {
agents_install(file, yes, show, server, branch, client.clone()).await?;
}
}
Ok(())
}
fn agents_show() -> Result<(), Box<dyn std::error::Error>> {
let (content, display_source) =
load_agents_md(None).map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
println!("# AGENTS.md source: {}", display_source);
println!();
println!("{}", content);
Ok(())
}
async fn agents_paths(
server: &str,
branch: &str,
client: &reqwest::Client,
url_for: impl Fn(&str) -> String,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let url = url_for(&format!(
"{}/api/state/{}/paths?prefix=/memory/pinned/{}",
server,
encode_ref(branch),
AGENTS_SOURCE
));
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if resp.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(Vec::new());
}
if !resp.status().is_success() {
http_error_exit(resp, "list paths failed").await;
}
Ok(resp.json().await?)
}
fn agents_section_count(paths: &[String]) -> usize {
paths
.iter()
.filter(|p| p.ends_with("/title") || p.ends_with("/body"))
.count()
/ 2
}
async fn agents_forget(
server: &str,
branch: &str,
client: &reqwest::Client,
reason: &str,
url_for: impl Fn(&str) -> String,
) -> bool {
let path = format!("/memory/pinned/{}", AGENTS_SOURCE);
let body = serde_json::json!({
"path": path,
"reason": reason,
"ref": branch,
});
let resp = client
.post(url_for(&format!("{}/api/memory/forget", server)))
.json(&body)
.send()
.await;
match resp {
Ok(r) if r.status().is_success() => true,
Ok(r) => {
eprintln!(" \u{2717} forget {}: HTTP {}", path, r.status());
false
}
Err(e) => unreachable_exit(server, e),
}
}
async fn agents_status(
server: &str,
branch: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let disk_path = agents_md_path();
let disk_status = if disk_path.exists() {
format!("present at {}", disk_path.display())
} else {
"not written (will use embedded default)".to_string()
};
let personal = agents_paths(server, PERSONAL_REF, &client, in_personal).await?;
let section_count = agents_section_count(&personal);
let workspace = agents_paths(server, branch, &client, |u| u.to_string()).await?;
let workspace_count = agents_section_count(&workspace);
emit(
format,
&serde_json::json!({
"disk_path": disk_path.display().to_string(),
"disk_exists": disk_path.exists(),
"primed_sections": section_count,
"namespace": PERSONAL_NAMESPACE,
"ref": PERSONAL_REF,
"workspace_copy_sections": workspace_count,
"workspace_copy_ref": branch,
"source": AGENTS_SOURCE,
}),
|_| {
println!("AGENTS.md status");
println!(" Disk: {}", disk_status);
if section_count > 0 {
println!(
" Primed: {} sections under /memory/pinned/{} in your personal namespace",
section_count, AGENTS_SOURCE
);
println!();
println!(
" Inspect: ctx ls /memory/pinned/{} --namespace {}",
AGENTS_SOURCE, PERSONAL_NAMESPACE
);
} else {
println!(" Primed: NOT primed in your personal namespace");
println!();
println!(" Run `ctx agents install` to prime the guidance.");
}
if workspace_count > 0 {
println!();
println!(
" This workspace still has an older copy ({} sections on {}).",
workspace_count, branch
);
println!(
" `ctx agents migrate` lists every workspace's copy; --apply removes them."
);
}
},
);
Ok(())
}
async fn agents_remove(
server: &str,
branch: &str,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let personal =
agents_section_count(&agents_paths(server, PERSONAL_REF, &client, in_personal).await?);
let workspace =
agents_section_count(&agents_paths(server, branch, &client, |u| u.to_string()).await?);
if personal == 0 && workspace == 0 {
println!("AGENTS.md is not primed. Nothing to remove.");
return Ok(());
}
let reason = "ctx agents remove";
let from_personal =
personal > 0 && agents_forget(server, PERSONAL_REF, &client, reason, in_personal).await;
let from_workspace =
workspace > 0 && agents_forget(server, branch, &client, reason, |u| u.to_string()).await;
let mut removed = Vec::new();
if from_personal {
removed.push(format!("{personal} sections from your personal namespace"));
}
if from_workspace {
removed.push(format!("{workspace} from this workspace's older copy"));
}
println!("Removed AGENTS.md: {}.", removed.join(" and "));
println!(
"The local file at {} is untouched.",
agents_md_path().display()
);
println!("Prior content is still in blame history.");
Ok(())
}
async fn agents_migrate(
server: &str,
apply: bool,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let resp = match client
.get(format!("{}/api/namespaces", server))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "list namespaces failed").await;
}
let listed: Value = resp.json().await?;
let mut copies: Vec<(String, Vec<String>)> = Vec::new();
for ns in listed["namespaces"]
.as_array()
.into_iter()
.flatten()
.filter_map(|n| n.get("namespace").and_then(|v| v.as_str()))
.filter(|ns| *ns != PERSONAL_NAMESPACE)
{
let paths = agents_paths(server, "main", &client, |u| in_namespace(u, ns)).await?;
if agents_section_count(&paths) > 0 {
copies.push((ns.to_string(), paths));
}
}
let mut removed = 0usize;
let mut primed_personal = false;
if apply && !copies.is_empty() {
let personal = agents_paths(server, PERSONAL_REF, &client, in_personal).await?;
if agents_section_count(&personal) == 0 {
let (content, _) =
load_agents_md(None).map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
agents_prime_personal(server, &client, &content).await?;
primed_personal = true;
}
for (ns, _) in &copies {
if agents_forget(server, "main", &client, "ctx agents migrate", |u| {
in_namespace(u, ns)
})
.await
{
removed += 1;
}
}
}
let listing: Vec<Value> = copies
.iter()
.map(|(ns, paths)| {
serde_json::json!({
"namespace": ns,
"sections": agents_section_count(paths),
"paths": paths,
})
})
.collect();
emit(
format,
&serde_json::json!({
"copies": listing,
"applied": apply,
"removed_from": removed,
"primed_personal": primed_personal,
}),
|_| {
if copies.is_empty() {
println!("No workspace holds its own copy of AGENTS.md. Nothing to migrate.");
return;
}
println!("Workspaces with their own copy of AGENTS.md (on main):");
for (ns, paths) in &copies {
println!(" {:<40} {} sections", ns, agents_section_count(paths));
}
println!();
if apply {
if primed_personal {
println!("Primed AGENTS.md into your personal namespace first.");
}
println!(
"Removed {} of {} copies. Every workspace's recall reads the personal one.",
removed,
copies.len()
);
println!("Prior content is still in blame history.");
} else {
println!(
"Recall reads the copy in your personal namespace, so these aren't needed."
);
println!("Run `ctx agents migrate --apply` to remove them.");
}
},
);
Ok(())
}
async fn agents_prime_personal(
server: &str,
client: &reqwest::Client,
content: &str,
) -> Result<u64, Box<dyn std::error::Error>> {
let sections = parse_markdown_sections(content);
if sections.is_empty() {
eprintln!("AGENTS.md has no H1/H2 sections — nothing to prime.");
std::process::exit(EX_DATAERR);
}
let body = serde_json::json!({
"source": AGENTS_SOURCE,
"pinned": true,
"sections": sections,
"ref": PERSONAL_REF,
});
let resp = match client
.post(in_personal(&format!("{}/api/memory/prime", server)))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "prime failed").await;
}
let parsed: Value = resp.json().await?;
Ok(parsed
.get("sections_written")
.and_then(|x| x.as_u64())
.unwrap_or(0))
}
async fn agents_install(
file: Option<String>,
yes: bool,
show: bool,
server: &str,
branch: &str,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let (content, source_desc) =
load_agents_md(file.as_deref()).map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
if show {
println!("# AGENTS.md preview");
println!("# Source: {}", source_desc);
println!("# (use `ctx agents install` without --show to prime it)");
println!();
println!("{}", content);
return Ok(());
}
let disk_path = write_agents_md_if_absent(&content)
.map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
let _ = yes;
println!("CTXone ships a short guidance file that teaches AI tools how");
println!("to use the Hub effectively. It is pinned in your personal");
println!("namespace, so every workspace's recall includes it.");
println!();
println!(" File: {}", disk_path.display());
println!(" Primed under: /memory/pinned/{}", AGENTS_SOURCE);
println!(
" Namespace: {} (your personal namespace)",
PERSONAL_NAMESPACE
);
println!(
" Visible in: ctx ls /memory/pinned/{} --namespace {}",
AGENTS_SOURCE, PERSONAL_NAMESPACE
);
println!(" Removable: ctx agents remove");
println!();
let count = agents_prime_personal(server, &client, &content).await?;
println!(
"\u{2713} Primed {} AGENTS.md sections under /memory/pinned/{} in your personal namespace",
count, AGENTS_SOURCE
);
let workspace =
agents_section_count(&agents_paths(server, branch, &client, |u| u.to_string()).await?);
if workspace > 0
&& agents_forget(
server,
branch,
&client,
"ctx agents install: moved to the personal namespace",
|u| u.to_string(),
)
.await
{
println!(
" Removed this workspace's older copy ({} sections). Other workspaces: `ctx agents migrate`.",
workspace
);
}
println!(" Disk file: {}", disk_path.display());
println!(" Edit the file then re-run `ctx agents install` to update.");
Ok(())
}
async fn agents_install_after_init(
server: &str,
branch: &str,
_format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
println!("---");
println!();
agents_install(None, true, false, server, branch, client).await
}
pub(crate) fn urlencoding(s: &str) -> String {
s.replace(' ', "%20")
.replace('&', "%26")
.replace('?', "%3F")
}
pub(crate) fn encode_ref(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => out.push(c),
_ => {
let mut buf = [0u8; 4];
for b in c.encode_utf8(&mut buf).as_bytes() {
out.push_str(&format!("%{b:02X}"));
}
}
}
}
out
}
fn find_hub_binary() -> String {
let exe_suffix = if cfg!(target_os = "windows") {
".exe"
} else {
""
};
let hub_name = format!("ctxone-hub{}", exe_suffix);
let engine_name = format!("agentstategraph-mcp{}", exe_suffix);
let mut candidates: Vec<PathBuf> = Vec::new();
if let Ok(exe) = std::env::current_exe()
&& let Some(dir) = exe.parent()
{
candidates.push(dir.join(&hub_name));
}
if let Some(home) = dirs::home_dir() {
candidates.push(home.join(".local").join("bin").join(&hub_name));
candidates.push(home.join(".local").join("bin").join(&engine_name));
}
if let Some(exe_dir) = dirs::executable_dir() {
candidates.push(exe_dir.join(&hub_name));
}
#[cfg(unix)]
{
candidates.push(PathBuf::from("/usr/local/bin").join(&hub_name));
candidates.push(PathBuf::from("/usr/local/bin").join(&engine_name));
}
#[cfg(windows)]
{
if let Ok(program_files) = std::env::var("ProgramFiles") {
candidates.push(PathBuf::from(program_files).join("ctxone").join(&hub_name));
}
}
for c in &candidates {
if c.exists() {
return c.to_string_lossy().to_string();
}
}
hub_name
}
struct AiTool {
name: &'static str,
detected: bool,
config_path: PathBuf,
config_type: ConfigType,
}
enum ConfigType {
McpJson,
Toml,
}
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum McpTransport {
Http,
Stdio,
}
fn app_data_dir(app: &str) -> Option<PathBuf> {
dirs::config_dir().map(|d| d.join(app))
}
fn dotfile_dir(name: &str) -> Option<PathBuf> {
dirs::home_dir().map(|h| h.join(format!(".{}", name)))
}
fn detect_tools(global: bool) -> Vec<AiTool> {
let cwd = std::env::current_dir().unwrap_or_default();
let mut tools: Vec<AiTool> = Vec::new();
let claude_code_path = if global {
dotfile_dir("claude")
.map(|d| d.join("settings.json"))
.unwrap_or_else(|| cwd.join(".mcp.json"))
} else {
cwd.join(".mcp.json")
};
tools.push(AiTool {
name: "Claude Code",
detected: true, config_path: claude_code_path,
config_type: ConfigType::McpJson,
});
let claude_desktop = app_data_dir("Claude").map(|d| d.join("claude_desktop_config.json"));
if let Some(path) = claude_desktop {
tools.push(AiTool {
name: "Claude Desktop",
detected: path.exists(),
config_path: path,
config_type: ConfigType::McpJson,
});
}
let cursor_global_dir = dotfile_dir("cursor");
let cursor_path = if global {
cursor_global_dir
.as_ref()
.map(|d| d.join("mcp.json"))
.unwrap_or_else(|| cwd.join(".cursor/mcp.json"))
} else {
cwd.join(".cursor/mcp.json")
};
let cursor_detected = cursor_global_dir.as_ref().is_some_and(|d| d.exists());
tools.push(AiTool {
name: "Cursor",
detected: cursor_detected,
config_path: cursor_path,
config_type: ConfigType::McpJson,
});
let vscode_app_dir = app_data_dir("Code");
let vscode_path = if global {
vscode_app_dir
.as_ref()
.map(|d| d.join("User").join("settings.json"))
.unwrap_or_else(|| cwd.join(".vscode/mcp.json"))
} else {
cwd.join(".vscode/mcp.json")
};
let vscode_detected = vscode_app_dir.as_ref().is_some_and(|d| d.exists());
tools.push(AiTool {
name: "VS Code",
detected: vscode_detected,
config_path: vscode_path,
config_type: ConfigType::McpJson,
});
let codex_dir = dotfile_dir("codex");
if let Some(dir) = codex_dir {
tools.push(AiTool {
name: "Codex",
detected: dir.exists(),
config_path: dir.join("config.toml"),
config_type: ConfigType::Toml,
});
}
let gemini_global = dotfile_dir("gemini");
let gemini_path = if global {
gemini_global
.as_ref()
.map(|d| d.join("settings.json"))
.unwrap_or_else(|| cwd.join(".gemini/settings.json"))
} else {
cwd.join(".gemini/settings.json")
};
let gemini_detected = gemini_global.as_ref().is_some_and(|d| d.exists());
tools.push(AiTool {
name: "Gemini",
detected: gemini_detected,
config_path: gemini_path,
config_type: ConfigType::McpJson,
});
let grok_global = dotfile_dir("grok");
let grok_path = if global {
grok_global
.as_ref()
.map(|d| d.join("settings.json"))
.unwrap_or_else(|| cwd.join(".grok/settings.json"))
} else {
cwd.join(".grok/settings.json")
};
let grok_detected = grok_global.as_ref().is_some_and(|d| d.exists());
tools.push(AiTool {
name: "Grok",
detected: grok_detected,
config_path: grok_path,
config_type: ConfigType::McpJson,
});
tools
}
fn print_commits(commits: &[serde_json::Value]) {
if commits.is_empty() {
println!("No commits.");
return;
}
for c in commits {
let ts = c
.get("timestamp")
.and_then(|v| v.as_str())
.unwrap_or("")
.get(..19)
.unwrap_or("");
let id = c.get("id").and_then(|v| v.as_str()).unwrap_or("");
let category = c
.get("intent")
.and_then(|i| i.get("category"))
.and_then(|v| v.as_str())
.unwrap_or("");
let desc = c
.get("intent")
.and_then(|i| i.get("description"))
.and_then(|v| v.as_str())
.unwrap_or("");
let conf = c.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0);
println!(
"{} {} [{}] {} ({:.0}%)",
ts,
id,
category,
desc,
conf * 100.0
);
}
}
async fn run_tail(
server: &str,
branch: &str,
interval_ms: u64,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
use std::collections::HashSet;
use std::time::Duration;
println!(
"Watching {} for new commits (every {}ms, Ctrl-C to stop)",
branch, interval_ms
);
println!();
let mut seen: HashSet<String> = HashSet::new();
let mut first = true;
loop {
let url = format!("{}/api/log/{}?limit=20", server, encode_ref(branch),);
match client.get(&url).send().await {
Ok(resp) if resp.status().is_success() => {
if let Ok(commits) = resp.json::<Vec<serde_json::Value>>().await {
let mut fresh: Vec<&serde_json::Value> = commits
.iter()
.filter(|c| {
let id = c.get("id").and_then(|v| v.as_str()).unwrap_or("");
!seen.contains(id)
})
.collect();
fresh.reverse();
if first {
let history: Vec<serde_json::Value> =
commits.iter().take(5).rev().cloned().collect();
print_commits(&history);
for c in &commits {
if let Some(id) = c.get("id").and_then(|v| v.as_str()) {
seen.insert(id.to_string());
}
}
first = false;
} else {
for c in &fresh {
print_commits(std::slice::from_ref(*c));
if let Some(id) = c.get("id").and_then(|v| v.as_str()) {
seen.insert(id.to_string());
}
}
}
}
}
Ok(resp) => {
eprintln!("Error: {}", resp.status());
}
Err(e) => {
eprintln!("Hub unreachable: {}", e);
}
}
tokio::time::sleep(Duration::from_millis(interval_ms)).await;
}
}
async fn run_doctor(cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let mut checks: Vec<(String, bool, String)> = Vec::new();
let mut suggestions: Vec<String> = Vec::new();
let hub_bin = find_hub_binary();
let hub_exists = std::path::Path::new(&hub_bin).exists();
checks.push((
"ctxone-hub binary".to_string(),
hub_exists,
if hub_exists {
hub_bin.clone()
} else {
"not found in PATH or ~/.local/bin".to_string()
},
));
if !hub_exists {
suggestions.push(
"Install ctxone-hub: curl -sSL https://raw.githubusercontent.com/AgentStateLabs/CTXone/main/install.sh | sh".to_string(),
);
}
let db = canonical_db_path();
let db_path = std::path::Path::new(&db);
let parent = db_path.parent().map(|p| p.to_path_buf());
let parent_ok = parent
.as_ref()
.map(|p| p.exists() || std::fs::create_dir_all(p).is_ok())
.unwrap_or(false);
checks.push(("memory db location".to_string(), parent_ok, db.clone()));
if !parent_ok {
suggestions.push(format!(
"Create the db directory: mkdir -p {}",
parent.as_ref().and_then(|p| p.to_str()).unwrap_or("")
));
}
let hub_reachable = client
.get(format!("{}/api/health", cli.server))
.send()
.await
.map(|r| r.status().is_success())
.unwrap_or(false);
checks.push((
"hub HTTP endpoint".to_string(),
hub_reachable,
cli.server.clone(),
));
if !hub_reachable {
suggestions.push(format!(
"Start the Hub: ctx serve --http (or set CTX_SERVER={})",
cli.server
));
}
let main_exists = if hub_reachable {
client
.get(format!("{}/api/stats/main", cli.server))
.send()
.await
.map(|r| r.status().is_success())
.unwrap_or(false)
} else {
false
};
checks.push((
"main branch".to_string(),
main_exists,
if main_exists {
"reachable".to_string()
} else {
"not reachable (hub down?)".to_string()
},
));
if hub_reachable {
let (ok, detail) = match cli.resolve_namespace().await {
Ok(Some(ns)) if cli.namespace.is_some() => {
(true, format!("{ns} (from --namespace / CTX_NAMESPACE)"))
}
Ok(Some(ns)) => (true, ns),
Ok(None) => (true, "default (no project registered here)".to_string()),
Err(f) => {
suggestions.push(
"Fix workspace detection (see its detail above), or pass \
--namespace <workspace> / set CTX_NAMESPACE to skip it"
.to_string(),
);
(false, f.detail)
}
};
checks.push(("workspace detection".to_string(), ok, detail));
}
let tools = detect_tools(false);
for t in &tools {
if !t.detected {
continue;
}
let has_mcp = if t.config_path.exists() {
match std::fs::read_to_string(&t.config_path) {
Ok(content) => content.contains("\"ctxone\""),
Err(_) => false,
}
} else {
false
};
checks.push((
format!("{} MCP config", t.name),
has_mcp,
if has_mcp {
format!("configured at {}", t.config_path.display())
} else {
"ctxone not in mcpServers".to_string()
},
));
if !has_mcp {
suggestions.push(format!(
"Configure {}: ctx init --tool {}",
t.name,
t.name
.split_whitespace()
.next()
.unwrap_or("")
.to_lowercase()
));
}
}
let mut candidate_paths: Vec<std::path::PathBuf> = Vec::new();
if let Ok(cwd) = std::env::current_dir() {
candidate_paths.push(cwd.join("ctxone.db"));
candidate_paths.push(cwd.join("target").join("ctxone.db"));
}
if let Some(home) = dirs::home_dir() {
candidate_paths.push(home.join(".ctxone").join("memory.db"));
}
candidate_paths.push(std::path::PathBuf::from(&db));
let mut seen = std::collections::HashSet::new();
candidate_paths.retain(|p| {
let key = p.canonicalize().unwrap_or_else(|_| p.clone());
seen.insert(key)
});
let mut drift_problems: Vec<String> = Vec::new();
for p in &candidate_paths {
let lock = std::path::PathBuf::from(format!("{}.lock", p.display()));
if !lock.exists() {
continue;
}
let body = std::fs::read_to_string(&lock).unwrap_or_default();
let pid: Option<u32> = body
.split("\"pid\":")
.nth(1)
.map(|s| {
s.chars()
.take_while(|c| c.is_ascii_digit())
.collect::<String>()
})
.and_then(|s| s.parse().ok());
let alive = pid
.map(|p| {
std::process::Command::new("kill")
.args(["-0", &p.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
})
.unwrap_or(false);
if alive && !p.exists() {
drift_problems.push(format!(
"{} (lock pid {} alive, db missing)",
p.display(),
pid.unwrap_or(0)
));
}
}
let drift_ok = drift_problems.is_empty();
checks.push((
"db inode drift".to_string(),
drift_ok,
if drift_ok {
"no live hubs with missing db files".to_string()
} else {
drift_problems.join("; ")
},
));
if !drift_ok {
suggestions.push(
"Restart the hub immediately and restore from <db>.bak.<utc> — \
writes are hitting an orphaned inode and will be lost on next restart"
.to_string(),
);
}
let existing_dbs: Vec<std::path::PathBuf> = candidate_paths
.iter()
.filter(|p| p.exists())
.cloned()
.collect();
let canonical_key = std::path::Path::new(&db)
.canonicalize()
.unwrap_or_else(|_| std::path::PathBuf::from(&db));
let stray_dbs: Vec<std::path::PathBuf> = existing_dbs
.iter()
.filter(|p| p.canonicalize().unwrap_or_else(|_| (*p).clone()) != canonical_key)
.cloned()
.collect();
let stray_ok = stray_dbs.is_empty();
checks.push((
"stray db files".to_string(),
stray_ok,
if stray_ok {
format!("canonical db only ({})", db)
} else {
format!(
"{} stub db file(s) beside the canonical {}: {}",
stray_dbs.len(),
db,
stray_dbs
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
)
},
));
if !stray_ok {
suggestions.push(format!(
"Stub db file(s) exist beside the canonical {} — the hub uses --path (the \
canonical one); remove the stragglers ({})",
db,
stray_dbs
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
));
}
let now = std::time::SystemTime::now();
let one_day = std::time::Duration::from_secs(86_400);
let mut recent_count = 0usize;
for p in &existing_dbs {
let parent = p.parent().unwrap_or_else(|| std::path::Path::new("."));
let basename = p
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let prefix = format!("{}.bak.", basename);
if let Ok(entries) = std::fs::read_dir(parent) {
for e in entries.flatten() {
if !e.file_name().to_string_lossy().starts_with(&prefix) {
continue;
}
if let Ok(meta) = e.metadata()
&& let Ok(mtime) = meta.modified()
&& now
.duration_since(mtime)
.map(|d| d < one_day)
.unwrap_or(false)
{
recent_count += 1;
}
}
}
}
let backups_ok = !existing_dbs.is_empty() && recent_count > 0;
checks.push((
"recent backups".to_string(),
backups_ok || existing_dbs.is_empty(),
if existing_dbs.is_empty() {
"no db files to back up".to_string()
} else if backups_ok {
format!("{} snapshot(s) within last 24h", recent_count)
} else {
"no .bak.* siblings within last 24h".to_string()
},
));
if !existing_dbs.is_empty() && !backups_ok {
suggestions.push(
"Take a snapshot now: ctx db backup (or start the hub — startup snapshots are automatic)"
.to_string(),
);
}
let checks_json: Vec<Value> = checks
.iter()
.map(|(name, ok, detail)| {
serde_json::json!({
"name": name,
"ok": ok,
"detail": detail,
})
})
.collect();
let all_ok = checks.iter().all(|(_, ok, _)| *ok);
let out = serde_json::json!({
"all_ok": all_ok,
"checks": checks_json,
"suggestions": suggestions,
});
emit(cli.format, &out, |_| {
println!("CtxOne Doctor");
println!();
for (name, ok, detail) in &checks {
let marker = if *ok { "\u{2713}" } else { "\u{2717}" };
println!(" {} {:24} {}", marker, name, detail);
}
println!();
if all_ok {
println!("All checks passed.");
} else {
println!("Suggestions:");
for s in &suggestions {
println!(" \u{2192} {}", s);
}
}
});
if !all_ok {
std::process::exit(EX_SOFTWARE);
}
Ok(())
}
fn session_id_for_file(path: &std::path::Path) -> String {
path.file_stem()
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| "default".to_string())
}
#[allow(clippy::too_many_arguments)]
const INGEST_CONCURRENCY: usize = 8;
struct IngestJob {
session_ref: crate::sources::SessionRef,
source_id: String,
effective_session: Option<String>,
routed: crate::workspace::Routed,
client: reqwest::Client,
}
#[derive(Default)]
struct SessionOutcome {
sessions: usize,
turns: usize,
skipped: usize,
full_turns: usize,
memories: usize,
tokens: crate::ingest::TurnTokens,
log: String,
}
#[allow(clippy::too_many_arguments)]
async fn ingest_one_session(
job: IngestJob,
source_label: &str,
label: &str,
server: &str,
branch: &str,
since_ts: &str,
last: Option<usize>,
dry_run: bool,
full_turn: bool,
tokens_only: bool,
reingest: bool,
extraction: Option<&crate::ingest::ExtractionConfig>,
) -> SessionOutcome {
use std::fmt::Write as _;
let mut out = SessionOutcome::default();
let session_ref = &job.session_ref;
let path = &session_ref.path;
let fname = path.file_name().unwrap_or_default().to_string_lossy();
let effective_session = job.effective_session.as_deref();
let client = &job.client;
let routed = &job.routed;
let source_impl =
crate::sources::source_by_id(&job.source_id).expect("source id came from the registry");
let fingerprint = source_impl.fingerprint(session_ref);
if !reingest
&& !dry_run
&& let (Some(sid), Some(fp)) = (effective_session, fingerprint.as_deref())
{
let stored = crate::ingest::fetch_stored_fingerprint(server, branch, sid, client).await;
if stored.as_deref() == Some(fp) {
out.skipped = 1;
return out;
}
}
let _ = writeln!(
out.log,
"→ {} (session: {}, workspace: {})",
fname,
effective_session.unwrap_or("default"),
match routed {
crate::workspace::Routed::Existing(ns) => ns.clone(),
crate::workspace::Routed::Registered(ns) => format!("{ns} (new)"),
crate::workspace::Routed::WouldRegister(ns) => format!("{ns} (would create)"),
crate::workspace::Routed::Fallback => "default".to_string(),
crate::workspace::Routed::Unresolved(_) => "unknown".to_string(),
}
);
let mut turns = source_impl.parse(session_ref);
if !turns.is_empty() {
out.sessions = 1;
}
let title = crate::ingest::derive_session_title(&turns).unwrap_or_else(|| {
let proj = if !label.is_empty() {
label.to_string()
} else {
std::env::current_dir()
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
.unwrap_or_else(|| "session".to_string())
};
let date = turns
.first()
.map(|t| t.timestamp.clone())
.filter(|ts| ts.len() >= 10)
.map(|ts| ts[..10].to_string())
.unwrap_or_else(|| chrono::Utc::now().format("%Y-%m-%d").to_string());
crate::ingest::truncate_title(&format!("{} · {}", proj, date))
});
if dry_run {
let _ = writeln!(
out.log,
" [dry] title: /sessions/{}/title = {:?}",
effective_session.unwrap_or("default"),
title
);
} else {
crate::ingest::store_session_title(&title, server, branch, effective_session, client).await;
}
let started_at = turns
.first()
.map(|t| t.timestamp.clone())
.unwrap_or_default();
let updated_at = turns
.last()
.map(|t| t.timestamp.clone())
.unwrap_or_default();
let mut models_used: Vec<String> = Vec::new();
for t in &turns {
let m = t.model.trim();
let real = !m.is_empty() && !m.starts_with('<');
if real && !models_used.iter().any(|x| x == m) {
models_used.push(m.to_string());
}
}
if dry_run {
let _ = writeln!(
out.log,
" [dry] meta: /sessions/{}/meta = {{source: {:?}, started_at: {:?}, updated_at: {:?}, models_used: {:?}}}",
effective_session.unwrap_or("default"),
source_label,
started_at,
updated_at,
models_used
);
} else {
crate::ingest::store_session_meta(
source_label,
&started_at,
&updated_at,
&models_used,
fingerprint.as_deref(),
server,
branch,
effective_session,
client,
)
.await;
}
let provenance = crate::ingest::build_provenance(&turns);
if let Some(prov) = &provenance {
if dry_run {
let _ = writeln!(
out.log,
" [dry] provenance: /sessions/{}/provenance = {}",
effective_session.unwrap_or("default"),
serde_json::to_string(prov).unwrap_or_default()
);
} else {
crate::ingest::store_session_provenance(
prov,
routed.namespace(),
routed.namespace(), &fname,
path.to_string_lossy().contains("/archived_sessions/"),
server,
branch,
effective_session,
client,
)
.await;
}
}
let burn = crate::burn::compute(&turns);
let burn_updated_at = turns
.last()
.map(|t| t.timestamp.clone())
.unwrap_or_default();
if dry_run {
let _ = writeln!(
out.log,
" [dry] burn: /sessions/{}/burn = level={} ratio={:?}",
effective_session.unwrap_or("default"),
burn.level,
burn.ratio,
);
} else {
crate::ingest::store_session_burn(
&burn.to_json(&burn_updated_at),
server,
branch,
effective_session,
client,
)
.await;
}
let usage = crate::ingest::session_usage(&turns);
let usage_stored = if dry_run {
let _ = writeln!(
out.log,
" [dry] usage: /sessions/{}/usage = {}",
effective_session.unwrap_or("default"),
serde_json::to_string(&usage).unwrap_or_default()
);
crate::ingest::UsageStored::Failed
} else {
crate::ingest::store_session_usage(&usage, server, branch, effective_session, client).await
};
if !since_ts.is_empty() {
turns.retain(|t| t.timestamp.as_str() >= since_ts);
}
if let Some(n) = last {
let skip = turns.len().saturating_sub(n);
turns = turns.into_iter().skip(skip).collect();
}
let source_file = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
for turn in turns.iter() {
out.turns += 1;
out.tokens.add(&turn.tokens);
}
if full_turn && !turns.is_empty() {
if dry_run {
let _ = writeln!(
out.log,
" [dry] full turns: /sessions/{}/turns ({} turns, 1 bulk write)",
effective_session.unwrap_or("default"),
turns.len(),
);
} else {
out.full_turns += crate::ingest::store_turns_bulk(
&turns,
&source_file,
server,
branch,
effective_session,
client,
)
.await;
if usage_stored != crate::ingest::UsageStored::Stored {
crate::ingest::trigger_session_by_model_backfill(server, effective_session, client)
.await;
}
}
}
if let Some(cfg) = extraction.filter(|_| !dry_run && !tokens_only) {
let sid = effective_session.unwrap_or("default");
let already = crate::ingest::extraction_watermark(sid)
.max(crate::ingest::hub_analyzed_through(server, sid, client).await);
for (idx, turn) in turns.iter().enumerate() {
if idx < already {
continue; }
if !turn.is_substantial() {
continue;
}
let memories = crate::ingest::extract_memories(turn, cfg, client).await;
for mem in &memories {
crate::ingest::store_memory(mem, server, branch, effective_session, client).await;
}
out.memories += memories.len();
}
if turns.len() > already {
crate::ingest::set_extraction_watermark(sid, turns.len());
let structure = crate::ingest::analyze_session(&turns, cfg, client).await;
let mut record = serde_json::json!({
"analyzed_through": turns.len(),
"analyzed_at": chrono::Utc::now()
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
"provider": cfg.provider.key_slug(),
"model": cfg.model,
});
if let Some(s) = structure {
record["summary"] = serde_json::Value::String(s.summary);
record["topics"] =
serde_json::to_value(&s.topics).unwrap_or(serde_json::Value::Null);
}
crate::ingest::put_analysis(server, sid, &record, client).await;
}
}
if !dry_run && full_turn && !tokens_only {
if let Some(sid) = effective_session {
let url = format!(
"{}/api/sessions/{}/derive_links?ref={}",
server,
urlencoding(sid),
encode_ref(branch),
);
let _ = client.post(url).send().await;
}
}
out
}
fn parse_since_epoch(s: &str) -> Option<i64> {
let s = s.trim();
if s.is_empty() {
return None;
}
if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
return Some(dt.timestamp());
}
if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
return d.and_hms_opt(0, 0, 0).map(|ndt| ndt.and_utc().timestamp());
}
None
}
async fn run_ingest_session(
server: &str,
branch: &str,
session: Option<&str>,
file: Option<String>,
source: &str,
all: bool,
since: Option<String>,
scan_dirs: Vec<String>,
last: Option<usize>,
tokens_only: bool,
dry_run: bool,
mut full_turn: bool,
clients: ClientFactory,
auto_register: bool,
fallback_namespace: Option<String>,
reingest: bool,
dir_workspaces: bool,
only_ids: Option<std::collections::HashSet<String>>,
force_namespace: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
let extraction = crate::ingest::resolve_extraction_config();
if extraction.is_none() && !tokens_only {
eprintln!(
"warn: no extraction provider/key configured — memory extraction disabled \
(set ~/.ctxone/keys/<provider> or a provider env var; use --tokens-only to suppress)"
);
}
if all {
full_turn = true;
}
if full_turn && !turns_allowed(server) {
eprintln!(
"Not sending raw turns to {}: that hub isn't on this machine. Session titles, \
metadata, per-model token usage and extracted memories still go. To send turns \
too, run `ctx config set remote_turns true` (or set CTX_REMOTE_TURNS=1).",
crate::ingest::hub_origin(server)
);
full_turn = false;
}
use crate::sources::{SessionRef, SessionSource};
let selected: Vec<Box<dyn SessionSource>> = if source == "all" {
crate::sources::all_sources()
.into_iter()
.filter(|s| s.is_available())
.collect()
} else {
match crate::sources::source_by_id(source) {
Some(s) => vec![s],
None => {
let known: Vec<&str> = crate::sources::all_sources()
.iter()
.map(|s| s.id())
.collect();
return Err(format!(
"unknown --source '{}' (known: {}, all)",
source,
known.join(", ")
)
.into());
}
}
};
let mut groups: Vec<(&'static str, &'static str, String, Vec<SessionRef>)> =
if let Some(f) = file {
let src = selected
.first()
.filter(|_| source != "all")
.ok_or("--file requires a concrete --source (not 'all')")?;
vec![(
src.id(),
src.label(),
String::new(),
vec![SessionRef {
label: String::new(),
cwd: None,
path: std::path::PathBuf::from(f),
native_id: None,
precomputed_fp: None,
}],
)]
} else {
let cwd = if all {
None
} else {
Some(std::env::current_dir()?)
};
let mut out = vec![];
for src in &selected {
let mut refs = match &cwd {
Some(dir) => src.discover_for_project(dir),
None => src.discover_all(),
};
for extra in &scan_dirs {
refs.extend(src.discover_in(std::path::Path::new(extra)));
}
refs.sort_by(|a, b| a.label.cmp(&b.label));
let mut by_label: Vec<(String, Vec<SessionRef>)> = vec![];
for r in refs {
match by_label.last_mut() {
Some((l, v)) if *l == r.label => v.push(r),
_ => by_label.push((r.label.clone(), vec![r])),
}
}
for (label, refs) in by_label {
out.push((src.id(), src.label(), label, refs));
}
}
out
};
let ignored = if session.is_some() || only_ids.is_some() {
std::collections::HashSet::new()
} else {
crate::session_import::load_ignored()
};
if only_ids.is_some() || !ignored.is_empty() {
for g in &mut groups {
let sid = g.0;
g.3.retain(|r| {
let id = r.namespaced_id(sid);
only_ids.as_ref().is_none_or(|w| w.contains(&id)) && !ignored.contains(&id)
});
}
groups.retain(|g| !g.3.is_empty());
}
if groups.iter().all(|(_, _, _, f)| f.is_empty()) {
if all {
println!("No session transcripts found for source '{}'.", source);
println!(
"{}",
serde_json::json!({ "sessions": 0, "turns": 0, "tokens": 0 })
);
} else {
println!("No session files found for this project.");
println!("Pass --file <path> to specify a .jsonl file directly.");
}
return Ok(());
}
let since_epoch: Option<i64> = since.as_deref().and_then(parse_since_epoch);
if since.as_deref().is_some_and(|s| !s.trim().is_empty()) && since_epoch.is_none() {
eprintln!(
"warn: could not parse --since '{}' (expected YYYY-MM-DD or RFC3339); importing everything",
since.as_deref().unwrap_or("")
);
}
let since_ts = "";
let mut total_skipped_since = 0usize;
let mut total_sessions = 0usize;
let mut total_skipped_unchanged = 0usize;
let mut skipped_deleted = 0usize;
let mut skipped_unresolved = 0usize;
let mut total_turns_seen = 0usize;
let mut total_memories = 0usize;
let mut total_full_turns = 0usize;
let mut total_tokens = crate::ingest::TurnTokens::default();
let mut router =
crate::workspace::Router::new(server, auto_register, dry_run, fallback_namespace)
.with_dir_workspaces(dir_workspaces);
for (source_id, source_label, label, files) in &groups {
if files.is_empty() {
continue;
}
if all && !label.is_empty() {
println!(
"\n=== {} · project: {} ({} files) ===",
source_label,
label,
files.len()
);
}
let mut proj_sessions = 0usize;
let mut proj_turns = 0usize;
let mut proj_skipped = 0usize;
let mut proj_tokens = crate::ingest::TurnTokens::default();
let src_impl = crate::sources::source_by_id(source_id);
let mut jobs: Vec<IngestJob> = Vec::with_capacity(files.len());
for session_ref in files {
if let Some(cutoff) = since_epoch
&& src_impl
.as_ref()
.and_then(|s| s.last_activity(session_ref))
.is_some_and(|a| a < cutoff)
{
total_skipped_since += 1;
continue;
}
let effective_session: Option<String> = match session {
Some(s) => Some(s.to_string()),
None => Some(session_ref.namespaced_id(source_id)),
};
let routed = match &force_namespace {
Some(ns) => crate::workspace::Routed::Existing(ns.clone()),
None => router.route(session_ref.cwd.as_deref()).await,
};
if routed.unresolved().is_some() {
skipped_unresolved += 1;
continue;
}
if let Some(sid) = effective_session.as_deref()
&& router.is_tombstoned(routed.namespace(), sid).await
{
let fname = session_ref
.path
.file_name()
.unwrap_or_default()
.to_string_lossy();
println!("→ {} (session: {}) — skipped, deleted", fname, sid);
skipped_deleted += 1;
continue;
}
let client = router.client_for(routed.namespace(), |ns| clients.build(ns));
jobs.push(IngestJob {
session_ref: session_ref.clone(),
source_id: source_id.to_string(),
effective_session,
routed,
client,
});
}
use futures::stream::StreamExt as _;
let outcomes: Vec<SessionOutcome> = futures::stream::iter(jobs)
.map(|job| {
ingest_one_session(
job,
source_label,
label,
server,
branch,
since_ts,
last,
dry_run,
full_turn,
tokens_only,
reingest,
extraction.as_ref(),
)
})
.buffer_unordered(INGEST_CONCURRENCY)
.collect()
.await;
for o in outcomes {
print!("{}", o.log);
proj_sessions += o.sessions;
proj_turns += o.turns;
proj_skipped += o.skipped;
proj_tokens.add(&o.tokens);
total_full_turns += o.full_turns;
total_memories += o.memories;
}
if all && !label.is_empty() {
let skip_note = if proj_skipped > 0 {
format!(", {proj_skipped} unchanged (skipped)")
} else {
String::new()
};
println!(
" project {}: {} sessions, {} turns, {} tokens{}",
label,
proj_sessions,
proj_turns,
proj_tokens.input
+ proj_tokens.output
+ proj_tokens.cache_read
+ proj_tokens.cache_creation,
skip_note,
);
}
total_sessions += proj_sessions;
total_turns_seen += proj_turns;
total_skipped_unchanged += proj_skipped;
total_tokens.add(&proj_tokens);
}
let grand_tokens = total_tokens.input
+ total_tokens.output
+ total_tokens.cache_read
+ total_tokens.cache_creation;
println!();
println!(
"Done. {} sessions, {} turns processed, {} memories stored, {} full turns persisted.",
total_sessions, total_turns_seen, total_memories, total_full_turns
);
if total_skipped_unchanged > 0 {
println!(
"Skipped {} unchanged session{} (fingerprint matched — pass --reingest to force).",
total_skipped_unchanged,
if total_skipped_unchanged == 1 {
""
} else {
"s"
}
);
}
if skipped_deleted > 0 {
println!(
"Skipped {} deleted session{} (tombstoned; their transcripts are still on disk).",
skipped_deleted,
if skipped_deleted == 1 { "" } else { "s" }
);
}
if total_skipped_since > 0 {
println!(
"Skipped {} session{} last active before the --since cutoff.",
total_skipped_since,
if total_skipped_since == 1 { "" } else { "s" }
);
}
if skipped_unresolved > 0 {
eprintln!(
"\u{26A0} Skipped {} session{} whose workspace couldn't be determined \
(not filed in 'default'; a later sync imports them once detection works):",
skipped_unresolved,
if skipped_unresolved == 1 { "" } else { "s" }
);
for (cwd, routed) in router.decisions() {
if let Some(why) = routed.unresolved() {
eprintln!(" {cwd}: {why}");
}
}
}
println!(
"Tokens — input: {} output: {} cache_read: {} cache_create: {}",
total_tokens.input,
total_tokens.output,
total_tokens.cache_read,
total_tokens.cache_creation,
);
let decisions = router.decisions();
if !decisions.is_empty() && (all || dry_run) {
println!("\nWorkspaces:");
for (cwd, routed) in &decisions {
let (ns, note) = match routed {
crate::workspace::Routed::Existing(ns) => (ns.as_str(), ""),
crate::workspace::Routed::Registered(ns) => (ns.as_str(), " (registered)"),
crate::workspace::Routed::WouldRegister(ns) => (ns.as_str(), " (would register)"),
crate::workspace::Routed::Fallback => ("default", " (no project)"),
crate::workspace::Routed::Unresolved(_) => ("?", " (detection failed; skipped)"),
};
println!(" {:<20} {}{}", ns, cwd, note);
}
}
if all {
println!(
"{}",
serde_json::json!({
"sessions": total_sessions,
"turns": total_turns_seen,
"tokens": grand_tokens,
"skipped_unresolved": skipped_unresolved,
})
);
}
Ok(())
}
async fn run_session_action(
action: SessionAction,
server: &str,
branch: &str,
clients: ClientFactory,
) -> Result<(), Box<dyn std::error::Error>> {
match action {
SessionAction::Metrics {
project,
session,
list,
all,
json,
gap,
verbose,
} => {
run_session_metrics(project, session, list, all, json, gap, verbose).await?;
}
SessionAction::Reattribute {
dry_run,
auto_register,
} => {
run_reattribute(server, &clients, dry_run, auto_register).await?;
}
SessionAction::Move { session_id, to } => {
let client = clients.build(None);
let agent_id = std::env::var("CTX_AGENT_ID").unwrap_or_else(|_| "ctx-cli".to_string());
let body = serde_json::json!({ "to_namespace": to, "ref": "main" });
let url = format!("{server}/api/sessions/{session_id}/move");
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => return Err(format!("session move failed: {e}").into()),
};
if !resp.status().is_success() {
let st = resp.status();
let msg = resp.text().await.unwrap_or_default();
return Err(format!("session move failed: {st} — {msg}").into());
}
let v: Value = resp.json().await?;
println!(
"Moved session {session_id} → {} ({} leaves){}",
v["to"].as_str().unwrap_or(&to),
v["dst_leaves"].as_u64().unwrap_or(0),
if v["deleted_source"].as_bool().unwrap_or(false) {
""
} else {
" (source kept)"
},
);
}
SessionAction::Segments { session_id, gap } => {
let client = clients.build(None);
let url = format!("{server}/api/sessions/{session_id}/segments?gap={gap}");
let resp = client.get(&url).send().await?;
if !resp.status().is_success() {
return Err(format!("segments failed: {}", resp.status()).into());
}
let v: Value = resp.json().await?;
let segs = v
.get("segments")
.and_then(|s| s.as_array())
.cloned()
.unwrap_or_default();
println!("session {session_id} — {} topic arc(s)", segs.len());
for s in &segs {
let u = |k: &str| s.get(k).and_then(|x| x.as_u64()).unwrap_or(0);
let st = |k: &str| s.get(k).and_then(|x| x.as_str()).unwrap_or("");
println!(
" [{:>3}-{:<3}] {:>3}t {:>8}tok {:<18} (start:{})",
u("start"),
u("end"),
u("turn_count"),
u("tokens"),
st("label"),
st("reason"),
);
}
}
SessionAction::List {
source,
page,
all,
json,
} => {
use crate::session_import as si;
let rows = si::discover(source.as_deref());
let imported = fetch_imported_ids(server, &clients).await;
let ignored = si::load_ignored();
if json {
let out: Vec<serde_json::Value> = rows
.iter()
.map(|r| {
let status = si::status_for(&r.id, &imported, &ignored);
serde_json::json!({
"number": r.number,
"id": r.id,
"source": r.source_id,
"project": r.project,
"last_activity": r.last_activity,
"status": status.as_str(),
})
})
.collect();
println!("{}", serde_json::to_string(&out)?);
return Ok(());
}
if rows.is_empty() {
println!("No agent sessions found on this machine.");
return Ok(());
}
if all {
let pages = rows.len().div_ceil(si::PAGE_SIZE).max(1);
for p in 1..=pages {
si::print_page(&rows, p, &imported, &ignored);
}
} else {
si::print_page(&rows, page, &imported, &ignored);
}
}
SessionAction::Import {
selectors,
source,
to,
include_ignored,
quiet,
dry_run,
} => {
use crate::session_import as si;
let rows = si::discover(source.as_deref());
if rows.is_empty() {
println!("No agent sessions found on this machine.");
return Ok(());
}
let imported = fetch_imported_ids(server, &clients).await;
let ignored = si::load_ignored();
let mut ids: std::collections::HashSet<String> = if selectors.is_empty() {
match si::interactive_select(&rows, &imported, &ignored) {
Some(set) => set,
None => {
println!("Aborted — nothing imported.");
return Ok(());
}
}
} else {
let (set, unmatched) = si::resolve_selectors(&rows, &selectors);
if !unmatched.is_empty() {
eprintln!(
"warn: unrecognized selectors ignored: {}",
unmatched.join(", ")
);
}
set
};
if !include_ignored {
let before = ids.len();
ids.retain(|id| !ignored.contains(id));
let skipped = before - ids.len();
if skipped > 0 {
println!(
"Skipping {skipped} session{} on the privacy skip-list \
(pass --include-ignored to import them).",
if skipped == 1 { "" } else { "s" }
);
}
}
if ids.is_empty() {
println!("Nothing selected to import.");
return Ok(());
}
println!(
"Selected {} session{} to import:",
ids.len(),
if ids.len() == 1 { "" } else { "s" }
);
{
let mut listed: Vec<&String> = ids.iter().collect();
listed.sort();
for id in listed {
println!(" {id}");
}
}
if let Some(ns) = &to {
println!("Assigning all imported sessions to workspace '{ns}'.");
}
if !quiet {
println!("{}", si::extraction_notice());
}
run_ingest_session(
server,
branch,
None,
None,
source.as_deref().unwrap_or("all"),
true, None,
vec![],
None,
false,
dry_run,
false,
clients,
true, None, false,
false,
Some(ids),
to, )
.await?;
}
SessionAction::Ignore { selectors, source } => {
use crate::session_import as si;
let rows = si::discover(source.as_deref());
let (ids, unmatched) = si::resolve_selectors(&rows, &selectors);
if !unmatched.is_empty() {
eprintln!(
"warn: unrecognized selectors ignored: {}",
unmatched.join(", ")
);
}
if ids.is_empty() {
println!("Nothing to ignore.");
return Ok(());
}
let mut ids: Vec<String> = ids.into_iter().collect();
ids.sort();
let added = si::add_ignored(&ids)?;
println!(
"Added {added} session{} to the privacy skip-list ({} already there). \
They will not be imported by manual runs or the background sweep.",
if added == 1 { "" } else { "s" },
ids.len() - added,
);
for id in &ids {
println!(" ignored: {id}");
}
}
SessionAction::Unignore { selectors, source } => {
use crate::session_import as si;
let rows = si::discover(source.as_deref());
let (ids, unmatched) = si::resolve_selectors(&rows, &selectors);
if !unmatched.is_empty() {
eprintln!(
"warn: unrecognized selectors ignored: {}",
unmatched.join(", ")
);
}
if ids.is_empty() {
println!("Nothing to unignore.");
return Ok(());
}
let ids: Vec<String> = ids.into_iter().collect();
let removed = si::remove_ignored(&ids)?;
println!(
"Removed {removed} session{} from the privacy skip-list.",
if removed == 1 { "" } else { "s" }
);
}
}
Ok(())
}
async fn fetch_imported_ids(
server: &str,
clients: &ClientFactory,
) -> std::collections::HashSet<String> {
let client = clients.build(None);
let url = format!("{server}/api/sessions/imported");
match client.get(&url).send().await {
Ok(r) if r.status().is_success() => r
.json::<Vec<String>>()
.await
.unwrap_or_default()
.into_iter()
.collect(),
_ => std::collections::HashSet::new(),
}
}
async fn fetch_session_cwd_from_graph(
client: &reqwest::Client,
server: &str,
sid: &str,
) -> Option<String> {
for idx in 0..3 {
let url = format!(
"{server}/api/sessions/{}/turns/{idx}?namespace=default",
urlencoding(sid)
);
let Ok(resp) = client.get(url).send().await else {
continue;
};
if !resp.status().is_success() {
continue;
}
if let Ok(v) = resp.json::<serde_json::Value>().await
&& let Some(s) = v.get("cwd").and_then(|c| c.as_str())
&& !s.trim().is_empty()
{
return Some(s.to_string());
}
}
None
}
async fn run_reattribute(
server: &str,
clients: &ClientFactory,
dry_run: bool,
auto_register: bool,
) -> Result<(), Box<dyn std::error::Error>> {
use crate::sources::SessionSource;
let mut cwd_by_sid: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for src in crate::sources::all_sources() {
if !src.is_available() {
continue;
}
for r in src.discover_all() {
if let Some(cwd) = &r.cwd {
cwd_by_sid
.entry(r.namespaced_id(src.id()))
.or_insert_with(|| cwd.clone());
}
}
}
let default_client = clients.build(Some("default"));
let registry: Vec<serde_json::Value> = default_client
.get(format!("{server}/api/stats/sessions"))
.send()
.await?
.json()
.await?;
let mut sids: std::collections::BTreeSet<String> = registry
.iter()
.filter_map(|s| s["session_id"].as_str().map(str::to_string))
.collect();
let registry_count = sids.len();
if let Ok(resp) = default_client
.get(format!(
"{server}/api/state/main/paths?prefix=/sessions&max_depth=2&namespace=default"
))
.send()
.await
&& let Ok(paths) = resp.json::<Vec<String>>().await
{
for p in &paths {
if let Some(id) = p
.strip_prefix("/sessions/")
.and_then(|rest| rest.split('/').next())
.filter(|id| !id.is_empty())
{
sids.insert(id.to_string());
}
}
}
println!(
"{} sessions in `default` ({} from registry, {} total incl. graph).",
sids.len(),
registry_count,
sids.len(),
);
let mut router = crate::workspace::Router::new(server, auto_register, dry_run, None);
let mut plan: Vec<(String, String)> = Vec::new(); let mut unresolved = 0usize;
for sid in &sids {
let cwd: Option<String> = match cwd_by_sid.get(sid) {
Some(c) => Some(c.clone()),
None => fetch_session_cwd_from_graph(&default_client, server, sid).await,
};
let Some(cwd) = cwd else {
unresolved += 1;
continue;
};
let routed = router.route(Some(&cwd)).await;
if let Some(why) = routed.unresolved() {
eprintln!(" {}: workspace unknown ({why})", &sid[..sid.len().min(24)]);
unresolved += 1;
continue;
}
match routed.namespace() {
Some(ns) if ns != "default" => plan.push((sid.to_string(), ns.to_string())),
_ => {} }
}
println!(
"\n{} to move, {} staying in `default` ({} unresolved, rest already default):",
plan.len(),
sids.len() - plan.len(),
unresolved,
);
for (sid, ns) in &plan {
println!(" {} default → {}", &sid[..sid.len().min(24)], ns);
}
if dry_run {
println!("\nDry run — nothing moved. Re-run without --dry-run to apply.");
return Ok(());
}
let mut moved = 0usize;
let mut already = 0usize;
let mut failed = 0usize;
for (sid, ns) in &plan {
let body = serde_json::json!({ "to_namespace": ns });
let resp = default_client
.post(format!("{server}/api/sessions/{}/move", urlencoding(sid)))
.json(&body)
.send()
.await;
match resp {
Ok(r) if r.status().is_success() => moved += 1,
Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND => already += 1,
Ok(r) => {
failed += 1;
eprintln!(" move {} → {} failed: {}", sid, ns, r.status());
}
Err(e) => {
failed += 1;
eprintln!(" move {} → {} error: {}", sid, ns, e);
}
}
}
println!("\nMoved {moved}, already in place {already}, failed {failed}.");
Ok(())
}
async fn run_session_metrics(
project: Option<String>,
session_filter: Option<String>,
list: bool,
all: bool,
json_out: bool,
gap: f64,
verbose: bool,
) -> Result<(), Box<dyn std::error::Error>> {
use crate::metrics::{
SessionMetrics, all_project_sessions, find_session_files, fmt_tokens,
parse_session_metrics, render_list_row, render_metrics,
};
if all {
let projects = all_project_sessions();
if projects.is_empty() {
println!("No Claude Code session files found in ~/.claude/projects/");
return Ok(());
}
let mut all_sessions: Vec<(String, Vec<SessionMetrics>)> = vec![];
for (label, files) in &projects {
let sessions: Vec<SessionMetrics> = files
.iter()
.map(|f| parse_session_metrics(f, gap))
.filter(|s| s.turns > 0)
.collect();
if !sessions.is_empty() {
all_sessions.push((label.clone(), sessions));
}
}
if json_out {
println!("{}", serde_json::to_string_pretty(&all_sessions)?);
return Ok(());
}
let mut grand_total = SessionMetrics::default();
for (label, sessions) in &all_sessions {
let bar = "─".repeat(62);
println!("\n{}", bar);
println!(" Project: {}", label);
println!("{}", bar);
if list {
for sm in sessions {
render_list_row(sm);
}
}
let mut project_total = SessionMetrics::default();
for sm in sessions {
project_total.add(sm);
}
let savings_pct = if project_total.cost_no_cache_usd > 0.0 {
project_total.cache_savings_usd / project_total.cost_no_cache_usd * 100.0
} else {
0.0
};
println!(
" {} sessions {} turns {:.1}% cache ${:.2} actual (saved {:.0}% vs no-cache ${:.2})",
sessions.len(),
project_total.turns,
project_total.cache_hit_rate * 100.0,
project_total.cost_usd,
savings_pct,
project_total.cost_no_cache_usd,
);
grand_total.add(&project_total);
}
let grand_savings_pct = if grand_total.cost_no_cache_usd > 0.0 {
grand_total.cache_savings_usd / grand_total.cost_no_cache_usd * 100.0
} else {
0.0
};
println!("\n{}", "═".repeat(70));
println!(
" TOTAL {} projects {} turns {:.1}% cache",
all_sessions.len(),
grand_total.turns,
grand_total.cache_hit_rate * 100.0,
);
println!(
" Actual cost: ${:.2} (per-turn pricing with cache discount applied)",
grand_total.cost_usd,
);
println!(
" Without cache: ${:.2} (saved ${:.2} = {:.1}% reduction)",
grand_total.cost_no_cache_usd, grand_total.cache_savings_usd, grand_savings_pct,
);
println!("{}", "═".repeat(70));
return Ok(());
}
let project_dir = project.map(std::path::PathBuf::from).unwrap_or_else(|| {
std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
});
let files = find_session_files(&project_dir);
if files.is_empty() {
println!("No session files found for: {}", project_dir.display());
println!(" (expected ~/.claude/projects/<hash>/*.jsonl)");
return Ok(());
}
let files: Vec<_> = if let Some(ref sid) = session_filter {
files
.into_iter()
.filter(|f| {
f.file_stem()
.and_then(|s| s.to_str())
.map(|s| s.starts_with(sid.as_str()))
.unwrap_or(false)
})
.collect()
} else {
files
};
if files.is_empty() {
println!("No sessions match that filter.");
return Ok(());
}
let sessions: Vec<SessionMetrics> = files
.iter()
.map(|f| parse_session_metrics(f, gap))
.filter(|s| s.turns > 0)
.collect();
let label = project_dir
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("project")
.to_string();
if list {
let bar = "─".repeat(62);
println!("\n{}", bar);
println!(" Sessions — {}", label);
println!("{}", bar);
println!(
" {:8} {:16} {:9} {:8} {:7} {:11} {}",
"UUID", "Started", "Turns", "Input", "Output", "Cache hit%", "Cost"
);
for sm in &sessions {
render_list_row(sm);
}
let mut total = SessionMetrics::default();
for sm in &sessions {
total.add(sm);
}
println!("{}", bar);
println!(
" Total: {} sessions, {} turns, ${:.4}",
sessions.len(),
total.turns,
total.cost_usd
);
return Ok(());
}
if json_out {
println!("{}", serde_json::to_string_pretty(&sessions)?);
return Ok(());
}
if session_filter.is_some() {
for sm in &sessions {
render_metrics(sm, &sm.session_id, gap, verbose);
}
} else {
let mut total = SessionMetrics::default();
for sm in &sessions {
total.add(sm);
}
total.session_id = format!("{} sessions", sessions.len());
render_metrics(&total, &label, gap, verbose);
}
Ok(())
}
async fn run_capture_turn(
server: &str,
branch: &str,
session: Option<&str>,
transcript: Option<String>,
turns: usize,
tokens_only: bool,
full_turn: bool,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let full_turn = full_turn && turns_allowed(server);
let transcript_path: std::path::PathBuf = if let Some(t) = transcript {
std::path::PathBuf::from(t)
} else {
let stdin_payload = read_stdin_nonblocking();
if let Some(path) = stdin_payload
.as_deref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
.and_then(|v| {
v.get("transcript_path")
.and_then(|p| p.as_str())
.map(|s| s.to_string())
})
{
std::path::PathBuf::from(path)
} else {
let cwd = std::env::current_dir()?;
match crate::ingest::latest_session_file(&cwd) {
Some(p) => p,
None => {
return Ok(());
}
}
}
};
if !transcript_path.exists() {
return Ok(());
}
let extraction = crate::ingest::resolve_extraction_config();
let detected = crate::sources::source_ref_for_path(&transcript_path)
.filter(|(src, _)| src.id() != "claude");
let (recent, base_idx, derived_sid): (Vec<crate::ingest::Turn>, usize, String) =
if let Some((src, sref)) = &detected {
let mut all = src.parse(sref);
let all_count = all.len();
let take = turns.min(all_count);
let base = all_count - take;
let tail = all.split_off(base);
(tail, base, sref.namespaced_id(src.id()))
} else {
let all_count = crate::ingest::parse_turns(&transcript_path).len();
let recent = crate::ingest::last_turns(&transcript_path, turns);
let base = all_count.saturating_sub(recent.len());
(recent, base, session_id_for_file(&transcript_path))
};
let source_file = transcript_path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let effective_session: Option<&str> = match session {
Some(s) => Some(s),
None => Some(derived_sid.as_str()),
};
for (offset, turn) in recent.iter().enumerate() {
let idx = base_idx + offset;
if !turn.tokens.is_empty() {
crate::ingest::record_turn_tokens(
&turn.tokens,
&turn.model,
crate::ingest::provider_for_model(&turn.model),
server,
effective_session,
&client,
)
.await;
}
if full_turn {
crate::ingest::store_full_turn(
turn,
idx,
&source_file,
server,
branch,
effective_session,
&client,
)
.await;
}
let Some(cfg) = extraction.as_ref().filter(|_| !tokens_only) else {
continue;
};
if !turn.is_substantial() {
continue;
}
let memories = crate::ingest::extract_memories(turn, cfg, &client).await;
for mem in &memories {
crate::ingest::store_memory(mem, server, branch, effective_session, &client).await;
}
}
Ok(())
}
fn read_stdin_nonblocking() -> Option<String> {
use std::io::Read;
if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
return None;
}
let mut buf = String::new();
let _ = std::io::stdin().take(4096).read_to_string(&mut buf);
if buf.trim().is_empty() {
None
} else {
Some(buf)
}
}
async fn run_demo(server: &str, client: reqwest::Client) -> Result<(), Box<dyn std::error::Error>> {
match client.get(format!("{}/api/health", server)).send().await {
Ok(r) if r.status().is_success() => {}
_ => {
eprintln!(
"Hub unreachable at {}. Start it with: ctx serve --http",
server
);
std::process::exit(1);
}
}
println!("Seeding demo memory graph...\n");
let seed: &[(&str, &str, &str)] = &[
(
"licensing",
"high",
"CtxOne is licensed under BSL-1.1 with automatic Apache 2.0 conversion after 18 months",
),
(
"licensing",
"high",
"The engine (AgentStateGraph) is MIT OR Apache-2.0 licensed, by the same author",
),
(
"licensing",
"medium",
"Commercial licensing contact: licensing@agentstatelabs.com",
),
(
"architecture",
"high",
"CtxOne Hub wraps AgentStateGraph with a token-tracking memory API",
),
(
"architecture",
"high",
"Lens is a SvelteKit web app that reads the Hub over HTTP",
),
(
"architecture",
"high",
"The ctx CLI is Rust with clap, talks to the Hub over HTTP",
),
(
"architecture",
"medium",
"Default database path is ~/.ctxone/memory.db for shared memory across tools",
),
(
"architecture",
"medium",
"The Hub exposes both MCP stdio mode and REST HTTP mode",
),
(
"architecture",
"low",
"The engine uses blake3 for content hashing and SQLite for default storage",
),
(
"features",
"high",
"ctx init auto-configures Claude Code, Cursor, VS Code, Codex with MCP",
),
(
"features",
"high",
"ctx prime loads markdown files as pinned or searchable memories",
),
(
"features",
"high",
"Pinned memories are always included in every recall response",
),
(
"features",
"medium",
"ctx recall returns token savings metadata on every call",
),
(
"features",
"medium",
"ctx stats shows cumulative session token savings",
),
(
"economics",
"high",
"Flat memory files scale O(n) on cost — every turn loads everything",
),
(
"economics",
"high",
"CtxOne scales O(log n) — recall loads only what's relevant",
),
(
"economics",
"medium",
"Typical savings: 60x tokens per session vs flat memory files",
),
(
"economics",
"medium",
"Enterprise ROI: mid-sized company saves ~$32k/year on token costs",
),
("team", "medium", "Craig Brown is the primary maintainer"),
(
"team",
"medium",
"Pre-commit: run cargo fmt, clippy, and svelte-check",
),
(
"team",
"low",
"CI runs on every push to main and on tagged releases",
),
];
let mut remembered = 0;
for (context, importance, fact) in seed {
let body = serde_json::json!({
"fact": fact,
"importance": importance,
"context": context,
});
let resp = client
.post(format!("{}/api/memory/remember", server))
.json(&body)
.send()
.await?;
if resp.status().is_success() {
remembered += 1;
print!(".");
use std::io::Write;
std::io::stdout().flush().ok();
}
}
println!("\nSeeded {} facts.\n", remembered);
let queries = [
("licensing", 1500usize),
("architecture", 1500),
("tokens", 1500),
("Lens", 800),
];
for (topic, budget) in queries {
let resp = client
.get(format!(
"{}/api/memory/recall?topic={}&budget={}",
server,
urlencoding(topic),
budget
))
.send()
.await?;
if let Ok(parsed) = resp.json::<serde_json::Value>().await {
let matches = parsed
.get("topic_matches")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let sent = parsed
.get("ctx_tokens_sent")
.and_then(|v| v.as_u64())
.unwrap_or(0);
println!(
" recall \"{}\" → {} matches, {} tokens injected",
topic, matches, sent
);
}
}
if let Ok(resp) = client
.get(format!("{}/api/stats/tokens", server))
.send()
.await
&& let Ok(parsed) = resp.json::<serde_json::Value>().await
{
let used = parsed
.get("session_tokens_used")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let saved = parsed
.get("session_tokens_saved")
.and_then(|v| v.as_u64())
.unwrap_or(0);
println!();
println!("Estimated savings this session (conservative model — savings from a memory");
println!("tool is a counterfactual and can't be measured, so this is an estimate):");
println!(
" {} tokens injected · ~{} tokens saved (est.), growing as the session grows",
used, saved
);
}
println!();
println!("Try: ctx recall \"your topic here\"");
println!("Or open Lens: http://localhost:5173");
Ok(())
}
#[derive(serde::Serialize)]
struct Section {
title: String,
body: String,
}
fn parse_markdown_sections(content: &str) -> Vec<Section> {
let mut sections: Vec<Section> = Vec::new();
let mut current_title: Option<String> = None;
let mut current_body = String::new();
for line in content.lines() {
let trimmed = line.trim_start();
let is_h1 = trimmed.starts_with("# ") && !trimmed.starts_with("## ");
let is_h2 = trimmed.starts_with("## ") && !trimmed.starts_with("### ");
if is_h1 || is_h2 {
if let Some(title) = current_title.take() {
let body = current_body.trim().to_string();
if !body.is_empty() {
sections.push(Section { title, body });
}
} else if !current_body.trim().is_empty() {
sections.push(Section {
title: "Intro".to_string(),
body: current_body.trim().to_string(),
});
}
current_body.clear();
let prefix_len = if is_h1 { 2 } else { 3 };
current_title = Some(trimmed[prefix_len..].trim().to_string());
} else {
current_body.push_str(line);
current_body.push('\n');
}
}
if let Some(title) = current_title {
let body = current_body.trim().to_string();
if !body.is_empty() {
sections.push(Section { title, body });
}
} else if !current_body.trim().is_empty() {
sections.push(Section {
title: "Intro".to_string(),
body: current_body.trim().to_string(),
});
}
sections
}
fn agents_md_path() -> PathBuf {
let base = if cfg!(target_os = "windows") {
dirs::config_dir().or_else(dirs::data_dir)
} else {
dirs::config_dir()
};
match base {
Some(dir) => dir.join("ctxone").join("AGENTS.md"),
None => PathBuf::from("./AGENTS.md"),
}
}
fn load_agents_md(override_path: Option<&str>) -> Result<(String, String), String> {
let path = match override_path {
Some(p) => PathBuf::from(p),
None => agents_md_path(),
};
if path.exists() {
let content = std::fs::read_to_string(&path)
.map_err(|e| format!("failed to read {}: {}", path.display(), e))?;
Ok((content, path.display().to_string()))
} else {
Ok((
EMBEDDED_AGENTS_MD.to_string(),
format!("(embedded default — will be written to {})", path.display()),
))
}
}
fn write_agents_md_if_absent(content: &str) -> Result<PathBuf, String> {
let path = agents_md_path();
if path.exists() {
return Ok(path);
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("mkdir {}: {}", parent.display(), e))?;
}
std::fs::write(&path, content).map_err(|e| format!("write {}: {}", path.display(), e))?;
Ok(path)
}
fn canonical_db_path() -> String {
let base = if cfg!(target_os = "windows") {
dirs::data_dir()
} else {
dirs::home_dir().map(|h| h.join(".ctxone"))
};
match base {
Some(dir) => {
let p = if cfg!(target_os = "windows") {
dir.join("ctxone").join("memory.db")
} else {
dir.join("memory.db")
};
p.to_string_lossy().into_owned()
}
None => "./ctxone.db".to_string(),
}
}
fn tool_slug(name: &str) -> String {
let mut out = String::with_capacity(name.len());
let mut prev_dash = false;
for c in name.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
prev_dash = false;
} else if !prev_dash && !out.is_empty() {
out.push('-');
prev_dash = true;
}
}
out.trim_end_matches('-').to_string()
}
fn tool_filter_matches(filter: &str, tool_name: &str) -> bool {
let f = tool_slug(filter);
let slug = tool_slug(tool_name);
let canonical = match f.as_str() {
"claude" => "claude-code",
"vscode" | "vs" | "code" => "vs-code",
"desktop" => "claude-desktop",
other => other,
};
slug == canonical
}
pub const CHECKOUT_TOKEN_FILE: &str = ".ctxproject.local";
fn checkout_token(start: &std::path::Path) -> String {
let root = find_git_root(start).unwrap_or_else(|| start.to_path_buf());
let token_path = root.join(CHECKOUT_TOKEN_FILE);
if let Ok(existing) = std::fs::read_to_string(&token_path) {
let t = existing.trim();
if !t.is_empty() {
return t.to_string();
}
}
let token = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or_default()
.hash(&mut h);
root.hash(&mut h);
std::process::id().hash(&mut h);
format!("{:08x}", h.finish() as u32)
};
if std::fs::write(&token_path, format!("{token}\n")).is_ok() {
let _ = exclude_locally(&root, CHECKOUT_TOKEN_FILE);
return token;
}
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
root.to_string_lossy().hash(&mut h);
format!("{:08x}", h.finish() as u32)
}
fn exclude_locally(root: &std::path::Path, entry: &str) -> std::io::Result<()> {
let out = std::process::Command::new("git")
.args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
.current_dir(root)
.output()?;
if !out.status.success() {
return Ok(());
}
let common = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim().to_string());
let exclude = common.join("info").join("exclude");
if !exclude.exists() {
return Ok(());
}
let body = std::fs::read_to_string(&exclude).unwrap_or_default();
if body.lines().any(|l| l.trim() == entry) {
return Ok(());
}
let sep = if body.is_empty() || body.ends_with('\n') {
""
} else {
"\n"
};
std::fs::write(&exclude, format!("{body}{sep}{entry}\n"))
}
fn compose_session_id(namespace: Option<&str>, agent_slug: &str, token: &str) -> String {
match namespace.map(str::trim).filter(|n| !n.is_empty()) {
Some(ns) => format!("{ns}:{agent_slug}:{token}"),
None => format!("proj-{agent_slug}-{token}"),
}
}
fn exclude_written_config(config_path: &std::path::Path) {
let Some(dir) = config_path.parent() else {
return;
};
let Some(root) = find_git_root(dir) else {
return;
};
let Ok(rel) = config_path.strip_prefix(&root) else {
return;
};
let entry = match rel.components().count() {
0 => return,
1 => rel.to_string_lossy().to_string(),
_ => format!(
"{}/",
rel.components()
.next()
.unwrap()
.as_os_str()
.to_string_lossy()
),
};
let _ = exclude_locally(&root, &entry);
}
fn init_session_id(global: bool, namespace: Option<&str>, agent_slug: &str) -> String {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
session_id_in(global, namespace, agent_slug, &cwd)
}
const GLOBAL_SESSION_TOKEN: &str = "global";
fn session_id_in(
global: bool,
namespace: Option<&str>,
agent_slug: &str,
cwd: &std::path::Path,
) -> String {
if global {
return compose_session_id(namespace, agent_slug, GLOBAL_SESSION_TOKEN);
}
compose_session_id(namespace, agent_slug, &checkout_token(cwd))
}
fn global_init_namespace(explicit: Option<&str>) -> String {
explicit
.map(str::trim)
.filter(|ns| !ns.is_empty())
.unwrap_or(DEFAULT_NAMESPACE)
.to_string()
}
fn mcp_server_entry(
agent_id: &str,
client_name: &str,
transport: McpTransport,
mcp_url: &str,
namespace: Option<&str>,
auth_token: Option<&str>,
auth_token_env: Option<&str>,
session_id: &str,
) -> Value {
match transport {
McpTransport::Http => {
let url = mcp_http_url(mcp_url, namespace);
if http_client_needs_bridge(client_name) {
let mut args = vec![
"-y".to_string(),
"mcp-remote".to_string(),
url,
"--transport".to_string(),
"http-only".to_string(),
];
args.push("--header".to_string());
args.push(format!("X-CTXone-Session: {session_id}"));
args.push("--header".to_string());
args.push(format!("X-CTXone-Agent: {agent_id}"));
if let Some(tok) = auth_token {
args.push("--header".to_string());
args.push(format!("Authorization: Bearer {tok}"));
}
serde_json::json!({ "command": "npx", "args": args })
} else {
let mut entry = serde_json::json!({ "type": "http", "url": url });
let mut headers = serde_json::Map::new();
headers.insert(
"X-CTXone-Session".to_string(),
serde_json::Value::String(session_id.to_string()),
);
headers.insert(
"X-CTXone-Agent".to_string(),
serde_json::Value::String(agent_id.to_string()),
);
let auth_value = auth_token
.map(|t| format!("Bearer {t}"))
.or_else(|| auth_token_env.map(|v| format!("Bearer ${{{v}}}")));
if let Some(v) = auth_value {
headers.insert("Authorization".to_string(), serde_json::Value::String(v));
}
entry["headers"] = serde_json::Value::Object(headers);
entry
}
}
McpTransport::Stdio => {
let hub_bin = find_hub_binary();
let db_path = canonical_db_path();
if let Some(parent) = std::path::Path::new(&db_path).parent() {
let _ = std::fs::create_dir_all(parent);
}
serde_json::json!({
"command": hub_bin,
"args": ["--path", db_path, "--agent-id", agent_id]
})
}
}
}
fn http_client_needs_bridge(client_name: &str) -> bool {
client_name == "Claude Desktop"
}
fn hub_health_url(base: &str) -> Option<String> {
let (scheme, rest) = base.split_once("://")?;
let authority = rest.split(['/', '?']).next().filter(|a| !a.is_empty())?;
Some(format!("{scheme}://{authority}/api/health"))
}
fn mcp_http_url(base: &str, namespace: Option<&str>) -> String {
match namespace {
Some(ns) if !ns.is_empty() => {
let sep = if base.contains('?') { '&' } else { '?' };
format!("{base}{sep}namespace={ns}")
}
_ => base.to_string(),
}
}
fn codex_mcp_http_url(
base: &str,
namespace: Option<&str>,
session_id: &str,
agent_id: &str,
) -> String {
let url = mcp_http_url(base, namespace);
let sep = if url.contains('?') { '&' } else { '?' };
format!(
"{url}{sep}session={}&agent={}",
urlencoding(session_id),
urlencoding(agent_id)
)
}
fn merge_codex_ctxone_toml(
existing: &str,
hub_bin: &str,
db_path: &str,
agent_id: &str,
session_id: &str,
) -> Result<String, String> {
use toml::Value;
let mut doc: Value = if existing.trim().is_empty() {
Value::Table(toml::map::Map::new())
} else {
toml::from_str(existing).map_err(|e| format!("invalid existing TOML: {}", e))?
};
let root = doc
.as_table_mut()
.ok_or_else(|| "config root is not a table".to_string())?;
let servers = root
.entry("mcp_servers".to_string())
.or_insert_with(|| Value::Table(toml::map::Map::new()))
.as_table_mut()
.ok_or_else(|| "mcp_servers is not a table".to_string())?;
let mut ctxone = toml::map::Map::new();
ctxone.insert("command".to_string(), Value::String(hub_bin.to_string()));
ctxone.insert(
"args".to_string(),
Value::Array(vec![
Value::String("--path".to_string()),
Value::String(db_path.to_string()),
Value::String("--agent-id".to_string()),
Value::String(agent_id.to_string()),
]),
);
let mut env = toml::map::Map::new();
env.insert(
"CTX_SESSION".to_string(),
Value::String(session_id.to_string()),
);
ctxone.insert("env".to_string(), Value::Table(env));
servers.insert("ctxone".to_string(), Value::Table(ctxone));
toml::to_string_pretty(&doc).map_err(|e| format!("serialize failed: {}", e))
}
fn merge_codex_ctxone_toml_http(
existing: &str,
url: &str,
auth_token_env: Option<&str>,
) -> Result<String, String> {
use toml::Value;
let mut doc: Value = if existing.trim().is_empty() {
Value::Table(toml::map::Map::new())
} else {
toml::from_str(existing).map_err(|e| format!("invalid existing TOML: {}", e))?
};
let root = doc
.as_table_mut()
.ok_or_else(|| "config root is not a table".to_string())?;
let servers = root
.entry("mcp_servers".to_string())
.or_insert_with(|| Value::Table(toml::map::Map::new()))
.as_table_mut()
.ok_or_else(|| "mcp_servers is not a table".to_string())?;
let mut ctxone = toml::map::Map::new();
ctxone.insert("url".to_string(), Value::String(url.to_string()));
if let Some(var) = auth_token_env {
ctxone.insert(
"bearer_token_env_var".to_string(),
Value::String(var.to_string()),
);
}
servers.insert("ctxone".to_string(), Value::Table(ctxone));
toml::to_string_pretty(&doc).map_err(|e| format!("serialize failed: {}", e))
}
async fn branch_list(
server: &str,
format: OutputFormat,
current: &str,
client: &reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let resp = match client.get(format!("{}/api/branches", server)).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "branches failed").await;
}
let branches: Vec<Value> = resp.json().await?;
let value = Value::Array(branches.clone());
emit(format, &value, |_| {
if branches.is_empty() {
println!("No branches.");
} else {
for b in &branches {
let name = b.get("name").and_then(|v| v.as_str()).unwrap_or("");
let id = b.get("id").and_then(|v| v.as_str()).unwrap_or("");
let marker = if name == current { "*" } else { " " };
println!("{} {:30} {}", marker, name, id);
}
}
});
Ok(())
}
fn handle_config(
action: ConfigAction,
format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
match action {
ConfigAction::Path => {
emit(
format,
&serde_json::json!({ "path": CtxConfig::path() }),
|_| {
println!("{}", CtxConfig::path().display());
},
);
}
ConfigAction::Show => {
let config = CtxConfig::load();
let value = serde_json::to_value(&config).unwrap_or_default();
emit(format, &value, |v| {
if v.as_object().map(|o| o.is_empty()).unwrap_or(true) {
println!("(empty config at {})", CtxConfig::path().display());
println!("Set a value with: ctx config set <key> <value>");
} else {
println!("Config file: {}", CtxConfig::path().display());
if let Some(s) = v.get("server").and_then(|x| x.as_str()) {
println!(" server: {}", s);
}
if let Some(b) = v.get("branch").and_then(|x| x.as_str()) {
println!(" branch: {}", b);
}
if let Some(f) = v.get("format").and_then(|x| x.as_str()) {
println!(" format: {}", f);
}
if let Some(r) = v.get("remote_turns").and_then(|x| x.as_bool()) {
println!(" remote_turns: {}", r);
}
}
});
}
ConfigAction::Get { key } => {
let config = CtxConfig::load();
match config.get_key(&key) {
Ok(value) => {
emit(
format,
&serde_json::json!({ "key": key, "value": value }),
|_| println!("{}", value),
);
}
Err(e) => {
eprintln!("{}", e);
std::process::exit(EX_DATAERR);
}
}
}
ConfigAction::Set { key, value } => {
let mut config = CtxConfig::load();
if let Err(e) = config.set_key(&key, &value) {
eprintln!("{}", e);
std::process::exit(EX_DATAERR);
}
config.save()?;
emit(
format,
&serde_json::json!({ "status": "ok", "key": key, "value": value }),
|_| {
println!("Saved: {} = {}", key, value);
println!(" → {}", CtxConfig::path().display());
},
);
}
ConfigAction::Unset { key } => {
let mut config = CtxConfig::load();
if let Err(e) = config.unset_key(&key) {
eprintln!("{}", e);
std::process::exit(EX_DATAERR);
}
config.save()?;
emit(
format,
&serde_json::json!({ "status": "ok", "key": key }),
|_| println!("Unset: {}", key),
);
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn init_mcp(
global: bool,
tool_filter: Option<String>,
generic_config_path: Option<String>,
dry_run: bool,
transport: McpTransport,
mcp_url: &str,
namespace: Option<String>,
auth_token: Option<&str>,
auth_token_env: Option<&str>,
session_override: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
let mut tools = detect_tools(global);
if let Some(path_str) = generic_config_path.as_deref() {
tools.push(AiTool {
name: "Generic",
detected: true,
config_path: PathBuf::from(path_str),
config_type: ConfigType::McpJson,
});
}
let effective_filter = match (&tool_filter, &generic_config_path) {
(None, Some(_)) => Some("Generic".to_string()),
_ => tool_filter.clone(),
};
if global && let Some(ns) = namespace.as_deref() {
println!(
"Global config: tools use workspace `{ns}` from every directory. \
Pass --namespace <workspace> to name another."
);
println!();
}
println!("Detected AI tools:");
for t in &tools {
let icon = if t.detected { "\u{2713}" } else { "\u{2717}" };
println!(" {} {}", icon, t.name);
}
println!();
let targets: Vec<&AiTool> = tools
.iter()
.filter(|t| {
if let Some(f) = effective_filter.as_ref() {
tool_filter_matches(f, t.name)
} else {
t.detected
}
})
.collect();
if targets.is_empty() {
println!("No matching AI tools detected.");
return Ok(());
}
for t in &targets {
let agent_id = tool_slug(t.name);
let session_id = match session_override {
Some(s) => s.to_string(),
None => init_session_id(global, namespace.as_deref(), &agent_id),
};
let mut entry = mcp_server_entry(
&agent_id,
t.name,
transport,
mcp_url,
namespace.as_deref(),
auth_token,
auth_token_env,
&session_id,
);
if transport == McpTransport::Stdio
&& let Some(obj) = entry.as_object_mut()
{
obj.insert(
"env".to_string(),
serde_json::json!({ "CTX_SESSION": session_id }),
);
}
if transport == McpTransport::Http && http_client_needs_bridge(t.name) {
eprintln!(
" \u{2139} {}: no native HTTP MCP support; using the `mcp-remote` \
stdio bridge (requires Node/npx).",
t.name
);
}
if transport == McpTransport::Http {
let is_codex = matches!(t.config_type, ConfigType::Toml);
if is_codex && auth_token_env.is_none() && auth_token.is_some() {
eprintln!(
" \u{26A0} {}: Codex reads the token from an env var — pass \
--auth-token-env <VAR> (and export it); a literal --auth-token \
can't be embedded, so no token was written.",
t.name
);
} else if http_client_needs_bridge(t.name)
&& auth_token.is_none()
&& auth_token_env.is_some()
{
eprintln!(
" \u{26A0} {}: the mcp-remote bridge can't expand an env var — \
pass a literal --auth-token <TOK> to authenticate; none was written.",
t.name
);
} else if auth_token.is_some() && !is_codex {
eprintln!(
" \u{26A0} {}: bearer token written in plaintext into {}.",
t.name,
t.config_path.display()
);
}
}
match t.config_type {
ConfigType::McpJson => {
let mut config: Value = if t.config_path.exists() {
let content = std::fs::read_to_string(&t.config_path)?;
serde_json::from_str(&content).unwrap_or(serde_json::json!({}))
} else {
serde_json::json!({})
};
config
.as_object_mut()
.unwrap()
.entry("mcpServers")
.or_insert(serde_json::json!({}))
.as_object_mut()
.unwrap()
.insert("ctxone".to_string(), entry.clone());
let pretty = serde_json::to_string_pretty(&config)?;
if dry_run {
println!(
" [dry-run] {}: would write {}",
t.name,
t.config_path.display()
);
println!(" {}", pretty);
} else {
if let Some(parent) = t.config_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&t.config_path, pretty)?;
exclude_written_config(&t.config_path);
println!(
" \u{2192} {}: wrote {} \u{2713}",
t.name,
t.config_path.display()
);
}
}
ConfigType::Toml => {
let db_path = canonical_db_path();
if let Some(parent) = std::path::Path::new(&db_path).parent() {
let _ = std::fs::create_dir_all(parent);
}
let existing = if t.config_path.exists() {
std::fs::read_to_string(&t.config_path).unwrap_or_default()
} else {
String::new()
};
let merged = match transport {
McpTransport::Http => {
let url = codex_mcp_http_url(
mcp_url,
namespace.as_deref(),
&session_id,
&agent_id,
);
merge_codex_ctxone_toml_http(&existing, &url, auth_token_env)
}
McpTransport::Stdio => merge_codex_ctxone_toml(
&existing,
&find_hub_binary(),
&db_path,
&agent_id,
&session_id,
),
};
let new_content = match merged {
Ok(s) => s,
Err(e) => {
eprintln!(" \u{2717} {}: could not merge TOML config: {}", t.name, e);
continue;
}
};
if dry_run {
println!(
" [dry-run] {}: would write {}",
t.name,
t.config_path.display()
);
for line in new_content.lines() {
println!(" {}", line);
}
} else {
if let Some(parent) = t.config_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&t.config_path, new_content)?;
exclude_written_config(&t.config_path);
println!(
" \u{2192} {}: wrote {} \u{2713}",
t.name,
t.config_path.display()
);
}
}
}
}
println!();
println!("CtxOne is ready. Try: \"remember that we use BSL-1.1 licensing\"");
Ok(())
}
fn status_glyph(status: &str) -> &'static str {
match status {
"done" => "[x]",
"in_progress" => "[>]",
"abandoned" => "[!]",
_ => "[ ]",
}
}
fn priority_tag(priority: &str) -> &'static str {
match priority {
"critical" => "[CR]",
"high" => "[HI]",
"medium" => "[ME]",
"low" => "[LO]",
_ => "[??]",
}
}
async fn handle_analyze(
action: AnalyzeAction,
server: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
match action {
AnalyzeAction::List => analyze_list(server, format, &client).await,
AnalyzeAction::Estimate { provider, model } => {
analyze_estimate(server, format, provider, model, &client).await
}
}
}
async fn analyze_list(
server: &str,
format: OutputFormat,
client: &reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let sessions: Vec<Value> = client
.get(format!("{server}/api/stats/sessions"))
.send()
.await?
.json()
.await
.unwrap_or_default();
let mut rows: Vec<Value> = Vec::new();
for s in &sessions {
let Some(sid) = s.get("session_id").and_then(|x| x.as_str()) else {
continue;
};
let analysis: Value = match client
.get(format!(
"{server}/api/sessions/{}/analysis",
urlencoding(sid)
))
.send()
.await
{
Ok(r) if r.status().is_success() => r.json().await.unwrap_or(Value::Null),
_ => Value::Null,
};
rows.push(serde_json::json!({
"session": sid,
"source": s.get("source").cloned().unwrap_or(Value::Null),
"analyzed_through": analysis.get("analyzed_through").cloned().unwrap_or(Value::Null),
"analyzed_at": analysis.get("analyzed_at").cloned().unwrap_or(Value::Null),
"provider": analysis.get("provider").cloned().unwrap_or(Value::Null),
"status": if analysis.is_null() { "none" } else { "analyzed" },
}));
}
emit(format, &Value::Array(rows.clone()), |_| {
let analyzed = rows.iter().filter(|r| r["status"] == "analyzed").count();
println!(
"{} sessions · {} analyzed · {} none",
rows.len(),
analyzed,
rows.len() - analyzed
);
for r in &rows {
println!(
" {:<8} through={:<5} {:<10} {}",
r["status"].as_str().unwrap_or(""),
r["analyzed_through"]
.as_u64()
.map(|n| n.to_string())
.unwrap_or_else(|| "-".into()),
r["provider"].as_str().unwrap_or("-"),
r["session"].as_str().unwrap_or(""),
);
}
});
Ok(())
}
async fn analyze_estimate(
server: &str,
format: OutputFormat,
provider_override: Option<String>,
model_override: Option<String>,
client: &reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
use crate::sources::SessionSource;
let cfg = crate::ingest::resolve_extraction_config();
let provider = provider_override
.or_else(|| cfg.as_ref().map(|c| c.provider.key_slug().to_string()))
.unwrap_or_else(|| "anthropic".to_string());
let model = model_override
.or_else(|| cfg.as_ref().map(|c| c.model.clone()))
.unwrap_or_else(|| "claude-haiku-4-5-20251001".to_string());
let price = crate::pricing::price_for(&provider, &model);
let mut sessions_with_work = 0usize;
let mut total_turns = 0usize;
let mut total_chars = 0usize;
for src in crate::sources::all_sources()
.iter()
.filter(|s| s.is_available())
{
for sref in src.discover_all() {
let sid = sref.namespaced_id(src.id());
let analyzed = crate::ingest::hub_analyzed_through(server, &sid, client).await;
let turns = src.parse(&sref);
let mut sturns = 0usize;
let mut schars = 0usize;
for (idx, t) in turns.iter().enumerate() {
if idx < analyzed || !t.is_substantial() {
continue;
}
sturns += 1;
schars += t.to_exchange_text().len();
}
if sturns > 0 {
sessions_with_work += 1;
total_turns += sturns;
total_chars += schars;
}
}
}
let est = crate::pricing::estimate_cost(total_turns, total_chars, &price);
let out = serde_json::json!({
"provider": provider,
"model": model,
"sessions_with_unanalyzed": sessions_with_work,
"turns": est.turns,
"input_tokens": est.input_tokens,
"output_tokens": est.output_tokens,
"est_usd": est.usd,
});
emit(format, &out, |v| {
println!(
"Estimate — {} / {}",
v["provider"].as_str().unwrap_or(""),
v["model"].as_str().unwrap_or("")
);
println!(
" {} sessions with unanalyzed work · {} turns",
v["sessions_with_unanalyzed"].as_u64().unwrap_or(0),
v["turns"].as_u64().unwrap_or(0),
);
println!(
" ~{} input + ~{} output tokens",
v["input_tokens"].as_u64().unwrap_or(0),
v["output_tokens"].as_u64().unwrap_or(0),
);
println!(" est. cost: ${:.2}", v["est_usd"].as_f64().unwrap_or(0.0));
println!(" (approximate; nothing was spent)");
});
Ok(())
}
async fn handle_plan(
action: PlanAction,
server: &str,
branch: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let agent_id = std::env::var("CTX_AGENT_ID").unwrap_or_else(|_| "ctx-cli".to_string());
match action {
PlanAction::New { name, description } => {
let mut body = serde_json::json!({
"name": name.clone(),
"ref": branch,
});
if let Some(d) = description {
body["description"] = serde_json::json!(d);
}
let resp = match client
.post(format!("{}/api/plans", server))
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan new failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
println!("Plan created: {}", v["name"].as_str().unwrap_or(""));
if let Some(s) = v["status"].as_str() {
println!(" status: {}", s);
}
});
}
PlanAction::Relocate { name, to } => {
let body = serde_json::json!({ "to_namespace": to, "ref": branch });
let resp = match client
.post(format!(
"{}/api/plans/{}/relocate",
server,
urlencoding(&name)
))
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan relocate failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
if v["target_already_had_it"].as_bool().unwrap_or(false) {
println!(
"{} already in {} — removed the stale copy from {}",
name,
v["to"].as_str().unwrap_or(&to),
v["from"].as_str().unwrap_or("?"),
);
} else {
println!("Moved {} → {}", name, v["to"].as_str().unwrap_or(&to));
}
});
}
PlanAction::Add {
plan_id,
title,
notes,
priority,
parent,
assigned_to,
blocks,
force,
} => {
let mut body = serde_json::json!({
"title": title,
"priority": priority,
"ref": branch,
});
if force {
body["force"] = serde_json::json!(true);
}
if let Some(n) = notes {
body["notes"] = serde_json::json!(n);
}
if let Some(p) = parent {
body["parent_id"] = serde_json::json!(p);
}
if let Some(a) = assigned_to {
body["assigned_to"] = serde_json::json!(a);
}
if !blocks.is_empty() {
body["blocked_by"] = serde_json::json!(blocks);
}
let url = format!("{}/api/plans/{}/tasks", server, urlencoding(&plan_id));
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan add failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let id = v["id"].as_str().unwrap_or("?");
let title = v["title"].as_str().unwrap_or("");
let pri = v["priority"].as_str().unwrap_or("medium");
println!("Added {} {} {}", id, priority_tag(pri), title);
if let Some(a) = v["assigned_to"].as_str() {
println!(" assigned to: {}", a);
}
if let Some(blockers) = v["blocked_by"].as_array()
&& !blockers.is_empty()
{
let list: Vec<String> = blockers
.iter()
.filter_map(|b| b.as_str().map(String::from))
.collect();
println!(" blocked by: {}", list.join(", "));
}
});
}
PlanAction::Start {
plan_id,
task_id,
reason,
} => {
let body = match reason {
Some(r) => serde_json::json!({"reason": r, "ref": branch}),
None => serde_json::json!({"ref": branch}),
};
let url = format!(
"{}/api/plans/{}/tasks/{}/start",
server,
urlencoding(&plan_id),
urlencoding(&task_id),
);
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan start failed").await;
}
let parsed: Value = resp.json().await?;
if let Some(w) = parsed["warning"].as_str() {
eprintln!(" \u{26A0} {}", w);
}
emit(format, &parsed, |v| {
println!(
"Started {}: {}",
v["id"].as_str().unwrap_or(""),
v["title"].as_str().unwrap_or("")
);
println!(" status: {}", v["status"].as_str().unwrap_or("?"));
});
}
PlanAction::Done {
plan_id,
task_id,
proof,
reason,
} => {
let (kind, value, note) = match parse_proof_spec(&proof) {
Ok(triple) => triple,
Err(e) => {
eprintln!("plan done: {}", e);
std::process::exit(EX_DATAERR);
}
};
let mut proof_obj = serde_json::json!({"kind": kind, "value": value});
if let Some(n) = note {
proof_obj["note"] = serde_json::json!(n);
}
let mut body = serde_json::json!({"proof": proof_obj, "ref": branch});
if let Some(r) = reason {
body["reason"] = serde_json::json!(r);
}
let url = format!(
"{}/api/plans/{}/tasks/{}/complete",
server,
urlencoding(&plan_id),
urlencoding(&task_id),
);
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan done failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
println!(
"Marked {} done: {}",
v["id"].as_str().unwrap_or(""),
v["title"].as_str().unwrap_or("")
);
if let Some(p) = v.get("proof") {
let kind = p["kind"].as_str().unwrap_or("?");
let val = p["value"].as_str().unwrap_or("");
println!(" proof: {} {}", kind, val);
}
if let Some(sat) = v["satisfies"].as_array()
&& !sat.is_empty()
{
let targets: Vec<&str> = sat.iter().filter_map(|x| x.as_str()).collect();
println!(
" \u{21B3} satisfies {} — mark it done too if complete",
targets.join(", ")
);
}
});
}
PlanAction::Abandon {
plan_id,
task_id,
reason,
} => {
let body = serde_json::json!({"reason": reason, "ref": branch});
let url = format!(
"{}/api/plans/{}/tasks/{}/abandon",
server,
urlencoding(&plan_id),
urlencoding(&task_id),
);
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan abandon failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
println!(
"Abandoned {}: {}",
v["id"].as_str().unwrap_or(""),
v["title"].as_str().unwrap_or("")
);
println!(" reason: {}", v["abandoned_reason"].as_str().unwrap_or(""));
});
}
PlanAction::Edit {
plan_id,
task_id,
title,
notes,
priority,
blocks,
clear_blockers,
force,
} => {
let mut body = serde_json::json!({"ref": branch});
if let Some(t) = title {
body["title"] = serde_json::json!(t);
}
if let Some(n) = notes {
body["notes"] = serde_json::json!(n);
}
if let Some(p) = priority {
body["priority"] = serde_json::json!(p);
}
if clear_blockers || !blocks.is_empty() {
body["blocked_by"] = serde_json::json!(blocks);
}
if force {
body["force"] = serde_json::json!(true);
}
let url = format!(
"{}/api/plans/{}/tasks/{}",
server,
urlencoding(&plan_id),
urlencoding(&task_id),
);
let resp = match client
.patch(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan edit failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let id = v["id"].as_str().unwrap_or("");
let changed: Vec<&str> = v["changed"]
.as_array()
.map(|a| a.iter().filter_map(|x| x.as_str()).collect())
.unwrap_or_default();
if changed.is_empty() {
println!("No change to {id}: it already has those values");
} else {
println!("Edited {id} ({})", changed.join(", "));
}
println!(" title: {}", v["title"].as_str().unwrap_or(""));
if let Some(b) = v["blocked_by"].as_array()
&& !b.is_empty()
{
let ids: Vec<&str> = b.iter().filter_map(|x| x.as_str()).collect();
println!(" blocked by: {}", ids.join(", "));
}
});
}
PlanAction::Next {
plan_id,
assigned_to,
me,
include_unassigned,
assigned_only,
in_order,
} => {
let mut parts = vec![format!("ref={}", encode_ref(branch))];
let assignee = if me {
Some(agent_id.clone())
} else {
assigned_to
};
if let Some(a) = assignee {
parts.push(format!("assigned_to={}", urlencoding(&a)));
}
parts.push(format!("include_unassigned={}", include_unassigned));
if assigned_only {
parts.push("assigned_only=true".to_string());
}
if in_order {
parts.push("mode=order".to_string());
}
let url = format!(
"{}/api/plans/{}/next?{}",
server,
urlencoding(&plan_id),
parts.join("&"),
);
let resp = match client
.get(&url)
.header("X-CTXone-Agent", &agent_id)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan next failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
match v.get("task") {
Some(t) if !t.is_null() => {
let pri = t["priority"].as_str().unwrap_or("");
println!(
"Next: {} {} {}",
t["id"].as_str().unwrap_or(""),
priority_tag(pri),
t["title"].as_str().unwrap_or("")
);
if let Some(a) = t["assigned_to"].as_str() {
println!(" assigned to: {}", a);
}
}
_ => {
println!("No pickable tasks.");
}
}
if let Some(active) = v["in_progress"].as_array()
&& !active.is_empty()
{
println!("In progress:");
for t in active {
println!(
" {} {}",
t["id"].as_str().unwrap_or(""),
t["title"].as_str().unwrap_or("")
);
}
}
});
}
PlanAction::List {
status,
all_namespaces,
} => {
let mut url = format!("{}/api/plans?ref={}", server, encode_ref(branch));
if let Some(s) = status {
url.push_str(&format!("&status={}", urlencoding(&s)));
}
if all_namespaces {
url.push_str("&all_namespaces=true");
}
let resp = match client
.get(&url)
.header("X-CTXone-Agent", &agent_id)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan list failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let empty = vec![];
let arr = v.as_array().unwrap_or(&empty);
if arr.is_empty() {
println!("No plans.");
return;
}
for plan in arr {
let name = plan["name"].as_str().unwrap_or("");
let status = plan["status"].as_str().unwrap_or("?");
let counts = &plan["task_counts"];
let done = counts["done"].as_u64().unwrap_or(0);
let in_progress = counts["in_progress"].as_u64().unwrap_or(0);
let pending = counts["pending"].as_u64().unwrap_or(0);
let total = counts["total"].as_u64().unwrap_or(0);
let ns_prefix = plan["namespace"]
.as_str()
.map(|n| format!("[{n}] "))
.unwrap_or_default();
println!(
"{}{:<24} {:<10} {} tasks [{}✓ {}→ {} ]",
ns_prefix, name, status, total, done, in_progress, pending
);
}
});
}
PlanAction::Link {
plan_id,
task_id,
target,
} => {
let url = format!(
"{}/api/plans/{}/tasks/{}/link",
server,
urlencoding(&plan_id),
urlencoding(&task_id),
);
let body = serde_json::json!({ "ref": branch, "target": target });
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan link failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let sat: Vec<&str> = v["satisfies"]
.as_array()
.map(|a| a.iter().filter_map(|x| x.as_str()).collect())
.unwrap_or_default();
println!("{} {} now satisfies: {}", plan_id, task_id, sat.join(", "));
});
}
PlanAction::Stale {
days,
all_namespaces,
} => {
let mut url = format!(
"{}/api/plans/stale?ref={}&days={}",
server,
encode_ref(branch),
days
);
if all_namespaces {
url.push_str("&all_namespaces=true");
}
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan stale failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let empty = vec![];
let arr = v.as_array().unwrap_or(&empty);
if arr.is_empty() {
println!("No stale in-progress tasks (older than {days}d).");
return;
}
println!("Stale in-progress tasks (>{days}d):");
for t in arr {
let ns_prefix = t["namespace"]
.as_str()
.map(|n| format!("[{n}] "))
.unwrap_or_default();
println!(
" {}{} {} ({}d) — {}",
ns_prefix,
t["plan"].as_str().unwrap_or(""),
t["id"].as_str().unwrap_or(""),
t["age_days"].as_i64().unwrap_or(0),
t["title"].as_str().unwrap_or("")
);
}
});
}
PlanAction::Show { plan_id } => {
let url = format!(
"{}/api/plans/{}?ref={}",
server,
urlencoding(&plan_id),
encode_ref(branch)
);
let resp = match client
.get(&url)
.header("X-CTXone-Agent", &agent_id)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan show failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let name = v["name"].as_str().unwrap_or("");
let status = v["status"].as_str().unwrap_or("?");
let desc = v["description"].as_str().unwrap_or("");
println!("Plan: {} — {}", name, desc);
println!(" status: {}", status);
let empty = vec![];
let tasks = v["tasks"].as_array().unwrap_or(&empty);
if tasks.is_empty() {
println!(" (no tasks)");
return;
}
println!();
for task in tasks {
let id = task["id"].as_str().unwrap_or("");
let title = task["title"].as_str().unwrap_or("");
let status = task["status"].as_str().unwrap_or("");
let pri = task["priority"].as_str().unwrap_or("");
let assigned = task["assigned_to"].as_str();
let mut line = format!(
" {} {} {} {}",
status_glyph(status),
id,
priority_tag(pri),
title
);
if let Some(a) = assigned {
line.push_str(&format!(" @{}", a));
}
if task["has_notes"].as_bool().unwrap_or(false) {
line.push_str(" [notes]");
}
println!("{}", line);
if let Some(proof) = task.get("proof")
&& !proof.is_null()
{
let kind = proof["kind"].as_str().unwrap_or("?");
let val = proof["value"].as_str().unwrap_or("");
println!(" proof: {} {}", kind, val);
}
if status == "abandoned"
&& let Some(reason) = task["abandoned_reason"].as_str()
{
println!(" reason: {}", reason);
}
let blockers: Vec<&str> = task["blocked_by"]
.as_array()
.map(|arr| arr.iter().filter_map(|b| b.as_str()).collect())
.unwrap_or_default();
if !blockers.is_empty() {
println!(" blocked by: {}", blockers.join(", "));
}
}
});
}
PlanAction::Tasks { plan_id, task_id } => {
let url = match &task_id {
Some(id) => format!(
"{}/api/plans/{}/tasks/{}?ref={}",
server,
urlencoding(&plan_id),
urlencoding(id),
encode_ref(branch)
),
None => format!(
"{}/api/plans/{}/tasks?ref={}",
server,
urlencoding(&plan_id),
encode_ref(branch)
),
};
let resp = match client
.get(&url)
.header("X-CTXone-Agent", &agent_id)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan tasks failed").await;
}
let parsed: Value = resp.json().await?;
let parsed = if task_id.is_some() {
Value::Array(vec![parsed])
} else {
parsed
};
let show_notes = task_id.is_some();
emit(format, &parsed, |v| {
let empty = vec![];
let tasks = v.as_array().unwrap_or(&empty);
if tasks.is_empty() {
println!("(no tasks)");
return;
}
for task in tasks {
let id = task["id"].as_str().unwrap_or("");
let title = task["title"].as_str().unwrap_or("");
let status = task["status"].as_str().unwrap_or("");
let pri = task["priority"].as_str().unwrap_or("");
let assigned = task["assigned_to"].as_str();
let notes = task["notes"].as_str();
let mut line = format!(
"{} {} {} {}",
status_glyph(status),
id,
priority_tag(pri),
title
);
if let Some(a) = assigned {
line.push_str(&format!(" @{}", a));
}
if notes.is_some() && !show_notes {
line.push_str(" [notes]");
}
println!("{}", line);
if let Some(n) = notes.filter(|_| show_notes) {
println!();
for l in n.lines() {
println!(" {l}");
}
}
}
});
}
PlanAction::Unpack {
plan_id,
all: _,
dry_run,
} => {
let names: Vec<String> = match plan_id {
Some(p) => vec![p],
None => {
let url = format!("{}/api/plans?ref={}", server, encode_ref(branch));
let resp = match client
.get(&url)
.header("X-CTXone-Agent", &agent_id)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan unpack failed").await;
}
let plans: Value = resp.json().await?;
plans
.as_array()
.map(|a| {
a.iter()
.filter_map(|p| p["name"].as_str().map(str::to_string))
.collect()
})
.unwrap_or_default()
}
};
let mut reports = Vec::new();
for name in &names {
let url = format!(
"{}/api/plans/{}/unpack?ref={}&dry_run={}",
server,
urlencoding(name),
encode_ref(branch),
dry_run
);
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, &format!("plan unpack {name} failed")).await;
}
reports.push(resp.json::<Value>().await?);
}
let out = Value::Array(reports);
emit(format, &out, |v| {
let empty = vec![];
let (mut moved, mut kept) = (0, 0);
for r in v.as_array().unwrap_or(&empty) {
let unpacked = r["unpacked"].as_array().map_or(0, Vec::len);
let held = r["kept"].as_array().map_or(0, Vec::len);
moved += unpacked;
kept += held;
if unpacked + held > 0 {
println!(
" {}: {} {}{}",
r["plan"].as_str().unwrap_or("?"),
unpacked,
if dry_run { "to unpack" } else { "unpacked" },
if held > 0 {
format!(", {held} kept (notes already set)")
} else {
String::new()
}
);
}
}
println!(
"{} {} task(s){}{}",
if dry_run { "Would unpack" } else { "Unpacked" },
moved,
if kept > 0 {
format!("; kept {kept}")
} else {
String::new()
},
if dry_run {
" (dry run: nothing written)"
} else {
""
}
);
});
}
PlanAction::Archive { plan_id } => {
let url = format!(
"{}/api/plans/{}/archive?ref={}",
server,
urlencoding(&plan_id),
urlencoding(&branch),
);
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&serde_json::json!({"ref": branch}))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan archive failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
println!("Archived plan {}", v["name"].as_str().unwrap_or(""));
});
}
PlanAction::Close { plan_id, summary } => {
let url = format!(
"{}/api/plans/{}/close?ref={}",
server,
urlencoding(&plan_id),
urlencoding(&branch)
);
let body = serde_json::json!({ "summary": summary });
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan close failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let plan_name = v["plan"]["name"].as_str().unwrap_or("");
println!("Closed plan {}", plan_name);
if let Some(r) = v["reminder"].as_str() {
println!(" {}", r);
}
});
}
PlanAction::Complete {
plan_id,
summary,
reason,
} => {
let url = format!(
"{}/api/plans/{}/force_complete?ref={}",
server,
urlencoding(&plan_id),
urlencoding(&branch)
);
let body = serde_json::json!({ "summary": summary, "reason": reason });
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan complete failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let plan_name = v["plan"]["name"].as_str().unwrap_or("");
let abandoned = v["abandoned_task_ids"]
.as_array()
.map(|a| a.len())
.unwrap_or(0);
println!(
"Force-completed plan {} ({} task{} abandoned)",
plan_name,
abandoned,
if abandoned == 1 { "" } else { "s" }
);
if let Some(arr) = v["abandoned_task_ids"].as_array() {
for id in arr {
if let Some(s) = id.as_str() {
println!(" - {}", s);
}
}
}
if let Some(r) = v["reminder"].as_str() {
println!(" {}", r);
}
});
}
PlanAction::Move {
plan_id,
target,
replace_archived,
} => {
let url = format!(
"{}/api/plans/{}/move?ref={}",
server,
urlencoding(&plan_id),
urlencoding(&branch)
);
let body = serde_json::json!({
"target_ref": target,
"replace_archived": replace_archived,
});
let resp = match client
.post(&url)
.header("X-CTXone-Agent", &agent_id)
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "plan move failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let plan_name = v["plan"]["name"].as_str().unwrap_or("");
let count = v["task_count"].as_u64().unwrap_or(0);
println!(
"Moved plan {} from {} to {} ({} task{})",
plan_name,
v["source_ref"].as_str().unwrap_or(""),
v["target_ref"].as_str().unwrap_or(""),
count,
if count == 1 { "" } else { "s" }
);
});
}
}
Ok(())
}
async fn handle_taint(
action: TaintAction,
server: &str,
branch: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let agent_id = std::env::var("CTX_AGENT_ID").unwrap_or_else(|_| "ctx-cli".to_string());
let agent_id = agent_id.as_str();
match action {
TaintAction::List {
path_prefix,
kind,
include_resolved,
} => {
let mut url = format!("{}/api/taint?include_resolved={}", server, include_resolved);
if let Some(p) = &path_prefix {
url.push_str(&format!("&path_prefix={}", urlencoding(p)));
}
if let Some(k) = &kind {
url.push_str(&format!("&kind={}", urlencoding(k)));
}
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "taint list failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let empty = vec![];
let taints = v["taints"].as_array().unwrap_or(&empty);
if taints.is_empty() {
println!("(no taints)");
return;
}
for t in taints {
let id = t["id"].as_str().unwrap_or("");
let kind = t["kind"].as_str().unwrap_or("?");
let name = t["name"].as_str().unwrap_or("");
let path = t["path"].as_str().unwrap_or("");
let sev = t["severity"].as_str().unwrap_or("");
let resolved = t["resolved_at"].as_str().is_some();
let mark = if resolved { "[resolved] " } else { "" };
println!("{}{} {} {} {} — {}", mark, id, kind, sev, path, name);
}
});
}
TaintAction::Check {
path,
agent_id: who,
confidence,
} => {
let who = who.unwrap_or_else(|| agent_id.to_string());
let url = format!(
"{}/api/taint/check?path={}&agent_id={}&confidence={}",
server,
urlencoding(&path),
urlencoding(&who),
confidence,
);
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "taint check failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let can_write = v["can_write"].as_bool().unwrap_or(false);
let isolated = v["isolated"].as_bool().unwrap_or(false);
let req = v["required_confidence"].as_f64().unwrap_or(0.0);
println!(
"can_write: {}{}",
can_write,
if isolated { " (isolated)" } else { "" }
);
println!("required_confidence: {:.2}", req);
if let Some(eff) = v["effect"].as_str() {
println!("effect: {}", eff);
}
if let Some(id) = v["matching_taint_id"].as_str() {
println!("matching_taint_id: {}", id);
}
let warnings = v["warnings"].as_array().cloned().unwrap_or_default();
if !warnings.is_empty() {
println!("warnings:");
for w in &warnings {
if let Some(s) = w.as_str() {
println!(" - {}", s);
}
}
}
});
}
TaintAction::Apply {
path,
name,
kind,
effect,
severity,
reason,
authorized,
} => {
let mut body = serde_json::json!({
"path": path,
"name": name,
"kind": kind,
"effect": effect.unwrap_or_else(|| "warn".to_string()),
"severity": severity,
"reason": reason,
"agent_id": agent_id,
"ref_name": branch,
});
if !authorized.is_empty() {
body["authorized_agents"] = serde_json::json!(authorized);
}
let url = format!("{}/api/taint", server);
let resp = match client.post(&url).json(&body).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "taint apply failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let id = v["taint_id"].as_str().unwrap_or("");
let path = v["path"].as_str().unwrap_or("");
println!("Applied {} on {}", id, path);
});
}
TaintAction::Remove { taint_id, reason } => {
let body = serde_json::json!({
"reason": reason,
"agent_id": agent_id,
"ref_name": branch,
});
let url = format!("{}/api/taint/{}", server, urlencoding(&taint_id));
let resp = match client.delete(&url).json(&body).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "taint remove failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let at = v["resolved_at"].as_str().unwrap_or("?");
println!("Resolved {} at {}", taint_id, at);
});
}
}
Ok(())
}
async fn handle_db(
action: DbAction,
server: &str,
branch: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
match action {
DbAction::Export { out } => {
let url = format!("{}/api/export?ref={}", server, encode_ref(branch));
let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "db export failed").await;
}
let parsed: Value = resp.json().await?;
let pretty = serde_json::to_string_pretty(&parsed)?;
let count = parsed["count"].as_u64().unwrap_or(0);
match out {
Some(path) => {
std::fs::write(&path, &pretty)?;
eprintln!("Exported {count} paths (branch {branch}) → {path}");
}
None => println!("{pretty}"),
}
}
DbAction::Import { file } => {
let content = std::fs::read_to_string(&file)?;
let snapshot: Value = serde_json::from_str(&content)
.map_err(|e| format!("{file} is not valid JSON: {e}"))?;
let paths = snapshot.get("paths").cloned().unwrap_or(snapshot);
let body = serde_json::json!({ "ref": branch, "paths": paths });
let resp = match client
.post(format!("{server}/api/import"))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "db import failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
println!(
"Imported {} paths onto branch {branch}.",
v["imported"].as_u64().unwrap_or(0)
);
});
}
DbAction::Backup { suffix } => {
let mut body = serde_json::Map::new();
if let Some(s) = suffix {
body.insert("suffix".into(), Value::String(s));
}
let url = format!("{}/api/admin/backup", server);
let resp = match client.post(&url).json(&Value::Object(body)).send().await {
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "backup failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let path = v.get("path").and_then(|x| x.as_str()).unwrap_or("?");
println!("Snapshot written: {}", path);
});
}
DbAction::Restore { snapshot, to, yes } => {
let lock_path = format!("{}.lock", to);
if std::path::Path::new(&lock_path).exists() {
if let Ok(body) = std::fs::read_to_string(&lock_path)
&& let Some(pid_str) = body.split("\"pid\":").nth(1).map(|s| {
s.chars()
.take_while(|c| c.is_ascii_digit())
.collect::<String>()
})
&& let Ok(pid) = pid_str.parse::<u32>()
&& std::process::Command::new("kill")
.args(["-0", &pid.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
{
eprintln!(
"ctx db restore: hub is running (pid {} holds {}); stop it first",
pid, lock_path
);
std::process::exit(EX_TEMPFAIL);
}
}
if !std::path::Path::new(&snapshot).exists() {
eprintln!("ctx db restore: snapshot not found: {}", snapshot);
std::process::exit(EX_NOINPUT);
}
if !yes {
eprintln!(
"About to restore {} → {}\n current db will be moved to {}.pre-restore-<utc>\nProceed? [y/N] ",
snapshot, to, to
);
use std::io::BufRead;
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
if !matches!(line.trim().to_lowercase().as_str(), "y" | "yes") {
eprintln!("aborted");
std::process::exit(0);
}
}
let suffix = {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
format!("{}", secs) };
let preserved = format!("{}.pre-restore-{}", to, suffix);
if std::path::Path::new(&to).exists() {
std::fs::rename(&to, &preserved)
.map_err(|e| format!("could not rename {} → {}: {}", to, preserved, e))?;
eprintln!("preserved current db at {}", preserved);
}
std::fs::copy(&snapshot, &to)
.map_err(|e| format!("could not copy {} → {}: {}", snapshot, to, e))?;
let result = serde_json::json!({
"status": "ok",
"restored_to": to,
"from_snapshot": snapshot,
"preserved_at": preserved,
});
emit(format, &result, |_| {
println!("Restored {} from {}", to, snapshot);
println!(" previous db preserved at {}", preserved);
println!(" start the hub when ready");
});
}
DbAction::Fsck { repair, yes } => {
if repair && !yes {
eprintln!(
"About to REPAIR: every damaged branch will be rewound to its nearest\n\
fully-readable ancestor commit (the dangling commit is abandoned).\n\
Take a snapshot first: `ctx db backup`.\nProceed? [y/N] "
);
use std::io::BufRead;
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
if !matches!(line.trim().to_lowercase().as_str(), "y" | "yes") {
eprintln!("aborted");
std::process::exit(0);
}
}
let body = serde_json::json!({ "repair": repair });
let resp = match client
.post(format!("{server}/api/fsck"))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "db fsck failed").await;
}
let parsed: Value = resp.json().await?;
let problems = parsed["problems"].as_array().cloned().unwrap_or_default();
emit(format, &parsed, |v| {
let checked = v["checked"].as_u64().unwrap_or(0);
let healthy = v["healthy"].as_u64().unwrap_or(0);
if problems.is_empty() {
println!("fsck: {checked} branch(es) checked, all healthy ✓");
return;
}
println!(
"fsck: {checked} checked, {healthy} healthy, {} PROBLEM(S):",
problems.len()
);
for p in &problems {
let ns = p["namespace"].as_str().unwrap_or("?");
let br = p["branch"].as_str().unwrap_or("?");
let missing = p["missing_object"].as_str().unwrap_or("?");
let anc = p["nearest_readable_ancestor"].as_str();
println!(" ✗ {ns}/{br}");
println!(" missing object: {missing}");
match anc {
Some(a) => println!(" nearest readable ancestor: {a}"),
None => {
println!(" nearest readable ancestor: NONE (corruption at root)")
}
}
if p["repaired"].as_bool().unwrap_or(false) {
println!(
" REPAIRED → rewound to {}",
p["repaired_to"].as_str().unwrap_or("?")
);
} else if let Some(err) = p["repair_error"].as_str() {
println!(" repair FAILED: {err}");
}
}
if !repair {
println!(
"\nRun `ctx db fsck --repair` to rewind damaged refs (snapshot first)."
);
}
});
if !problems.is_empty() && !repair {
std::process::exit(1);
}
}
DbAction::Upgrade { check } => {
let probe = match client
.post(format!("{server}/api/db/upgrade"))
.json(&serde_json::json!({ "check": true }))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !probe.status().is_success() {
http_error_exit(probe, "db upgrade check failed").await;
}
let status: Value = probe.json().await?;
let cur = status["current_version"].as_u64().unwrap_or(0);
let target = status["target_version"].as_u64().unwrap_or(0);
let pending = status["pending"].as_bool().unwrap_or(false);
if check {
emit(format, &status, |_| {
if pending {
println!(
"schema: at v{cur}, target v{target} — {} migration(s) pending",
target - cur
);
println!("run `ctx db upgrade` to apply (snapshots first).");
} else {
println!("schema: at v{cur} — up to date ✓");
}
});
return Ok(());
}
if !pending {
emit(format, &status, |_| {
println!("schema: at v{cur} — already up to date, nothing to do ✓");
});
return Ok(());
}
let backup = match client
.post(format!("{server}/api/admin/backup"))
.json(&serde_json::json!({}))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if backup.status().is_success() {
if let Ok(b) = backup.json::<Value>().await
&& let Some(path) = b["path"].as_str()
{
eprintln!("snapshot: {path}");
}
} else {
eprintln!("warning: snapshot failed; continuing (migrations are version-guarded)");
}
let resp = match client
.post(format!("{server}/api/db/upgrade"))
.json(&serde_json::json!({ "check": false }))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "db upgrade failed").await;
}
let done: Value = resp.json().await?;
let now = done["current_version"].as_u64().unwrap_or(cur);
let mut problems = 0usize;
if let Ok(r) = client
.post(format!("{server}/api/fsck"))
.json(&serde_json::json!({ "repair": false }))
.send()
.await
&& let Ok(v) = r.json::<Value>().await
{
problems = v["problems"].as_array().map(|a| a.len()).unwrap_or(0);
}
emit(format, &done, |_| {
println!("schema: upgraded v{cur} → v{now} ✓");
if problems == 0 {
println!("integrity: fsck clean ✓");
} else {
println!("integrity: fsck found {problems} problem(s) — run `ctx db fsck`");
}
});
}
}
Ok(())
}
async fn handle_docs(
action: DocsAction,
server: &str,
branch: &str,
format: OutputFormat,
client: reqwest::Client,
) -> Result<(), Box<dyn std::error::Error>> {
let print_entry = |d: &Value| {
let status = d["status"].as_str().unwrap_or("?");
let scope = d["scope"]
.as_str()
.map(|s| format!(" — {s}"))
.unwrap_or_default();
let answers = d["answers"]
.as_str()
.map(|s| format!("\n answers: {s}"))
.unwrap_or_default();
println!(
" {} [{}]{}{}",
d["path"].as_str().unwrap_or(""),
status,
scope,
answers
);
};
match action {
DocsAction::Add {
path,
status,
scope,
owner,
answers,
supersedes,
verified_commit,
} => {
let body = serde_json::json!({
"ref": branch, "path": path, "status": status, "scope": scope,
"owner": owner, "answers": answers, "supersedes": supersedes,
"last_verified_commit": verified_commit,
});
let resp = match client
.post(format!("{server}/api/docs"))
.json(&body)
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "docs add failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
println!(
"Registered {} [{}]",
v["path"].as_str().unwrap_or(""),
v["status"].as_str().unwrap_or("")
);
});
}
DocsAction::List => {
let resp = match client
.get(format!("{server}/api/docs?ref={}", encode_ref(branch)))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "docs list failed").await;
}
let parsed: Value = resp.json().await?;
emit(format, &parsed, |v| {
let empty = vec![];
let arr = v.as_array().unwrap_or(&empty);
if arr.is_empty() {
println!("No registered docs.");
return;
}
println!("Registered docs:");
for d in arr {
print_entry(d);
}
});
}
DocsAction::Find { query } => {
let resp = match client
.get(format!("{server}/api/docs?ref={}", encode_ref(branch)))
.send()
.await
{
Ok(r) => r,
Err(e) => unreachable_exit(server, e),
};
if !resp.status().is_success() {
http_error_exit(resp, "docs find failed").await;
}
let parsed: Value = resp.json().await?;
let q = query.to_lowercase();
let matches: Vec<Value> = parsed
.as_array()
.map(|a| {
a.iter()
.filter(|d| {
["path", "scope", "answers", "owner"].iter().any(|k| {
d[*k]
.as_str()
.map(|s| s.to_lowercase().contains(&q))
.unwrap_or(false)
})
})
.cloned()
.collect()
})
.unwrap_or_default();
emit(format, &Value::Array(matches.clone()), |_| {
if matches.is_empty() {
println!("No docs match '{query}'.");
return;
}
for d in &matches {
print_entry(d);
}
});
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn a_reminder_runs_here_only_when_the_hub_says_so() {
assert!(trusted_here(&serde_json::json!({ "trusted_here": true })));
assert!(!trusted_here(&serde_json::json!({ "trusted_here": false })));
assert!(!trusted_here(&serde_json::json!({ "id": "r1" })));
}
use super::*;
use serde_json::json;
#[test]
fn parse_bool_takes_the_usual_spellings() {
for v in ["true", "TRUE", "1", "yes", "on", " On "] {
assert_eq!(parse_bool(v), Some(true), "{v:?}");
}
for v in ["false", "0", "no", "off"] {
assert_eq!(parse_bool(v), Some(false), "{v:?}");
}
for v in ["", "maybe", "2"] {
assert_eq!(parse_bool(v), None, "{v:?}");
}
}
#[test]
fn remote_turns_are_off_unless_opted_in() {
let mut cfg = CtxConfig::default();
assert!(!remote_turns_opted_in(None, &cfg), "off by default");
cfg.set_key("remote_turns", "true").unwrap();
assert!(remote_turns_opted_in(None, &cfg), "config opts in");
assert!(
!remote_turns_opted_in(Some("0"), &cfg),
"CTX_REMOTE_TURNS=0 overrides the config"
);
assert!(
!remote_turns_opted_in(Some("perhaps"), &cfg),
"an unrecognised value counts as no"
);
assert!(
remote_turns_opted_in(Some(""), &cfg),
"an empty variable falls back to the config"
);
let off = CtxConfig::default();
assert!(remote_turns_opted_in(Some("1"), &off), "env opts in alone");
}
#[test]
fn remote_turns_config_key_round_trips() {
let mut cfg = CtxConfig::default();
assert_eq!(cfg.get_key("remote_turns").unwrap(), "");
cfg.set_key("remote_turns", "yes").unwrap();
assert_eq!(cfg.get_key("remote_turns").unwrap(), "true");
assert!(cfg.set_key("remote_turns", "sometimes").is_err());
assert_eq!(cfg.get_key("remote_turns").unwrap(), "true");
cfg.unset_key("remote_turns").unwrap();
assert_eq!(cfg.get_key("remote_turns").unwrap(), "");
assert!(
!toml::to_string(&CtxConfig::default())
.unwrap()
.contains("remote_turns")
);
}
#[test]
fn embedded_agents_md_matches_docs() {
let docs = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/AGENTS.md");
let Ok(text) = std::fs::read_to_string(&docs) else {
return;
};
assert_eq!(
EMBEDDED_AGENTS_MD, text,
"cli/assets/AGENTS.md has drifted from docs/AGENTS.md; copy the docs file over it"
);
}
#[test]
fn effective_namespace_is_always_concrete() {
assert_eq!(Cli::effective_namespace(Some("ctxone")), "ctxone");
assert_eq!(Cli::effective_namespace(None), DEFAULT_NAMESPACE);
assert_eq!(
DEFAULT_NAMESPACE, "default",
"must match Namespace::DEFAULT on the hub"
);
}
#[test]
fn every_client_sends_a_namespace_header() {
let f = ClientFactory::default();
for ns in [None, Some("ctxone")] {
let _ = f.build(ns); }
assert_eq!(Cli::effective_namespace(None), "default");
}
#[test]
fn a_secret_findings_forget_command_names_only_what_differs() {
let scan = SecretsScan {
workspace: "repo-a",
branch: "main",
only: None,
turns: false,
all: false,
};
assert_eq!(
forget_command("repo-a", "main", "/memory/ci/f1", &scan),
"ctx forget /memory/ci/f1"
);
assert_eq!(
forget_command("repo-a", "feat-x", "/memory/ci/f1", &scan),
"ctx --branch feat-x forget /memory/ci/f1"
);
assert_eq!(
forget_command("repo-b", "main", "/sessions/s1/summary", &scan),
"ctx --namespace repo-b forget /sessions/s1/summary"
);
assert_eq!(
forget_command(PERSONAL_NAMESPACE, "main", "/memory/me/f2", &scan),
"ctx forget --personal /memory/me/f2"
);
assert_eq!(
forget_command("repo-a", "main", "/memory/odd topic/it's", &scan),
r"ctx forget '/memory/odd topic/it'\''s'"
);
}
#[test]
fn urlencoding_escapes_spaces() {
assert_eq!(urlencoding("hello world"), "hello%20world");
}
#[test]
fn urlencoding_escapes_ampersand_and_question() {
assert_eq!(urlencoding("a&b?c"), "a%26b%3Fc");
}
#[test]
fn urlencoding_passthrough_safe_chars() {
assert_eq!(urlencoding("abc123"), "abc123");
}
#[test]
fn parse_markdown_sections_h1_split() {
let md = "# First\n\nbody of first\n\n# Second\n\nbody of second\n";
let sections = parse_markdown_sections(md);
assert_eq!(sections.len(), 2);
assert_eq!(sections[0].title, "First");
assert_eq!(sections[0].body, "body of first");
assert_eq!(sections[1].title, "Second");
assert_eq!(sections[1].body, "body of second");
}
#[test]
fn parse_markdown_sections_h2_split() {
let md = "## One\n\ntext one\n\n## Two\n\ntext two";
let sections = parse_markdown_sections(md);
assert_eq!(sections.len(), 2);
assert_eq!(sections[0].title, "One");
assert_eq!(sections[1].title, "Two");
}
#[test]
fn parse_markdown_sections_h3_does_not_split() {
let md = "# Top\n\nintro\n\n### Sub\n\ndeep content\n";
let sections = parse_markdown_sections(md);
assert_eq!(sections.len(), 1);
assert_eq!(sections[0].title, "Top");
assert!(sections[0].body.contains("intro"));
assert!(sections[0].body.contains("### Sub"));
assert!(sections[0].body.contains("deep content"));
}
#[test]
fn parse_markdown_sections_intro_before_first_heading() {
let md = "some preamble\n\nmore preamble\n\n# First\n\nbody\n";
let sections = parse_markdown_sections(md);
assert_eq!(sections.len(), 2);
assert_eq!(sections[0].title, "Intro");
assert_eq!(sections[0].body, "some preamble\n\nmore preamble");
assert_eq!(sections[1].title, "First");
}
#[test]
fn parse_markdown_sections_empty_body_skipped() {
let md = "# Only heading\n";
let sections = parse_markdown_sections(md);
assert_eq!(sections.len(), 0); }
#[test]
fn parse_markdown_sections_empty_input() {
let sections = parse_markdown_sections("");
assert_eq!(sections.len(), 0);
}
#[test]
fn extract_id_prefers_name() {
let v = json!({ "name": "main", "commit_id": "sg_abc", "id": "xyz" });
assert_eq!(extract_id(&v), Some("main"));
}
#[test]
fn extract_id_falls_back_to_commit_id() {
let v = json!({ "commit_id": "sg_abc", "path": "/foo" });
assert_eq!(extract_id(&v), Some("sg_abc"));
}
#[test]
fn extract_id_falls_back_to_path() {
let v = json!({ "path": "/memory/facts/123" });
assert_eq!(extract_id(&v), Some("/memory/facts/123"));
}
#[test]
fn extract_id_none_for_empty_object() {
let v = json!({});
assert_eq!(extract_id(&v), None);
}
#[test]
fn extract_id_none_for_array() {
let v = json!([1, 2, 3]);
assert_eq!(extract_id(&v), None);
}
#[test]
fn canonical_db_path_ends_with_memory_db() {
let p = canonical_db_path();
assert!(!p.is_empty());
assert!(
p.ends_with("memory.db"),
"canonical db path should end with memory.db, got: {}",
p
);
assert!(
p.contains("ctxone"),
"canonical db path should contain 'ctxone', got: {}",
p
);
}
#[test]
fn ctx_config_default_is_empty() {
let cfg = CtxConfig::default();
assert!(cfg.server.is_none());
assert!(cfg.branch.is_none());
assert!(cfg.format.is_none());
}
#[test]
fn ctx_config_set_and_get_round_trip() {
let mut cfg = CtxConfig::default();
cfg.set_key("server", "http://example.com:3001").unwrap();
cfg.set_key("branch", "dev").unwrap();
cfg.set_key("format", "json").unwrap();
assert_eq!(cfg.get_key("server").unwrap(), "http://example.com:3001");
assert_eq!(cfg.get_key("branch").unwrap(), "dev");
assert_eq!(cfg.get_key("format").unwrap(), "json");
}
#[test]
fn ctx_config_set_rejects_unknown_key() {
let mut cfg = CtxConfig::default();
assert!(cfg.set_key("hostname", "foo").is_err());
}
#[test]
fn ctx_config_set_rejects_invalid_format() {
let mut cfg = CtxConfig::default();
assert!(cfg.set_key("format", "yaml").is_err());
}
#[test]
fn ctx_config_unset_clears_value() {
let mut cfg = CtxConfig::default();
cfg.set_key("server", "http://example.com").unwrap();
assert_eq!(cfg.get_key("server").unwrap(), "http://example.com");
cfg.unset_key("server").unwrap();
assert_eq!(cfg.get_key("server").unwrap(), "");
assert!(cfg.server.is_none());
}
#[test]
fn ctx_config_toml_round_trip() {
let mut cfg = CtxConfig::default();
cfg.set_key("server", "http://example.com:3001").unwrap();
cfg.set_key("format", "id").unwrap();
let serialized = toml::to_string(&cfg).unwrap();
let deserialized: CtxConfig = toml::from_str(&serialized).unwrap();
assert_eq!(
deserialized.server.as_deref(),
Some("http://example.com:3001")
);
assert_eq!(deserialized.format, Some(OutputFormat::Id));
assert_eq!(deserialized.branch, None);
}
fn raw_with_no_flags() -> RawCli {
RawCli {
server: None,
branch: None,
format: None,
session: None,
namespace: None,
token: None,
command: Commands::Status,
}
}
#[test]
fn cli_resolution_uses_hardcoded_defaults_when_nothing_set() {
let cli = Cli::from_raw(raw_with_no_flags(), &CtxConfig::default());
assert_eq!(cli.server, "http://localhost:3001");
assert_eq!(cli.branch, "main");
assert_eq!(cli.format, OutputFormat::Text);
}
#[test]
fn cli_resolution_uses_config_when_no_flag_or_env() {
let mut config = CtxConfig::default();
config.set_key("server", "http://config:3001").unwrap();
config.set_key("branch", "dev").unwrap();
let cli = Cli::from_raw(raw_with_no_flags(), &config);
assert_eq!(cli.server, "http://config:3001");
assert_eq!(cli.branch, "dev");
assert_eq!(cli.format, OutputFormat::Text); }
#[test]
fn cli_resolution_flag_overrides_config() {
let mut config = CtxConfig::default();
config.set_key("server", "http://config:3001").unwrap();
let mut raw = raw_with_no_flags();
raw.server = Some("http://flag:3001".to_string());
let cli = Cli::from_raw(raw, &config);
assert_eq!(cli.server, "http://flag:3001");
}
#[test]
fn count_tokens_empty_string() {
assert_eq!(count_tokens_cl100k(""), 0);
}
#[test]
fn count_tokens_single_word() {
assert_eq!(count_tokens_cl100k("hello"), 1);
}
#[test]
fn count_tokens_short_sentence() {
assert_eq!(
count_tokens_cl100k("The quick brown fox jumps over the lazy dog"),
9
);
}
#[test]
fn count_tokens_multiple_calls_consistent() {
let a = count_tokens_cl100k("CtxOne memory layer");
let b = count_tokens_cl100k("CtxOne memory layer");
assert_eq!(a, b);
assert!(a > 0);
}
#[test]
fn codex_merge_creates_entry_in_empty_config() {
let out = merge_codex_ctxone_toml(
"",
"/usr/local/bin/ctxone-hub",
"/home/user/.ctxone/memory.db",
"codex",
"proj-abc123",
)
.expect("merge should succeed on empty input");
assert!(out.contains("[mcp_servers.ctxone]"));
assert!(out.contains("command = \"/usr/local/bin/ctxone-hub\""));
assert!(out.contains("--path"));
assert!(out.contains("/home/user/.ctxone/memory.db"));
assert!(out.contains("--agent-id"));
assert!(out.contains("\"codex\""));
assert!(out.contains("CTX_SESSION"));
assert!(out.contains("proj-abc123"));
}
#[test]
fn codex_merge_preserves_other_mcp_servers() {
let existing = r#"
[mcp_servers.linear]
command = "wsl"
args = ["npx", "-y", "mcp-remote", "https://mcp.linear.app/sse"]
"#;
let out = merge_codex_ctxone_toml(existing, "/bin/ctxone-hub", "/db", "codex", "proj-x")
.expect("merge should succeed");
assert!(out.contains("[mcp_servers.linear]"));
assert!(out.contains("[mcp_servers.ctxone]"));
assert!(out.contains("\"wsl\""));
assert!(out.contains("\"npx\""));
}
#[test]
fn codex_merge_preserves_top_level_keys() {
let existing = r#"
project_trust_level = "workspace-trusted"
some_other_setting = 42
[mcp_servers.figma]
command = "figma-mcp"
"#;
let out = merge_codex_ctxone_toml(existing, "/bin/ctxone-hub", "/db", "codex", "proj-x")
.expect("merge should succeed");
assert!(out.contains("project_trust_level = \"workspace-trusted\""));
assert!(out.contains("some_other_setting = 42"));
assert!(out.contains("[mcp_servers.figma]"));
assert!(out.contains("[mcp_servers.ctxone]"));
}
#[test]
fn codex_merge_is_idempotent() {
let first = merge_codex_ctxone_toml("", "/bin/hub", "/db/main.db", "codex", "proj-x")
.expect("first merge");
let second = merge_codex_ctxone_toml(&first, "/bin/hub", "/db/main.db", "codex", "proj-x")
.expect("second merge");
assert_eq!(first, second);
}
#[test]
fn codex_merge_overwrites_stale_ctxone_entry() {
let existing = r#"
[mcp_servers.ctxone]
command = "/old/path/ctxone-hub"
args = ["--path", "/old/db"]
"#;
let out = merge_codex_ctxone_toml(
existing,
"/new/path/ctxone-hub",
"/new/db",
"codex",
"proj-x",
)
.expect("merge should succeed");
assert!(out.contains("/new/path/ctxone-hub"));
assert!(out.contains("/new/db"));
assert!(!out.contains("/old/path/ctxone-hub"));
assert!(!out.contains("/old/db"));
}
#[test]
fn codex_merge_rejects_invalid_toml() {
let broken = "this is { not valid toml }}";
assert!(merge_codex_ctxone_toml(broken, "/bin/hub", "/db", "codex", "proj-x").is_err());
}
#[test]
fn hub_health_url_derives_from_mcp_url() {
assert_eq!(
hub_health_url("http://localhost:3001/mcp").as_deref(),
Some("http://localhost:3001/api/health")
);
assert_eq!(
hub_health_url("https://hub.example:8443/mcp?namespace=p").as_deref(),
Some("https://hub.example:8443/api/health")
);
assert_eq!(hub_health_url("not-a-url").as_deref(), None);
}
#[test]
fn personal_requests_name_the_namespace_in_the_query() {
assert_eq!(
in_personal("http://hub:3001/api/memory/remember"),
"http://hub:3001/api/memory/remember?namespace=_personal"
);
assert_eq!(
in_personal("http://hub:3001/api/state/main/paths?prefix=/memory/pinned/ctxone-agents"),
"http://hub:3001/api/state/main/paths?prefix=/memory/pinned/ctxone-agents&namespace=_personal"
);
assert_eq!(
in_namespace("http://hub:3001/api/memory/forget", "github-com-a-app"),
"http://hub:3001/api/memory/forget?namespace=github-com-a-app"
);
}
#[test]
fn codex_url_carries_session_and_agent_in_the_query() {
assert_eq!(
codex_mcp_http_url(
"http://localhost:3001/mcp",
Some("p"),
"p:codex:ab12",
"codex"
),
"http://localhost:3001/mcp?namespace=p&session=p:codex:ab12&agent=codex"
);
assert_eq!(
codex_mcp_http_url(
"http://localhost:3001/mcp",
None,
"proj-codex-ab12",
"codex"
),
"http://localhost:3001/mcp?session=proj-codex-ab12&agent=codex"
);
}
#[test]
fn codex_http_merge_writes_url_entry() {
let out = merge_codex_ctxone_toml_http("", "http://localhost:3001/mcp?namespace=p", None)
.expect("http merge");
assert!(out.contains("[mcp_servers.ctxone]"));
assert!(out.contains("url = \"http://localhost:3001/mcp?namespace=p\""));
assert!(!out.contains("command"));
assert!(!out.contains("bearer_token_env_var"));
}
#[test]
fn codex_http_merge_writes_bearer_env_var() {
let out = merge_codex_ctxone_toml_http(
"",
"http://localhost:3001/mcp",
Some("CTXONE_AUTH_TOKEN"),
)
.expect("http merge");
assert!(out.contains("bearer_token_env_var = \"CTXONE_AUTH_TOKEN\""));
}
#[test]
fn codex_http_merge_replaces_stale_stdio_entry() {
let existing = r#"
[mcp_servers.ctxone]
command = "/old/ctxone-hub"
args = ["--path", "/old/db"]
"#;
let out = merge_codex_ctxone_toml_http(existing, "http://localhost:3001/mcp", None)
.expect("http merge");
assert!(out.contains("url = \"http://localhost:3001/mcp\""));
assert!(!out.contains("command"));
assert!(!out.contains("/old/db"));
}
#[test]
fn tool_filter_claude_does_not_match_claude_desktop() {
assert!(tool_filter_matches("claude", "Claude Code"));
assert!(!tool_filter_matches("claude", "Claude Desktop"));
}
#[test]
fn tool_filter_targets_desktop_only_via_full_slug() {
assert!(tool_filter_matches("claude-desktop", "Claude Desktop"));
assert!(!tool_filter_matches("claude-desktop", "Claude Code"));
}
#[test]
fn tool_filter_accepts_documented_aliases() {
for (f, name) in [
("vscode", "VS Code"),
("codex", "Codex"),
("gemini", "Gemini"),
("cursor", "Cursor"),
("grok", "Grok"),
] {
assert!(tool_filter_matches(f, name), "{f} should match {name}");
}
}
#[test]
fn tool_filter_is_not_substring_matching() {
assert!(!tool_filter_matches("code", "Claude Code"));
assert!(tool_filter_matches("code", "VS Code"));
}
#[test]
fn session_id_separates_tools_in_one_workspace() {
let a = compose_session_id(Some("ctxone"), "claude-code", "tok1");
let b = compose_session_id(Some("ctxone"), "codex", "tok1");
assert_ne!(a, b);
assert_eq!(a, "ctxone:claude-code:tok1");
assert_eq!(b, "ctxone:codex:tok1");
}
#[test]
fn session_id_namespaces_default_explicitly() {
assert_eq!(
compose_session_id(Some("default"), "codex", "tok1"),
"default:codex:tok1"
);
}
#[test]
fn session_id_falls_back_without_a_namespace() {
assert_eq!(
compose_session_id(None, "claude-code", "tok1"),
"proj-claude-code-tok1"
);
}
#[test]
fn global_init_names_the_explicit_namespace_else_default() {
assert_eq!(global_init_namespace(None), "default");
assert_eq!(global_init_namespace(Some("team")), "team");
assert_eq!(global_init_namespace(Some(" ")), "default");
}
#[test]
fn global_init_writes_the_same_entry_inside_a_repo_and_outside_one() {
let repo = tempfile::tempdir().unwrap();
git_init(repo.path());
let plain = tempfile::tempdir().unwrap();
let entry_from = |cwd: &std::path::Path, explicit: Option<&str>| {
let ns = global_init_namespace(explicit);
let session = session_id_in(true, Some(&ns), "cursor", cwd);
mcp_server_entry(
"cursor",
"Cursor",
McpTransport::Http,
"http://localhost:3001/mcp",
Some(&ns),
None,
None,
&session,
)
};
let inside = entry_from(repo.path(), None);
assert_eq!(inside, entry_from(plain.path(), None));
assert_eq!(
inside.get("url").and_then(|v| v.as_str()),
Some("http://localhost:3001/mcp?namespace=default")
);
assert_eq!(
entry_from(repo.path(), Some("team"))
.get("url")
.and_then(|v| v.as_str()),
Some("http://localhost:3001/mcp?namespace=team")
);
assert!(!repo.path().join(CHECKOUT_TOKEN_FILE).exists());
assert!(!plain.path().join(CHECKOUT_TOKEN_FILE).exists());
}
#[test]
fn a_global_session_id_names_no_checkout() {
let repo = tempfile::tempdir().unwrap();
git_init(repo.path());
assert_eq!(
session_id_in(true, Some("default"), "cursor", repo.path()),
"default:cursor:global"
);
assert_eq!(
session_id_in(false, Some("app"), "cursor", repo.path()),
format!("app:cursor:{}", checkout_token(repo.path()))
);
}
fn git_init(dir: &std::path::Path) {
std::process::Command::new("git")
.args(["init", "-q"])
.current_dir(dir)
.output()
.expect("git init");
}
#[test]
fn checkout_token_is_stable_across_calls() {
let tmp = tempfile::tempdir().unwrap();
git_init(tmp.path());
let a = checkout_token(tmp.path());
let b = checkout_token(tmp.path());
assert_eq!(a, b, "token must not drift; it is baked into a config file");
assert!(!a.is_empty());
}
#[test]
fn checkout_token_survives_a_directory_rename() {
let parent = tempfile::tempdir().unwrap();
let before = parent.path().join("old-name");
std::fs::create_dir(&before).unwrap();
git_init(&before);
let original = checkout_token(&before);
let after = parent.path().join("new-name");
std::fs::rename(&before, &after).unwrap();
assert_eq!(
checkout_token(&after),
original,
"renaming a checkout must not change its identity"
);
}
#[test]
fn checkout_token_differs_between_checkouts() {
let a = tempfile::tempdir().unwrap();
let b = tempfile::tempdir().unwrap();
git_init(a.path());
git_init(b.path());
assert_ne!(checkout_token(a.path()), checkout_token(b.path()));
}
#[test]
fn checkout_token_is_excluded_from_git() {
let tmp = tempfile::tempdir().unwrap();
git_init(tmp.path());
checkout_token(tmp.path());
let exclude = std::fs::read_to_string(tmp.path().join(".git/info/exclude")).unwrap();
assert!(
exclude.lines().any(|l| l.trim() == CHECKOUT_TOKEN_FILE),
"token file must be locally excluded, got:\n{exclude}"
);
}
#[test]
fn tool_slug_lowercases_and_dashes() {
assert_eq!(tool_slug("Claude Code"), "claude-code");
assert_eq!(tool_slug("VS Code"), "vs-code");
assert_eq!(tool_slug("Cursor"), "cursor");
}
#[test]
fn tool_slug_collapses_punctuation_and_runs_of_whitespace() {
assert_eq!(tool_slug("Claude Code (beta)"), "claude-code-beta");
}
#[test]
fn tool_slug_handles_already_slugged_names() {
assert_eq!(tool_slug("codex"), "codex");
assert_eq!(tool_slug("my-tool"), "my-tool");
}
#[test]
fn tool_slug_trims_trailing_dashes() {
assert_eq!(tool_slug("Tool!"), "tool");
}
#[test]
fn mcp_server_entry_includes_agent_id() {
let entry = mcp_server_entry(
"claude-code",
"Claude Code",
McpTransport::Stdio,
"http://localhost:3001/mcp",
None,
None,
None,
"sess-test",
);
let args = entry
.get("args")
.and_then(|v| v.as_array())
.expect("args should be an array");
let arg_strs: Vec<&str> = args.iter().filter_map(|v| v.as_str()).collect();
assert!(arg_strs.contains(&"--agent-id"));
assert!(arg_strs.contains(&"claude-code"));
}
#[test]
fn mcp_server_entry_http_native_for_claude_code() {
let entry = mcp_server_entry(
"claude-code",
"Claude Code",
McpTransport::Http,
"http://localhost:3001/mcp",
Some("proj-ns"),
None,
None,
"sess-test",
);
assert_eq!(entry.get("type").and_then(|v| v.as_str()), Some("http"));
assert_eq!(
entry.get("url").and_then(|v| v.as_str()),
Some("http://localhost:3001/mcp?namespace=proj-ns")
);
assert!(entry.get("command").is_none(), "native http has no command");
assert_eq!(
entry["headers"]["X-CTXone-Session"].as_str(),
Some("sess-test")
);
assert_eq!(
entry["headers"]["X-CTXone-Agent"].as_str(),
Some("claude-code")
);
assert!(
entry["headers"].get("Authorization").is_none(),
"no token → no auth header"
);
}
#[test]
fn mcp_server_entry_http_native_embeds_literal_token() {
let entry = mcp_server_entry(
"claude-code",
"Claude Code",
McpTransport::Http,
"http://localhost:3001/mcp",
None,
Some("s3cret"),
None,
"sess-test",
);
assert_eq!(
entry["headers"]["Authorization"].as_str(),
Some("Bearer s3cret")
);
}
#[test]
fn mcp_server_entry_http_native_uses_env_ref_when_no_literal() {
let entry = mcp_server_entry(
"cursor",
"Cursor",
McpTransport::Http,
"http://localhost:3001/mcp",
None,
None,
Some("CTXONE_AUTH_TOKEN"),
"sess-test",
);
assert_eq!(
entry["headers"]["Authorization"].as_str(),
Some("Bearer ${CTXONE_AUTH_TOKEN}")
);
}
#[test]
fn mcp_server_entry_http_bridges_claude_desktop() {
let entry = mcp_server_entry(
"claude-desktop",
"Claude Desktop",
McpTransport::Http,
"http://localhost:3001/mcp",
Some("proj-ns"),
None,
None,
"sess-test",
);
assert!(
entry.get("type").is_none(),
"bridge is a stdio command, not type:http"
);
assert_eq!(entry.get("command").and_then(|v| v.as_str()), Some("npx"));
let args: Vec<&str> = entry
.get("args")
.and_then(|v| v.as_array())
.expect("args array")
.iter()
.filter_map(|v| v.as_str())
.collect();
assert!(args.contains(&"mcp-remote"));
assert!(args.contains(&"http://localhost:3001/mcp?namespace=proj-ns"));
assert!(args.contains(&"http-only"));
assert!(args.contains(&"--header"));
assert!(args.contains(&"X-CTXone-Session: sess-test"));
assert!(args.contains(&"X-CTXone-Agent: claude-desktop"));
assert!(
!args.iter().any(|a| a.starts_with("Authorization:")),
"no token → no Authorization header"
);
}
#[test]
fn mcp_server_entry_bridge_adds_literal_header_token() {
let entry = mcp_server_entry(
"claude-desktop",
"Claude Desktop",
McpTransport::Http,
"http://localhost:3001/mcp",
None,
Some("s3cret"),
None,
"sess-test",
);
let args: Vec<String> = entry["args"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect();
assert!(args.iter().any(|a| a == "--header"));
assert!(args.iter().any(|a| a == "Authorization: Bearer s3cret"));
}
#[test]
fn cli_resolution_mixes_sources() {
let mut config = CtxConfig::default();
config.set_key("server", "http://config:3001").unwrap();
let mut raw = raw_with_no_flags();
raw.branch = Some("feature-x".to_string());
let cli = Cli::from_raw(raw, &config);
assert_eq!(cli.server, "http://config:3001");
assert_eq!(cli.branch, "feature-x");
assert_eq!(cli.format, OutputFormat::Text);
}
}