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/// A supervisor task lifecycle, projected for the TUI. One row per task in the
281/// coord `tasks` table. `state` is the wire label (`TaskState::as_str`), kept as
282/// a string so the contract doesn't drag the coord state enum upward.
283#[derive(Debug, Clone, Serialize, Deserialize)]
284pub struct TaskSummary {
285    pub id: String,
286    pub name: String,
287    pub state: String,
288    pub role: Option<String>,
289    /// Number of recorded attempts so far.
290    pub attempts: u32,
291    pub max_retries: u32,
292    /// Session id of the most recent attempt, when one has run.
293    pub last_session_id: Option<String>,
294    /// Most recent verifier verdict (e.g. "PASS"/"FAIL"), or `None` if no
295    /// verifier has run for this task yet.
296    #[serde(default)]
297    pub last_verdict: Option<String>,
298    /// Total cost in USD across all attempts.
299    #[serde(default)]
300    pub cost_usd: f64,
301    pub created_at: String,
302    pub updated_at: String,
303}
304
305/// Read access to coordination state (leases, handoffs, interrupts, tasks).
306/// Backed today by the `coord` SQLite store; in tests, by a fixture.
307pub trait CoordView: Send + Sync {
308    fn active_leases(&self) -> Vec<LeaseSummary>;
309    fn pending_handoffs(&self) -> Vec<HandoffSummary>;
310    fn pending_interrupts(&self) -> Vec<InterruptSummary>;
311    /// Supervisor task lifecycles, newest first. Empty when the `coord` feature
312    /// is off so the TUI can render a "no supervisor" state without cfg.
313    fn tasks(&self) -> Vec<TaskSummary>;
314}
315
316// ============================================================================
317// Agent bus
318// ============================================================================
319
320#[derive(Debug, Clone, Serialize, Deserialize)]
321pub struct AgentDirectoryEntry {
322    pub session_id: String,
323    pub pid: u32,
324    pub cwd: String,
325    pub project: String,
326    pub status: String,
327    pub role: Option<String>,
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize)]
331pub struct RoleBinding {
332    pub name: String,
333    pub cwd_selector: String,
334    pub last_session_id: Option<String>,
335    pub last_seen: String,
336    /// PID this role is bound to (#307). `None` for cwd-only bindings.
337    pub pid: Option<u32>,
338}
339
340/// Read access to the agent-bus roster + role table. Disabled implementations
341/// (`bus` feature off in the binary) return empty vectors so the TUI can
342/// render the panel as "no bus" without conditional compilation.
343pub trait BusView: Send + Sync {
344    fn list_agents(&self) -> Vec<AgentDirectoryEntry>;
345    fn list_roles(&self) -> Vec<RoleBinding>;
346}
347
348// ============================================================================
349// Actions (write surface)
350// ============================================================================
351
352/// What the TUI needs to record alongside a user action. Core-owned so the
353/// trait doesn't drag `brain::decisions::log_observation`'s argument list
354/// upward into the TUI surface.
355#[derive(Debug, Clone, Serialize, Deserialize)]
356pub struct ObservationInput {
357    /// PID of the session the observation belongs to.
358    pub session_pid: u32,
359    /// Project label (usually the cwd basename).
360    pub project: String,
361    /// Tool the action targeted, when applicable ("Bash", "Write", …).
362    pub tool: Option<String>,
363    /// The command or input string the user ran/sent.
364    pub command: Option<String>,
365    /// Classification — `"user_approve"`, `"user_input"`, `"rule_approve"`,
366    /// `"rule_deny"`, and friends. Kept as a string so callers can introduce
367    /// new categories without a trait change.
368    pub observed_action: String,
369}
370
371/// Whether a decision was about a session or about an orchestration task.
372/// Mirrors `brain::decisions::DecisionType` without depending on it.
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
374#[serde(rename_all = "snake_case")]
375pub enum DecisionScope {
376    Session,
377    Orchestration,
378}
379
380impl DecisionScope {
381    /// Wire label. Matches what `brain::decisions::DecisionType::as_label`
382    /// writes to disk so the round-trip is stable.
383    pub fn as_str(&self) -> &'static str {
384        match self {
385            Self::Session => "session",
386            Self::Orchestration => "orchestration",
387        }
388    }
389}
390
391/// What the TUI needs to record when the user resolves a brain suggestion.
392/// Carries the suggestion that was on screen at the time, plus what the user
393/// did and (optionally) why they overrode the brain.
394#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct LogDecisionInput {
396    /// PID of the session the decision applies to.
397    pub session_pid: u32,
398    /// Project label.
399    pub project: String,
400    /// Tool name the suggestion targeted.
401    pub tool: Option<String>,
402    /// Command / input string the suggestion targeted.
403    pub command: Option<String>,
404    /// The brain's suggestion the user is resolving.
405    pub suggestion: PendingSuggestion,
406    /// What the user did — `"accept"`, `"reject"`, `"deny_rule_override"`, etc.
407    pub user_action: String,
408    /// Whether this was a session decision or an orchestration decision.
409    pub decision_type: DecisionScope,
410    /// Why the user overrode a brain denial (if applicable).
411    pub override_reason: Option<String>,
412}
413
414/// Side-effecting paths the TUI invokes when the user takes an action
415/// (terminating a session, sending a prompt, flipping the brain mode,
416/// recording an observation, marking a decision canonical for teaching).
417///
418/// Each method is fallible — implementations return a `Result` rather than
419/// silently swallowing errors so the TUI can surface failures in the status
420/// bar instead of pretending an action succeeded.
421///
422/// **Not modeled here (intentionally):**
423///
424/// - `launch::*` — launching a new Claude Code session is wider than a single
425///   call (cwd selection, model defaults, plugin propagation). Will get its
426///   own trait once the TUI's launcher surface is refactored alongside #275.
427/// - `mailbox::deliver_pending` — orchestrator-style mailbox delivery; should
428///   eventually move to an `Orchestrator` trait, not `Actions`.
429/// - `log_decision` (vs. `log_observation`) — currently only called from the
430///   plugin gate path, not the TUI. Stays a direct call until a TUI site
431///   needs it.
432pub trait Actions: Send + Sync {
433    /// Terminate the OS process with the given PID. The TUI uses this for
434    /// "kill session" hotkeys.
435    fn terminate_session(&self, pid: u32) -> Result<(), String>;
436
437    /// Inject text into the session's terminal. Implementations pick the
438    /// right backend (tmux, Kitty, etc.) from the session metadata.
439    ///
440    /// The `text` is sent verbatim — the caller is responsible for any
441    /// trailing newline they want. Sanitization (e.g. neutralizing a leading
442    /// `/`) belongs to the caller; this trait is a transport.
443    fn inject_text(&self, session_id: &str, text: &str) -> Result<(), String>;
444
445    /// Update the persisted brain gate mode. Reflected back through
446    /// `BrainView::gate_mode` on the next call.
447    fn set_gate_mode(&self, mode: BrainGateMode) -> Result<(), String>;
448
449    /// Record an observation about a user action — non-LLM "the user did X."
450    /// Drives the brain's outcome telemetry and preference distillation.
451    fn log_observation(&self, observation: ObservationInput) -> Result<(), String>;
452
453    /// Record a user's accept/reject decision on a brain suggestion. The
454    /// distinction from `log_observation` is that `log_decision` carries
455    /// the actual suggestion that was on screen — the brain pairs it with
456    /// the user's response for outcome telemetry, counterfactual analysis,
457    /// and few-shot retrieval.
458    fn log_decision(&self, input: LogDecisionInput) -> Result<(), String>;
459
460    /// Mark a past brain decision as canonical for teaching. Optional `note`
461    /// is the operator's annotation. Used by the Brain Review surface.
462    fn mark_canonical(&self, decision_id: &str, note: Option<String>) -> Result<(), String>;
463
464    /// Bind an agent-bus role to a `(cwd, pid)` pair. The TUI calls this from
465    /// the new role-bind key (Ctrl+R) so the operator can attach a role to a
466    /// specific running Claude session without dropping to another terminal.
467    /// Returns `Err` when the bus feature is compiled out or the DB write
468    /// fails. See issue #307.
469    fn bind_bus_role(&self, name: &str, cwd: &str, pid: u32) -> Result<(), String>;
470
471    /// Cancel a supervisor task (move it to CANCELLED). Used by the Supervisor
472    /// panel's one-key cancel (#368). `Err` when the `coord` feature is compiled
473    /// out, the task is already terminal, or the store write fails.
474    fn cancel_task(&self, task_id: &str) -> Result<(), String>;
475
476    /// Set or clear the supervisor drain marker. When draining, the reconciler
477    /// stops issuing new task assignments while letting running tasks finish.
478    /// `Err` when the `coord` feature is compiled out.
479    fn set_supervisor_drain(&self, draining: bool) -> Result<(), String>;
480
481    /// Re-queue a failed/cancelled task (move it back to PENDING so the
482    /// reconciler re-assigns it). `Err` for a DONE task (nothing to retry), a
483    /// still-active task, or when the `coord` feature is compiled out.
484    fn retry_task(&self, task_id: &str) -> Result<(), String>;
485
486    /// Approve a NEEDS_HUMAN task — accept the work as-is and move it to DONE,
487    /// overriding the verifier that escalated it. `Err` when the task isn't in
488    /// NEEDS_HUMAN, or the `coord` feature is compiled out.
489    fn approve_task(&self, task_id: &str) -> Result<(), String>;
490}
491
492// ============================================================================
493// Hive actions — knowledge-store (`hive`) + transport (`relay`) reads/writes
494// ============================================================================
495
496/// Snapshot of local hive state the overlay reads to render the Hive tab.
497///
498/// Mirrors the binary's same-named struct, lifted here so the TUI can hold
499/// it without depending on the binary's app module.
500#[derive(Debug, Clone, Default)]
501pub struct HiveViewSnapshot {
502    /// Local relay identity (peer ID string). `None` when the `relay`
503    /// feature is compiled out.
504    pub identity: Option<String>,
505    /// Known peers, paired with last-seen address when available.
506    pub peers: Vec<(String, Option<String>)>,
507}
508
509/// Hive + relay surface the TUI needs to render the Skills and Hive panels.
510///
511/// Separate trait from `Actions` because the underlying subsystems are
512/// feature-gated (`hive`, `relay`) — when those features are off the
513/// implementation returns empty/no-op values rather than failing.
514pub trait HiveActions: Send + Sync {
515    /// Semantic keys (`skill:<lowered-name>`) of skills already shared into
516    /// the local hive store. Used by the Skills overlay to mark "already
517    /// shared" rows.
518    fn shared_skill_keys(&self) -> std::collections::HashSet<String>;
519
520    /// Share a discovered skill into the local hive store. Returns the new
521    /// unit ID on success.
522    fn share_skill(&self, skill: &crate::skills::DiscoveredSkill) -> Result<String, String>;
523
524    /// Current view of the local relay identity + known peers for the Hive
525    /// tab.
526    fn hive_view_snapshot(&self) -> HiveViewSnapshot;
527}
528
529// ============================================================================
530// Brain driver (stateful)
531// ============================================================================
532
533/// One pending brain suggestion the user can accept or reject. Mirrors the
534/// binary's `brain::client::BrainSuggestion` without exposing brain types.
535#[derive(Debug, Clone, Serialize, Deserialize)]
536pub struct PendingSuggestion {
537    /// PID of the session this suggestion applies to.
538    pub pid: u32,
539    /// String label of the suggested action — `"approve"`, `"deny"`,
540    /// `"send"`, `"terminate"`. String to avoid pulling `RuleAction`'s enum
541    /// shape into the contract (it's already in `claudectl-core::rules` but
542    /// callers may want to add new categories without bumping the trait).
543    pub action: String,
544    /// Suggested message body (a prompt to inject, a rationale to surface).
545    pub message: Option<String>,
546    /// Why the brain suggested this — used for the detail panel and the
547    /// rejection log.
548    pub reasoning: String,
549    /// 0.0–1.0 confidence the brain assigned.
550    pub confidence: f64,
551    /// Epoch seconds when the suggestion was created. Drives time-to-correct
552    /// telemetry.
553    pub suggested_at: u64,
554}
555
556/// Stateful brain orchestration. Unlike the read-only views, this needs
557/// `&mut` per tick — the engine accumulates pending suggestions, cleans up
558/// after exited sessions, and applies user accept/reject decisions.
559///
560/// Boxed as `Box<dyn BrainDriver>` rather than `Arc<dyn BrainDriver>`
561/// because there is exactly one owner (the TUI's `App`) and every method
562/// needs `&mut self`. Sharing across threads is not a goal here.
563///
564/// Implementations may be `None` — the brain is opt-in (`--brain` flag).
565/// When the field is `None` the TUI renders without brain interaction.
566pub trait BrainDriver: Send {
567    /// Run one tick of the brain loop against the current session set and
568    /// the operator's deny rules. Returns `(pid, status_message)` pairs
569    /// for any actions the brain decided on this tick — the TUI surfaces
570    /// the messages in the status bar.
571    fn tick(
572        &mut self,
573        sessions: &[SessionSnapshot],
574        deny_rules: &[crate::rules::AutoRule],
575    ) -> Vec<(u32, String)>;
576
577    /// Drop pending suggestions for sessions that have exited. Called every
578    /// refresh so the pending map stays bounded by the live session count.
579    fn cleanup(&mut self, sessions: &[SessionSnapshot]);
580
581    /// User accepted the pending suggestion for `pid`. Implementations
582    /// return the log message the TUI should surface (`None` when there's
583    /// no suggestion to accept).
584    fn accept(&mut self, pid: u32) -> Option<String>;
585
586    /// User rejected the pending suggestion for `pid`. Returns the
587    /// suggestion that was rejected — the TUI logs it for replay /
588    /// counterfactual analysis.
589    fn reject(&mut self, pid: u32) -> Option<PendingSuggestion>;
590
591    /// Lookup the pending suggestion for `pid`, if any. Used by detail
592    /// panels and the status bar.
593    fn pending_for(&self, pid: u32) -> Option<PendingSuggestion>;
594
595    /// Total pending suggestion count. Used by the status bar.
596    fn pending_count(&self) -> usize;
597
598    /// Drop every pending suggestion. Called when the brain mode flips
599    /// off or the operator resets state.
600    fn clear_pending(&mut self);
601
602    /// Inject a pending suggestion for `pid`. Used by demo mode to fake
603    /// brain activity for screenshots / recordings. Implementations may
604    /// drop suggestions whose `action` string doesn't map to a known
605    /// engine action (rather than erroring out) — demo is best-effort.
606    fn set_pending(&mut self, suggestion: PendingSuggestion);
607}
608
609// ============================================================================
610// Orchestrator
611// ============================================================================
612
613/// Tick the orchestration layer once per refresh: deliver pending mailbox
614/// messages, deliver pending coordination interrupts, and bookkeep stale
615/// rows in the underlying stores.
616///
617/// Each `deliver_*` method returns `(id, status_message)` tuples the TUI
618/// surfaces in the status bar. `id` is a `u32` for mailbox (matching the
619/// brain's per-PID queue) and a `String` for interrupts (matching the
620/// coord interrupt_id). They differ deliberately — keeping the trait honest
621/// to the underlying surfaces rather than papering over the distinction.
622///
623/// Unlike `CoordView` / `BrainView` which are read-only, this trait is
624/// stateful: each call writes to the brain/coord SQLite stores. It still
625/// boxes as `Arc<dyn>` because no method needs `&mut self` — implementations
626/// open a connection per call.
627///
628/// Implementations may be no-ops when the relevant feature is off (e.g. the
629/// `coord` feature is disabled at compile time), so call sites don't need
630/// `#[cfg(feature = "...")]` guards.
631pub trait Orchestrator: Send + Sync {
632    /// Drain pending mailbox messages addressed to running sessions and
633    /// deliver them to the live terminals. Used by `App::tick` to surface
634    /// `"Brain → sess_X: 'go ahead'"` style messages.
635    fn deliver_mailbox(&self, sessions: &[SessionSnapshot]) -> Vec<(u32, String)>;
636
637    /// Deliver pending coordination interrupts (cross-agent signals) to
638    /// running sessions. Returns `(interrupt_id, status_message)` tuples.
639    fn deliver_interrupts(&self, sessions: &[SessionSnapshot]) -> Vec<(String, String)>;
640
641    /// Expire stale leases and interrupts that have passed their deadline.
642    /// Bookkeeping side-effect; best-effort, no return. Implementations
643    /// log failures rather than propagating them.
644    fn expire_stale(&self);
645}
646
647// ============================================================================
648// Runtime aggregate
649// ============================================================================
650
651/// Single struct the binary builds at startup and hands to the TUI.
652///
653/// All fields are `Arc<dyn ...>` so the TUI doesn't care whether an impl is
654/// a thin SQLite wrapper, a remote HTTP client, or an in-memory mock — they
655/// all share the same shape.
656#[derive(Clone)]
657pub struct Runtime {
658    pub sessions: Arc<dyn SessionSource>,
659    pub brain: Arc<dyn BrainView>,
660    pub coord: Arc<dyn CoordView>,
661    pub bus: Arc<dyn BusView>,
662    pub actions: Arc<dyn Actions>,
663    pub review: Arc<dyn BrainReviewView>,
664    pub orchestrator: Arc<dyn Orchestrator>,
665    pub hive: Arc<dyn HiveActions>,
666}
667
668impl Runtime {
669    // 8-trait composition root; each view is its own arc. Splitting this into
670    // sub-records would just trade one wide ctor for several narrow ones with
671    // the same total fan-out.
672    #[allow(clippy::too_many_arguments)]
673    pub fn new(
674        sessions: Arc<dyn SessionSource>,
675        brain: Arc<dyn BrainView>,
676        coord: Arc<dyn CoordView>,
677        bus: Arc<dyn BusView>,
678        actions: Arc<dyn Actions>,
679        review: Arc<dyn BrainReviewView>,
680        orchestrator: Arc<dyn Orchestrator>,
681        hive: Arc<dyn HiveActions>,
682    ) -> Self {
683        Self {
684            sessions,
685            brain,
686            coord,
687            bus,
688            actions,
689            review,
690            orchestrator,
691            hive,
692        }
693    }
694}
695
696// ============================================================================
697// MockRuntime — for tests in this crate and in claudectl-tui
698// ============================================================================
699
700/// In-memory runtime backed by `Vec`s and interior-mutable counters. Used by
701/// tests in this crate to verify the trait shapes compile and roundtrip
702/// cleanly, and by the future `claudectl-tui` crate's tests to render the
703/// TUI against fixtures without dragging in brain / coord / bus.
704///
705/// `Actions` impls record their calls in `actions_log` so tests can assert
706/// "the TUI invoked the right side-effect" without spying on real I/O.
707#[derive(Default)]
708pub struct MockRuntime {
709    pub sessions: Vec<SessionSnapshot>,
710    pub gate_mode: std::sync::Mutex<Option<BrainGateMode>>,
711    pub decisions: Vec<DecisionSummary>,
712    pub review_queue: Vec<ReviewItemSummary>,
713    pub leases: Vec<LeaseSummary>,
714    pub handoffs: Vec<HandoffSummary>,
715    pub interrupts: Vec<InterruptSummary>,
716    pub tasks: Vec<TaskSummary>,
717    pub agents: Vec<AgentDirectoryEntry>,
718    pub roles: Vec<RoleBinding>,
719    pub actions_log: std::sync::Mutex<Vec<MockAction>>,
720}
721
722/// Recorded `Actions` calls. Tests use this to assert side-effect ordering
723/// without needing a real terminal or filesystem.
724#[derive(Debug, Clone, PartialEq, Eq)]
725pub enum MockAction {
726    Terminate {
727        pid: u32,
728    },
729    InjectText {
730        session_id: String,
731        text: String,
732    },
733    SetGateMode(BrainGateMode),
734    LogObservation(ObservationInput),
735    LogDecision(LogDecisionInput),
736    MarkCanonical {
737        decision_id: String,
738        note: Option<String>,
739    },
740    BindBusRole {
741        name: String,
742        cwd: String,
743        pid: u32,
744    },
745    CancelTask {
746        task_id: String,
747    },
748    SetSupervisorDrain {
749        draining: bool,
750    },
751    RetryTask {
752        task_id: String,
753    },
754    ApproveTask {
755        task_id: String,
756    },
757}
758
759impl PartialEq for ObservationInput {
760    fn eq(&self, other: &Self) -> bool {
761        self.session_pid == other.session_pid
762            && self.project == other.project
763            && self.tool == other.tool
764            && self.command == other.command
765            && self.observed_action == other.observed_action
766    }
767}
768
769impl Eq for ObservationInput {}
770
771impl PartialEq for LogDecisionInput {
772    fn eq(&self, other: &Self) -> bool {
773        self.session_pid == other.session_pid
774            && self.project == other.project
775            && self.tool == other.tool
776            && self.command == other.command
777            && self.user_action == other.user_action
778            && self.decision_type == other.decision_type
779            && self.override_reason == other.override_reason
780            // PendingSuggestion's field-by-field equality
781            && self.suggestion.pid == other.suggestion.pid
782            && self.suggestion.action == other.suggestion.action
783            && self.suggestion.message == other.suggestion.message
784            && self.suggestion.reasoning == other.suggestion.reasoning
785    }
786}
787
788impl Eq for LogDecisionInput {}
789
790impl MockRuntime {
791    pub fn into_runtime(self) -> Runtime {
792        let arc = Arc::new(self);
793        Runtime::new(
794            arc.clone(),
795            arc.clone(),
796            arc.clone(),
797            arc.clone(),
798            arc.clone(),
799            arc.clone(),
800            arc.clone(),
801            arc,
802        )
803    }
804
805    pub fn actions(&self) -> Vec<MockAction> {
806        self.actions_log
807            .lock()
808            .expect("actions_log poisoned")
809            .clone()
810    }
811}
812
813impl SessionSource for MockRuntime {
814    fn list(&self) -> Vec<SessionSnapshot> {
815        self.sessions.clone()
816    }
817}
818
819impl BrainView for MockRuntime {
820    fn gate_mode(&self) -> BrainGateMode {
821        self.gate_mode
822            .lock()
823            .expect("gate_mode poisoned")
824            .unwrap_or(BrainGateMode::On)
825    }
826    fn recent_decisions(&self, n: usize) -> Vec<DecisionSummary> {
827        self.decisions.iter().take(n).cloned().collect()
828    }
829    fn decision_count(&self) -> usize {
830        self.decisions.len()
831    }
832}
833
834impl CoordView for MockRuntime {
835    fn active_leases(&self) -> Vec<LeaseSummary> {
836        self.leases.clone()
837    }
838    fn pending_handoffs(&self) -> Vec<HandoffSummary> {
839        self.handoffs.clone()
840    }
841    fn pending_interrupts(&self) -> Vec<InterruptSummary> {
842        self.interrupts.clone()
843    }
844    fn tasks(&self) -> Vec<TaskSummary> {
845        self.tasks.clone()
846    }
847}
848
849impl BusView for MockRuntime {
850    fn list_agents(&self) -> Vec<AgentDirectoryEntry> {
851        self.agents.clone()
852    }
853    fn list_roles(&self) -> Vec<RoleBinding> {
854        self.roles.clone()
855    }
856}
857
858impl BrainReviewView for MockRuntime {
859    fn all_decisions(&self) -> Vec<DecisionSummary> {
860        self.decisions.clone()
861    }
862    fn review_queue(&self) -> Vec<ReviewItemSummary> {
863        self.review_queue.clone()
864    }
865}
866
867impl Orchestrator for MockRuntime {
868    fn deliver_mailbox(&self, _sessions: &[SessionSnapshot]) -> Vec<(u32, String)> {
869        Vec::new()
870    }
871    fn deliver_interrupts(&self, _sessions: &[SessionSnapshot]) -> Vec<(String, String)> {
872        Vec::new()
873    }
874    fn expire_stale(&self) {}
875}
876
877impl HiveActions for MockRuntime {
878    fn shared_skill_keys(&self) -> std::collections::HashSet<String> {
879        std::collections::HashSet::new()
880    }
881    fn share_skill(&self, _skill: &crate::skills::DiscoveredSkill) -> Result<String, String> {
882        Err("MockRuntime does not implement skill sharing".into())
883    }
884    fn hive_view_snapshot(&self) -> HiveViewSnapshot {
885        HiveViewSnapshot::default()
886    }
887}
888
889impl Actions for MockRuntime {
890    fn terminate_session(&self, pid: u32) -> Result<(), String> {
891        self.actions_log
892            .lock()
893            .expect("actions_log poisoned")
894            .push(MockAction::Terminate { pid });
895        Ok(())
896    }
897    fn inject_text(&self, session_id: &str, text: &str) -> Result<(), String> {
898        self.actions_log
899            .lock()
900            .expect("actions_log poisoned")
901            .push(MockAction::InjectText {
902                session_id: session_id.into(),
903                text: text.into(),
904            });
905        Ok(())
906    }
907    fn set_gate_mode(&self, mode: BrainGateMode) -> Result<(), String> {
908        *self.gate_mode.lock().expect("gate_mode poisoned") = Some(mode);
909        self.actions_log
910            .lock()
911            .expect("actions_log poisoned")
912            .push(MockAction::SetGateMode(mode));
913        Ok(())
914    }
915    fn log_observation(&self, observation: ObservationInput) -> Result<(), String> {
916        self.actions_log
917            .lock()
918            .expect("actions_log poisoned")
919            .push(MockAction::LogObservation(observation));
920        Ok(())
921    }
922    fn log_decision(&self, input: LogDecisionInput) -> Result<(), String> {
923        self.actions_log
924            .lock()
925            .expect("actions_log poisoned")
926            .push(MockAction::LogDecision(input));
927        Ok(())
928    }
929    fn mark_canonical(&self, decision_id: &str, note: Option<String>) -> Result<(), String> {
930        self.actions_log
931            .lock()
932            .expect("actions_log poisoned")
933            .push(MockAction::MarkCanonical {
934                decision_id: decision_id.into(),
935                note,
936            });
937        Ok(())
938    }
939    fn bind_bus_role(&self, name: &str, cwd: &str, pid: u32) -> Result<(), String> {
940        self.actions_log
941            .lock()
942            .expect("actions_log poisoned")
943            .push(MockAction::BindBusRole {
944                name: name.into(),
945                cwd: cwd.into(),
946                pid,
947            });
948        Ok(())
949    }
950    fn cancel_task(&self, task_id: &str) -> Result<(), String> {
951        self.actions_log
952            .lock()
953            .expect("actions_log poisoned")
954            .push(MockAction::CancelTask {
955                task_id: task_id.into(),
956            });
957        Ok(())
958    }
959    fn set_supervisor_drain(&self, draining: bool) -> Result<(), String> {
960        self.actions_log
961            .lock()
962            .expect("actions_log poisoned")
963            .push(MockAction::SetSupervisorDrain { draining });
964        Ok(())
965    }
966    fn retry_task(&self, task_id: &str) -> Result<(), String> {
967        self.actions_log
968            .lock()
969            .expect("actions_log poisoned")
970            .push(MockAction::RetryTask {
971                task_id: task_id.into(),
972            });
973        Ok(())
974    }
975    fn approve_task(&self, task_id: &str) -> Result<(), String> {
976        self.actions_log
977            .lock()
978            .expect("actions_log poisoned")
979            .push(MockAction::ApproveTask {
980                task_id: task_id.into(),
981            });
982        Ok(())
983    }
984}
985
986#[cfg(test)]
987mod tests {
988    use super::*;
989
990    fn sample_session(id: &str) -> SessionSnapshot {
991        SessionSnapshot {
992            session_id: id.into(),
993            pid: 12345,
994            cwd: "/work/proj".into(),
995            project_name: "proj".into(),
996            status: "Processing".into(),
997            cost_usd: 1.23,
998            context_tokens: 4000,
999            context_max: 200_000,
1000            last_message_ts: 1_780_000_000,
1001        }
1002    }
1003
1004    #[test]
1005    fn mock_runtime_assembles_and_lists_sessions() {
1006        let mock = MockRuntime {
1007            sessions: vec![sample_session("sess_a"), sample_session("sess_b")],
1008            ..Default::default()
1009        };
1010        let rt = mock.into_runtime();
1011        let listed = rt.sessions.list();
1012        assert_eq!(listed.len(), 2);
1013        assert_eq!(listed[0].session_id, "sess_a");
1014    }
1015
1016    #[test]
1017    fn session_detail_falls_back_to_list_scan() {
1018        let mock = MockRuntime {
1019            sessions: vec![sample_session("sess_a"), sample_session("sess_b")],
1020            ..Default::default()
1021        };
1022        let rt = mock.into_runtime();
1023        assert!(rt.sessions.detail("sess_a").is_some());
1024        assert!(rt.sessions.detail("sess_missing").is_none());
1025    }
1026
1027    #[test]
1028    fn brain_view_returns_recent_decisions_with_cap() {
1029        let mock = MockRuntime {
1030            decisions: (0..5)
1031                .map(|i| DecisionSummary {
1032                    id: format!("dec_{i}"),
1033                    timestamp: format!("2026-06-06T00:00:0{i}Z"),
1034                    action: "approve".into(),
1035                    confidence: Some(0.9),
1036                    project: None,
1037                    tool: None,
1038                    pid: 0,
1039                    command: None,
1040                    reasoning: None,
1041                    user_action: None,
1042                    override_reason: None,
1043                    brain_decision_ms: None,
1044                    canonical: None,
1045                    cache_hit: None,
1046                    cost_usd: None,
1047                    model: None,
1048                    outcome_kind: None,
1049                    outcome_detail: None,
1050                    suggested_at: None,
1051                    resolved_at: None,
1052                })
1053                .collect(),
1054            ..Default::default()
1055        };
1056        let rt = mock.into_runtime();
1057        assert_eq!(rt.brain.recent_decisions(3).len(), 3);
1058        assert_eq!(rt.brain.decision_count(), 5);
1059        assert_eq!(rt.brain.gate_mode(), BrainGateMode::On);
1060    }
1061
1062    #[test]
1063    fn coord_view_reports_empty_state_cleanly() {
1064        let rt = MockRuntime::default().into_runtime();
1065        assert!(rt.coord.active_leases().is_empty());
1066        assert!(rt.coord.pending_handoffs().is_empty());
1067        assert!(rt.coord.pending_interrupts().is_empty());
1068        assert!(rt.coord.tasks().is_empty());
1069    }
1070
1071    #[test]
1072    fn coord_view_returns_task_fixture() {
1073        let mock = MockRuntime {
1074            tasks: vec![TaskSummary {
1075                id: "t1".into(),
1076                name: "ship the thing".into(),
1077                state: "running".into(),
1078                role: Some("backend".into()),
1079                attempts: 2,
1080                max_retries: 3,
1081                last_session_id: Some("sess-abcdef12".into()),
1082                last_verdict: Some("PASS".into()),
1083                cost_usd: 1.25,
1084                created_at: "2026-06-25T10:00:00Z".into(),
1085                updated_at: "2026-06-25T10:05:00Z".into(),
1086            }],
1087            ..Default::default()
1088        };
1089        let rt = mock.into_runtime();
1090        let tasks = rt.coord.tasks();
1091        assert_eq!(tasks.len(), 1);
1092        assert_eq!(tasks[0].state, "running");
1093        assert_eq!(tasks[0].attempts, 2);
1094    }
1095
1096    #[test]
1097    fn bus_view_reports_empty_state_cleanly() {
1098        let rt = MockRuntime::default().into_runtime();
1099        assert!(rt.bus.list_agents().is_empty());
1100        assert!(rt.bus.list_roles().is_empty());
1101    }
1102
1103    /// Smoke test that the trait shapes are usable behind `dyn`. If this
1104    /// compiles, the boxed-trait composition works.
1105    #[test]
1106    fn runtime_implements_clone_and_send() {
1107        fn assert_send<T: Send>() {}
1108        assert_send::<Runtime>();
1109
1110        let rt = MockRuntime::default().into_runtime();
1111        let _rt2 = rt.clone();
1112    }
1113
1114    #[test]
1115    fn actions_terminate_records_in_log() {
1116        let rt = MockRuntime::default().into_runtime();
1117        rt.actions.terminate_session(42).unwrap();
1118        rt.actions.terminate_session(43).unwrap();
1119        // No public mock accessor on Arc<dyn Actions>, but we can downcast
1120        // through the trait by going via the *original* Arc through inspecting
1121        // the trait's behavior — the integration test in the binary covers
1122        // that surface. Here we just assert the calls succeeded.
1123    }
1124
1125    #[test]
1126    fn actions_task_writes_record_in_log() {
1127        let mock = MockRuntime::default();
1128        // MockRuntime itself implements Actions; call directly so we can read
1129        // the recorded log via the public `actions()` accessor.
1130        mock.cancel_task("t-1").unwrap();
1131        mock.set_supervisor_drain(true).unwrap();
1132        mock.retry_task("t-2").unwrap();
1133        mock.approve_task("t-3").unwrap();
1134        let actions = mock.actions();
1135        assert!(matches!(&actions[0], MockAction::CancelTask { task_id } if task_id == "t-1"));
1136        assert!(matches!(
1137            actions[1],
1138            MockAction::SetSupervisorDrain { draining: true }
1139        ));
1140        assert!(matches!(&actions[2], MockAction::RetryTask { task_id } if task_id == "t-2"));
1141        assert!(matches!(&actions[3], MockAction::ApproveTask { task_id } if task_id == "t-3"));
1142    }
1143
1144    #[test]
1145    fn actions_set_gate_mode_round_trips_through_brain_view() {
1146        let mock = MockRuntime::default();
1147        let arc = Arc::new(mock);
1148        let rt = Runtime::new(
1149            arc.clone(),
1150            arc.clone(),
1151            arc.clone(),
1152            arc.clone(),
1153            arc.clone(),
1154            arc.clone(),
1155            arc.clone(),
1156            arc.clone(),
1157        );
1158        // Initial: default On.
1159        assert_eq!(rt.brain.gate_mode(), BrainGateMode::On);
1160        // Flip via Actions; observe via BrainView.
1161        rt.actions.set_gate_mode(BrainGateMode::Off).unwrap();
1162        assert_eq!(rt.brain.gate_mode(), BrainGateMode::Off);
1163        rt.actions.set_gate_mode(BrainGateMode::Auto).unwrap();
1164        assert_eq!(rt.brain.gate_mode(), BrainGateMode::Auto);
1165        // And the log captured both transitions.
1166        let calls = arc.actions();
1167        assert_eq!(
1168            calls,
1169            vec![
1170                MockAction::SetGateMode(BrainGateMode::Off),
1171                MockAction::SetGateMode(BrainGateMode::Auto),
1172            ]
1173        );
1174    }
1175
1176    #[test]
1177    fn actions_log_observation_captures_full_input() {
1178        let mock = MockRuntime::default();
1179        let arc = Arc::new(mock);
1180        let rt = Runtime::new(
1181            arc.clone(),
1182            arc.clone(),
1183            arc.clone(),
1184            arc.clone(),
1185            arc.clone(),
1186            arc.clone(),
1187            arc.clone(),
1188            arc.clone(),
1189        );
1190        let obs = ObservationInput {
1191            session_pid: 12345,
1192            project: "claudectl".into(),
1193            tool: Some("Bash".into()),
1194            command: Some("cargo test".into()),
1195            observed_action: "user_approve".into(),
1196        };
1197        rt.actions.log_observation(obs.clone()).unwrap();
1198        let calls = arc.actions();
1199        assert_eq!(calls, vec![MockAction::LogObservation(obs)]);
1200    }
1201
1202    #[test]
1203    fn actions_inject_text_and_mark_canonical_record_inputs() {
1204        let mock = MockRuntime::default();
1205        let arc = Arc::new(mock);
1206        let rt = Runtime::new(
1207            arc.clone(),
1208            arc.clone(),
1209            arc.clone(),
1210            arc.clone(),
1211            arc.clone(),
1212            arc.clone(),
1213            arc.clone(),
1214            arc.clone(),
1215        );
1216        rt.actions.inject_text("sess_a", "/compact\n").unwrap();
1217        rt.actions
1218            .mark_canonical("dec_42", Some("nice catch".into()))
1219            .unwrap();
1220        let calls = arc.actions();
1221        assert_eq!(
1222            calls,
1223            vec![
1224                MockAction::InjectText {
1225                    session_id: "sess_a".into(),
1226                    text: "/compact\n".into(),
1227                },
1228                MockAction::MarkCanonical {
1229                    decision_id: "dec_42".into(),
1230                    note: Some("nice catch".into()),
1231                },
1232            ]
1233        );
1234    }
1235}