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