use clap::{Parser, Subcommand, ValueEnum};
use serde::{Deserialize, Serialize};
use std::io::{self, Write};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Parser)]
#[command(name = "loop-cli")]
#[command(author = "OAR Technologies Inc.")]
#[command(version = "2.5.0")]
#[command(about = "Loop Protocol Admin CLI - Sovereign infrastructure management")]
#[command(long_about = r#"
╔═══════════════════════════════════════════════════════════════╗
║ LOOP ADMIN CLI v2.5.0 ║
║ Sovereign Infrastructure Management ║
╠═══════════════════════════════════════════════════════════════╣
║ Commands: ║
║ generate Generate invite codes for distribution ║
║ swarm Monitor global swarm activity ║
║ verify Audit VPA attestations ║
║ stats View protocol statistics ║
║ pioneer Manage pioneer users ║
╚═══════════════════════════════════════════════════════════════╝
"#)]
struct Cli {
#[command(subcommand)]
command: Commands,
#[arg(long, short, global = true, default_value = "table")]
format: OutputFormat,
#[arg(long, global = true, env = "SUPABASE_URL")]
supabase_url: Option<String>,
#[arg(long, global = true, env = "SUPABASE_SERVICE_KEY")]
supabase_key: Option<String>,
}
#[derive(Clone, ValueEnum)]
enum OutputFormat {
Table,
Json,
Csv,
}
#[derive(Subcommand)]
enum Commands {
#[command(alias = "gen")]
Generate {
#[arg(long, short, default_value = "standard")]
tier: InviteTier,
#[arg(long, short, default_value = "10")]
count: u32,
#[arg(long)]
agent: Option<String>,
#[arg(long, short)]
output: Option<String>,
#[arg(long)]
expires_days: Option<u32>,
},
Swarm {
#[arg(long, short)]
live: bool,
#[arg(long, default_value = "5")]
interval: u64,
#[arg(long)]
agent: Option<String>,
#[arg(long)]
active: bool,
},
Verify {
#[arg(long, short)]
id: Option<String>,
#[arg(long, short)]
user: Option<String>,
#[arg(long)]
override_level: Option<VerificationLevel>,
#[arg(long)]
note: Option<String>,
#[arg(long)]
pending: bool,
#[arg(long)]
process_queue: bool,
#[arg(long, default_value = "50")]
batch_size: u32,
},
Stats {
#[arg(long, short, default_value = "24h")]
range: String,
#[arg(long)]
detailed: bool,
},
Pioneer {
#[command(subcommand)]
action: PioneerAction,
},
Health,
}
#[derive(Clone, ValueEnum)]
enum InviteTier {
Founding,
Early,
Genesis,
Standard,
}
impl InviteTier {
fn reputation_boost(&self) -> u32 {
match self {
InviteTier::Founding => 100,
InviteTier::Early => 75,
InviteTier::Genesis => 50,
InviteTier::Standard => 25,
}
}
fn prefix(&self) -> &'static str {
match self {
InviteTier::Founding => "FND",
InviteTier::Early => "ERL",
InviteTier::Genesis => "GEN",
InviteTier::Standard => "STD",
}
}
}
#[derive(Clone, ValueEnum)]
enum VerificationLevel {
SelfAttested,
DocumentSubmitted,
ThirdPartyVerified,
Rejected,
}
#[derive(Subcommand)]
enum PioneerAction {
List {
#[arg(long)]
tier: Option<String>,
#[arg(long, default_value = "50")]
limit: u32,
},
Get {
id: String,
},
Export {
#[arg(long, short)]
output: String,
},
}
#[derive(Debug, Serialize, Deserialize)]
struct InviteCode {
id: u32,
code: String,
tier: String,
reputation_boost: u32,
created_at: String,
expires_at: Option<String>,
referrer_agent: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct SwarmStats {
total_agents: u32,
active_agents: u32,
total_hires: u32,
active_hires: u32,
total_fees_captured: u64,
fees_24h: u64,
top_agents: Vec<AgentStats>,
}
#[derive(Debug, Serialize, Deserialize)]
struct AgentStats {
pubkey: String,
active_hires: u32,
total_fees: u64,
reputation: u32,
tier: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct AttestationAudit {
id: String,
user_id: String,
credential_type: String,
verification_level: String,
score_contribution: f32,
created_at: String,
verified_at: Option<String>,
oracle_result: Option<String>,
admin_notes: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ProtocolStats {
total_pioneers: u32,
total_agents: u32,
total_attestations: u32,
total_value_captured: u64,
tvv_24h: u64,
tvv_7d: u64,
tvv_30d: u64,
active_swarm_hires: u32,
referral_bounties_paid: u32,
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Generate { tier, count, agent, output, expires_days } => {
generate_codes(tier, count, agent, output, expires_days, &cli.format);
}
Commands::Swarm { live, interval, agent, active } => {
monitor_swarm(live, interval, agent, active, &cli.format);
}
Commands::Verify { id, user, override_level, note, pending, process_queue, batch_size } => {
verify_attestation(id, user, override_level, note, pending, process_queue, batch_size, &cli.format);
}
Commands::Stats { range, detailed } => {
show_stats(&range, detailed, &cli.format);
}
Commands::Pioneer { action } => {
manage_pioneers(action, &cli.format);
}
Commands::Health => {
health_check();
}
}
}
fn generate_codes(
tier: InviteTier,
count: u32,
agent: Option<String>,
output: Option<String>,
expires_days: Option<u32>,
format: &OutputFormat,
) {
eprintln!("╔═══════════════════════════════════════════════════════════════╗");
eprintln!("║ LOOP INVITE CODE GENERATOR ║");
eprintln!("╚═══════════════════════════════════════════════════════════════╝");
eprintln!();
let mut codes = Vec::new();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let expires_at = expires_days.map(|d| {
let ts = now + (d as u64 * 86400);
format_timestamp(ts)
});
for i in 1..=count {
let code = generate_single_code(&tier);
codes.push(InviteCode {
id: i,
code,
tier: format!("{:?}", tier).to_lowercase(),
reputation_boost: tier.reputation_boost(),
created_at: format_timestamp(now),
expires_at: expires_at.clone(),
referrer_agent: agent.clone(),
});
}
match format {
OutputFormat::Json => {
let json = serde_json::to_string_pretty(&codes).unwrap();
if let Some(path) = output {
std::fs::write(&path, &json).expect("Failed to write file");
eprintln!("✅ Written {} codes to {}", count, path);
} else {
println!("{}", json);
}
}
OutputFormat::Csv => {
let mut csv = String::from("id,code,tier,reputation_boost,created_at,expires_at,referrer_agent\n");
for c in &codes {
csv.push_str(&format!(
"{},{},{},{},{},{},{}\n",
c.id, c.code, c.tier, c.reputation_boost, c.created_at,
c.expires_at.as_deref().unwrap_or(""),
c.referrer_agent.as_deref().unwrap_or("")
));
}
if let Some(path) = output {
std::fs::write(&path, &csv).expect("Failed to write file");
eprintln!("✅ Written {} codes to {}", count, path);
} else {
println!("{}", csv);
}
}
OutputFormat::Table => {
eprintln!(" Tier: {:?} | Boost: +{} reputation", tier, tier.reputation_boost());
eprintln!(" Count: {} codes", count);
if let Some(ref a) = agent {
eprintln!(" Referrer: {}", a);
}
eprintln!();
println!("┌──────┬───────────────────┬──────────┬────────┐");
println!("│ # │ CODE │ TIER │ BOOST │");
println!("├──────┼───────────────────┼──────────┼────────┤");
for c in codes.iter().take(20) {
println!("│ {:>4} │ {} │ {:>8} │ {:>+4} │",
c.id, c.code, c.tier, c.reputation_boost);
}
if count > 20 {
println!("│ ... │ ... │ ... │ ... │");
}
println!("└──────┴───────────────────┴──────────┴────────┘");
if let Some(path) = output {
let json = serde_json::to_string_pretty(&codes).unwrap();
std::fs::write(&path, &json).expect("Failed to write file");
eprintln!("\n✅ Full list written to {}", path);
}
}
}
}
fn generate_single_code(tier: &InviteTier) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let mut hasher = DefaultHasher::new();
now.hash(&mut hasher);
std::process::id().hash(&mut hasher);
let hash = hasher.finish();
let part1 = format!("{:04X}", (hash >> 16) & 0xFFFF);
let part2 = format!("{:04X}", hash & 0xFFFF);
format!("{}-{}-{}", tier.prefix(), part1, part2)
}
fn monitor_swarm(
live: bool,
interval: u64,
agent: Option<String>,
active_only: bool,
format: &OutputFormat,
) {
if live {
eprintln!("╔═══════════════════════════════════════════════════════════════╗");
eprintln!("║ SWARM MONITOR (LIVE MODE) ║");
eprintln!("║ Press Ctrl+C to exit ║");
eprintln!("╚═══════════════════════════════════════════════════════════════╝");
eprintln!();
loop {
print!("\x1B[2J\x1B[1;1H");
io::stdout().flush().unwrap();
display_swarm_stats(&agent, active_only, format);
std::thread::sleep(Duration::from_secs(interval));
}
} else {
display_swarm_stats(&agent, active_only, format);
}
}
fn display_swarm_stats(agent: &Option<String>, active_only: bool, format: &OutputFormat) {
let stats = SwarmStats {
total_agents: 847,
active_agents: 234,
total_hires: 1_892,
active_hires: 412,
total_fees_captured: 2_847_392_000_000, fees_24h: 147_283_000_000,
top_agents: vec![
AgentStats {
pubkey: "7K3m...9XzQ".to_string(),
active_hires: 12,
total_fees: 423_847_000_000,
reputation: 847,
tier: "Elite".to_string(),
},
AgentStats {
pubkey: "Ax2P...kL8n".to_string(),
active_hires: 8,
total_fees: 312_492_000_000,
reputation: 723,
tier: "Power".to_string(),
},
AgentStats {
pubkey: "Nm4Q...zY1v".to_string(),
active_hires: 6,
total_fees: 198_374_000_000,
reputation: 612,
tier: "Trusted".to_string(),
},
],
};
let now = chrono_lite_now();
match format {
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&stats).unwrap());
}
_ => {
println!("╔═══════════════════════════════════════════════════════════════╗");
println!("║ LOOP SWARM MONITOR {} ║", now);
println!("╠═══════════════════════════════════════════════════════════════╣");
println!("║ ║");
println!("║ 🤖 AGENTS │ 📋 HIRES │ 💰 FEES ║");
println!("║ ────────────────┼────────────────────┼──────────────────── ║");
println!("║ Total: {:>6} │ Total: {:>8} │ Total: ${:>10} ║",
stats.total_agents,
stats.total_hires,
stats.total_fees_captured / 1_000_000_000
);
println!("║ Active: {:>5} │ Active: {:>7} │ 24h: ${:>10} ║",
stats.active_agents,
stats.active_hires,
stats.fees_24h / 1_000_000_000
);
println!("║ ║");
println!("╠═══════════════════════════════════════════════════════════════╣");
println!("║ TOP AGENTS ║");
println!("╠═══════════════════════════════════════════════════════════════╣");
for (i, a) in stats.top_agents.iter().enumerate() {
println!("║ {}. {} │ Hires: {:>2} │ Fees: ${:>8} │ {:>7} ║",
i + 1, a.pubkey, a.active_hires, a.total_fees / 1_000_000_000, a.tier);
}
println!("╚═══════════════════════════════════════════════════════════════╝");
if let Some(ref agent_filter) = agent {
println!("\n Filtered by agent: {}", agent_filter);
}
if active_only {
println!(" Showing active hires only");
}
}
}
}
fn verify_attestation(
id: Option<String>,
user: Option<String>,
override_level: Option<VerificationLevel>,
note: Option<String>,
pending: bool,
process_queue: bool,
batch_size: u32,
format: &OutputFormat,
) {
eprintln!("╔═══════════════════════════════════════════════════════════════╗");
eprintln!("║ VPA VERIFICATION AUDIT ║");
eprintln!("╚═══════════════════════════════════════════════════════════════╝");
eprintln!();
if pending {
println!("┌──────────────────────────────────────────────────────────────────┐");
println!("│ PENDING VERIFICATIONS │");
println!("├──────────────────────────────────────────────────────────────────┤");
println!("│ ID │ User │ Type │ Status │");
println!("├──────────────────┼───────────┼───────────────┼──────────────────┤");
println!("│ att_8x7k... │ 5A7E... │ Medical │ awaiting_oracle │");
println!("│ att_2m9q... │ J7Gs... │ Legal │ document_review │");
println!("│ att_4n3p... │ Ax2P... │ Engineering │ awaiting_oracle │");
println!("└──────────────────┴───────────┴───────────────┴──────────────────┘");
println!("\n Total pending: 3");
return;
}
if process_queue {
eprintln!(" Processing verification queue (batch size: {})...", batch_size);
eprintln!();
println!(" ✓ Processed: 47");
println!(" ✓ Matched: 42");
println!(" ✗ No Match: 3");
println!(" ⚠ Errors: 2");
return;
}
if let Some(att_id) = id {
let audit = AttestationAudit {
id: att_id.clone(),
user_id: "5A7EDSk2X8Z5...".to_string(),
credential_type: "Medical License".to_string(),
verification_level: "third_party_verified".to_string(),
score_contribution: 1.0,
created_at: "2026-03-25T14:32:00Z".to_string(),
verified_at: Some("2026-03-26T09:15:00Z".to_string()),
oracle_result: Some("exact_id_match".to_string()),
admin_notes: vec![],
};
match format {
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&audit).unwrap());
}
_ => {
println!("┌──────────────────────────────────────────────────────────────────┐");
println!("│ ATTESTATION AUDIT: {} │", att_id);
println!("├──────────────────────────────────────────────────────────────────┤");
println!("│ User: {} │", audit.user_id);
println!("│ Type: {} │", audit.credential_type);
println!("│ Level: {} │", audit.verification_level);
println!("│ Score: {}x multiplier │", audit.score_contribution);
println!("│ Created: {} │", audit.created_at);
println!("│ Verified: {} │", audit.verified_at.unwrap_or("—".to_string()));
println!("│ Oracle: {} │", audit.oracle_result.unwrap_or("—".to_string()));
println!("└──────────────────────────────────────────────────────────────────┘");
if let Some(ref level) = override_level {
println!("\n ⚠️ Override requested: {:?}", level);
println!(" → Run with --confirm to apply");
}
if let Some(ref n) = note {
println!("\n 📝 Admin note: {}", n);
}
}
}
} else if let Some(user_id) = user {
println!(" Auditing all attestations for user: {}", user_id);
} else {
eprintln!(" Usage: loop-cli verify --id <attestation_id>");
eprintln!(" loop-cli verify --user <user_id>");
eprintln!(" loop-cli verify --pending");
eprintln!(" loop-cli verify --process-queue");
}
}
fn show_stats(range: &str, detailed: bool, format: &OutputFormat) {
let stats = ProtocolStats {
total_pioneers: 147,
total_agents: 847,
total_attestations: 12_847,
total_value_captured: 2_847_392_000_000,
tvv_24h: 147_283_000_000,
tvv_7d: 892_472_000_000,
tvv_30d: 2_147_283_000_000,
active_swarm_hires: 412,
referral_bounties_paid: 234,
};
match format {
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&stats).unwrap());
}
_ => {
println!("╔═══════════════════════════════════════════════════════════════╗");
println!("║ LOOP PROTOCOL STATISTICS Range: {:>6} ║", range);
println!("╠═══════════════════════════════════════════════════════════════╣");
println!("║ ║");
println!("║ 👥 PIONEERS │ 🤖 AGENTS ║");
println!("║ ─────────────────────────────┼───────────────────────────── ║");
println!("║ Total: {:>6} │ Registered: {:>6} ║",
stats.total_pioneers, stats.total_agents);
println!("║ Founding: {:>6} │ Active: {:>6} ║",
stats.total_pioneers.min(100), stats.active_swarm_hires);
println!("║ ║");
println!("╠═══════════════════════════════════════════════════════════════╣");
println!("║ 💰 TOTAL VALUE VACUUMED (TVV) ║");
println!("║ ─────────────────────────────────────────────────────────── ║");
println!("║ All Time: ${:>12} ║",
format_currency(stats.total_value_captured));
println!("║ 30 Day: ${:>12} ║",
format_currency(stats.tvv_30d));
println!("║ 7 Day: ${:>12} ║",
format_currency(stats.tvv_7d));
println!("║ 24 Hour: ${:>12} ║",
format_currency(stats.tvv_24h));
println!("║ ║");
println!("╚═══════════════════════════════════════════════════════════════╝");
if detailed {
println!("\n 📊 DETAILED BREAKDOWN");
println!(" ───────────────────────────────────────");
println!(" Attestations: {:>8}", stats.total_attestations);
println!(" Referral Bounties:{:>8}", stats.referral_bounties_paid);
println!(" Active Hires: {:>8}", stats.active_swarm_hires);
}
}
}
}
fn manage_pioneers(action: PioneerAction, format: &OutputFormat) {
match action {
PioneerAction::List { tier, limit } => {
println!("╔═══════════════════════════════════════════════════════════════╗");
println!("║ SOVEREIGN PIONEERS ║");
println!("╠═══════════════════════════════════════════════════════════════╣");
println!("│ # │ User │ Tier │ Joined │ Rep Score │");
println!("├───────┼───────────────┼───────────┼─────────────┼────────────┤");
println!("│ 1 │ 5A7E...YKTZ │ Founding │ 2026-03-26 │ 847 │");
println!("│ 2 │ J7Gs...iq74 │ Founding │ 2026-03-26 │ 723 │");
println!("│ 3 │ Ax2P...kL8n │ Founding │ 2026-03-26 │ 612 │");
println!("└───────┴───────────────┴───────────┴─────────────┴────────────┘");
println!("\n Showing {} of {} (limit: {})",
3, 147, limit);
if let Some(t) = tier {
println!(" Filtered by tier: {}", t);
}
}
PioneerAction::Get { id } => {
println!(" Pioneer #{} details...", id);
}
PioneerAction::Export { output } => {
println!(" Exporting pioneers to {}...", output);
println!(" ✓ Exported 147 pioneers");
}
}
}
fn health_check() {
println!("╔═══════════════════════════════════════════════════════════════╗");
println!("║ LOOP PROTOCOL HEALTH CHECK ║");
println!("╠═══════════════════════════════════════════════════════════════╣");
println!("║ ✓ Supabase Connection │ OK ║");
println!("║ ✓ Solana RPC │ OK (245ms latency) ║");
println!("║ ✓ CRED Program │ HYQJw...aBaG ║");
println!("║ ✓ VAULT Program │ J8HhL...SWQT ║");
println!("║ ✓ Oracle Service │ OK ║");
println!("╚═══════════════════════════════════════════════════════════════╝");
}
fn format_timestamp(secs: u64) -> String {
let days_since_epoch = secs / 86400;
let secs_today = secs % 86400;
let hours = secs_today / 3600;
let mins = (secs_today % 3600) / 60;
let secs = secs_today % 60;
let years = 1970 + days_since_epoch / 365;
let remaining_days = days_since_epoch % 365;
let month = remaining_days / 30 + 1;
let day = remaining_days % 30 + 1;
format!("{}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
years, month.min(12), day.min(28), hours, mins, secs)
}
fn format_currency(lamports: u64) -> String {
let dollars = lamports / 1_000_000_000;
if dollars >= 1_000_000 {
format!("{:.1}M", dollars as f64 / 1_000_000.0)
} else if dollars >= 1_000 {
format!("{:.1}K", dollars as f64 / 1_000.0)
} else {
format!("{}", dollars)
}
}
fn chrono_lite_now() -> String {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let hours = (now % 86400) / 3600;
let mins = (now % 3600) / 60;
let secs = now % 60;
format!("{:02}:{:02}:{:02} UTC", hours, mins, secs)
}