turbine-cli 0.1.2

TURBINE command-line interface and daemon (binary name: turbine)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! `turbine` — the single client/daemon binary (plan §9.1).
//!
//! Subcommands:
//! - `start`  : boot the daemon (ingestion + processing + execution + AI + IPC).
//! - `run`    : send a mock scenario to the running daemon over IPC (falls back
//!   to an in-process demo when no daemon is reachable).
//! - `stop`   : gracefully stop the running daemon over IPC.
//! - `status` : print a health snapshot from the running daemon over IPC.
//!
//! The IPC control plane (Phase 7) lives in `turbine-ipc`; the daemon-side command
//! handler is in [`daemon`]. The TUI/web surfaces land in Phases 8–9.

mod daemon;

use std::io::IsTerminal;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use clap::{Parser, Subcommand};
use tracing::info;
use tracing_subscriber::EnvFilter;
use turbine_core::config::Config;
use turbine_ipc::{Request, Response};
use turbine_sdk::Turbine;

#[derive(Parser, Debug)]
#[command(
    name = "turbine",
    version,
    about = "TURBINE — ultra-low-latency smart transaction infrastructure on Solana"
)]
struct Cli {
    /// Path to the TOML configuration file.
    #[arg(short, long, default_value = "turbine.toml", global = true)]
    config: PathBuf,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Boot the daemon: ingestion, processing, execution, TUI, and web server.
    Start {
        /// Disable the live TUI dashboard (stream logs to stdout instead). Auto-
        /// disabled when stdout is not a terminal (e.g. piped or backgrounded).
        #[arg(long)]
        no_tui: bool,
        /// Use SubscribeDeshred for write-lock contention (pre-execution). Requires a
        /// Triton extension Geyser endpoint; falls back to standard Geyser targets if unavailable.
        #[arg(long)]
        deshred: bool,
    },

    /// Send a mock trade scenario to the running daemon over IPC.
    Run {
        /// Scenario name, e.g. `happy-test`, `fail-slippage`.
        scenario: String,
    },

    /// Gracefully stop the running daemon.
    Stop,

    /// Print a health snapshot from the running daemon.
    Status,
}

/// Initialize logging. In TUI mode the terminal is owned by the dashboard, so logs
/// are redirected to a file (`$TMPDIR/turbine.log`) to keep the screen clean;
/// otherwise they stream to stdout as usual.
fn init_tracing(to_file: bool) -> anyhow::Result<()> {
    let filter =
        EnvFilter::try_from_env("TURBINE_LOG").unwrap_or_else(|_| EnvFilter::new("info"));
    if to_file {
        let path = std::env::temp_dir().join("turbine.log");
        let file = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
        eprintln!("TURBINE — launching dashboard; logs → {}", path.display());
        tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_target(false)
            .with_ansi(false)
            .with_writer(move || file.try_clone().expect("clone log file handle"))
            .init();
    } else {
        tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_target(false)
            .init();
    }
    Ok(())
}

/// Phase 4 one-shot demo: warm the inputs the engine needs (blockhash, tip
/// accounts, tip percentiles), seed the slot/leader so the gate opens, then build
/// → price → gate → submit (dry-run by default). Replaced by IPC in Phase 7.
async fn run_local_demo(config: &std::path::Path, scenario: &str) -> anyhow::Result<()> {
    use turbine_core::tips::TipSnapshot;
    use turbine_execute::{ExecutionEngine, TradeIntent};

    // `fail-*` scenarios exercise the Phase 6 AI failure-analyst loop instead.
    if let Some(suffix) = scenario.strip_prefix("fail-") {
        return run_failure_demo(config, suffix).await;
    }

    let cfg = Arc::new(Config::load(config)?);
    info!(%scenario, dry_run = cfg.execution.dry_run, "Phase 4 local execution demo");

    let state = Arc::new(turbine_state::HotState::new(&cfg));

    // Warm blockhash (real if RPC reachable, else a synthetic placeholder).
    match turbine_ingest::blockhash::fetch_latest_blockhash(&cfg.rpc.http_url).await {
        Ok(bh) => {
            info!(blockhash = %bh.blockhash, slot = bh.slot, "fetched warm blockhash");
            state.set_blockhash(bh);
        }
        Err(e) => {
            tracing::warn!("blockhash fetch failed ({e}); using synthetic placeholder");
            state.set_blockhash(turbine_core::blockhash::CachedBlockhash {
                blockhash: "11111111111111111111111111111111".into(),
                last_valid_block_height: 0,
                slot: 0,
                fetched_at: std::time::Instant::now(),
            });
        }
    }

    // Tip accounts (real if reachable, else the engine has nothing to tip).
    match turbine_ingest::tips::fetch_tip_accounts(&cfg.jito.json_rpc_url).await {
        Ok(accts) if !accts.is_empty() => {
            info!(count = accts.len(), "fetched Jito tip accounts");
            state.set_tip_accounts(accts);
        }
        other => {
            if let Err(e) = other {
                tracing::warn!("tip account fetch failed ({e}); using a synthetic tip account");
            }
            state.set_tip_accounts(vec![solana_pubkey::Pubkey::new_from_array([9u8; 32])]);
        }
    }

    // Smoothed tip percentiles (real floor if reachable, else synthetic).
    match turbine_ingest::tips::fetch_tip_floor(&cfg.jito.tip_floor_url).await {
        Ok(t) => {
            info!(p50 = t.p50, p95 = t.p95, "fetched tip floor");
            state.set_tips(TipSnapshot { p25: t.p25, p50: t.p50, p75: t.p75, p95: t.p95, p99: t.p99 });
        }
        Err(e) => {
            tracing::warn!("tip floor fetch failed ({e}); using synthetic percentiles");
            state.set_tips(TipSnapshot { p25: 1_000, p50: 2_000, p75: 5_000, p95: 50_000, p99: 200_000 });
        }
    }

    // Seed slot + leader so the lookahead gate opens immediately (no live Geyser
    // in a one-shot run). dist = gate_min keeps us inside the window.
    let slot = 1_000u64;
    state.set_slot(slot);
    state.set_leader(turbine_core::leader::LeaderView {
        next_jito_leader_slot: Some(slot + cfg.strategy.gate_min),
        slots_until_leader: Some(cfg.strategy.gate_min),
    });
    state.set_geyser_healthy(true);

    // Dry-run demo uses no searcher channel; live submission would pass one.
    let engine = ExecutionEngine::new(cfg.clone(), state.clone(), None)?;
    let report = engine.execute(TradeIntent::mock(scenario)).await?;

    info!(
        label = %report.label,
        congestion = ?report.congestion,
        percentile = ?report.percentile,
        tip_lamports = report.tip_lamports,
        tip_account = %report.tip_account,
        tx_count = report.tx_count,
        bundle_b64_bytes = report.bundle_b64_bytes,
        build_us = report.build_us,
        gate = ?report.gate,
        submit_us = ?report.submit_us,
        bundle_id = ?report.bundle_id,
        dry_run = report.dry_run,
        "scenario complete",
    );
    Ok(())
}

/// Phase 6 demo (revised): drive the **full autonomous loop** for `fail-<class>`.
/// Submit a (dry-run) bundle, inject a failure, and let the AI coordinator
/// classify → store reasoning → rebuild with the fix → resubmit autonomously.
/// When AI is disabled (no API key) a mock analyst stands in so the loop is visible.
async fn run_failure_demo(config: &std::path::Path, class_name: &str) -> anyhow::Result<()> {
    use turbine_ai::{AiEngine, Analyst, AnalystVerdict, RetryAdjustments};
    use turbine_core::tips::TipSnapshot;
    use turbine_core::types::FailureClass;
    use turbine_execute::{ExecutionEngine, FailureEvent, RetryCoordinator, TradeIntent};

    let class = match class_name {
        "blockhash" => FailureClass::BlockhashExpired,
        "tip" => FailureClass::TipTooLow,
        "auction" => FailureClass::AuctionTimeout,
        "dropped" => FailureClass::BundleDropped,
        "transient" => FailureClass::Transient,
        "slippage" => FailureClass::Slippage,
        "account" => FailureClass::AccountInUse,
        "sim" => FailureClass::SimulationError,
        "custom" => FailureClass::ProgramCustom(6001),
        other => {
            tracing::warn!(%other, "unknown fail-* scenario; using Unknown");
            FailureClass::Unknown
        }
    };

    // Force dry-run for the demo so no funds ever move.
    let mut cfg = Config::load(config)?;
    cfg.execution.dry_run = true;
    let cfg = Arc::new(cfg);
    info!(?class, ai_enabled = cfg.ai.enabled, "Phase 6 autonomous AI retry demo");

    let state = Arc::new(turbine_state::HotState::new(&cfg));
    state.set_blockhash(turbine_core::blockhash::CachedBlockhash {
        blockhash: "11111111111111111111111111111111".into(),
        last_valid_block_height: 0,
        slot: 0,
        fetched_at: std::time::Instant::now(),
    });
    state.set_tip_accounts(vec![solana_pubkey::Pubkey::new_from_array([9u8; 32])]);
    state.set_tips(TipSnapshot { p25: 1_000, p50: 6_700, p75: 20_000, p95: 460_000, p99: 1_800_000 });
    let slot = 1_000u64;
    state.set_slot(slot);
    state.set_leader(turbine_core::leader::LeaderView {
        next_jito_leader_slot: Some(slot + cfg.strategy.gate_min),
        slots_until_leader: Some(cfg.strategy.gate_min),
    });
    state.set_geyser_healthy(true);

    let engine = Arc::new(ExecutionEngine::new(cfg.clone(), state.clone(), None)?);

    // Real analyst when configured; otherwise a mock that proposes a fix so the
    // autonomous loop is demonstrable offline.
    let ai = if cfg.ai.enabled {
        Arc::new(AiEngine::new(&cfg, state.clone()))
    } else {
        let verdict = AnalystVerdict {
            classification: format!("{class:?}"),
            root_cause: format!("demo: synthetic {class_name} failure"),
            adjustments: RetryAdjustments {
                tip_bump_pct: Some(0.5),
                cu_limit: Some(300_000),
                fresh_blockhash: true,
                rebuild: true,
                ..Default::default()
            },
            should_retry: true,
            confidence: 0.8,
        };
        Arc::new(AiEngine::with_analyst(&cfg, state.clone(), Analyst::Mock(Box::new(verdict))))
    };

    let coordinator =
        RetryCoordinator::new(cfg.clone(), engine.clone(), ai, state.clone());

    // 1) Submit the original bundle (dry-run) → an in-flight tracking id.
    let rep = engine.execute(TradeIntent::mock(format!("demo-{class_name}"))).await?;
    info!(tracking_id = rep.tracking_id, attempt = rep.attempt, "original bundle submitted");

    // 2) Inject the failure → AI classifies, stores reasoning, rebuilds, resubmits.
    coordinator
        .on_failure(FailureEvent {
            tracking_id: Some(rep.tracking_id),
            bundle_id: None,
            raw_reason: format!("synthetic {class_name} failure"),
            class_hint: class,
            logs: vec!["Program log: demo".into()],
        })
        .await;

    // 3) Show the persisted reasoning trail (what the web UI will render).
    for rec in state.ai_audit.snapshot() {
        info!(
            seq = rec.seq,
            attempt = rec.attempt,
            outcome = ?rec.outcome,
            class = %rec.classification,
            fix = %rec.fix,
            "AI reasoning: {}", rec.root_cause
        );
    }
    info!(
        in_flight = engine.registry().len(),
        audit_records = state.ai_audit.len(),
        "autonomous retry demo complete"
    );
    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    // The dashboard runs only for `start` on an interactive terminal (and unless
    // `--no-tui` is set); everything else logs to stdout.
    let tui_active = matches!(
        cli.command,
        Command::Start { no_tui: false, .. }
    ) && std::io::stdout().is_terminal();
    init_tracing(tui_active)?;

    match cli.command {
        Command::Start { deshred, .. } => {
            let turbine = Turbine::builder()
                .config_path(&cli.config)
                .deshred(deshred)
                .web(true)
                .start()
                .await?;
            let cfg = turbine.config_arc();
            info!(config = %cli.config.display(), "configuration loaded and validated");
            info!(
                geyser = %cfg.geyser.endpoint,
                commitment = %cfg.geyser.commitment,
                deshred,
                programs = cfg.targets.programs.len(),
                watched = cfg.targets.watched_accounts.len(),
                socket = %cfg.ipc.socket_path.display(),
                studio = %turbine.studio_url(),
                tui = tui_active,
                "ingestion + processing + execution + AI + IPC running — `turbine stop` or Ctrl-C"
            );

            let shutdown = turbine.shutdown_notify();
            let (cmd_tx, cmd_rx) =
                tokio::sync::mpsc::channel::<(Request, tokio::sync::oneshot::Sender<Response>)>(64);
            let daemon = Arc::new(daemon::Daemon::new(
                cfg.clone(),
                turbine.state(),
                turbine.engine(),
                turbine.fail_tx(),
                shutdown.clone(),
                turbine.jito_connected(),
            ));
            turbine.spawn_task(tokio::spawn(daemon.run(cmd_rx)));
            {
                let socket = cfg.ipc.socket_path.clone();
                let sd = shutdown.clone();
                turbine.spawn_task(tokio::spawn(async move {
                    if let Err(e) = turbine_ipc::serve(&socket, cmd_tx, sd).await {
                        tracing::error!("ipc server error: {e}");
                    }
                }));
            }

            let deshred_boot = turbine.deshred_boot();
            if tui_active {
                if let Some(notice) = deshred_boot.terminal_notice() {
                    use std::io::Write;
                    let mut stderr = std::io::stderr();
                    let _ = writeln!(stderr);
                    for line in notice.lines() {
                        let _ = writeln!(stderr, "{line}");
                    }
                    let _ = writeln!(stderr);
                    let _ = stderr.flush();
                }
                let stopping = Arc::new(AtomicBool::new(false));
                let tui = turbine_tui::spawn_dashboard(
                    turbine.bus().subscribe(),
                    turbine.studio_url(),
                    cfg.execution.dry_run,
                    shutdown.clone(),
                    stopping.clone(),
                    deshred_boot,
                );

                turbine.wait_shutdown().await;
                stopping.store(true, Ordering::Relaxed);
                turbine.shutdown();
                let _ = tui.await;
                info!("dashboard closed; TURBINE stopped");
            } else {
                if let Some(notice) = deshred_boot.terminal_notice() {
                    eprintln!();
                    for line in notice.lines() {
                        eprintln!("{line}");
                    }
                    eprintln!();
                }
                turbine.wait_shutdown().await;
                info!("stop requested; shutting down");
                turbine.shutdown();
            }

            // Background gRPC/TLS reconnect loops can otherwise delay runtime
            // teardown, so exit promptly and deterministically.
            std::process::exit(0);
        }
        Command::Run { scenario } => {
            let cfg = Config::load(&cli.config)?;
            match turbine_ipc::request(
                &cfg.ipc.socket_path,
                Request::RunScenario { scenario: scenario.clone() },
            )
            .await
            {
                Ok(resp) => print_response(resp),
                Err(e) => {
                    info!("daemon not reachable ({e}); running in-process demo");
                    run_local_demo(&cli.config, &scenario).await?;
                }
            }
        }
        Command::Stop => {
            let cfg = Config::load(&cli.config)?;
            match turbine_ipc::request(&cfg.ipc.socket_path, Request::Stop).await {
                Ok(resp) => print_response(resp),
                Err(e) => info!("could not reach daemon to stop ({e}); is it running?"),
            }
        }
        Command::Status => {
            let cfg = Config::load(&cli.config)?;
            match turbine_ipc::request(&cfg.ipc.socket_path, Request::Status).await {
                Ok(resp) => print_response(resp),
                Err(e) => info!(
                    socket = %cfg.ipc.socket_path.display(),
                    "daemon not running ({e}); config is valid"
                ),
            }
        }
    }

    Ok(())
}

/// Render an IPC response for the CLI client.
fn print_response(resp: Response) {
    match resp {
        Response::Pong => info!("pong"),
        Response::Ack { message } => info!("{message}"),
        Response::Error { message } => tracing::error!("daemon error: {message}"),
        Response::RunResult(r) => info!(
            label = %r.label,
            tracking_id = r.tracking_id,
            gate = %r.gate,
            tip_lamports = r.tip_lamports,
            tx_count = r.tx_count,
            bundle_id = ?r.bundle_id,
            submitted = r.submitted,
            failure_injected = r.failure_injected,
            dry_run = r.dry_run,
            "scenario accepted by daemon",
        ),
        Response::Status(s) => info!(
            uptime_secs = s.uptime_secs,
            slot = s.slot,
            geyser_healthy = s.geyser_healthy,
            jito_connected = s.jito_connected,
            next_jito_leader_slot = ?s.next_jito_leader_slot,
            slots_until_leader = ?s.slots_until_leader,
            tip_p50 = s.tip_p50,
            tip_p95 = s.tip_p95,
            in_flight = s.in_flight,
            ai_decisions = s.ai_decisions,
            submission_killed = s.submission_killed,
            dry_run = s.dry_run,
            "daemon status",
        ),
    }
}