Skip to main content

codewhale_command_contract/
facets.rs

1//! Independent, object-safe capability shapes for staged command migration.
2//!
3//! FEAT-014 publishes these interfaces without implementing them for the TUI
4//! or changing an existing command. Later work adopts them inside
5//! `codewhale-tui` one command group at a time. Only after every group uses
6//! these shapes will groups move physically into a commands crate.
7
8pub use crate::config_policy::{CommandConfigStatusContext, CommandPermissionsContext};
9
10use std::path::{Path, PathBuf};
11
12mod session_structcopy;
13pub use session_structcopy::*;
14
15mod debug_operations;
16pub mod debug_receipts;
17pub use debug_operations::*;
18pub use debug_receipts::*;
19
20mod diagnostics_report;
21mod diagnostics_tools;
22pub use diagnostics_report::*;
23pub use diagnostics_tools::*;
24
25use codewhale_protocol::request::{Message, SystemPrompt};
26use serde_json::Value;
27
28use crate::types::{CommandApprovalMode, CommandCurrency, CommandMode, CommandProviderId};
29
30/// Session identity, messages, queue operations, and token totals.
31pub trait CommandSessionContext {
32    fn session_id(&self) -> Option<String>;
33    fn api_messages(&self) -> Vec<Message>;
34    fn add_message(&mut self, message: Message);
35    fn queued_message_count(&self) -> usize;
36    fn remove_queued_message(&mut self, index: usize) -> Result<(), String>;
37    fn total_tokens(&self) -> u64;
38}
39
40/// Model selection, provider identity, and fallback chain.
41///
42/// Slice 4 dropped the `reasoning_effort()` facet: reasoning preference is
43/// owned by `codewhale_tui::reasoning_preference::ReasoningEffort` and no
44/// command group consumed the duplicated boundary enum.
45pub trait CommandModelContext {
46    fn current_model(&self) -> String;
47    fn auto_model(&self) -> bool;
48    fn set_model_selection(&mut self, model: String, provider: Option<CommandProviderId>);
49    fn provider_identity(&self) -> Option<CommandProviderId>;
50    fn fallback_chain(&self) -> Vec<CommandProviderId>;
51}
52
53/// Cost display and accounting operations.
54pub trait CommandCostContext {
55    fn display_currency(&self) -> CommandCurrency;
56    fn session_cost_for_currency(&self, currency: CommandCurrency) -> f64;
57    fn subagent_cost_for_currency(&self, currency: CommandCurrency) -> f64;
58    fn accrue_cost_estimate(&mut self, amount: f64, currency: CommandCurrency);
59    fn record_turn_cost(
60        &mut self,
61        amount: f64,
62        currency: CommandCurrency,
63        route_receipt: Option<String>,
64    );
65}
66
67/// Operating mode, approval posture, shell access, and policy lock.
68pub trait CommandModePolicyContext {
69    fn mode(&self) -> CommandMode;
70    fn set_mode(&mut self, mode: CommandMode);
71    fn approval_mode(&self) -> CommandApprovalMode;
72    fn allow_shell(&self) -> bool;
73    fn set_shell_access(&mut self, allow: bool);
74    fn policy_locked(&self) -> bool;
75    /// Apply a mode selection the way `/mode` does, reporting which of the
76    /// three outcomes occurred (changed, same-but-persisted, refused).
77    fn select_mode(&mut self, mode: CommandMode) -> CommandModeSelection;
78    /// Apply the legacy YOLO alias (invisible Act + full access).
79    fn select_yolo_compat(&mut self) -> CommandModeSelection;
80    /// The receipt shown when the same mode was persisted as the default.
81    fn mode_startup_default_receipt(&self, mode: CommandMode) -> String;
82    /// The refusal text when a locked policy blocks the change.
83    fn setting_locked_mode_message(&self) -> String;
84    /// Localized display name for a mode (e.g. `Work`, `Plan`).
85    fn mode_label(&self, mode: CommandMode) -> String;
86    /// Localized label for the legacy YOLO alias (`Full Access (Work)`).
87    fn yolo_compat_label(&self) -> String;
88}
89
90/// Outcome of a `/mode` selection (mirrors the host `SettingSelection`).
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum CommandModeSelection {
93    Changed,
94    PersistedSame,
95    Refused,
96}
97
98/// Read access to the effective system prompt.
99pub trait CommandSystemPromptContext {
100    fn system_prompt(&self) -> Option<SystemPrompt>;
101}
102
103/// Active skill identity and skill-cache refresh.
104pub trait CommandSkillsContext {
105    fn active_skill(&self) -> Option<String>;
106    fn active_skill_provenance(&self) -> Option<String>;
107    fn refresh_skill_cache(&mut self);
108}
109
110/// Workspace path, bounded work-state observations and confined anchor storage.
111pub trait CommandWorkspaceContext {
112    fn workspace(&self) -> PathBuf;
113    fn effective_home_dir(&self) -> Option<PathBuf>;
114    fn inspect_workspace_target(&self, candidate: &Path) -> crate::navigation::WorkspaceTarget;
115    fn read_anchor_document(&self) -> Result<Option<String>, String>;
116    fn append_anchor_bytes(
117        &mut self,
118        parts: &[&[u8]],
119    ) -> Result<PathBuf, crate::navigation::AnchorWriteError>;
120    fn replace_anchor_document(&mut self, bytes: &[u8]) -> Result<(), String>;
121    fn work_state_snapshot(&self) -> Result<Option<String>, String>;
122    /// Session-aware canonical operation digest. Returns the final user-facing
123    /// digest text or a safe explicit error; never a serialized snapshot.
124    /// No-active-work and temporary-unavailability semantics are preserved by
125    /// the host implementation (FEAT-018 D5).
126    fn operation_digest(&mut self) -> Result<String, String>;
127}
128
129/// Stable-key translation with named replacements (FEAT-018 D3).
130///
131/// Message identity uses stable snake_case keys plus named replacements. The
132/// TUI host maps those keys to the current catalog and preserves the existing
133/// English fallback for intentionally incomplete locale packs. Unknown keys or
134/// invalid replacement contracts fail safely and produce a command error; they
135/// never panic and never display a raw lookup key.
136pub trait CommandPresentationContext {
137    /// Resolve a stable message key with its named replacements.
138    fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String>;
139
140    fn language_name(&self) -> &'static str {
141        "English"
142    }
143}
144
145/// Portable receipt for a successful atomic media attachment (FEAT-018 D4).
146/// Carries only the information needed for the existing confirmation text.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct MediaAttachmentReceipt {
149    pub kind: String,
150    pub path: std::path::PathBuf,
151}
152
153/// Atomic composer/media capability (FEAT-018 D4).
154///
155/// The host performs media validation and composer insertion as one atomic
156/// operation. Rejected, missing, unsupported, corrupt, or oversized media
157/// leaves composer state unchanged and returns a safe error. Only portable
158/// success information crosses the boundary; composer markup, mutable input
159/// text, decoder internals, and TUI types never do.
160pub trait CommandMediaContext {
161    /// Validate and insert a resolved media path atomically.
162    fn attach_media(&mut self, resolved_path: &Path) -> Result<MediaAttachmentReceipt, String>;
163}
164
165// ---------------------------------------------------------------------------
166// Debug diagnostics (FEAT-029 D3)
167// ---------------------------------------------------------------------------
168
169/// Only the provider identity and support decision consumed by `/balance`.
170/// The adapter derives support from the authoritative provider policy; the
171/// portable handler decides whether to emit `FetchBalance` or the original text.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct DebugBalanceProjection {
174    pub provider_display_name: String,
175    pub supports_balance_api: bool,
176}
177
178/// Source text consumed by `/system`; retain Text/Blocks/None separately
179/// so the portable handler alone owns the separators and empty-state text.
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum DebugSystemPrompt {
182    None,
183    Text(String),
184    Blocks(Vec<String>),
185}
186
187/// Only the data read by the `/system` renderer, with the host's mode label.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct DebugSystemProjection {
190    pub mode_label: String,
191    pub prompt: DebugSystemPrompt,
192}
193
194/// Published usage telemetry remains optional: absence is not zero.
195#[derive(Debug, Clone, PartialEq)]
196pub struct DebugTokenProjection {
197    pub active_context_used: usize,
198    pub context_window: u32,
199    pub last_input: Option<u32>,
200    pub last_output: Option<u32>,
201    pub cache_hit: Option<u32>,
202    pub cache_miss: Option<u32>,
203    pub total_tokens: u64,
204    pub cache_write_tokens: u64,
205    pub api_message_count: usize,
206    pub chat_message_count: usize,
207    pub model: String,
208    pub cost: DebugCostProjection,
209}
210
211/// Already-authoritative monetary values and bounded route attribution.
212/// Calculation and price/source selection stay with the TUI host; formatting,
213/// ordering and coverage wording belong to the portable handlers.
214#[derive(Debug, Clone, PartialEq)]
215pub struct DebugCostProjection {
216    pub currency: CommandCurrency,
217    pub total: f64,
218    pub parent_turns: f64,
219    pub subagents: f64,
220    pub display_floor: f64,
221    pub priced_turns: u32,
222    pub unpriced_turns: u32,
223    pub legacy_coverage_unknown: bool,
224    pub user_declared_estimates: bool,
225    pub itemized_turns: u32,
226    pub route_amounts: Vec<DebugRouteCost>,
227    pub turn_history_capacity: usize,
228    pub unpriced_reason_labels: Vec<String>,
229    pub unpriced_classes: Vec<String>,
230    pub pricing_provenances: Vec<String>,
231    pub live_pricing_defects: Vec<String>,
232    pub unusable_pricing_defects: Vec<String>,
233    pub route_receipts: Vec<String>,
234}
235
236#[derive(Debug, Clone, PartialEq)]
237pub struct DebugRouteCost {
238    pub route: String,
239    pub amount: f64,
240}
241
242/// A cache inspection's semantic layer, retaining the same public JSON
243/// field order as the baseline without borrowing the client request type.
244#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
245pub struct DebugPromptLayer {
246    pub name: String,
247    pub stability: DebugPromptLayerStability,
248    pub char_len: usize,
249    pub byte_len: usize,
250    pub token_estimate: usize,
251    pub sha256: String,
252    pub tool_result: Option<DebugToolResultInspection>,
253    pub turn_meta: Option<DebugTurnMetaInspection>,
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
257pub enum DebugPromptLayerStability {
258    Static,
259    History,
260    Dynamic,
261}
262
263impl DebugPromptLayerStability {
264    pub const fn label(self) -> &'static str {
265        match self {
266            Self::Static => "static",
267            Self::History => "history",
268            Self::Dynamic => "dynamic",
269        }
270    }
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
274pub struct DebugToolResultInspection {
275    pub original_chars: usize,
276    pub sent_chars: usize,
277    pub truncated: bool,
278    pub deduplicated: bool,
279}
280
281#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
282pub struct DebugTurnMetaInspection {
283    pub original_chars: usize,
284    pub sent_chars: usize,
285    pub deduplicated: bool,
286    pub sha256: String,
287}
288
289#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
290pub struct DebugPromptInspection {
291    pub base_static_prefix_hash: String,
292    pub full_request_prefix_hash: String,
293    pub tool_catalog_hash: String,
294    pub layers: Vec<DebugPromptLayer>,
295}
296
297/// Full key fields are needed for the existing comparison and JSON report;
298/// the short hash is computed by the authoritative host hashing function.
299#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
300pub struct DebugWarmupKey {
301    pub provider: String,
302    pub model: String,
303    pub base_url: String,
304    pub static_prefix_hash: String,
305    pub tool_catalog_hash: String,
306    pub project_pack_hash: String,
307    pub skills_hash: String,
308}
309
310/// One coherent observation, including previous inspection before any write.
311/// Inspect errors occur before this value exists and never update session state.
312#[derive(Debug, Clone, PartialEq, Eq)]
313pub struct DebugCacheInspectionObservation {
314    pub current: DebugPromptInspection,
315    pub previous: Option<DebugPromptInspection>,
316    pub current_warmup_key: DebugWarmupKey,
317    pub last_warmup_key: Option<DebugWarmupKey>,
318    pub current_warmup_hash_short: String,
319    pub last_warmup_hash_short: Option<String>,
320}
321
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub enum DebugCacheInspectionUnavailable {
324    NoConcreteRoute,
325    MissingCapturedEndpoint,
326}
327
328/// A bounded turn row. Pricing class partition and amount come from the
329/// authoritative host, not a second implementation of provider billing.
330/// Missing telemetry, missing audit and a measured zero remain distinct.
331#[derive(Debug, Clone, PartialEq)]
332pub struct DebugCacheTurn {
333    pub provider: Option<String>,
334    pub provider_identity: Option<String>,
335    pub model: Option<String>,
336    pub auto_model: bool,
337    pub input_tokens: u32,
338    pub output_tokens: u32,
339    pub cache_hit_tokens: Option<u32>,
340    pub cache_miss_tokens: Option<u32>,
341    pub cache_write_tokens: Option<u32>,
342    pub reasoning_tokens: Option<u32>,
343    pub reasoning_replay_tokens: Option<u32>,
344    pub priced_amount: Option<f64>,
345    pub unpriced_reason_key: Option<String>,
346    /// Original host enum order for deduplicated /cache note ordering.
347    pub unpriced_reason_sort_rank: Option<u8>,
348    pub unpriced_classes: Vec<String>,
349    pub priced_cache_read: u64,
350    pub priced_cache_miss: u64,
351    pub priced_cache_write: u64,
352    /// Coherent age at observation time; portable display rounds seconds.
353    pub age_seconds: u64,
354}
355
356/// Prompt-cache hit rates, each labelled by whose requests it covers (#6565).
357///
358/// `parent` is this conversation's own requests: the footer `cache N%` and it
359/// never change meaning. `agents` covers sub-agent and other background
360/// requests. `combined` weights both by their tokens. Each is `None` when its
361/// requests reported no cache telemetry; no report is never 0%.
362#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
363pub struct DebugCacheRates {
364    pub parent: Option<u8>,
365    pub agents: Option<u8>,
366    pub combined: Option<u8>,
367}
368
369impl DebugCacheRates {
370    /// `parent 82% · agents 64% · combined 75%` with the given words, or just
371    /// `82%` when only the parent reported. `None` when nothing did.
372    #[must_use]
373    pub fn labelled(&self, parent: &str, agents: &str, combined: &str) -> Option<String> {
374        match (self.parent, self.agents) {
375            (Some(pct), None) => Some(format!("{pct}%")),
376            (None, None) => None,
377            _ => Some(
378                [
379                    (parent, self.parent),
380                    (agents, self.agents),
381                    (combined, self.combined),
382                ]
383                .into_iter()
384                .filter_map(|(word, pct)| pct.map(|pct| format!("{word} {pct}%")))
385                .collect::<Vec<_>>()
386                .join(" · "),
387            ),
388        }
389    }
390}
391
392/// Shared source for `/cache [count|stats|zones]` branches. One host read
393/// preserves ring order, optional telemetry and prefix stability evidence.
394#[derive(Debug, Clone, PartialEq)]
395pub struct DebugCacheTelemetry {
396    pub model: String,
397    /// Parent/agent/combined percentages computed once by the host.
398    pub session_cache_rates: DebugCacheRates,
399    pub history: Vec<DebugCacheTurn>,
400    pub history_capacity: usize,
401    pub prefix_stability_pct: Option<u32>,
402    pub prefix_checks_total: u64,
403    pub prefix_change_count: u64,
404    pub prefix_drift_count: u64,
405    pub prefix_context_updates: u64,
406    pub prefix_pin_reason: Option<String>,
407    pub prefix_last_miss_reason: Option<String>,
408    pub last_prefix_change_desc: Option<String>,
409    pub last_pinned_prefix_hash: Option<String>,
410    pub api_message_count: usize,
411    pub non_system_message_count: usize,
412}
413
414/// Narrow, synchronous data boundary for the debug diagnostics slice.
415///
416/// No concrete provider, App, completed message, or network operation crosses
417/// this interface. Add operations only when their live branches require them.
418/// Portable handlers consume these facts without concrete host access.
419pub trait CommandDebugDiagnosticsContext {
420    fn balance_projection(&self) -> DebugBalanceProjection;
421    fn system_projection(&self) -> DebugSystemProjection;
422    fn token_projection(&self) -> DebugTokenProjection;
423    fn cost_projection(&self) -> DebugCostProjection;
424    fn cache_telemetry(&self) -> DebugCacheTelemetry;
425    /// The report builder stays host-owned; format and JSON serialization
426    /// consume only this data-only source map.
427    fn context_source_map(&self) -> DebugPromptSourceMap;
428    fn prompt_context(&self) -> DebugPromptContext;
429    /// None means no prepared snapshot exists; argument validation occurs
430    /// only after this check in the portable `/tools` handler.
431    fn tool_snapshot(&self) -> Option<DebugToolSnapshot>;
432    /// Route resolution and request inspection remain host-owned. This call
433    /// must not update the remembered inspection on failure or success.
434    fn inspect_cache(
435        &self,
436    ) -> Result<DebugCacheInspectionObservation, DebugCacheInspectionUnavailable>;
437    /// Store the already-observed inspection after portable rendering, without
438    /// rebuilding or re-inspecting the request. The baseline also commits on
439    /// JSON serialization fallback.
440    fn remember_cache_inspection(&mut self, inspection: DebugPromptInspection);
441}
442
443// ---------------------------------------------------------------------------
444// Project (FEAT-021 D1/D2/D3/D4)
445// ---------------------------------------------------------------------------
446
447/// Portable goal status for the project facet (FEAT-021 D1).
448///
449/// Mirrors the four TUI-owned `tools::goal::GoalStatus` variants without
450/// naming the TUI type. The adapter maps host state onto this enum; handlers
451/// compare and render it directly.
452#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
453pub enum ProjectGoalStatus {
454    #[default]
455    Active,
456    Paused,
457    Complete,
458    Blocked,
459}
460
461/// Portable goal projection (FEAT-021 D1).
462///
463/// Carries the visible goal state, the effective pending-control view, and the
464/// session-derived token fallback the live `/goal` handler consumes. Concrete
465/// goal-service, session-manager, and `App` types never cross the boundary.
466#[derive(Debug, Clone, PartialEq, Eq)]
467pub struct ProjectGoalState {
468    /// Visible goal objective.
469    pub objective: Option<String>,
470    /// Visible goal status.
471    pub status: ProjectGoalStatus,
472    /// Pause reason label when the goal is paused (already rendered).
473    pub pause_reason: Option<String>,
474    /// Elapsed seconds from `started_at` when present (host-computed).
475    pub started_at_elapsed_seconds: Option<u64>,
476    /// Seconds of goal time used (stable budget/elapsed source).
477    pub time_used_seconds: u64,
478    /// Optional token budget.
479    pub token_budget: Option<u32>,
480    /// Tokens used by the goal engine.
481    pub tokens_used: u64,
482    /// Session conversation-token total (fallback when tokens_used == 0).
483    pub session_total_tokens: u32,
484    /// Goal continuation count.
485    pub continuation_count: u32,
486    /// Whether pending goal controls are queued (effective-state gate).
487    pub pending_controls: bool,
488    /// Last-known durable objective (session-derived effective source).
489    pub last_known_objective: Option<String>,
490    /// Last-known durable status (session-derived effective source).
491    pub last_known_status: Option<ProjectGoalStatus>,
492    /// Whether the conversation has API messages (bare `/goal` context gate).
493    pub conversation_present: bool,
494    /// Whether the host is currently loading (idle-hint gate).
495    pub is_loading: bool,
496    /// Whether the goal continuation loop is waiting (idle-hint gate).
497    pub goal_continuation_waiting: bool,
498}
499
500/// Host project data for the project command group (FEAT-021 D1).
501///
502/// Exposes the typed, exact-minimum operations the live project handlers
503/// consume: `/lsp` status/set state, `/share` session payload data, and
504/// `/goal` goal state including the session-derived effective values.
505/// `/init` host data flows through the existing `WORKSPACE` facet (D2), so
506/// `/init` destructures exactly `WORKSPACE` (D4) and consumes no
507/// project-facet method. All results are contract-owned portable values; implementation
508/// errors cross as safe text. The TUI adapter is the only place that touches
509/// `App`, `config::config`, the goal service, or the session manager.
510pub trait CommandProjectContext {
511    /// `/lsp` status: whether LSP diagnostics are enabled.
512    fn lsp_enabled(&self) -> bool;
513    /// `/lsp` set: enable or disable LSP diagnostics.
514    fn lsp_set(&mut self, enabled: bool) -> Result<(), String>;
515    /// `/goal` projection: visible and effective goal state.
516    fn goal_state(&self) -> ProjectGoalState;
517}
518
519// ---------------------------------------------------------------------------
520// Memory (FEAT-019 D1/D2/D8/D9)
521// ---------------------------------------------------------------------------
522
523/// Portable semantic hit for a native-memory search or get result.
524///
525/// Carries only the typed location and text the handler consumes for
526/// formatting; the TUI-owned `NativeMemoryHit` never crosses the boundary.
527#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct MemoryHit {
529    pub source: PathBuf,
530    pub line_start: usize,
531    pub line_end: usize,
532    pub text: String,
533}
534
535/// Portable native-memory location summary (status operation).
536#[derive(Debug, Clone, PartialEq, Eq)]
537pub struct MemoryStatus {
538    pub root: PathBuf,
539    pub source: PathBuf,
540    pub index: PathBuf,
541}
542
543/// Portable result of a successful remember operation.
544#[derive(Debug, Clone, PartialEq, Eq)]
545pub struct MemoryRemembered {
546    pub source: PathBuf,
547    pub line_start: usize,
548}
549
550/// Portable import outcome: imported (with destination) or skipped.
551#[derive(Debug, Clone, PartialEq, Eq)]
552pub enum MemoryImportOutcome {
553    Imported { destination: PathBuf },
554    Skipped,
555}
556
557/// Portable get outcome: found hit or explicit not-found.
558#[derive(Debug, Clone, PartialEq, Eq)]
559pub enum MemoryGetOutcome {
560    Found(MemoryHit),
561    NotFound,
562}
563
564/// Portable export payload — the exported memory document itself, never a
565/// preformatted command response.
566#[derive(Debug, Clone, PartialEq, Eq)]
567pub struct MemoryExport {
568    pub content: String,
569}
570
571/// Portable reindex entry count.
572#[derive(Debug, Clone, PartialEq, Eq)]
573pub struct MemoryReindex {
574    pub entry_count: usize,
575}
576
577/// Zero-field success value for delete operations (D2): the handler already
578/// owns the selected scope and needs no additional success data.
579#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
580pub struct MemoryDelete;
581
582/// Typed remember target (D9): the handler resolves workspace identity through
583/// the workspace facet and passes the resulting typed ID here.
584#[derive(Debug, Clone, PartialEq, Eq)]
585pub enum MemoryRememberTarget {
586    Global,
587    Workspace { workspace_id: String },
588}
589
590/// Typed delete scope for the non-workspace delete method (D8/D9).
591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
592pub enum MemoryDeleteScope {
593    /// Delete every memory entry (global and all workspace scopes).
594    All,
595    /// Delete only the global scope entries.
596    Global,
597}
598
599/// Host memory data for the memory command group (FEAT-019 D1).
600///
601/// Exposes the resolved user-memory file path, the enablement flag, and one
602/// typed method per exposed native-memory operation. All results are
603/// contract-owned portable values; implementation errors cross as safe text.
604/// Workspace-scoped operations take the borrowed workspace path as their first
605/// argument (D8); non-workspace operations never receive workspace authority
606/// and the facet never captures or retains workspace state internally.
607pub trait CommandMemoryContext {
608    /// The resolved user-memory file path.
609    fn memory_path(&self) -> PathBuf;
610    /// Whether the `[memory] enabled` / `DEEPSEEK_MEMORY=on` flag is set.
611    fn memory_enabled(&self) -> bool;
612    /// Native-memory root, global source, and index paths.
613    fn status(&self) -> Result<MemoryStatus, String>;
614    /// The native-memory root path.
615    fn path(&self) -> Result<PathBuf, String>;
616    /// Workspace identity for the given workspace path.
617    fn workspace_id(&self, workspace: &Path) -> Result<String, String>;
618    /// Workspace-scoped search over the native-memory store.
619    fn search(&self, workspace: &Path, query: &str, limit: usize)
620    -> Result<Vec<MemoryHit>, String>;
621    /// Append a reviewed note to the typed global or workspace target.
622    fn remember(
623        &self,
624        target: MemoryRememberTarget,
625        note: &str,
626    ) -> Result<MemoryRemembered, String>;
627    /// Import legacy memory; distinguishes imported from skipped.
628    fn import(&self) -> Result<MemoryImportOutcome, String>;
629    /// Workspace-scoped get by entry id; not-found is a typed outcome.
630    fn get(&self, workspace: &Path, id: i64) -> Result<MemoryGetOutcome, String>;
631    /// Export the native-memory document content.
632    fn export(&self) -> Result<MemoryExport, String>;
633    /// Reindex the native-memory store; returns the indexed entry count.
634    fn reindex(&self) -> Result<MemoryReindex, String>;
635    /// Delete all or global scope; never receives workspace authority.
636    fn delete(&self, scope: MemoryDeleteScope) -> Result<MemoryDelete, String>;
637    /// Delete the given workspace scope; workspace path is the first argument.
638    fn delete_workspace(&self, workspace: &Path) -> Result<MemoryDelete, String>;
639}
640
641// ---------------------------------------------------------------------------
642// Plugin (FEAT-020 D1/D2/D10/D11)
643// ---------------------------------------------------------------------------
644
645/// Portable plugin diagnostic level (FEAT-020 D2).
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
647pub enum PluginDiagnosticLevel {
648    Warning,
649    Error,
650}
651
652/// Portable plugin diagnostic entry.
653#[derive(Debug, Clone, PartialEq, Eq)]
654pub struct PluginDiagnostic {
655    pub level: PluginDiagnosticLevel,
656    pub code: String,
657    pub message: String,
658    pub path: Option<PathBuf>,
659}
660
661/// Portable MCP transport classification for the capability review body.
662#[derive(Debug, Clone, Copy, PartialEq, Eq)]
663pub enum PluginMcpTransport {
664    Stdio,
665    Http,
666    Invalid,
667}
668
669/// Portable MCP server detail for the capability review body (FEAT-020 D2).
670///
671/// Carries only the semantic fields `render_mcp_inventory` consumes:
672/// transport, command/url, argv, cwd, env provenance, timeouts, required,
673/// enabled/disabled tool lists, and the enabled flag. Host `McpServerConfig`
674/// never crosses the boundary.
675#[derive(Debug, Clone, PartialEq, Eq)]
676pub struct PluginMcpServerDetail {
677    pub name: String,
678    pub transport: PluginMcpTransport,
679    pub command: Option<String>,
680    pub argv: Vec<String>,
681    pub cwd: Option<PathBuf>,
682    pub env: Vec<(String, String)>,
683    pub url: Option<String>,
684    pub env_headers: Vec<(String, String)>,
685    pub bearer_token_env_var: Option<String>,
686    pub connect_timeout_secs: Option<u64>,
687    pub execute_timeout_secs: Option<u64>,
688    pub read_timeout_secs: Option<u64>,
689    pub required: bool,
690    pub enabled_tools: Vec<String>,
691    pub disabled_tools: Vec<String>,
692    pub enabled: bool,
693}
694
695/// Portable summary of one loaded plugin bundle (list output, FEAT-020 D2).
696#[derive(Debug, Clone, PartialEq, Eq)]
697pub struct PluginSummary {
698    pub name: String,
699    pub id: String,
700    pub state_label: String,
701    pub scope: String,
702    pub trust_status: String,
703    pub compatibility: String,
704    pub inventory: String,
705    pub active: bool,
706    pub trusted: bool,
707    pub enabled: bool,
708}
709
710/// Portable full bundle detail for show/review/validate rendering (FEAT-020 D2).
711///
712/// Carries every semantic value the render helpers consume. The complete
713/// `LoadedPlugin` never crosses the boundary; only branch-consumed fields are
714/// projected here (D10).
715#[derive(Debug, Clone, PartialEq, Eq)]
716pub struct PluginDetail {
717    /// Inventory summary string (host-computed, e.g. `skills=1 mcp=0`).
718    pub inventory_summary: String,
719    pub name: String,
720    pub id: String,
721    pub version: String,
722    pub origin: String,
723    pub scope: String,
724    pub state_label: String,
725    pub trust_status: String,
726    pub compatibility: String,
727    pub content_hash: String,
728    pub capability_hash: String,
729    pub canonical_root: PathBuf,
730    pub active: bool,
731    pub trusted: bool,
732    pub enabled: bool,
733    pub unsupported_labels: Vec<String>,
734    pub supported_labels: Vec<String>,
735    pub skills: Vec<String>,
736    pub filesystem_roots: Vec<String>,
737    pub network_hosts: Vec<String>,
738    pub stdio_mcp_servers: usize,
739    pub lifecycle_mutation: bool,
740    pub mcp_servers: Vec<PluginMcpServerDetail>,
741    pub diagnostics: Vec<PluginDiagnostic>,
742}
743
744/// Portable outcome of a plugin mutation (FEAT-020 D2/D11).
745#[derive(Debug, Clone, PartialEq, Eq)]
746pub enum PluginMutationOutcome {
747    Installed,
748    Updated,
749    NoChange,
750    Uninstalled,
751    NeedsApproval(String),
752    NetworkDenied(String),
753}
754
755/// Portable mutation receipt returned synchronously by the facet (FEAT-020 D11).
756#[derive(Debug, Clone, PartialEq, Eq)]
757pub struct PluginMutationReceipt {
758    pub name: String,
759    pub path: Option<PathBuf>,
760    pub content_hash: Option<String>,
761    pub installed_content_hash: Option<String>,
762    pub outcome: PluginMutationOutcome,
763}
764
765/// Portable bundle export receipt (FEAT-020 D2).
766#[derive(Debug, Clone, PartialEq, Eq)]
767pub struct PluginExportReceipt {
768    pub exported_name: String,
769    pub target: PathBuf,
770    pub display_name: Option<String>,
771    pub wrote_mcp_json: bool,
772    pub files_copied: u64,
773    pub skills_normalized: bool,
774}
775
776/// Portable legacy executable-tool detail (FEAT-020 D2).
777#[derive(Debug, Clone, PartialEq, Eq)]
778pub struct PluginLegacyTool {
779    pub name: String,
780    pub description: String,
781    pub approval: String,
782    pub input_schema: Option<String>,
783    pub path: PathBuf,
784}
785
786/// Portable legacy-tool scan result: directory, discovered tools, and load
787/// diagnostics for scripts that asked for something the loader ignored.
788#[derive(Debug, Clone, PartialEq, Eq)]
789pub struct PluginLegacyScan {
790    pub dir: PathBuf,
791    pub tools: Vec<PluginLegacyTool>,
792    pub diagnostics: Vec<PluginDiagnostic>,
793}
794
795/// Portable Kimi managed-plugin candidate (FEAT-020 D2).
796#[derive(Debug, Clone, PartialEq, Eq)]
797pub struct PluginManagedCandidate {
798    pub name: String,
799    pub version: String,
800    pub license: Option<String>,
801    pub canonical_path: PathBuf,
802    pub content_hash: String,
803    pub capability_hash: String,
804    pub inventory: String,
805    pub applicable: bool,
806}
807
808/// Portable Kimi managed-scan result (FEAT-020 D2).
809#[derive(Debug, Clone, PartialEq, Eq)]
810pub struct PluginManagedScan {
811    pub root: PathBuf,
812    pub candidates: Vec<PluginManagedCandidate>,
813    pub rejected: Vec<String>,
814}
815
816/// Portable review of a DeepSeek Harness bundle package before import: what
817/// converts, what is skipped, the authority it will request, and the content
818/// hash an exact install of the same package stages.
819#[derive(Debug, Clone, PartialEq, Eq)]
820pub struct PluginDshPreview {
821    pub package_path: PathBuf,
822    pub plugin_name: String,
823    pub source_package: Option<String>,
824    pub source_version: Option<String>,
825    pub content_hash: String,
826    pub skills: Vec<String>,
827    pub remote_servers: Vec<String>,
828    pub local_servers: Vec<String>,
829    pub network_hosts: Vec<String>,
830    /// Rows that become Native host code (JavaScript run by the extension host).
831    pub native_rows: Vec<String>,
832    pub requires_node: bool,
833    /// One line per skipped row or patch operation (a manual port).
834    pub manual_ports: Vec<String>,
835    pub diagnostics: Vec<String>,
836}
837
838/// Portable marketplace candidate install plan (FEAT-020 D2).
839#[derive(Debug, Clone, PartialEq, Eq)]
840pub enum PluginMarketplaceInstallPlan {
841    Supported { spec: String, source_kind: String },
842    AlreadyPresent { selector: String, reason: String },
843    Unsupported { reason: String },
844}
845
846/// Portable marketplace candidate (FEAT-020 D2).
847#[derive(Debug, Clone, PartialEq, Eq)]
848pub struct PluginMarketplaceCandidate {
849    pub name: String,
850    pub display_name: Option<String>,
851    pub version: Option<String>,
852    pub tier: String,
853    pub compatibility: Option<String>,
854    pub install_plan: PluginMarketplaceInstallPlan,
855    pub description: Option<String>,
856    pub homepage: Option<String>,
857    pub repository: Option<String>,
858    pub author: Option<String>,
859    pub license: Option<String>,
860    pub keywords: Vec<String>,
861    pub when: Option<String>,
862    pub diagnostics: Vec<PluginDiagnostic>,
863    pub has_errors: bool,
864}
865
866/// Portable marketplace catalog (FEAT-020 D2).
867#[derive(Debug, Clone, PartialEq, Eq)]
868pub struct PluginMarketplaceCatalog {
869    pub id: String,
870    /// Source document path (for the `show` provenance line).
871    pub source_path: Option<String>,
872    pub display_name: Option<String>,
873    pub description: Option<String>,
874    pub format: String,
875    pub tier: String,
876    pub publisher: Option<String>,
877    pub total_candidates: usize,
878    pub warning_count: usize,
879    pub candidates: Vec<PluginMarketplaceCandidate>,
880    pub diagnostics: Vec<PluginDiagnostic>,
881}
882
883/// Portable marketplace add receipt (FEAT-020 D2).
884#[derive(Debug, Clone, PartialEq, Eq)]
885pub struct PluginMarketplaceAddReceipt {
886    pub name: String,
887    pub candidate_count: usize,
888    pub warning_count: usize,
889    pub catalog: PluginMarketplaceCatalog,
890}
891
892/// Portable marketplace state: stored catalogs plus an optional host-provided
893/// built-in `official` catalog.
894#[derive(Debug, Clone, PartialEq, Eq)]
895pub struct PluginMarketplaceState {
896    /// Optional host-provided built-in catalog. Current main provides none;
897    /// retaining the option keeps the portable boundary future-compatible
898    /// without inventing a catalog in the handler.
899    pub official: Option<PluginMarketplaceCatalog>,
900    pub stored: Vec<PluginMarketplaceCatalog>,
901}
902
903/// Portable suggestion for the `/plugin suggest` recommendation output.
904#[derive(Debug, Clone, PartialEq, Eq)]
905pub struct PluginSuggestion {
906    pub name: String,
907    /// State label rendered beside the plugin name (active/not-reviewed/…).
908    pub state_label: String,
909    pub description: String,
910    pub why: Vec<String>,
911    /// The actionable next step rendered under the suggestion.
912    pub next_step: String,
913}
914
915/// Plugins hidden from proactive suggestions (plugin policy rule 9). Names
916/// are lowercase; each list is sorted.
917#[derive(Debug, Clone, Default, PartialEq, Eq)]
918pub struct PluginSuggestionDismissals {
919    /// "Don't suggest again": kept across sessions until reset.
920    pub persisted: Vec<String>,
921    /// Hidden for this session only (Esc, or a review the user already opened).
922    pub session: Vec<String>,
923}
924
925/// Host plugin data for the plugin command group (FEAT-020 D1).
926///
927/// One object-safe, synchronous facet exposing the exact-minimum typed
928/// operations the live `/plugin` branch closure consumes. Registry reads and
929/// mutations, async-bridged install/update/uninstall (returning synchronous
930/// portable receipts), export, legacy executable-tool scan, Kimi managed
931/// import, and marketplace operations are all represented. The handler never
932/// names `crate::plugins`, `PluginRegistry`, `LoadedPlugin`, `Config`, or
933/// another concrete host service; implementation errors cross as safe text.
934///
935/// Post-mutation side effects (rediscovery, skill-cache refresh, active-skill
936/// reset) happen host-side inside the facet implementation; the handler only
937/// renders the returned receipt (D11).
938pub trait CommandPluginContext {
939    /// Read-only: registry summaries for list output.
940    fn summaries(&self) -> Result<Vec<PluginSummary>, String>;
941    /// Read-only: full portable detail for show/review/validate.
942    fn detail(&self, selector: &str) -> Result<PluginDetail, String>;
943    /// Read-only: registry-level diagnostics.
944    fn registry_diagnostics(&self) -> Vec<PluginDiagnostic>;
945    /// Read-only: whether validation reports no errors.
946    fn validation_is_clean(&self) -> bool;
947    /// Read-only: registry length (used by list/reload empty branches).
948    fn len(&self) -> usize;
949    /// Mutation: rediscover the workspace registry and refresh the skill
950    /// cache; returns the new registry length for the reload message.
951    fn reload(&mut self) -> Result<usize, String>;
952    /// Read-only: whether the registry is empty.
953    fn is_empty(&self) -> bool;
954    /// Return the one-shot on-disk-change nudge, if the host detects one.
955    /// The host owns the mutable catalog-stamp state; handlers only render.
956    fn reload_nudge(&mut self) -> Option<String>;
957    /// Read-only: persistence store path for marketplace state.
958    fn state_path(&self) -> Option<PathBuf>;
959    /// Read-only: recommend installed bundles for a task without side effects.
960    fn suggest(&self, task: &str) -> Result<Vec<PluginSuggestion>, String>;
961    /// Mutation: trust a bundle by exact review token. Success means the
962    /// mutation was applied; the handler renders the action word from its own
963    /// dispatch arm and may re-read `detail` for post-mutation state.
964    fn trust(&mut self, selector: &str, token: &str) -> Result<(), String>;
965    /// Mutation: enable a bundle. Success means enabled; re-read `detail` for
966    /// the post-mutation compatibility note.
967    fn enable(&mut self, selector: &str) -> Result<(), String>;
968    /// Mutation: disable a bundle.
969    fn disable(&mut self, selector: &str) -> Result<(), String>;
970    /// Mutation: revoke trust.
971    fn revoke_trust(&mut self, selector: &str) -> Result<(), String>;
972    /// Async-bridged install; returns a synchronous portable receipt (D11).
973    fn install(
974        &mut self,
975        source: &str,
976        expected_content_hash: Option<&str>,
977    ) -> Result<PluginMutationReceipt, String>;
978    /// Async-bridged update; returns a synchronous portable receipt (D11).
979    fn update(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
980    /// Async-bridged uninstall; returns a synchronous portable receipt (D11).
981    fn uninstall(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
982    /// File-level removal of a just-installed bundle whose content hash
983    /// mismatched (rollback). Unlike [`Self::uninstall`] it does not resolve a
984    /// registry selector and triggers no rediscovery or skill-cache side
985    /// effects; the host adapter owns the `crate::plugins` call (D1).
986    fn uninstall_path(&mut self, name: &str, plugins_dir: &Path) -> Result<(), String>;
987    /// Read-only: export a loaded bundle to a target directory.
988    fn export(&self, selector: &str, target: &Path) -> Result<PluginExportReceipt, String>;
989    /// Read-only: scan legacy executable plugin tools.
990    fn legacy_scan(&self) -> Result<Option<PluginLegacyScan>, String>;
991    /// Read-only: Kimi managed-plugin directory scan.
992    fn managed_scan(&self, home_override: Option<&Path>) -> Result<PluginManagedScan, String>;
993    /// Mutation: install a Kimi managed candidate by exact content hash.
994    fn managed_install(
995        &mut self,
996        canonical_path: &Path,
997        expected_content_hash: &str,
998    ) -> Result<PluginMutationReceipt, String>;
999    /// Read-only: convert a DeepSeek Harness bundle package into scratch and
1000    /// review it without installing anything.
1001    fn dsh_preview(&self, package: &Path) -> Result<PluginDshPreview, String> {
1002        let _ = package;
1003        Err("DeepSeek Harness import is not available in this host.".to_string())
1004    }
1005    /// Read-only: marketplace state (optional host catalog + stored catalogs).
1006    fn marketplace_state(&self) -> Result<PluginMarketplaceState, String>;
1007    /// Mutation: add a local catalog document to the marketplace store.
1008    fn marketplace_add(
1009        &mut self,
1010        name: &str,
1011        path: &Path,
1012    ) -> Result<PluginMarketplaceAddReceipt, String>;
1013    /// Mutation: remove a stored marketplace catalog.
1014    fn marketplace_remove(&mut self, name: &str) -> Result<bool, String>;
1015    /// Mutation: install a marketplace candidate through the reviewed installer.
1016    fn marketplace_install(
1017        &mut self,
1018        catalog: &str,
1019        candidate: &str,
1020    ) -> Result<PluginMutationReceipt, String>;
1021    /// Read-only: which plugins proactive suggestions currently skip.
1022    fn suggestion_dismissals(&self) -> Result<PluginSuggestionDismissals, String>;
1023    /// Mutation: let suggestions offer `name` again (every dismissed plugin
1024    /// when `None`), in this session and future ones. Returns the names
1025    /// cleared, sorted.
1026    fn reset_suggestion_dismissals(&mut self, name: Option<&str>) -> Result<Vec<String>, String>;
1027}
1028
1029// ---------------------------------------------------------------------------
1030// Skill group (FEAT-022 D1)
1031// ---------------------------------------------------------------------------
1032
1033/// Source provenance of a discovered skill (native file vs reviewed plugin snapshot).
1034#[derive(Debug, Clone, PartialEq, Eq)]
1035pub enum SkillSourceKind {
1036    Native,
1037    Plugin {
1038        plugin_name: String,
1039        plugin_id: String,
1040    },
1041}
1042
1043/// Curated product tier for bundled (shipped) skills.
1044///
1045/// The canonical name→tier classification stays in the TUI host
1046/// (`crate::skills::system::bundled_skill_tier`); the portable projection
1047/// carries the resolved tier so the handler can render the curated listing
1048/// without duplicating the canonical bundle list.
1049#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1050pub enum SkillBundledTier {
1051    CoreAgentic,
1052    FormatTooling,
1053}
1054
1055impl SkillBundledTier {
1056    /// Product-facing tier heading used by the `/skills` listing.
1057    #[must_use]
1058    pub fn heading(self) -> &'static str {
1059        match self {
1060            Self::CoreAgentic => "Core agentic",
1061            Self::FormatTooling => "Format & tooling",
1062        }
1063    }
1064}
1065
1066/// One discovered skill entry (portable).
1067///
1068/// The body is intentionally excluded: activation and review receive body
1069/// text through their own delegates (`SkillActivationOutcome`/`ReviewOutcome`);
1070/// listing and inspect render name, description, source, and path only (D1
1071/// exact-minimum).
1072#[derive(Debug, Clone, PartialEq, Eq)]
1073pub struct SkillEntry {
1074    pub name: String,
1075    pub description: String,
1076    pub source: SkillSourceKind,
1077    /// Native skills carry their on-disk path (inspect output).
1078    pub path: Option<String>,
1079    /// Bundled catalog tier; `None` for user/compatible skills.
1080    pub bundled_tier: Option<SkillBundledTier>,
1081}
1082
1083/// Portable projection of the host skill registry (discovery, D1).
1084///
1085/// Carries every value the `/skills` and `/skill` handlers render: workspace
1086/// and configured skills dir displays, discovery mode label, searched
1087/// directories, entries, warnings, and the enabled-skill total.
1088#[derive(Debug, Clone, PartialEq, Eq)]
1089pub struct SkillRegistryProjection {
1090    pub workspace: String,
1091    pub skills_dir: String,
1092    pub mode_label: String,
1093    pub dirs: Vec<String>,
1094    pub entries: Vec<SkillEntry>,
1095    pub warnings: Vec<String>,
1096    pub total: usize,
1097}
1098
1099/// Target scope for skill mutations (`/skill install|update|uninstall|trust`).
1100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1101pub enum SkillTargetScope {
1102    Project,
1103    Global,
1104}
1105
1106/// Portable mutation outcome mirroring the host receipt variants.
1107#[derive(Debug, Clone, PartialEq, Eq)]
1108pub enum SkillMutationOutcome {
1109    Installed,
1110    Updated,
1111    NoChange,
1112    Removed,
1113    Trusted,
1114    Imported,
1115    AlreadyPresent,
1116    NeedsApproval(String),
1117    NetworkDenied(String),
1118}
1119
1120/// Synchronous portable receipt for a skill mutation (FEAT-020 D11 mirror):
1121/// the host owns the async network bridge; the handler renders the receipt
1122/// byte-identically from these values.
1123#[derive(Debug, Clone, PartialEq, Eq)]
1124pub struct SkillMutationReceipt {
1125    pub name: String,
1126    pub safe_target_path: String,
1127    pub outcome: SkillMutationOutcome,
1128}
1129
1130/// One curated remote registry entry (`/skills --remote`).
1131#[derive(Debug, Clone, PartialEq, Eq)]
1132pub struct RemoteSkillEntry {
1133    pub name: String,
1134    pub description: Option<String>,
1135    pub source: String,
1136}
1137
1138/// Remote registry fetch outcome (`/skills --remote`, suggest source).
1139#[derive(Debug, Clone, PartialEq, Eq)]
1140pub enum RemoteRegistryOutcome {
1141    Loaded { entries: Vec<RemoteSkillEntry> },
1142    NeedsApproval(String),
1143    Denied(String),
1144}
1145
1146/// Remote recommendation for `/skills suggest <task>`.
1147#[derive(Debug, Clone, PartialEq, Eq)]
1148pub struct SkillRecommendation {
1149    pub name: String,
1150    pub description: Option<String>,
1151    pub matched_terms: Vec<String>,
1152}
1153
1154/// Per-skill outcome of `/skills sync`.
1155#[derive(Debug, Clone, PartialEq, Eq)]
1156pub enum SkillSyncEntry {
1157    Downloaded { name: String, path: String },
1158    Fresh { name: String },
1159    Failed { name: String, reason: String },
1160    Denied { name: String, host: String },
1161    NeedsApproval { name: String, host: String },
1162}
1163
1164/// Aggregate `/skills sync` outcome.
1165///
1166/// Registry-level network-policy outcomes are carried as variants so the
1167/// portable handler composes the exact `needs_approval` / `denied` messages.
1168#[derive(Debug, Clone, PartialEq, Eq)]
1169pub enum SkillSyncOutcome {
1170    Done {
1171        total: usize,
1172        downloaded: usize,
1173        fresh: usize,
1174        failed: usize,
1175        entries: Vec<SkillSyncEntry>,
1176    },
1177    RegistryNeedsApproval(String),
1178    RegistryDenied(String),
1179}
1180
1181/// Successful skill activation data (host performs the side effects).
1182#[derive(Debug, Clone, PartialEq, Eq)]
1183pub struct SkillActivationOutcome {
1184    pub name: String,
1185    pub description: String,
1186}
1187
1188/// Activation failures with the exact data the handler renders.
1189#[derive(Debug, Clone, PartialEq, Eq)]
1190pub enum SkillActivationError {
1191    NotFound {
1192        requested: String,
1193        available: Vec<String>,
1194        warnings: Vec<String>,
1195    },
1196    InvocationRejected {
1197        name: String,
1198        reason: String,
1199    },
1200    PluginRejected {
1201        name: String,
1202        reason: String,
1203    },
1204}
1205
1206/// `/review` outcome data (host performs the side effects).
1207///
1208/// On success the baseline `/review` renders no message — it only emits the
1209/// `SendMessage` action — so `Ready` carries no payload (D1 exact-minimum).
1210/// Warnings are only rendered on the not-found path.
1211#[derive(Debug, Clone, PartialEq, Eq)]
1212pub enum ReviewOutcome {
1213    Ready,
1214    NotFound {
1215        skills_dir: String,
1216        global_dir: String,
1217        warnings: Vec<String>,
1218    },
1219}
1220
1221/// One snapshot entry for `/restore` listings.
1222#[derive(Debug, Clone, PartialEq, Eq)]
1223pub struct SnapshotEntry {
1224    pub id: String,
1225    pub label: String,
1226    pub timestamp: i64,
1227}
1228
1229/// Host approval posture for the `/restore` trust gate (D4: no MODE_POLICY).
1230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1231pub struct CommandApprovalState {
1232    pub yolo: bool,
1233    pub trust_mode: bool,
1234}
1235
1236/// Host skill data for the skills command group (FEAT-022 D1).
1237///
1238/// Exposes the typed, exact-minimum operations the live skills handlers
1239/// consume: discovery (`/skills`), activation (`/skill`), synchronous
1240/// mutation receipts (`/skill install|update|uninstall|trust`), remote
1241/// registry + sync (`/skills --remote|sync|suggest`), review (`/review`),
1242/// and snapshot list/restore plus approval state (`/restore`). The host
1243/// adapter is the only place that touches `App`, `crate::plugins`,
1244/// `SnapshotRepo`, `crate::skills` services, config/network policy, and the
1245/// async runtime bridge. The shared FEAT-015 `CommandSkillsContext` is never
1246/// widened; active-skill reads use that facet, mutations flow through the
1247/// delegates here (D2). All results are contract-owned portable values;
1248/// implementation errors cross as safe text. `/skill` declares this facet
1249/// plus `CommandSkillsContext` for the baseline cache-refresh policy;
1250/// `/skills`, `/review`, and `/restore` declare exactly this facet.
1251pub trait CommandSkillGroupContext {
1252    /// `/skills` discovery projection (workspace, skills dir, scan mode,
1253    /// searched directories, plugin-provided skills, warnings).
1254    fn skill_registry_projection(&self) -> SkillRegistryProjection;
1255    /// `/skill` activation: host lookup, plugin-authority verification, and
1256    /// active-skill/history side effects. `SendMessage` task composition is
1257    /// handler-side.
1258    fn activate_skill(
1259        &mut self,
1260        name: &str,
1261    ) -> Result<SkillActivationOutcome, SkillActivationError>;
1262    /// `/skill install` — synchronous portable receipt; host owns network/async.
1263    fn install_skill(
1264        &mut self,
1265        scope: Option<SkillTargetScope>,
1266        spec: &str,
1267    ) -> Result<SkillMutationReceipt, String>;
1268    /// `/skill update` — synchronous portable receipt; host owns network/async.
1269    fn update_skill(
1270        &mut self,
1271        scope: Option<SkillTargetScope>,
1272        name: &str,
1273    ) -> Result<SkillMutationReceipt, String>;
1274    /// `/skill uninstall` — synchronous portable receipt.
1275    fn uninstall_skill(
1276        &mut self,
1277        scope: Option<SkillTargetScope>,
1278        name: &str,
1279    ) -> Result<SkillMutationReceipt, String>;
1280    /// `/skill trust` — synchronous portable receipt.
1281    fn trust_skill(
1282        &mut self,
1283        scope: Option<SkillTargetScope>,
1284        name: &str,
1285    ) -> Result<SkillMutationReceipt, String>;
1286    /// `/skills --remote` registry fetch (network policy host-side).
1287    fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String>;
1288    /// `/skills suggest <task>` — host fetch + recommendation computation.
1289    fn recommend_skills(&mut self, task: &str) -> Result<Vec<SkillRecommendation>, String>;
1290    /// `/skills sync` — host registry sync (async bridge host-side).
1291    fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String>;
1292    /// `/review` activation: host discovery + side effects (empty-target
1293    /// validation and `SendMessage` composition are handler-side).
1294    fn run_review(&mut self) -> Result<ReviewOutcome, String>;
1295    /// `/restore` snapshot listing.
1296    fn snapshot_list(&mut self, limit: usize) -> Result<Vec<SnapshotEntry>, String>;
1297    /// `/restore <N>`: host restores by snapshot id; handler composes the
1298    /// exact success message from its list entry.
1299    fn restore_snapshot(&mut self, id: &str) -> Result<(), String>;
1300    /// `/restore` trust gate posture (yolo / trust_mode).
1301    fn approval_state(&self) -> CommandApprovalState;
1302}
1303
1304// ---------------------------------------------------------------------------
1305// Session lifecycle capability (FEAT-023).
1306//
1307// One contract-owned facet for the seven host-dependent lifecycle commands;
1308// `/compact` and `/purge` stay pure. The shared `CommandSessionContext` above
1309// stays unchanged: it
1310// serves commands outside this slice and must not gain persistence,
1311// navigation, picker, or lifecycle mutation authority (D2). No concrete App,
1312// SessionManager, session-journal, picker, configuration, or view-stack type
1313// crosses this boundary; successful results are structured portable fields so
1314// the handlers retain exact message composition (D2/D5).
1315// ---------------------------------------------------------------------------
1316
1317/// Portable synchronization fields carried by shared session and debug actions.
1318/// Conversation and prompt types are protocol-owned shapes; concrete runtime
1319/// state and host action conversion remain outside the command contract.
1320#[derive(Clone, Debug, PartialEq)]
1321pub struct SessionSyncPayload {
1322    pub session_id: Option<String>,
1323    pub messages: Vec<Message>,
1324    pub system_prompt: Option<SystemPrompt>,
1325    pub model: String,
1326    pub workspace: PathBuf,
1327    pub mode: CommandMode,
1328}
1329
1330/// `/branch` success projection (`session/branch.rs`). The handler composes
1331/// the exact success line from these deterministic fields.
1332#[derive(Clone, Debug, PartialEq)]
1333pub struct SessionBranchOutcome {
1334    pub leaf_display: String,
1335    pub journal_entries_before: usize,
1336    pub sync: SessionSyncPayload,
1337}
1338
1339/// `/fork` success projection for an active-conversation fork. The handler
1340/// composes `Forked session {parent} -> {fork}` from these required fields.
1341#[derive(Clone, Debug, PartialEq)]
1342pub struct SessionForkReceipt {
1343    pub parent_label: String,
1344    pub fork_label: String,
1345    pub sync: SessionSyncPayload,
1346}
1347
1348/// `/fork <session_id|prefix>` success projection. Explicit-source forks
1349/// always report their spawn depth, so the contract makes that field required
1350/// rather than permitting an invalid missing-depth state.
1351#[derive(Clone, Debug, PartialEq)]
1352pub struct SessionForkFromReceipt {
1353    pub parent_label: String,
1354    pub fork_label: String,
1355    pub spawn_depth: u64,
1356    pub sync: SessionSyncPayload,
1357}
1358
1359/// `/save` success projection. The host performs the full baseline sequence
1360/// (snapshot, serialization, atomic write, metadata application, work-state
1361/// publication); the handler renders `Session saved to {display_path} (ID:
1362/// {truncated_id})`.
1363#[derive(Clone, Debug, PartialEq)]
1364pub struct SessionSaveReceipt {
1365    pub display_path: String,
1366    pub truncated_id: String,
1367}
1368
1369/// `/new` success projection. The handler renders
1370/// `Started new session {truncated_id} (New Session). Previous sessions
1371/// remain available via /resume.`
1372#[derive(Clone, Debug, PartialEq)]
1373pub struct SessionNewReceipt {
1374    pub truncated_id: String,
1375    pub sync: SessionSyncPayload,
1376}
1377
1378/// `/sessions archive|unarchive|restore` success projection. The handler
1379/// renders `Archived session {id} ({title})` or `Restored session ...` from
1380/// the verb it dispatched.
1381#[derive(Clone, Debug, PartialEq)]
1382pub struct SessionArchiveReceipt {
1383    pub truncated_id: String,
1384    pub title: String,
1385}
1386
1387/// `/tree` body projection. The body rendering source (journal tree and
1388/// linear transcript) stays TUI-owned; the handler appends the exact
1389/// guidance lines (D5).
1390#[derive(Clone, Debug, PartialEq)]
1391pub enum TreeBodyProjection {
1392    /// Journal render already includes the trailing newline before guidance.
1393    Journal {
1394        rendered: String,
1395    },
1396    /// Linear pre-journal render (the marker lines).
1397    Linear {
1398        rendered: String,
1399    },
1400    EmptySession,
1401    NoSession,
1402}
1403
1404/// Lifecycle authority for the session command slice (FEAT-023 D2).
1405///
1406/// Operation-granular synchronous delegates over the exact minimum host work
1407/// the nine commands consume. Delegates may return the explicit host-error
1408/// text the baseline surfaces for a failing stage; successful results are
1409/// structured portable fields so handlers retain byte-identical composition.
1410pub trait CommandSessionLifecycleContext {
1411    /// Live transition gate. Handlers return their own blocked-error text
1412    /// before invoking any mutating delegate, matching the baseline ordering
1413    /// (`/branch`, `/fork`, `/load`, `/new`). `/fork picker` and `/tree`
1414    /// never consult it in the baseline, so their paths must not either.
1415    fn transition_blocked(&self) -> bool;
1416
1417    /// Why the transition gate is closed, in operator terms; empty means the
1418    /// transition is allowed. Consulted only after [`Self::transition_blocked`]
1419    /// reports a block, so the refusal can name the work that holds the
1420    /// session instead of restating that it is held.
1421    ///
1422    /// Display projection, not a data source: the strings are pre-rendered
1423    /// for a refusal message and carry no stable shape. A caller that needs
1424    /// ids, durations, or owners should add a structured method instead of
1425    /// parsing these back out.
1426    fn transition_blockers(&self) -> Vec<String>;
1427
1428    /// `/branch` with no argument: the current leaf when an active journaled
1429    /// session resolves, otherwise `None` (the baseline silently falls back
1430    /// to the usage message on this path).
1431    fn branch_current_leaf_hint(&self) -> Option<String>;
1432
1433    /// `/branch <entry_id>`: persist the leaf move and apply the branched
1434    /// transcript. Errors are the exact baseline message for the failing
1435    /// stage (no active session, directory open, load, persist, or branch
1436    /// failure).
1437    fn branch_to(&mut self, entry_id: &str) -> Result<SessionBranchOutcome, String>;
1438
1439    /// `/tree`: produce the journal/linear/empty/no-session projection.
1440    /// Errors are the exact baseline directory-open message.
1441    fn tree_body(&self) -> Result<TreeBodyProjection, String>;
1442
1443    /// `/save [path]`: the full baseline persistence sequence.
1444    fn save_session(&mut self, explicit_path: Option<String>)
1445    -> Result<SessionSaveReceipt, String>;
1446
1447    /// `/fork` (active conversation): the full baseline parent/child save and
1448    /// switch sequence.
1449    fn fork_active(&mut self) -> Result<SessionForkReceipt, String>;
1450
1451    /// `/fork <session_id|prefix>`: explicit-source fork.
1452    fn fork_from(&mut self, session_id_or_prefix: &str) -> Result<SessionForkFromReceipt, String>;
1453
1454    /// `/new [--force]`: fresh-session transition. The caller has already
1455    /// parsed the argument and applied the transition-blocked gate; blocker,
1456    /// busy-work-state, and success handling match the baseline.
1457    fn fresh_session(&mut self, force: bool) -> Result<SessionNewReceipt, String>;
1458
1459    /// `/load <path>`: resolve the path (separator-bearing direct vs
1460    /// workspace-relative) and validate the saved-session shape without
1461    /// applying state or emitting a premature success receipt.
1462    fn load_session(&mut self, path: &str) -> Result<PathBuf, String>;
1463
1464    /// `/sessions` picker open with optional preselection (bare, `show`,
1465    /// `list`, `picker`, and `open <id>` forms). Picker construction and
1466    /// locale selection stay host-side.
1467    fn open_picker(&mut self, preselected: Option<String>);
1468
1469    /// `/sessions archive|unarchive|restore <id>`: durable lifecycle state
1470    /// update that also syncs the live cached metadata atomically.
1471    fn set_archived(
1472        &mut self,
1473        session_id: &str,
1474        archived: bool,
1475    ) -> Result<SessionArchiveReceipt, String>;
1476
1477    /// `/sessions prune <days>`: prune persisted sessions older than `days`
1478    /// days while protecting the active session; returns the number pruned.
1479    fn prune_sessions(&mut self, days: u64) -> Result<usize, String>;
1480}
1481
1482// ---------------------------------------------------------------------------
1483// FEAT-024: session control slice (D2-D7).
1484//
1485// One independently optional session-control authority covering exactly the
1486// host work the seven control commands (`/relay`, `/rename`, `/resume`, `/rc`,
1487// `/remote-env`, `/title`, `/color`) consume. `CommandSessionContext` and
1488// `CommandSessionLifecycleContext` are deliberately not widened: control
1489// authority exists only on this facet, and every delegate is an atomic host
1490// operation or a semantic projection so handlers keep byte-identical
1491// composition. Portable values never expose TUI state beyond what the
1492// baseline branches on.
1493// ---------------------------------------------------------------------------
1494
1495/// `/relay` semantic snapshot (D4). The handler composes the byte-identical
1496/// instruction from these deterministic fields; `crate::prompts`,
1497/// `crate::todo_snapshot`, goal/todo/plan machinery, Work-state objects, and
1498/// locks stay host-side.
1499#[derive(Clone, Debug, PartialEq)]
1500pub struct RelayProjection {
1501    /// Authoritative compact-template text (`COMPACT_TEMPLATE`), echoed with
1502    /// a trailing trim by the handler exactly as today.
1503    pub compact_template: String,
1504    /// Workspace-relative path the relay is written to. The host supplies
1505    /// the same path its startup loader reads first, so the writer and the
1506    /// loader cannot drift.
1507    pub handoff_path: String,
1508    pub workspace: String,
1509    pub mode: String,
1510    pub model: String,
1511    pub goal_objective: Option<String>,
1512    pub goal_token_budget: Option<u32>,
1513    pub todos: TodoProjection,
1514    pub plan: PlanProjection,
1515}
1516
1517/// To-do state distinction for the relay snapshot. The rendered body (if any)
1518/// is produced host-side from the authoritative graph-backed snapshot seam.
1519#[derive(Clone, Debug, PartialEq)]
1520pub enum TodoProjection {
1521    /// Rendered to-do body lines.
1522    Body(String),
1523    /// Work state could not be read (`To-do: unavailable because the list is
1524    /// busy.`).
1525    Unavailable,
1526    /// No Work state or no to-do body.
1527    Absent,
1528}
1529
1530/// Plan-state distinction for the relay snapshot. `Busy` reproduces the
1531/// baseline `try_lock` failure branch; `Absent` reproduces an empty snapshot.
1532///
1533/// `PlanSections` is intentionally not boxed: the command-crate boundary gate
1534/// forbids boxed storage in the contract, and the section payload is only ever
1535/// built once per `/relay` dispatch.
1536#[derive(Clone, Debug, PartialEq)]
1537#[allow(clippy::large_enum_variant)]
1538pub enum PlanProjection {
1539    Sections(PlanSections),
1540    Busy,
1541    Absent,
1542}
1543
1544/// Semantic plan snapshot fields consumed by `/relay`. Values are the raw
1545/// snapshot values; the handler applies the baseline trim/empty filtering and
1546/// label composition so ordering and spacing stay byte-identical.
1547#[derive(Clone, Debug, Default, PartialEq)]
1548pub struct PlanSections {
1549    pub title: Option<String>,
1550    pub objective: Option<String>,
1551    pub context_summary: Option<String>,
1552    pub explanation: Option<String>,
1553    pub sources_used: Vec<String>,
1554    pub critical_files: Vec<String>,
1555    pub constraints: Vec<String>,
1556    pub recommended_approach: Option<String>,
1557    pub verification_plan: Option<String>,
1558    pub risks_and_unknowns: Option<String>,
1559    pub handoff_packet: Option<String>,
1560    pub items: Vec<PlanStep>,
1561}
1562
1563/// Portable plan-step status. The adapter maps the TUI plan status onto this
1564/// semantic enum; the command handler remains the sole owner of the exact
1565/// `pending`/`in_progress`/`completed` labels.
1566#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1567pub enum PlanStepStatus {
1568    Pending,
1569    InProgress,
1570    Completed,
1571}
1572
1573/// One semantic plan checklist item.
1574#[derive(Clone, Debug, PartialEq, Eq)]
1575pub struct PlanStep {
1576    pub status: PlanStepStatus,
1577    pub text: String,
1578}
1579
1580/// `/resume` route resolution (D6). The host resolves argument shape and
1581/// performs container imports atomically; the handler selects the exact
1582/// baseline message/action per variant.
1583#[derive(Clone, Debug, PartialEq)]
1584pub enum ResumeSource {
1585    /// Argument resolves to a readable file (`raw` direct path or
1586    /// workspace-relative path); the handler calls `import_session_file`.
1587    File(PathBuf),
1588    /// Argument resolved through the session manager (id or prefix).
1589    Session {
1590        /// Durable session file when present; `None` reproduces the baseline
1591        /// non-file fallback message arm.
1592        load_path: Option<PathBuf>,
1593        truncated_id: String,
1594        title: String,
1595    },
1596    /// Argument parsed as a foreign session container, which was imported
1597    /// atomically by the resolver.
1598    Imported(ResumeImportReceipt),
1599    /// Argument matched neither a file, a session, nor a container.
1600    NotFound { raw: String, error: String },
1601}
1602
1603/// Portable `/resume` import receipt. The handler renders
1604/// `Imported foreign session as {truncated_id} ({entry_count} entries, leaf
1605/// {leaf_display})`, and carries `sync` so the engine adopts the imported
1606/// conversation instead of staying on the previous one.
1607#[derive(Clone, Debug, PartialEq)]
1608pub struct ResumeImportReceipt {
1609    pub truncated_id: String,
1610    pub entry_count: usize,
1611    pub leaf_display: String,
1612    pub sync: SessionSyncPayload,
1613}
1614
1615/// `/rename` success receipt; the title is the sanitized persisted value so
1616/// the handler echoes exactly what was written.
1617#[derive(Clone, Debug, PartialEq)]
1618pub struct SessionTitleReceipt {
1619    pub title: String,
1620}
1621
1622/// Bare `/title` status projection (`Window title: [{effective}]{source}`).
1623#[derive(Clone, Debug, PartialEq)]
1624pub struct TitleReport {
1625    /// Effective window-title prefix, or `unset`.
1626    pub effective: String,
1627    pub source: TitleSource,
1628}
1629
1630#[derive(Clone, Debug, PartialEq)]
1631pub enum TitleSource {
1632    /// Session-level window title set.
1633    Session,
1634    /// Config-default title applies.
1635    ConfigDefault,
1636    /// Neither a session title nor a config default.
1637    None,
1638}
1639
1640/// `/rc link` structured link data.
1641#[derive(Clone, Debug, PartialEq)]
1642pub struct RemoteLink {
1643    pub url: String,
1644    pub computer_url: Option<String>,
1645}
1646
1647/// `/rc open` outcome. Browser launch stays synchronous and single-attempt;
1648/// no deferred external-URL action is produced (D6).
1649#[derive(Clone, Debug, PartialEq)]
1650pub enum RemoteOpenOutcome {
1651    NoLink,
1652    Opened { url: String },
1653    LaunchFailed { url: String },
1654}
1655
1656/// `/rc start` wording input: the active-turn copy is used while a turn is
1657/// loading or a dispatch is in flight.
1658#[derive(Clone, Debug, PartialEq)]
1659pub struct RemoteStartInfo {
1660    pub connecting: bool,
1661}
1662
1663/// `/remote-env open` hosted-work target. The URL is fully encoded host-side
1664/// (the portable handler must not depend on `urlencoding`); repo/branch echo
1665/// the raw values used by the baseline message replacements.
1666#[derive(Clone, Debug, PartialEq)]
1667pub struct HostedWorkTarget {
1668    pub url: String,
1669    pub repo: String,
1670    pub branch: String,
1671}
1672
1673/// Control authority for the session command slice (FEAT-024 D2/D5).
1674///
1675/// Operation-granular synchronous delegates over the exact minimum host work
1676/// the seven control commands consume. Delegates reproduce the baseline
1677/// check/mutation order (transition gate before resume I/O, save before
1678/// publication, single-attempt browser launch) and return portable receipts/
1679/// projections or the exact host-error text the baseline surfaces. No
1680/// `SessionManager`, saved-session/container type, `SessionPickerView`,
1681/// remote-control service, Git wrapper, configuration, model/history type,
1682/// lock, or host callback crosses the facet.
1683pub trait CommandSessionControlContext {
1684    /// Live transition gate consulted by `/resume` before any picker or I/O.
1685    fn transition_blocked(&self) -> bool;
1686
1687    /// Why the transition gate is closed, in operator terms; empty means the
1688    /// transition is allowed. Consulted only after [`Self::transition_blocked`]
1689    /// reports a block.
1690    ///
1691    /// Display projection, not a data source: the strings are pre-rendered
1692    /// for a refusal message and carry no stable shape. A caller that needs
1693    /// ids, durations, or owners should add a structured method instead of
1694    /// parsing these back out.
1695    fn transition_blockers(&self) -> Vec<String>;
1696
1697    /// `/relay`: authoritative semantic snapshot (workspace/mode/model/goal/
1698    /// to-do/plan/compact-template). Unavailable sources are represented as
1699    /// explicit states, never panics.
1700    fn relay_projection(&self) -> RelayProjection;
1701
1702    /// Bare `/resume`: push the existing picker without preselection.
1703    fn open_resume_picker(&mut self);
1704
1705    /// `/resume <raw>`: resolve direct-path, workspace-relative, session
1706    /// id/prefix, and inline-container routes in the established order; a
1707    /// recognized inline container is imported atomically here.
1708    fn resolve_resume_source(&mut self, raw: &str) -> Result<ResumeSource, String>;
1709
1710    /// `/resume <file>`: read, parse, persist, and apply a foreign session
1711    /// file (container or plain saved session). Errors are the exact baseline
1712    /// read/parse/import text.
1713    fn import_session_file(&mut self, path: PathBuf) -> Result<ResumeImportReceipt, String>;
1714
1715    /// Apply the authoritative session-title character policy before the
1716    /// portable `/rename` and `/title` handlers validate and compose output.
1717    fn sanitize_session_title(&self, raw_title: &str) -> String;
1718
1719    /// `/rename <title>`: recover first-snapshot state, sync live state,
1720    /// persist, and publish with baseline order. The handler already applied
1721    /// sanitization plus blank and 100-character validation.
1722    fn rename_session(&mut self, title: &str) -> Result<SessionTitleReceipt, String>;
1723
1724    /// Bare `/title`: effective prefix and its source.
1725    fn title_report(&self) -> TitleReport;
1726
1727    /// `/title <title>`: persist an already sanitized and validated window
1728    /// title with baseline save/publication/redraw semantics.
1729    fn set_window_title(&mut self, title: String) -> Result<(), String>;
1730
1731    /// `/title off|clear|none`: clear the session window title with the same
1732    /// baseline persistence/redraw semantics.
1733    fn clear_window_title(&mut self) -> Result<(), String>;
1734
1735    fn composer_color(&self) -> Option<String>;
1736
1737    fn set_composer_color(&mut self, color: Option<String>) -> Result<(), String>;
1738
1739    /// `/rc status`: current remote-control status line.
1740    fn remote_status(&self) -> String;
1741
1742    /// `/rc link`: live session link plus optional computer-management URL.
1743    fn remote_link(&self) -> Option<RemoteLink>;
1744
1745    /// `/rc open`: synchronous single browser attempt over the authoritative
1746    /// URL-opening helper; outcome carries the URL for exact message text.
1747    fn remote_browser_open(&self) -> RemoteOpenOutcome;
1748
1749    /// `/rc start`: whether the active-turn copy applies.
1750    fn remote_start_info(&self) -> RemoteStartInfo;
1751
1752    /// `/rc stop`: refusal reason while a remote turn/envelope is active.
1753    fn remote_stop_refusal(&self) -> Option<String>;
1754
1755    /// `/remote-env open`: validate the hosted-work Git target host-side and
1756    /// return the encoded URL plus raw repo/branch echoes; `None` reproduces
1757    /// the unavailable-target error. Credentials never appear in values or
1758    /// errors.
1759    fn resolve_hosted_work_target(&self) -> Option<HostedWorkTarget>;
1760}
1761
1762// ---------------------------------------------------------------------------
1763// FEAT-025: session export slice (D1-D9).
1764//
1765// One independently optional session-export authority covering exactly the
1766// host work `/export` (and its `/daochu` alias) consumes. The shared
1767// `CommandSessionContext`, `CommandSessionLifecycleContext`, and
1768// `CommandSessionControlContext` facets are deliberately not widened: export
1769// authority exists only on this facet, and every delegate is an atomic host
1770// operation or a semantic projection so the portable handler keeps
1771// byte-identical composition. Hidden payloads are excluded while projections
1772// are built (D9), so internal reasoning, reasoning signatures, and inline or
1773// local image bytes never enter these DTOs. No `App`, clipboard handler,
1774// snapshot repository, history cell, session manager, configuration, client,
1775// filesystem handle, or host callback crosses this boundary (D1/D3/D5/D7).
1776// ---------------------------------------------------------------------------
1777
1778/// Portable conversation metadata for the export header (D3).
1779///
1780/// Values that already have an authoritative host derivation keep it
1781/// (session-label truncation, provider identity, model label, mode display,
1782/// workspace basename, message count, clock); portable rendering adds only
1783/// export formatting and sanitization (D10).
1784#[derive(Clone, Debug, PartialEq, Eq)]
1785pub struct ExportMetadata {
1786    /// Host-truncated session id, or the baseline `unsaved` fallback.
1787    pub session_label: String,
1788    pub provider: String,
1789    pub model: String,
1790    pub mode: String,
1791    /// Workspace directory basename, or the baseline `workspace` fallback.
1792    pub workspace_name: String,
1793    /// `api_messages.len()` when authoritative, otherwise `history.len()`.
1794    pub message_count: usize,
1795    pub exported_at_unix: i64,
1796}
1797
1798/// One tool-call caller projection (D3). Only the fields the baseline export
1799/// renders cross the boundary.
1800#[derive(Clone, Debug, PartialEq, Eq)]
1801pub struct ToolCallerProjection {
1802    pub caller_type: String,
1803    pub tool_id: Option<String>,
1804}
1805
1806/// One projected content block (D3/D9).
1807///
1808/// Visible text and structured content cross as portable data; internal
1809/// reasoning bodies, reasoning signatures, and inline or local image payloads
1810/// are replaced by typed omission markers at projection time and never cross.
1811#[derive(Clone, Debug, PartialEq)]
1812pub enum ExportBlock {
1813    /// Visible text block; portable rendering sanitizes it.
1814    Text {
1815        text: String,
1816    },
1817    /// External image reference (`http`/`https` only); portable rendering
1818    /// redacts credential-bearing URLs.
1819    ImageReference {
1820        url: String,
1821    },
1822    /// Inline or local image payload excluded at projection time (D9).
1823    ImageOmitted,
1824    /// Internal reasoning body and reasoning signature excluded (D9).
1825    InternalReasoning,
1826    ToolCall {
1827        id: String,
1828        name: String,
1829        caller: Option<ToolCallerProjection>,
1830        input: Value,
1831    },
1832    ToolResult {
1833        tool_use_id: String,
1834        content: String,
1835        is_error: bool,
1836        /// `Some` when the host message carried structured result blocks; the
1837        /// host has already applied the safe-result filter (D9).
1838        structured: Option<Value>,
1839    },
1840    ServerToolCall {
1841        id: String,
1842        name: String,
1843        input: Value,
1844    },
1845    ToolSearchResult {
1846        tool_use_id: String,
1847        content: Value,
1848    },
1849    CodeExecutionResult {
1850        tool_use_id: String,
1851        content: Value,
1852    },
1853}
1854
1855/// One projected authoritative message (D3).
1856///
1857/// `prompt_snippet` is the host-computed `snapshot_label_prompt_snippet` of
1858/// the first visible text block. The parser and snippet algorithm stay
1859/// TUI-owned (D8), so correlation compares authoritative values instead of
1860/// re-deriving them portably.
1861///
1862/// `is_user_role` carries the host's exact `Role::User` comparison. `role` is
1863/// the rendered wire string, and comparing it textually would also match a
1864/// `Role::Unrecognized("user")`, which the baseline never treated as a user
1865/// turn. The flag keeps restore-point correlation faithful to the baseline.
1866#[derive(Clone, Debug, PartialEq)]
1867pub struct ExportMessage {
1868    pub role: String,
1869    /// Exact `message.role == Role::User`, not a string comparison.
1870    pub is_user_role: bool,
1871    pub blocks: Vec<ExportBlock>,
1872    pub prompt_snippet: Option<String>,
1873}
1874
1875/// One projected visible-history fallback entry (D3).
1876#[derive(Clone, Debug, PartialEq, Eq)]
1877pub enum HistoryEntry {
1878    /// Visible host content that portable rendering must still sanitize.
1879    Sanitized { role: String, body: String },
1880    /// An already-final baseline marker line that must not be sanitized again.
1881    Literal { role: String, body: String },
1882}
1883
1884/// Transcript source precedence (D3): authoritative API messages when
1885/// present, otherwise the sanitized visible-history fallback.
1886#[derive(Clone, Debug, PartialEq)]
1887pub enum TranscriptProjection {
1888    Authoritative(Vec<ExportMessage>),
1889    HistoryFallback(Vec<HistoryEntry>),
1890}
1891
1892/// One snapshot projected to semantic fields (D8).
1893///
1894/// `kind`, `sequence`, and `prompt_snippet` are the host-parsed label fields;
1895/// the raw `label` is kept only for the human-readable table column. No
1896/// preformatted correlation line crosses the boundary.
1897#[derive(Clone, Debug, PartialEq, Eq)]
1898pub struct RestoreSnapshot {
1899    pub id: String,
1900    pub label: String,
1901    pub timestamp_unix: i64,
1902    pub kind: String,
1903    pub sequence: Option<u64>,
1904    pub prompt_snippet: Option<String>,
1905}
1906
1907/// Restore-point projection with distinct baseline states (D3/D8).
1908///
1909/// `None` means no snapshot repository exists, `Unreadable` preserves the host
1910/// failure reason, and `Recorded` distinguishes an existing-but-empty
1911/// repository from one with snapshots by the vector length.
1912#[derive(Clone, Debug, PartialEq, Eq)]
1913pub enum RestorePointProjection {
1914    None,
1915    Unreadable { reason: String },
1916    Recorded { snapshots: Vec<RestoreSnapshot> },
1917}
1918
1919/// Full conversation projection (D3/D8/D9).
1920#[derive(Clone, Debug, PartialEq)]
1921pub struct ConversationExportProjection {
1922    pub metadata: ExportMetadata,
1923    pub transcript: TranscriptProjection,
1924    pub restore_points: RestorePointProjection,
1925}
1926
1927/// Turn-handoff projection (D2).
1928///
1929/// `markdown` is the unmodified shared TUI renderer output and
1930/// `workspace_path` is the value the portable handler replaces with `.` after
1931/// sanitizing; the renderer itself is neither moved nor duplicated.
1932#[derive(Clone, Debug, PartialEq, Eq)]
1933pub struct TurnHandoffProjection {
1934    pub markdown: String,
1935    pub workspace_path: String,
1936}
1937
1938/// Session-export authority for the `/export` slice (FEAT-025 D1-D9).
1939///
1940/// Operation-granular synchronous delegates over the exact minimum host work
1941/// the command consumes. The portable handler parses the request first, renders
1942/// the selected scope second, and then uses these delegates in baseline order:
1943/// clipboard exports call terminal-paste detection, recovery write, and
1944/// clipboard delivery exactly once each with the same Markdown; file exports
1945/// resolve the destination before writing it. A recovery-write `None` never
1946/// prevents the clipboard attempt, and a turn-only export never requests the
1947/// conversation projection (D6/D7).
1948pub trait CommandSessionExportContext {
1949    /// Conversation export projection: metadata, authoritative-or-fallback
1950    /// transcript, and restore-point state. Read-only; opens only an existing
1951    /// snapshot repository and never creates one (D8).
1952    fn conversation_projection(&self) -> ConversationExportProjection;
1953
1954    /// Turn-handoff projection: unmodified shared renderer Markdown plus the
1955    /// workspace path value (D2).
1956    fn turn_handoff_projection(&self) -> TurnHandoffProjection;
1957
1958    /// Whether clipboard delivery goes through the terminal-client (SSH/OSC 52
1959    /// via tmux) path (D6).
1960    fn clipboard_requires_terminal_paste(&self) -> bool;
1961
1962    /// Write the shared `last-copy.md` recovery file. `None` reproduces the
1963    /// baseline silent failure; recovery writing never falls through to an
1964    /// error (D5/D6).
1965    fn write_recovery_copy(&self, markdown: &str) -> Option<PathBuf>;
1966
1967    /// Attempt clipboard delivery. `Err` carries the raw host clipboard error
1968    /// text; the handler composes the exact failure wording (D6).
1969    fn write_clipboard(&self, markdown: &str) -> Result<(), String>;
1970
1971    /// Resolve a file destination exactly as the baseline does (trim, empty
1972    /// check, `..` rejection, workspace canonicalization and rebasing, filename
1973    /// requirement). Errors are returned unwrapped (D7).
1974    fn resolve_export_path(&self, raw: &str) -> Result<PathBuf, String>;
1975
1976    /// Write the rendered export to a resolved destination with the baseline
1977    /// protection checks. Errors are returned unwrapped; the handler wraps them
1978    /// in `Failed to export {label} to {path}: {err}` (D7).
1979    fn write_export_file(&self, path: &Path, contents: &[u8], force: bool) -> Result<(), String>;
1980}