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
8use std::path::{Path, PathBuf};
9
10use codewhale_core::request::{Message, SystemPrompt};
11
12use crate::types::{
13 CommandApprovalMode, CommandCurrency, CommandMode, CommandProviderId, CommandReasoningEffort,
14};
15
16/// Session identity, messages, queue operations, and token totals.
17pub trait CommandSessionContext {
18 fn session_id(&self) -> Option<String>;
19 fn api_messages(&self) -> Vec<Message>;
20 fn add_message(&mut self, message: Message);
21 fn queued_message_count(&self) -> usize;
22 fn remove_queued_message(&mut self, index: usize) -> Result<(), String>;
23 fn total_tokens(&self) -> u64;
24}
25
26/// Model selection, provider identity, effort, and fallback chain.
27pub trait CommandModelContext {
28 fn current_model(&self) -> String;
29 fn auto_model(&self) -> bool;
30 fn set_model_selection(&mut self, model: String, provider: Option<CommandProviderId>);
31 fn reasoning_effort(&self) -> CommandReasoningEffort;
32 fn provider_identity(&self) -> Option<CommandProviderId>;
33 fn fallback_chain(&self) -> Vec<CommandProviderId>;
34}
35
36/// Cost display and accounting operations.
37pub trait CommandCostContext {
38 fn display_currency(&self) -> CommandCurrency;
39 fn session_cost_for_currency(&self, currency: CommandCurrency) -> f64;
40 fn subagent_cost_for_currency(&self, currency: CommandCurrency) -> f64;
41 fn accrue_cost_estimate(&mut self, amount: f64, currency: CommandCurrency);
42 fn record_turn_cost(
43 &mut self,
44 amount: f64,
45 currency: CommandCurrency,
46 route_receipt: Option<String>,
47 );
48}
49
50/// Operating mode, approval posture, shell access, and policy lock.
51pub trait CommandModePolicyContext {
52 fn mode(&self) -> CommandMode;
53 fn set_mode(&mut self, mode: CommandMode);
54 fn approval_mode(&self) -> CommandApprovalMode;
55 fn allow_shell(&self) -> bool;
56 fn set_shell_access(&mut self, allow: bool);
57 fn policy_locked(&self) -> bool;
58}
59
60/// Read access to the effective system prompt.
61pub trait CommandSystemPromptContext {
62 fn system_prompt(&self) -> Option<SystemPrompt>;
63}
64
65/// Active skill identity and skill-cache refresh.
66pub trait CommandSkillsContext {
67 fn active_skill(&self) -> Option<String>;
68 fn active_skill_provenance(&self) -> Option<String>;
69 fn refresh_skill_cache(&mut self);
70}
71
72/// Workspace path and a bounded serialized work-state snapshot.
73pub trait CommandWorkspaceContext {
74 fn workspace(&self) -> PathBuf;
75 fn work_state_snapshot(&self) -> Result<Option<String>, String>;
76 /// Session-aware canonical operation digest. Returns the final user-facing
77 /// digest text or a safe explicit error; never a serialized snapshot.
78 /// No-active-work and temporary-unavailability semantics are preserved by
79 /// the host implementation (FEAT-018 D5).
80 fn operation_digest(&mut self) -> Result<String, String>;
81}
82
83/// Stable-key translation with named replacements (FEAT-018 D3).
84///
85/// Message identity uses stable snake_case keys plus named replacements. The
86/// TUI host maps those keys to the current catalog and preserves the existing
87/// English fallback for intentionally incomplete locale packs. Unknown keys or
88/// invalid replacement contracts fail safely and produce a command error; they
89/// never panic and never display a raw lookup key.
90pub trait CommandPresentationContext {
91 /// Resolve a stable message key with its named replacements.
92 fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String>;
93}
94
95/// Portable receipt for a successful atomic media attachment (FEAT-018 D4).
96/// Carries only the information needed for the existing confirmation text.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct MediaAttachmentReceipt {
99 pub kind: String,
100 pub path: std::path::PathBuf,
101}
102
103/// Atomic composer/media capability (FEAT-018 D4).
104///
105/// The host performs media validation and composer insertion as one atomic
106/// operation. Rejected, missing, unsupported, corrupt, or oversized media
107/// leaves composer state unchanged and returns a safe error. Only portable
108/// success information crosses the boundary; composer markup, mutable input
109/// text, decoder internals, and TUI types never do.
110pub trait CommandMediaContext {
111 /// Validate and insert a resolved media path atomically.
112 fn attach_media(&mut self, resolved_path: &Path) -> Result<MediaAttachmentReceipt, String>;
113}
114
115// ---------------------------------------------------------------------------
116// Project (FEAT-021 D1/D2/D3/D4)
117// ---------------------------------------------------------------------------
118
119/// Portable goal status for the project facet (FEAT-021 D1).
120///
121/// Mirrors the four TUI-owned `tools::goal::GoalStatus` variants without
122/// naming the TUI type. The adapter maps host state onto this enum; handlers
123/// compare and render it directly.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
125pub enum ProjectGoalStatus {
126 #[default]
127 Active,
128 Paused,
129 Complete,
130 Blocked,
131}
132
133/// Portable session-share projection (FEAT-021 D1).
134///
135/// Carries only the emptiness/length and the model/mode labels the live
136/// `/share` handler consumes. The session history itself, exporter I/O, and
137/// all `App` state stay host-side.
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct ProjectShareProjection {
140 /// Whether the session history is empty (drives the empty-share error).
141 pub history_is_empty: bool,
142 /// Session history length used in the export message and action.
143 pub history_len: usize,
144 /// Current model label.
145 pub model: String,
146 /// Current operating-mode label.
147 pub mode_label: String,
148}
149
150/// Portable goal projection (FEAT-021 D1).
151///
152/// Carries the visible goal state, the effective pending-control view, and the
153/// session-derived token fallback the live `/goal` handler consumes. Concrete
154/// goal-service, session-manager, and `App` types never cross the boundary.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct ProjectGoalState {
157 /// Visible goal objective.
158 pub objective: Option<String>,
159 /// Visible goal status.
160 pub status: ProjectGoalStatus,
161 /// Pause reason label when the goal is paused (already rendered).
162 pub pause_reason: Option<String>,
163 /// Elapsed seconds from `started_at` when present (host-computed).
164 pub started_at_elapsed_seconds: Option<u64>,
165 /// Seconds of goal time used (stable budget/elapsed source).
166 pub time_used_seconds: u64,
167 /// Optional token budget.
168 pub token_budget: Option<u32>,
169 /// Tokens used by the goal engine.
170 pub tokens_used: u64,
171 /// Session conversation-token total (fallback when tokens_used == 0).
172 pub session_total_tokens: u32,
173 /// Goal continuation count.
174 pub continuation_count: u32,
175 /// Whether pending goal controls are queued (effective-state gate).
176 pub pending_controls: bool,
177 /// Last-known durable objective (session-derived effective source).
178 pub last_known_objective: Option<String>,
179 /// Last-known durable status (session-derived effective source).
180 pub last_known_status: Option<ProjectGoalStatus>,
181 /// Whether the conversation has API messages (bare `/goal` context gate).
182 pub conversation_present: bool,
183 /// Whether the host is currently loading (idle-hint gate).
184 pub is_loading: bool,
185 /// Whether the goal continuation loop is waiting (idle-hint gate).
186 pub goal_continuation_waiting: bool,
187}
188
189/// Host project data for the project command group (FEAT-021 D1).
190///
191/// Exposes the typed, exact-minimum operations the live project handlers
192/// consume: `/lsp` status/set state, `/share` session payload data, and
193/// `/goal` goal state including the session-derived effective values.
194/// `/init` host data flows through the existing `WORKSPACE` facet (D2), so
195/// `/init` destructures exactly `WORKSPACE` (D4) and consumes no
196/// project-facet method. All results are contract-owned portable values; implementation
197/// errors cross as safe text. The TUI adapter is the only place that touches
198/// `App`, `config::config`, the goal service, or the session manager.
199pub trait CommandProjectContext {
200 /// `/lsp` status: whether LSP diagnostics are enabled.
201 fn lsp_enabled(&self) -> bool;
202 /// `/lsp` set: enable or disable LSP diagnostics.
203 fn lsp_set(&mut self, enabled: bool) -> Result<(), String>;
204 /// `/share` projection: session emptiness, length, model, and mode label.
205 fn share_projection(&self) -> ProjectShareProjection;
206 /// `/goal` projection: visible and effective goal state.
207 fn goal_state(&self) -> ProjectGoalState;
208}
209
210// ---------------------------------------------------------------------------
211// Memory (FEAT-019 D1/D2/D8/D9)
212// ---------------------------------------------------------------------------
213
214/// Portable semantic hit for a native-memory search or get result.
215///
216/// Carries only the typed location and text the handler consumes for
217/// formatting; the TUI-owned `NativeMemoryHit` never crosses the boundary.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct MemoryHit {
220 pub source: PathBuf,
221 pub line_start: usize,
222 pub line_end: usize,
223 pub text: String,
224}
225
226/// Portable native-memory location summary (status operation).
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct MemoryStatus {
229 pub root: PathBuf,
230 pub source: PathBuf,
231 pub index: PathBuf,
232}
233
234/// Portable result of a successful remember operation.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct MemoryRemembered {
237 pub source: PathBuf,
238 pub line_start: usize,
239}
240
241/// Portable import outcome: imported (with destination) or skipped.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub enum MemoryImportOutcome {
244 Imported { destination: PathBuf },
245 Skipped,
246}
247
248/// Portable get outcome: found hit or explicit not-found.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub enum MemoryGetOutcome {
251 Found(MemoryHit),
252 NotFound,
253}
254
255/// Portable export payload — the exported memory document itself, never a
256/// preformatted command response.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct MemoryExport {
259 pub content: String,
260}
261
262/// Portable reindex entry count.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct MemoryReindex {
265 pub entry_count: usize,
266}
267
268/// Zero-field success value for delete operations (D2): the handler already
269/// owns the selected scope and needs no additional success data.
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
271pub struct MemoryDelete;
272
273/// Typed remember target (D9): the handler resolves workspace identity through
274/// the workspace facet and passes the resulting typed ID here.
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub enum MemoryRememberTarget {
277 Global,
278 Workspace { workspace_id: String },
279}
280
281/// Typed delete scope for the non-workspace delete method (D8/D9).
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum MemoryDeleteScope {
284 /// Delete every memory entry (global and all workspace scopes).
285 All,
286 /// Delete only the global scope entries.
287 Global,
288}
289
290/// Host memory data for the memory command group (FEAT-019 D1).
291///
292/// Exposes the resolved user-memory file path, the enablement flag, and one
293/// typed method per exposed native-memory operation. All results are
294/// contract-owned portable values; implementation errors cross as safe text.
295/// Workspace-scoped operations take the borrowed workspace path as their first
296/// argument (D8); non-workspace operations never receive workspace authority
297/// and the facet never captures or retains workspace state internally.
298pub trait CommandMemoryContext {
299 /// The resolved user-memory file path.
300 fn memory_path(&self) -> PathBuf;
301 /// Whether the `[memory] enabled` / `DEEPSEEK_MEMORY=on` flag is set.
302 fn memory_enabled(&self) -> bool;
303 /// Native-memory root, global source, and index paths.
304 fn status(&self) -> Result<MemoryStatus, String>;
305 /// The native-memory root path.
306 fn path(&self) -> Result<PathBuf, String>;
307 /// Workspace identity for the given workspace path.
308 fn workspace_id(&self, workspace: &Path) -> Result<String, String>;
309 /// Workspace-scoped search over the native-memory store.
310 fn search(&self, workspace: &Path, query: &str, limit: usize)
311 -> Result<Vec<MemoryHit>, String>;
312 /// Append a reviewed note to the typed global or workspace target.
313 fn remember(
314 &self,
315 target: MemoryRememberTarget,
316 note: &str,
317 ) -> Result<MemoryRemembered, String>;
318 /// Import legacy memory; distinguishes imported from skipped.
319 fn import(&self) -> Result<MemoryImportOutcome, String>;
320 /// Workspace-scoped get by entry id; not-found is a typed outcome.
321 fn get(&self, workspace: &Path, id: i64) -> Result<MemoryGetOutcome, String>;
322 /// Export the native-memory document content.
323 fn export(&self) -> Result<MemoryExport, String>;
324 /// Reindex the native-memory store; returns the indexed entry count.
325 fn reindex(&self) -> Result<MemoryReindex, String>;
326 /// Delete all or global scope; never receives workspace authority.
327 fn delete(&self, scope: MemoryDeleteScope) -> Result<MemoryDelete, String>;
328 /// Delete the given workspace scope; workspace path is the first argument.
329 fn delete_workspace(&self, workspace: &Path) -> Result<MemoryDelete, String>;
330}
331
332// ---------------------------------------------------------------------------
333// Plugin (FEAT-020 D1/D2/D10/D11)
334// ---------------------------------------------------------------------------
335
336/// Portable plugin diagnostic level (FEAT-020 D2).
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338pub enum PluginDiagnosticLevel {
339 Warning,
340 Error,
341}
342
343/// Portable plugin diagnostic entry.
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct PluginDiagnostic {
346 pub level: PluginDiagnosticLevel,
347 pub code: String,
348 pub message: String,
349 pub path: Option<PathBuf>,
350}
351
352/// Portable MCP transport classification for the capability review body.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub enum PluginMcpTransport {
355 Stdio,
356 Http,
357 Invalid,
358}
359
360/// Portable MCP server detail for the capability review body (FEAT-020 D2).
361///
362/// Carries only the semantic fields `render_mcp_inventory` consumes:
363/// transport, command/url, argv, cwd, env provenance, timeouts, required,
364/// enabled/disabled tool lists, and the enabled flag. Host `McpServerConfig`
365/// never crosses the boundary.
366#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct PluginMcpServerDetail {
368 pub name: String,
369 pub transport: PluginMcpTransport,
370 pub command: Option<String>,
371 pub argv: Vec<String>,
372 pub cwd: Option<PathBuf>,
373 pub env: Vec<(String, String)>,
374 pub url: Option<String>,
375 pub env_headers: Vec<(String, String)>,
376 pub bearer_token_env_var: Option<String>,
377 pub connect_timeout_secs: Option<u64>,
378 pub execute_timeout_secs: Option<u64>,
379 pub read_timeout_secs: Option<u64>,
380 pub required: bool,
381 pub enabled_tools: Vec<String>,
382 pub disabled_tools: Vec<String>,
383 pub enabled: bool,
384}
385
386/// Portable summary of one loaded plugin bundle (list output, FEAT-020 D2).
387#[derive(Debug, Clone, PartialEq, Eq)]
388pub struct PluginSummary {
389 pub name: String,
390 pub id: String,
391 pub state_label: String,
392 pub scope: String,
393 pub trust_status: String,
394 pub compatibility: String,
395 pub inventory: String,
396 pub active: bool,
397 pub trusted: bool,
398 pub enabled: bool,
399}
400
401/// Portable full bundle detail for show/review/validate rendering (FEAT-020 D2).
402///
403/// Carries every semantic value the render helpers consume. The complete
404/// `LoadedPlugin` never crosses the boundary; only branch-consumed fields are
405/// projected here (D10).
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct PluginDetail {
408 /// Inventory summary string (host-computed, e.g. `skills=1 mcp=0`).
409 pub inventory_summary: String,
410 pub name: String,
411 pub id: String,
412 pub version: String,
413 pub origin: String,
414 pub scope: String,
415 pub state_label: String,
416 pub trust_status: String,
417 pub compatibility: String,
418 pub content_hash: String,
419 pub capability_hash: String,
420 pub canonical_root: PathBuf,
421 pub active: bool,
422 pub trusted: bool,
423 pub enabled: bool,
424 pub unsupported_labels: Vec<String>,
425 pub supported_labels: Vec<String>,
426 pub skills: Vec<String>,
427 pub filesystem_roots: Vec<String>,
428 pub network_hosts: Vec<String>,
429 pub stdio_mcp_servers: usize,
430 pub lifecycle_mutation: bool,
431 pub mcp_servers: Vec<PluginMcpServerDetail>,
432 pub diagnostics: Vec<PluginDiagnostic>,
433}
434
435/// Portable outcome of a plugin mutation (FEAT-020 D2/D11).
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub enum PluginMutationOutcome {
438 Installed,
439 Updated,
440 NoChange,
441 Uninstalled,
442 NeedsApproval(String),
443 NetworkDenied(String),
444}
445
446/// Portable mutation receipt returned synchronously by the facet (FEAT-020 D11).
447#[derive(Debug, Clone, PartialEq, Eq)]
448pub struct PluginMutationReceipt {
449 pub name: String,
450 pub path: Option<PathBuf>,
451 pub content_hash: Option<String>,
452 pub installed_content_hash: Option<String>,
453 pub outcome: PluginMutationOutcome,
454}
455
456/// Portable bundle export receipt (FEAT-020 D2).
457#[derive(Debug, Clone, PartialEq, Eq)]
458pub struct PluginExportReceipt {
459 pub exported_name: String,
460 pub target: PathBuf,
461 pub display_name: Option<String>,
462 pub wrote_mcp_json: bool,
463 pub files_copied: u64,
464 pub skills_normalized: bool,
465}
466
467/// Portable legacy executable-tool detail (FEAT-020 D2).
468#[derive(Debug, Clone, PartialEq, Eq)]
469pub struct PluginLegacyTool {
470 pub name: String,
471 pub description: String,
472 pub approval: String,
473 pub input_schema: Option<String>,
474 pub path: PathBuf,
475}
476
477/// Portable legacy-tool scan result: directory and discovered tools.
478#[derive(Debug, Clone, PartialEq, Eq)]
479pub struct PluginLegacyScan {
480 pub dir: PathBuf,
481 pub tools: Vec<PluginLegacyTool>,
482}
483
484/// Portable Kimi managed-plugin candidate (FEAT-020 D2).
485#[derive(Debug, Clone, PartialEq, Eq)]
486pub struct PluginManagedCandidate {
487 pub name: String,
488 pub version: String,
489 pub license: Option<String>,
490 pub canonical_path: PathBuf,
491 pub content_hash: String,
492 pub capability_hash: String,
493 pub inventory: String,
494 pub applicable: bool,
495}
496
497/// Portable Kimi managed-scan result (FEAT-020 D2).
498#[derive(Debug, Clone, PartialEq, Eq)]
499pub struct PluginManagedScan {
500 pub root: PathBuf,
501 pub candidates: Vec<PluginManagedCandidate>,
502 pub rejected: Vec<String>,
503}
504
505/// Portable marketplace candidate install plan (FEAT-020 D2).
506#[derive(Debug, Clone, PartialEq, Eq)]
507pub enum PluginMarketplaceInstallPlan {
508 Supported { spec: String, source_kind: String },
509 Unsupported { reason: String },
510}
511
512/// Portable marketplace candidate (FEAT-020 D2).
513#[derive(Debug, Clone, PartialEq, Eq)]
514pub struct PluginMarketplaceCandidate {
515 pub name: String,
516 pub display_name: Option<String>,
517 pub version: Option<String>,
518 pub tier: String,
519 pub compatibility: Option<String>,
520 pub install_plan: PluginMarketplaceInstallPlan,
521 pub description: Option<String>,
522 pub homepage: Option<String>,
523 pub repository: Option<String>,
524 pub author: Option<String>,
525 pub license: Option<String>,
526 pub keywords: Vec<String>,
527 pub when: Option<String>,
528 pub diagnostics: Vec<PluginDiagnostic>,
529 pub has_errors: bool,
530}
531
532/// Portable marketplace catalog (FEAT-020 D2).
533#[derive(Debug, Clone, PartialEq, Eq)]
534pub struct PluginMarketplaceCatalog {
535 pub id: String,
536 /// Source document path (for the `show` provenance line).
537 pub source_path: Option<String>,
538 pub display_name: Option<String>,
539 pub description: Option<String>,
540 pub format: String,
541 pub tier: String,
542 pub publisher: Option<String>,
543 pub total_candidates: usize,
544 pub warning_count: usize,
545 pub candidates: Vec<PluginMarketplaceCandidate>,
546 pub diagnostics: Vec<PluginDiagnostic>,
547}
548
549/// Portable marketplace add receipt (FEAT-020 D2).
550#[derive(Debug, Clone, PartialEq, Eq)]
551pub struct PluginMarketplaceAddReceipt {
552 pub name: String,
553 pub candidate_count: usize,
554 pub warning_count: usize,
555 pub catalog: PluginMarketplaceCatalog,
556}
557
558/// Portable marketplace state: stored catalogs plus an optional host-provided
559/// built-in `official` catalog.
560#[derive(Debug, Clone, PartialEq, Eq)]
561pub struct PluginMarketplaceState {
562 /// Optional host-provided built-in catalog. Current main provides none;
563 /// retaining the option keeps the portable boundary future-compatible
564 /// without inventing a catalog in the handler.
565 pub official: Option<PluginMarketplaceCatalog>,
566 pub stored: Vec<PluginMarketplaceCatalog>,
567}
568
569/// Portable suggestion for the `/plugin suggest` recommendation output.
570#[derive(Debug, Clone, PartialEq, Eq)]
571pub struct PluginSuggestion {
572 pub name: String,
573 /// State label rendered beside the plugin name (active/not-reviewed/…).
574 pub state_label: String,
575 pub description: String,
576 pub why: Vec<String>,
577 /// The actionable next step rendered under the suggestion.
578 pub next_step: String,
579}
580
581/// Host plugin data for the plugin command group (FEAT-020 D1).
582///
583/// One object-safe, synchronous facet exposing the exact-minimum typed
584/// operations the live `/plugin` branch closure consumes. Registry reads and
585/// mutations, async-bridged install/update/uninstall (returning synchronous
586/// portable receipts), export, legacy executable-tool scan, Kimi managed
587/// import, and marketplace operations are all represented. The handler never
588/// names `crate::plugins`, `PluginRegistry`, `LoadedPlugin`, `Config`, or
589/// another concrete host service; implementation errors cross as safe text.
590///
591/// Post-mutation side effects (rediscovery, skill-cache refresh, active-skill
592/// reset) happen host-side inside the facet implementation; the handler only
593/// renders the returned receipt (D11).
594pub trait CommandPluginContext {
595 /// Read-only: registry summaries for list output.
596 fn summaries(&self) -> Result<Vec<PluginSummary>, String>;
597 /// Read-only: full portable detail for show/review/validate.
598 fn detail(&self, selector: &str) -> Result<PluginDetail, String>;
599 /// Read-only: registry-level diagnostics.
600 fn registry_diagnostics(&self) -> Vec<PluginDiagnostic>;
601 /// Read-only: whether validation reports no errors.
602 fn validation_is_clean(&self) -> bool;
603 /// Read-only: registry length (used by list/reload empty branches).
604 fn len(&self) -> usize;
605 /// Mutation: rediscover the workspace registry and refresh the skill
606 /// cache; returns the new registry length for the reload message.
607 fn reload(&mut self) -> Result<usize, String>;
608 /// Read-only: whether the registry is empty.
609 fn is_empty(&self) -> bool;
610 /// Return the one-shot on-disk-change nudge, if the host detects one.
611 /// The host owns the mutable catalog-stamp state; handlers only render.
612 fn reload_nudge(&mut self) -> Option<String>;
613 /// Read-only: persistence store path for marketplace state.
614 fn state_path(&self) -> Option<PathBuf>;
615 /// Read-only: recommend installed bundles for a task without side effects.
616 fn suggest(&self, task: &str) -> Result<Vec<PluginSuggestion>, String>;
617 /// Mutation: trust a bundle by exact review token. Success means the
618 /// mutation was applied; the handler renders the action word from its own
619 /// dispatch arm and may re-read `detail` for post-mutation state.
620 fn trust(&mut self, selector: &str, token: &str) -> Result<(), String>;
621 /// Mutation: enable a bundle. Success means enabled; re-read `detail` for
622 /// the post-mutation compatibility note.
623 fn enable(&mut self, selector: &str) -> Result<(), String>;
624 /// Mutation: disable a bundle.
625 fn disable(&mut self, selector: &str) -> Result<(), String>;
626 /// Mutation: revoke trust.
627 fn revoke_trust(&mut self, selector: &str) -> Result<(), String>;
628 /// Async-bridged install; returns a synchronous portable receipt (D11).
629 fn install(
630 &mut self,
631 source: &str,
632 expected_content_hash: Option<&str>,
633 ) -> Result<PluginMutationReceipt, String>;
634 /// Async-bridged update; returns a synchronous portable receipt (D11).
635 fn update(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
636 /// Async-bridged uninstall; returns a synchronous portable receipt (D11).
637 fn uninstall(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
638 /// File-level removal of a just-installed bundle whose content hash
639 /// mismatched (rollback). Unlike [`Self::uninstall`] it does not resolve a
640 /// registry selector and triggers no rediscovery or skill-cache side
641 /// effects; the host adapter owns the `crate::plugins` call (D1).
642 fn uninstall_path(&mut self, name: &str, plugins_dir: &Path) -> Result<(), String>;
643 /// Read-only: export a loaded bundle to a target directory.
644 fn export(&self, selector: &str, target: &Path) -> Result<PluginExportReceipt, String>;
645 /// Read-only: scan legacy executable plugin tools.
646 fn legacy_scan(&self) -> Result<Option<PluginLegacyScan>, String>;
647 /// Read-only: Kimi managed-plugin directory scan.
648 fn managed_scan(&self, home_override: Option<&Path>) -> Result<PluginManagedScan, String>;
649 /// Mutation: install a Kimi managed candidate by exact content hash.
650 fn managed_install(
651 &mut self,
652 canonical_path: &Path,
653 expected_content_hash: &str,
654 ) -> Result<PluginMutationReceipt, String>;
655 /// Read-only: marketplace state (optional host catalog + stored catalogs).
656 fn marketplace_state(&self) -> Result<PluginMarketplaceState, String>;
657 /// Mutation: add a local catalog document to the marketplace store.
658 fn marketplace_add(
659 &mut self,
660 name: &str,
661 path: &Path,
662 ) -> Result<PluginMarketplaceAddReceipt, String>;
663 /// Mutation: remove a stored marketplace catalog.
664 fn marketplace_remove(&mut self, name: &str) -> Result<bool, String>;
665 /// Mutation: install a marketplace candidate through the reviewed installer.
666 fn marketplace_install(
667 &mut self,
668 catalog: &str,
669 candidate: &str,
670 ) -> Result<PluginMutationReceipt, String>;
671}
672
673// ---------------------------------------------------------------------------
674// Skill group (FEAT-022 D1)
675// ---------------------------------------------------------------------------
676
677/// Source provenance of a discovered skill (native file vs reviewed plugin snapshot).
678#[derive(Debug, Clone, PartialEq, Eq)]
679pub enum SkillSourceKind {
680 Native,
681 Plugin {
682 plugin_name: String,
683 plugin_id: String,
684 },
685}
686
687/// Curated product tier for bundled (shipped) skills.
688///
689/// The canonical name→tier classification stays in the TUI host
690/// (`crate::skills::system::bundled_skill_tier`); the portable projection
691/// carries the resolved tier so the handler can render the curated listing
692/// without duplicating the canonical bundle list.
693#[derive(Debug, Clone, Copy, PartialEq, Eq)]
694pub enum SkillBundledTier {
695 CoreAgentic,
696 FormatTooling,
697}
698
699impl SkillBundledTier {
700 /// Product-facing tier heading used by the `/skills` listing.
701 #[must_use]
702 pub fn heading(self) -> &'static str {
703 match self {
704 Self::CoreAgentic => "Core agentic",
705 Self::FormatTooling => "Format & tooling",
706 }
707 }
708}
709
710/// One discovered skill entry (portable).
711///
712/// The body is intentionally excluded: activation and review receive body
713/// text through their own delegates (`SkillActivationOutcome`/`ReviewOutcome`);
714/// listing and inspect render name, description, source, and path only (D1
715/// exact-minimum).
716#[derive(Debug, Clone, PartialEq, Eq)]
717pub struct SkillEntry {
718 pub name: String,
719 pub description: String,
720 pub source: SkillSourceKind,
721 /// Native skills carry their on-disk path (inspect output).
722 pub path: Option<String>,
723 /// Bundled catalog tier; `None` for user/compatible skills.
724 pub bundled_tier: Option<SkillBundledTier>,
725}
726
727/// Portable projection of the host skill registry (discovery, D1).
728///
729/// Carries every value the `/skills` and `/skill` handlers render: workspace
730/// and configured skills dir displays, discovery mode label, searched
731/// directories, entries, warnings, and the enabled-skill total.
732#[derive(Debug, Clone, PartialEq, Eq)]
733pub struct SkillRegistryProjection {
734 pub workspace: String,
735 pub skills_dir: String,
736 pub mode_label: String,
737 pub dirs: Vec<String>,
738 pub entries: Vec<SkillEntry>,
739 pub warnings: Vec<String>,
740 pub total: usize,
741}
742
743/// Target scope for skill mutations (`/skill install|update|uninstall|trust`).
744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
745pub enum SkillTargetScope {
746 Project,
747 Global,
748}
749
750/// Portable mutation outcome mirroring the host receipt variants.
751#[derive(Debug, Clone, PartialEq, Eq)]
752pub enum SkillMutationOutcome {
753 Installed,
754 Updated,
755 NoChange,
756 Removed,
757 Trusted,
758 Imported,
759 AlreadyPresent,
760 NeedsApproval(String),
761 NetworkDenied(String),
762}
763
764/// Synchronous portable receipt for a skill mutation (FEAT-020 D11 mirror):
765/// the host owns the async network bridge; the handler renders the receipt
766/// byte-identically from these values.
767#[derive(Debug, Clone, PartialEq, Eq)]
768pub struct SkillMutationReceipt {
769 pub name: String,
770 pub safe_target_path: String,
771 pub outcome: SkillMutationOutcome,
772}
773
774/// One curated remote registry entry (`/skills --remote`).
775#[derive(Debug, Clone, PartialEq, Eq)]
776pub struct RemoteSkillEntry {
777 pub name: String,
778 pub description: Option<String>,
779 pub source: String,
780}
781
782/// Remote registry fetch outcome (`/skills --remote`, suggest source).
783#[derive(Debug, Clone, PartialEq, Eq)]
784pub enum RemoteRegistryOutcome {
785 Loaded { entries: Vec<RemoteSkillEntry> },
786 NeedsApproval(String),
787 Denied(String),
788}
789
790/// Remote recommendation for `/skills suggest <task>`.
791#[derive(Debug, Clone, PartialEq, Eq)]
792pub struct SkillRecommendation {
793 pub name: String,
794 pub description: Option<String>,
795 pub matched_terms: Vec<String>,
796}
797
798/// Per-skill outcome of `/skills sync`.
799#[derive(Debug, Clone, PartialEq, Eq)]
800pub enum SkillSyncEntry {
801 Downloaded { name: String, path: String },
802 Fresh { name: String },
803 Failed { name: String, reason: String },
804 Denied { name: String, host: String },
805 NeedsApproval { name: String, host: String },
806}
807
808/// Aggregate `/skills sync` outcome.
809///
810/// Registry-level network-policy outcomes are carried as variants so the
811/// portable handler composes the exact `needs_approval` / `denied` messages.
812#[derive(Debug, Clone, PartialEq, Eq)]
813pub enum SkillSyncOutcome {
814 Done {
815 total: usize,
816 downloaded: usize,
817 fresh: usize,
818 failed: usize,
819 entries: Vec<SkillSyncEntry>,
820 },
821 RegistryNeedsApproval(String),
822 RegistryDenied(String),
823}
824
825/// Successful skill activation data (host performs the side effects).
826#[derive(Debug, Clone, PartialEq, Eq)]
827pub struct SkillActivationOutcome {
828 pub name: String,
829 pub description: String,
830}
831
832/// Activation failures with the exact data the handler renders.
833#[derive(Debug, Clone, PartialEq, Eq)]
834pub enum SkillActivationError {
835 NotFound {
836 requested: String,
837 available: Vec<String>,
838 warnings: Vec<String>,
839 },
840 PluginRejected {
841 name: String,
842 reason: String,
843 },
844}
845
846/// `/review` outcome data (host performs the side effects).
847///
848/// On success the baseline `/review` renders no message — it only emits the
849/// `SendMessage` action — so `Ready` carries no payload (D1 exact-minimum).
850/// Warnings are only rendered on the not-found path.
851#[derive(Debug, Clone, PartialEq, Eq)]
852pub enum ReviewOutcome {
853 Ready,
854 NotFound {
855 skills_dir: String,
856 global_dir: String,
857 warnings: Vec<String>,
858 },
859}
860
861/// One snapshot entry for `/restore` listings.
862#[derive(Debug, Clone, PartialEq, Eq)]
863pub struct SnapshotEntry {
864 pub id: String,
865 pub label: String,
866 pub timestamp: i64,
867}
868
869/// Host approval posture for the `/restore` trust gate (D4: no MODE_POLICY).
870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
871pub struct CommandApprovalState {
872 pub yolo: bool,
873 pub trust_mode: bool,
874}
875
876/// Host skill data for the skills command group (FEAT-022 D1).
877///
878/// Exposes the typed, exact-minimum operations the live skills handlers
879/// consume: discovery (`/skills`), activation (`/skill`), synchronous
880/// mutation receipts (`/skill install|update|uninstall|trust`), remote
881/// registry + sync (`/skills --remote|sync|suggest`), review (`/review`),
882/// and snapshot list/restore plus approval state (`/restore`). The host
883/// adapter is the only place that touches `App`, `crate::plugins`,
884/// `SnapshotRepo`, `crate::skills` services, config/network policy, and the
885/// async runtime bridge. The shared FEAT-015 `CommandSkillsContext` is never
886/// widened; active-skill reads use that facet, mutations flow through the
887/// delegates here (D2). All results are contract-owned portable values;
888/// implementation errors cross as safe text. `/skill` declares this facet
889/// plus `CommandSkillsContext` for the baseline cache-refresh policy;
890/// `/skills`, `/review`, and `/restore` declare exactly this facet.
891pub trait CommandSkillGroupContext {
892 /// `/skills` discovery projection (workspace, skills dir, scan mode,
893 /// searched directories, plugin-provided skills, warnings).
894 fn skill_registry_projection(&self) -> SkillRegistryProjection;
895 /// `/skill` activation: host lookup, plugin-authority verification, and
896 /// active-skill/history side effects. `SendMessage` task composition is
897 /// handler-side.
898 fn activate_skill(
899 &mut self,
900 name: &str,
901 ) -> Result<SkillActivationOutcome, SkillActivationError>;
902 /// `/skill install` — synchronous portable receipt; host owns network/async.
903 fn install_skill(
904 &mut self,
905 scope: Option<SkillTargetScope>,
906 spec: &str,
907 ) -> Result<SkillMutationReceipt, String>;
908 /// `/skill update` — synchronous portable receipt; host owns network/async.
909 fn update_skill(
910 &mut self,
911 scope: Option<SkillTargetScope>,
912 name: &str,
913 ) -> Result<SkillMutationReceipt, String>;
914 /// `/skill uninstall` — synchronous portable receipt.
915 fn uninstall_skill(
916 &mut self,
917 scope: Option<SkillTargetScope>,
918 name: &str,
919 ) -> Result<SkillMutationReceipt, String>;
920 /// `/skill trust` — synchronous portable receipt.
921 fn trust_skill(
922 &mut self,
923 scope: Option<SkillTargetScope>,
924 name: &str,
925 ) -> Result<SkillMutationReceipt, String>;
926 /// `/skills --remote` registry fetch (network policy host-side).
927 fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String>;
928 /// `/skills suggest <task>` — host fetch + recommendation computation.
929 fn recommend_skills(&mut self, task: &str) -> Result<Vec<SkillRecommendation>, String>;
930 /// `/skills sync` — host registry sync (async bridge host-side).
931 fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String>;
932 /// `/review` activation: host discovery + side effects (empty-target
933 /// validation and `SendMessage` composition are handler-side).
934 fn run_review(&mut self) -> Result<ReviewOutcome, String>;
935 /// `/restore` snapshot listing.
936 fn snapshot_list(&mut self, limit: usize) -> Result<Vec<SnapshotEntry>, String>;
937 /// `/restore <N>`: host restores by snapshot id; handler composes the
938 /// exact success message from its list entry.
939 fn restore_snapshot(&mut self, id: &str) -> Result<(), String>;
940 /// `/restore` trust gate posture (yolo / trust_mode).
941 fn approval_state(&self) -> CommandApprovalState;
942}