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