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 AlreadyPresent { selector: String, reason: String },
510 Unsupported { reason: String },
511}
512
513/// Portable marketplace candidate (FEAT-020 D2).
514#[derive(Debug, Clone, PartialEq, Eq)]
515pub struct PluginMarketplaceCandidate {
516 pub name: String,
517 pub display_name: Option<String>,
518 pub version: Option<String>,
519 pub tier: String,
520 pub compatibility: Option<String>,
521 pub install_plan: PluginMarketplaceInstallPlan,
522 pub description: Option<String>,
523 pub homepage: Option<String>,
524 pub repository: Option<String>,
525 pub author: Option<String>,
526 pub license: Option<String>,
527 pub keywords: Vec<String>,
528 pub when: Option<String>,
529 pub diagnostics: Vec<PluginDiagnostic>,
530 pub has_errors: bool,
531}
532
533/// Portable marketplace catalog (FEAT-020 D2).
534#[derive(Debug, Clone, PartialEq, Eq)]
535pub struct PluginMarketplaceCatalog {
536 pub id: String,
537 /// Source document path (for the `show` provenance line).
538 pub source_path: Option<String>,
539 pub display_name: Option<String>,
540 pub description: Option<String>,
541 pub format: String,
542 pub tier: String,
543 pub publisher: Option<String>,
544 pub total_candidates: usize,
545 pub warning_count: usize,
546 pub candidates: Vec<PluginMarketplaceCandidate>,
547 pub diagnostics: Vec<PluginDiagnostic>,
548}
549
550/// Portable marketplace add receipt (FEAT-020 D2).
551#[derive(Debug, Clone, PartialEq, Eq)]
552pub struct PluginMarketplaceAddReceipt {
553 pub name: String,
554 pub candidate_count: usize,
555 pub warning_count: usize,
556 pub catalog: PluginMarketplaceCatalog,
557}
558
559/// Portable marketplace state: stored catalogs plus an optional host-provided
560/// built-in `official` catalog.
561#[derive(Debug, Clone, PartialEq, Eq)]
562pub struct PluginMarketplaceState {
563 /// Optional host-provided built-in catalog. Current main provides none;
564 /// retaining the option keeps the portable boundary future-compatible
565 /// without inventing a catalog in the handler.
566 pub official: Option<PluginMarketplaceCatalog>,
567 pub stored: Vec<PluginMarketplaceCatalog>,
568}
569
570/// Portable suggestion for the `/plugin suggest` recommendation output.
571#[derive(Debug, Clone, PartialEq, Eq)]
572pub struct PluginSuggestion {
573 pub name: String,
574 /// State label rendered beside the plugin name (active/not-reviewed/…).
575 pub state_label: String,
576 pub description: String,
577 pub why: Vec<String>,
578 /// The actionable next step rendered under the suggestion.
579 pub next_step: String,
580}
581
582/// Host plugin data for the plugin command group (FEAT-020 D1).
583///
584/// One object-safe, synchronous facet exposing the exact-minimum typed
585/// operations the live `/plugin` branch closure consumes. Registry reads and
586/// mutations, async-bridged install/update/uninstall (returning synchronous
587/// portable receipts), export, legacy executable-tool scan, Kimi managed
588/// import, and marketplace operations are all represented. The handler never
589/// names `crate::plugins`, `PluginRegistry`, `LoadedPlugin`, `Config`, or
590/// another concrete host service; implementation errors cross as safe text.
591///
592/// Post-mutation side effects (rediscovery, skill-cache refresh, active-skill
593/// reset) happen host-side inside the facet implementation; the handler only
594/// renders the returned receipt (D11).
595pub trait CommandPluginContext {
596 /// Read-only: registry summaries for list output.
597 fn summaries(&self) -> Result<Vec<PluginSummary>, String>;
598 /// Read-only: full portable detail for show/review/validate.
599 fn detail(&self, selector: &str) -> Result<PluginDetail, String>;
600 /// Read-only: registry-level diagnostics.
601 fn registry_diagnostics(&self) -> Vec<PluginDiagnostic>;
602 /// Read-only: whether validation reports no errors.
603 fn validation_is_clean(&self) -> bool;
604 /// Read-only: registry length (used by list/reload empty branches).
605 fn len(&self) -> usize;
606 /// Mutation: rediscover the workspace registry and refresh the skill
607 /// cache; returns the new registry length for the reload message.
608 fn reload(&mut self) -> Result<usize, String>;
609 /// Read-only: whether the registry is empty.
610 fn is_empty(&self) -> bool;
611 /// Return the one-shot on-disk-change nudge, if the host detects one.
612 /// The host owns the mutable catalog-stamp state; handlers only render.
613 fn reload_nudge(&mut self) -> Option<String>;
614 /// Read-only: persistence store path for marketplace state.
615 fn state_path(&self) -> Option<PathBuf>;
616 /// Read-only: recommend installed bundles for a task without side effects.
617 fn suggest(&self, task: &str) -> Result<Vec<PluginSuggestion>, String>;
618 /// Mutation: trust a bundle by exact review token. Success means the
619 /// mutation was applied; the handler renders the action word from its own
620 /// dispatch arm and may re-read `detail` for post-mutation state.
621 fn trust(&mut self, selector: &str, token: &str) -> Result<(), String>;
622 /// Mutation: enable a bundle. Success means enabled; re-read `detail` for
623 /// the post-mutation compatibility note.
624 fn enable(&mut self, selector: &str) -> Result<(), String>;
625 /// Mutation: disable a bundle.
626 fn disable(&mut self, selector: &str) -> Result<(), String>;
627 /// Mutation: revoke trust.
628 fn revoke_trust(&mut self, selector: &str) -> Result<(), String>;
629 /// Async-bridged install; returns a synchronous portable receipt (D11).
630 fn install(
631 &mut self,
632 source: &str,
633 expected_content_hash: Option<&str>,
634 ) -> Result<PluginMutationReceipt, String>;
635 /// Async-bridged update; returns a synchronous portable receipt (D11).
636 fn update(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
637 /// Async-bridged uninstall; returns a synchronous portable receipt (D11).
638 fn uninstall(&mut self, selector: &str) -> Result<PluginMutationReceipt, String>;
639 /// File-level removal of a just-installed bundle whose content hash
640 /// mismatched (rollback). Unlike [`Self::uninstall`] it does not resolve a
641 /// registry selector and triggers no rediscovery or skill-cache side
642 /// effects; the host adapter owns the `crate::plugins` call (D1).
643 fn uninstall_path(&mut self, name: &str, plugins_dir: &Path) -> Result<(), String>;
644 /// Read-only: export a loaded bundle to a target directory.
645 fn export(&self, selector: &str, target: &Path) -> Result<PluginExportReceipt, String>;
646 /// Read-only: scan legacy executable plugin tools.
647 fn legacy_scan(&self) -> Result<Option<PluginLegacyScan>, String>;
648 /// Read-only: Kimi managed-plugin directory scan.
649 fn managed_scan(&self, home_override: Option<&Path>) -> Result<PluginManagedScan, String>;
650 /// Mutation: install a Kimi managed candidate by exact content hash.
651 fn managed_install(
652 &mut self,
653 canonical_path: &Path,
654 expected_content_hash: &str,
655 ) -> Result<PluginMutationReceipt, String>;
656 /// Read-only: marketplace state (optional host catalog + stored catalogs).
657 fn marketplace_state(&self) -> Result<PluginMarketplaceState, String>;
658 /// Mutation: add a local catalog document to the marketplace store.
659 fn marketplace_add(
660 &mut self,
661 name: &str,
662 path: &Path,
663 ) -> Result<PluginMarketplaceAddReceipt, String>;
664 /// Mutation: remove a stored marketplace catalog.
665 fn marketplace_remove(&mut self, name: &str) -> Result<bool, String>;
666 /// Mutation: install a marketplace candidate through the reviewed installer.
667 fn marketplace_install(
668 &mut self,
669 catalog: &str,
670 candidate: &str,
671 ) -> Result<PluginMutationReceipt, String>;
672}
673
674// ---------------------------------------------------------------------------
675// Skill group (FEAT-022 D1)
676// ---------------------------------------------------------------------------
677
678/// Source provenance of a discovered skill (native file vs reviewed plugin snapshot).
679#[derive(Debug, Clone, PartialEq, Eq)]
680pub enum SkillSourceKind {
681 Native,
682 Plugin {
683 plugin_name: String,
684 plugin_id: String,
685 },
686}
687
688/// Curated product tier for bundled (shipped) skills.
689///
690/// The canonical name→tier classification stays in the TUI host
691/// (`crate::skills::system::bundled_skill_tier`); the portable projection
692/// carries the resolved tier so the handler can render the curated listing
693/// without duplicating the canonical bundle list.
694#[derive(Debug, Clone, Copy, PartialEq, Eq)]
695pub enum SkillBundledTier {
696 CoreAgentic,
697 FormatTooling,
698}
699
700impl SkillBundledTier {
701 /// Product-facing tier heading used by the `/skills` listing.
702 #[must_use]
703 pub fn heading(self) -> &'static str {
704 match self {
705 Self::CoreAgentic => "Core agentic",
706 Self::FormatTooling => "Format & tooling",
707 }
708 }
709}
710
711/// One discovered skill entry (portable).
712///
713/// The body is intentionally excluded: activation and review receive body
714/// text through their own delegates (`SkillActivationOutcome`/`ReviewOutcome`);
715/// listing and inspect render name, description, source, and path only (D1
716/// exact-minimum).
717#[derive(Debug, Clone, PartialEq, Eq)]
718pub struct SkillEntry {
719 pub name: String,
720 pub description: String,
721 pub source: SkillSourceKind,
722 /// Native skills carry their on-disk path (inspect output).
723 pub path: Option<String>,
724 /// Bundled catalog tier; `None` for user/compatible skills.
725 pub bundled_tier: Option<SkillBundledTier>,
726}
727
728/// Portable projection of the host skill registry (discovery, D1).
729///
730/// Carries every value the `/skills` and `/skill` handlers render: workspace
731/// and configured skills dir displays, discovery mode label, searched
732/// directories, entries, warnings, and the enabled-skill total.
733#[derive(Debug, Clone, PartialEq, Eq)]
734pub struct SkillRegistryProjection {
735 pub workspace: String,
736 pub skills_dir: String,
737 pub mode_label: String,
738 pub dirs: Vec<String>,
739 pub entries: Vec<SkillEntry>,
740 pub warnings: Vec<String>,
741 pub total: usize,
742}
743
744/// Target scope for skill mutations (`/skill install|update|uninstall|trust`).
745#[derive(Debug, Clone, Copy, PartialEq, Eq)]
746pub enum SkillTargetScope {
747 Project,
748 Global,
749}
750
751/// Portable mutation outcome mirroring the host receipt variants.
752#[derive(Debug, Clone, PartialEq, Eq)]
753pub enum SkillMutationOutcome {
754 Installed,
755 Updated,
756 NoChange,
757 Removed,
758 Trusted,
759 Imported,
760 AlreadyPresent,
761 NeedsApproval(String),
762 NetworkDenied(String),
763}
764
765/// Synchronous portable receipt for a skill mutation (FEAT-020 D11 mirror):
766/// the host owns the async network bridge; the handler renders the receipt
767/// byte-identically from these values.
768#[derive(Debug, Clone, PartialEq, Eq)]
769pub struct SkillMutationReceipt {
770 pub name: String,
771 pub safe_target_path: String,
772 pub outcome: SkillMutationOutcome,
773}
774
775/// One curated remote registry entry (`/skills --remote`).
776#[derive(Debug, Clone, PartialEq, Eq)]
777pub struct RemoteSkillEntry {
778 pub name: String,
779 pub description: Option<String>,
780 pub source: String,
781}
782
783/// Remote registry fetch outcome (`/skills --remote`, suggest source).
784#[derive(Debug, Clone, PartialEq, Eq)]
785pub enum RemoteRegistryOutcome {
786 Loaded { entries: Vec<RemoteSkillEntry> },
787 NeedsApproval(String),
788 Denied(String),
789}
790
791/// Remote recommendation for `/skills suggest <task>`.
792#[derive(Debug, Clone, PartialEq, Eq)]
793pub struct SkillRecommendation {
794 pub name: String,
795 pub description: Option<String>,
796 pub matched_terms: Vec<String>,
797}
798
799/// Per-skill outcome of `/skills sync`.
800#[derive(Debug, Clone, PartialEq, Eq)]
801pub enum SkillSyncEntry {
802 Downloaded { name: String, path: String },
803 Fresh { name: String },
804 Failed { name: String, reason: String },
805 Denied { name: String, host: String },
806 NeedsApproval { name: String, host: String },
807}
808
809/// Aggregate `/skills sync` outcome.
810///
811/// Registry-level network-policy outcomes are carried as variants so the
812/// portable handler composes the exact `needs_approval` / `denied` messages.
813#[derive(Debug, Clone, PartialEq, Eq)]
814pub enum SkillSyncOutcome {
815 Done {
816 total: usize,
817 downloaded: usize,
818 fresh: usize,
819 failed: usize,
820 entries: Vec<SkillSyncEntry>,
821 },
822 RegistryNeedsApproval(String),
823 RegistryDenied(String),
824}
825
826/// Successful skill activation data (host performs the side effects).
827#[derive(Debug, Clone, PartialEq, Eq)]
828pub struct SkillActivationOutcome {
829 pub name: String,
830 pub description: String,
831}
832
833/// Activation failures with the exact data the handler renders.
834#[derive(Debug, Clone, PartialEq, Eq)]
835pub enum SkillActivationError {
836 NotFound {
837 requested: String,
838 available: Vec<String>,
839 warnings: Vec<String>,
840 },
841 PluginRejected {
842 name: String,
843 reason: String,
844 },
845}
846
847/// `/review` outcome data (host performs the side effects).
848///
849/// On success the baseline `/review` renders no message — it only emits the
850/// `SendMessage` action — so `Ready` carries no payload (D1 exact-minimum).
851/// Warnings are only rendered on the not-found path.
852#[derive(Debug, Clone, PartialEq, Eq)]
853pub enum ReviewOutcome {
854 Ready,
855 NotFound {
856 skills_dir: String,
857 global_dir: String,
858 warnings: Vec<String>,
859 },
860}
861
862/// One snapshot entry for `/restore` listings.
863#[derive(Debug, Clone, PartialEq, Eq)]
864pub struct SnapshotEntry {
865 pub id: String,
866 pub label: String,
867 pub timestamp: i64,
868}
869
870/// Host approval posture for the `/restore` trust gate (D4: no MODE_POLICY).
871#[derive(Debug, Clone, Copy, PartialEq, Eq)]
872pub struct CommandApprovalState {
873 pub yolo: bool,
874 pub trust_mode: bool,
875}
876
877/// Host skill data for the skills command group (FEAT-022 D1).
878///
879/// Exposes the typed, exact-minimum operations the live skills handlers
880/// consume: discovery (`/skills`), activation (`/skill`), synchronous
881/// mutation receipts (`/skill install|update|uninstall|trust`), remote
882/// registry + sync (`/skills --remote|sync|suggest`), review (`/review`),
883/// and snapshot list/restore plus approval state (`/restore`). The host
884/// adapter is the only place that touches `App`, `crate::plugins`,
885/// `SnapshotRepo`, `crate::skills` services, config/network policy, and the
886/// async runtime bridge. The shared FEAT-015 `CommandSkillsContext` is never
887/// widened; active-skill reads use that facet, mutations flow through the
888/// delegates here (D2). All results are contract-owned portable values;
889/// implementation errors cross as safe text. `/skill` declares this facet
890/// plus `CommandSkillsContext` for the baseline cache-refresh policy;
891/// `/skills`, `/review`, and `/restore` declare exactly this facet.
892pub trait CommandSkillGroupContext {
893 /// `/skills` discovery projection (workspace, skills dir, scan mode,
894 /// searched directories, plugin-provided skills, warnings).
895 fn skill_registry_projection(&self) -> SkillRegistryProjection;
896 /// `/skill` activation: host lookup, plugin-authority verification, and
897 /// active-skill/history side effects. `SendMessage` task composition is
898 /// handler-side.
899 fn activate_skill(
900 &mut self,
901 name: &str,
902 ) -> Result<SkillActivationOutcome, SkillActivationError>;
903 /// `/skill install` — synchronous portable receipt; host owns network/async.
904 fn install_skill(
905 &mut self,
906 scope: Option<SkillTargetScope>,
907 spec: &str,
908 ) -> Result<SkillMutationReceipt, String>;
909 /// `/skill update` — synchronous portable receipt; host owns network/async.
910 fn update_skill(
911 &mut self,
912 scope: Option<SkillTargetScope>,
913 name: &str,
914 ) -> Result<SkillMutationReceipt, String>;
915 /// `/skill uninstall` — synchronous portable receipt.
916 fn uninstall_skill(
917 &mut self,
918 scope: Option<SkillTargetScope>,
919 name: &str,
920 ) -> Result<SkillMutationReceipt, String>;
921 /// `/skill trust` — synchronous portable receipt.
922 fn trust_skill(
923 &mut self,
924 scope: Option<SkillTargetScope>,
925 name: &str,
926 ) -> Result<SkillMutationReceipt, String>;
927 /// `/skills --remote` registry fetch (network policy host-side).
928 fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String>;
929 /// `/skills suggest <task>` — host fetch + recommendation computation.
930 fn recommend_skills(&mut self, task: &str) -> Result<Vec<SkillRecommendation>, String>;
931 /// `/skills sync` — host registry sync (async bridge host-side).
932 fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String>;
933 /// `/review` activation: host discovery + side effects (empty-target
934 /// validation and `SendMessage` composition are handler-side).
935 fn run_review(&mut self) -> Result<ReviewOutcome, String>;
936 /// `/restore` snapshot listing.
937 fn snapshot_list(&mut self, limit: usize) -> Result<Vec<SnapshotEntry>, String>;
938 /// `/restore <N>`: host restores by snapshot id; handler composes the
939 /// exact success message from its list entry.
940 fn restore_snapshot(&mut self, id: &str) -> Result<(), String>;
941 /// `/restore` trust gate posture (yolo / trust_mode).
942 fn approval_state(&self) -> CommandApprovalState;
943}
944
945// ---------------------------------------------------------------------------
946// Session lifecycle capability (FEAT-023).
947//
948// One contract-owned facet for the seven host-dependent lifecycle commands;
949// `/compact` and `/purge` stay pure. The shared `CommandSessionContext` above
950// stays unchanged: it
951// serves commands outside this slice and must not gain persistence,
952// navigation, picker, or lifecycle mutation authority (D2). No concrete App,
953// SessionManager, session-journal, picker, configuration, or view-stack type
954// crosses this boundary; successful results are structured portable fields so
955// the handlers retain exact message composition (D2/D5).
956// ---------------------------------------------------------------------------
957
958/// Portable synchronization fields a lifecycle handler maps into the
959/// temporary `SyncSession` action payload. The conversation and prompt types
960/// are `codewhale-core` request types shared by the contract and the TUI
961/// (FEAT-037 will move shared outcome ownership; FEAT-023 keeps the bounded
962/// reference only for `/fork` and `/new` transitions, D6).
963#[derive(Clone, Debug, PartialEq)]
964pub struct SessionSyncPayload {
965 pub session_id: Option<String>,
966 pub messages: Vec<Message>,
967 pub system_prompt: Option<SystemPrompt>,
968 pub model: String,
969 pub workspace: PathBuf,
970 pub mode: CommandMode,
971}
972
973/// `/branch` success projection (`session/branch.rs`). The handler composes
974/// the exact success line from these deterministic fields.
975#[derive(Clone, Debug, PartialEq)]
976pub struct SessionBranchOutcome {
977 pub leaf_display: String,
978 pub journal_entries_before: usize,
979}
980
981/// `/fork` success projection for an active-conversation fork. The handler
982/// composes `Forked session {parent} -> {fork}` from these required fields.
983#[derive(Clone, Debug, PartialEq)]
984pub struct SessionForkReceipt {
985 pub parent_label: String,
986 pub fork_label: String,
987 pub sync: SessionSyncPayload,
988}
989
990/// `/fork <session_id|prefix>` success projection. Explicit-source forks
991/// always report their spawn depth, so the contract makes that field required
992/// rather than permitting an invalid missing-depth state.
993#[derive(Clone, Debug, PartialEq)]
994pub struct SessionForkFromReceipt {
995 pub parent_label: String,
996 pub fork_label: String,
997 pub spawn_depth: u64,
998 pub sync: SessionSyncPayload,
999}
1000
1001/// `/save` success projection. The host performs the full baseline sequence
1002/// (snapshot, serialization, atomic write, metadata application, work-state
1003/// publication); the handler renders `Session saved to {display_path} (ID:
1004/// {truncated_id})`.
1005#[derive(Clone, Debug, PartialEq)]
1006pub struct SessionSaveReceipt {
1007 pub display_path: String,
1008 pub truncated_id: String,
1009}
1010
1011/// `/new` success projection. The handler renders
1012/// `Started new session {truncated_id} (New Session). Previous sessions
1013/// remain available via /resume.`
1014#[derive(Clone, Debug, PartialEq)]
1015pub struct SessionNewReceipt {
1016 pub truncated_id: String,
1017 pub sync: SessionSyncPayload,
1018}
1019
1020/// `/sessions archive|unarchive|restore` success projection. The handler
1021/// renders `Archived session {id} ({title})` or `Restored session ...` from
1022/// the verb it dispatched.
1023#[derive(Clone, Debug, PartialEq)]
1024pub struct SessionArchiveReceipt {
1025 pub truncated_id: String,
1026 pub title: String,
1027}
1028
1029/// `/tree` body projection. The body rendering source (journal tree and
1030/// linear transcript) stays TUI-owned; the handler appends the exact
1031/// guidance lines (D5).
1032#[derive(Clone, Debug, PartialEq)]
1033pub enum TreeBodyProjection {
1034 /// Journal render already includes the trailing newline before guidance.
1035 Journal {
1036 rendered: String,
1037 },
1038 /// Linear pre-journal render (the marker lines).
1039 Linear {
1040 rendered: String,
1041 },
1042 EmptySession,
1043 NoSession,
1044}
1045
1046/// Lifecycle authority for the session command slice (FEAT-023 D2).
1047///
1048/// Operation-granular synchronous delegates over the exact minimum host work
1049/// the nine commands consume. Delegates may return the explicit host-error
1050/// text the baseline surfaces for a failing stage; successful results are
1051/// structured portable fields so handlers retain byte-identical composition.
1052pub trait CommandSessionLifecycleContext {
1053 /// Live transition gate. Handlers return their own blocked-error text
1054 /// before invoking any mutating delegate, matching the baseline ordering
1055 /// (`/branch`, `/fork`, `/load`, `/new`). `/fork picker` and `/tree`
1056 /// never consult it in the baseline, so their paths must not either.
1057 fn transition_blocked(&self) -> bool;
1058
1059 /// `/branch` with no argument: the current leaf when an active journaled
1060 /// session resolves, otherwise `None` (the baseline silently falls back
1061 /// to the usage message on this path).
1062 fn branch_current_leaf_hint(&self) -> Option<String>;
1063
1064 /// `/branch <entry_id>`: persist the leaf move and apply the branched
1065 /// transcript. Errors are the exact baseline message for the failing
1066 /// stage (no active session, directory open, load, persist, or branch
1067 /// failure).
1068 fn branch_to(&mut self, entry_id: &str) -> Result<SessionBranchOutcome, String>;
1069
1070 /// `/tree`: produce the journal/linear/empty/no-session projection.
1071 /// Errors are the exact baseline directory-open message.
1072 fn tree_body(&self) -> Result<TreeBodyProjection, String>;
1073
1074 /// `/save [path]`: the full baseline persistence sequence.
1075 fn save_session(&mut self, explicit_path: Option<String>)
1076 -> Result<SessionSaveReceipt, String>;
1077
1078 /// `/fork` (active conversation): the full baseline parent/child save and
1079 /// switch sequence.
1080 fn fork_active(&mut self) -> Result<SessionForkReceipt, String>;
1081
1082 /// `/fork <session_id|prefix>`: explicit-source fork.
1083 fn fork_from(&mut self, session_id_or_prefix: &str) -> Result<SessionForkFromReceipt, String>;
1084
1085 /// `/new [--force]`: fresh-session transition. The caller has already
1086 /// parsed the argument and applied the transition-blocked gate; blocker,
1087 /// busy-work-state, and success handling match the baseline.
1088 fn fresh_session(&mut self, force: bool) -> Result<SessionNewReceipt, String>;
1089
1090 /// `/load <path>`: resolve the path (separator-bearing direct vs
1091 /// workspace-relative) and validate the saved-session shape without
1092 /// applying state or emitting a premature success receipt.
1093 fn load_session(&mut self, path: &str) -> Result<PathBuf, String>;
1094
1095 /// `/sessions` picker open with optional preselection (bare, `show`,
1096 /// `list`, `picker`, and `open <id>` forms). Picker construction and
1097 /// locale selection stay host-side.
1098 fn open_picker(&mut self, preselected: Option<String>);
1099
1100 /// `/sessions archive|unarchive|restore <id>`: durable lifecycle state
1101 /// update that also syncs the live cached metadata atomically.
1102 fn set_archived(
1103 &mut self,
1104 session_id: &str,
1105 archived: bool,
1106 ) -> Result<SessionArchiveReceipt, String>;
1107
1108 /// `/sessions prune <days>`: prune persisted sessions older than `days`
1109 /// days while protecting the active session; returns the number pruned.
1110 fn prune_sessions(&mut self, days: u64) -> Result<usize, String>;
1111}
1112
1113// ---------------------------------------------------------------------------
1114// FEAT-024: session control slice (D2-D7).
1115//
1116// One independently optional session-control authority covering exactly the
1117// host work the six control commands (`/relay`, `/rename`, `/resume`, `/rc`,
1118// `/remote-env`, `/title`) consume. `CommandSessionContext` and
1119// `CommandSessionLifecycleContext` are deliberately not widened: control
1120// authority exists only on this facet, and every delegate is an atomic host
1121// operation or a semantic projection so handlers keep byte-identical
1122// composition. Portable values never expose TUI state beyond what the
1123// baseline branches on.
1124// ---------------------------------------------------------------------------
1125
1126/// `/relay` semantic snapshot (D4). The handler composes the byte-identical
1127/// instruction from these deterministic fields; `crate::prompts`,
1128/// `crate::todo_snapshot`, goal/todo/plan machinery, Work-state objects, and
1129/// locks stay host-side.
1130#[derive(Clone, Debug, PartialEq)]
1131pub struct RelayProjection {
1132 /// Authoritative compact-template text (`COMPACT_TEMPLATE`), echoed with
1133 /// a trailing trim by the handler exactly as today.
1134 pub compact_template: String,
1135 pub workspace: String,
1136 pub mode: String,
1137 pub model: String,
1138 pub goal_objective: Option<String>,
1139 pub goal_token_budget: Option<u32>,
1140 pub todos: TodoProjection,
1141 pub plan: PlanProjection,
1142}
1143
1144/// To-do state distinction for the relay snapshot. The rendered body (if any)
1145/// is produced host-side from the authoritative graph-backed snapshot seam.
1146#[derive(Clone, Debug, PartialEq)]
1147pub enum TodoProjection {
1148 /// Rendered to-do body lines.
1149 Body(String),
1150 /// Work state could not be read (`To-do: unavailable because the list is
1151 /// busy.`).
1152 Unavailable,
1153 /// No Work state or no to-do body.
1154 Absent,
1155}
1156
1157/// Plan-state distinction for the relay snapshot. `Busy` reproduces the
1158/// baseline `try_lock` failure branch; `Absent` reproduces an empty snapshot.
1159///
1160/// `PlanSections` is intentionally not boxed: the command-crate boundary gate
1161/// forbids boxed storage in the contract, and the section payload is only ever
1162/// built once per `/relay` dispatch.
1163#[derive(Clone, Debug, PartialEq)]
1164#[allow(clippy::large_enum_variant)]
1165pub enum PlanProjection {
1166 Sections(PlanSections),
1167 Busy,
1168 Absent,
1169}
1170
1171/// Semantic plan snapshot fields consumed by `/relay`. Values are the raw
1172/// snapshot values; the handler applies the baseline trim/empty filtering and
1173/// label composition so ordering and spacing stay byte-identical.
1174#[derive(Clone, Debug, Default, PartialEq)]
1175pub struct PlanSections {
1176 pub title: Option<String>,
1177 pub objective: Option<String>,
1178 pub context_summary: Option<String>,
1179 pub explanation: Option<String>,
1180 pub sources_used: Vec<String>,
1181 pub critical_files: Vec<String>,
1182 pub constraints: Vec<String>,
1183 pub recommended_approach: Option<String>,
1184 pub verification_plan: Option<String>,
1185 pub risks_and_unknowns: Option<String>,
1186 pub handoff_packet: Option<String>,
1187 pub items: Vec<PlanStep>,
1188}
1189
1190/// Portable plan-step status. The adapter maps the TUI plan status onto this
1191/// semantic enum; the command handler remains the sole owner of the exact
1192/// `pending`/`in_progress`/`completed` labels.
1193#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1194pub enum PlanStepStatus {
1195 Pending,
1196 InProgress,
1197 Completed,
1198}
1199
1200/// One semantic plan checklist item.
1201#[derive(Clone, Debug, PartialEq, Eq)]
1202pub struct PlanStep {
1203 pub status: PlanStepStatus,
1204 pub text: String,
1205}
1206
1207/// `/resume` route resolution (D6). The host resolves argument shape and
1208/// performs container imports atomically; the handler selects the exact
1209/// baseline message/action per variant.
1210#[derive(Clone, Debug, PartialEq)]
1211pub enum ResumeSource {
1212 /// Argument resolves to a readable file (`raw` direct path or
1213 /// workspace-relative path); the handler calls `import_session_file`.
1214 File(PathBuf),
1215 /// Argument resolved through the session manager (id or prefix).
1216 Session {
1217 /// Durable session file when present; `None` reproduces the baseline
1218 /// non-file fallback message arm.
1219 load_path: Option<PathBuf>,
1220 truncated_id: String,
1221 title: String,
1222 },
1223 /// Argument parsed as a foreign session container, which was imported
1224 /// atomically by the resolver.
1225 Imported(ResumeImportReceipt),
1226 /// Argument matched neither a file, a session, nor a container.
1227 NotFound { raw: String, error: String },
1228}
1229
1230/// Portable `/resume` import receipt. The handler renders
1231/// `Imported foreign session as {truncated_id} ({entry_count} entries, leaf
1232/// {leaf_display})`.
1233#[derive(Clone, Debug, PartialEq)]
1234pub struct ResumeImportReceipt {
1235 pub truncated_id: String,
1236 pub entry_count: usize,
1237 pub leaf_display: String,
1238}
1239
1240/// `/rename` success receipt; the title is the sanitized persisted value so
1241/// the handler echoes exactly what was written.
1242#[derive(Clone, Debug, PartialEq)]
1243pub struct SessionTitleReceipt {
1244 pub title: String,
1245}
1246
1247/// Bare `/title` status projection (`Window title: [{effective}]{source}`).
1248#[derive(Clone, Debug, PartialEq)]
1249pub struct TitleReport {
1250 /// Effective window-title prefix, or `unset`.
1251 pub effective: String,
1252 pub source: TitleSource,
1253}
1254
1255#[derive(Clone, Debug, PartialEq)]
1256pub enum TitleSource {
1257 /// Session-level window title set.
1258 Session,
1259 /// Config-default title applies.
1260 ConfigDefault,
1261 /// Neither a session title nor a config default.
1262 None,
1263}
1264
1265/// `/rc link` structured link data.
1266#[derive(Clone, Debug, PartialEq)]
1267pub struct RemoteLink {
1268 pub url: String,
1269 pub computer_url: Option<String>,
1270}
1271
1272/// `/rc open` outcome. Browser launch stays synchronous and single-attempt;
1273/// no deferred external-URL action is produced (D6).
1274#[derive(Clone, Debug, PartialEq)]
1275pub enum RemoteOpenOutcome {
1276 NoLink,
1277 Opened { url: String },
1278 LaunchFailed { url: String },
1279}
1280
1281/// `/rc start` wording input: the active-turn copy is used while a turn is
1282/// loading or a dispatch is in flight.
1283#[derive(Clone, Debug, PartialEq)]
1284pub struct RemoteStartInfo {
1285 pub connecting: bool,
1286}
1287
1288/// `/remote-env open` hosted-work target. The URL is fully encoded host-side
1289/// (the portable handler must not depend on `urlencoding`); repo/branch echo
1290/// the raw values used by the baseline message replacements.
1291#[derive(Clone, Debug, PartialEq)]
1292pub struct HostedWorkTarget {
1293 pub url: String,
1294 pub repo: String,
1295 pub branch: String,
1296}
1297
1298/// Control authority for the session command slice (FEAT-024 D2/D5).
1299///
1300/// Operation-granular synchronous delegates over the exact minimum host work
1301/// the six control commands consume. Delegates reproduce the baseline
1302/// check/mutation order (transition gate before resume I/O, save before
1303/// publication, single-attempt browser launch) and return portable receipts/
1304/// projections or the exact host-error text the baseline surfaces. No
1305/// `SessionManager`, saved-session/container type, `SessionPickerView`,
1306/// remote-control service, Git wrapper, configuration, model/history type,
1307/// lock, or host callback crosses the facet.
1308pub trait CommandSessionControlContext {
1309 /// Live transition gate consulted by `/resume` before any picker or I/O.
1310 fn transition_blocked(&self) -> bool;
1311
1312 /// `/relay`: authoritative semantic snapshot (workspace/mode/model/goal/
1313 /// to-do/plan/compact-template). Unavailable sources are represented as
1314 /// explicit states, never panics.
1315 fn relay_projection(&self) -> RelayProjection;
1316
1317 /// Bare `/resume`: push the existing picker without preselection.
1318 fn open_resume_picker(&mut self);
1319
1320 /// `/resume <raw>`: resolve direct-path, workspace-relative, session
1321 /// id/prefix, and inline-container routes in the established order; a
1322 /// recognized inline container is imported atomically here.
1323 fn resolve_resume_source(&mut self, raw: &str) -> Result<ResumeSource, String>;
1324
1325 /// `/resume <file>`: read, parse, persist, and apply a foreign session
1326 /// file (container or plain saved session). Errors are the exact baseline
1327 /// read/parse/import text.
1328 fn import_session_file(&mut self, path: PathBuf) -> Result<ResumeImportReceipt, String>;
1329
1330 /// Apply the authoritative session-title character policy before the
1331 /// portable `/rename` and `/title` handlers validate and compose output.
1332 fn sanitize_session_title(&self, raw_title: &str) -> String;
1333
1334 /// `/rename <title>`: recover first-snapshot state, sync live state,
1335 /// persist, and publish with baseline order. The handler already applied
1336 /// sanitization plus blank and 100-character validation.
1337 fn rename_session(&mut self, title: &str) -> Result<SessionTitleReceipt, String>;
1338
1339 /// Bare `/title`: effective prefix and its source.
1340 fn title_report(&self) -> TitleReport;
1341
1342 /// `/title <title>`: persist an already sanitized and validated window
1343 /// title with baseline save/publication/redraw semantics.
1344 fn set_window_title(&mut self, title: String) -> Result<(), String>;
1345
1346 /// `/title off|clear|none`: clear the session window title with the same
1347 /// baseline persistence/redraw semantics.
1348 fn clear_window_title(&mut self) -> Result<(), String>;
1349
1350 /// `/rc status`: current remote-control status line.
1351 fn remote_status(&self) -> String;
1352
1353 /// `/rc link`: live session link plus optional computer-management URL.
1354 fn remote_link(&self) -> Option<RemoteLink>;
1355
1356 /// `/rc open`: synchronous single browser attempt over the authoritative
1357 /// URL-opening helper; outcome carries the URL for exact message text.
1358 fn remote_browser_open(&self) -> RemoteOpenOutcome;
1359
1360 /// `/rc start`: whether the active-turn copy applies.
1361 fn remote_start_info(&self) -> RemoteStartInfo;
1362
1363 /// `/rc stop`: refusal reason while a remote turn/envelope is active.
1364 fn remote_stop_refusal(&self) -> Option<String>;
1365
1366 /// `/remote-env open`: validate the hosted-work Git target host-side and
1367 /// return the encoded URL plus raw repo/branch echoes; `None` reproduces
1368 /// the unavailable-target error. Credentials never appear in values or
1369 /// errors.
1370 fn resolve_hosted_work_target(&self) -> Option<HostedWorkTarget>;
1371}