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