codewhale-command-contract 0.9.12

Prototype command capability and dispatch shapes for the staged TUI command extraction
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//! Independent, object-safe capability shapes for staged command migration.
//!
//! FEAT-014 publishes these interfaces without implementing them for the TUI
//! or changing an existing command. Later work adopts them inside
//! `codewhale-tui` one command group at a time. Only after every group uses
//! these shapes will groups move physically into a commands crate.

use std::path::{Path, PathBuf};

use codewhale_core::request::{Message, SystemPrompt};

use crate::types::{
    CommandApprovalMode, CommandCurrency, CommandMode, CommandProviderId, CommandReasoningEffort,
};

/// Session identity, messages, queue operations, and token totals.
pub trait CommandSessionContext {
    fn session_id(&self) -> Option<String>;
    fn api_messages(&self) -> Vec<Message>;
    fn add_message(&mut self, message: Message);
    fn queued_message_count(&self) -> usize;
    fn remove_queued_message(&mut self, index: usize) -> Result<(), String>;
    fn total_tokens(&self) -> u64;
}

/// Model selection, provider identity, effort, and fallback chain.
pub trait CommandModelContext {
    fn current_model(&self) -> String;
    fn auto_model(&self) -> bool;
    fn set_model_selection(&mut self, model: String, provider: Option<CommandProviderId>);
    fn reasoning_effort(&self) -> CommandReasoningEffort;
    fn provider_identity(&self) -> Option<CommandProviderId>;
    fn fallback_chain(&self) -> Vec<CommandProviderId>;
}

/// Cost display and accounting operations.
pub trait CommandCostContext {
    fn display_currency(&self) -> CommandCurrency;
    fn session_cost_for_currency(&self, currency: CommandCurrency) -> f64;
    fn subagent_cost_for_currency(&self, currency: CommandCurrency) -> f64;
    fn accrue_cost_estimate(&mut self, amount: f64, currency: CommandCurrency);
    fn record_turn_cost(
        &mut self,
        amount: f64,
        currency: CommandCurrency,
        route_receipt: Option<String>,
    );
}

/// Operating mode, approval posture, shell access, and policy lock.
pub trait CommandModePolicyContext {
    fn mode(&self) -> CommandMode;
    fn set_mode(&mut self, mode: CommandMode);
    fn approval_mode(&self) -> CommandApprovalMode;
    fn allow_shell(&self) -> bool;
    fn set_shell_access(&mut self, allow: bool);
    fn policy_locked(&self) -> bool;
}

/// Read access to the effective system prompt.
pub trait CommandSystemPromptContext {
    fn system_prompt(&self) -> Option<SystemPrompt>;
}

/// Active skill identity and skill-cache refresh.
pub trait CommandSkillsContext {
    fn active_skill(&self) -> Option<String>;
    fn active_skill_provenance(&self) -> Option<String>;
    fn refresh_skill_cache(&mut self);
}

/// Workspace path and a bounded serialized work-state snapshot.
pub trait CommandWorkspaceContext {
    fn workspace(&self) -> PathBuf;
    fn work_state_snapshot(&self) -> Result<Option<String>, String>;
    /// Session-aware canonical operation digest. Returns the final user-facing
    /// digest text or a safe explicit error; never a serialized snapshot.
    /// No-active-work and temporary-unavailability semantics are preserved by
    /// the host implementation (FEAT-018 D5).
    fn operation_digest(&mut self) -> Result<String, String>;
}

/// Stable-key translation with named replacements (FEAT-018 D3).
///
/// Message identity uses stable snake_case keys plus named replacements. The
/// TUI host maps those keys to the current catalog and preserves the existing
/// English fallback for intentionally incomplete locale packs. Unknown keys or
/// invalid replacement contracts fail safely and produce a command error; they
/// never panic and never display a raw lookup key.
pub trait CommandPresentationContext {
    /// Resolve a stable message key with its named replacements.
    fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String>;
}

/// Portable receipt for a successful atomic media attachment (FEAT-018 D4).
/// Carries only the information needed for the existing confirmation text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MediaAttachmentReceipt {
    pub kind: String,
    pub path: std::path::PathBuf,
}

/// Atomic composer/media capability (FEAT-018 D4).
///
/// The host performs media validation and composer insertion as one atomic
/// operation. Rejected, missing, unsupported, corrupt, or oversized media
/// leaves composer state unchanged and returns a safe error. Only portable
/// success information crosses the boundary; composer markup, mutable input
/// text, decoder internals, and TUI types never do.
pub trait CommandMediaContext {
    /// Validate and insert a resolved media path atomically.
    fn attach_media(&mut self, resolved_path: &Path) -> Result<MediaAttachmentReceipt, String>;
}

// ---------------------------------------------------------------------------
// Project (FEAT-021 D1/D2/D3/D4)
// ---------------------------------------------------------------------------

/// Portable goal status for the project facet (FEAT-021 D1).
///
/// Mirrors the four TUI-owned `tools::goal::GoalStatus` variants without
/// naming the TUI type. The adapter maps host state onto this enum; handlers
/// compare and render it directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProjectGoalStatus {
    #[default]
    Active,
    Paused,
    Complete,
    Blocked,
}

/// Portable session-share projection (FEAT-021 D1).
///
/// Carries only the emptiness/length and the model/mode labels the live
/// `/share` handler consumes. The session history itself, exporter I/O, and
/// all `App` state stay host-side.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectShareProjection {
    /// Whether the session history is empty (drives the empty-share error).
    pub history_is_empty: bool,
    /// Session history length used in the export message and action.
    pub history_len: usize,
    /// Current model label.
    pub model: String,
    /// Current operating-mode label.
    pub mode_label: String,
}

/// Portable goal projection (FEAT-021 D1).
///
/// Carries the visible goal state, the effective pending-control view, and the
/// session-derived token fallback the live `/goal` handler consumes. Concrete
/// goal-service, session-manager, and `App` types never cross the boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectGoalState {
    /// Visible goal objective.
    pub objective: Option<String>,
    /// Visible goal status.
    pub status: ProjectGoalStatus,
    /// Pause reason label when the goal is paused (already rendered).
    pub pause_reason: Option<String>,
    /// Elapsed seconds from `started_at` when present (host-computed).
    pub started_at_elapsed_seconds: Option<u64>,
    /// Seconds of goal time used (stable budget/elapsed source).
    pub time_used_seconds: u64,
    /// Optional token budget.
    pub token_budget: Option<u32>,
    /// Tokens used by the goal engine.
    pub tokens_used: u64,
    /// Session conversation-token total (fallback when tokens_used == 0).
    pub session_total_tokens: u32,
    /// Goal continuation count.
    pub continuation_count: u32,
    /// Whether pending goal controls are queued (effective-state gate).
    pub pending_controls: bool,
    /// Last-known durable objective (session-derived effective source).
    pub last_known_objective: Option<String>,
    /// Last-known durable status (session-derived effective source).
    pub last_known_status: Option<ProjectGoalStatus>,
    /// Whether the conversation has API messages (bare `/goal` context gate).
    pub conversation_present: bool,
    /// Whether the host is currently loading (idle-hint gate).
    pub is_loading: bool,
    /// Whether the goal continuation loop is waiting (idle-hint gate).
    pub goal_continuation_waiting: bool,
}

/// Host project data for the project command group (FEAT-021 D1).
///
/// Exposes the typed, exact-minimum operations the live project handlers
/// consume: `/lsp` status/set state, `/share` session payload data, and
/// `/goal` goal state including the session-derived effective values.
/// `/init` host data flows through the existing `WORKSPACE` facet (D2), so
/// `/init` destructures exactly `WORKSPACE` (D4) and consumes no
/// project-facet method. All results are contract-owned portable values; implementation
/// errors cross as safe text. The TUI adapter is the only place that touches
/// `App`, `config::config`, the goal service, or the session manager.
pub trait CommandProjectContext {
    /// `/lsp` status: whether LSP diagnostics are enabled.
    fn lsp_enabled(&self) -> bool;
    /// `/lsp` set: enable or disable LSP diagnostics.
    fn lsp_set(&mut self, enabled: bool) -> Result<(), String>;
    /// `/share` projection: session emptiness, length, model, and mode label.
    fn share_projection(&self) -> ProjectShareProjection;
    /// `/goal` projection: visible and effective goal state.
    fn goal_state(&self) -> ProjectGoalState;
}

// ---------------------------------------------------------------------------
// Memory (FEAT-019 D1/D2/D8/D9)
// ---------------------------------------------------------------------------

/// Portable semantic hit for a native-memory search or get result.
///
/// Carries only the typed location and text the handler consumes for
/// formatting; the TUI-owned `NativeMemoryHit` never crosses the boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryHit {
    pub source: PathBuf,
    pub line_start: usize,
    pub line_end: usize,
    pub text: String,
}

/// Portable native-memory location summary (status operation).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryStatus {
    pub root: PathBuf,
    pub source: PathBuf,
    pub index: PathBuf,
}

/// Portable result of a successful remember operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryRemembered {
    pub source: PathBuf,
    pub line_start: usize,
}

/// Portable import outcome: imported (with destination) or skipped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemoryImportOutcome {
    Imported { destination: PathBuf },
    Skipped,
}

/// Portable get outcome: found hit or explicit not-found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemoryGetOutcome {
    Found(MemoryHit),
    NotFound,
}

/// Portable export payload — the exported memory document itself, never a
/// preformatted command response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryExport {
    pub content: String,
}

/// Portable reindex entry count.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryReindex {
    pub entry_count: usize,
}

/// Zero-field success value for delete operations (D2): the handler already
/// owns the selected scope and needs no additional success data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MemoryDelete;

/// Typed remember target (D9): the handler resolves workspace identity through
/// the workspace facet and passes the resulting typed ID here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemoryRememberTarget {
    Global,
    Workspace { workspace_id: String },
}

/// Typed delete scope for the non-workspace delete method (D8/D9).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryDeleteScope {
    /// Delete every memory entry (global and all workspace scopes).
    All,
    /// Delete only the global scope entries.
    Global,
}

/// Host memory data for the memory command group (FEAT-019 D1).
///
/// Exposes the resolved user-memory file path, the enablement flag, and one
/// typed method per exposed native-memory operation. All results are
/// contract-owned portable values; implementation errors cross as safe text.
/// Workspace-scoped operations take the borrowed workspace path as their first
/// argument (D8); non-workspace operations never receive workspace authority
/// and the facet never captures or retains workspace state internally.
pub trait CommandMemoryContext {
    /// The resolved user-memory file path.
    fn memory_path(&self) -> PathBuf;
    /// Whether the `[memory] enabled` / `DEEPSEEK_MEMORY=on` flag is set.
    fn memory_enabled(&self) -> bool;
    /// Native-memory root, global source, and index paths.
    fn status(&self) -> Result<MemoryStatus, String>;
    /// The native-memory root path.
    fn path(&self) -> Result<PathBuf, String>;
    /// Workspace identity for the given workspace path.
    fn workspace_id(&self, workspace: &Path) -> Result<String, String>;
    /// Workspace-scoped search over the native-memory store.
    fn search(&self, workspace: &Path, query: &str, limit: usize)
    -> Result<Vec<MemoryHit>, String>;
    /// Append a reviewed note to the typed global or workspace target.
    fn remember(
        &self,
        target: MemoryRememberTarget,
        note: &str,
    ) -> Result<MemoryRemembered, String>;
    /// Import legacy memory; distinguishes imported from skipped.
    fn import(&self) -> Result<MemoryImportOutcome, String>;
    /// Workspace-scoped get by entry id; not-found is a typed outcome.
    fn get(&self, workspace: &Path, id: i64) -> Result<MemoryGetOutcome, String>;
    /// Export the native-memory document content.
    fn export(&self) -> Result<MemoryExport, String>;
    /// Reindex the native-memory store; returns the indexed entry count.
    fn reindex(&self) -> Result<MemoryReindex, String>;
    /// Delete all or global scope; never receives workspace authority.
    fn delete(&self, scope: MemoryDeleteScope) -> Result<MemoryDelete, String>;
    /// Delete the given workspace scope; workspace path is the first argument.
    fn delete_workspace(&self, workspace: &Path) -> Result<MemoryDelete, String>;
}

// ---------------------------------------------------------------------------
// Plugin (FEAT-020 D1/D2/D10/D11)
// ---------------------------------------------------------------------------

/// Portable plugin diagnostic level (FEAT-020 D2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginDiagnosticLevel {
    Warning,
    Error,
}

/// Portable plugin diagnostic entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginDiagnostic {
    pub level: PluginDiagnosticLevel,
    pub code: String,
    pub message: String,
    pub path: Option<PathBuf>,
}

/// Portable MCP transport classification for the capability review body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginMcpTransport {
    Stdio,
    Http,
    Invalid,
}

/// Portable MCP server detail for the capability review body (FEAT-020 D2).
///
/// Carries only the semantic fields `render_mcp_inventory` consumes:
/// transport, command/url, argv, cwd, env provenance, timeouts, required,
/// enabled/disabled tool lists, and the enabled flag. Host `McpServerConfig`
/// never crosses the boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginMcpServerDetail {
    pub name: String,
    pub transport: PluginMcpTransport,
    pub command: Option<String>,
    pub argv: Vec<String>,
    pub cwd: Option<PathBuf>,
    pub env: Vec<(String, String)>,
    pub url: Option<String>,
    pub env_headers: Vec<(String, String)>,
    pub bearer_token_env_var: Option<String>,
    pub connect_timeout_secs: Option<u64>,
    pub execute_timeout_secs: Option<u64>,
    pub read_timeout_secs: Option<u64>,
    pub required: bool,
    pub enabled_tools: Vec<String>,
    pub disabled_tools: Vec<String>,
    pub enabled: bool,
}

/// Portable summary of one loaded plugin bundle (list output, FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginSummary {
    pub name: String,
    pub id: String,
    pub state_label: String,
    pub scope: String,
    pub trust_status: String,
    pub compatibility: String,
    pub inventory: String,
    pub active: bool,
    pub trusted: bool,
    pub enabled: bool,
}

/// Portable full bundle detail for show/review/validate rendering (FEAT-020 D2).
///
/// Carries every semantic value the render helpers consume. The complete
/// `LoadedPlugin` never crosses the boundary; only branch-consumed fields are
/// projected here (D10).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginDetail {
    /// Inventory summary string (host-computed, e.g. `skills=1 mcp=0`).
    pub inventory_summary: String,
    pub name: String,
    pub id: String,
    pub version: String,
    pub origin: String,
    pub scope: String,
    pub state_label: String,
    pub trust_status: String,
    pub compatibility: String,
    pub content_hash: String,
    pub capability_hash: String,
    pub canonical_root: PathBuf,
    pub active: bool,
    pub trusted: bool,
    pub enabled: bool,
    pub unsupported_labels: Vec<String>,
    pub supported_labels: Vec<String>,
    pub skills: Vec<String>,
    pub filesystem_roots: Vec<String>,
    pub network_hosts: Vec<String>,
    pub stdio_mcp_servers: usize,
    pub lifecycle_mutation: bool,
    pub mcp_servers: Vec<PluginMcpServerDetail>,
    pub diagnostics: Vec<PluginDiagnostic>,
}

/// Portable outcome of a plugin mutation (FEAT-020 D2/D11).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PluginMutationOutcome {
    Installed,
    Updated,
    NoChange,
    Uninstalled,
    NeedsApproval(String),
    NetworkDenied(String),
}

/// Portable mutation receipt returned synchronously by the facet (FEAT-020 D11).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginMutationReceipt {
    pub name: String,
    pub path: Option<PathBuf>,
    pub content_hash: Option<String>,
    pub installed_content_hash: Option<String>,
    pub outcome: PluginMutationOutcome,
}

/// Portable bundle export receipt (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginExportReceipt {
    pub exported_name: String,
    pub target: PathBuf,
    pub display_name: Option<String>,
    pub wrote_mcp_json: bool,
    pub files_copied: u64,
    pub skills_normalized: bool,
}

/// Portable legacy executable-tool detail (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginLegacyTool {
    pub name: String,
    pub description: String,
    pub approval: String,
    pub input_schema: Option<String>,
    pub path: PathBuf,
}

/// Portable legacy-tool scan result: directory and discovered tools.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginLegacyScan {
    pub dir: PathBuf,
    pub tools: Vec<PluginLegacyTool>,
}

/// Portable Kimi managed-plugin candidate (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginManagedCandidate {
    pub name: String,
    pub version: String,
    pub license: Option<String>,
    pub canonical_path: PathBuf,
    pub content_hash: String,
    pub capability_hash: String,
    pub inventory: String,
    pub applicable: bool,
}

/// Portable Kimi managed-scan result (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginManagedScan {
    pub root: PathBuf,
    pub candidates: Vec<PluginManagedCandidate>,
    pub rejected: Vec<String>,
}

/// Portable marketplace candidate install plan (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PluginMarketplaceInstallPlan {
    Supported { spec: String, source_kind: String },
    Unsupported { reason: String },
}

/// Portable marketplace candidate (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginMarketplaceCandidate {
    pub name: String,
    pub display_name: Option<String>,
    pub version: Option<String>,
    pub tier: String,
    pub compatibility: Option<String>,
    pub install_plan: PluginMarketplaceInstallPlan,
    pub description: Option<String>,
    pub homepage: Option<String>,
    pub repository: Option<String>,
    pub author: Option<String>,
    pub license: Option<String>,
    pub keywords: Vec<String>,
    pub when: Option<String>,
    pub diagnostics: Vec<PluginDiagnostic>,
    pub has_errors: bool,
}

/// Portable marketplace catalog (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginMarketplaceCatalog {
    pub id: String,
    /// Source document path (for the `show` provenance line).
    pub source_path: Option<String>,
    pub display_name: Option<String>,
    pub description: Option<String>,
    pub format: String,
    pub tier: String,
    pub publisher: Option<String>,
    pub total_candidates: usize,
    pub warning_count: usize,
    pub candidates: Vec<PluginMarketplaceCandidate>,
    pub diagnostics: Vec<PluginDiagnostic>,
}

/// Portable marketplace add receipt (FEAT-020 D2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginMarketplaceAddReceipt {
    pub name: String,
    pub candidate_count: usize,
    pub warning_count: usize,
    pub catalog: PluginMarketplaceCatalog,
}

/// Portable marketplace state: stored catalogs plus an optional host-provided
/// built-in `official` catalog.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginMarketplaceState {
    /// Optional host-provided built-in catalog. Current main provides none;
    /// retaining the option keeps the portable boundary future-compatible
    /// without inventing a catalog in the handler.
    pub official: Option<PluginMarketplaceCatalog>,
    pub stored: Vec<PluginMarketplaceCatalog>,
}

/// Portable suggestion for the `/plugin suggest` recommendation output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginSuggestion {
    pub name: String,
    /// State label rendered beside the plugin name (active/not-reviewed/…).
    pub state_label: String,
    pub description: String,
    pub why: Vec<String>,
    /// The actionable next step rendered under the suggestion.
    pub next_step: String,
}

/// Host plugin data for the plugin command group (FEAT-020 D1).
///
/// One object-safe, synchronous facet exposing the exact-minimum typed
/// operations the live `/plugin` branch closure consumes. Registry reads and
/// mutations, async-bridged install/update/uninstall (returning synchronous
/// portable receipts), export, legacy executable-tool scan, Kimi managed
/// import, and marketplace operations are all represented. The handler never
/// names `crate::plugins`, `PluginRegistry`, `LoadedPlugin`, `Config`, or
/// another concrete host service; implementation errors cross as safe text.
///
/// Post-mutation side effects (rediscovery, skill-cache refresh, active-skill
/// reset) happen host-side inside the facet implementation; the handler only
/// renders the returned receipt (D11).
pub trait CommandPluginContext {
    /// Read-only: registry summaries for list output.
    fn summaries(&self) -> Result<Vec<PluginSummary>, String>;
    /// Read-only: full portable detail for show/review/validate.
    fn detail(&self, selector: &str) -> Result<PluginDetail, String>;
    /// Read-only: registry-level diagnostics.
    fn registry_diagnostics(&self) -> Vec<PluginDiagnostic>;
    /// Read-only: whether validation reports no errors.
    fn validation_is_clean(&self) -> bool;
    /// Read-only: registry length (used by list/reload empty branches).
    fn len(&self) -> usize;
    /// Mutation: rediscover the workspace registry and refresh the skill
    /// cache; returns the new registry length for the reload message.
    fn reload(&mut self) -> Result<usize, String>;
    /// Read-only: whether the registry is empty.
    fn is_empty(&self) -> bool;
    /// Return the one-shot on-disk-change nudge, if the host detects one.
    /// The host owns the mutable catalog-stamp state; handlers only render.
    fn reload_nudge(&mut self) -> Option<String>;
    /// Read-only: persistence store path for marketplace state.
    fn state_path(&self) -> Option<PathBuf>;
    /// Read-only: recommend installed bundles for a task without side effects.
    fn suggest(&self, task: &str) -> Result<Vec<PluginSuggestion>, String>;
    /// Mutation: trust a bundle by exact review token. Success means the
    /// mutation was applied; the handler renders the action word from its own
    /// dispatch arm and may re-read `detail` for post-mutation state.
    fn trust(&mut self, selector: &str, token: &str) -> Result<(), String>;
    /// Mutation: enable a bundle. Success means enabled; re-read `detail` for
    /// the post-mutation compatibility note.
    fn enable(&mut self, selector: &str) -> Result<(), String>;
    /// Mutation: disable a bundle.
    fn disable(&mut self, selector: &str) -> Result<(), String>;
    /// Mutation: revoke trust.
    fn revoke_trust(&mut self, selector: &str) -> Result<(), String>;
    /// Async-bridged install; returns a synchronous portable receipt (D11).
    fn install(
        &mut self,
        source: &str,
        expected_content_hash: Option<&str>,
    ) -> Result<PluginMutationReceipt, String>;
    /// Async-bridged update; returns a synchronous portable receipt (D11).
    fn update(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
    /// Async-bridged uninstall; returns a synchronous portable receipt (D11).
    fn uninstall(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
    /// File-level removal of a just-installed bundle whose content hash
    /// mismatched (rollback). Unlike [`Self::uninstall`] it does not resolve a
    /// registry selector and triggers no rediscovery or skill-cache side
    /// effects; the host adapter owns the `crate::plugins` call (D1).
    fn uninstall_path(&mut self, name: &str, plugins_dir: &Path) -> Result<(), String>;
    /// Read-only: export a loaded bundle to a target directory.
    fn export(&self, selector: &str, target: &Path) -> Result<PluginExportReceipt, String>;
    /// Read-only: scan legacy executable plugin tools.
    fn legacy_scan(&self) -> Result<Option<PluginLegacyScan>, String>;
    /// Read-only: Kimi managed-plugin directory scan.
    fn managed_scan(&self, home_override: Option<&Path>) -> Result<PluginManagedScan, String>;
    /// Mutation: install a Kimi managed candidate by exact content hash.
    fn managed_install(
        &mut self,
        canonical_path: &Path,
        expected_content_hash: &str,
    ) -> Result<PluginMutationReceipt, String>;
    /// Read-only: marketplace state (optional host catalog + stored catalogs).
    fn marketplace_state(&self) -> Result<PluginMarketplaceState, String>;
    /// Mutation: add a local catalog document to the marketplace store.
    fn marketplace_add(
        &mut self,
        name: &str,
        path: &Path,
    ) -> Result<PluginMarketplaceAddReceipt, String>;
    /// Mutation: remove a stored marketplace catalog.
    fn marketplace_remove(&mut self, name: &str) -> Result<bool, String>;
    /// Mutation: install a marketplace candidate through the reviewed installer.
    fn marketplace_install(
        &mut self,
        catalog: &str,
        candidate: &str,
    ) -> Result<PluginMutationReceipt, String>;
}

// ---------------------------------------------------------------------------
// Skill group (FEAT-022 D1)
// ---------------------------------------------------------------------------

/// Source provenance of a discovered skill (native file vs reviewed plugin snapshot).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillSourceKind {
    Native,
    Plugin {
        plugin_name: String,
        plugin_id: String,
    },
}

/// Curated product tier for bundled (shipped) skills.
///
/// The canonical name→tier classification stays in the TUI host
/// (`crate::skills::system::bundled_skill_tier`); the portable projection
/// carries the resolved tier so the handler can render the curated listing
/// without duplicating the canonical bundle list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillBundledTier {
    CoreAgentic,
    FormatTooling,
}

impl SkillBundledTier {
    /// Product-facing tier heading used by the `/skills` listing.
    #[must_use]
    pub fn heading(self) -> &'static str {
        match self {
            Self::CoreAgentic => "Core agentic",
            Self::FormatTooling => "Format & tooling",
        }
    }
}

/// One discovered skill entry (portable).
///
/// The body is intentionally excluded: activation and review receive body
/// text through their own delegates (`SkillActivationOutcome`/`ReviewOutcome`);
/// listing and inspect render name, description, source, and path only (D1
/// exact-minimum).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillEntry {
    pub name: String,
    pub description: String,
    pub source: SkillSourceKind,
    /// Native skills carry their on-disk path (inspect output).
    pub path: Option<String>,
    /// Bundled catalog tier; `None` for user/compatible skills.
    pub bundled_tier: Option<SkillBundledTier>,
}

/// Portable projection of the host skill registry (discovery, D1).
///
/// Carries every value the `/skills` and `/skill` handlers render: workspace
/// and configured skills dir displays, discovery mode label, searched
/// directories, entries, warnings, and the enabled-skill total.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillRegistryProjection {
    pub workspace: String,
    pub skills_dir: String,
    pub mode_label: String,
    pub dirs: Vec<String>,
    pub entries: Vec<SkillEntry>,
    pub warnings: Vec<String>,
    pub total: usize,
}

/// Target scope for skill mutations (`/skill install|update|uninstall|trust`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillTargetScope {
    Project,
    Global,
}

/// Portable mutation outcome mirroring the host receipt variants.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillMutationOutcome {
    Installed,
    Updated,
    NoChange,
    Removed,
    Trusted,
    Imported,
    AlreadyPresent,
    NeedsApproval(String),
    NetworkDenied(String),
}

/// Synchronous portable receipt for a skill mutation (FEAT-020 D11 mirror):
/// the host owns the async network bridge; the handler renders the receipt
/// byte-identically from these values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillMutationReceipt {
    pub name: String,
    pub safe_target_path: String,
    pub outcome: SkillMutationOutcome,
}

/// One curated remote registry entry (`/skills --remote`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteSkillEntry {
    pub name: String,
    pub description: Option<String>,
    pub source: String,
}

/// Remote registry fetch outcome (`/skills --remote`, suggest source).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RemoteRegistryOutcome {
    Loaded { entries: Vec<RemoteSkillEntry> },
    NeedsApproval(String),
    Denied(String),
}

/// Remote recommendation for `/skills suggest <task>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillRecommendation {
    pub name: String,
    pub description: Option<String>,
    pub matched_terms: Vec<String>,
}

/// Per-skill outcome of `/skills sync`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillSyncEntry {
    Downloaded { name: String, path: String },
    Fresh { name: String },
    Failed { name: String, reason: String },
    Denied { name: String, host: String },
    NeedsApproval { name: String, host: String },
}

/// Aggregate `/skills sync` outcome.
///
/// Registry-level network-policy outcomes are carried as variants so the
/// portable handler composes the exact `needs_approval` / `denied` messages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillSyncOutcome {
    Done {
        total: usize,
        downloaded: usize,
        fresh: usize,
        failed: usize,
        entries: Vec<SkillSyncEntry>,
    },
    RegistryNeedsApproval(String),
    RegistryDenied(String),
}

/// Successful skill activation data (host performs the side effects).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillActivationOutcome {
    pub name: String,
    pub description: String,
}

/// Activation failures with the exact data the handler renders.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillActivationError {
    NotFound {
        requested: String,
        available: Vec<String>,
        warnings: Vec<String>,
    },
    PluginRejected {
        name: String,
        reason: String,
    },
}

/// `/review` outcome data (host performs the side effects).
///
/// On success the baseline `/review` renders no message — it only emits the
/// `SendMessage` action — so `Ready` carries no payload (D1 exact-minimum).
/// Warnings are only rendered on the not-found path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReviewOutcome {
    Ready,
    NotFound {
        skills_dir: String,
        global_dir: String,
        warnings: Vec<String>,
    },
}

/// One snapshot entry for `/restore` listings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotEntry {
    pub id: String,
    pub label: String,
    pub timestamp: i64,
}

/// Host approval posture for the `/restore` trust gate (D4: no MODE_POLICY).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandApprovalState {
    pub yolo: bool,
    pub trust_mode: bool,
}

/// Host skill data for the skills command group (FEAT-022 D1).
///
/// Exposes the typed, exact-minimum operations the live skills handlers
/// consume: discovery (`/skills`), activation (`/skill`), synchronous
/// mutation receipts (`/skill install|update|uninstall|trust`), remote
/// registry + sync (`/skills --remote|sync|suggest`), review (`/review`),
/// and snapshot list/restore plus approval state (`/restore`). The host
/// adapter is the only place that touches `App`, `crate::plugins`,
/// `SnapshotRepo`, `crate::skills` services, config/network policy, and the
/// async runtime bridge. The shared FEAT-015 `CommandSkillsContext` is never
/// widened; active-skill reads use that facet, mutations flow through the
/// delegates here (D2). All results are contract-owned portable values;
/// implementation errors cross as safe text. `/skill` declares this facet
/// plus `CommandSkillsContext` for the baseline cache-refresh policy;
/// `/skills`, `/review`, and `/restore` declare exactly this facet.
pub trait CommandSkillGroupContext {
    /// `/skills` discovery projection (workspace, skills dir, scan mode,
    /// searched directories, plugin-provided skills, warnings).
    fn skill_registry_projection(&self) -> SkillRegistryProjection;
    /// `/skill` activation: host lookup, plugin-authority verification, and
    /// active-skill/history side effects. `SendMessage` task composition is
    /// handler-side.
    fn activate_skill(
        &mut self,
        name: &str,
    ) -> Result<SkillActivationOutcome, SkillActivationError>;
    /// `/skill install` — synchronous portable receipt; host owns network/async.
    fn install_skill(
        &mut self,
        scope: Option<SkillTargetScope>,
        spec: &str,
    ) -> Result<SkillMutationReceipt, String>;
    /// `/skill update` — synchronous portable receipt; host owns network/async.
    fn update_skill(
        &mut self,
        scope: Option<SkillTargetScope>,
        name: &str,
    ) -> Result<SkillMutationReceipt, String>;
    /// `/skill uninstall` — synchronous portable receipt.
    fn uninstall_skill(
        &mut self,
        scope: Option<SkillTargetScope>,
        name: &str,
    ) -> Result<SkillMutationReceipt, String>;
    /// `/skill trust` — synchronous portable receipt.
    fn trust_skill(
        &mut self,
        scope: Option<SkillTargetScope>,
        name: &str,
    ) -> Result<SkillMutationReceipt, String>;
    /// `/skills --remote` registry fetch (network policy host-side).
    fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String>;
    /// `/skills suggest <task>` — host fetch + recommendation computation.
    fn recommend_skills(&mut self, task: &str) -> Result<Vec<SkillRecommendation>, String>;
    /// `/skills sync` — host registry sync (async bridge host-side).
    fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String>;
    /// `/review` activation: host discovery + side effects (empty-target
    /// validation and `SendMessage` composition are handler-side).
    fn run_review(&mut self) -> Result<ReviewOutcome, String>;
    /// `/restore` snapshot listing.
    fn snapshot_list(&mut self, limit: usize) -> Result<Vec<SnapshotEntry>, String>;
    /// `/restore <N>`: host restores by snapshot id; handler composes the
    /// exact success message from its list entry.
    fn restore_snapshot(&mut self, id: &str) -> Result<(), String>;
    /// `/restore` trust gate posture (yolo / trust_mode).
    fn approval_state(&self) -> CommandApprovalState;
}