Skip to main content

claudectl_core/
runtime.rs

1//! UI ↔ runtime contract.
2//!
3//! Tracking: issue #274 of the workspace-refactor epic (#279).
4//!
5//! The TUI today reaches deep into brain / coord / bus / rules internals. This
6//! module defines the **read-only** boundary it should reach through instead,
7//! so a future `claudectl-tui` crate (#275) can be extracted and iterated on
8//! without recompiling brain or the bus.
9//!
10//! ## Why traits, why core-owned DTOs
11//!
12//! Each view is a trait, not a concrete struct, so:
13//!
14//! - The binary crate can hand the TUI a real implementation backed by SQLite
15//!   / the engine / the bus DB. A future remote frontend can hand it an HTTP
16//!   client. Tests hand it a fixture.
17//! - Adding a method to a trait is a contract change reviewable in one PR;
18//!   adding a method to a concrete struct ripples through every caller.
19//!
20//! Each DTO (`SessionSnapshot`, `LeaseSummary`, …) is owned by `core` so the
21//! traits don't drag `brain::DecisionRecord` / `coord::Lease` upward into the
22//! TUI's dependency surface. Conversion happens once, in the wrapper.
23//!
24//! ## What's in scope here
25//!
26//! Read-only views only. Side-effecting paths (`terminate_session`,
27//! `inject_prompt`, `log_decision`) deserve a separate `Actions` trait once
28//! the TUI's write surface is mapped. Adding it speculatively now would
29//! violate the "only add methods existing call sites need" rule the epic
30//! committed to.
31//!
32//! ## What's NOT in scope
33//!
34//! - The TUI doesn't yet call through these traits — that's #275.
35//! - Brain's review/scorecard surface — it's heavier and worth its own
36//!   trait once #275 stabilizes the basic shape.
37//! - Pub/sub claim protocol — #283 builds on top of these traits, not the
38//!   other way around.
39
40use serde::{Deserialize, Serialize};
41use std::sync::Arc;
42
43// ============================================================================
44// Sessions
45// ============================================================================
46
47/// One running Claude Code session, as observed by the runtime. Minimal
48/// projection of the binary-crate `ClaudeSession`; only fields the TUI
49/// renders.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct SessionSnapshot {
52    pub session_id: String,
53    pub pid: u32,
54    pub cwd: String,
55    pub project_name: String,
56    pub status: String,
57    pub cost_usd: f64,
58    pub context_tokens: u64,
59    pub context_max: u64,
60    pub last_message_ts: u64,
61}
62
63/// Read access to the live session roster.
64pub trait SessionSource: Send + Sync {
65    /// Snapshot of every running Claude Code session. Order is the
66    /// implementor's choice; the TUI sorts again client-side.
67    fn list(&self) -> Vec<SessionSnapshot>;
68
69    /// Fetch a specific session by its ID. `None` when the session has
70    /// exited or never existed.
71    fn detail(&self, session_id: &str) -> Option<SessionSnapshot> {
72        self.list().into_iter().find(|s| s.session_id == session_id)
73    }
74}
75
76// ============================================================================
77// Brain
78// ============================================================================
79
80/// Mirrors the binary's `brain::GateMode` without depending on the brain
81/// crate. Persisted as the lowercased label.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum BrainGateMode {
85    On,
86    Off,
87    Auto,
88}
89
90impl BrainGateMode {
91    /// Canonical lowercase label — the form persisted to
92    /// `~/.claudectl/brain/gate-mode` and emitted by the TUI status messages.
93    pub fn as_str(&self) -> &'static str {
94        match self {
95            Self::On => "on",
96            Self::Off => "off",
97            Self::Auto => "auto",
98        }
99    }
100}
101
102impl std::fmt::Display for BrainGateMode {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.write_str(self.as_str())
105    }
106}
107
108/// A single past brain decision, projected for display.
109///
110/// The first six fields are the common shape used by `BrainView::recent_decisions`.
111/// The remaining fields support the Brain Review surface (`BrainReviewView`); they
112/// are `Option`-wrapped + `#[serde(default)]` so older `BrainView` callers can
113/// keep treating them as opaque.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct DecisionSummary {
116    pub id: String,
117    pub timestamp: String,
118    pub action: String,
119    pub confidence: Option<f64>,
120    pub project: Option<String>,
121    pub tool: Option<String>,
122    /// PID of the session this decision belongs to. Used by counterfactual
123    /// analysis to pair decisions with their subsequent outcome from the
124    /// same session.
125    #[serde(default)]
126    pub pid: u32,
127
128    /// Tool input string when the decision was about a specific command.
129    #[serde(default)]
130    pub command: Option<String>,
131    /// Brain's free-form rationale for the suggestion.
132    #[serde(default)]
133    pub reasoning: Option<String>,
134    /// What the user did with the suggestion — `"accept"`, `"reject"`,
135    /// `"deny_rule_override"`, etc.
136    #[serde(default)]
137    pub user_action: Option<String>,
138    /// Why the user overrode the brain (if applicable).
139    #[serde(default)]
140    pub override_reason: Option<String>,
141    /// Wall-clock latency of the brain decision in milliseconds.
142    #[serde(default)]
143    pub brain_decision_ms: Option<u64>,
144    /// Whether the operator has marked this decision as canonical (teaching
145    /// material). `None` for records written before the field existed.
146    #[serde(default)]
147    pub canonical: Option<bool>,
148    /// Cache hit flag — served from the few-shot store without an LLM call.
149    /// `None` before instrumentation.
150    #[serde(default)]
151    pub cache_hit: Option<bool>,
152    /// Cost in USD when this decision was made (context snapshot).
153    #[serde(default)]
154    pub cost_usd: Option<f64>,
155    /// Model that produced the suggestion.
156    #[serde(default)]
157    pub model: Option<String>,
158    /// Resolved outcome category, when known. `"success" | "error" |
159    /// "test_failed" | "skipped"` etc. Mirrors the variants of the binary's
160    /// `brain::decisions::DecisionOutcome` enum, flattened to a string so
161    /// the contract doesn't pull the enum upward.
162    #[serde(default)]
163    pub outcome_kind: Option<String>,
164    /// Free-form detail for failure outcomes (the failing command for
165    /// `test_failed`, the error message for `error`).
166    #[serde(default)]
167    pub outcome_detail: Option<String>,
168    /// Epoch seconds when the brain suggestion was first surfaced. Used by
169    /// time-to-correct analysis. `None` for records pre-instrumentation or
170    /// passive observations.
171    #[serde(default)]
172    pub suggested_at: Option<u64>,
173    /// Epoch seconds when the user acted on the suggestion. `None` for
174    /// passive observations or records still in flight.
175    #[serde(default)]
176    pub resolved_at: Option<u64>,
177}
178
179impl DecisionSummary {
180    /// Whether the user agreed with the brain (or the call was auto-executed).
181    /// Mirrors `brain::decisions::DecisionRecord::is_positive`.
182    pub fn is_positive(&self) -> bool {
183        matches!(
184            self.user_action.as_deref(),
185            Some("accept" | "auto" | "user_approve" | "rule_approve")
186        )
187    }
188
189    /// Whether the user disagreed with the brain. Mirrors
190    /// `brain::decisions::DecisionRecord::is_negative`.
191    pub fn is_negative(&self) -> bool {
192        matches!(
193            self.user_action.as_deref(),
194            Some("reject" | "deny_rule_override" | "rule_deny" | "conflict_deny")
195        )
196    }
197}
198
199/// Read access to the brain's decision history and current mode.
200pub trait BrainView: Send + Sync {
201    fn gate_mode(&self) -> BrainGateMode;
202
203    /// Most recent `n` decisions, newest first.
204    fn recent_decisions(&self, n: usize) -> Vec<DecisionSummary>;
205
206    /// Total count of brain decisions on disk. Drives the "decisions: N"
207    /// status line.
208    fn decision_count(&self) -> usize;
209}
210
211/// One entry in the Brain Review queue — a decision worth showing the operator
212/// for canonical-marking review, with a reason and a priority score.
213#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct ReviewItemSummary {
215    pub decision: DecisionSummary,
216    /// Free-form rationale for why this decision was queued for review.
217    pub reason: String,
218    /// Priority score (higher = more important to review first).
219    pub score: f64,
220}
221
222/// Read access to the Brain Review surface — the full decision log plus the
223/// review-queue projection. Separate trait from `BrainView` because:
224///
225/// - The Brain Review screen is the only TUI consumer; the dashboard's status
226///   bar only needs `BrainView::recent_decisions(n)`.
227/// - `all_decisions()` returns the whole log (can be thousands of records);
228///   it's a heavier surface than the lightweight `BrainView` methods and
229///   worth gating behind its own trait so callers don't accidentally invoke it.
230pub trait BrainReviewView: Send + Sync {
231    /// Every decision on disk, newest first. Used by the Brain Review screen
232    /// to render the full history list.
233    fn all_decisions(&self) -> Vec<DecisionSummary>;
234
235    /// Priority-ordered review queue. Built from `all_decisions()` plus the
236    /// brain's queue-building heuristics (counterfactual hits, Critical-tier
237    /// safety cases, high-confidence misses).
238    fn review_queue(&self) -> Vec<ReviewItemSummary>;
239}
240
241// ============================================================================
242// Coordination layer
243// ============================================================================
244
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct LeaseSummary {
247    pub id: String,
248    pub owner_session_id: String,
249    pub resource_kind: String,
250    pub resource_value: String,
251    pub mode: String,
252    pub acquired_at: String,
253    /// ISO timestamp when the lease expires. `None` for leases held without
254    /// an explicit deadline.
255    #[serde(default)]
256    pub expires_at: Option<String>,
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize)]
260pub struct HandoffSummary {
261    pub id: String,
262    pub from_session_id: String,
263    pub to_session_id: Option<String>,
264    pub task_id: String,
265    pub summary: String,
266    pub priority: String,
267    pub created_at: String,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct InterruptSummary {
272    pub id: String,
273    pub interrupt_type: String,
274    pub priority: String,
275    pub target_session_id: String,
276    pub reason: String,
277    pub created_at: String,
278}
279
280/// Read access to coordination state (leases, handoffs, interrupts).
281/// Backed today by the `coord` SQLite store; in tests, by a fixture.
282pub trait CoordView: Send + Sync {
283    fn active_leases(&self) -> Vec<LeaseSummary>;
284    fn pending_handoffs(&self) -> Vec<HandoffSummary>;
285    fn pending_interrupts(&self) -> Vec<InterruptSummary>;
286}
287
288// ============================================================================
289// Agent bus
290// ============================================================================
291
292#[derive(Debug, Clone, Serialize, Deserialize)]
293pub struct AgentDirectoryEntry {
294    pub session_id: String,
295    pub pid: u32,
296    pub cwd: String,
297    pub project: String,
298    pub status: String,
299    pub role: Option<String>,
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize)]
303pub struct RoleBinding {
304    pub name: String,
305    pub cwd_selector: String,
306    pub last_session_id: Option<String>,
307    pub last_seen: String,
308    /// PID this role is bound to (#307). `None` for cwd-only bindings.
309    pub pid: Option<u32>,
310}
311
312/// Read access to the agent-bus roster + role table. Disabled implementations
313/// (`bus` feature off in the binary) return empty vectors so the TUI can
314/// render the panel as "no bus" without conditional compilation.
315pub trait BusView: Send + Sync {
316    fn list_agents(&self) -> Vec<AgentDirectoryEntry>;
317    fn list_roles(&self) -> Vec<RoleBinding>;
318}
319
320// ============================================================================
321// Actions (write surface)
322// ============================================================================
323
324/// What the TUI needs to record alongside a user action. Core-owned so the
325/// trait doesn't drag `brain::decisions::log_observation`'s argument list
326/// upward into the TUI surface.
327#[derive(Debug, Clone, Serialize, Deserialize)]
328pub struct ObservationInput {
329    /// PID of the session the observation belongs to.
330    pub session_pid: u32,
331    /// Project label (usually the cwd basename).
332    pub project: String,
333    /// Tool the action targeted, when applicable ("Bash", "Write", …).
334    pub tool: Option<String>,
335    /// The command or input string the user ran/sent.
336    pub command: Option<String>,
337    /// Classification — `"user_approve"`, `"user_input"`, `"rule_approve"`,
338    /// `"rule_deny"`, and friends. Kept as a string so callers can introduce
339    /// new categories without a trait change.
340    pub observed_action: String,
341}
342
343/// Whether a decision was about a session or about an orchestration task.
344/// Mirrors `brain::decisions::DecisionType` without depending on it.
345#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
346#[serde(rename_all = "snake_case")]
347pub enum DecisionScope {
348    Session,
349    Orchestration,
350}
351
352impl DecisionScope {
353    /// Wire label. Matches what `brain::decisions::DecisionType::as_label`
354    /// writes to disk so the round-trip is stable.
355    pub fn as_str(&self) -> &'static str {
356        match self {
357            Self::Session => "session",
358            Self::Orchestration => "orchestration",
359        }
360    }
361}
362
363/// What the TUI needs to record when the user resolves a brain suggestion.
364/// Carries the suggestion that was on screen at the time, plus what the user
365/// did and (optionally) why they overrode the brain.
366#[derive(Debug, Clone, Serialize, Deserialize)]
367pub struct LogDecisionInput {
368    /// PID of the session the decision applies to.
369    pub session_pid: u32,
370    /// Project label.
371    pub project: String,
372    /// Tool name the suggestion targeted.
373    pub tool: Option<String>,
374    /// Command / input string the suggestion targeted.
375    pub command: Option<String>,
376    /// The brain's suggestion the user is resolving.
377    pub suggestion: PendingSuggestion,
378    /// What the user did — `"accept"`, `"reject"`, `"deny_rule_override"`, etc.
379    pub user_action: String,
380    /// Whether this was a session decision or an orchestration decision.
381    pub decision_type: DecisionScope,
382    /// Why the user overrode a brain denial (if applicable).
383    pub override_reason: Option<String>,
384}
385
386/// Side-effecting paths the TUI invokes when the user takes an action
387/// (terminating a session, sending a prompt, flipping the brain mode,
388/// recording an observation, marking a decision canonical for teaching).
389///
390/// Each method is fallible — implementations return a `Result` rather than
391/// silently swallowing errors so the TUI can surface failures in the status
392/// bar instead of pretending an action succeeded.
393///
394/// **Not modeled here (intentionally):**
395///
396/// - `launch::*` — launching a new Claude Code session is wider than a single
397///   call (cwd selection, model defaults, plugin propagation). Will get its
398///   own trait once the TUI's launcher surface is refactored alongside #275.
399/// - `mailbox::deliver_pending` — orchestrator-style mailbox delivery; should
400///   eventually move to an `Orchestrator` trait, not `Actions`.
401/// - `log_decision` (vs. `log_observation`) — currently only called from the
402///   plugin gate path, not the TUI. Stays a direct call until a TUI site
403///   needs it.
404pub trait Actions: Send + Sync {
405    /// Terminate the OS process with the given PID. The TUI uses this for
406    /// "kill session" hotkeys.
407    fn terminate_session(&self, pid: u32) -> Result<(), String>;
408
409    /// Inject text into the session's terminal. Implementations pick the
410    /// right backend (tmux, Kitty, etc.) from the session metadata.
411    ///
412    /// The `text` is sent verbatim — the caller is responsible for any
413    /// trailing newline they want. Sanitization (e.g. neutralizing a leading
414    /// `/`) belongs to the caller; this trait is a transport.
415    fn inject_text(&self, session_id: &str, text: &str) -> Result<(), String>;
416
417    /// Update the persisted brain gate mode. Reflected back through
418    /// `BrainView::gate_mode` on the next call.
419    fn set_gate_mode(&self, mode: BrainGateMode) -> Result<(), String>;
420
421    /// Record an observation about a user action — non-LLM "the user did X."
422    /// Drives the brain's outcome telemetry and preference distillation.
423    fn log_observation(&self, observation: ObservationInput) -> Result<(), String>;
424
425    /// Record a user's accept/reject decision on a brain suggestion. The
426    /// distinction from `log_observation` is that `log_decision` carries
427    /// the actual suggestion that was on screen — the brain pairs it with
428    /// the user's response for outcome telemetry, counterfactual analysis,
429    /// and few-shot retrieval.
430    fn log_decision(&self, input: LogDecisionInput) -> Result<(), String>;
431
432    /// Mark a past brain decision as canonical for teaching. Optional `note`
433    /// is the operator's annotation. Used by the Brain Review surface.
434    fn mark_canonical(&self, decision_id: &str, note: Option<String>) -> Result<(), String>;
435
436    /// Bind an agent-bus role to a `(cwd, pid)` pair. The TUI calls this from
437    /// the new role-bind key (Ctrl+R) so the operator can attach a role to a
438    /// specific running Claude session without dropping to another terminal.
439    /// Returns `Err` when the bus feature is compiled out or the DB write
440    /// fails. See issue #307.
441    fn bind_bus_role(&self, name: &str, cwd: &str, pid: u32) -> Result<(), String>;
442}
443
444// ============================================================================
445// Hive actions — knowledge-store (`hive`) + transport (`relay`) reads/writes
446// ============================================================================
447
448/// Snapshot of local hive state the overlay reads to render the Hive tab.
449///
450/// Mirrors the binary's same-named struct, lifted here so the TUI can hold
451/// it without depending on the binary's app module.
452#[derive(Debug, Clone, Default)]
453pub struct HiveViewSnapshot {
454    /// Local relay identity (peer ID string). `None` when the `relay`
455    /// feature is compiled out.
456    pub identity: Option<String>,
457    /// Known peers, paired with last-seen address when available.
458    pub peers: Vec<(String, Option<String>)>,
459}
460
461/// Hive + relay surface the TUI needs to render the Skills and Hive panels.
462///
463/// Separate trait from `Actions` because the underlying subsystems are
464/// feature-gated (`hive`, `relay`) — when those features are off the
465/// implementation returns empty/no-op values rather than failing.
466pub trait HiveActions: Send + Sync {
467    /// Semantic keys (`skill:<lowered-name>`) of skills already shared into
468    /// the local hive store. Used by the Skills overlay to mark "already
469    /// shared" rows.
470    fn shared_skill_keys(&self) -> std::collections::HashSet<String>;
471
472    /// Share a discovered skill into the local hive store. Returns the new
473    /// unit ID on success.
474    fn share_skill(&self, skill: &crate::skills::DiscoveredSkill) -> Result<String, String>;
475
476    /// Current view of the local relay identity + known peers for the Hive
477    /// tab.
478    fn hive_view_snapshot(&self) -> HiveViewSnapshot;
479}
480
481// ============================================================================
482// Brain driver (stateful)
483// ============================================================================
484
485/// One pending brain suggestion the user can accept or reject. Mirrors the
486/// binary's `brain::client::BrainSuggestion` without exposing brain types.
487#[derive(Debug, Clone, Serialize, Deserialize)]
488pub struct PendingSuggestion {
489    /// PID of the session this suggestion applies to.
490    pub pid: u32,
491    /// String label of the suggested action — `"approve"`, `"deny"`,
492    /// `"send"`, `"terminate"`. String to avoid pulling `RuleAction`'s enum
493    /// shape into the contract (it's already in `claudectl-core::rules` but
494    /// callers may want to add new categories without bumping the trait).
495    pub action: String,
496    /// Suggested message body (a prompt to inject, a rationale to surface).
497    pub message: Option<String>,
498    /// Why the brain suggested this — used for the detail panel and the
499    /// rejection log.
500    pub reasoning: String,
501    /// 0.0–1.0 confidence the brain assigned.
502    pub confidence: f64,
503    /// Epoch seconds when the suggestion was created. Drives time-to-correct
504    /// telemetry.
505    pub suggested_at: u64,
506}
507
508/// Stateful brain orchestration. Unlike the read-only views, this needs
509/// `&mut` per tick — the engine accumulates pending suggestions, cleans up
510/// after exited sessions, and applies user accept/reject decisions.
511///
512/// Boxed as `Box<dyn BrainDriver>` rather than `Arc<dyn BrainDriver>`
513/// because there is exactly one owner (the TUI's `App`) and every method
514/// needs `&mut self`. Sharing across threads is not a goal here.
515///
516/// Implementations may be `None` — the brain is opt-in (`--brain` flag).
517/// When the field is `None` the TUI renders without brain interaction.
518pub trait BrainDriver: Send {
519    /// Run one tick of the brain loop against the current session set and
520    /// the operator's deny rules. Returns `(pid, status_message)` pairs
521    /// for any actions the brain decided on this tick — the TUI surfaces
522    /// the messages in the status bar.
523    fn tick(
524        &mut self,
525        sessions: &[SessionSnapshot],
526        deny_rules: &[crate::rules::AutoRule],
527    ) -> Vec<(u32, String)>;
528
529    /// Drop pending suggestions for sessions that have exited. Called every
530    /// refresh so the pending map stays bounded by the live session count.
531    fn cleanup(&mut self, sessions: &[SessionSnapshot]);
532
533    /// User accepted the pending suggestion for `pid`. Implementations
534    /// return the log message the TUI should surface (`None` when there's
535    /// no suggestion to accept).
536    fn accept(&mut self, pid: u32) -> Option<String>;
537
538    /// User rejected the pending suggestion for `pid`. Returns the
539    /// suggestion that was rejected — the TUI logs it for replay /
540    /// counterfactual analysis.
541    fn reject(&mut self, pid: u32) -> Option<PendingSuggestion>;
542
543    /// Lookup the pending suggestion for `pid`, if any. Used by detail
544    /// panels and the status bar.
545    fn pending_for(&self, pid: u32) -> Option<PendingSuggestion>;
546
547    /// Total pending suggestion count. Used by the status bar.
548    fn pending_count(&self) -> usize;
549
550    /// Drop every pending suggestion. Called when the brain mode flips
551    /// off or the operator resets state.
552    fn clear_pending(&mut self);
553
554    /// Inject a pending suggestion for `pid`. Used by demo mode to fake
555    /// brain activity for screenshots / recordings. Implementations may
556    /// drop suggestions whose `action` string doesn't map to a known
557    /// engine action (rather than erroring out) — demo is best-effort.
558    fn set_pending(&mut self, suggestion: PendingSuggestion);
559}
560
561// ============================================================================
562// Orchestrator
563// ============================================================================
564
565/// Tick the orchestration layer once per refresh: deliver pending mailbox
566/// messages, deliver pending coordination interrupts, and bookkeep stale
567/// rows in the underlying stores.
568///
569/// Each `deliver_*` method returns `(id, status_message)` tuples the TUI
570/// surfaces in the status bar. `id` is a `u32` for mailbox (matching the
571/// brain's per-PID queue) and a `String` for interrupts (matching the
572/// coord interrupt_id). They differ deliberately — keeping the trait honest
573/// to the underlying surfaces rather than papering over the distinction.
574///
575/// Unlike `CoordView` / `BrainView` which are read-only, this trait is
576/// stateful: each call writes to the brain/coord SQLite stores. It still
577/// boxes as `Arc<dyn>` because no method needs `&mut self` — implementations
578/// open a connection per call.
579///
580/// Implementations may be no-ops when the relevant feature is off (e.g. the
581/// `coord` feature is disabled at compile time), so call sites don't need
582/// `#[cfg(feature = "...")]` guards.
583pub trait Orchestrator: Send + Sync {
584    /// Drain pending mailbox messages addressed to running sessions and
585    /// deliver them to the live terminals. Used by `App::tick` to surface
586    /// `"Brain → sess_X: 'go ahead'"` style messages.
587    fn deliver_mailbox(&self, sessions: &[SessionSnapshot]) -> Vec<(u32, String)>;
588
589    /// Deliver pending coordination interrupts (cross-agent signals) to
590    /// running sessions. Returns `(interrupt_id, status_message)` tuples.
591    fn deliver_interrupts(&self, sessions: &[SessionSnapshot]) -> Vec<(String, String)>;
592
593    /// Expire stale leases and interrupts that have passed their deadline.
594    /// Bookkeeping side-effect; best-effort, no return. Implementations
595    /// log failures rather than propagating them.
596    fn expire_stale(&self);
597}
598
599// ============================================================================
600// Runtime aggregate
601// ============================================================================
602
603/// Single struct the binary builds at startup and hands to the TUI.
604///
605/// All fields are `Arc<dyn ...>` so the TUI doesn't care whether an impl is
606/// a thin SQLite wrapper, a remote HTTP client, or an in-memory mock — they
607/// all share the same shape.
608#[derive(Clone)]
609pub struct Runtime {
610    pub sessions: Arc<dyn SessionSource>,
611    pub brain: Arc<dyn BrainView>,
612    pub coord: Arc<dyn CoordView>,
613    pub bus: Arc<dyn BusView>,
614    pub actions: Arc<dyn Actions>,
615    pub review: Arc<dyn BrainReviewView>,
616    pub orchestrator: Arc<dyn Orchestrator>,
617    pub hive: Arc<dyn HiveActions>,
618}
619
620impl Runtime {
621    // 8-trait composition root; each view is its own arc. Splitting this into
622    // sub-records would just trade one wide ctor for several narrow ones with
623    // the same total fan-out.
624    #[allow(clippy::too_many_arguments)]
625    pub fn new(
626        sessions: Arc<dyn SessionSource>,
627        brain: Arc<dyn BrainView>,
628        coord: Arc<dyn CoordView>,
629        bus: Arc<dyn BusView>,
630        actions: Arc<dyn Actions>,
631        review: Arc<dyn BrainReviewView>,
632        orchestrator: Arc<dyn Orchestrator>,
633        hive: Arc<dyn HiveActions>,
634    ) -> Self {
635        Self {
636            sessions,
637            brain,
638            coord,
639            bus,
640            actions,
641            review,
642            orchestrator,
643            hive,
644        }
645    }
646}
647
648// ============================================================================
649// MockRuntime — for tests in this crate and in claudectl-tui
650// ============================================================================
651
652/// In-memory runtime backed by `Vec`s and interior-mutable counters. Used by
653/// tests in this crate to verify the trait shapes compile and roundtrip
654/// cleanly, and by the future `claudectl-tui` crate's tests to render the
655/// TUI against fixtures without dragging in brain / coord / bus.
656///
657/// `Actions` impls record their calls in `actions_log` so tests can assert
658/// "the TUI invoked the right side-effect" without spying on real I/O.
659#[derive(Default)]
660pub struct MockRuntime {
661    pub sessions: Vec<SessionSnapshot>,
662    pub gate_mode: std::sync::Mutex<Option<BrainGateMode>>,
663    pub decisions: Vec<DecisionSummary>,
664    pub review_queue: Vec<ReviewItemSummary>,
665    pub leases: Vec<LeaseSummary>,
666    pub handoffs: Vec<HandoffSummary>,
667    pub interrupts: Vec<InterruptSummary>,
668    pub agents: Vec<AgentDirectoryEntry>,
669    pub roles: Vec<RoleBinding>,
670    pub actions_log: std::sync::Mutex<Vec<MockAction>>,
671}
672
673/// Recorded `Actions` calls. Tests use this to assert side-effect ordering
674/// without needing a real terminal or filesystem.
675#[derive(Debug, Clone, PartialEq, Eq)]
676pub enum MockAction {
677    Terminate {
678        pid: u32,
679    },
680    InjectText {
681        session_id: String,
682        text: String,
683    },
684    SetGateMode(BrainGateMode),
685    LogObservation(ObservationInput),
686    LogDecision(LogDecisionInput),
687    MarkCanonical {
688        decision_id: String,
689        note: Option<String>,
690    },
691    BindBusRole {
692        name: String,
693        cwd: String,
694        pid: u32,
695    },
696}
697
698impl PartialEq for ObservationInput {
699    fn eq(&self, other: &Self) -> bool {
700        self.session_pid == other.session_pid
701            && self.project == other.project
702            && self.tool == other.tool
703            && self.command == other.command
704            && self.observed_action == other.observed_action
705    }
706}
707
708impl Eq for ObservationInput {}
709
710impl PartialEq for LogDecisionInput {
711    fn eq(&self, other: &Self) -> bool {
712        self.session_pid == other.session_pid
713            && self.project == other.project
714            && self.tool == other.tool
715            && self.command == other.command
716            && self.user_action == other.user_action
717            && self.decision_type == other.decision_type
718            && self.override_reason == other.override_reason
719            // PendingSuggestion's field-by-field equality
720            && self.suggestion.pid == other.suggestion.pid
721            && self.suggestion.action == other.suggestion.action
722            && self.suggestion.message == other.suggestion.message
723            && self.suggestion.reasoning == other.suggestion.reasoning
724    }
725}
726
727impl Eq for LogDecisionInput {}
728
729impl MockRuntime {
730    pub fn into_runtime(self) -> Runtime {
731        let arc = Arc::new(self);
732        Runtime::new(
733            arc.clone(),
734            arc.clone(),
735            arc.clone(),
736            arc.clone(),
737            arc.clone(),
738            arc.clone(),
739            arc.clone(),
740            arc,
741        )
742    }
743
744    pub fn actions(&self) -> Vec<MockAction> {
745        self.actions_log
746            .lock()
747            .expect("actions_log poisoned")
748            .clone()
749    }
750}
751
752impl SessionSource for MockRuntime {
753    fn list(&self) -> Vec<SessionSnapshot> {
754        self.sessions.clone()
755    }
756}
757
758impl BrainView for MockRuntime {
759    fn gate_mode(&self) -> BrainGateMode {
760        self.gate_mode
761            .lock()
762            .expect("gate_mode poisoned")
763            .unwrap_or(BrainGateMode::On)
764    }
765    fn recent_decisions(&self, n: usize) -> Vec<DecisionSummary> {
766        self.decisions.iter().take(n).cloned().collect()
767    }
768    fn decision_count(&self) -> usize {
769        self.decisions.len()
770    }
771}
772
773impl CoordView for MockRuntime {
774    fn active_leases(&self) -> Vec<LeaseSummary> {
775        self.leases.clone()
776    }
777    fn pending_handoffs(&self) -> Vec<HandoffSummary> {
778        self.handoffs.clone()
779    }
780    fn pending_interrupts(&self) -> Vec<InterruptSummary> {
781        self.interrupts.clone()
782    }
783}
784
785impl BusView for MockRuntime {
786    fn list_agents(&self) -> Vec<AgentDirectoryEntry> {
787        self.agents.clone()
788    }
789    fn list_roles(&self) -> Vec<RoleBinding> {
790        self.roles.clone()
791    }
792}
793
794impl BrainReviewView for MockRuntime {
795    fn all_decisions(&self) -> Vec<DecisionSummary> {
796        self.decisions.clone()
797    }
798    fn review_queue(&self) -> Vec<ReviewItemSummary> {
799        self.review_queue.clone()
800    }
801}
802
803impl Orchestrator for MockRuntime {
804    fn deliver_mailbox(&self, _sessions: &[SessionSnapshot]) -> Vec<(u32, String)> {
805        Vec::new()
806    }
807    fn deliver_interrupts(&self, _sessions: &[SessionSnapshot]) -> Vec<(String, String)> {
808        Vec::new()
809    }
810    fn expire_stale(&self) {}
811}
812
813impl HiveActions for MockRuntime {
814    fn shared_skill_keys(&self) -> std::collections::HashSet<String> {
815        std::collections::HashSet::new()
816    }
817    fn share_skill(&self, _skill: &crate::skills::DiscoveredSkill) -> Result<String, String> {
818        Err("MockRuntime does not implement skill sharing".into())
819    }
820    fn hive_view_snapshot(&self) -> HiveViewSnapshot {
821        HiveViewSnapshot::default()
822    }
823}
824
825impl Actions for MockRuntime {
826    fn terminate_session(&self, pid: u32) -> Result<(), String> {
827        self.actions_log
828            .lock()
829            .expect("actions_log poisoned")
830            .push(MockAction::Terminate { pid });
831        Ok(())
832    }
833    fn inject_text(&self, session_id: &str, text: &str) -> Result<(), String> {
834        self.actions_log
835            .lock()
836            .expect("actions_log poisoned")
837            .push(MockAction::InjectText {
838                session_id: session_id.into(),
839                text: text.into(),
840            });
841        Ok(())
842    }
843    fn set_gate_mode(&self, mode: BrainGateMode) -> Result<(), String> {
844        *self.gate_mode.lock().expect("gate_mode poisoned") = Some(mode);
845        self.actions_log
846            .lock()
847            .expect("actions_log poisoned")
848            .push(MockAction::SetGateMode(mode));
849        Ok(())
850    }
851    fn log_observation(&self, observation: ObservationInput) -> Result<(), String> {
852        self.actions_log
853            .lock()
854            .expect("actions_log poisoned")
855            .push(MockAction::LogObservation(observation));
856        Ok(())
857    }
858    fn log_decision(&self, input: LogDecisionInput) -> Result<(), String> {
859        self.actions_log
860            .lock()
861            .expect("actions_log poisoned")
862            .push(MockAction::LogDecision(input));
863        Ok(())
864    }
865    fn mark_canonical(&self, decision_id: &str, note: Option<String>) -> Result<(), String> {
866        self.actions_log
867            .lock()
868            .expect("actions_log poisoned")
869            .push(MockAction::MarkCanonical {
870                decision_id: decision_id.into(),
871                note,
872            });
873        Ok(())
874    }
875    fn bind_bus_role(&self, name: &str, cwd: &str, pid: u32) -> Result<(), String> {
876        self.actions_log
877            .lock()
878            .expect("actions_log poisoned")
879            .push(MockAction::BindBusRole {
880                name: name.into(),
881                cwd: cwd.into(),
882                pid,
883            });
884        Ok(())
885    }
886}
887
888#[cfg(test)]
889mod tests {
890    use super::*;
891
892    fn sample_session(id: &str) -> SessionSnapshot {
893        SessionSnapshot {
894            session_id: id.into(),
895            pid: 12345,
896            cwd: "/work/proj".into(),
897            project_name: "proj".into(),
898            status: "Processing".into(),
899            cost_usd: 1.23,
900            context_tokens: 4000,
901            context_max: 200_000,
902            last_message_ts: 1_780_000_000,
903        }
904    }
905
906    #[test]
907    fn mock_runtime_assembles_and_lists_sessions() {
908        let mock = MockRuntime {
909            sessions: vec![sample_session("sess_a"), sample_session("sess_b")],
910            ..Default::default()
911        };
912        let rt = mock.into_runtime();
913        let listed = rt.sessions.list();
914        assert_eq!(listed.len(), 2);
915        assert_eq!(listed[0].session_id, "sess_a");
916    }
917
918    #[test]
919    fn session_detail_falls_back_to_list_scan() {
920        let mock = MockRuntime {
921            sessions: vec![sample_session("sess_a"), sample_session("sess_b")],
922            ..Default::default()
923        };
924        let rt = mock.into_runtime();
925        assert!(rt.sessions.detail("sess_a").is_some());
926        assert!(rt.sessions.detail("sess_missing").is_none());
927    }
928
929    #[test]
930    fn brain_view_returns_recent_decisions_with_cap() {
931        let mock = MockRuntime {
932            decisions: (0..5)
933                .map(|i| DecisionSummary {
934                    id: format!("dec_{i}"),
935                    timestamp: format!("2026-06-06T00:00:0{i}Z"),
936                    action: "approve".into(),
937                    confidence: Some(0.9),
938                    project: None,
939                    tool: None,
940                    pid: 0,
941                    command: None,
942                    reasoning: None,
943                    user_action: None,
944                    override_reason: None,
945                    brain_decision_ms: None,
946                    canonical: None,
947                    cache_hit: None,
948                    cost_usd: None,
949                    model: None,
950                    outcome_kind: None,
951                    outcome_detail: None,
952                    suggested_at: None,
953                    resolved_at: None,
954                })
955                .collect(),
956            ..Default::default()
957        };
958        let rt = mock.into_runtime();
959        assert_eq!(rt.brain.recent_decisions(3).len(), 3);
960        assert_eq!(rt.brain.decision_count(), 5);
961        assert_eq!(rt.brain.gate_mode(), BrainGateMode::On);
962    }
963
964    #[test]
965    fn coord_view_reports_empty_state_cleanly() {
966        let rt = MockRuntime::default().into_runtime();
967        assert!(rt.coord.active_leases().is_empty());
968        assert!(rt.coord.pending_handoffs().is_empty());
969        assert!(rt.coord.pending_interrupts().is_empty());
970    }
971
972    #[test]
973    fn bus_view_reports_empty_state_cleanly() {
974        let rt = MockRuntime::default().into_runtime();
975        assert!(rt.bus.list_agents().is_empty());
976        assert!(rt.bus.list_roles().is_empty());
977    }
978
979    /// Smoke test that the trait shapes are usable behind `dyn`. If this
980    /// compiles, the boxed-trait composition works.
981    #[test]
982    fn runtime_implements_clone_and_send() {
983        fn assert_send<T: Send>() {}
984        assert_send::<Runtime>();
985
986        let rt = MockRuntime::default().into_runtime();
987        let _rt2 = rt.clone();
988    }
989
990    #[test]
991    fn actions_terminate_records_in_log() {
992        let rt = MockRuntime::default().into_runtime();
993        rt.actions.terminate_session(42).unwrap();
994        rt.actions.terminate_session(43).unwrap();
995        // No public mock accessor on Arc<dyn Actions>, but we can downcast
996        // through the trait by going via the *original* Arc through inspecting
997        // the trait's behavior — the integration test in the binary covers
998        // that surface. Here we just assert the calls succeeded.
999    }
1000
1001    #[test]
1002    fn actions_set_gate_mode_round_trips_through_brain_view() {
1003        let mock = MockRuntime::default();
1004        let arc = Arc::new(mock);
1005        let rt = Runtime::new(
1006            arc.clone(),
1007            arc.clone(),
1008            arc.clone(),
1009            arc.clone(),
1010            arc.clone(),
1011            arc.clone(),
1012            arc.clone(),
1013            arc.clone(),
1014        );
1015        // Initial: default On.
1016        assert_eq!(rt.brain.gate_mode(), BrainGateMode::On);
1017        // Flip via Actions; observe via BrainView.
1018        rt.actions.set_gate_mode(BrainGateMode::Off).unwrap();
1019        assert_eq!(rt.brain.gate_mode(), BrainGateMode::Off);
1020        rt.actions.set_gate_mode(BrainGateMode::Auto).unwrap();
1021        assert_eq!(rt.brain.gate_mode(), BrainGateMode::Auto);
1022        // And the log captured both transitions.
1023        let calls = arc.actions();
1024        assert_eq!(
1025            calls,
1026            vec![
1027                MockAction::SetGateMode(BrainGateMode::Off),
1028                MockAction::SetGateMode(BrainGateMode::Auto),
1029            ]
1030        );
1031    }
1032
1033    #[test]
1034    fn actions_log_observation_captures_full_input() {
1035        let mock = MockRuntime::default();
1036        let arc = Arc::new(mock);
1037        let rt = Runtime::new(
1038            arc.clone(),
1039            arc.clone(),
1040            arc.clone(),
1041            arc.clone(),
1042            arc.clone(),
1043            arc.clone(),
1044            arc.clone(),
1045            arc.clone(),
1046        );
1047        let obs = ObservationInput {
1048            session_pid: 12345,
1049            project: "claudectl".into(),
1050            tool: Some("Bash".into()),
1051            command: Some("cargo test".into()),
1052            observed_action: "user_approve".into(),
1053        };
1054        rt.actions.log_observation(obs.clone()).unwrap();
1055        let calls = arc.actions();
1056        assert_eq!(calls, vec![MockAction::LogObservation(obs)]);
1057    }
1058
1059    #[test]
1060    fn actions_inject_text_and_mark_canonical_record_inputs() {
1061        let mock = MockRuntime::default();
1062        let arc = Arc::new(mock);
1063        let rt = Runtime::new(
1064            arc.clone(),
1065            arc.clone(),
1066            arc.clone(),
1067            arc.clone(),
1068            arc.clone(),
1069            arc.clone(),
1070            arc.clone(),
1071            arc.clone(),
1072        );
1073        rt.actions.inject_text("sess_a", "/compact\n").unwrap();
1074        rt.actions
1075            .mark_canonical("dec_42", Some("nice catch".into()))
1076            .unwrap();
1077        let calls = arc.actions();
1078        assert_eq!(
1079            calls,
1080            vec![
1081                MockAction::InjectText {
1082                    session_id: "sess_a".into(),
1083                    text: "/compact\n".into(),
1084                },
1085                MockAction::MarkCanonical {
1086                    decision_id: "dec_42".into(),
1087                    note: Some("nice catch".into()),
1088                },
1089            ]
1090        );
1091    }
1092}