返回 CodeWhale
contract.rs
根目录 / crates / tui / src / commands / contract.rs
1 //! FEAT-015 TUI command-boundary surface.
2 //!
3 //! This module holds the TUI-owned pieces of the staged command migration:
4 //! the pending-frontier projection (D4), the capability facet adapters
5 //! (D1), boundary-value and localization-key mappings (D3/D8), the envelope
6 //! construction helper (D1), and the seam helpers (D7-D9). It is deliberately
7 //! the only new TUI module for the migration surface; the production
8 //! registry/dispatch stay in `traits.rs` / `mod.rs`.
9 //!
10 //! FEAT-015 does NOT migrate any production command. The adapters below wrap
11 //! App-owned state behind the FEAT-014 contract shapes so later FEATs
12 //! (FEAT-018+) can adopt them one group at a time. Handlers only ever see
13 //! `&mut dyn` facets — concrete `App` is never exposed through an envelope.
14 //!
15 //! ## Authoritative host-proxy design (D1)
16 //!
17 //! `CommandContexts` has independently optional facet slots, all
18 //! constructed here. The diagnostics adapter joins the host bundle in FEAT-029. Important behavior (mode transitions, model
19 //! invalidation, cost accounting, skill refresh) is authoritative on `App`. The adapters therefore share a
20 //! synchronous TUI-owned host proxy. Each trait call borrows `App` only for the
21 //! duration of that call and delegates to the real operation; handlers still
22 //! receive only portable facets and can never name concrete TUI state.
23 //!
24 //! ## Dead-code note
25 //!
26 //! FEAT-015 intentionally wires no production contextual command. Some bridge
27 //! helpers remain production-dead until the first slice migrates (FEAT-018+),
28 //! so this transitional module keeps a bounded dead-code allow.
29
30 use crate::commands::groups::plugins::render::ReviewTextContext;
31 use std::cell::RefCell;
32 use std::path::{Path, PathBuf};
33 use std::rc::Rc;
34
35 mod composer;
36 mod config_main;
37 pub(crate) mod constitution;
38 mod core_navigation;
39 mod core_policy;
40 mod fleet_lane;
41 mod hooks;
42 mod model_reference;
43 mod model_setup;
44 mod workflow;
45 use core_navigation::{NavigationAdapter, VoiceInputAdapter};
46 use fleet_lane::{FleetAdapter, LaneAdapter};
47 pub(in crate::commands) mod config_policy;
48 #[cfg(test)]
49 mod config_policy_baseline;
50 use config_main::{ConfigAdapter, LoginAdapter, PetAdapter, TrustAdapter, WorkSurfaceAdapter};
51 use config_policy::{ConfigStatusAdapter, PermissionsAdapter};
52 mod debug_diagnostics;
53 pub(in crate::commands) mod debug_operations;
54 use debug_operations::DebugOperationsAdapter;
55 pub(in crate::commands) mod config_messages;
56 mod config_policy_messages;
57 #[cfg(test)]
58 pub(crate) use debug_diagnostics::CostComponents as DebugCostComponents;
59 use debug_diagnostics::DebugDiagnosticsAdapter;
60 #[cfg(test)]
61 pub(crate) use debug_diagnostics::warmup_key as project_debug_warmup_key;
62
63 use codewhale_command_contract::facets::{
64 CommandApprovalState, CommandCostContext, CommandMediaContext, CommandMemoryContext,
65 CommandModePolicyContext, CommandModelContext, CommandPluginContext,
66 CommandPresentationContext, CommandProjectContext, CommandSessionContext,
67 CommandSessionControlContext, CommandSessionLifecycleContext, CommandSkillGroupContext,
68 CommandSkillsContext, CommandSystemPromptContext, CommandWorkspaceContext, HostedWorkTarget,
69 MediaAttachmentReceipt, MemoryDelete, MemoryDeleteScope, MemoryExport, MemoryGetOutcome,
70 MemoryHit, MemoryImportOutcome, MemoryReindex, MemoryRememberTarget, MemoryRemembered,
71 MemoryStatus, PlanProjection, PlanSections, PlanStep, PlanStepStatus, PluginDetail,
72 PluginDiagnostic, PluginDiagnosticLevel, PluginEarlierReview, PluginExportReceipt,
73 PluginHostServiceDetail, PluginLegacyScan, PluginLegacyTool, PluginManagedCandidate,
74 PluginManagedScan, PluginMarketplaceAddReceipt, PluginMarketplaceCandidate,
75 PluginMarketplaceCatalog, PluginMarketplaceInstallPlan, PluginMarketplaceState,
76 PluginMcpServerDetail, PluginMcpTransport, PluginMutationOutcome, PluginMutationReceipt,
77 PluginSuggestion, PluginSummary, ProjectGoalState, ProjectGoalStatus, RelayProjection,
78 RemoteLink, RemoteOpenOutcome, RemoteRegistryOutcome, RemoteSkillEntry, RemoteStartInfo,
79 ResumeImportReceipt, ResumeSource, ReviewOutcome, SessionArchiveReceipt, SessionBranchOutcome,
80 SessionForkFromReceipt, SessionForkReceipt, SessionNewReceipt, SessionSaveReceipt,
81 SessionSyncPayload, SessionTitleReceipt, SkillActivationError, SkillActivationOutcome,
82 SkillBundledTier, SkillEntry, SkillMutationOutcome, SkillMutationReceipt, SkillRecommendation,
83 SkillRegistryProjection, SkillSourceKind, SkillSyncEntry, SkillSyncOutcome, SkillTargetScope,
84 SnapshotEntry, TitleReport, TitleSource, TodoProjection, TreeBodyProjection,
85 };
86 use codewhale_command_contract::facets::{
87 CommandSessionExportContext, ConversationExportProjection, ExportBlock, ExportMessage,
88 ExportMetadata, ExportTurnOutcome, HistoryEntry, RestorePointProjection, RestoreSnapshot,
89 ToolCallerProjection, TranscriptProjection, TurnHandoffProjection,
90 };
91 #[cfg(test)]
92 use codewhale_command_contract::handler::ContextParts;
93 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts};
94 use codewhale_command_contract::types::{
95 CommandApprovalMode, CommandCurrency, CommandMode, CommandProviderId,
96 };
97 use codewhale_config::AppMode;
98 use codewhale_core::request::{ContentBlock, Message, SystemPrompt};
99 use codewhale_execpolicy::ApprovalMode;
100
101 use crate::commands::groups::plugins::plugin_network_policy;
102
103 use crate::tui::app::App;
104 use crate::tui::history::HistoryCell;
105 use codewhale_config::pricing::CostCurrency;
106 use codewhale_dependencies::ExternalTool as _;
107 use codewhale_localization::{Locale, MessageId, tr};
108 use codewhale_net::network_policy::NetworkPolicy;
109
110 // ---------------------------------------------------------------------------
111 // Pending frontier projection (D4)
112 // ---------------------------------------------------------------------------
113
114 /// Sorted, unique frontier of command groups that still use concrete-`App`
115 /// handlers. This is the TUI-visible projection of the checked-in migration
116 /// topology (`scripts/command-migration-topology.json`); the CI gate performs
117 /// the authoritative bidirectional source scan against that artifact.
118 ///
119 /// Not referenced by production dispatch code — the fail-closed Python gate
120 /// (`scripts/check-command-migration-manifest.py`) reads this exact
121 /// declaration by source regex and the Rust frontier tests assert it.
122 #[cfg(test)]
123 pub(crate) const PENDING_GROUPS: &[&str] = &[];
124
125 // ---------------------------------------------------------------------------
126 // Boundary-value mappings (D8)
127 // ---------------------------------------------------------------------------
128
129 /// Map the TUI operating mode onto the portable command boundary value.
130 pub(crate) fn to_command_mode(mode: AppMode) -> CommandMode {
131 match mode {
132 AppMode::Agent => CommandMode::Agent,
133 AppMode::Plan => CommandMode::Plan,
134 }
135 }
136
137 pub(crate) fn from_command_mode(mode: CommandMode) -> AppMode {
138 match mode {
139 CommandMode::Agent => AppMode::Agent,
140 CommandMode::Plan => AppMode::Plan,
141 }
142 }
143
144 /// Map the TUI approval posture onto the portable command boundary value.
145 pub(crate) fn to_command_approval(mode: ApprovalMode) -> CommandApprovalMode {
146 match mode {
147 ApprovalMode::Auto => CommandApprovalMode::Auto,
148 ApprovalMode::Bypass => CommandApprovalMode::Bypass,
149 ApprovalMode::Suggest => CommandApprovalMode::Suggest,
150 ApprovalMode::AcceptEdits => CommandApprovalMode::AcceptEdits,
151 ApprovalMode::Never => CommandApprovalMode::Never,
152 }
153 }
154
155 /// Map the TUI cost-display currency onto the portable command boundary value.
156 pub(crate) fn to_command_currency(currency: CostCurrency) -> CommandCurrency {
157 match currency {
158 CostCurrency::Usd => CommandCurrency::Usd,
159 CostCurrency::Cny => CommandCurrency::Cny,
160 }
161 }
162
163 fn from_command_currency(currency: CommandCurrency) -> CostCurrency {
164 match currency {
165 CommandCurrency::Usd => CostCurrency::Usd,
166 CommandCurrency::Cny => CostCurrency::Cny,
167 }
168 }
169
170 /// Stable provider identity text at the command boundary.
171 ///
172 /// The TUI persists either the canonical `ProviderKind::as_str()` spelling or —
173 /// for named custom providers — the exact configured identity text. This
174 /// function never leaks URLs, credentials, or filesystem paths.
175 pub(crate) fn to_provider_id(identity: &str) -> CommandProviderId {
176 CommandProviderId(identity.to_string())
177 }
178
179 /// Bridge a portable metadata description key onto the TUI localization id.
180 ///
181 /// The key convention (D3) is mechanical: the contract key equals the
182 /// snake_case of the [`MessageId`] variant name. The match table is the
183 /// authoritative bridge; unknown keys fail deterministically.
184 pub(crate) fn key_to_message_id(key: &'static str) -> Option<MessageId> {
185 Some(match key {
186 "cmd_advisor_description" => MessageId::CmdAdvisorDescription,
187 "cmd_agent_description" => MessageId::CmdAgentDescription,
188 "cmd_anchor_description" => MessageId::CmdAnchorDescription,
189 "cmd_attach_description" => MessageId::CmdAttachDescription,
190 "cmd_auto_description" => MessageId::CmdAutoDescription,
191 "cmd_auth_description" => MessageId::CmdAuthDescription,
192 "cmd_automation_description" => MessageId::CmdAutomationDescription,
193 "cmd_balance_description" => MessageId::CmdBalanceDescription,
194 "cmd_branch_description" => MessageId::CmdBranchDescription,
195 "cmd_cache_description" => MessageId::CmdCacheDescription,
196 "cmd_change_description" => MessageId::CmdChangeDescription,
197 "cmd_copy_description" => MessageId::CmdCopyDescription,
198 "cmd_clear_description" => MessageId::CmdClearDescription,
199 "cmd_color_description" => MessageId::CmdColorDescription,
200 "cmd_compact_description" => MessageId::CmdCompactDescription,
201 "cmd_config_description" => MessageId::CmdConfigDescription,
202 "cmd_connect_description" => MessageId::ConnectionSetupTitle,
203 "cmd_disconnect_description" => MessageId::CmdDisconnectDescription,
204 "cmd_constitution_description" => MessageId::CmdConstitutionDescription,
205 "cmd_context_description" => MessageId::CmdContextDescription,
206 "cmd_cost_description" => MessageId::CmdCostDescription,
207 "cmd_dashboard_description" => MessageId::CmdDashboardDescription,
208 "cmd_diff_description" => MessageId::CmdDiffDescription,
209 "cmd_edit_description" => MessageId::CmdEditDescription,
210 "cmd_effort_description" => MessageId::CmdEffortDescription,
211 "cmd_exit_description" => MessageId::CmdExitDescription,
212 "cmd_export_description" => MessageId::CmdExportDescription,
213 "cmd_feedback_description" => MessageId::CmdFeedbackDescription,
214 "cmd_fleet_description" => MessageId::CmdFleetDescription,
215 "cmd_fork_description" => MessageId::CmdForkDescription,
216 "cmd_goal_description" => MessageId::CmdGoalDescription,
217 "cmd_help_description" => MessageId::CmdHelpDescription,
218 "cmd_hf_description" => MessageId::CmdHfDescription,
219 "cmd_home_description" => MessageId::CmdHomeDescription,
220 "cmd_overview_description" => MessageId::CmdOverviewDescription,
221 "cmd_hooks_description" => MessageId::CmdHooksDescription,
222 "cmd_import_claude_description" => MessageId::CmdImportClaudeDescription,
223 "cmd_hotbar_description" => MessageId::CmdHotbarDescription,
224 "cmd_init_description" => MessageId::CmdInitDescription,
225 "cmd_jobs_description" => MessageId::CmdJobsDescription,
226 "cmd_lane_description" => MessageId::CmdLaneDescription,
227 "cmd_links_description" => MessageId::CmdLinksDescription,
228 "cmd_load_description" => MessageId::CmdLoadDescription,
229 "cmd_login_description" => MessageId::CmdLoginDescription,
230 "cmd_logout_description" => MessageId::CmdLogoutDescription,
231 "cmd_lsp_description" => MessageId::CmdLspDescription,
232 "cmd_mcp_description" => MessageId::CmdMcpDescription,
233 "cmd_memory_description" => MessageId::CmdMemoryDescription,
234 "cmd_mode_description" => MessageId::CmdModeDescription,
235 "cmd_model_db_description" => MessageId::CmdModelDbDescription,
236 "cmd_router_description" => MessageId::CmdRouterDescription,
237 "cmd_model_description" => MessageId::CmdModelDescription,
238 "cmd_models_description" => MessageId::CmdModelsDescription,
239 "cmd_network_description" => MessageId::CmdNetworkDescription,
240 "cmd_new_description" => MessageId::CmdNewDescription,
241 "cmd_note_description" => MessageId::CmdNoteDescription,
242 "cmd_permissions_description" => MessageId::CmdPermissionsDescription,
243 "cmd_pet_description" => MessageId::CmdPetDescription,
244 "cmd_pin_description" => MessageId::CmdPinDescription,
245 "cmd_plugin_description" => MessageId::CmdPluginDescription,
246 "cmd_plugin_detail_description" => MessageId::CmdPluginDetailDescription,
247 "cmd_preview_request_description" => MessageId::CmdPreviewRequestDescription,
248 "cmd_profile_description" => MessageId::CmdProfileDescription,
249 "cmd_provider_description" => MessageId::CmdProviderDescription,
250 "cmd_purge_description" => MessageId::CmdPurgeDescription,
251 "cmd_queue_description" => MessageId::CmdQueueDescription,
252 "cmd_relay_description" => MessageId::CmdRelayDescription,
253 "cmd_remote_control_description" => MessageId::CmdRemoteControlDescription,
254 "cmd_remote_env_description" => MessageId::CmdRemoteEnvDescription,
255 "cmd_rename_description" => MessageId::CmdRenameDescription,
256 "cmd_restore_description" => MessageId::CmdRestoreDescription,
257 "cmd_resume_description" => MessageId::CmdResumeDescription,
258 "cmd_receipts_description" => MessageId::CmdReceiptsDescription,
259 "cmd_retry_description" => MessageId::CmdRetryDescription,
260 "cmd_review_description" => MessageId::CmdReviewDescription,
261 "cmd_rlm_description" => MessageId::CmdRlmDescription,
262 "cmd_save_description" => MessageId::CmdSaveDescription,
263 "cmd_sessions_description" => MessageId::CmdSessionsDescription,
264 "cmd_settings_description" => MessageId::CmdSettingsDescription,
265 "cmd_setup_description" => MessageId::CmdSetupDescription,
266 "cmd_share_description" => MessageId::CmdShareDescription,
267 "cmd_sidebar_description" => MessageId::CmdSidebarDescription,
268 "cmd_skill_description" => MessageId::CmdSkillDescription,
269 "cmd_skills_description" => MessageId::CmdSkillsDescription,
270 "cmd_stash_description" => MessageId::CmdStashDescription,
271 "cmd_status_description" => MessageId::CmdStatusDescription,
272 "cmd_statusline_description" => MessageId::CmdStatuslineDescription,
273 "cmd_structcopy_description" => MessageId::CmdStructcopyDescription,
274 "cmd_agent_profiles_description" => MessageId::CmdAgentProfilesDescription,
275 "cmd_subagents_description" => MessageId::CmdSubagentsDescription,
276 "cmd_system_description" => MessageId::CmdSystemDescription,
277 "cmd_task_description" => MessageId::CmdTaskDescription,
278 "cmd_theme_description" => MessageId::CmdThemeDescription,
279 "cmd_title_description" => MessageId::CmdTitleDescription,
280 "cmd_tokens_description" => MessageId::CmdTokensDescription,
281 "cmd_tools_description" => MessageId::CmdToolsDescription,
282 "cmd_translate_description" => MessageId::CmdTranslateDescription,
283 "cmd_tree_description" => MessageId::CmdTreeDescription,
284 "cmd_trust_description" => MessageId::CmdTrustDescription,
285 "cmd_turn_inspect_description" => MessageId::CmdTurnInspectDescription,
286 "kb_live_transcript" => MessageId::KbLiveTranscript,
287 "cmd_undo_description" => MessageId::CmdUndoDescription,
288 "cmd_update_description" => MessageId::CmdUpdateDescription,
289 "cmd_verbose_description" => MessageId::CmdVerboseDescription,
290 "cmd_voice_control_description" => MessageId::CmdVoiceControlDescription,
291 "cmd_voice_description" => MessageId::CmdVoiceDescription,
292 "cmd_voice_send_description" => MessageId::CmdVoiceSendDescription,
293 "cmd_workflow_description" => MessageId::CmdWorkflowDescription,
294 "cmd_workflows_description" => MessageId::CmdWorkflowsDescription,
295 "cmd_view_plan_description" => MessageId::CmdViewPlanDescription,
296 "cmd_worktree_description" => MessageId::CmdWorktreeDescription,
297 "cmd_workspace_description" => MessageId::CmdWorkspaceDescription,
298 _ => return None,
299 })
300 }
301
302 // ---------------------------------------------------------------------------
303 // Capability facet adapters (D1)
304 // ---------------------------------------------------------------------------
305
306 /// Shared TUI host hidden behind the portable command facets.
307 ///
308 /// The envelope has twenty-two optional facet slots; authoritative mutation methods live on `App`. Each adapter therefore owns
309 /// an `Rc` clone of this synchronous host proxy. Trait calls borrow `App` only
310 /// for the duration of one method, delegate to the real TUI authority, and
311 /// return owned values. Command handlers never receive or name `App`.
312 struct CommandHost<'a> {
313 app: RefCell<&'a mut App>,
314 config: Option<&'a codewhale_runtime::config::Config>,
315 }
316
317 type SharedCommandHost<'a> = Rc<CommandHost<'a>>;
318
319 #[path = "session_structcopy_host.rs"]
320 pub(in crate::commands) mod structcopy_host;
321 use structcopy_host::SessionStructcopyAdapter;
322
323 // ---------------------------------------------------------------------------
324 // Session lifecycle adapter (FEAT-023 D4)
325 //
326 // Sole host owner of concrete lifecycle machinery for the nine lifecycle
327 // commands: App reads/mutations, SessionManager, saved-session creation,
328 // journal load/branching, filesystem persistence, work-state snapshots/
329 // publication, picker/view-stack construction, archive/prune, and the core
330 // `reset_conversation_state` call for `/new`. Every delegate reproduces the
331 // baseline check/mutation order exactly (blocked transitions fail before I/O,
332 // branching never rewrites journal history, publication failures retain their
333 // post-save semantics, archive state updates atomically) and returns portable
334 // receipts or the exact host-error text the baseline surfaces. The lifecycle
335 // bodies no longer live in `groups/session/session.rs`; adapter regressions and
336 // portable-handler tests preserve their host and presentation contracts.
337 // ---------------------------------------------------------------------------
338 pub(crate) struct SessionLifecycleAdapter<'a> {
339 host: SharedCommandHost<'a>,
340 }
341
342 impl CommandSessionLifecycleContext for SessionLifecycleAdapter<'_> {
343 fn transition_blocked(&self) -> bool {
344 self.host.app.borrow().session_transition_blocked()
345 }
346
347 fn transition_blockers(&self) -> Vec<String> {
348 self.host.app.borrow().session_transition_blockers()
349 }
350
351 fn branch_current_leaf_hint(&self) -> Option<String> {
352 let session_id = self.host.app.borrow().current_session_id.clone()?;
353 run_owner_blocking(move || {
354 let Ok(manager) = codewhale_engine::session_manager::SessionManager::default_location()
355 else {
356 return Ok(None);
357 };
358 let Ok(mut session) = manager.load_session(&session_id) else {
359 return Ok(None);
360 };
361 session.ensure_journal();
362 Ok(session
363 .journal
364 .as_ref()
365 .and_then(|journal| journal.leaf_id.clone()))
366 })
367 .ok()
368 .flatten()
369 }
370
371 fn branch_to(&mut self, entry_id: &str) -> Result<SessionBranchOutcome, String> {
372 let mut app = self.host.app.borrow_mut();
373 let session_id = match app.current_session_id.clone() {
374 Some(id) => id,
375 None => {
376 return Err(
377 "No active session to branch. Resume or create a session first.".to_string(),
378 );
379 }
380 };
381 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
382 Ok(m) => m,
383 Err(e) => return Err(format!("could not open sessions directory: {e}")),
384 };
385 crate::tui::persistence_actor::flush_before_transition()?;
386 let source = app
387 .session_write_receipt
388 .as_ref()
389 .ok_or_else(|| {
390 "Session source was not admitted; reopen its managed record before branching"
391 .to_string()
392 })?
393 .capture(codewhale_engine::session_manager::SessionWriteOwner::control())
394 .map_err(|error| error.to_string())?;
395 let load_id = session_id.clone();
396 let entry_id = entry_id.to_string();
397 let (mut session, publication, journal_len_before) = run_owner_blocking(move || {
398 let mut session = match manager.load_session(&load_id) {
399 Ok(s) => s,
400 Err(e) => return Err(format!("could not load session {load_id}: {e}")),
401 };
402 session.write_receipt = Some(source);
403 session.ensure_journal();
404 let journal_len_before = session
405 .journal
406 .as_ref()
407 .map(|j| j.entries.len())
408 .unwrap_or(0);
409 if let Err(e) = manager.restore_archived_journal_chain(&mut session, &entry_id) {
410 return Err(format!(
411 "branch failed: could not restore {entry_id} from the session's journal archive: {e}"
412 ));
413 }
414 match session.journal_branch_to(&entry_id) {
415 Ok(()) => {}
416 Err(e) => {
417 return Err(format!(
418 "branch failed: {e}. Use `/tree` to see valid entry ids."
419 ));
420 }
421 }
422 let publication = manager.publish_session(&session).map_err(|error| {
423 format!("branch could not be persisted; active conversation unchanged: {error}")
424 })?;
425 Ok((session, publication, journal_len_before))
426 })?;
427 session.adopt_publication(&publication);
428 app.restore_api_messages(session.messages.clone(), &session);
429 let leaf_display = session
430 .leaf_id
431 .clone()
432 .unwrap_or_else(|| "(none)".to_string());
433 app.clear_history();
434 app.session_turn_outcomes = session.turn_outcomes.clone();
435 app.delegated_writes = session
436 .delegated_writes
437 .iter()
438 .map(|(seq, paths)| ((session_id.clone(), *seq), paths.iter().cloned().collect()))
439 .collect();
440 app.session_artifacts = session.artifacts.clone();
441 app.session_context_references = session.context_references.clone();
442 app.extend_history(session.messages.iter().flat_map(|message| {
443 crate::tui::history::history_cells_from_message_with_results(message, &session.messages)
444 }));
445 app.scroll_to_bottom();
446 Ok(SessionBranchOutcome {
447 leaf_display,
448 journal_entries_before: journal_len_before,
449 sync: SessionSyncPayload {
450 session_id: Some(session_id),
451 messages: session.messages,
452 system_prompt: app.system_prompt.clone(),
453 model: app.model.clone(),
454 workspace: app.workspace.clone(),
455 mode: to_command_mode(app.mode),
456 agent_preset: app.agent_preset(),
457 },
458 })
459 }
460
461 fn tree_body(&self) -> Result<TreeBodyProjection, String> {
462 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
463 Ok(m) => m,
464 Err(e) => return Err(format!("could not open sessions directory: {e}")),
465 };
466 let session_id = self.host.app.borrow().current_session_id.clone();
467 let journal = match session_id {
468 Some(session_id) => run_owner_blocking(move || {
469 let Ok(mut session) = manager.load_session(&session_id) else {
470 return Ok(None);
471 };
472 session.ensure_journal();
473 let Some(journal) = session.journal.as_ref() else {
474 return Ok(None);
475 };
476 let mut rendered = codewhale_runtime::session_tree::render_tree(journal);
477 match manager.journal_archive_summary(&session_id) {
478 Ok(Some(summary)) if summary.unique_entries > 0 => {
479 let size = if summary.total_bytes >= 1_048_576 {
480 format!("{:.1} MiB", summary.total_bytes as f64 / 1_048_576.0)
481 } else if summary.total_bytes >= 1_024 {
482 format!("{:.1} KiB", summary.total_bytes as f64 / 1_024.0)
483 } else {
484 format!("{} B", summary.total_bytes)
485 };
486 rendered.push_str(&format!(
487 "{} archived entries are stored in {}/ ({size}, {} segment(s), not drawn); `/branch <id>` restores one.\n",
488 summary.unique_entries,
489 codewhale_engine::session_manager::JOURNAL_ARCHIVE_DIR,
490 summary.segment_count,
491 ));
492 }
493 Ok(_) => {}
494 Err(e) => {
495 rendered.push_str(&format!("journal archive could not be read: {e}\n"));
496 }
497 }
498 Ok(Some(TreeBodyProjection::Journal { rendered }))
499 })?,
500 None => return Ok(TreeBodyProjection::NoSession),
501 };
502 if let Some(journal) = journal {
503 return Ok(journal);
504 }
505 let app = self.host.app.borrow();
506 if app.api_messages.is_empty() {
507 return Ok(TreeBodyProjection::EmptySession);
508 }
509 let mut rendered =
510 String::from("Active branch (linear — journal will be created on save):\n");
511 for (i, msg) in app.api_messages.iter().enumerate() {
512 let meta_index = codewhale_models::turn_classify::turn_metadata_text(msg)
513 .filter(|_| msg.role == codewhale_models::Role::User)
514 .map(|(index, _)| index);
515 let snippet: String = msg
516 .content
517 .iter()
518 .enumerate()
519 .filter_map(|(index, b)| match b {
520 codewhale_models::ContentBlock::Text { text, .. }
521 if Some(index) != meta_index =>
522 {
523 Some(text.as_str())
524 }
525 _ => None,
526 })
527 .collect::<Vec<_>>()
528 .join(" ");
529 let short: String = snippet.chars().take(60).collect();
530 let marker = if i + 1 == app.api_messages.len() {
531 "*"
532 } else {
533 "●"
534 };
535 rendered.push_str(&format!(" {marker} [{i}] {}: {short}\n", msg.role));
536 }
537 Ok(TreeBodyProjection::Linear { rendered })
538 }
539
540 fn save_session(
541 &mut self,
542 explicit_path: Option<String>,
543 ) -> Result<SessionSaveReceipt, String> {
544 let mut app = self.host.app.borrow_mut();
545 let explicit_save_path = explicit_path.map(|path| {
546 app.workspace
547 .join(crate::commands::config_main_host::expand_tilde(&path))
548 });
549
550 // Explicit save must report contended Work state instead of falling
551 // back to the last automatic snapshot. Reuse the canonical snapshot
552 // builder after that preflight so stable IDs also retain lifecycle,
553 // title, provider, and window metadata.
554 app.work_state_snapshot()
555 .map_err(|error| format!("Failed to snapshot Work state: {error}"))?;
556 let manager = codewhale_engine::session_manager::SessionManager::default_location()
557 .map_err(|error| format!("could not open sessions directory: {error}"))?;
558 crate::tui::persistence_actor::flush_before_transition()?;
559 let control_owner = codewhale_engine::session_manager::SessionWriteOwner::control();
560 let control_source = app.session_write_receipt.clone();
561 let mut session = crate::tui::ui::build_session_snapshot(&mut app, &manager)?;
562 let work_owner = app.current_session_id.clone();
563 // Snapshots are journal-only (#6214 T3); exports need the legacy
564 // `messages` projection too.
565 session.make_storage_compatible();
566 let queue_transition =
567 crate::tui::ui::prepare_offline_queue_transition(&app, &session.metadata.id)?;
568 // C01-09: an explicit path may replace a saved session (a re-save),
569 // never an arbitrary file. Whatever exists there must read as one.
570 let inspect_path = explicit_save_path.clone();
571 let in_place = explicit_save_path.is_none();
572 let save_path = explicit_save_path.unwrap_or_else(|| {
573 let dir = codewhale_engine::session_manager::default_sessions_dir()
574 .unwrap_or_else(|_| app.workspace.clone());
575 dir.join(format!("{}.json", session.metadata.id))
576 });
577
578 let sessions_dir = save_path
579 .parent()
580 .filter(|p| !p.as_os_str().is_empty())
581 .map_or_else(|| app.workspace.clone(), std::path::Path::to_path_buf);
582 let display_path = save_path.display().to_string();
583
584 let (mut session, publication) = run_owner_blocking(move || {
585 if let Some(path) = inspect_path.as_deref() {
586 match path.symlink_metadata() {
587 Ok(_) => {
588 if let Err(error) =
589 codewhale_engine::session_manager::SessionManager::load_session_metadata(
590 path,
591 )
592 {
593 return Err(format!(
594 "Refusing to overwrite {}: the existing session could not be inspected ({error}). Choose a new path, or move that file first.",
595 path.display()
596 ));
597 }
598 }
599 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
600 Err(error) => {
601 return Err(format!("Could not inspect {}: {error}", path.display()));
602 }
603 }
604 }
605 std::fs::create_dir_all(&sessions_dir)
606 .map_err(|e| format!("Failed to create directory: {e}"))?;
607 let managed = in_place || manager.owns_session_path(&session.metadata.id, &save_path);
608 if managed {
609 let mut session = session;
610 if let Some(source) = control_source {
611 session.write_receipt = Some(
612 source
613 .capture(control_owner)
614 .map_err(|error| error.to_string())?,
615 );
616 } else {
617 session
618 .capture_publication(control_owner)
619 .map_err(|error| error.to_string())?;
620 }
621 let publication = manager
622 .publish_session_bounded(session.clone())
623 .map_err(|e| format!("Failed to save session: {e}"))?;
624 Ok((session, Some(publication)))
625 } else {
626 let json = serde_json::to_string_pretty(&session)
627 .map_err(|error| format!("Failed to serialize session: {error}"))?;
628 codewhale_util::utils::write_atomic(&save_path, json.as_bytes())
629 .map_err(|e| format!("Failed to save session: {e}"))?;
630 Ok((session, None))
631 }
632 })?;
633 if let Some(publication) = publication {
634 session.adopt_publication(&publication);
635 }
636 crate::tui::ui::install_offline_queue_transition(&mut app, queue_transition);
637 app.set_current_session_id(Some(session.metadata.id.clone()));
638 app.session_write_receipt = session.write_receipt.clone();
639 app.current_session_metadata = Some(session.metadata.clone());
640 app.session_title = Some(session.metadata.title.clone());
641 if let Err(err) =
642 app.publish_saved_work_state(work_owner.as_deref(), session.work_state.as_ref())
643 {
644 return Err(format!(
645 "Session saved, but Work views were not published: {err}"
646 ));
647 }
648 Ok(SessionSaveReceipt {
649 display_path,
650 truncated_id: codewhale_engine::session_manager::truncate_id(&session.metadata.id)
651 .to_string(),
652 })
653 }
654
655 fn fork_active(&mut self) -> Result<SessionForkReceipt, String> {
656 let mut app = self.host.app.borrow_mut();
657 if app.api_messages.is_empty() {
658 return Err("Nothing to fork. Send or load a message first.".to_string());
659 }
660
661 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
662 Ok(manager) => manager,
663 Err(err) => {
664 return Err(format!("could not open sessions directory: {err}"));
665 }
666 };
667
668 crate::tui::persistence_actor::flush_before_transition()?;
669 let control_owner = codewhale_engine::session_manager::SessionWriteOwner::control();
670 let control_source = app
671 .session_write_receipt
672 .as_ref()
673 .map(|source| source.capture(control_owner.clone()))
674 .transpose()
675 .map_err(|error| error.to_string())?;
676 let mut parent = crate::tui::ui::build_session_snapshot(&mut app, &manager)?;
677 if let Some(source) = control_source {
678 parent.write_receipt = Some(source);
679 } else if parent.write_receipt.is_some() {
680 parent
681 .capture_publication(control_owner)
682 .map_err(|error| error.to_string())?;
683 }
684
685 let work_owner = app.current_session_id.clone();
686 parent.make_storage_compatible();
687 let (manager, mut parent, publication) = run_owner_blocking(move || {
688 let publication = manager
689 .publish_session_bounded(parent.clone())
690 .map_err(|error| format!("Failed to save parent session: {error}"))?;
691 Ok((manager, parent, publication))
692 })?;
693 parent.adopt_publication(&publication);
694 app.session_write_receipt = parent.write_receipt.clone();
695
696 let fork_id = uuid::Uuid::new_v4().to_string();
697 let fork_source = manager
698 .expect_absent_session(&fork_id)
699 .map_err(|error| error.to_string())?
700 .capture(codewhale_engine::session_manager::SessionWriteOwner::control())
701 .map_err(|error| error.to_string())?;
702 let mut forked = parent.clone();
703 forked.metadata.id = fork_id;
704 forked.metadata.created_at = chrono::Utc::now();
705 forked.metadata.updated_at = forked.metadata.created_at;
706 forked.metadata.archived = false;
707 forked.metadata.runtime_store = None;
708 forked.approval_receipts.clear();
709 forked.window_title = None;
710 forked.composer_color = None;
711 forked.metadata.spawn_depth = parent.metadata.spawn_depth.saturating_add(1);
712 forked.metadata.mark_forked_from(&parent.metadata);
713 if let Some(journal) = forked.journal.as_mut() {
714 journal.spawn_depth = forked.metadata.spawn_depth;
715 }
716 let queue_transition =
717 crate::tui::ui::prepare_offline_queue_transition(&app, &forked.metadata.id)?;
718
719 forked.write_receipt = Some(fork_source);
720 let (mut forked, publication) = run_owner_blocking(move || {
721 let publication = manager
722 .publish_session(&forked)
723 .map_err(|error| format!("Failed to save forked session: {error}"))?;
724 Ok((forked, publication))
725 })?;
726 forked.adopt_publication(&publication);
727 if let Err(err) =
728 app.publish_saved_work_state(work_owner.as_deref(), parent.work_state.as_ref())
729 {
730 return Err(format!(
731 "Parent and fork {} were saved; the active session did not change because Work views were not published: {err}",
732 forked.metadata.id
733 ));
734 }
735
736 crate::tui::ui::install_offline_queue_transition(&mut app, queue_transition);
737 app.set_current_session_id(Some(forked.metadata.id.clone()));
738 app.current_session_metadata = Some(forked.metadata.clone());
739 app.restore_api_messages(forked.messages.clone(), &forked);
740 app.session_title = Some(forked.metadata.title.clone());
741 // A fork starts as its own session: no inherited tab/window title.
742 app.window_title = None;
743 app.composer_color = None;
744 let fork_id = forked.metadata.id.clone();
745 let parent_label =
746 codewhale_engine::session_manager::truncate_id(&parent.metadata.id).to_string();
747 let fork_label = codewhale_engine::session_manager::truncate_id(&fork_id).to_string();
748 let mode = to_command_mode(app.mode);
749 Ok(SessionForkReceipt {
750 parent_label,
751 fork_label,
752 sync: SessionSyncPayload {
753 session_id: Some(fork_id),
754 messages: app.api_messages.as_ref().clone(),
755 system_prompt: app.system_prompt.clone(),
756 model: app.model.clone(),
757 workspace: app.workspace.clone(),
758 mode,
759 agent_preset: app.agent_preset(),
760 },
761 })
762 }
763
764 fn fork_from(&mut self, session_id_or_prefix: &str) -> Result<SessionForkFromReceipt, String> {
765 let mut config = self
766 .host
767 .config
768 .ok_or_else(|| "The fork command has no active provider configuration.".to_string())?
769 .clone();
770 let mut app = self.host.app.borrow_mut();
771 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
772 Ok(m) => m,
773 Err(err) => {
774 return Err(format!("could not open sessions directory: {err}"));
775 }
776 };
777 let source_id = session_id_or_prefix.to_string();
778 let (manager, mut source_session) = run_owner_blocking(move || {
779 let source = manager
780 .load_session(&source_id)
781 .or_else(|_| manager.load_session_by_prefix(&source_id));
782 match source {
783 Ok(session) => Ok((manager, session)),
784 Err(error) => Err(format!("could not load session '{source_id}': {error}")),
785 }
786 })?;
787 source_session.ensure_journal();
788 let journal = source_session.journal.clone().unwrap_or_else(|| {
789 codewhale_runtime::session_tree::SessionJournal::from_messages(
790 source_session.messages.clone(),
791 source_session.metadata.spawn_depth,
792 )
793 });
794 let fork_id = uuid::Uuid::new_v4().to_string();
795 let fork_source = manager
796 .expect_absent_session(&fork_id)
797 .map_err(|error| error.to_string())?
798 .capture(codewhale_engine::session_manager::SessionWriteOwner::control())
799 .map_err(|error| error.to_string())?;
800 let forked_journal = journal.fork_from(None).unwrap_or_else(|_| {
801 codewhale_runtime::session_tree::SessionJournal::with_spawn_depth(
802 source_session.metadata.spawn_depth.saturating_add(1),
803 )
804 });
805 let messages = forked_journal.to_messages();
806 let mut forked = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
807 fork_id,
808 &messages,
809 &source_session.metadata.model,
810 &app.workspace,
811 source_session.metadata.total_tokens,
812 source_session
813 .system_prompt
814 .as_ref()
815 .map(|s| codewhale_models::SystemPrompt::Text(s.clone()))
816 .as_ref(),
817 source_session.metadata.mode.as_deref(),
818 );
819 forked.journal = Some(forked_journal);
820 forked.leaf_id = forked.journal.as_ref().and_then(|j| j.leaf_id.clone());
821 forked.messages = messages;
822 forked.agent_preset = source_session.agent_preset.clone();
823 forked.metadata.spawn_depth = forked.journal.as_ref().map(|j| j.spawn_depth).unwrap_or(0);
824 forked.metadata.parent_session_id = Some(source_session.metadata.id.clone());
825 forked.metadata.forked_from_message_count = Some(source_session.metadata.message_count);
826 forked.metadata.set_model_provider_route(
827 source_session.metadata.model_provider.as_str(),
828 source_session.metadata.model_provider_id.as_deref(),
829 );
830 forked.metadata.exec_route_binding = source_session.metadata.exec_route_binding.clone();
831 forked.metadata.copy_cost_from(&source_session.metadata);
832 forked.context_references = source_session.context_references.clone();
833 forked.artifacts = source_session.artifacts.clone();
834 forked.work_state = source_session.work_state.clone();
835 forked.last_auto_route = source_session.last_auto_route.clone();
836 forked.write_receipt = Some(fork_source);
837 let (mut forked, publication) = run_owner_blocking(move || {
838 let publication = manager
839 .publish_session(&forked)
840 .map_err(|error| format!("Failed to save forked session: {error}"))?;
841 Ok((forked, publication))
842 })?;
843 forked.adopt_publication(&publication);
844 let parent_label =
845 codewhale_engine::session_manager::truncate_id(&source_session.metadata.id).to_string();
846 let fork_label =
847 codewhale_engine::session_manager::truncate_id(&forked.metadata.id).to_string();
848 let spawn_depth = forked.metadata.spawn_depth;
849 crate::tui::ui::apply_loaded_session_with_goal(&mut app, &mut config, forked, None)?;
850 let mode = to_command_mode(app.mode);
851 Ok(SessionForkFromReceipt {
852 parent_label,
853 fork_label,
854 spawn_depth: spawn_depth.into(),
855 sync: SessionSyncPayload {
856 session_id: app.current_session_id.clone(),
857 messages: app.api_messages.as_ref().clone(),
858 system_prompt: app.system_prompt.clone(),
859 model: app.model.clone(),
860 workspace: app.workspace.clone(),
861 mode,
862 agent_preset: app.agent_preset(),
863 },
864 })
865 }
866
867 fn fresh_session(
868 &mut self,
869 force: bool,
870 conversation_mode: Option<&str>,
871 ) -> Result<SessionNewReceipt, String> {
872 let app = self.host.app.borrow();
873 let agent_preset = match conversation_mode {
874 None => None,
875 Some(id) => {
876 let table = crate::tui::conversation_mode::current_table_blocking(self.host.config);
877 match crate::tui::conversation_mode::resolve(app.ui_locale, &table, id) {
878 crate::tui::conversation_mode::Resolution::Unknown(message) => {
879 return Err(message);
880 }
881 crate::tui::conversation_mode::Resolution::Unavailable { name, reason } => {
882 return Err(crate::tui::conversation_mode::unavailable_message(
883 app.ui_locale,
884 &name,
885 &reason,
886 ));
887 }
888 crate::tui::conversation_mode::Resolution::Ready { stored, .. } => stored,
889 }
890 }
891 };
892 if !force {
893 let mut blockers: Vec<&'static str> = Vec::new();
894 if !app.input.trim().is_empty() {
895 blockers.push("the composer has unsent text");
896 }
897 if !app.queued_messages.is_empty() || app.queued_draft.is_some() {
898 blockers.push("queued messages are pending");
899 }
900 if !blockers.is_empty() {
901 return Err(format!(
902 "Cannot start a new session while {}. Run `/new --force` to discard pending work and start a fresh session.",
903 blockers.join(", ")
904 ));
905 }
906 }
907
908 app.work_state_snapshot().map_err(|_| {
909 "Could not start a new session because Work state is busy; retry in a moment."
910 .to_string()
911 })?;
912 let new_id = uuid::Uuid::new_v4().to_string();
913 let mode = to_command_mode(app.mode);
914 Ok(SessionNewReceipt {
915 truncated_id: codewhale_engine::session_manager::truncate_id(&new_id).to_string(),
916 sync: SessionSyncPayload {
917 session_id: Some(new_id),
918 messages: Vec::new(),
919 system_prompt: None,
920 model: app.model.clone(),
921 workspace: app.workspace.clone(),
922 mode,
923 agent_preset,
924 },
925 })
926 }
927
928 fn load_session(&mut self, path: &str) -> Result<PathBuf, String> {
929 let load_path = {
930 let app = self.host.app.borrow();
931 app.workspace
932 .join(crate::commands::config_main_host::expand_tilde(path))
933 };
934
935 let read_path = load_path.clone();
936 run_owner_blocking(move || {
937 let content = read_session_file_capped(&read_path)
938 .map_err(|e| format!("Failed to read session file: {e}"))?;
939 let _session: codewhale_engine::session_manager::SavedSession =
940 serde_json::from_str(&content)
941 .map_err(|e| format!("Failed to parse session file: {e}"))?;
942 Ok(())
943 })?;
944 Ok(load_path)
945 }
946
947 fn open_picker(&mut self, preselected: Option<String>) {
948 let mut app = self.host.app.borrow_mut();
949 // Materialize the picker inputs before mutating the view stack so the
950 // `RefCell` borrow of `App` is not simultaneously mutable and shared.
951 let workspace = app.workspace.clone();
952 let ui_locale = app.ui_locale;
953 let current_id = app.current_session_id.clone();
954 match preselected {
955 Some(session_id) => {
956 app.view_stack.push(
957 crate::tui::session_picker::SessionPickerView::new_selecting(
958 &workspace,
959 ui_locale,
960 &session_id,
961 )
962 .with_current_session(current_id.as_deref()),
963 );
964 }
965 None => {
966 app.view_stack.push(
967 crate::tui::session_picker::SessionPickerView::new(&workspace, ui_locale)
968 .with_current_session(current_id.as_deref()),
969 );
970 }
971 }
972 }
973
974 fn set_archived(
975 &mut self,
976 session_id: &str,
977 archived: bool,
978 ) -> Result<SessionArchiveReceipt, String> {
979 let verb = if archived { "archive" } else { "unarchive" };
980 let mut app = self.host.app.borrow_mut();
981 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
982 Ok(manager) => manager,
983 Err(err) => {
984 return Err(format!("could not open sessions directory: {err}"));
985 }
986 };
987 crate::tui::persistence_actor::flush_before_transition()?;
988 let session_id = session_id.to_string();
989 let metadata = run_owner_blocking(move || {
990 manager
991 .set_session_archived(
992 &session_id,
993 archived,
994 codewhale_engine::session_manager::SessionMutator::Owner,
995 )
996 .map_err(|err| format!("{verb} failed: {err}"))
997 })?;
998 app.adopt_session_mutation(&metadata);
999 if let Some(cached) = app.current_session_metadata.as_mut()
1000 && cached.id == metadata.id
1001 {
1002 cached.archived = metadata.archived;
1003 }
1004 Ok(SessionArchiveReceipt {
1005 truncated_id: codewhale_engine::session_manager::truncate_id(&metadata.id).to_string(),
1006 title: metadata.title,
1007 })
1008 }
1009
1010 fn prune_sessions(&mut self, days: u64) -> Result<usize, String> {
1011 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
1012 Ok(m) => m,
1013 Err(err) => {
1014 return Err(format!("could not open sessions directory: {err}"));
1015 }
1016 };
1017
1018 let max_age = std::time::Duration::from_secs(days.saturating_mul(24 * 60 * 60));
1019 // Never prune the active session, even if its timestamp is stale (a
1020 // just-resumed session isn't re-saved until its first post-resume write).
1021 let keep = self.host.app.borrow().current_session_id.clone();
1022 run_owner_blocking(move || {
1023 manager
1024 .prune_sessions_older_than_keeping(max_age, keep.as_deref())
1025 .map_err(|err| format!("prune failed: {err}"))
1026 })
1027 }
1028 }
1029
1030 // ---------------------------------------------------------------------------
1031 // FEAT-024 Phase 4: relocated host machinery for the control slice.
1032 //
1033 // These helpers were extracted from the legacy `/remote-env` command body
1034 // when that file became portable; they are host-owned and stay in TUI (the
1035 // future movable group never names them).
1036 // ---------------------------------------------------------------------------
1037
1038 const HOSTED_WORK_URL: &str = "https://app.codewhale.net/work";
1039 const MAX_GIT_VALUE_BYTES: usize = 4 * 1024;
1040
1041 /// Validated hosted-work Git target (repo slug + checked-out branch).
1042 #[derive(Debug, Clone, PartialEq, Eq)]
1043 struct RemoteEnvTarget {
1044 repo: String,
1045 branch: String,
1046 }
1047
1048 /// Resolve the hosted-work launcher target for a workspace: read the origin
1049 /// URL and symbolic branch, normalize the repository slug against the
1050 /// allowlist, and encode the launcher URL. Credentials never appear in the
1051 /// returned values.
1052 fn resolve_target(workspace: &Path) -> Option<RemoteEnvTarget> {
1053 let origin = read_git_value(
1054 workspace,
1055 &["config", "--local", "--get", "remote.origin.url"],
1056 )?;
1057 let repo = normalize_repo_slug(&origin)?;
1058 let branch = read_git_value(workspace, &["symbolic-ref", "--quiet", "--short", "HEAD"])?;
1059 if !valid_branch_name(&branch) {
1060 return None;
1061 }
1062 Some(RemoteEnvTarget { repo, branch })
1063 }
1064
1065 fn hosted_work_url(repo: &str, branch: &str) -> String {
1066 format!(
1067 "{HOSTED_WORK_URL}?repo={}&branch={}",
1068 urlencoding::encode(repo),
1069 urlencoding::encode(branch),
1070 )
1071 }
1072
1073 fn read_git_value(workspace: &Path, args: &[&str]) -> Option<String> {
1074 let mut command = codewhale_dependencies::Git::command()?;
1075 let output = command.arg("-C").arg(workspace).args(args).output().ok()?;
1076 if !output.status.success()
1077 || output.stdout.is_empty()
1078 || output.stdout.len() > MAX_GIT_VALUE_BYTES
1079 {
1080 return None;
1081 }
1082 let value = String::from_utf8(output.stdout).ok()?;
1083 let value = value.trim_end_matches(&['\r', '\n'][..]);
1084 if value.is_empty() {
1085 None
1086 } else {
1087 Some(value.to_string())
1088 }
1089 }
1090
1091 fn valid_branch_name(branch: &str) -> bool {
1092 if branch.is_empty() || branch.len() > MAX_GIT_VALUE_BYTES {
1093 return false;
1094 }
1095 let Some(mut command) = codewhale_dependencies::Git::command() else {
1096 return false;
1097 };
1098 command
1099 .args(["check-ref-format", "--branch"])
1100 .arg(branch)
1101 .stdout(std::process::Stdio::null())
1102 .stderr(std::process::Stdio::null())
1103 .status()
1104 .is_ok_and(|status| status.success())
1105 }
1106
1107 fn normalize_repo_slug(origin: &str) -> Option<String> {
1108 let origin = origin.trim();
1109 if origin.is_empty()
1110 || origin.len() > MAX_GIT_VALUE_BYTES
1111 || origin.chars().any(char::is_control)
1112 {
1113 return None;
1114 }
1115
1116 let (host, path) = if starts_with_ascii_case(origin, "https://") {
1117 split_url_origin(&origin["https://".len()..], UrlScheme::Https)?
1118 } else if starts_with_ascii_case(origin, "ssh://") {
1119 split_url_origin(&origin["ssh://".len()..], UrlScheme::Ssh)?
1120 } else {
1121 split_scp_origin(origin)?
1122 };
1123 if !matches!(
1124 host.to_ascii_lowercase().as_str(),
1125 "github.com" | "cnb.cool"
1126 ) {
1127 return None;
1128 }
1129 normalize_repo_path(path)
1130 }
1131
1132 #[derive(Debug, Clone, Copy)]
1133 enum UrlScheme {
1134 Https,
1135 Ssh,
1136 }
1137
1138 fn starts_with_ascii_case(value: &str, prefix: &str) -> bool {
1139 value
1140 .get(..prefix.len())
1141 .is_some_and(|candidate| candidate.eq_ignore_ascii_case(prefix))
1142 }
1143
1144 fn split_url_origin(origin: &str, scheme: UrlScheme) -> Option<(&str, &str)> {
1145 let (authority, path) = origin.split_once('/')?;
1146 if authority.is_empty() || path.is_empty() {
1147 return None;
1148 }
1149 let host_port = authority
1150 .rsplit_once('@')
1151 .map_or(authority, |(_, host)| host);
1152 let host = match host_port.rsplit_once(':') {
1153 Some((host, port))
1154 if !host.is_empty()
1155 && !port.is_empty()
1156 && port.bytes().all(|byte| byte.is_ascii_digit())
1157 && (matches!(scheme, UrlScheme::Ssh) || port == "443") =>
1158 {
1159 host
1160 }
1161 Some(_) => return None,
1162 None => host_port,
1163 };
1164 (!host.is_empty()).then_some((host, path))
1165 }
1166
1167 fn split_scp_origin(origin: &str) -> Option<(&str, &str)> {
1168 let (authority, path) = origin.split_once(':')?;
1169 let (_, host) = authority.rsplit_once('@')?;
1170 if host.is_empty() || path.is_empty() {
1171 return None;
1172 }
1173 Some((host, path))
1174 }
1175
1176 fn normalize_repo_path(path: &str) -> Option<String> {
1177 if path.chars().any(|ch| matches!(ch, '?' | '#' | '\\')) {
1178 return None;
1179 }
1180 let path = path.trim_matches('/');
1181 let path = path.strip_suffix(".git").unwrap_or(path);
1182 let mut parts = path.split('/');
1183 let namespace = parts.next()?;
1184 let repository = parts.next()?;
1185 if parts.next().is_some()
1186 || !valid_repo_component(namespace)
1187 || !valid_repo_component(repository)
1188 {
1189 return None;
1190 }
1191 Some(format!("{namespace}/{repository}"))
1192 }
1193
1194 fn valid_repo_component(value: &str) -> bool {
1195 !value.is_empty()
1196 && value.len() <= 255
1197 && !matches!(value, "." | "..")
1198 && value
1199 .bytes()
1200 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
1201 }
1202
1203 // ---------------------------------------------------------------------------
1204 // Session control adapter (FEAT-024 D4/D5)
1205 //
1206 // Sole host owner of concrete control machinery for the seven control commands:
1207 // relay snapshot reads (goal/plan/work/todo/compact-template), rename/title/color
1208 // persistence (sanitization, checkpoint recovery, live synchronization, save,
1209 // publication, redraw), resume routing/imports, remote-control state and the
1210 // synchronous single-attempt browser launch, and hosted-work Git target
1211 // resolution. Every delegate reproduces the baseline check/mutation order
1212 // exactly (transition gate before resume I/O, save before publication,
1213 // browser launch without retry/deferral) and returns portable
1214 // projections/receipts or the exact host-error text the baseline surfaces.
1215 // No `SessionManager`, saved-session/container type, `SessionPickerView`,
1216 // remote-control service, Git wrapper, configuration, model/history type,
1217 // lock, or host callback crosses the facet.
1218 // ---------------------------------------------------------------------------
1219 pub(crate) struct SessionControlAdapter<'a> {
1220 host: SharedCommandHost<'a>,
1221 }
1222
1223 impl CommandSessionControlContext for SessionControlAdapter<'_> {
1224 fn transition_blocked(&self) -> bool {
1225 self.host.app.borrow().session_transition_blocked()
1226 }
1227
1228 fn transition_blockers(&self) -> Vec<String> {
1229 self.host.app.borrow().session_transition_blockers()
1230 }
1231
1232 fn relay_projection(&self) -> RelayProjection {
1233 let app = self.host.app.borrow();
1234 let plan = match app.plan_state.try_lock() {
1235 Ok(plan) => {
1236 let snapshot = plan.snapshot();
1237 if snapshot.is_empty() {
1238 PlanProjection::Absent
1239 } else {
1240 PlanProjection::Sections(plan_snapshot_to_sections(&snapshot))
1241 }
1242 }
1243 Err(_) => PlanProjection::Busy,
1244 };
1245 let todos = match app.work_state_snapshot() {
1246 Ok(Some(state)) => {
1247 match codewhale_engine::todo_snapshot::todo_snapshot_body(&state.todos) {
1248 Some(body) => TodoProjection::Body(body),
1249 None => TodoProjection::Absent,
1250 }
1251 }
1252 Ok(None) => TodoProjection::Absent,
1253 Err(_) => TodoProjection::Unavailable,
1254 };
1255 RelayProjection {
1256 compact_template: codewhale_engine::prompts::COMPACT_TEMPLATE.to_string(),
1257 handoff_path: codewhale_engine::prompts::HANDOFF_RELATIVE_PATH.to_string(),
1258 workspace: app.workspace.display().to_string(),
1259 mode: app.mode.label().to_string(),
1260 model: app.model_display_label(),
1261 goal_objective: app.goal.objective.clone(),
1262 goal_token_budget: app.goal.token_budget,
1263 todos,
1264 plan,
1265 }
1266 }
1267
1268 fn open_resume_picker(&mut self) {
1269 let mut app = self.host.app.borrow_mut();
1270 let picker =
1271 crate::tui::session_picker::SessionPickerView::new(&app.workspace, app.ui_locale)
1272 .with_current_session(app.current_session_id.as_deref());
1273 app.view_stack.push(picker);
1274 }
1275
1276 fn resolve_resume_source(&mut self, raw: &str) -> Result<ResumeSource, String> {
1277 let workspace = self.host.app.borrow().workspace.clone();
1278 let raw_owned = raw.to_string();
1279 match run_owner_blocking(move || probe_resume_source(&raw_owned, &workspace))? {
1280 ResumeProbe::File(path) => Ok(ResumeSource::File(path)),
1281 ResumeProbe::Session {
1282 load_path,
1283 truncated_id,
1284 title,
1285 } => Ok(ResumeSource::Session {
1286 load_path,
1287 truncated_id,
1288 title,
1289 }),
1290 ResumeProbe::Container(container) => {
1291 let mut app = self.host.app.borrow_mut();
1292 import_session_container(&mut app, container).map(ResumeSource::Imported)
1293 }
1294 ResumeProbe::NotFound { error } => Ok(ResumeSource::NotFound {
1295 raw: raw.to_string(),
1296 error,
1297 }),
1298 }
1299 }
1300
1301 fn import_session_file(&mut self, path: PathBuf) -> Result<ResumeImportReceipt, String> {
1302 let mut app = self.host.app.borrow_mut();
1303 import_foreign_file(&mut app, &path)
1304 }
1305
1306 fn sanitize_session_title(&self, raw_title: &str) -> String {
1307 codewhale_engine::session_manager::sanitize_session_title(raw_title)
1308 }
1309
1310 fn rename_session(&mut self, new_title: &str) -> Result<SessionTitleReceipt, String> {
1311 let mut app = self.host.app.borrow_mut();
1312 let session_id = match &app.current_session_id {
1313 Some(id) => id.clone(),
1314 None => {
1315 return Err(
1316 "No active session. Send a message first to start a session.".to_string(),
1317 );
1318 }
1319 };
1320 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
1321 Ok(m) => m,
1322 Err(e) => return Err(format!("Could not open sessions directory: {e}")),
1323 };
1324
1325 crate::tui::persistence_actor::flush_before_transition()?;
1326 let control_owner = codewhale_engine::session_manager::SessionWriteOwner::control();
1327 let control_source = app
1328 .session_write_receipt
1329 .as_ref()
1330 .map(|source| source.capture(control_owner.clone()))
1331 .transpose()
1332 .map_err(|error| error.to_string())?;
1333 let mut session = crate::tui::ui::build_session_snapshot(&mut app, &manager)?;
1334 if let Some(source) = control_source {
1335 session.write_receipt = Some(source);
1336 } else if session.write_receipt.is_some() {
1337 session
1338 .capture_publication(control_owner)
1339 .map_err(|error| error.to_string())?;
1340 }
1341
1342 session.make_storage_compatible();
1343 session = codewhale_engine::session_manager::update_session(
1344 session,
1345 &app.api_messages,
1346 u64::from(app.session.total_tokens),
1347 app.system_prompt.as_ref(),
1348 );
1349 session.work_state = match app.work_state_snapshot() {
1350 Ok(state) => state,
1351 Err(err) => {
1352 return Err(format!(
1353 "Could not snapshot Work state before rename: {err}"
1354 ));
1355 }
1356 };
1357 session.context_references = app.session_context_references.clone();
1358 session.artifacts = app.session_artifacts.clone();
1359 session.last_auto_route = app.auto_route_for_persistence();
1360 session.metadata.model = app.model_selection_for_persistence();
1361 session
1362 .metadata
1363 .set_model_provider_route(app.api_provider.as_str(), app.provider_id_for_persistence());
1364 session.metadata.workspace.clone_from(&app.workspace);
1365 session.metadata.mode = Some(app.mode.as_setting().to_string());
1366 app.sync_cost_to_metadata(&mut session.metadata);
1367 session.metadata.title = new_title.to_string();
1368 session.metadata.title_is_custom = true;
1369
1370 let (mut session, publication) = run_owner_blocking(move || {
1371 let publication = manager
1372 .publish_session(&session)
1373 .map_err(|e| format!("Could not save session: {e}"))?;
1374 Ok((session, publication))
1375 })?;
1376 session.adopt_publication(&publication);
1377 app.session_write_receipt = session.write_receipt.clone();
1378 app.current_session_metadata = Some(session.metadata.clone());
1379 app.session_title = Some(new_title.to_string());
1380 if let Err(err) =
1381 app.publish_saved_work_state(Some(&session_id), session.work_state.as_ref())
1382 {
1383 return Err(format!(
1384 "Session renamed, but Work views were not published: {err}"
1385 ));
1386 }
1387 Ok(SessionTitleReceipt {
1388 title: new_title.to_string(),
1389 })
1390 }
1391
1392 fn title_report(&self) -> TitleReport {
1393 let app = self.host.app.borrow();
1394 let source = if app.window_title.is_some() {
1395 TitleSource::Session
1396 } else if app.title_default.is_some() {
1397 TitleSource::ConfigDefault
1398 } else {
1399 TitleSource::None
1400 };
1401 TitleReport {
1402 effective: app.window_title_prefix().unwrap_or("unset").to_string(),
1403 source,
1404 }
1405 }
1406
1407 fn set_window_title(&mut self, title: String) -> Result<(), String> {
1408 let mut app = self.host.app.borrow_mut();
1409 persist_window_title(&mut app, Some(title))
1410 }
1411
1412 fn clear_window_title(&mut self) -> Result<(), String> {
1413 let mut app = self.host.app.borrow_mut();
1414 persist_window_title(&mut app, None)
1415 }
1416
1417 fn composer_color(&self) -> Option<String> {
1418 self.host.app.borrow().composer_color.clone()
1419 }
1420
1421 fn set_composer_color(&mut self, color: Option<String>) -> Result<(), String> {
1422 let mut app = self.host.app.borrow_mut();
1423 persist_composer_color(&mut app, color)
1424 }
1425
1426 fn remote_status(&self) -> String {
1427 self.host.app.borrow().remote_control.status_line()
1428 }
1429
1430 fn remote_link(&self) -> Option<RemoteLink> {
1431 let app = self.host.app.borrow();
1432 let url = app.remote_control.run_url()?.to_string();
1433 Some(RemoteLink {
1434 computer_url: app.remote_control.computer_url().map(str::to_string),
1435 url,
1436 })
1437 }
1438
1439 fn remote_browser_open(&self) -> RemoteOpenOutcome {
1440 let app = self.host.app.borrow();
1441 let Some(url) = app.remote_control.run_url().map(str::to_string) else {
1442 return RemoteOpenOutcome::NoLink;
1443 };
1444 // Synchronous single attempt through the authoritative URL-opening
1445 // helper; never retried and never deferred to an external-URL action.
1446 let launched = codewhale_runtime::browser::open_url(&url).is_ok();
1447 map_browser_open_result(url, launched)
1448 }
1449
1450 fn remote_start_info(&self) -> RemoteStartInfo {
1451 let app = self.host.app.borrow();
1452 RemoteStartInfo {
1453 connecting: app.is_loading || app.dispatch_in_flight,
1454 }
1455 }
1456
1457 fn remote_stop_refusal(&self) -> Option<String> {
1458 self.host.app.borrow().remote_control.stop_refusal().clone()
1459 }
1460
1461 fn resolve_hosted_work_target(&self) -> Option<HostedWorkTarget> {
1462 let workspace = self.host.app.borrow().workspace.clone();
1463 let target = run_owner_blocking(move || Ok(resolve_target(&workspace)))
1464 .ok()
1465 .flatten()?;
1466 let url = hosted_work_url(&target.repo, &target.branch);
1467 Some(HostedWorkTarget {
1468 url,
1469 repo: target.repo,
1470 branch: target.branch,
1471 })
1472 }
1473 }
1474
1475 /// Persist an already sanitized window title through the baseline host path.
1476 /// Manager resolution intentionally precedes active-session lookup, matching
1477 /// the original `/title` error precedence for both set and clear operations.
1478 fn persist_window_title(app: &mut App, title: Option<String>) -> Result<(), String> {
1479 persist_session_display(
1480 app,
1481 "title",
1482 "Window title",
1483 |session| session.window_title.clone_from(&title),
1484 |app| app.window_title = title.clone(),
1485 )
1486 }
1487
1488 fn persist_composer_color(app: &mut App, color: Option<String>) -> Result<(), String> {
1489 persist_session_display(
1490 app,
1491 "composer color",
1492 "Composer color",
1493 |session| session.composer_color.clone_from(&color),
1494 |app| app.composer_color = color.clone(),
1495 )
1496 }
1497
1498 fn persist_session_display(
1499 app: &mut App,
1500 setting: &str,
1501 saved: &str,
1502 stage: impl FnOnce(&mut codewhale_engine::session_manager::SavedSession),
1503 commit: impl FnOnce(&mut App),
1504 ) -> Result<(), String> {
1505 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
1506 Ok(manager) => manager,
1507 Err(error) => return Err(format!("Could not open sessions directory: {error}")),
1508 };
1509 let session_id = match &app.current_session_id {
1510 Some(id) => id.clone(),
1511 None => {
1512 return Err("No active session. Send a message first to start a session.".to_string());
1513 }
1514 };
1515 crate::tui::persistence_actor::flush_before_transition()?;
1516 let control_owner = codewhale_engine::session_manager::SessionWriteOwner::control();
1517 let control_source = app
1518 .session_write_receipt
1519 .as_ref()
1520 .map(|source| source.capture(control_owner.clone()))
1521 .transpose()
1522 .map_err(|error| error.to_string())?;
1523 let mut session = crate::tui::ui::build_session_snapshot(app, &manager)?;
1524 if let Some(source) = control_source {
1525 session.write_receipt = Some(source);
1526 } else if session.write_receipt.is_some() {
1527 session
1528 .capture_publication(control_owner)
1529 .map_err(|error| error.to_string())?;
1530 }
1531
1532 session.make_storage_compatible();
1533 session = codewhale_engine::session_manager::update_session(
1534 session,
1535 &app.api_messages,
1536 u64::from(app.session.total_tokens),
1537 app.system_prompt.as_ref(),
1538 );
1539 session.work_state = match app.work_state_snapshot() {
1540 Ok(state) => state,
1541 Err(error) => {
1542 return Err(format!(
1543 "Could not snapshot Work state before setting {setting}: {error}"
1544 ));
1545 }
1546 };
1547 session.context_references = app.session_context_references.clone();
1548 session.artifacts = app.session_artifacts.clone();
1549 session.last_auto_route = app.auto_route_for_persistence();
1550 session.metadata.model = app.model_selection_for_persistence();
1551 session
1552 .metadata
1553 .set_model_provider_route(app.api_provider.as_str(), app.provider_id_for_persistence());
1554 session.metadata.workspace.clone_from(&app.workspace);
1555 session.metadata.mode = Some(app.mode.as_setting().to_string());
1556 app.sync_cost_to_metadata(&mut session.metadata);
1557 stage(&mut session);
1558
1559 let (mut session, publication) = run_owner_blocking(move || {
1560 let publication = manager
1561 .publish_session_preserving_lifecycle(&session)
1562 .map_err(|error| format!("Could not save session: {error}"))?;
1563 Ok((session, publication))
1564 })?;
1565 session.adopt_publication(&publication);
1566 app.session_write_receipt = session.write_receipt.clone();
1567 app.current_session_metadata = Some(session.metadata.clone());
1568 commit(app);
1569 app.needs_redraw = true;
1570 if let Err(error) = app.publish_saved_work_state(Some(&session_id), session.work_state.as_ref())
1571 {
1572 return Err(format!(
1573 "{saved} saved, but Work views were not published: {error}"
1574 ));
1575 }
1576 Ok(())
1577 }
1578
1579 /// Map one synchronous browser-launch attempt to its portable outcome.
1580 /// Split out so the delegate's success/failure branches are unit-provable
1581 /// without spawning a real browser (utils tests cover the launcher itself).
1582 fn map_browser_open_result(url: String, launched: bool) -> RemoteOpenOutcome {
1583 if launched {
1584 RemoteOpenOutcome::Opened { url }
1585 } else {
1586 RemoteOpenOutcome::LaunchFailed { url }
1587 }
1588 }
1589
1590 fn plan_snapshot_to_sections(
1591 snapshot: &codewhale_engine::tools::plan::PlanSnapshot,
1592 ) -> PlanSections {
1593 PlanSections {
1594 title: snapshot.title.clone(),
1595 objective: snapshot.objective.clone(),
1596 context_summary: snapshot.context_summary.clone(),
1597 explanation: snapshot.explanation.clone(),
1598 sources_used: snapshot.sources_used.clone(),
1599 critical_files: snapshot.critical_files.clone(),
1600 constraints: snapshot.constraints.clone(),
1601 recommended_approach: snapshot.recommended_approach.clone(),
1602 verification_plan: snapshot.verification_plan.clone(),
1603 risks_and_unknowns: snapshot.risks_and_unknowns.clone(),
1604 handoff_packet: snapshot.handoff_packet.clone(),
1605 replan_if: snapshot.replan_if.clone(),
1606 items: snapshot
1607 .items
1608 .iter()
1609 .map(|item| PlanStep {
1610 status: match &item.status {
1611 codewhale_engine::tools::plan::StepStatus::Pending => PlanStepStatus::Pending,
1612 codewhale_engine::tools::plan::StepStatus::InProgress => {
1613 PlanStepStatus::InProgress
1614 }
1615 codewhale_engine::tools::plan::StepStatus::Completed => {
1616 PlanStepStatus::Completed
1617 }
1618 },
1619 text: item.step.clone(),
1620 })
1621 .collect(),
1622 }
1623 }
1624
1625 /// `/resume <file>` import: read, parse a container or plain saved session,
1626 /// and apply it atomically. Errors are the exact baseline text.
1627 fn import_foreign_file(app: &mut App, path: &Path) -> Result<ResumeImportReceipt, String> {
1628 let read_path = path.to_path_buf();
1629 let container = run_owner_blocking(move || {
1630 let content = read_session_file_capped(&read_path)
1631 .map_err(|e| format!("failed to read import file {}: {e}", read_path.display()))?;
1632 if let Ok(container) =
1633 codewhale_runtime::session_tree::SessionImportContainer::from_json(&content)
1634 {
1635 return Ok(container);
1636 }
1637 if let Ok(foreign) =
1638 serde_json::from_str::<codewhale_engine::session_manager::SavedSession>(&content)
1639 {
1640 return Ok(foreign.export_container("foreign"));
1641 }
1642 Err(format!(
1643 "File {} is not a recognized session export",
1644 read_path.display()
1645 ))
1646 })?;
1647 import_session_container(app, container)
1648 }
1649
1650 enum ResumeProbe {
1651 File(PathBuf),
1652 Session {
1653 load_path: Option<PathBuf>,
1654 truncated_id: String,
1655 title: String,
1656 },
1657 Container(codewhale_runtime::session_tree::SessionImportContainer),
1658 NotFound {
1659 error: String,
1660 },
1661 }
1662
1663 fn probe_resume_source(raw: &str, workspace: &Path) -> Result<ResumeProbe, String> {
1664 let raw_path = PathBuf::from(raw);
1665 if raw_path.is_file() || (raw.ends_with(".json") && Path::new(raw).exists()) {
1666 return Ok(ResumeProbe::File(raw_path));
1667 }
1668 let ws_path = workspace.join(raw);
1669 if ws_path.is_file() {
1670 return Ok(ResumeProbe::File(ws_path));
1671 }
1672 let manager = codewhale_engine::session_manager::SessionManager::default_location()
1673 .map_err(|e| format!("could not open sessions directory: {e}"))?;
1674 match manager.load_session_snapshot(raw).or_else(|_| {
1675 manager
1676 .resolve_session_id_prefix(raw)
1677 .and_then(|id| manager.load_session_snapshot(&id))
1678 }) {
1679 Ok(sess) => {
1680 let path = manager
1681 .sessions_dir()
1682 .join(format!("{}.json", sess.metadata.id));
1683 Ok(ResumeProbe::Session {
1684 load_path: path.exists().then_some(path),
1685 truncated_id: codewhale_engine::session_manager::truncate_id(&sess.metadata.id)
1686 .to_string(),
1687 title: sess.metadata.title,
1688 })
1689 }
1690 Err(e) => {
1691 if let Ok(container) =
1692 codewhale_runtime::session_tree::SessionImportContainer::from_json(raw)
1693 {
1694 Ok(ResumeProbe::Container(container))
1695 } else {
1696 Ok(ResumeProbe::NotFound {
1697 error: e.to_string(),
1698 })
1699 }
1700 }
1701 }
1702 }
1703
1704 /// Apply a parsed foreign container: persist, mutate the active session,
1705 /// select it in a fresh picker, and return the portable receipt.
1706 fn import_session_container(
1707 app: &mut App,
1708 container: codewhale_runtime::session_tree::SessionImportContainer,
1709 ) -> Result<ResumeImportReceipt, String> {
1710 let manager = match codewhale_engine::session_manager::SessionManager::default_location() {
1711 Ok(m) => m,
1712 Err(e) => return Err(format!("could not open sessions directory: {e}")),
1713 };
1714 let model = app.model.clone();
1715 let workspace = app.workspace.clone();
1716 let mut imported = match codewhale_engine::session_manager::SavedSession::import_foreign(
1717 container, workspace, model,
1718 ) {
1719 Ok(s) => s,
1720 Err(e) => return Err(format!("foreign import failed: {e}")),
1721 };
1722 // The import takes this window's model, so it takes this window's route
1723 // too. Left at the record default it named a different provider, and
1724 // opening the imported session sent its whole history there.
1725 let (provider, provider_id) = (
1726 app.provider_identity_for_persistence().to_string(),
1727 app.provider_id_for_persistence().map(str::to_string),
1728 );
1729 imported
1730 .metadata
1731 .set_model_provider_route(&provider, provider_id.as_deref());
1732 let new_id = imported.metadata.id.clone();
1733 let queue_transition = crate::tui::ui::prepare_offline_queue_transition(app, &new_id)?;
1734 imported.write_receipt = Some(
1735 manager
1736 .expect_absent_session(&new_id)
1737 .map_err(|error| error.to_string())?,
1738 );
1739 imported
1740 .capture_publication(codewhale_engine::session_manager::SessionWriteOwner::control())
1741 .map_err(|error| error.to_string())?;
1742 let (mut imported, publication) = run_owner_blocking(move || {
1743 let publication = manager
1744 .publish_session(&imported)
1745 .map_err(|error| format!("imported session could not be saved: {error}"))?;
1746 Ok((imported, publication))
1747 })?;
1748 imported.adopt_publication(&publication);
1749 crate::tui::ui::install_offline_queue_transition(app, queue_transition);
1750 app.set_current_session_id(Some(new_id.clone()));
1751 app.current_session_metadata = Some(imported.metadata.clone());
1752 app.window_title.clone_from(&imported.window_title);
1753 app.composer_color.clone_from(&imported.composer_color);
1754 app.restore_api_messages(imported.messages.clone(), &imported);
1755 let picker = crate::tui::session_picker::SessionPickerView::new_selecting(
1756 &app.workspace,
1757 app.ui_locale,
1758 &new_id,
1759 )
1760 .with_current_session(app.current_session_id.as_deref());
1761 app.view_stack.push(picker);
1762 Ok(ResumeImportReceipt {
1763 truncated_id: codewhale_engine::session_manager::truncate_id(&new_id).to_string(),
1764 entry_count: imported
1765 .journal
1766 .as_ref()
1767 .map(|journal| journal.entries.len())
1768 .unwrap_or(0),
1769 leaf_display: imported.leaf_id.as_deref().unwrap_or("(none)").to_string(),
1770 sync: SessionSyncPayload {
1771 session_id: Some(new_id.clone()),
1772 messages: app.api_messages.as_ref().clone(),
1773 system_prompt: app.system_prompt.clone(),
1774 model: app.model.clone(),
1775 workspace: app.workspace.clone(),
1776 mode: to_command_mode(app.mode),
1777 agent_preset: app.agent_preset(),
1778 },
1779 })
1780 }
1781
1782 // ---------------------------------------------------------------------------
1783 // Session export adapter (FEAT-025 D1/D2/D3/D5/D7/D8/D9)
1784 //
1785 // Sole host owner of concrete export machinery for `/export` and `/daochu`:
1786 // metadata derivation, authoritative/visible-history projection, semantic
1787 // restore-point projection, the shared `turn_handoff_markdown` renderer,
1788 // clipboard mode/recovery/delivery, and protected destination resolution/
1789 // writing. Every delegate reproduces the baseline order and returns portable
1790 // data or the exact host-error text; no concrete `App`, clipboard, snapshot,
1791 // history, filesystem, or turn-handoff type crosses the boundary. Hidden
1792 // reasoning bodies, signatures, and inline/local image payloads are excluded
1793 // while the projection is built (D9). The shared recovery writer and protected
1794 // file services live in `commands::session_export_host` (outside the future
1795 // portable group) so `/copy` and `/export` reuse one implementation (D5).
1796 // ---------------------------------------------------------------------------
1797 pub(crate) struct SessionExportAdapter<'a> {
1798 host: SharedCommandHost<'a>,
1799 }
1800
1801 impl codewhale_command_contract::navigation::CommandResponseCopyContext
1802 for SessionExportAdapter<'_>
1803 {
1804 fn copy_completed_response(
1805 &mut self,
1806 ) -> Option<codewhale_command_contract::navigation::ResponseCopyDelivery> {
1807 let content = self
1808 .host
1809 .app
1810 .borrow()
1811 .completed_assistant_output_receipt()?
1812 .to_owned();
1813 Some(
1814 codewhale_command_contract::navigation::ResponseCopyDelivery {
1815 requires_terminal_paste: self.clipboard_requires_terminal_paste(),
1816 recovery_path: self.write_recovery_copy(&content),
1817 clipboard_result: self.write_clipboard(&content),
1818 },
1819 )
1820 }
1821
1822 fn show_copy_receipt(&mut self, message: &str, is_error: bool) {
1823 use crate::tui::app::{StatusToast, StatusToastLevel};
1824 let level = if is_error {
1825 StatusToastLevel::Error
1826 } else {
1827 StatusToastLevel::Info
1828 };
1829 self.host.app.borrow_mut().push_status_toast_record(
1830 StatusToast::new(message.to_owned(), level, Some(8_000)).for_command_receipt(),
1831 );
1832 }
1833 }
1834
1835 impl CommandSessionExportContext for SessionExportAdapter<'_> {
1836 /// Conversation export projection: metadata, transcript, and restore-point
1837 /// state.
1838 ///
1839 /// Memory note (FEAT-025 audit, finding F3): the projection is an *owned*
1840 /// copy of the transcript, so peak use is roughly the live `api_messages`
1841 /// plus this projection for the duration of one render. That copy is
1842 /// structural, not an oversight: the facet must return owned data because
1843 /// `SharedCommandHost` hands out `App` through a `RefCell`, so no borrow can
1844 /// outlive this method, and a `dyn` facet cannot lend a projection tied to a
1845 /// temporary `Ref`. The baseline rendered straight from `App` and cloned one
1846 /// block at a time, so this is a deliberate D3 cost accepted for the
1847 /// capability boundary. Removing it needs a host proxy that can lend a
1848 /// borrowed projection (tracked with the FEAT-043/046 extraction work); it is
1849 /// not something this slice can fix locally.
1850 fn conversation_projection(&self) -> ConversationExportProjection {
1851 let (metadata, transcript, turn_outcomes, workspace) = {
1852 let app = self.host.app.borrow();
1853 (
1854 export_metadata(&app),
1855 project_transcript(&app),
1856 project_turn_outcomes(&app),
1857 app.workspace.clone(),
1858 )
1859 };
1860 let restore_points =
1861 match run_owner_blocking(move || Ok(project_restore_points(&workspace))) {
1862 Ok(points) => points,
1863 Err(reason) => RestorePointProjection::Unreadable { reason },
1864 };
1865 ConversationExportProjection {
1866 metadata,
1867 transcript,
1868 restore_points,
1869 turn_outcomes,
1870 }
1871 }
1872
1873 fn turn_handoff_projection(&self) -> TurnHandoffProjection {
1874 let app = self.host.app.borrow();
1875 TurnHandoffProjection {
1876 markdown: crate::tui::ui::turn_handoff_markdown(&app),
1877 workspace_path: app.workspace.to_string_lossy().into_owned(),
1878 }
1879 }
1880
1881 fn clipboard_requires_terminal_paste(&self) -> bool {
1882 self.host.app.borrow().clipboard.requires_terminal_paste()
1883 }
1884
1885 fn write_recovery_copy(&self, markdown: &str) -> Option<PathBuf> {
1886 let markdown = markdown.to_string();
1887 run_owner_blocking(move || {
1888 Ok(crate::commands::session_export_host::write_last_copy(
1889 &markdown,
1890 ))
1891 })
1892 .ok()
1893 .flatten()
1894 }
1895
1896 fn write_clipboard(&self, markdown: &str) -> Result<(), String> {
1897 self.host
1898 .app
1899 .borrow_mut()
1900 .clipboard
1901 .write_text(markdown)
1902 .map_err(|err| err.to_string())
1903 }
1904
1905 fn resolve_export_path(&self, raw: &str) -> Result<PathBuf, String> {
1906 let workspace = self.host.app.borrow().workspace.clone();
1907 let raw = raw.to_string();
1908 run_owner_blocking(move || {
1909 crate::commands::session_export_host::resolve_export_path(&workspace, &raw)
1910 })
1911 }
1912
1913 fn default_export_path(&self, file_name: &str) -> Result<PathBuf, String> {
1914 let file_name = file_name.to_string();
1915 run_owner_blocking(move || {
1916 crate::commands::session_export_host::default_export_path(&file_name)
1917 })
1918 }
1919
1920 fn write_export_file(&self, path: &Path, contents: &[u8], force: bool) -> Result<(), String> {
1921 let path = path.to_path_buf();
1922 let contents = contents.to_vec();
1923 run_owner_blocking(move || {
1924 crate::commands::session_export_host::write_export_file(&path, &contents, force)
1925 })
1926 }
1927 }
1928
1929 /// Maximum restore points listed in the export summary (baseline bound).
1930 const RESTORE_POINT_SUMMARY_MAX: usize = 100;
1931
1932 /// Authoritative export metadata, reusing the baseline host derivations.
1933 fn export_metadata(app: &App) -> ExportMetadata {
1934 let message_count = if app.api_messages.is_empty() {
1935 app.history.len()
1936 } else {
1937 app.api_messages.len()
1938 };
1939 let session_label = app
1940 .current_session_id
1941 .as_deref()
1942 .map(codewhale_engine::session_manager::truncate_id)
1943 .unwrap_or("unsaved")
1944 .to_string();
1945 let workspace_name = app
1946 .workspace
1947 .file_name()
1948 .and_then(|name| name.to_str())
1949 .unwrap_or("workspace")
1950 .to_string();
1951 let title = app
1952 .session_title
1953 .as_deref()
1954 .map(str::trim)
1955 .filter(|title| {
1956 !title.is_empty() && *title != codewhale_engine::session_manager::DEFAULT_SESSION_TITLE
1957 })
1958 .map(str::to_string);
1959 ExportMetadata {
1960 session_label,
1961 title,
1962 provider: app.provider_identity_for_persistence().to_string(),
1963 model: app.model_display_label(),
1964 mode: app.mode.display_name().to_string(),
1965 workspace_name,
1966 message_count,
1967 exported_at_unix: chrono::Utc::now().timestamp(),
1968 }
1969 }
1970
1971 fn project_turn_outcomes(app: &App) -> Vec<ExportTurnOutcome> {
1972 app.session_turn_outcomes
1973 .iter()
1974 .filter(|outcome| {
1975 matches!(
1976 outcome.status,
1977 codewhale_engine::core::events::TurnOutcomeStatus::Failed
1978 | codewhale_engine::core::events::TurnOutcomeStatus::Interrupted
1979 )
1980 })
1981 .map(|outcome| ExportTurnOutcome {
1982 status: match outcome.status {
1983 codewhale_engine::core::events::TurnOutcomeStatus::Failed => "failed".to_string(),
1984 codewhale_engine::core::events::TurnOutcomeStatus::Interrupted => {
1985 "interrupted".to_string()
1986 }
1987 codewhale_engine::core::events::TurnOutcomeStatus::Completed => {
1988 "completed".to_string()
1989 }
1990 },
1991 error: outcome.error.clone(),
1992 code: outcome.code.clone(),
1993 ended_at_unix: outcome.ended_at.timestamp(),
1994 after_message_count: outcome.after_message_count,
1995 })
1996 .collect()
1997 }
1998
1999 /// Authoritative transcript when API messages exist, otherwise the visible
2000 /// history fallback (D3 precedence).
2001 fn project_transcript(app: &App) -> TranscriptProjection {
2002 if app.api_messages.is_empty() {
2003 TranscriptProjection::HistoryFallback(
2004 app.history.iter().map(project_history_cell).collect(),
2005 )
2006 } else {
2007 TranscriptProjection::Authoritative(app.api_messages.iter().map(project_message).collect())
2008 }
2009 }
2010
2011 fn project_message(message: &Message) -> ExportMessage {
2012 let meta_index = codewhale_models::turn_classify::turn_metadata_text(message)
2013 .filter(|_| message.role == codewhale_models::Role::User)
2014 .map(|(index, _)| index);
2015 ExportMessage {
2016 role: message.role.as_str().to_string(),
2017 // Exact enum identity, not a string comparison: `Role::Unrecognized("user")`
2018 // must not be treated as a user turn (baseline parity, F6).
2019 is_user_role: message.role == codewhale_models::Role::User,
2020 blocks: message
2021 .content
2022 .iter()
2023 .enumerate()
2024 .filter(|(index, _)| Some(*index) != meta_index)
2025 .map(|(_, block)| project_block(block))
2026 .collect(),
2027 prompt_snippet: first_text_block(message)
2028 .and_then(codewhale_engine::core::turn::snapshot_label_prompt_snippet),
2029 }
2030 }
2031
2032 fn first_text_block(message: &Message) -> Option<&str> {
2033 message.content.iter().find_map(|block| match block {
2034 ContentBlock::Text { text, .. } => Some(text.as_str()),
2035 _ => None,
2036 })
2037 }
2038
2039 /// Project one content block; hidden payloads become typed omission markers
2040 /// (D9) and never cross the boundary.
2041 fn project_block(block: &ContentBlock) -> ExportBlock {
2042 match block {
2043 ContentBlock::Text { text, .. } => ExportBlock::Text { text: text.clone() },
2044 ContentBlock::ImageUrl { image_url } => {
2045 if image_url.url.starts_with("http://") || image_url.url.starts_with("https://") {
2046 ExportBlock::ImageReference {
2047 url: image_url.url.clone(),
2048 }
2049 } else {
2050 ExportBlock::ImageOmitted
2051 }
2052 }
2053 ContentBlock::Thinking { .. } => ExportBlock::InternalReasoning,
2054 ContentBlock::ToolUse {
2055 id,
2056 name,
2057 input,
2058 caller,
2059 ..
2060 } => ExportBlock::ToolCall {
2061 id: id.clone(),
2062 name: name.clone(),
2063 caller: caller.as_ref().map(|caller| ToolCallerProjection {
2064 caller_type: caller.caller_type.clone(),
2065 tool_id: caller.tool_id.clone(),
2066 }),
2067 input: input.clone(),
2068 },
2069 ContentBlock::ToolResult {
2070 tool_use_id,
2071 content,
2072 is_error,
2073 content_blocks,
2074 ..
2075 } => ExportBlock::ToolResult {
2076 tool_use_id: tool_use_id.clone(),
2077 content: content.clone(),
2078 is_error: is_error.unwrap_or(false),
2079 structured: content_blocks.as_deref().map(|blocks| {
2080 serde_json::Value::Array(
2081 codewhale_engine::image_attach::safe_tool_result_content_blocks(Some(blocks))
2082 .unwrap_or_default(),
2083 )
2084 }),
2085 },
2086 ContentBlock::ServerToolUse {
2087 id, name, input, ..
2088 } => ExportBlock::ServerToolCall {
2089 id: id.clone(),
2090 name: name.clone(),
2091 input: input.clone(),
2092 },
2093 ContentBlock::ToolSearchToolResult {
2094 tool_use_id,
2095 content,
2096 }
2097 | ContentBlock::WebSearchToolResult {
2098 tool_use_id,
2099 content,
2100 ..
2101 } => ExportBlock::ToolSearchResult {
2102 tool_use_id: tool_use_id.clone(),
2103 content: content.clone(),
2104 },
2105 ContentBlock::CodeExecutionToolResult {
2106 tool_use_id,
2107 content,
2108 }
2109 | ContentBlock::WebFetchToolResult {
2110 tool_use_id,
2111 content,
2112 ..
2113 } => ExportBlock::CodeExecutionResult {
2114 tool_use_id: tool_use_id.clone(),
2115 content: content.clone(),
2116 },
2117 ContentBlock::WebSearchCall {
2118 id,
2119 kind,
2120 action,
2121 sources,
2122 page,
2123 ..
2124 } => ExportBlock::ServerToolCall {
2125 id: id.clone(),
2126 name: kind
2127 .clone()
2128 .unwrap_or_else(|| "web_search_call".to_string()),
2129 input: serde_json::json!({ "action": action, "sources": sources, "page": page }),
2130 },
2131 ContentBlock::ServerToolCalls { steps } => ExportBlock::ServerToolCall {
2132 id: String::new(),
2133 name: "server_tool_calls".to_string(),
2134 input: serde_json::Value::Array(steps.clone()),
2135 },
2136 ContentBlock::File { file_id } => ExportBlock::Text {
2137 text: format!("[file: {file_id}]"),
2138 },
2139 }
2140 }
2141
2142 fn project_history_cell(cell: &HistoryCell) -> HistoryEntry {
2143 match cell {
2144 HistoryCell::User { content } => HistoryEntry::Sanitized {
2145 role: "user".to_string(),
2146 body: content.clone(),
2147 },
2148 HistoryCell::Assistant { content, .. } => HistoryEntry::Sanitized {
2149 role: "assistant".to_string(),
2150 body: content.clone(),
2151 },
2152 HistoryCell::System { .. } => HistoryEntry::Literal {
2153 role: "system".to_string(),
2154 body: "[internal context omitted]".to_string(),
2155 },
2156 HistoryCell::Error {
2157 message,
2158 severity,
2159 code,
2160 } => HistoryEntry::Sanitized {
2161 role: error_severity_role(*severity).to_string(),
2162 body: match crate::tui::history::display_error_code(message, code.as_deref()) {
2163 Some(code) => format!("[{code}] {message}"),
2164 None => message.clone(),
2165 },
2166 },
2167 HistoryCell::Thinking { .. } => HistoryEntry::Literal {
2168 role: "internal reasoning".to_string(),
2169 body: "[internal reasoning omitted]".to_string(),
2170 },
2171 HistoryCell::Tool(tool) => HistoryEntry::Sanitized {
2172 role: "tool".to_string(),
2173 body: flatten_history_lines(tool.lines(120)),
2174 },
2175 HistoryCell::SubAgent(subagent) => HistoryEntry::Sanitized {
2176 role: "sub-agent".to_string(),
2177 body: flatten_history_lines(subagent.lines(120)),
2178 },
2179 HistoryCell::Automation(cell) => HistoryEntry::Sanitized {
2180 role: "automation".to_string(),
2181 body: flatten_history_lines(cell.render(120)),
2182 },
2183 HistoryCell::ApprovalReceipt(cell) => HistoryEntry::Sanitized {
2184 role: "approval".to_string(),
2185 body: cell.plain_summary(),
2186 },
2187 HistoryCell::ArchivedContext {
2188 level,
2189 range,
2190 summary,
2191 ..
2192 } => HistoryEntry::Sanitized {
2193 role: "archived context".to_string(),
2194 body: format!("L{level} [{range}]: {summary}"),
2195 },
2196 }
2197 }
2198
2199 fn error_severity_role(severity: codewhale_error_taxonomy::ErrorSeverity) -> &'static str {
2200 match severity {
2201 codewhale_error_taxonomy::ErrorSeverity::Info => "info",
2202 codewhale_error_taxonomy::ErrorSeverity::Warning => "warning",
2203 codewhale_error_taxonomy::ErrorSeverity::Error => "error",
2204 codewhale_error_taxonomy::ErrorSeverity::Critical => "critical error",
2205 }
2206 }
2207
2208 /// Flatten host UI lines/spans to plain text, preserving the baseline width
2209 /// and joining behavior (D3). UI rendering stays behind the adapter.
2210 fn flatten_history_lines(lines: Vec<ratatui::text::Line<'static>>) -> String {
2211 lines
2212 .into_iter()
2213 .map(|line| {
2214 line.spans
2215 .into_iter()
2216 .map(|span| span.content.to_string())
2217 .collect::<String>()
2218 })
2219 .collect::<Vec<_>>()
2220 .join("\n")
2221 }
2222
2223 /// Read the workspace snapshot repository read-only and project its state
2224 /// (D8): only an existing repo is opened, never created.
2225 fn project_restore_points(workspace: &Path) -> RestorePointProjection {
2226 match codewhale_snapshot::SnapshotRepo::open_existing(workspace) {
2227 Ok(None) => RestorePointProjection::None,
2228 Err(err) => RestorePointProjection::Unreadable {
2229 reason: err.to_string(),
2230 },
2231 Ok(Some(repo)) => match repo.list(RESTORE_POINT_SUMMARY_MAX) {
2232 Ok(snapshots) => RestorePointProjection::Recorded {
2233 snapshots: snapshots.iter().map(project_restore_snapshot).collect(),
2234 },
2235 Err(err) => RestorePointProjection::Unreadable {
2236 reason: err.to_string(),
2237 },
2238 },
2239 }
2240 }
2241
2242 fn project_restore_snapshot(snapshot: &codewhale_snapshot::Snapshot) -> RestoreSnapshot {
2243 let parsed = codewhale_engine::core::turn::parse_snapshot_label(&snapshot.label);
2244 RestoreSnapshot {
2245 id: snapshot.id.as_str().to_string(),
2246 label: snapshot.label.clone(),
2247 timestamp_unix: snapshot.timestamp,
2248 kind: parsed.kind,
2249 sequence: parsed.seq,
2250 prompt_snippet: parsed.prompt_snippet,
2251 }
2252 }
2253
2254 /// Session identity, messages, queue operations, and token totals.
2255 pub(crate) struct SessionAdapter<'a> {
2256 host: SharedCommandHost<'a>,
2257 }
2258
2259 impl CommandSessionContext for SessionAdapter<'_> {
2260 fn session_id(&self) -> Option<String> {
2261 self.host.app.borrow().current_session_id.clone()
2262 }
2263
2264 fn api_messages(&self) -> Vec<Message> {
2265 self.host.app.borrow().api_messages.as_ref().clone()
2266 }
2267
2268 fn add_message(&mut self, message: Message) {
2269 self.host.app.borrow_mut().push_api_message(message);
2270 }
2271
2272 fn queued_message_count(&self) -> usize {
2273 self.host.app.borrow().queued_message_count()
2274 }
2275
2276 fn remove_queued_message(&mut self, index: usize) -> Result<(), String> {
2277 self.host
2278 .app
2279 .borrow_mut()
2280 .remove_queued_message(index)
2281 .map(|_| ())
2282 .ok_or_else(|| format!("queued message index {index} out of bounds"))
2283 }
2284
2285 fn total_tokens(&self) -> u64 {
2286 u64::from(self.host.app.borrow().session.total_tokens)
2287 }
2288 }
2289
2290 /// Model selection, provider identity, effort, and fallback chain.
2291 pub(crate) struct ModelAdapter<'a> {
2292 host: SharedCommandHost<'a>,
2293 }
2294
2295 impl CommandModelContext for ModelAdapter<'_> {
2296 fn current_model(&self) -> String {
2297 self.host.app.borrow().model.clone()
2298 }
2299
2300 fn auto_model(&self) -> bool {
2301 self.host.app.borrow().auto_model
2302 }
2303
2304 fn set_model_selection(&mut self, model: String, provider: Option<CommandProviderId>) {
2305 let mut app = self.host.app.borrow_mut();
2306 let admission = (|| {
2307 let config = self.host.config.ok_or_else(|| {
2308 "The model command has no active provider configuration.".to_string()
2309 })?;
2310 let identity = match provider {
2311 Some(provider) => {
2312 let identity = config.resolve_provider_identity(&provider.0)?;
2313 if identity.key.as_str() != provider.0 {
2314 return Err(
2315 "The model command must name the exact admitted provider route."
2316 .to_string(),
2317 );
2318 }
2319 identity
2320 }
2321 None => app.admitted_provider_identity()?.clone(),
2322 };
2323 config.verify_provider_identity(&identity)?;
2324 Ok(identity)
2325 })();
2326 let identity = match admission {
2327 Ok(identity) => identity,
2328 Err(reason) => {
2329 app.push_status_toast(
2330 reason,
2331 crate::tui::app::StatusToastLevel::Error,
2332 Some(8_000),
2333 );
2334 return;
2335 }
2336 };
2337 app.set_provider_identity_record(identity);
2338 app.set_model_selection(model);
2339 }
2340
2341 fn provider_identity(&self) -> Option<CommandProviderId> {
2342 let app = self.host.app.borrow();
2343 let identity = app.provider_identity_for_persistence();
2344 (!identity.trim().is_empty()).then(|| to_provider_id(identity))
2345 }
2346
2347 fn fallback_chain(&self) -> Vec<CommandProviderId> {
2348 self.host
2349 .app
2350 .borrow()
2351 .fallback_chain_entries()
2352 .into_iter()
2353 .map(|(_, provider, _)| to_provider_id(provider.as_str()))
2354 .collect()
2355 }
2356 }
2357
2358 /// Cost display and accounting operations delegated to App's cost authority.
2359 pub(crate) struct CostAdapter<'a> {
2360 host: SharedCommandHost<'a>,
2361 }
2362
2363 fn command_cost_estimate(
2364 amount: f64,
2365 currency: CommandCurrency,
2366 ) -> codewhale_engine::pricing::CostEstimate {
2367 match currency {
2368 CommandCurrency::Usd => codewhale_engine::pricing::CostEstimate {
2369 usd: amount,
2370 cny: 0.0,
2371 },
2372 CommandCurrency::Cny => codewhale_engine::pricing::CostEstimate {
2373 usd: 0.0,
2374 cny: amount,
2375 },
2376 }
2377 }
2378
2379 impl CommandCostContext for CostAdapter<'_> {
2380 fn display_currency(&self) -> CommandCurrency {
2381 let app = self.host.app.borrow();
2382 to_command_currency(app.cost_display_currency(app.cost_currency))
2383 }
2384
2385 fn session_cost_for_currency(&self, currency: CommandCurrency) -> f64 {
2386 self.host
2387 .app
2388 .borrow()
2389 .session_cost_for_currency(from_command_currency(currency))
2390 }
2391
2392 fn subagent_cost_for_currency(&self, currency: CommandCurrency) -> f64 {
2393 self.host
2394 .app
2395 .borrow()
2396 .subagent_cost_for_currency(from_command_currency(currency))
2397 }
2398
2399 fn accrue_cost_estimate(&mut self, amount: f64, currency: CommandCurrency) {
2400 self.host
2401 .app
2402 .borrow_mut()
2403 .accrue_session_cost_estimate(command_cost_estimate(amount, currency));
2404 }
2405
2406 fn record_turn_cost(
2407 &mut self,
2408 amount: f64,
2409 currency: CommandCurrency,
2410 route_receipt: Option<String>,
2411 ) {
2412 let mut app = self.host.app.borrow_mut();
2413 app.accrue_session_cost_estimate(command_cost_estimate(amount, currency));
2414 if let Some(receipt) = route_receipt {
2415 app.record_turn_cost_route_receipt(receipt);
2416 }
2417 }
2418 }
2419
2420 /// Operating mode, approval posture, shell access, and policy lock.
2421 pub(crate) struct ModePolicyAdapter<'a> {
2422 host: SharedCommandHost<'a>,
2423 }
2424
2425 impl CommandModePolicyContext for ModePolicyAdapter<'_> {
2426 fn mode(&self) -> CommandMode {
2427 to_command_mode(self.host.app.borrow().mode)
2428 }
2429
2430 fn set_mode(&mut self, mode: CommandMode) {
2431 self.host.app.borrow_mut().set_mode(from_command_mode(mode));
2432 }
2433
2434 fn approval_mode(&self) -> CommandApprovalMode {
2435 to_command_approval(self.host.app.borrow().approval_mode)
2436 }
2437
2438 fn allow_shell(&self) -> bool {
2439 self.host.app.borrow().allow_shell
2440 }
2441
2442 fn set_shell_access(&mut self, allow: bool) {
2443 self.host.app.borrow_mut().set_agent_shell_access(allow);
2444 }
2445
2446 fn policy_locked(&self) -> bool {
2447 self.host.app.borrow().approval_policy_locked()
2448 }
2449
2450 fn select_mode(
2451 &mut self,
2452 mode: CommandMode,
2453 ) -> codewhale_command_contract::facets::CommandModeSelection {
2454 use codewhale_command_contract::facets::CommandModeSelection;
2455 match self
2456 .host
2457 .app
2458 .borrow_mut()
2459 .select_mode(from_command_mode(mode))
2460 {
2461 crate::tui::app::SettingSelection::Changed => CommandModeSelection::Changed,
2462 crate::tui::app::SettingSelection::PersistedSame => CommandModeSelection::PersistedSame,
2463 crate::tui::app::SettingSelection::Refused => CommandModeSelection::Refused,
2464 }
2465 }
2466
2467 fn mode_startup_default_receipt(&self, mode: CommandMode) -> String {
2468 self.host
2469 .app
2470 .borrow()
2471 .mode_startup_default_receipt(from_command_mode(mode))
2472 }
2473
2474 fn setting_locked_mode_message(&self) -> String {
2475 self.host
2476 .app
2477 .borrow()
2478 .setting_locked_message(MessageId::SettingSubjectMode)
2479 }
2480
2481 fn mode_label(&self, mode: CommandMode) -> String {
2482 use crate::tui::app::AppModeUi;
2483 let locale = self.host.app.borrow().ui_locale;
2484 from_command_mode(mode)
2485 .display_name_localized(locale)
2486 .to_string()
2487 }
2488 }
2489
2490 /// Read access to the effective system prompt.
2491 pub(crate) struct SystemPromptAdapter<'a> {
2492 host: SharedCommandHost<'a>,
2493 }
2494
2495 impl CommandSystemPromptContext for SystemPromptAdapter<'_> {
2496 fn system_prompt(&self) -> Option<SystemPrompt> {
2497 self.host.app.borrow().system_prompt.clone()
2498 }
2499 }
2500
2501 /// Active skill identity and authoritative skill-cache refresh.
2502 pub(crate) struct SkillsAdapter<'a> {
2503 host: SharedCommandHost<'a>,
2504 }
2505
2506 impl CommandSkillsContext for SkillsAdapter<'_> {
2507 fn active_skill(&self) -> Option<String> {
2508 self.host.app.borrow().active_skill.clone()
2509 }
2510
2511 fn active_skill_provenance(&self) -> Option<String> {
2512 self.host
2513 .app
2514 .borrow()
2515 .active_skill_provenance
2516 .as_ref()
2517 .map(|provenance| provenance.authority().plugin_name.clone())
2518 }
2519
2520 fn refresh_skill_cache(&mut self) {
2521 self.host.app.borrow_mut().refresh_skill_cache();
2522 }
2523 }
2524
2525 /// Workspace observations and confined anchor operations.
2526 pub(crate) struct WorkspaceAdapter<'a> {
2527 host: SharedCommandHost<'a>,
2528 }
2529
2530 impl CommandWorkspaceContext for WorkspaceAdapter<'_> {
2531 fn workspace(&self) -> PathBuf {
2532 self.host.app.borrow().workspace.clone()
2533 }
2534
2535 fn effective_home_dir(&self) -> Option<PathBuf> {
2536 codewhale_paths::user_home()
2537 }
2538
2539 fn inspect_workspace_target(
2540 &self,
2541 candidate: &Path,
2542 ) -> codewhale_command_contract::navigation::WorkspaceTarget {
2543 use codewhale_command_contract::navigation::WorkspaceTarget;
2544 match candidate.metadata() {
2545 Ok(metadata) if metadata.is_file() => WorkspaceTarget::File,
2546 Ok(metadata) if metadata.is_dir() => WorkspaceTarget::Directory {
2547 canonical_or_candidate: candidate
2548 .canonicalize()
2549 .unwrap_or_else(|_| candidate.to_owned()),
2550 },
2551 Ok(_) => WorkspaceTarget::NotDirectory,
2552 Err(_) => WorkspaceTarget::Missing,
2553 }
2554 }
2555
2556 fn read_anchor_document(&self) -> Result<Option<String>, String> {
2557 core_navigation::read_anchor_document(&self.workspace())
2558 }
2559
2560 fn append_anchor_bytes(
2561 &mut self,
2562 parts: &[&[u8]],
2563 ) -> Result<PathBuf, codewhale_command_contract::navigation::AnchorWriteError> {
2564 core_navigation::append_anchor_bytes(&self.workspace(), parts)
2565 }
2566
2567 fn replace_anchor_document(&mut self, bytes: &[u8]) -> Result<(), String> {
2568 core_navigation::replace_anchor_document(&self.workspace(), bytes)
2569 }
2570
2571 fn work_state_snapshot(&self) -> Result<Option<String>, String> {
2572 self.host.app.borrow().work_state_snapshot().map(|state| {
2573 state
2574 .and_then(|state| codewhale_engine::todo_snapshot::todo_snapshot_body(&state.todos))
2575 })
2576 }
2577
2578 fn operation_digest(&mut self) -> Result<String, String> {
2579 let app = self.host.app.borrow();
2580 let Some(work) = app.runtime_services.work.as_ref() else {
2581 return Ok("No active operations or to-do items.".to_string());
2582 };
2583 match work.capture(app.current_session_id.as_deref()) {
2584 Ok(snapshot) => Ok(codewhale_engine::work_graph::format_operation_digest(
2585 snapshot.as_ref(),
2586 )),
2587 Err(error) => Err(format!(
2588 "Operation digest is temporarily unavailable: {error}"
2589 )),
2590 }
2591 }
2592 }
2593
2594 /// Stable-key translation adapter (FEAT-018 D3).
2595 ///
2596 /// Maps stable snake_case utility message keys to the current catalog and
2597 /// preserves the existing English fallback for intentionally incomplete locale
2598 /// packs. Unknown keys and invalid replacement contracts fail safely; a raw
2599 /// lookup key is never exposed.
2600 pub(crate) struct PresentationAdapter<'a> {
2601 host: SharedCommandHost<'a>,
2602 }
2603
2604 /// Resolve one stable key to the current catalog id, in the order every host
2605 /// adapter must use. Kept in one place so the terminal host and the remote
2606 /// snapshot-backed adapter cannot answer the same key differently.
2607 pub(crate) fn resolve_message_id(key: &str) -> Option<MessageId> {
2608 key_to_utility_message_id(key)
2609 .or_else(|| key_to_project_message_id(key))
2610 .or_else(|| key_to_plugin_message_id(key))
2611 .or_else(|| key_to_session_message_id(key))
2612 .or_else(|| codewhale_engine::diagnostics_messages::resolve(key))
2613 .or_else(|| config_policy_messages::resolve(key))
2614 .or_else(|| config_messages::resolve(key))
2615 .or_else(|| core_navigation::resolve_message(key))
2616 .or_else(|| core_policy::resolve_message(key))
2617 }
2618
2619 impl CommandPresentationContext for PresentationAdapter<'_> {
2620 fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> {
2621 let Some(message_id) = resolve_message_id(key) else {
2622 return Err("unknown translation key".to_string());
2623 };
2624 let locale = self.host.app.borrow().ui_locale;
2625 let template = tr(locale, message_id);
2626 apply_named_replacements(&template, replacements)
2627 .ok_or_else(|| "invalid translation replacement contract".to_string())
2628 }
2629
2630 fn language_name(&self) -> &'static str {
2631 self.host.app.borrow().ui_locale.translation_target_name()
2632 }
2633 }
2634
2635 /// Resolve session-control and structural-copy runtime keys to the current
2636 /// catalog. Other session commands retain metadata-only localization.
2637 pub(crate) fn key_to_session_message_id(key: &str) -> Option<MessageId> {
2638 Some(match key {
2639 "cmd_structcopy_kind_turn" => MessageId::CmdStructcopyKindTurn,
2640 "cmd_structcopy_kind_tool" => MessageId::CmdStructcopyKindTool,
2641 "cmd_structcopy_kind_plan" => MessageId::CmdStructcopyKindPlan,
2642 "cmd_structcopy_kind_workflow" => MessageId::CmdStructcopyKindWorkflow,
2643 "cmd_structcopy_usage_error" => MessageId::CmdStructcopyUsageError,
2644 "cmd_structcopy_unavailable" => MessageId::CmdStructcopyUnavailable,
2645 "cmd_structcopy_busy" => MessageId::CmdStructcopyBusy,
2646 "cmd_structcopy_prepare_failed" => MessageId::CmdStructcopyPrepareFailed,
2647 "cmd_structcopy_receipt_too_large" => MessageId::CmdStructcopyReceiptTooLarge,
2648 "cmd_structcopy_clipboard_queued" => MessageId::CmdStructcopyClipboardQueued,
2649 "cmd_structcopy_clipboard_accepted" => MessageId::CmdStructcopyClipboardAccepted,
2650 "cmd_structcopy_clipboard_failed" => MessageId::CmdStructcopyClipboardFailed,
2651 "cmd_remote_env_overview" => MessageId::CmdRemoteEnvOverview,
2652 "cmd_remote_env_opening" => MessageId::CmdRemoteEnvOpening,
2653 "cmd_remote_env_unavailable" => MessageId::CmdRemoteEnvUnavailable,
2654 "cmd_remote_env_source_custody_policy" => MessageId::CmdRemoteEnvSourceCustodyPolicy,
2655 "cmd_remote_env_browser_label" => MessageId::CmdRemoteEnvBrowserLabel,
2656 "cmd_color_set" => MessageId::CmdColorSet,
2657 "cmd_color_reset" => MessageId::CmdColorReset,
2658 "cmd_color_unknown" => MessageId::CmdColorUnknown,
2659 _ => return None,
2660 })
2661 }
2662
2663 /// Resolve a stable plugin message key to the current catalog id (FEAT-020 D5).
2664 ///
2665 /// Every plugin-group catalog message uses a stable snake_case key; the TUI
2666 /// adapter maps it to the current `MessageId` value and preserves the
2667 /// authoritative English fallback. Unknown keys fail safely.
2668 pub(crate) fn key_to_plugin_message_id(key: &str) -> Option<MessageId> {
2669 Some(match key {
2670 "cmd_plugin_action_failed" => MessageId::CmdPluginActionFailed,
2671 "cmd_plugin_audit_agent_process_note" => MessageId::CmdPluginAuditAgentProcessNote,
2672 "cmd_plugin_audit_approved_date" => MessageId::CmdPluginAuditApprovedDate,
2673 "cmd_plugin_audit_reach_here" => MessageId::CmdPluginAuditReachHere,
2674 "cmd_plugin_audit_reach_only_in" => MessageId::CmdPluginAuditReachOnlyIn,
2675 "cmd_plugin_audit_service_can_use" => MessageId::CmdPluginAuditServiceCanUse,
2676 "cmd_plugin_audit_service_not_offered" => MessageId::CmdPluginAuditServiceNotOffered,
2677 "cmd_plugin_audit_service_withheld_many" => MessageId::CmdPluginAuditServiceWithheldMany,
2678 "cmd_plugin_audit_service_withheld_one" => MessageId::CmdPluginAuditServiceWithheldOne,
2679 "extensions_trust_not_reviewed" => MessageId::ExtensionsTrustNotReviewed,
2680 "cmd_plugin_bundle_detail" => MessageId::CmdPluginBundleDetail,
2681 "cmd_plugin_owner_report" => MessageId::CmdPluginOwnerReport,
2682 "cmd_plugin_owner_activating" => MessageId::CmdPluginOwnerActivating,
2683 "cmd_plugin_owner_active" => MessageId::CmdPluginOwnerActive,
2684 "cmd_plugin_owner_failed" => MessageId::CmdPluginOwnerFailed,
2685 "cmd_plugin_owner_faulted" => MessageId::CmdPluginOwnerFaulted,
2686 "cmd_plugin_owner_revoked" => MessageId::CmdPluginOwnerRevoked,
2687 "cmd_plugin_owner_inactive" => MessageId::CmdPluginOwnerInactive,
2688 "cmd_plugin_bundle_diagnostics_header" => MessageId::CmdPluginBundleDiagnosticsHeader,
2689 "cmd_plugin_bundle_list_header" => MessageId::CmdPluginBundleListHeader,
2690 "cmd_plugin_bundle_mutation_success" => MessageId::CmdPluginBundleMutationSuccess,
2691 "cmd_plugin_bundle_none_found" => MessageId::CmdPluginBundleNoneFound,
2692 "cmd_plugin_bundle_not_found" => MessageId::CmdPluginBundleNotFound,
2693 "cmd_plugin_bundle_reloaded" => MessageId::CmdPluginBundleReloaded,
2694 "cmd_plugin_bundle_usage" => MessageId::CmdPluginBundleUsage,
2695 "cmd_plugin_detail_description" => MessageId::CmdPluginDetailDescription,
2696 "cmd_plugin_detail_approval" => MessageId::CmdPluginDetailApproval,
2697 "cmd_plugin_detail_path" => MessageId::CmdPluginDetailPath,
2698 "cmd_plugin_detail_schema" => MessageId::CmdPluginDetailSchema,
2699 "cmd_plugin_legacy_list_header" => MessageId::CmdPluginLegacyListHeader,
2700 "cmd_plugin_none_found" => MessageId::CmdPluginNoneFound,
2701 "cmd_plugin_not_found" => MessageId::CmdPluginNotFound,
2702 "plugin_kimi_applicable" => MessageId::PluginKimiApplicable,
2703 "plugin_kimi_candidate_changed" => MessageId::PluginKimiCandidateChanged,
2704 "plugin_kimi_candidate_details" => MessageId::PluginKimiCandidateDetails,
2705 "plugin_kimi_candidate_missing" => MessageId::PluginKimiCandidateMissing,
2706 "plugin_kimi_candidate_summary" => MessageId::PluginKimiCandidateSummary,
2707 "plugin_kimi_directory_name_mismatch" => MessageId::PluginKimiDirectoryNameMismatch,
2708 "plugin_kimi_entry_canonicalize_failed" => MessageId::PluginKimiEntryCanonicalizeFailed,
2709 "plugin_kimi_entry_inspect_failed" => MessageId::PluginKimiEntryInspectFailed,
2710 "plugin_kimi_entry_limit" => MessageId::PluginKimiEntryLimit,
2711 "plugin_kimi_entry_links_refused" => MessageId::PluginKimiEntryLinksRefused,
2712 "plugin_kimi_entry_outside_root" => MessageId::PluginKimiEntryOutsideRoot,
2713 "plugin_kimi_entry_read_failed" => MessageId::PluginKimiEntryReadFailed,
2714 "plugin_kimi_hash_unavailable" => MessageId::PluginKimiHashUnavailable,
2715 "plugin_kimi_home_missing" => MessageId::PluginKimiHomeMissing,
2716 "plugin_kimi_inspection_footer" => MessageId::PluginKimiInspectionFooter,
2717 "plugin_kimi_license_unspecified" => MessageId::PluginKimiLicenseUnspecified,
2718 "plugin_kimi_managed_root_heading" => MessageId::PluginKimiManagedRootHeading,
2719 "plugin_kimi_manifest_invalid" => MessageId::PluginKimiManifestInvalid,
2720 "plugin_kimi_manifest_must_be_file" => MessageId::PluginKimiManifestMustBeFile,
2721 "plugin_kimi_manifest_unreadable" => MessageId::PluginKimiManifestUnreadable,
2722 "plugin_kimi_marketplace_gzip_tarball" => MessageId::PluginKimiMarketplaceGzipTarball,
2723 "kimi_zip_unsupported" => MessageId::PluginKimiMarketplaceZipUnsupported,
2724 "kimi_remote_archive_unsupported" => MessageId::PluginKimiMarketplaceRemoteUnsupported,
2725 "kimi_gzip_tarball_url" => MessageId::PluginKimiMarketplaceGzipTarball,
2726 "plugin_kimi_marketplace_remote_unsupported" => {
2727 MessageId::PluginKimiMarketplaceRemoteUnsupported
2728 }
2729 "plugin_kimi_marketplace_zip_unsupported" => MessageId::PluginKimiMarketplaceZipUnsupported,
2730 "plugin_kimi_mismatch_removed" => MessageId::PluginKimiMismatchRemoved,
2731 "plugin_kimi_mismatch_rollback_failed" => MessageId::PluginKimiMismatchRollbackFailed,
2732 "plugin_kimi_none_found" => MessageId::PluginKimiNoneFound,
2733 "plugin_kimi_not_applicable" => MessageId::PluginKimiNotApplicable,
2734 "plugin_kimi_rejected_heading" => MessageId::PluginKimiRejectedHeading,
2735 "plugin_kimi_rollback_destination_missing" => {
2736 MessageId::PluginKimiRollbackDestinationMissing
2737 }
2738 "plugin_kimi_root_canonicalize_failed" => MessageId::PluginKimiRootCanonicalizeFailed,
2739 "plugin_kimi_root_inspect_failed" => MessageId::PluginKimiRootInspectFailed,
2740 "plugin_kimi_root_list_failed" => MessageId::PluginKimiRootListFailed,
2741 "plugin_kimi_root_must_be_directory" => MessageId::PluginKimiRootMustBeDirectory,
2742 "plugin_kimi_usage" => MessageId::PluginKimiUsage,
2743 "plugin_kimi_user_plugin_directory" => MessageId::PluginKimiUserPluginDirectory,
2744 _ => return None,
2745 })
2746 }
2747
2748 /// Resolve a stable utility message key to the current catalog id.
2749 fn key_to_utility_message_id(key: &str) -> Option<MessageId> {
2750 Some(match key {
2751 "auto_receipt_on" => MessageId::AutoReceiptOn,
2752 "auto_receipt_plan_note" => MessageId::AutoReceiptPlanNote,
2753 "auto_receipt_broad_allows_paused" => MessageId::AutoReceiptBroadAllowsPaused,
2754 "automation_usage" => MessageId::AutomationUsage,
2755 "mcp_recommended_unknown_id" => MessageId::McpRecommendedUnknownId,
2756 "mcp_recommendations_heading" => MessageId::McpRecommendationsHeading,
2757 "mcp_recommendations_safety" => MessageId::McpRecommendationsSafety,
2758 "mcp_recommendation_github" => MessageId::McpRecommendationGithub,
2759 "mcp_recommendation_chrome" => MessageId::McpRecommendationChrome,
2760 "mcp_recommendation_playwright" => MessageId::McpRecommendationPlaywright,
2761 "mcp_recommendation_container_use" => MessageId::McpRecommendationContainerUse,
2762 _ => return None,
2763 })
2764 }
2765
2766 /// Resolve a stable project message key to the current catalog id (FEAT-021 D5).
2767 ///
2768 /// Only `/goal` uses runtime translations (`GoalControlAccepted`,
2769 /// `GoalStatusIdleHint`); all four description keys resolve through the
2770 /// metadata bridge (`key_to_message_id`) and do not require the presentation
2771 /// facet.
2772 pub(crate) fn key_to_project_message_id(key: &str) -> Option<MessageId> {
2773 Some(match key {
2774 "goal_control_accepted" => MessageId::GoalControlAccepted,
2775 "goal_status_idle_hint" => MessageId::GoalStatusIdleHint,
2776 _ => return None,
2777 })
2778 }
2779
2780 pub(in crate::commands) use codewhale_engine::diagnostics_messages::apply_named_replacements;
2781
2782 /// Atomic composer/media adapter (FEAT-018 D4).
2783 ///
2784 /// Performs media validation and composer insertion as one host operation by
2785 /// delegating to the authoritative image-validation and attachment behavior.
2786 pub(crate) struct MediaAdapter<'a> {
2787 host: SharedCommandHost<'a>,
2788 }
2789
2790 impl CommandMediaContext for MediaAdapter<'_> {
2791 fn attach_media(&mut self, resolved_path: &Path) -> Result<MediaAttachmentReceipt, String> {
2792 let Ok(path) = resolved_path.canonicalize() else {
2793 return Err(format!("Attachment not found: {}", resolved_path.display()));
2794 };
2795 if !path.is_file() {
2796 return Err(format!("Attachment is not a file: {}", path.display()));
2797 }
2798 let Some(kind) = media_kind(&path) else {
2799 return Err(
2800 "Unsupported attachment type. /attach is for image/video paths; use @path for \
2801 text files or directories."
2802 .to_string(),
2803 );
2804 };
2805 if kind == "image"
2806 && let Err(error) = codewhale_engine::image_attach::attach_image_from_path(&path)
2807 {
2808 return Err(error.to_string());
2809 }
2810 let mut app = self.host.app.borrow_mut();
2811 app.insert_media_attachment(kind, &path, None);
2812 Ok(MediaAttachmentReceipt {
2813 kind: kind.to_string(),
2814 path,
2815 })
2816 }
2817 }
2818
2819 /// Classify a media path by extension (image or video).
2820 fn media_kind(path: &Path) -> Option<&'static str> {
2821 let ext = path.extension()?.to_str()?.to_ascii_lowercase();
2822 match ext.as_str() {
2823 "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" | "ppm" => Some("image"),
2824 "mp4" | "mov" | "m4v" | "webm" | "avi" | "mkv" => Some("video"),
2825 _ => None,
2826 }
2827 }
2828
2829 /// Memory host-data adapter (FEAT-019 D1).
2830 ///
2831 /// Derives the authoritative native store exactly like the legacy `/memory`
2832 /// handler (`from_global_path` on the app memory path, falling back to a
2833 /// `memory` root beside it) and converts every host value/error to a portable
2834 /// contract value before it crosses the boundary. All methods are `&self` and
2835 /// borrow `App` only for the duration of one call; workspace state is passed
2836 /// per call and never retained by the facet (D8).
2837 pub(crate) struct MemoryAdapter<'a> {
2838 host: SharedCommandHost<'a>,
2839 }
2840
2841 /// Derive the authoritative native-memory store from the resolved user-memory
2842 /// file path, mirroring the pre-migration `/memory` handler exactly.
2843 fn native_store_from_memory_path(
2844 memory_path: &Path,
2845 ) -> codewhale_runtime::native_memory::NativeMemoryStore {
2846 codewhale_runtime::native_memory::NativeMemoryStore::from_memory_anchor(memory_path)
2847 }
2848
2849 /// Convert a TUI-owned native hit into the portable contract hit. Only the
2850 /// semantic fields the handler consumes for rendering cross the boundary (D2).
2851 fn portable_hit(hit: codewhale_runtime::native_memory::MemoryHit) -> MemoryHit {
2852 MemoryHit {
2853 source: hit.source,
2854 line_start: hit.line_start,
2855 line_end: hit.line_end,
2856 text: hit.text,
2857 }
2858 }
2859
2860 impl CommandMemoryContext for MemoryAdapter<'_> {
2861 fn memory_path(&self) -> PathBuf {
2862 self.host.app.borrow().memory_path.clone()
2863 }
2864
2865 fn memory_enabled(&self) -> bool {
2866 self.host.app.borrow().use_memory
2867 }
2868
2869 fn status(&self) -> Result<MemoryStatus, String> {
2870 let app = self.host.app.borrow();
2871 let store = native_store_from_memory_path(&app.memory_path);
2872 Ok(MemoryStatus {
2873 root: store.root().to_path_buf(),
2874 source: store.global_path(),
2875 index: store.index_path(),
2876 })
2877 }
2878
2879 fn path(&self) -> Result<PathBuf, String> {
2880 let app = self.host.app.borrow();
2881 Ok(native_store_from_memory_path(&app.memory_path)
2882 .root()
2883 .to_path_buf())
2884 }
2885
2886 fn workspace_id(&self, workspace: &Path) -> Result<String, String> {
2887 let workspace = workspace.to_path_buf();
2888 run_owner_blocking(move || {
2889 match codewhale_runtime::native_memory::NativeMemoryStore::workspace_id(&workspace) {
2890 Ok(Some(id)) => Ok(id),
2891 Ok(None) => {
2892 Err("workspace memory requires a git repository with an origin".to_string())
2893 }
2894 Err(err) => Err(format!("failed to resolve workspace identity: {err}")),
2895 }
2896 })
2897 }
2898
2899 fn search(
2900 &self,
2901 workspace: &Path,
2902 query: &str,
2903 limit: usize,
2904 ) -> Result<Vec<MemoryHit>, String> {
2905 let store = {
2906 let app = self.host.app.borrow();
2907 native_store_from_memory_path(&app.memory_path)
2908 };
2909 let workspace = workspace.to_path_buf();
2910 let query = query.to_string();
2911 run_owner_blocking(
2912 move || match store.search_for_workspace(&workspace, &query, limit) {
2913 Ok(hits) => Ok(hits.into_iter().map(portable_hit).collect()),
2914 Err(err) => Err(err.to_string()),
2915 },
2916 )
2917 }
2918
2919 fn remember(
2920 &self,
2921 target: MemoryRememberTarget,
2922 note: &str,
2923 ) -> Result<MemoryRemembered, String> {
2924 let store = {
2925 let app = self.host.app.borrow();
2926 native_store_from_memory_path(&app.memory_path)
2927 };
2928 let (scope, workspace_id) = match target {
2929 MemoryRememberTarget::Global => {
2930 (codewhale_runtime::native_memory::MemoryScope::Global, None)
2931 }
2932 MemoryRememberTarget::Workspace { workspace_id } => (
2933 codewhale_runtime::native_memory::MemoryScope::Workspace,
2934 Some(workspace_id),
2935 ),
2936 };
2937 let note = note.to_string();
2938 run_owner_blocking(move || {
2939 match store.remember_reviewed(scope, workspace_id.as_deref(), &note) {
2940 Ok(hit) => Ok(MemoryRemembered {
2941 source: hit.source,
2942 line_start: hit.line_start,
2943 }),
2944 Err(err) => Err(err.to_string()),
2945 }
2946 })
2947 }
2948
2949 fn import(&self) -> Result<MemoryImportOutcome, String> {
2950 let (store, legacy_path) = {
2951 let app = self.host.app.borrow();
2952 let store = native_store_from_memory_path(&app.memory_path);
2953 let legacy_path = store
2954 .root()
2955 .parent()
2956 .map(|parent| parent.join("memory.md"))
2957 .unwrap_or_else(|| app.memory_path.clone());
2958 (store, legacy_path)
2959 };
2960 run_owner_blocking(move || match store.import_legacy(&legacy_path) {
2961 Ok(true) => Ok(MemoryImportOutcome::Imported {
2962 destination: store.global_path(),
2963 }),
2964 Ok(false) => Ok(MemoryImportOutcome::Skipped),
2965 Err(err) => Err(err.to_string()),
2966 })
2967 }
2968
2969 fn get(&self, workspace: &Path, id: i64) -> Result<MemoryGetOutcome, String> {
2970 let store = {
2971 let app = self.host.app.borrow();
2972 native_store_from_memory_path(&app.memory_path)
2973 };
2974 let workspace = workspace.to_path_buf();
2975 run_owner_blocking(move || match store.get_for_workspace(&workspace, id) {
2976 Ok(Some(hit)) => Ok(MemoryGetOutcome::Found(portable_hit(hit))),
2977 Ok(None) => Ok(MemoryGetOutcome::NotFound),
2978 Err(err) => Err(err.to_string()),
2979 })
2980 }
2981
2982 fn export(&self) -> Result<MemoryExport, String> {
2983 let store = {
2984 let app = self.host.app.borrow();
2985 native_store_from_memory_path(&app.memory_path)
2986 };
2987 run_owner_blocking(move || match store.export() {
2988 Ok(content) => Ok(MemoryExport { content }),
2989 Err(err) => Err(err.to_string()),
2990 })
2991 }
2992
2993 fn reindex(&self) -> Result<MemoryReindex, String> {
2994 let store = {
2995 let app = self.host.app.borrow();
2996 native_store_from_memory_path(&app.memory_path)
2997 };
2998 run_owner_blocking(move || match store.reindex() {
2999 Ok(entry_count) => Ok(MemoryReindex { entry_count }),
3000 Err(err) => Err(err.to_string()),
3001 })
3002 }
3003
3004 fn delete(&self, scope: MemoryDeleteScope) -> Result<MemoryDelete, String> {
3005 let store = {
3006 let app = self.host.app.borrow();
3007 native_store_from_memory_path(&app.memory_path)
3008 };
3009 run_owner_blocking(move || {
3010 let result = match scope {
3011 MemoryDeleteScope::All => store.delete_all(None, None),
3012 MemoryDeleteScope::Global => store.delete_all(
3013 Some(codewhale_runtime::native_memory::MemoryScope::Global),
3014 None,
3015 ),
3016 };
3017 result.map(|()| MemoryDelete).map_err(|err| err.to_string())
3018 })
3019 }
3020
3021 fn delete_workspace(&self, workspace: &Path) -> Result<MemoryDelete, String> {
3022 let store = {
3023 let app = self.host.app.borrow();
3024 native_store_from_memory_path(&app.memory_path)
3025 };
3026 let workspace = workspace.to_path_buf();
3027 run_owner_blocking(move || {
3028 match codewhale_runtime::native_memory::NativeMemoryStore::workspace_id(&workspace) {
3029 Ok(Some(id)) => store
3030 .delete_all(
3031 Some(codewhale_runtime::native_memory::MemoryScope::Workspace),
3032 Some(&id),
3033 )
3034 .map(|()| MemoryDelete)
3035 .map_err(|err| err.to_string()),
3036 Ok(None) => {
3037 Err("workspace memory requires a git repository with an origin".to_string())
3038 }
3039 Err(err) => Err(format!("failed to resolve workspace identity: {err}")),
3040 }
3041 })
3042 }
3043 }
3044
3045 // ---------------------------------------------------------------------------
3046 // Project host adapter (FEAT-021 D1/D3)
3047 // ---------------------------------------------------------------------------
3048
3049 /// Concrete TUI host mapping for the project command group (FEAT-021 D1/D3).
3050 ///
3051 /// The only place that touches `App` goal/share/LSP state, `config::config`
3052 /// (cross-group LSP bridge), and the session manager. Every method borrows
3053 /// `App` for one call and converts host values to portable contract values
3054 /// before returning; the `/init` workspace path flows through the existing
3055 /// `WORKSPACE` facet (D2), so no init-specific method exists here.
3056 pub(crate) struct ProjectAdapter<'a> {
3057 host: SharedCommandHost<'a>,
3058 }
3059
3060 /// Map the TUI-owned goal status onto the portable project status.
3061 fn portable_goal_status(status: codewhale_engine::tools::goal::GoalStatus) -> ProjectGoalStatus {
3062 match status {
3063 codewhale_engine::tools::goal::GoalStatus::Active => ProjectGoalStatus::Active,
3064 codewhale_engine::tools::goal::GoalStatus::Paused => ProjectGoalStatus::Paused,
3065 codewhale_engine::tools::goal::GoalStatus::Complete => ProjectGoalStatus::Complete,
3066 codewhale_engine::tools::goal::GoalStatus::Blocked => ProjectGoalStatus::Blocked,
3067 }
3068 }
3069
3070 /// Map the durable session goal status onto the portable project status.
3071 fn portable_session_goal_status(
3072 status: codewhale_engine::session_manager::SessionGoalStatus,
3073 ) -> ProjectGoalStatus {
3074 match status {
3075 codewhale_engine::session_manager::SessionGoalStatus::Active => ProjectGoalStatus::Active,
3076 codewhale_engine::session_manager::SessionGoalStatus::Paused => ProjectGoalStatus::Paused,
3077 codewhale_engine::session_manager::SessionGoalStatus::Complete => {
3078 ProjectGoalStatus::Complete
3079 }
3080 codewhale_engine::session_manager::SessionGoalStatus::Blocked => ProjectGoalStatus::Blocked,
3081 }
3082 }
3083
3084 impl CommandProjectContext for ProjectAdapter<'_> {
3085 fn lsp_status(&self) -> String {
3086 let app = self.host.app.borrow();
3087 codewhale_lsp::approval::render_status(app.lsp_config.as_ref(), &app.workspace)
3088 }
3089
3090 fn lsp_approve(&mut self, names: &[&str]) -> Result<String, String> {
3091 let app = self.host.app.borrow();
3092 let config = app.lsp_config.as_ref().ok_or_else(|| {
3093 "No `[lsp]` table in your config, so no language server is configured.".to_owned()
3094 })?;
3095 if !config.enabled {
3096 return Err("Language servers are disabled (`[lsp] enabled = false`).".to_owned());
3097 }
3098 if names.is_empty() {
3099 let mut text = codewhale_lsp::approval::approval_explanation(
3100 &codewhale_lsp::approval::configured_servers(config),
3101 );
3102 text.push_str("\nApprove one with `/lsp approve <name>`.");
3103 return Ok(text);
3104 }
3105 let specs = codewhale_lsp::approval::resolve_names(config, names)?;
3106 for spec in &specs {
3107 codewhale_lsp::approval::approve(&app.workspace, spec)?;
3108 }
3109 let mut text = codewhale_lsp::approval::approval_explanation(&specs);
3110 text.push_str("\nApproved for this folder. Withdraw it with `/lsp revoke <name>`.");
3111 Ok(text)
3112 }
3113
3114 fn lsp_revoke(&mut self, names: &[&str]) -> Result<String, String> {
3115 let app = self.host.app.borrow();
3116 let config = app.lsp_config.as_ref().ok_or_else(|| {
3117 "No `[lsp]` table in your config, so no language server is configured.".to_owned()
3118 })?;
3119 if names.is_empty() {
3120 return Err("Name the server to revoke, for example `/lsp revoke rust`.".to_owned());
3121 }
3122 let specs = codewhale_lsp::approval::resolve_names(config, names)?;
3123 let mut lines = Vec::new();
3124 for spec in &specs {
3125 let removed = codewhale_lsp::approval::revoke(&app.workspace, spec)?;
3126 lines.push(if removed {
3127 format!("Revoked {}; it stops at its next use.", spec.name)
3128 } else {
3129 format!("{} had no approval in this folder.", spec.name)
3130 });
3131 }
3132 Ok(lines.join("\n"))
3133 }
3134
3135 fn goal_state(&self) -> ProjectGoalState {
3136 let app = self.host.app.borrow();
3137 let pending_controls = !app.pending_goal_controls.is_empty();
3138 let last_known = app.last_known_goal_state.as_ref();
3139 ProjectGoalState {
3140 objective: app.goal.objective.clone(),
3141 status: portable_goal_status(app.goal.status),
3142 pause_reason: app
3143 .goal
3144 .pause_reason
3145 .map(|reason| reason.label().to_string()),
3146 started_at_elapsed_seconds: app.goal.started_at.map(|t| t.elapsed().as_secs()),
3147 time_used_seconds: app.goal.time_used_seconds,
3148 token_budget: app.goal.token_budget,
3149 tokens_used: app.goal.tokens_used,
3150 session_total_tokens: app.session.total_conversation_tokens,
3151 continuation_count: app.goal.continuation_count,
3152 pending_controls,
3153 last_known_objective: last_known.map(|goal| goal.objective.clone()),
3154 last_known_status: last_known.map(|goal| portable_session_goal_status(goal.status)),
3155 conversation_present: !app.api_messages.is_empty(),
3156 is_loading: app.is_loading,
3157 goal_continuation_waiting: app.goal_continuation_waiting,
3158 }
3159 }
3160 }
3161
3162 // ---------------------------------------------------------------------------
3163 // Skill group adapter (FEAT-022 D1/D3)
3164 // ---------------------------------------------------------------------------
3165
3166 /// The single new skills-specific host adapter.
3167 ///
3168 /// Owns every concrete skills touch: `App` skill state, `codewhale_skills`
3169 /// discovery/mutation/install/recommend services, `codewhale_plugins` authority
3170 /// verification, `SnapshotRepo`, config/network policy, and the async bridge
3171 /// (`tokio::task::block_in_place`). Portable handlers never name these
3172 /// subsystems (D3); every method returns portable contract values or safe
3173 /// error text (D1).
3174 pub(crate) struct SkillGroupAdapter<'a> {
3175 host: SharedCommandHost<'a>,
3176 }
3177
3178 /// Bridge a sync slash-command handler back into the async ecosystem.
3179 ///
3180 /// We are on the TUI's thread, which is part of the multi-threaded runtime;
3181 /// `block_in_place` + `Handle::current().block_on` bridges sync handlers back
3182 /// into the async ecosystem. Mirrors `groups/skills/skills.rs::run_async`;
3183 /// the legacy copy is removed in Phase 4 when the handlers are ported.
3184 pub(super) fn run_async<F, T>(future: F) -> T
3185 where
3186 F: std::future::Future<Output = T>,
3187 {
3188 tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(future))
3189 }
3190
3191 pub(crate) fn run_owner_blocking<T, F>(work: F) -> Result<T, String>
3192 where
3193 T: Send + 'static,
3194 F: FnOnce() -> Result<T, String> + Send + 'static,
3195 {
3196 match tokio::runtime::Handle::try_current() {
3197 Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
3198 run_async(async move {
3199 codewhale_runtime::runtime_control::owner_work(move || {
3200 work().map_err(anyhow::Error::msg)
3201 })
3202 .await
3203 .map_err(|error| error.to_string())
3204 })
3205 }
3206 _ => work(),
3207 }
3208 }
3209
3210 pub(crate) const MAX_LOAD_SESSION_BYTES: u64 = 256 * 1024 * 1024;
3211
3212 pub(crate) fn read_session_file_capped(path: &Path) -> Result<String, String> {
3213 use std::io::Read as _;
3214 let len = std::fs::metadata(path)
3215 .map_err(|err| err.to_string())?
3216 .len();
3217 if len > MAX_LOAD_SESSION_BYTES {
3218 return Err(format!(
3219 "session file is {len} bytes, over the {MAX_LOAD_SESSION_BYTES}-byte load limit"
3220 ));
3221 }
3222 let mut raw = String::new();
3223 std::fs::File::open(path)
3224 .map_err(|err| err.to_string())?
3225 .take(MAX_LOAD_SESSION_BYTES + 1)
3226 .read_to_string(&mut raw)
3227 .map_err(|err| err.to_string())?;
3228 if raw.len() as u64 > MAX_LOAD_SESSION_BYTES {
3229 return Err(format!(
3230 "session file is over the {MAX_LOAD_SESSION_BYTES}-byte load limit"
3231 ));
3232 }
3233 Ok(raw)
3234 }
3235
3236 /// Read the active config knobs for the installer (network policy, max size,
3237 /// registry URL). `Config::load` is cheap and `App` does not carry a `Config`.
3238 /// A config that cannot be loaded refuses the mutation: defaults would drop
3239 /// the user's network policy, size cap and registry URL, the same refusal the
3240 /// Skills Manager path gives.
3241 fn installer_settings() -> Result<(NetworkPolicy, u64, String), String> {
3242 let cfg = codewhale_plugins::providers::load_config(None, None).map_err(|err| {
3243 tracing::warn!(error = %err, "skills config unavailable; refusing skill mutation");
3244 format!("Skill mutation refused: config could not be loaded ({err:#})")
3245 })?;
3246 let network = cfg
3247 .network
3248 .clone()
3249 .map(codewhale_net::network_policy::NetworkPolicy::from)
3250 .unwrap_or_default();
3251 let skills_cfg = cfg.skills.as_ref();
3252 let max_size = skills_cfg
3253 .and_then(|s| s.max_install_size_bytes)
3254 .unwrap_or(codewhale_skill_install::install::DEFAULT_MAX_SIZE_BYTES);
3255 let registry_url = skills_cfg
3256 .and_then(|s| s.registry_url.clone())
3257 .unwrap_or_else(|| codewhale_skill_install::install::DEFAULT_REGISTRY_URL.to_string());
3258 Ok((network, max_size, registry_url))
3259 }
3260
3261 /// Resolve the cache destination before loading settings or entering the network bridge.
3262 fn sync_registry_to_cache(cache_dir: Option<PathBuf>) -> Result<SkillSyncOutcome, String> {
3263 use codewhale_skill_install::install::{SkillSyncOutcome as TuiSyncOutcome, SyncResult};
3264 let cache_dir =
3265 cache_dir.ok_or_else(|| "global skill mutations require a home directory".to_string())?;
3266 let (network, max_size, registry_url) = run_owner_blocking(installer_settings)?;
3267 let result = run_async(async move {
3268 codewhale_skill_install::install::sync_registry(
3269 &network,
3270 &registry_url,
3271 &cache_dir,
3272 max_size,
3273 )
3274 .await
3275 });
3276 match result {
3277 Ok(SyncResult::RegistryDenied(host)) => Ok(SkillSyncOutcome::RegistryDenied(host)),
3278 Ok(SyncResult::RegistryNeedsApproval(host)) => {
3279 Ok(SkillSyncOutcome::RegistryNeedsApproval(host))
3280 }
3281 Ok(SyncResult::Done { outcomes }) => {
3282 let total = outcomes.len();
3283 let mut downloaded = 0usize;
3284 let mut fresh = 0usize;
3285 let mut failed = 0usize;
3286 let entries = outcomes
3287 .into_iter()
3288 .map(|outcome| match outcome {
3289 TuiSyncOutcome::Downloaded { name, path } => {
3290 downloaded += 1;
3291 SkillSyncEntry::Downloaded {
3292 name,
3293 path: path.display().to_string(),
3294 }
3295 }
3296 TuiSyncOutcome::Fresh { name } => {
3297 fresh += 1;
3298 SkillSyncEntry::Fresh { name }
3299 }
3300 TuiSyncOutcome::Failed { name, reason } => {
3301 failed += 1;
3302 SkillSyncEntry::Failed { name, reason }
3303 }
3304 TuiSyncOutcome::Denied { name, host } => {
3305 failed += 1;
3306 SkillSyncEntry::Denied { name, host }
3307 }
3308 TuiSyncOutcome::NeedsApproval { name, host } => {
3309 failed += 1;
3310 SkillSyncEntry::NeedsApproval { name, host }
3311 }
3312 })
3313 .collect();
3314 Ok(SkillSyncOutcome::Done {
3315 total,
3316 downloaded,
3317 fresh,
3318 failed,
3319 entries,
3320 })
3321 }
3322 Err(err) => Err(format_registry_error("Sync failed", &err)),
3323 }
3324 }
3325
3326 /// Inspect an anyhow chain and surface a one-line hint pointing at the most
3327 /// common cause of a registry fetch failure (DNS, refused, TLS, HTTP status,
3328 /// timeout). Mirrors `groups/skills/skills.rs::registry_fetch_error_hint`.
3329 fn registry_fetch_error_hint(err: &anyhow::Error) -> Option<&'static str> {
3330 let msg = format!("{err:#}").to_lowercase();
3331 if msg.contains("dns")
3332 || msg.contains("name resolution")
3333 || msg.contains("getaddrinfo")
3334 || msg.contains("nodename nor servname")
3335 {
3336 Some(
3337 "Hint: DNS lookup failed. Check internet/DNS connectivity, or override the registry URL in [skills] of ~/.codewhale/config.toml.",
3338 )
3339 } else if msg.contains("connection refused")
3340 || msg.contains("connection reset")
3341 || msg.contains("connection aborted")
3342 {
3343 Some(
3344 "Hint: connection refused/reset. The registry host may be unreachable from this network (corporate proxy, firewall, offline).",
3345 )
3346 } else if msg.contains("tls")
3347 || msg.contains("certificate")
3348 || msg.contains("ssl")
3349 || msg.contains("handshake")
3350 {
3351 Some(
3352 "Hint: TLS handshake failed. The system trust store may be missing the registry's CA, or a TLS-intercepting proxy is rewriting the certificate.",
3353 )
3354 } else if msg.contains(" 404") || msg.contains("not found") {
3355 Some(
3356 "Hint: registry URL returned 404. Verify the registry URL in [skills] of ~/.codewhale/config.toml.",
3357 )
3358 } else if msg.contains(" 401") || msg.contains(" 403") || msg.contains("forbidden") {
3359 Some(
3360 "Hint: registry returned an auth error. The registry may require credentials or have been moved.",
3361 )
3362 } else if msg.contains(" 429") || msg.contains("rate limit") || msg.contains("too many") {
3363 Some("Hint: rate-limited by the registry. Try again in a moment.")
3364 } else if msg.contains("timed out") || msg.contains("timeout") {
3365 Some("Hint: request timed out. Network may be slow or the registry host may be down.")
3366 } else {
3367 None
3368 }
3369 }
3370
3371 /// Append the actionable hint to a registry fetch error. Mirrors
3372 /// `groups/skills/skills.rs::format_registry_error`.
3373 fn format_registry_error(prefix: &str, err: &anyhow::Error) -> String {
3374 let mut out = format!("{prefix}: {err:#}");
3375 if let Some(hint) = registry_fetch_error_hint(err) {
3376 out.push_str("\n\n");
3377 out.push_str(hint);
3378 }
3379 out
3380 }
3381
3382 /// Discover the enabled visible skills for the current App state.
3383 fn discover_visible(
3384 workspace: &Path,
3385 skills_dir: &Path,
3386 skills_config: &codewhale_runtime::config::SkillsConfig,
3387 plugins: Option<&codewhale_plugins::PluginRegistry>,
3388 ) -> codewhale_skills::SkillRegistry {
3389 codewhale_skills::discover_for_workspace(workspace, Some(skills_dir), skills_config, plugins)
3390 .into_enabled()
3391 }
3392
3393 /// Map a TUI skill to its portable projection entry.
3394 fn portable_skill_entry(
3395 skill: &codewhale_skills::Skill,
3396 locale: codewhale_localization::Locale,
3397 skills_config: &codewhale_runtime::config::SkillsConfig,
3398 ) -> SkillEntry {
3399 let source = match &skill.source {
3400 codewhale_skills::SkillSource::Native => SkillSourceKind::Native,
3401 codewhale_skills::SkillSource::Plugin {
3402 plugin_id,
3403 plugin_name,
3404 ..
3405 } => SkillSourceKind::Plugin {
3406 plugin_name: plugin_name.clone(),
3407 plugin_id: plugin_id.clone(),
3408 },
3409 };
3410 let path = match &skill.source {
3411 codewhale_skills::SkillSource::Native => Some(skill.path.display().to_string()),
3412 codewhale_skills::SkillSource::Plugin { .. } => None,
3413 };
3414 let bundled_tier = codewhale_skills::bundled_skill_tier(&skill.name).map(|tier| match tier {
3415 codewhale_skills::BundledSkillTier::CoreAgentic => SkillBundledTier::CoreAgentic,
3416 codewhale_skills::BundledSkillTier::FormatTooling => SkillBundledTier::FormatTooling,
3417 });
3418 SkillEntry {
3419 name: skill.name.clone(),
3420 description: skill.description_for_locale(locale.tag()).to_string(),
3421 index_note: codewhale_skills::description_index_cap_if_shortened(
3422 skill.description_for_locale(locale.tag()),
3423 skills_config,
3424 )
3425 .map(|cap| {
3426 codewhale_localization::tr(
3427 locale,
3428 codewhale_localization::MessageId::SkillsIndexDescriptionLimit,
3429 )
3430 .replace("{limit}", &cap.to_string())
3431 }),
3432 source,
3433 path,
3434 bundled_tier,
3435 }
3436 }
3437
3438 /// Map a TUI mutation receipt to its portable receipt.
3439 fn portable_mutation_receipt(
3440 receipt: &codewhale_skills::mutation::SkillMutationReceipt,
3441 ) -> SkillMutationReceipt {
3442 use codewhale_skills::mutation::SkillMutationOutcome as TuiOutcome;
3443 let outcome = match &receipt.outcome {
3444 TuiOutcome::Installed => SkillMutationOutcome::Installed,
3445 TuiOutcome::Updated => SkillMutationOutcome::Updated,
3446 TuiOutcome::NoChange => SkillMutationOutcome::NoChange,
3447 TuiOutcome::Removed => SkillMutationOutcome::Removed,
3448 TuiOutcome::Trusted => SkillMutationOutcome::Trusted,
3449 TuiOutcome::Imported => SkillMutationOutcome::Imported,
3450 TuiOutcome::AlreadyPresent => SkillMutationOutcome::AlreadyPresent,
3451 TuiOutcome::NeedsApproval(host) => SkillMutationOutcome::NeedsApproval(host.clone()),
3452 TuiOutcome::NetworkDenied(host) => SkillMutationOutcome::NetworkDenied(host.clone()),
3453 };
3454 SkillMutationReceipt {
3455 name: receipt.name.clone(),
3456 safe_target_path: receipt.safe_target_path.clone(),
3457 outcome,
3458 }
3459 }
3460
3461 /// Map a portable target scope to the TUI scope.
3462 fn portable_scope(
3463 scope: Option<SkillTargetScope>,
3464 ) -> Option<codewhale_skills::mutation::SkillTargetScope> {
3465 use codewhale_skills::mutation::SkillTargetScope as TuiScope;
3466 scope.map(|s| match s {
3467 SkillTargetScope::Project => TuiScope::Project,
3468 SkillTargetScope::Global => TuiScope::Global,
3469 })
3470 }
3471
3472 /// Map a curated registry document to portable entries.
3473 fn portable_registry_entries(
3474 doc: &codewhale_skill_install::install::RegistryDocument,
3475 ) -> Vec<RemoteSkillEntry> {
3476 doc.skills
3477 .iter()
3478 .map(|(name, entry)| RemoteSkillEntry {
3479 name: name.clone(),
3480 description: entry.description.clone(),
3481 source: entry.source.clone(),
3482 })
3483 .collect()
3484 }
3485
3486 /// Message shown when a network-policy host requires approval. Moved
3487 /// verbatim from `groups/skills/skills.rs`; the legacy copy is removed in
3488 /// Phase 4. Rendered by the portable handler from the typed outcome.
3489 fn needs_approval_message(host: &str) -> String {
3490 format!(
3491 "Network policy requires approval for {host}.\n\
3492 Add it to your allow list with `/network allow {host}` (or set [network].default = \"allow\" in ~/.codewhale/config.toml), then retry."
3493 )
3494 }
3495
3496 /// Message shown when a network-policy host is denied. Moved verbatim from
3497 /// `groups/skills/skills.rs`; the legacy copy is removed in Phase 4.
3498 fn network_denied_message(host: &str) -> String {
3499 format!(
3500 "Network policy denied access to {host}.\n\
3501 Remove the deny entry from ~/.codewhale/config.toml under [network] or contact your administrator."
3502 )
3503 }
3504
3505 impl CommandSkillGroupContext for SkillGroupAdapter<'_> {
3506 fn skill_registry_projection(&self) -> SkillRegistryProjection {
3507 let (workspace, skills_dir, skills_config, locale, plugin_view, mode_label, dirs) = {
3508 let app = self.host.app.borrow();
3509 let mode = codewhale_skills::SkillDiscoveryMode::from_config(&app.skills_config);
3510 let dirs = codewhale_skills::skill_directories_for_workspace_and_dir(
3511 &app.workspace,
3512 &app.skills_dir,
3513 mode,
3514 );
3515 let mode_label = match mode {
3516 codewhale_skills::SkillDiscoveryMode::Compatible => "compatible",
3517 codewhale_skills::SkillDiscoveryMode::CompatibleWithFlatWorkspace => {
3518 "compatible (flat workspace enabled)"
3519 }
3520 codewhale_skills::SkillDiscoveryMode::CodeWhaleOnly => "codewhale-only",
3521 };
3522 (
3523 app.workspace.clone(),
3524 app.skills_dir.clone(),
3525 std::sync::Arc::clone(&app.skills_config),
3526 app.ui_locale,
3527 app.extension_plugin_view(),
3528 mode_label.to_string(),
3529 dirs.iter()
3530 .map(|dir| dir.display().to_string())
3531 .collect::<Vec<_>>(),
3532 )
3533 };
3534 let workspace_label = workspace.display().to_string();
3535 let skills_dir_label = skills_dir.display().to_string();
3536 let projected = run_owner_blocking(move || {
3537 let registry = discover_visible(
3538 &workspace,
3539 &skills_dir,
3540 &skills_config,
3541 Some(plugin_view.as_ref()),
3542 );
3543 let bundled_status = codewhale_skills::bundled_skills_status(&skills_config, &registry)
3544 .map(|status| status.inspection())
3545 .unwrap_or_default();
3546 let entries = registry
3547 .list()
3548 .iter()
3549 .map(|skill| portable_skill_entry(skill, locale, &skills_config))
3550 .collect::<Vec<_>>();
3551 Ok((
3552 bundled_status,
3553 entries,
3554 registry.warnings().to_vec(),
3555 registry.len(),
3556 ))
3557 });
3558 let (bundled_status, entries, warnings, total) = match projected {
3559 Ok(projection) => projection,
3560 Err(reason) => (Vec::new(), Vec::new(), vec![reason], 0),
3561 };
3562 SkillRegistryProjection {
3563 workspace: workspace_label,
3564 skills_dir: skills_dir_label,
3565 mode_label,
3566 bundled_status,
3567 dirs,
3568 entries,
3569 warnings,
3570 total,
3571 }
3572 }
3573
3574 fn activate_skill(
3575 &mut self,
3576 name: &str,
3577 ) -> Result<SkillActivationOutcome, SkillActivationError> {
3578 let (workspace, skills_dir, skills_config, plugin_view) = {
3579 let app = self.host.app.borrow();
3580 (
3581 app.workspace.clone(),
3582 app.skills_dir.clone(),
3583 std::sync::Arc::clone(&app.skills_config),
3584 app.extension_plugin_view(),
3585 )
3586 };
3587 let registry = run_owner_blocking(move || {
3588 Ok(discover_visible(
3589 &workspace,
3590 &skills_dir,
3591 &skills_config,
3592 Some(plugin_view.as_ref()),
3593 ))
3594 })
3595 .map_err(|reason| SkillActivationError::InvocationRejected {
3596 name: name.to_string(),
3597 reason,
3598 })?;
3599 if let Some(skill) = registry.get(name) {
3600 if !skill.invocation.user_invocable() {
3601 return Err(SkillActivationError::InvocationRejected {
3602 name: skill.name.clone(),
3603 reason: "frontmatter does not allow user invocation".into(),
3604 });
3605 }
3606 let plugin_provenance = skill.source.provenance();
3607 if let Some(provenance) = &plugin_provenance
3608 && let Err(reason) = provenance.verify_for(
3609 &self.host.app.borrow().workspace,
3610 Some(self.host.app.borrow().extension_plugin_view().as_ref()),
3611 )
3612 {
3613 return Err(SkillActivationError::PluginRejected {
3614 name: skill.name.clone(),
3615 reason,
3616 });
3617 }
3618 let skill = skill.clone();
3619 let instruction = format!(
3620 "You are now using a skill. Follow these instructions:\n\n# Skill: {}\n\n{}\n\n---\n\nNow respond to the user's request following the above skill instructions.",
3621 skill.name, skill.body
3622 );
3623 let mut app = self.host.app.borrow_mut();
3624 app.add_message(HistoryCell::System {
3625 content: format!("Activated skill: {}\n\n{}", skill.name, skill.description),
3626 });
3627 app.active_skill = Some(instruction);
3628 app.active_skill_provenance = plugin_provenance;
3629 Ok(SkillActivationOutcome {
3630 name: skill.name,
3631 description: skill.description,
3632 })
3633 } else {
3634 let available: Vec<String> = registry.list().iter().map(|s| s.name.clone()).collect();
3635 Err(SkillActivationError::NotFound {
3636 requested: name.to_string(),
3637 available,
3638 warnings: registry.warnings().to_vec(),
3639 })
3640 }
3641 }
3642
3643 fn install_skill(
3644 &mut self,
3645 scope: Option<SkillTargetScope>,
3646 spec: &str,
3647 ) -> Result<SkillMutationReceipt, String> {
3648 use codewhale_skills::mutation::{MutationContext, SkillMutationRequest};
3649 let source = match codewhale_skill_install::install::InstallSource::parse(spec) {
3650 Ok(source) => source,
3651 Err(err) => return Err(format!("Invalid install source: {err}")),
3652 };
3653 let target =
3654 portable_scope(scope).unwrap_or(codewhale_skills::mutation::SkillTargetScope::Global);
3655 let workspace = self.host.app.borrow().workspace.clone();
3656 let home = codewhale_paths::user_home();
3657 let (network, max_size, registry_url) = run_owner_blocking(installer_settings)?;
3658 let outcome = run_async(async move {
3659 let ctx = MutationContext {
3660 workspace: &workspace,
3661 home: home.as_deref(),
3662 configured_skills_dir: None,
3663 network: &network,
3664 max_size,
3665 registry_url: &registry_url,
3666 };
3667 codewhale_skills::mutation::execute(
3668 SkillMutationRequest::InstallRemote { source, target },
3669 &ctx,
3670 )
3671 .await
3672 });
3673 match outcome {
3674 Ok(receipt) => Ok(portable_mutation_receipt(&receipt)),
3675 Err(err) => Err(format!("Install failed: {err:#}")),
3676 }
3677 }
3678
3679 fn update_skill(
3680 &mut self,
3681 scope: Option<SkillTargetScope>,
3682 name: &str,
3683 ) -> Result<SkillMutationReceipt, String> {
3684 use codewhale_skills::mutation::{MutationContext, SkillMutationRequest};
3685 let workspace = self.host.app.borrow().workspace.clone();
3686 let home = codewhale_paths::user_home();
3687 let (network, max_size, registry_url) = run_owner_blocking(installer_settings)?;
3688 let owned_name = name.to_string();
3689 let scope = portable_scope(scope);
3690 let outcome = run_async(async move {
3691 let ctx = MutationContext {
3692 workspace: &workspace,
3693 home: home.as_deref(),
3694 configured_skills_dir: None,
3695 network: &network,
3696 max_size,
3697 registry_url: &registry_url,
3698 };
3699 codewhale_skills::mutation::execute(
3700 SkillMutationRequest::UpdateByName {
3701 name: owned_name,
3702 scope,
3703 expected_digest: None,
3704 },
3705 &ctx,
3706 )
3707 .await
3708 });
3709 match outcome {
3710 Ok(receipt) => Ok(portable_mutation_receipt(&receipt)),
3711 Err(err) => Err(format!("Update failed: {err:#}")),
3712 }
3713 }
3714
3715 fn uninstall_skill(
3716 &mut self,
3717 scope: Option<SkillTargetScope>,
3718 name: &str,
3719 ) -> Result<SkillMutationReceipt, String> {
3720 use codewhale_skills::mutation::{MutationContext, SkillMutationRequest};
3721 let workspace = self.host.app.borrow().workspace.clone();
3722 let home = codewhale_paths::user_home();
3723 let request = SkillMutationRequest::RemoveByName {
3724 name: name.to_string(),
3725 scope: portable_scope(scope),
3726 expected_digest: None,
3727 };
3728 run_owner_blocking(move || {
3729 let (network, max_size, registry_url) = installer_settings()?;
3730 let ctx = MutationContext {
3731 workspace: &workspace,
3732 home: home.as_deref(),
3733 configured_skills_dir: None,
3734 network: &network,
3735 max_size,
3736 registry_url: &registry_url,
3737 };
3738 codewhale_skills::mutation::execute_sync(request, &ctx)
3739 .map(|receipt| portable_mutation_receipt(&receipt))
3740 .map_err(|err| format!("Uninstall failed: {err:#}"))
3741 })
3742 }
3743
3744 fn trust_skill(
3745 &mut self,
3746 scope: Option<SkillTargetScope>,
3747 name: &str,
3748 ) -> Result<SkillMutationReceipt, String> {
3749 use codewhale_skills::mutation::{MutationContext, SkillMutationRequest};
3750 let workspace = self.host.app.borrow().workspace.clone();
3751 let home = codewhale_paths::user_home();
3752 let request = SkillMutationRequest::TrustByName {
3753 name: name.to_string(),
3754 scope: portable_scope(scope),
3755 expected_digest: None,
3756 };
3757 run_owner_blocking(move || {
3758 let (network, max_size, registry_url) = installer_settings()?;
3759 let ctx = MutationContext {
3760 workspace: &workspace,
3761 home: home.as_deref(),
3762 configured_skills_dir: None,
3763 network: &network,
3764 max_size,
3765 registry_url: &registry_url,
3766 };
3767 codewhale_skills::mutation::execute_sync(request, &ctx)
3768 .map(|receipt| portable_mutation_receipt(&receipt))
3769 .map_err(|err| format!("Trust failed: {err:#}"))
3770 })
3771 }
3772
3773 fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String> {
3774 let (network, _max_size, registry_url) = run_owner_blocking(installer_settings)?;
3775 let registry = run_async(async move {
3776 codewhale_skill_install::install::fetch_registry(&network, &registry_url).await
3777 });
3778 match registry {
3779 Ok(codewhale_skill_install::install::RegistryFetchResult::Loaded(doc)) => {
3780 Ok(RemoteRegistryOutcome::Loaded {
3781 entries: portable_registry_entries(&doc),
3782 })
3783 }
3784 Ok(codewhale_skill_install::install::RegistryFetchResult::NeedsApproval(host)) => {
3785 Ok(RemoteRegistryOutcome::NeedsApproval(host))
3786 }
3787 Ok(codewhale_skill_install::install::RegistryFetchResult::Denied(host)) => {
3788 Ok(RemoteRegistryOutcome::Denied(host))
3789 }
3790 Err(err) => Err(format_registry_error("Failed to fetch registry", &err)),
3791 }
3792 }
3793
3794 fn recommend_skills(&mut self, task: &str) -> Result<Vec<SkillRecommendation>, String> {
3795 let (network, _max_size, registry_url) = run_owner_blocking(installer_settings)?;
3796 let registry = run_async(async move {
3797 codewhale_skill_install::install::fetch_registry(&network, &registry_url).await
3798 });
3799 match registry {
3800 Ok(codewhale_skill_install::install::RegistryFetchResult::Loaded(doc)) => {
3801 let recommendations =
3802 codewhale_skill_install::recommend::recommend_remote_skills(task, &doc, 3);
3803 Ok(recommendations
3804 .into_iter()
3805 .map(|recommendation| SkillRecommendation {
3806 name: recommendation.name.to_string(),
3807 description: recommendation.entry.description.clone(),
3808 matched_terms: recommendation.matched_terms.clone(),
3809 })
3810 .collect())
3811 }
3812 Ok(codewhale_skill_install::install::RegistryFetchResult::NeedsApproval(host)) => {
3813 Err(needs_approval_message(&host))
3814 }
3815 Ok(codewhale_skill_install::install::RegistryFetchResult::Denied(host)) => {
3816 Err(network_denied_message(&host))
3817 }
3818 Err(err) => Err(format_registry_error("Failed to fetch registry", &err)),
3819 }
3820 }
3821
3822 fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String> {
3823 sync_registry_to_cache(codewhale_skill_install::install::default_cache_skills_dir())
3824 }
3825
3826 fn run_review(&mut self) -> Result<ReviewOutcome, String> {
3827 let skills_dir = self.host.app.borrow().skills_dir.clone();
3828 let global_dir = codewhale_skills::default_skills_dir();
3829 let scan_dir = skills_dir.clone();
3830 let scan_global_dir = global_dir.clone();
3831 let (warnings, skill) = run_owner_blocking(move || {
3832 let registry = codewhale_skills::SkillRegistry::discover(&scan_dir).into_enabled();
3833 let mut warnings: Vec<String> = registry.warnings().to_vec();
3834 let mut skill = registry.get("review").cloned();
3835
3836 if skill.is_none() && scan_global_dir != scan_dir {
3837 let registry =
3838 codewhale_skills::SkillRegistry::discover(&scan_global_dir).into_enabled();
3839 if warnings.is_empty() {
3840 warnings = registry.warnings().to_vec();
3841 } else if !registry.warnings().is_empty() {
3842 warnings.extend(registry.warnings().iter().cloned());
3843 }
3844 skill = registry.get("review").cloned();
3845 }
3846 Ok((warnings, skill))
3847 })?;
3848
3849 match skill {
3850 Some(skill) => {
3851 if !skill.invocation.user_invocable() {
3852 return Err(format!(
3853 "Skill '{}' does not allow user invocation",
3854 skill.name
3855 ));
3856 }
3857 // Host-side side effects (D2): session-message insertion and
3858 // active-skill mutation are authoritative App operations; the
3859 // portable handler renders no success message (baseline emits
3860 // only the SendMessage action) and never touches App.
3861 let instruction = format!(
3862 "You are now using a skill. Follow these instructions:\n\n# Skill: {}\n\n{}\n\n---\n\nNow respond to the user's request following the above skill instructions.",
3863 skill.name, skill.body
3864 );
3865 let mut app = self.host.app.borrow_mut();
3866 app.add_message(HistoryCell::System {
3867 content: format!("Activated skill: {}\n\n{}", skill.name, skill.description),
3868 });
3869 app.active_skill = Some(instruction);
3870 app.active_skill_provenance = None;
3871 Ok(ReviewOutcome::Ready)
3872 }
3873 None => Ok(ReviewOutcome::NotFound {
3874 skills_dir: skills_dir.display().to_string(),
3875 global_dir: global_dir.display().to_string(),
3876 warnings,
3877 }),
3878 }
3879 }
3880
3881 fn snapshot_list(&mut self, limit: usize) -> Result<Vec<SnapshotEntry>, String> {
3882 let workspace = self.host.app.borrow().workspace.clone();
3883 run_owner_blocking(move || {
3884 let repo =
3885 codewhale_snapshot::SnapshotRepo::open_or_init(&workspace).map_err(|err| {
3886 format!(
3887 "Snapshot repo unavailable for {}: {err}",
3888 workspace.display(),
3889 )
3890 })?;
3891 let snapshots = repo
3892 .list(limit)
3893 .map_err(|err| format!("Failed to list snapshots: {err}"))?;
3894 Ok(snapshots
3895 .into_iter()
3896 .map(|snapshot| SnapshotEntry {
3897 id: snapshot.id.into_string(),
3898 label: snapshot.label,
3899 timestamp: snapshot.timestamp,
3900 })
3901 .collect())
3902 })
3903 }
3904
3905 fn restore_snapshot(&mut self, id: &str) -> Result<(), String> {
3906 if let Some(refusal) =
3907 debug_operations::active_turn_restore_refusal(&self.host.app.borrow())
3908 {
3909 return Err(refusal);
3910 }
3911 let workspace = self.host.app.borrow().workspace.clone();
3912 let id = id.to_owned();
3913 let restore = move || {
3914 let repo = match codewhale_snapshot::SnapshotRepo::open_or_init(&workspace) {
3915 Ok(repo) => repo,
3916 Err(err) => {
3917 return Err(format!(
3918 "Snapshot repo unavailable for {}: {err}",
3919 workspace.display(),
3920 ));
3921 }
3922 };
3923 let id = codewhale_snapshot::SnapshotId::parse(&id)
3924 .map_err(|err| format!("Restore failed: {err}"))?;
3925 repo.restore(&id)
3926 .map_err(|err| format!("Restore failed: {err}"))
3927 };
3928 // Standalone synchronous hosts have no runtime worker to protect.
3929 // Live TUI dispatch uses the existing bridge and blocking pool for
3930 // the entire restore, including its mandatory safety snapshot.
3931 if tokio::runtime::Handle::try_current().is_err() {
3932 return restore();
3933 }
3934 // A sealed test's home must follow the work onto the blocking pool.
3935 #[cfg(test)]
3936 let ticket = crate::test_support::env_scope_ticket();
3937 run_async(async move {
3938 tokio::task::spawn_blocking(move || {
3939 #[cfg(test)]
3940 let _membership = crate::test_support::join_env_scope(ticket);
3941 restore()
3942 })
3943 .await
3944 .map_err(|error| format!("Restore task failed: {error}"))?
3945 })
3946 }
3947
3948 fn approval_state(&self) -> CommandApprovalState {
3949 let app = self.host.app.borrow();
3950 CommandApprovalState {
3951 yolo: app.yolo,
3952 trust_mode: app.trust_mode,
3953 }
3954 }
3955 }
3956
3957 // ---------------------------------------------------------------------------
3958 // Plugin host adapter (FEAT-020 D1/D11)
3959 // ---------------------------------------------------------------------------
3960
3961 /// Plugin host-data adapter (FEAT-020 D1/D11).
3962 ///
3963 /// Owns every concrete plugin service the live `/plugin` branch closure
3964 /// consumes: registry reads/mutations, the async mutation/network-policy
3965 /// bridge (D11), export, legacy executable-tool scan, Kimi managed import,
3966 /// and the marketplace store. That store projects the bundled first-party
3967 /// catalog alongside locally added catalogs for every host surface.
3968 /// Every method borrows `App` only for the duration of one call and converts
3969 /// host values to portable contract values before returning. Handlers receive
3970 /// only the portable facet and never name `PluginRegistry`, `LoadedPlugin`,
3971 /// `Config`, or another concrete host service.
3972 pub(crate) struct PluginAdapter<'a> {
3973 host: SharedCommandHost<'a>,
3974 }
3975
3976 /// Convert a TUI-owned diagnostic to the portable contract diagnostic.
3977 fn portable_diagnostic(
3978 diagnostic: &codewhale_plugins::types::PluginDiagnostic,
3979 ) -> PluginDiagnostic {
3980 PluginDiagnostic {
3981 level: match diagnostic.level {
3982 codewhale_plugins::types::PluginDiagnosticLevel::Warning => {
3983 PluginDiagnosticLevel::Warning
3984 }
3985 codewhale_plugins::types::PluginDiagnosticLevel::Error => PluginDiagnosticLevel::Error,
3986 },
3987 code: diagnostic.code.to_string(),
3988 message: diagnostic.message.clone(),
3989 path: diagnostic.path.clone(),
3990 }
3991 }
3992
3993 /// Convert a TUI marketplace diagnostic into the portable contract diagnostic.
3994 fn portable_marketplace_diagnostic(
3995 diagnostic: &codewhale_plugins::marketplace::types::MarketplaceDiagnostic,
3996 ) -> PluginDiagnostic {
3997 PluginDiagnostic {
3998 level: match diagnostic.level {
3999 codewhale_plugins::types::PluginDiagnosticLevel::Warning => {
4000 PluginDiagnosticLevel::Warning
4001 }
4002 codewhale_plugins::types::PluginDiagnosticLevel::Error => PluginDiagnosticLevel::Error,
4003 },
4004 code: diagnostic.code.clone(),
4005 message: diagnostic.message.clone(),
4006 path: None,
4007 }
4008 }
4009
4010 /// Localize who approved a plugin using the same English phrases as
4011 /// `codewhale_plugins::host_services::approver_label`.
4012 pub(crate) fn localized_approver_label(
4013 locale: Locale,
4014 approver: Option<&codewhale_plugins::host_services::PluginApprover>,
4015 ) -> String {
4016 use codewhale_plugins::host_services::{AgentPosture, PluginApprover};
4017 let id = match approver {
4018 Some(PluginApprover::Person { .. }) => MessageId::CmdPluginAuditApprovedByYou,
4019 Some(PluginApprover::Agent(agent)) => match agent.posture {
4020 AgentPosture::FullAccess => MessageId::CmdPluginAuditApprovedByAgentFullAccess,
4021 AgentPosture::AutoReview => MessageId::CmdPluginAuditApprovedByAgentAutoReview,
4022 AgentPosture::CommandLine => MessageId::CmdPluginAuditApprovedByAgentShell,
4023 },
4024 Some(PluginApprover::CommandLine) => MessageId::CmdPluginAuditApprovedByCommandLine,
4025 None => MessageId::CmdPluginAuditApprovedByUnknown,
4026 };
4027 tr(locale, id).into_owned()
4028 }
4029
4030 /// Localize who turned a plugin on.
4031 pub(crate) fn localized_turned_on_by_label(
4032 locale: Locale,
4033 approver: Option<&codewhale_plugins::host_services::PluginApprover>,
4034 ) -> String {
4035 use codewhale_plugins::host_services::{AgentPosture, PluginApprover};
4036 let id = match approver {
4037 Some(PluginApprover::Person { .. }) => MessageId::CmdPluginAuditTurnedOnByYou,
4038 Some(PluginApprover::Agent(agent)) => match agent.posture {
4039 AgentPosture::FullAccess => MessageId::CmdPluginAuditTurnedOnByAgentFullAccess,
4040 AgentPosture::AutoReview => MessageId::CmdPluginAuditTurnedOnByAgentAutoReview,
4041 AgentPosture::CommandLine => MessageId::CmdPluginAuditTurnedOnByAgentShell,
4042 },
4043 Some(PluginApprover::CommandLine) => MessageId::CmdPluginAuditTurnedOnByCommandLine,
4044 None => MessageId::CmdPluginAuditTurnedOnByUnknown,
4045 };
4046 tr(locale, id).into_owned()
4047 }
4048
4049 /// Convert a TUI-owned loaded plugin into the portable list summary.
4050 fn portable_summary(
4051 plugin: &codewhale_plugins::types::LoadedPlugin,
4052 locale: Locale,
4053 ) -> PluginSummary {
4054 use codewhale_plugins::host_services::{
4055 PluginApprover, PluginCohort, cohort_of, short_review_date, workspace_folder_name,
4056 };
4057 let review_display = if plugin.trusted()
4058 && matches!(
4059 plugin.approved_by,
4060 Some(PluginApprover::Agent(_) | PluginApprover::CommandLine)
4061 ) {
4062 Some(tr(locale, MessageId::ExtensionsTrustNotReviewed).into_owned())
4063 } else {
4064 None
4065 };
4066 let approver = if plugin.trusted() || plugin.approved_by.is_some() {
4067 Some(localized_approver_label(
4068 locale,
4069 plugin.approved_by.as_ref(),
4070 ))
4071 } else {
4072 None
4073 };
4074 let reviewed_date = plugin
4075 .reviewed_at
4076 .as_deref()
4077 .map(|ts| short_review_date(ts).to_string());
4078 let enabled_by = plugin
4079 .enabled
4080 .then(|| localized_turned_on_by_label(locale, plugin.enabled_by.as_ref()));
4081 let reach_folder = plugin
4082 .approved_by
4083 .as_ref()
4084 .and_then(PluginApprover::agent_workspace)
4085 .map(|ws| workspace_folder_name(ws).to_string());
4086 let process_note = matches!(
4087 cohort_of(plugin.approved_by.as_ref()),
4088 PluginCohort::Agent { .. }
4089 )
4090 .then(|| tr(locale, MessageId::CmdPluginAuditAgentProcessNote).into_owned());
4091 PluginSummary {
4092 name: plugin.name().to_string(),
4093 id: plugin.id.as_str().to_string(),
4094 state_label: plugin.state_label().to_string(),
4095 scope: plugin.scope.as_str().to_string(),
4096 trust_status: plugin.trust_status.as_str().to_string(),
4097 review_display,
4098 approver,
4099 reviewed_date,
4100 enabled_by,
4101 reach_folder,
4102 outside_reach: plugin.outside_reach,
4103 process_note,
4104 compatibility: plugin.compatibility().as_str().to_string(),
4105 inventory: plugin.inventory.summary(),
4106 active: plugin.active(),
4107 trusted: plugin.trusted(),
4108 enabled: plugin.enabled,
4109 }
4110 }
4111
4112 fn plugin_command_names(plugin: &codewhale_plugins::types::LoadedPlugin) -> Vec<String> {
4113 let mut names = std::collections::BTreeSet::new();
4114 for path in &plugin.components.commands {
4115 let entries = crate::commands::user_commands::load_command_entries_from_component(path);
4116 if !entries.is_empty() {
4117 for (stem, content, file_path) in entries {
4118 let resolved = crate::commands::user_registry::resolved_command_name(
4119 stem, &content, &file_path,
4120 );
4121 if !resolved.is_empty() {
4122 names.insert(format!("/{resolved}"));
4123 }
4124 }
4125 continue;
4126 }
4127 if path.is_file()
4128 && path.extension().and_then(|ext| ext.to_str()) == Some("md")
4129 && let Some(stem) = path.file_stem().and_then(|stem| stem.to_str())
4130 {
4131 let lower = stem.to_lowercase();
4132 if !lower.is_empty() {
4133 names.insert(format!("/{lower}"));
4134 }
4135 }
4136 }
4137 names.into_iter().collect()
4138 }
4139
4140 fn plugin_profile_names(plugin: &codewhale_plugins::types::LoadedPlugin) -> Vec<String> {
4141 let authority = codewhale_config::PluginAuthority {
4142 plugin_id: plugin.id.clone(),
4143 plugin_name: plugin.name().to_string(),
4144 workspace: plugin.canonical_root.clone(),
4145 state_path: plugin.canonical_root.clone(),
4146 managed_policy_path: None,
4147 managed_policy_source: None,
4148 source_manifest: plugin.canonical_root.clone(),
4149 staged_manifest: plugin.canonical_root.clone(),
4150 content_hash: plugin.content_hash.clone(),
4151 capability_hash: plugin.capability_hash.clone(),
4152 state_generation: plugin.state_generation,
4153 };
4154 let mut names = std::collections::BTreeSet::new();
4155 for path in &plugin.components.agents {
4156 if let Ok((profiles, issues)) =
4157 codewhale_engine::fleet::profile::load_plugin_agent_profiles_from_component(
4158 path, &authority,
4159 )
4160 {
4161 for profile in profiles {
4162 names.insert(profile.id);
4163 }
4164 for issue in issues {
4165 names.insert(issue.id);
4166 }
4167 } else if path.extension().and_then(|ext| ext.to_str()) == Some("toml")
4168 && let Some(stem) = path.file_stem().and_then(|stem| stem.to_str())
4169 {
4170 names.insert(stem.to_string());
4171 }
4172 }
4173 names.into_iter().collect()
4174 }
4175
4176 /// Convert one TUI MCP server config into the portable review detail.
4177 fn portable_mcp_server(
4178 name: &str,
4179 server: &codewhale_mcp::config::McpServerConfig,
4180 ) -> PluginMcpServerDetail {
4181 let transport = if server.url.is_some() {
4182 PluginMcpTransport::Http
4183 } else if server.command.is_some() {
4184 PluginMcpTransport::Stdio
4185 } else {
4186 PluginMcpTransport::Invalid
4187 };
4188 let mut env = server
4189 .env
4190 .iter()
4191 .map(|(k, v)| (k.clone(), v.clone()))
4192 .collect::<Vec<_>>();
4193 env.sort_unstable();
4194 let mut env_headers = server
4195 .env_headers
4196 .iter()
4197 .map(|(k, v)| (k.clone(), v.clone()))
4198 .collect::<Vec<_>>();
4199 env_headers.sort_unstable();
4200 PluginMcpServerDetail {
4201 name: name.to_string(),
4202 transport,
4203 command: server.command.clone(),
4204 argv: server.args.clone(),
4205 cwd: server.cwd.clone(),
4206 env,
4207 url: server.url.clone(),
4208 env_headers,
4209 bearer_token_env_var: server.bearer_token_env_var.clone(),
4210 connect_timeout_secs: server.connect_timeout,
4211 execute_timeout_secs: server.execute_timeout,
4212 read_timeout_secs: server.read_timeout,
4213 required: server.required,
4214 enabled_tools: server.enabled_tools.clone(),
4215 disabled_tools: server.disabled_tools.clone(),
4216 enabled: server.is_enabled(),
4217 }
4218 }
4219
4220 /// Convert a TUI-owned loaded plugin into the portable full detail.
4221 pub(crate) fn portable_detail(
4222 plugin: &codewhale_plugins::types::LoadedPlugin,
4223 registry: Option<&codewhale_plugins::PluginRegistry>,
4224 locale: Locale,
4225 ) -> PluginDetail {
4226 use codewhale_plugins::host_services::{
4227 PluginApprover, PluginCohort, cohort_of, offered, short_review_date, workspace_folder_name,
4228 };
4229 let mcp_servers = plugin
4230 .manifest
4231 .mcp_servers
4232 .as_ref()
4233 .map(|servers| {
4234 let mut list = servers
4235 .iter()
4236 .map(|(name, server)| portable_mcp_server(name, server))
4237 .collect::<Vec<_>>();
4238 list.sort_by(|a, b| a.name.cmp(&b.name));
4239 list
4240 })
4241 .unwrap_or_default();
4242 let trust_display = if plugin.trusted()
4243 && matches!(
4244 plugin.approved_by,
4245 Some(PluginApprover::Agent(_) | PluginApprover::CommandLine)
4246 ) {
4247 Some(tr(locale, MessageId::ExtensionsTrustNotReviewed).into_owned())
4248 } else {
4249 None
4250 };
4251 let approver = if plugin.trusted() || plugin.approved_by.is_some() {
4252 Some(localized_approver_label(
4253 locale,
4254 plugin.approved_by.as_ref(),
4255 ))
4256 } else {
4257 None
4258 };
4259 let reviewed_date = plugin
4260 .reviewed_at
4261 .as_deref()
4262 .map(|ts| short_review_date(ts).to_string());
4263 let enabled_by = plugin
4264 .enabled
4265 .then(|| localized_turned_on_by_label(locale, plugin.enabled_by.as_ref()));
4266 let agent_thread_id = match plugin.approved_by.as_ref() {
4267 Some(PluginApprover::Agent(agent)) => agent.thread_id.clone(),
4268 _ => None,
4269 };
4270 let agent_workspace_path = plugin
4271 .approved_by
4272 .as_ref()
4273 .and_then(PluginApprover::agent_workspace)
4274 .map(str::to_string);
4275 let reach_folder = agent_workspace_path
4276 .as_deref()
4277 .map(|ws| workspace_folder_name(ws).to_string());
4278 let process_note = matches!(
4279 cohort_of(plugin.approved_by.as_ref()),
4280 PluginCohort::Agent { .. }
4281 )
4282 .then(|| tr(locale, MessageId::CmdPluginAuditAgentProcessNote).into_owned());
4283 let host_service_review = registry.and_then(|reg| match plugin.approved_by.as_ref() {
4284 Some(approver) => reg.host_service_review_for(plugin.id.as_str(), approver),
4285 None => reg.host_service_review(plugin.id.as_str()),
4286 });
4287 let host_services = match host_service_review {
4288 Some(review) => review
4289 .lines
4290 .into_iter()
4291 .map(|line| {
4292 let can_use = line.offered && plugin.host_services.contains(&line.service);
4293 let withheld_by = if can_use {
4294 line.withheld_by.into_iter().map(|peer| peer.name).collect()
4295 } else {
4296 Vec::new()
4297 };
4298 PluginHostServiceDetail {
4299 service: format!("{} ({})", line.service.name(), line.service.label()),
4300 can_use,
4301 withheld_by,
4302 }
4303 })
4304 .collect(),
4305 None => plugin
4306 .inventory
4307 .host_services
4308 .iter()
4309 .copied()
4310 .map(|service| PluginHostServiceDetail {
4311 service: format!("{} ({})", service.name(), service.label()),
4312 can_use: offered(service) && plugin.host_services.contains(&service),
4313 withheld_by: Vec::new(),
4314 })
4315 .collect(),
4316 };
4317 let earlier_reviews = plugin
4318 .earlier_review_history()
4319 .iter()
4320 .map(|entry| PluginEarlierReview {
4321 reviewed_at: short_review_date(&entry.reviewed_at).to_string(),
4322 approver: localized_approver_label(locale, entry.approved_by.as_ref()),
4323 })
4324 .collect();
4325 PluginDetail {
4326 name: plugin.name().to_string(),
4327 id: plugin.id.as_str().to_string(),
4328 inventory_summary: plugin.inventory.summary(),
4329 version: plugin.manifest.plugin.version.clone(),
4330 origin: plugin.origin.as_str().to_string(),
4331 scope: plugin.scope.as_str().to_string(),
4332 state_label: plugin.state_label().to_string(),
4333 trust_status: plugin.trust_status.as_str().to_string(),
4334 trust_display,
4335 approver,
4336 reviewed_date,
4337 enabled_by,
4338 agent_thread_id,
4339 agent_workspace_path,
4340 reach_folder,
4341 outside_reach: plugin.outside_reach,
4342 process_note,
4343 host_services,
4344 earlier_reviews,
4345 compatibility: plugin.compatibility().as_str().to_string(),
4346 content_hash: plugin.content_hash.clone(),
4347 capability_hash: plugin.capability_hash.clone(),
4348 canonical_root: plugin.canonical_root.clone(),
4349 active: plugin.active(),
4350 trusted: plugin.trusted(),
4351 enabled: plugin.enabled,
4352 unsupported_labels: plugin
4353 .inventory
4354 .unsupported_labels()
4355 .into_iter()
4356 .map(str::to_string)
4357 .collect(),
4358 supported_labels: plugin
4359 .inventory
4360 .supported_labels()
4361 .into_iter()
4362 .map(str::to_string)
4363 .collect(),
4364 skills: plugin
4365 .skill_snapshots
4366 .iter()
4367 .map(|skill| format!("{}:{}", plugin.name(), skill.name))
4368 .collect(),
4369 commands: plugin_command_names(plugin),
4370 profiles: plugin_profile_names(plugin),
4371 filesystem_roots: plugin.inventory.filesystem_roots.clone(),
4372 network_hosts: plugin.inventory.network_hosts.clone(),
4373 stdio_mcp_servers: plugin.inventory.stdio_mcp_servers,
4374 lifecycle_mutation: plugin.inventory.lifecycle_mutation,
4375 mcp_servers,
4376 diagnostics: plugin.diagnostics.iter().map(portable_diagnostic).collect(),
4377 }
4378 }
4379
4380 /// Convert a TUI mutation receipt into the portable contract receipt.
4381 fn portable_plugin_mutation_receipt(
4382 receipt: &codewhale_plugins::mutation::PluginMutationReceipt,
4383 ) -> PluginMutationReceipt {
4384 let outcome = match &receipt.outcome {
4385 codewhale_plugins::mutation::PluginMutationOutcome::Installed => {
4386 PluginMutationOutcome::Installed
4387 }
4388 codewhale_plugins::mutation::PluginMutationOutcome::Updated => {
4389 PluginMutationOutcome::Updated
4390 }
4391 codewhale_plugins::mutation::PluginMutationOutcome::NoChange => {
4392 PluginMutationOutcome::NoChange
4393 }
4394 codewhale_plugins::mutation::PluginMutationOutcome::Uninstalled => {
4395 PluginMutationOutcome::Uninstalled
4396 }
4397 codewhale_plugins::mutation::PluginMutationOutcome::NeedsApproval(host) => {
4398 PluginMutationOutcome::NeedsApproval(host.clone())
4399 }
4400 codewhale_plugins::mutation::PluginMutationOutcome::NetworkDenied(host) => {
4401 PluginMutationOutcome::NetworkDenied(host.clone())
4402 }
4403 };
4404 PluginMutationReceipt {
4405 name: receipt.name.clone(),
4406 path: receipt.path.clone(),
4407 content_hash: receipt.content_hash.clone(),
4408 installed_content_hash: receipt.installed_content_hash.clone(),
4409 outcome,
4410 }
4411 }
4412
4413 /// Convert a TUI export receipt into the portable contract receipt.
4414 fn portable_export_receipt(
4415 receipt: &codewhale_plugins::export::PluginExportReceipt,
4416 ) -> PluginExportReceipt {
4417 PluginExportReceipt {
4418 exported_name: receipt.exported_name.clone(),
4419 target: receipt.target.clone(),
4420 display_name: receipt.display_name.clone(),
4421 wrote_mcp_json: receipt.wrote_mcp_json,
4422 files_copied: receipt.files_copied as u64,
4423 skills_normalized: receipt.skills_normalized,
4424 }
4425 }
4426
4427 /// Convert one TUI legacy tool entry into the portable value.
4428 fn portable_legacy_tool(
4429 path: &Path,
4430 metadata: &codewhale_engine::tools::plugin::PluginMetadata,
4431 ) -> PluginLegacyTool {
4432 PluginLegacyTool {
4433 name: metadata.name.clone(),
4434 description: metadata.description.clone(),
4435 approval: match metadata.approval {
4436 codewhale_engine::tools::spec::ApprovalRequirement::Auto => "auto",
4437 codewhale_engine::tools::spec::ApprovalRequirement::Suggest => "suggest",
4438 codewhale_engine::tools::spec::ApprovalRequirement::Required => "required",
4439 }
4440 .to_string(),
4441 input_schema: Some(
4442 serde_json::to_string_pretty(&metadata.input_schema).unwrap_or_default(),
4443 ),
4444 path: path.to_path_buf(),
4445 }
4446 }
4447
4448 /// Convert one TUI marketplace candidate into the portable value.
4449 fn portable_marketplace_candidate(
4450 entry: &codewhale_plugins::marketplace::store::StoredMarketplaceCatalog,
4451 candidate: &codewhale_plugins::marketplace::types::MarketplaceCandidate,
4452 registry: &codewhale_plugins::PluginRegistry,
4453 ) -> PluginMarketplaceCandidate {
4454 use codewhale_plugins::marketplace::document::{
4455 CatalogInstallResolution, resolve_candidate_install,
4456 };
4457 let install_plan = match resolve_candidate_install(entry, candidate, registry) {
4458 CatalogInstallResolution::Supported { spec, source_kind } => {
4459 PluginMarketplaceInstallPlan::Supported { spec, source_kind }
4460 }
4461 CatalogInstallResolution::AlreadyPresent { plugin, reason } => {
4462 PluginMarketplaceInstallPlan::AlreadyPresent {
4463 selector: plugin.id.as_str().to_string(),
4464 reason,
4465 }
4466 }
4467 CatalogInstallResolution::Unsupported { reason } => {
4468 PluginMarketplaceInstallPlan::Unsupported { reason }
4469 }
4470 CatalogInstallResolution::HasErrors { diagnostics } => {
4471 PluginMarketplaceInstallPlan::Unsupported {
4472 reason: diagnostics,
4473 }
4474 }
4475 };
4476 PluginMarketplaceCandidate {
4477 name: candidate.name.clone(),
4478 display_name: candidate.display_name.clone(),
4479 version: candidate.version.clone(),
4480 tier: candidate.provenance.tier.as_str().to_string(),
4481 compatibility: candidate
4482 .compatibility
4483 .as_ref()
4484 .map(|c| c.as_str().to_string()),
4485 install_plan,
4486 description: candidate.description.clone(),
4487 homepage: candidate.homepage.clone(),
4488 repository: candidate.repository.clone(),
4489 author: candidate.author.clone(),
4490 license: candidate.license.clone(),
4491 keywords: candidate.keywords.clone(),
4492 when: candidate.when.as_ref().map(|when| format!("{when:?}")),
4493 diagnostics: candidate
4494 .diagnostics
4495 .iter()
4496 .map(portable_marketplace_diagnostic)
4497 .collect(),
4498 has_errors: candidate.has_errors(),
4499 }
4500 }
4501
4502 /// Convert one stored TUI marketplace catalog (with its source path).
4503 fn portable_marketplace_catalog_with_source(
4504 entry: &codewhale_plugins::marketplace::store::StoredMarketplaceCatalog,
4505 registry: &codewhale_plugins::PluginRegistry,
4506 ) -> PluginMarketplaceCatalog {
4507 let catalog = &entry.catalog;
4508 PluginMarketplaceCatalog {
4509 id: catalog.id.as_str().to_string(),
4510 source_path: Some(entry.source_path.clone()),
4511 display_name: catalog.display_name.clone(),
4512 description: catalog.description.clone(),
4513 format: catalog.format.as_str().to_string(),
4514 tier: catalog.provenance.tier.as_str().to_string(),
4515 publisher: catalog.provenance.publisher.clone(),
4516 total_candidates: catalog.total_candidates(),
4517 warning_count: catalog.warning_count(),
4518 candidates: catalog
4519 .candidates
4520 .iter()
4521 .map(|candidate| portable_marketplace_candidate(entry, candidate, registry))
4522 .collect(),
4523 diagnostics: catalog
4524 .diagnostics
4525 .iter()
4526 .map(portable_marketplace_diagnostic)
4527 .collect(),
4528 }
4529 }
4530
4531 /// Kimi managed-plugin scan (host-side, FEAT-020 D1). Mirrors the legacy
4532 /// `/plugin import kimi` scan exactly: only immediate canonical children of
4533 /// `~/.kimi-code/plugins/managed`, rejecting symlinks/reparse points,
4534 /// non-directories, and children that escape the root. Returns portable
4535 /// candidate values; rejection reasons cross as safe text.
4536 fn scan_managed_plugins_portable(
4537 home_override: Option<&Path>,
4538 ) -> Result<PluginManagedScan, String> {
4539 use std::fs;
4540 use std::path::PathBuf;
4541
4542 const MAX_MANAGED_CHILDREN: usize = 128;
4543 const KIMI_PLUGIN_JSON_NAME: &str = codewhale_plugins::agent_plugin::KIMI_PLUGIN_JSON_NAME;
4544
4545 struct Candidate {
4546 name: String,
4547 version: String,
4548 license: Option<String>,
4549 canonical_path: PathBuf,
4550 content_hash: String,
4551 capability_hash: String,
4552 inventory: String,
4553 applicable: bool,
4554 }
4555
4556 fn inspect_candidate(canonical_path: &Path) -> Result<Candidate, String> {
4557 let manifest_path = canonical_path.join(KIMI_PLUGIN_JSON_NAME);
4558 let metadata = fs::symlink_metadata(&manifest_path).map_err(|error| {
4559 format!(
4560 "Kimi manifest unreadable at {}: {}",
4561 canonical_path.display(),
4562 error
4563 )
4564 })?;
4565 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
4566 || !metadata.is_file()
4567 {
4568 return Err(format!(
4569 "Kimi manifest must be a regular file at {}",
4570 canonical_path.display()
4571 ));
4572 }
4573 let validated =
4574 codewhale_plugins::manifest::PluginManifest::validate_from_path(&manifest_path)
4575 .map_err(|error| {
4576 format!(
4577 "Kimi manifest invalid at {}: {error}",
4578 canonical_path.display()
4579 )
4580 })?;
4581 let name = validated.manifest.plugin.name.clone();
4582 if canonical_path.file_name().and_then(|part| part.to_str()) != Some(name.as_str()) {
4583 return Err(format!(
4584 "Kimi directory name `{}` does not match manifest name `{}`",
4585 canonical_path.display(),
4586 name
4587 ));
4588 }
4589 Ok(Candidate {
4590 name,
4591 version: validated.manifest.plugin.version.clone(),
4592 license: validated.manifest.plugin.license.clone(),
4593 canonical_path: validated.canonical_root,
4594 content_hash: validated.content_hash,
4595 capability_hash: validated.capability_hash,
4596 inventory: validated.inventory.summary(),
4597 applicable: validated.applicable,
4598 })
4599 }
4600
4601 let home = match home_override {
4602 Some(home) => home.to_path_buf(),
4603 None => codewhale_paths::user_home().ok_or_else(|| {
4604 tr(
4605 codewhale_localization::Locale::En,
4606 codewhale_localization::MessageId::PluginKimiHomeMissing,
4607 )
4608 .into_owned()
4609 .to_string()
4610 })?,
4611 };
4612 let configured_root = home.join(".kimi-code/plugins/managed");
4613 let metadata = match fs::symlink_metadata(&configured_root) {
4614 Ok(metadata) => metadata,
4615 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
4616 return Ok(PluginManagedScan {
4617 root: configured_root,
4618 candidates: Vec::new(),
4619 rejected: Vec::new(),
4620 });
4621 }
4622 Err(error) => {
4623 let root_text = escape_review_text(
4624 &configured_root.display().to_string(),
4625 ReviewTextContext::Prose,
4626 );
4627 let error_text = escape_review_text(&error.to_string(), ReviewTextContext::Prose);
4628 return Err(tr(
4629 codewhale_localization::Locale::En,
4630 codewhale_localization::MessageId::PluginKimiRootInspectFailed,
4631 )
4632 .replace("{root}", &root_text)
4633 .replace("{error}", &error_text));
4634 }
4635 };
4636 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
4637 let root_text = escape_review_text(
4638 &configured_root.display().to_string(),
4639 ReviewTextContext::Prose,
4640 );
4641 return Err(tr(
4642 codewhale_localization::Locale::En,
4643 codewhale_localization::MessageId::PluginKimiRootMustBeDirectory,
4644 )
4645 .replace("{root}", &root_text));
4646 }
4647 let canonical_root = configured_root.canonicalize().map_err(|error| {
4648 let root_text = escape_review_text(
4649 &configured_root.display().to_string(),
4650 ReviewTextContext::Prose,
4651 );
4652 let error_text = escape_review_text(&error.to_string(), ReviewTextContext::Prose);
4653 tr(
4654 codewhale_localization::Locale::En,
4655 codewhale_localization::MessageId::PluginKimiRootCanonicalizeFailed,
4656 )
4657 .replace("{root}", &root_text)
4658 .replace("{error}", &error_text)
4659 })?;
4660 let mut entries = fs::read_dir(&canonical_root)
4661 .map_err(|error| {
4662 let root_text = escape_review_text(
4663 &canonical_root.display().to_string(),
4664 ReviewTextContext::Prose,
4665 );
4666 let error_text = escape_review_text(&error.to_string(), ReviewTextContext::Prose);
4667 tr(
4668 codewhale_localization::Locale::En,
4669 codewhale_localization::MessageId::PluginKimiRootListFailed,
4670 )
4671 .replace("{root}", &root_text)
4672 .replace("{error}", &error_text)
4673 })?
4674 .collect::<Result<Vec<_>, _>>()
4675 .map_err(|error| {
4676 let error_text = escape_review_text(&error.to_string(), ReviewTextContext::Prose);
4677 tr(
4678 codewhale_localization::Locale::En,
4679 codewhale_localization::MessageId::PluginKimiEntryReadFailed,
4680 )
4681 .replace("{error}", &error_text)
4682 })?;
4683 if entries.len() > MAX_MANAGED_CHILDREN {
4684 return Err(tr(
4685 codewhale_localization::Locale::En,
4686 codewhale_localization::MessageId::PluginKimiEntryLimit,
4687 )
4688 .replace("{count}", &entries.len().to_string())
4689 .replace("{max}", &MAX_MANAGED_CHILDREN.to_string()));
4690 }
4691 entries.sort_by_key(fs::DirEntry::file_name);
4692
4693 let mut candidates = Vec::new();
4694 let mut rejected = Vec::new();
4695 for entry in entries {
4696 let path = entry.path();
4697 let metadata = match fs::symlink_metadata(&path) {
4698 Ok(metadata) => metadata,
4699 Err(error) => {
4700 let path_text =
4701 escape_review_text(&path.display().to_string(), ReviewTextContext::Prose);
4702 let error_text = escape_review_text(&error.to_string(), ReviewTextContext::Prose);
4703 rejected.push(
4704 tr(
4705 codewhale_localization::Locale::En,
4706 codewhale_localization::MessageId::PluginKimiEntryInspectFailed,
4707 )
4708 .replace("{path}", &path_text)
4709 .replace("{error}", &error_text),
4710 );
4711 continue;
4712 }
4713 };
4714 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) {
4715 let path_text = escape_review_path(&path, ReviewTextContext::Prose);
4716 rejected.push(
4717 tr(
4718 codewhale_localization::Locale::En,
4719 codewhale_localization::MessageId::PluginKimiEntryLinksRefused,
4720 )
4721 .replace("{path}", &path_text),
4722 );
4723 continue;
4724 }
4725 if !metadata.is_dir() {
4726 continue;
4727 }
4728 let canonical_path = match path.canonicalize() {
4729 Ok(path) if path.parent() == Some(canonical_root.as_path()) => path,
4730 Ok(canonical_path) => {
4731 let path_text =
4732 escape_review_text(&path.display().to_string(), ReviewTextContext::Prose);
4733 let canonical_text = escape_review_text(
4734 &canonical_path.display().to_string(),
4735 ReviewTextContext::Prose,
4736 );
4737 rejected.push(
4738 tr(
4739 codewhale_localization::Locale::En,
4740 codewhale_localization::MessageId::PluginKimiEntryOutsideRoot,
4741 )
4742 .replace("{path}", &path_text)
4743 .replace("{canonical_path}", &canonical_text),
4744 );
4745 continue;
4746 }
4747 Err(error) => {
4748 let path_text =
4749 escape_review_text(&path.display().to_string(), ReviewTextContext::Prose);
4750 let error_text = escape_review_text(&error.to_string(), ReviewTextContext::Prose);
4751 rejected.push(
4752 tr(
4753 codewhale_localization::Locale::En,
4754 codewhale_localization::MessageId::PluginKimiEntryCanonicalizeFailed,
4755 )
4756 .replace("{path}", &path_text)
4757 .replace("{error}", &error_text),
4758 );
4759 continue;
4760 }
4761 };
4762 match inspect_candidate(&canonical_path) {
4763 Ok(candidate) => candidates.push(candidate),
4764 Err(error) => rejected.push(error),
4765 }
4766 }
4767 candidates.sort_by(|left, right| left.name.cmp(&right.name));
4768 Ok(PluginManagedScan {
4769 root: canonical_root,
4770 candidates: candidates
4771 .into_iter()
4772 .map(|candidate| PluginManagedCandidate {
4773 name: candidate.name,
4774 version: candidate.version,
4775 license: candidate.license,
4776 canonical_path: candidate.canonical_path,
4777 content_hash: candidate.content_hash,
4778 capability_hash: candidate.capability_hash,
4779 inventory: candidate.inventory,
4780 applicable: candidate.applicable,
4781 })
4782 .collect(),
4783 rejected,
4784 })
4785 }
4786
4787 /// Escape review text exactly like the plugin render helpers (FEAT-020 D2).
4788 fn escape_review_text(value: &str, context: ReviewTextContext) -> String {
4789 crate::commands::groups::plugins::render::escape_review_text(value, context)
4790 }
4791
4792 /// Escape a review path exactly like the plugin render helpers (FEAT-020 D2).
4793 fn escape_review_path(path: &Path, context: ReviewTextContext) -> String {
4794 crate::commands::groups::plugins::render::escape_review_path(path, context)
4795 }
4796
4797 impl CommandPluginContext for PluginAdapter<'_> {
4798 fn summaries(&self) -> Result<Vec<PluginSummary>, String> {
4799 let app = self.host.app.borrow();
4800 let locale = app.ui_locale;
4801 Ok(app
4802 .plugin_registry
4803 .list()
4804 .iter()
4805 .map(|plugin| portable_summary(plugin, locale))
4806 .collect())
4807 }
4808
4809 fn detail(&self, selector: &str) -> Result<PluginDetail, String> {
4810 let app = self.host.app.borrow();
4811 let locale = app.ui_locale;
4812 let plugin = app
4813 .plugin_registry
4814 .get(selector)
4815 .ok_or_else(|| format!("no plugin named {selector}"))?;
4816 let mut detail = portable_detail(plugin, Some(&app.plugin_registry), locale);
4817 let mut commands: std::collections::BTreeSet<String> =
4818 detail.commands.into_iter().collect();
4819 for entry in
4820 codewhale_engine::extension_host::live_commands_for_plugins(&app.plugin_registry)
4821 {
4822 if entry.authority.plugin_id == plugin.id {
4823 commands.insert(format!("/{}", entry.registration.name.to_ascii_lowercase()));
4824 }
4825 }
4826 detail.commands = commands.into_iter().collect();
4827 let mut profiles: std::collections::BTreeSet<String> =
4828 detail.profiles.into_iter().collect();
4829 for (preset, authority) in
4830 codewhale_engine::extension_host::native_presets_for_plugins(&app.plugin_registry)
4831 {
4832 if authority.plugin_id == plugin.id {
4833 let label =
4834 codewhale_plugins::native_presets::metadata(&app.plugin_registry, &preset)
4835 .map(|data| data.name.unwrap_or(data.id))
4836 .unwrap_or_else(|| preset.entry.path.clone());
4837 profiles.insert(label);
4838 }
4839 }
4840 detail.profiles = profiles.into_iter().collect();
4841 Ok(detail)
4842 }
4843
4844 fn registry_diagnostics(&self) -> Vec<PluginDiagnostic> {
4845 self.host
4846 .app
4847 .borrow()
4848 .plugin_registry
4849 .diagnostics()
4850 .iter()
4851 .map(portable_diagnostic)
4852 .collect()
4853 }
4854
4855 fn validation_is_clean(&self) -> bool {
4856 self.host.app.borrow().plugin_registry.validation_is_clean()
4857 }
4858
4859 fn len(&self) -> usize {
4860 self.host.app.borrow().plugin_registry.len()
4861 }
4862
4863 fn is_empty(&self) -> bool {
4864 self.host.app.borrow().plugin_registry.is_empty()
4865 }
4866
4867 fn reload(&mut self) -> Result<usize, String> {
4868 let mut app = self.host.app.borrow_mut();
4869 let workspace = app.workspace.clone();
4870 app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace);
4871 app.refresh_skill_cache();
4872 app.refresh_agent_approved_plugins_notice();
4873 Ok(app.plugin_registry.len())
4874 }
4875
4876 fn reload_nudge(&mut self) -> Option<String> {
4877 let mut app = self.host.app.borrow_mut();
4878 let registry = app.plugin_registry.clone();
4879 codewhale_plugins::plugin_reload_nudge(
4880 registry.as_ref(),
4881 &mut app.plugin_reload_nudge_stamp,
4882 )
4883 .map(str::to_string)
4884 }
4885
4886 fn state_path(&self) -> Option<PathBuf> {
4887 self.host
4888 .app
4889 .borrow()
4890 .plugin_registry
4891 .state_path()
4892 .map(Path::to_path_buf)
4893 }
4894
4895 fn suggest(&self, task: &str) -> Result<Vec<PluginSuggestion>, String> {
4896 let task = task.trim();
4897 if task.chars().count() < 3 {
4898 return Err("Usage: /plugin suggest <task of at least 3 characters>".to_string());
4899 }
4900 let app = self.host.app.borrow();
4901 let marketplace = codewhale_plugins::recommend::load_marketplace_candidates(
4902 app.plugin_registry.state_path(),
4903 );
4904 let recommendations = codewhale_plugins::recommend::recommend_plugins_for_task(
4905 task,
4906 app.plugin_registry.as_ref(),
4907 &marketplace,
4908 codewhale_plugins::recommend::RecommendOptions::default(),
4909 );
4910 Ok(recommendations
4911 .into_iter()
4912 .map(|recommendation| {
4913 let description = match &recommendation.source {
4914 codewhale_plugins::recommend::PluginMatchSource::Installed { id } => app
4915 .plugin_registry
4916 .get(id)
4917 .and_then(|plugin| plugin.manifest.plugin.description.clone())
4918 .filter(|description| !description.trim().is_empty())
4919 .unwrap_or_else(|| "No description provided.".to_string()),
4920 codewhale_plugins::recommend::PluginMatchSource::Marketplace { catalog_id } => {
4921 marketplace
4922 .iter()
4923 .find(|candidate| {
4924 candidate.name.eq_ignore_ascii_case(&recommendation.name)
4925 && candidate.catalog_id.as_str() == catalog_id
4926 })
4927 .and_then(|candidate| candidate.description.clone())
4928 .filter(|description| !description.trim().is_empty())
4929 .unwrap_or_else(|| "Catalog plugin.".to_string())
4930 }
4931 };
4932 let state_label = match &recommendation.source {
4933 codewhale_plugins::recommend::PluginMatchSource::Installed { id } => app
4934 .plugin_registry
4935 .get(id)
4936 .map(|plugin| plugin.state_label().to_string())
4937 .unwrap_or_else(|| "installed".to_string()),
4938 codewhale_plugins::recommend::PluginMatchSource::Marketplace { .. } => {
4939 "not installed".to_string()
4940 }
4941 };
4942 PluginSuggestion {
4943 name: recommendation.name.clone(),
4944 state_label,
4945 description,
4946 why: recommendation.matched_terms.clone(),
4947 next_step: recommendation.command(),
4948 }
4949 })
4950 .collect())
4951 }
4952
4953 fn trust(&mut self, selector: &str, token: &str) -> Result<(), String> {
4954 let expected = {
4955 let app = self.host.app.borrow();
4956 app.plugin_registry
4957 .get(selector)
4958 .map(codewhale_plugins::types::LoadedPlugin::review_token)
4959 .ok_or_else(|| format!("no plugin named {selector}"))?
4960 };
4961 if token != expected {
4962 return Err(
4963 "Review token does not match this bundle content and capability set; run `/plugin trust <name>` again"
4964 .to_string(),
4965 );
4966 }
4967 {
4968 let mut app = self.host.app.borrow_mut();
4969 std::sync::Arc::make_mut(&mut app.plugin_registry).trust(selector)?;
4970 app.refresh_skill_cache();
4971 app.refresh_agent_approved_plugins_notice();
4972 }
4973 Ok(())
4974 }
4975
4976 fn enable(&mut self, selector: &str) -> Result<(), String> {
4977 let needs_review = self
4978 .host
4979 .app
4980 .borrow()
4981 .plugin_registry
4982 .get(selector)
4983 .is_some_and(|plugin| !plugin.trusted());
4984 if needs_review {
4985 // Enabling is the natural entry point; open the capability review
4986 // instead of an opaque denial (matches the legacy handler).
4987 return Err("plugin requires review before enabling".to_string());
4988 }
4989 let mut app = self.host.app.borrow_mut();
4990 std::sync::Arc::make_mut(&mut app.plugin_registry).enable(selector)?;
4991 // Rediscover, as install and reload do: an in-place enable keeps the
4992 // pinned Native selection, so a host plugin enabled after a preset
4993 // catalog was already active would never be activated.
4994 let workspace = app.workspace.clone();
4995 app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace);
4996 app.refresh_skill_cache();
4997 app.refresh_agent_approved_plugins_notice();
4998 Ok(())
4999 }
5000
5001 fn restage(&mut self, selector: &str) -> Result<(), String> {
5002 let mut app = self.host.app.borrow_mut();
5003 std::sync::Arc::make_mut(&mut app.plugin_registry).restage(selector)?;
5004 let workspace = app.workspace.clone();
5005 app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace);
5006 app.refresh_skill_cache();
5007 app.refresh_agent_approved_plugins_notice();
5008 Ok(())
5009 }
5010
5011 fn disable(&mut self, selector: &str) -> Result<(), String> {
5012 let mut app = self.host.app.borrow_mut();
5013 std::sync::Arc::make_mut(&mut app.plugin_registry).disable(selector)?;
5014 app.refresh_skill_cache();
5015 app.refresh_agent_approved_plugins_notice();
5016 app.active_skill = None;
5017 app.active_skill_provenance = None;
5018 Ok(())
5019 }
5020
5021 fn revoke_trust(&mut self, selector: &str) -> Result<(), String> {
5022 let mut app = self.host.app.borrow_mut();
5023 std::sync::Arc::make_mut(&mut app.plugin_registry).revoke_trust(selector)?;
5024 app.refresh_skill_cache();
5025 app.refresh_agent_approved_plugins_notice();
5026 app.active_skill = None;
5027 app.active_skill_provenance = None;
5028 Ok(())
5029 }
5030
5031 fn install(
5032 &mut self,
5033 source: &str,
5034 expected_content_hash: Option<&str>,
5035 ) -> Result<PluginMutationReceipt, String> {
5036 use codewhale_plugins::install::PluginInstallSource;
5037 use codewhale_plugins::mutation::{
5038 PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
5039 };
5040
5041 let plugin_source = PluginInstallSource::parse(source).map_err(|error| {
5042 format!(
5043 "Invalid plugin install source `{source}`: {error:#}\n\
5044 Expected a local path, github:owner/repo, an HTTPS tarball URL, or builtin:<name>."
5045 )
5046 })?;
5047 let network = plugin_network_policy();
5048 let expected_content_hash = expected_content_hash.map(str::to_string);
5049 let expected_for_request = expected_content_hash.clone();
5050 let mut app = self.host.app.borrow_mut();
5051 let registry = std::sync::Arc::make_mut(&mut app.plugin_registry);
5052 let outcome = run_async(async move {
5053 let ctx = PluginMutationContext {
5054 network: &network,
5055 max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
5056 };
5057 let request = match expected_for_request {
5058 Some(expected_content_hash) => PluginMutationRequest::InstallExact {
5059 source: plugin_source,
5060 expected_content_hash,
5061 },
5062 None => PluginMutationRequest::Install {
5063 source: plugin_source,
5064 },
5065 };
5066 codewhale_plugins::mutation::execute(request, &ctx, registry).await
5067 });
5068 match outcome {
5069 Ok(receipt) => {
5070 let portable = portable_plugin_mutation_receipt(&receipt);
5071 // Rediscover and refresh the skill cache after any install.
5072 if matches!(receipt.outcome, PluginMutationOutcome::Installed) {
5073 let workspace = app.workspace.clone();
5074 app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace);
5075 app.refresh_skill_cache();
5076 app.refresh_agent_approved_plugins_notice();
5077 }
5078 Ok(portable)
5079 }
5080 Err(error) => Err(format!("Plugin install failed: {error:#}")),
5081 }
5082 }
5083
5084 fn update(&mut self, selector: &str) -> Result<PluginMutationReceipt, String> {
5085 use codewhale_plugins::mutation::{
5086 PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
5087 };
5088 let network = plugin_network_policy();
5089 let selector_owned = selector.to_string();
5090 let mut app = self.host.app.borrow_mut();
5091 let registry = std::sync::Arc::make_mut(&mut app.plugin_registry);
5092 let outcome = run_async(async move {
5093 let ctx = PluginMutationContext {
5094 network: &network,
5095 max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
5096 };
5097 codewhale_plugins::mutation::execute(
5098 PluginMutationRequest::Update {
5099 selector: selector_owned,
5100 },
5101 &ctx,
5102 registry,
5103 )
5104 .await
5105 });
5106 match outcome {
5107 Ok(receipt) => {
5108 let portable = portable_plugin_mutation_receipt(&receipt);
5109 if matches!(receipt.outcome, PluginMutationOutcome::Updated) {
5110 let workspace = app.workspace.clone();
5111 app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace);
5112 app.refresh_skill_cache();
5113 app.refresh_agent_approved_plugins_notice();
5114 }
5115 Ok(portable)
5116 }
5117 Err(error) => Err(format!("Plugin update failed: {error:#}")),
5118 }
5119 }
5120
5121 fn uninstall(&mut self, selector: &str) -> Result<PluginMutationReceipt, String> {
5122 use codewhale_plugins::mutation::{
5123 PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
5124 };
5125 let network = plugin_network_policy();
5126 let selector_owned = selector.to_string();
5127 let mut app = self.host.app.borrow_mut();
5128 let registry = std::sync::Arc::make_mut(&mut app.plugin_registry);
5129 let outcome = run_async(async move {
5130 let ctx = PluginMutationContext {
5131 network: &network,
5132 max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
5133 };
5134 codewhale_plugins::mutation::execute(
5135 PluginMutationRequest::Uninstall {
5136 selector: selector_owned,
5137 },
5138 &ctx,
5139 registry,
5140 )
5141 .await
5142 });
5143 match outcome {
5144 Ok(receipt) => {
5145 let portable = portable_plugin_mutation_receipt(&receipt);
5146 if matches!(receipt.outcome, PluginMutationOutcome::Uninstalled) {
5147 let workspace = app.workspace.clone();
5148 app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace);
5149 app.refresh_skill_cache();
5150 app.refresh_agent_approved_plugins_notice();
5151 app.active_skill = None;
5152 app.active_skill_provenance = None;
5153 }
5154 Ok(portable)
5155 }
5156 Err(error) => Err(format!("Plugin uninstall failed: {error:#}")),
5157 }
5158 }
5159
5160 fn uninstall_path(&mut self, name: &str, plugins_dir: &Path) -> Result<(), String> {
5161 // File-level rollback removal for a bundle whose content hash
5162 // mismatched; no registry resolution, rediscovery, or skill side
5163 // effects (FEAT-020 D1 — the `codewhale_plugins` call stays host-side).
5164 let name = name.to_string();
5165 let plugins_dir = plugins_dir.to_path_buf();
5166 run_owner_blocking(move || {
5167 codewhale_plugins::install::uninstall(&name, &plugins_dir)
5168 .map_err(|error| format!("{error:#}"))
5169 })
5170 }
5171
5172 fn export(&self, selector: &str, target: &Path) -> Result<PluginExportReceipt, String> {
5173 let (plugin, existing_names, target) = {
5174 let app = self.host.app.borrow();
5175 let plugin = app
5176 .plugin_registry
5177 .get(selector)
5178 .ok_or_else(|| format!("no plugin named {selector}"))?
5179 .clone();
5180 let existing_names: std::collections::BTreeSet<String> = app
5181 .plugin_registry
5182 .list()
5183 .iter()
5184 .map(|other| other.name().to_string())
5185 .filter(|name| name != plugin.name())
5186 .collect();
5187 let target = if target.is_absolute() {
5188 target.to_path_buf()
5189 } else {
5190 app.workspace.join(target)
5191 };
5192 (plugin, existing_names, target)
5193 };
5194 run_owner_blocking(move || {
5195 codewhale_plugins::export::export_plugin_bundle(&plugin, &target, &existing_names)
5196 .map(|receipt| portable_export_receipt(&receipt))
5197 .map_err(|error| format!("Export of `{}` failed: {}", plugin.name(), error))
5198 })
5199 }
5200
5201 fn legacy_scan(&self) -> Result<Option<PluginLegacyScan>, String> {
5202 let dir = {
5203 let app = self.host.app.borrow();
5204 app.legacy_plugin_tools_dir
5205 .clone()
5206 .or_else(default_codewhale_tools_dir)
5207 };
5208 let Some(dir) = dir else {
5209 return Ok(None);
5210 };
5211 run_owner_blocking(move || {
5212 if !dir.exists() {
5213 return Ok(None);
5214 }
5215 let discovered = codewhale_engine::tools::plugin::scan_plugin_dir(&dir);
5216 let diagnostics = discovered
5217 .iter()
5218 .filter(|(_, metadata)| metadata.auto_approval_ignored)
5219 .map(|(path, metadata)| PluginDiagnostic {
5220 level: PluginDiagnosticLevel::Warning,
5221 code: "script_tool_auto_approval_ignored".to_string(),
5222 message: format!(
5223 "script tool '{}': {}",
5224 metadata.name,
5225 codewhale_engine::tools::plugin::AUTO_APPROVAL_UNSUPPORTED
5226 ),
5227 path: Some(path.clone()),
5228 })
5229 .collect();
5230 let tools = discovered
5231 .iter()
5232 .map(|(path, metadata)| portable_legacy_tool(path, metadata))
5233 .collect();
5234 Ok(Some(PluginLegacyScan {
5235 dir,
5236 tools,
5237 diagnostics,
5238 }))
5239 })
5240 }
5241
5242 fn managed_scan(&self, home_override: Option<&Path>) -> Result<PluginManagedScan, String> {
5243 let home = home_override.map(Path::to_path_buf);
5244 run_owner_blocking(move || scan_managed_plugins_portable(home.as_deref()))
5245 }
5246
5247 fn dsh_preview(
5248 &self,
5249 package: &Path,
5250 ) -> Result<codewhale_command_contract::facets::PluginDshPreview, String> {
5251 let package = package.to_path_buf();
5252 let preview = move || {
5253 let canonical = package
5254 .canonicalize()
5255 .map_err(|_| format!("DSH package not found at {}", package.display()))?;
5256 let (conversion, content_hash) = codewhale_plugins::install::preview_dsh(&canonical)
5257 .map_err(|error| format!("{error:#}"))?;
5258 Ok(codewhale_command_contract::facets::PluginDshPreview {
5259 package_path: canonical,
5260 plugin_name: conversion.plugin_name,
5261 source_package: conversion.source_package,
5262 source_version: conversion.source_version,
5263 content_hash,
5264 skills: conversion.skills,
5265 commands: conversion.commands,
5266 agents: conversion.agents,
5267 hooks: conversion.hooks,
5268 remote_servers: conversion.remote_servers,
5269 local_servers: conversion.local_servers,
5270 network_hosts: conversion.network_hosts,
5271 native_rows: conversion.native_rows,
5272 requires_node: conversion.requires_node,
5273 manual_ports: conversion
5274 .outcomes
5275 .iter()
5276 .filter(|outcome| outcome.needs_manual_port())
5277 .map(|outcome| {
5278 format!(
5279 "{} ({}) {}: {}",
5280 outcome.row.as_deref().unwrap_or("unlabeled"),
5281 outcome.package.as_deref().unwrap_or("unlabeled"),
5282 outcome.kind,
5283 outcome.reason
5284 )
5285 })
5286 .collect(),
5287 diagnostics: conversion.diagnostics,
5288 })
5289 };
5290 // Native composition review owns a bounded async process runner. Like
5291 // the Runtime API and installer, keep the complete filesystem/reviewer
5292 // operation off the TUI worker before entering that runner.
5293 if tokio::runtime::Handle::try_current().is_err() {
5294 return preview();
5295 }
5296 #[cfg(test)]
5297 let ticket = crate::test_support::env_scope_ticket();
5298 run_async(async move {
5299 tokio::task::spawn_blocking(move || {
5300 #[cfg(test)]
5301 let _membership = crate::test_support::join_env_scope(ticket);
5302 preview()
5303 })
5304 .await
5305 .map_err(|error| format!("DSH preview task failed: {error}"))?
5306 })
5307 }
5308
5309 fn managed_install(
5310 &mut self,
5311 canonical_path: &Path,
5312 expected_content_hash: &str,
5313 ) -> Result<PluginMutationReceipt, String> {
5314 use codewhale_plugins::install::PluginInstallSource;
5315 use codewhale_plugins::mutation::{
5316 PluginMutationContext, PluginMutationOutcome, PluginMutationRequest,
5317 };
5318 let network = plugin_network_policy();
5319 let expected_content_hash = expected_content_hash.to_string();
5320 let path = canonical_path.to_path_buf();
5321 let mut app = self.host.app.borrow_mut();
5322 let registry = std::sync::Arc::make_mut(&mut app.plugin_registry);
5323 let outcome = run_async(async move {
5324 let ctx = PluginMutationContext {
5325 network: &network,
5326 max_size: codewhale_plugins::install::DEFAULT_MAX_SIZE_BYTES,
5327 };
5328 codewhale_plugins::mutation::execute(
5329 PluginMutationRequest::InstallExact {
5330 source: PluginInstallSource::LocalPath(path),
5331 expected_content_hash,
5332 },
5333 &ctx,
5334 registry,
5335 )
5336 .await
5337 });
5338 match outcome {
5339 Ok(receipt) => {
5340 let portable = portable_plugin_mutation_receipt(&receipt);
5341 if matches!(receipt.outcome, PluginMutationOutcome::Installed) {
5342 let workspace = app.workspace.clone();
5343 app.plugin_registry = app.plugin_registry.rediscover_for_workspace(&workspace);
5344 app.refresh_skill_cache();
5345 app.refresh_agent_approved_plugins_notice();
5346 }
5347 Ok(portable)
5348 }
5349 Err(error) => Err(format!("Plugin install failed: {error:#}")),
5350 }
5351 }
5352
5353 fn marketplace_state(&self) -> Result<PluginMarketplaceState, String> {
5354 let (state_path, registry) = {
5355 let app = self.host.app.borrow();
5356 (
5357 app.plugin_registry.state_path().map(Path::to_path_buf),
5358 std::sync::Arc::clone(&app.plugin_registry),
5359 )
5360 };
5361 run_owner_blocking(move || {
5362 let store =
5363 codewhale_plugins::marketplace::store::MarketplaceStore::open(state_path.as_deref())
5364 .ok_or_else(|| {
5365 "This plugin registry has no persistence store, so marketplace catalogs cannot be saved."
5366 .to_string()
5367 })?;
5368 let state = store.load()?;
5369 let stored = state
5370 .catalogs()
5371 .values()
5372 .map(|entry| portable_marketplace_catalog_with_source(entry, &registry))
5373 .collect();
5374 Ok(PluginMarketplaceState {
5375 official: None,
5376 stored,
5377 })
5378 })
5379 }
5380
5381 fn marketplace_add(
5382 &mut self,
5383 name: &str,
5384 path: &Path,
5385 ) -> Result<PluginMarketplaceAddReceipt, String> {
5386 let app = self.host.app.borrow();
5387 let store = codewhale_plugins::marketplace::store::MarketplaceStore::open(
5388 app.plugin_registry.state_path(),
5389 )
5390 .ok_or_else(|| {
5391 "This plugin registry has no persistence store, so marketplace catalogs cannot be saved."
5392 .to_string()
5393 })?;
5394 let raw_path = path.to_string_lossy();
5395 let loaded = codewhale_plugins::marketplace::document::load_catalog_document(
5396 name,
5397 &app.workspace,
5398 &raw_path,
5399 )?;
5400 let candidate_count = loaded.candidate_count;
5401 let warning_count = loaded.warning_count;
5402 let portable_catalog =
5403 portable_marketplace_catalog_with_source(&loaded.entry, &app.plugin_registry);
5404 store.add(&loaded.entry.catalog.id.clone(), loaded.entry)?;
5405 Ok(PluginMarketplaceAddReceipt {
5406 name: name.to_string(),
5407 candidate_count,
5408 warning_count,
5409 catalog: portable_catalog,
5410 })
5411 }
5412
5413 fn marketplace_remove(&mut self, name: &str) -> Result<bool, String> {
5414 let app = self.host.app.borrow();
5415 let store = codewhale_plugins::marketplace::store::MarketplaceStore::open(
5416 app.plugin_registry.state_path(),
5417 )
5418 .ok_or_else(|| {
5419 "This plugin registry has no persistence store, so marketplace catalogs cannot be saved."
5420 .to_string()
5421 })?;
5422 store.remove(name)
5423 }
5424
5425 fn marketplace_install(
5426 &mut self,
5427 catalog: &str,
5428 candidate: &str,
5429 ) -> Result<PluginMutationReceipt, String> {
5430 let app = self.host.app.borrow();
5431 let store = codewhale_plugins::marketplace::store::MarketplaceStore::open(
5432 app.plugin_registry.state_path(),
5433 )
5434 .ok_or_else(|| {
5435 "This plugin registry has no persistence store, so marketplace catalogs cannot be saved."
5436 .to_string()
5437 })?;
5438 let state = store.load()?;
5439 let catalog_text = escape_review_text(catalog, ReviewTextContext::InlineCode);
5440 let candidate_text = escape_review_text(candidate, ReviewTextContext::InlineCode);
5441 let entry = state.get(catalog).cloned().ok_or_else(|| {
5442 format!("No marketplace named `{catalog_text}`. Use /plugin marketplace list.")
5443 })?;
5444 let candidate_entry = entry.catalog.candidate_by_name(candidate).ok_or_else(|| {
5445 format!("No candidate `{candidate_text}` in marketplace `{catalog_text}`.")
5446 })?;
5447 let spec = match codewhale_plugins::marketplace::document::resolve_candidate_install(
5448 &entry,
5449 candidate_entry,
5450 &app.plugin_registry,
5451 ) {
5452 codewhale_plugins::marketplace::document::CatalogInstallResolution::Supported {
5453 spec,
5454 ..
5455 } => spec,
5456 codewhale_plugins::marketplace::document::CatalogInstallResolution::AlreadyPresent {
5457 plugin,
5458 reason,
5459 } => {
5460 // Installing a bundle Codewhale ships succeeds as a no-op
5461 // (B5); any other occupied name stays a refusal.
5462 if plugin.scope == codewhale_plugins::types::PluginScope::Builtin {
5463 return Ok(PluginMutationReceipt {
5464 name: plugin.id.as_str().to_string(),
5465 path: None,
5466 content_hash: Some(plugin.content_hash.clone()),
5467 installed_content_hash: None,
5468 outcome:
5469 codewhale_command_contract::facets::PluginMutationOutcome::NoChange,
5470 });
5471 }
5472 return Err(escape_review_text(&reason, ReviewTextContext::Prose));
5473 }
5474 codewhale_plugins::marketplace::document::CatalogInstallResolution::Unsupported {
5475 reason,
5476 } => {
5477 let localized = key_to_plugin_message_id(&reason)
5478 .map(|message_id| tr(app.ui_locale, message_id).into_owned())
5479 .unwrap_or(reason);
5480 return Err(format!(
5481 "Candidate `{candidate_text}` cannot be installed by Codewhale: {}",
5482 escape_review_text(&localized, ReviewTextContext::Prose)
5483 ));
5484 }
5485 codewhale_plugins::marketplace::document::CatalogInstallResolution::HasErrors {
5486 diagnostics,
5487 } => {
5488 return Err(format!(
5489 "Candidate `{candidate_text}` has parse errors and cannot be installed:\n{}",
5490 escape_review_text(&diagnostics, ReviewTextContext::Prose)
5491 ));
5492 }
5493 };
5494 drop(app);
5495 self.install(&spec, None)
5496 }
5497
5498 fn suggestion_dismissals(
5499 &self,
5500 ) -> Result<codewhale_command_contract::facets::PluginSuggestionDismissals, String> {
5501 // Stored lowercase by the CTA, but a hand-edited settings file may not
5502 // be; fold here so the list matches what suggestions actually skip.
5503 let persisted: std::collections::BTreeSet<String> =
5504 codewhale_runtime::settings::Settings::load()
5505 .map_err(|err| format!("could not read saved plugin dismissals: {err}"))?
5506 .dismissed_plugin_suggestions
5507 .iter()
5508 .map(|name| name.to_ascii_lowercase())
5509 .collect();
5510 let app = self.host.app.borrow();
5511 let session = app
5512 .plugin_cta
5513 .dismissed
5514 .iter()
5515 .filter(|name| !persisted.contains(*name))
5516 .cloned()
5517 .collect();
5518 Ok(
5519 codewhale_command_contract::facets::PluginSuggestionDismissals {
5520 persisted: persisted.into_iter().collect(),
5521 session,
5522 },
5523 )
5524 }
5525
5526 fn reset_suggestion_dismissals(&mut self, name: Option<&str>) -> Result<Vec<String>, String> {
5527 let matches =
5528 |candidate: &String| name.is_none_or(|target| candidate.eq_ignore_ascii_case(target));
5529 let mut cleared = std::collections::BTreeSet::new();
5530 codewhale_runtime::settings::Settings::transact_opt(|settings| {
5531 let before = settings.dismissed_plugin_suggestions.len();
5532 settings.dismissed_plugin_suggestions.retain(|candidate| {
5533 let reset = matches(candidate);
5534 if reset {
5535 cleared.insert(candidate.to_ascii_lowercase());
5536 }
5537 !reset
5538 });
5539 Ok((settings.dismissed_plugin_suggestions.len() != before).then_some(()))
5540 })
5541 .map_err(|err| format!("could not save plugin dismissals: {err}"))?;
5542 let mut app = self.host.app.borrow_mut();
5543 app.plugin_cta.dismissed.retain(|candidate| {
5544 let reset = matches(candidate);
5545 if reset {
5546 cleared.insert(candidate.clone());
5547 }
5548 !reset
5549 });
5550 Ok(cleared.into_iter().collect())
5551 }
5552 }
5553
5554 /// Resolve the default Codewhale tools directory (mirrors the legacy handler).
5555 fn default_codewhale_tools_dir() -> Option<PathBuf> {
5556 codewhale_config::codewhale_home()
5557 .ok()
5558 .map(|home| home.join("tools"))
5559 }
5560
5561 // ---------------------------------------------------------------------------
5562 // Envelope construction (D1)
5563 // ---------------------------------------------------------------------------
5564
5565 /// Owns twenty-five facet objects sharing one synchronous TUI host proxy.
5566 ///
5567 /// Handlers borrow only these adapters. Every method delegates to the real App
5568 /// authority and releases its `RefCell` borrow before returning, so facets can
5569 /// be called sequentially without exposing TUI types across the boundary.
5570 pub(crate) struct CommandContextBundle<'a> {
5571 session: SessionAdapter<'a>,
5572 composer: composer::ComposerAdapter<'a>,
5573 model: ModelAdapter<'a>,
5574 feedback: core_policy::PolicyAdapter<'a>,
5575 effort: core_policy::PolicyAdapter<'a>,
5576 clear: core_policy::PolicyAdapter<'a>,
5577 provider_routes: ModelAdapter<'a>,
5578 workflow_review: workflow::WorkflowAdapter<'a>,
5579 workflow: workflow::WorkflowAdapter<'a>,
5580 auto_review: workflow::WorkflowAdapter<'a>,
5581 model_selection: ModelAdapter<'a>,
5582 cost: CostAdapter<'a>,
5583 mode_policy: ModePolicyAdapter<'a>,
5584 system_prompt: SystemPromptAdapter<'a>,
5585 skills: SkillsAdapter<'a>,
5586 workspace: WorkspaceAdapter<'a>,
5587 presentation: PresentationAdapter<'a>,
5588 media: MediaAdapter<'a>,
5589 project: ProjectAdapter<'a>,
5590 memory: MemoryAdapter<'a>,
5591 skill_group: SkillGroupAdapter<'a>,
5592 plugin: PluginAdapter<'a>,
5593 lifecycle: SessionLifecycleAdapter<'a>,
5594 control: SessionControlAdapter<'a>,
5595 response_copy: SessionExportAdapter<'a>,
5596 export: SessionExportAdapter<'a>,
5597 structcopy: SessionStructcopyAdapter<'a>,
5598 debug_receipts: DebugOperationsAdapter<'a>,
5599 debug_change: DebugOperationsAdapter<'a>,
5600 debug_history: DebugOperationsAdapter<'a>,
5601 debug_diff: DebugOperationsAdapter<'a>,
5602 debug_undo: DebugOperationsAdapter<'a>,
5603 debug_diagnostics: DebugDiagnosticsAdapter<'a>,
5604 permissions: PermissionsAdapter<'a>,
5605 config_status: ConfigStatusAdapter<'a>,
5606 config: ConfigAdapter<'a>,
5607 pet: PetAdapter<'a>,
5608 trust: TrustAdapter<'a>,
5609 login: LoginAdapter<'a>,
5610 work_surface: WorkSurfaceAdapter<'a>,
5611 navigation: NavigationAdapter<'a>,
5612 voice_input: VoiceInputAdapter<'a>,
5613 fleet: FleetAdapter<'a>,
5614 lane: LaneAdapter<'a>,
5615 constitution: constitution::ConstitutionAdapter<'a>,
5616 hooks: hooks::HooksAdapter<'a>,
5617 }
5618
5619 impl<'a> CommandContextBundle<'a> {
5620 /// Expose exactly the capabilities declared by the command registration.
5621 pub(crate) fn contexts(&mut self, capabilities: CommandCapabilities) -> CommandContexts<'_> {
5622 let mut contexts = CommandContexts::empty();
5623 if capabilities.contains(CommandCapabilities::SESSION) {
5624 contexts = contexts.with_session(&mut self.session);
5625 }
5626 if capabilities.contains(CommandCapabilities::PROVIDER_ROUTES) {
5627 contexts = contexts.with_provider_routes(&mut self.provider_routes);
5628 }
5629 if capabilities.contains(CommandCapabilities::FEEDBACK) {
5630 contexts = contexts.with_feedback(&mut self.feedback);
5631 }
5632 if capabilities.contains(CommandCapabilities::EFFORT) {
5633 contexts = contexts.with_effort(&mut self.effort);
5634 }
5635 if capabilities.contains(CommandCapabilities::CLEAR) {
5636 contexts = contexts.with_clear(&mut self.clear);
5637 }
5638 if capabilities.contains(CommandCapabilities::WORKFLOW_REVIEW) {
5639 contexts = contexts.with_workflow_review(&self.workflow_review);
5640 }
5641 if capabilities.contains(CommandCapabilities::WORKFLOW_CONTROL) {
5642 contexts = contexts.with_workflow(&mut self.workflow);
5643 }
5644 if capabilities.contains(CommandCapabilities::AUTO_REVIEW) {
5645 contexts = contexts.with_auto_review(&mut self.auto_review);
5646 }
5647 if capabilities.contains(CommandCapabilities::MODEL_SELECTION) {
5648 contexts = contexts.with_model_selection(&mut self.model_selection);
5649 }
5650 if capabilities.contains(CommandCapabilities::MODEL) {
5651 contexts = contexts.with_model(&mut self.model);
5652 }
5653 if capabilities.contains(CommandCapabilities::COST) {
5654 contexts = contexts.with_cost(&mut self.cost);
5655 }
5656 if capabilities.contains(CommandCapabilities::MODE_POLICY) {
5657 contexts = contexts.with_mode_policy(&mut self.mode_policy);
5658 }
5659 if capabilities.contains(CommandCapabilities::SYSTEM_PROMPT) {
5660 contexts = contexts.with_system_prompt(&mut self.system_prompt);
5661 }
5662 if capabilities.contains(CommandCapabilities::SKILLS) {
5663 contexts = contexts.with_skills(&mut self.skills);
5664 }
5665 if capabilities.contains(CommandCapabilities::WORKSPACE) {
5666 contexts = contexts.with_workspace(&mut self.workspace);
5667 }
5668 if capabilities.contains(CommandCapabilities::PRESENTATION) {
5669 contexts = contexts.with_presentation(&mut self.presentation);
5670 }
5671 if capabilities.contains(CommandCapabilities::MEDIA) {
5672 contexts = contexts.with_media(&mut self.media);
5673 }
5674 if capabilities.contains(CommandCapabilities::MEMORY) {
5675 contexts = contexts.with_memory(&mut self.memory);
5676 }
5677 if capabilities.contains(CommandCapabilities::PROJECT) {
5678 contexts = contexts.with_project(&mut self.project);
5679 }
5680 if capabilities.contains(CommandCapabilities::SKILL_GROUP) {
5681 contexts = contexts.with_skill_group(&mut self.skill_group);
5682 }
5683 if capabilities.contains(CommandCapabilities::PLUGIN) {
5684 contexts = contexts.with_plugin(&mut self.plugin);
5685 }
5686 if capabilities.contains(CommandCapabilities::SESSION_LIFECYCLE) {
5687 contexts = contexts.with_lifecycle(&mut self.lifecycle);
5688 }
5689 if capabilities.contains(CommandCapabilities::SESSION_CONTROL) {
5690 contexts = contexts.with_control(&mut self.control);
5691 }
5692 if capabilities.contains(CommandCapabilities::SESSION_STRUCTCOPY) {
5693 contexts = contexts.with_structcopy(&mut self.structcopy);
5694 }
5695 if capabilities.contains(CommandCapabilities::RESPONSE_COPY) {
5696 contexts = contexts.with_response_copy(&mut self.response_copy);
5697 }
5698 if capabilities.contains(CommandCapabilities::SESSION_EXPORT) {
5699 contexts = contexts.with_export(&mut self.export);
5700 }
5701 if capabilities.contains(CommandCapabilities::DEBUG_RECEIPTS) {
5702 contexts = contexts.with_debug_receipts(&mut self.debug_receipts);
5703 }
5704 if capabilities.contains(CommandCapabilities::DEBUG_CHANGE) {
5705 contexts = contexts.with_debug_change(&mut self.debug_change);
5706 }
5707 if capabilities.contains(CommandCapabilities::DEBUG_HISTORY) {
5708 contexts = contexts.with_debug_history(&mut self.debug_history);
5709 }
5710 if capabilities.contains(CommandCapabilities::DEBUG_DIFF) {
5711 contexts = contexts.with_debug_diff(&mut self.debug_diff);
5712 }
5713 if capabilities.contains(CommandCapabilities::DEBUG_UNDO) {
5714 contexts = contexts.with_debug_undo(&mut self.debug_undo);
5715 }
5716 if capabilities.contains(CommandCapabilities::DEBUG_DIAGNOSTICS) {
5717 contexts = contexts.with_debug_diagnostics(&mut self.debug_diagnostics);
5718 }
5719 if capabilities.contains(CommandCapabilities::PERMISSIONS) {
5720 contexts = contexts.with_permissions(&mut self.permissions);
5721 }
5722 if capabilities.contains(CommandCapabilities::CONFIG_STATUS) {
5723 contexts = contexts.with_config_status(&mut self.config_status);
5724 }
5725 if capabilities.contains(CommandCapabilities::CONFIG) {
5726 contexts = contexts.with_config(&mut self.config);
5727 }
5728 if capabilities.contains(CommandCapabilities::PET) {
5729 contexts = contexts.with_pet(&mut self.pet);
5730 }
5731 if capabilities.contains(CommandCapabilities::TRUST) {
5732 contexts = contexts.with_trust(&mut self.trust);
5733 }
5734 if capabilities.contains(CommandCapabilities::LOGIN) {
5735 contexts = contexts.with_login(&mut self.login);
5736 }
5737 if capabilities.contains(CommandCapabilities::WORK_SURFACE) {
5738 contexts = contexts.with_work_surface(&mut self.work_surface);
5739 }
5740 if capabilities.contains(CommandCapabilities::COMPOSER) {
5741 contexts = contexts.with_composer(&mut self.composer);
5742 }
5743 if capabilities.contains(CommandCapabilities::NAVIGATION) {
5744 contexts = contexts.with_navigation(&mut self.navigation);
5745 }
5746 if capabilities.contains(CommandCapabilities::VOICE_INPUT) {
5747 contexts = contexts.with_voice_input(&mut self.voice_input);
5748 }
5749 if capabilities.contains(CommandCapabilities::FLEET) {
5750 contexts = contexts.with_fleet(&mut self.fleet);
5751 }
5752 if capabilities.contains(CommandCapabilities::LANE) {
5753 contexts = contexts.with_lane(&mut self.lane);
5754 }
5755 if capabilities.contains(CommandCapabilities::CONSTITUTION) {
5756 contexts = contexts.with_constitution(&mut self.constitution);
5757 }
5758 if capabilities.contains(CommandCapabilities::HOOKS) {
5759 contexts = contexts.with_hooks(&mut self.hooks);
5760 }
5761 contexts
5762 }
5763
5764 /// Test-only: consume the bundle into independent facet parts.
5765 #[cfg(test)]
5766 pub(crate) fn parts(&mut self) -> ContextParts<'_> {
5767 let all_test_capabilities = CommandCapabilities::SESSION
5768 .union(CommandCapabilities::MODEL)
5769 .union(CommandCapabilities::COST)
5770 .union(CommandCapabilities::MODE_POLICY)
5771 .union(CommandCapabilities::SYSTEM_PROMPT)
5772 .union(CommandCapabilities::SKILLS)
5773 .union(CommandCapabilities::WORKSPACE)
5774 .union(CommandCapabilities::PRESENTATION)
5775 .union(CommandCapabilities::MEDIA)
5776 .union(CommandCapabilities::MEMORY)
5777 .union(CommandCapabilities::PROJECT)
5778 .union(CommandCapabilities::SKILL_GROUP)
5779 .union(CommandCapabilities::PLUGIN)
5780 .union(CommandCapabilities::SESSION_LIFECYCLE)
5781 .union(CommandCapabilities::SESSION_CONTROL)
5782 .union(CommandCapabilities::SESSION_EXPORT)
5783 .union(CommandCapabilities::SESSION_STRUCTCOPY)
5784 .union(CommandCapabilities::DEBUG_RECEIPTS)
5785 .union(CommandCapabilities::DEBUG_CHANGE)
5786 .union(CommandCapabilities::DEBUG_HISTORY)
5787 .union(CommandCapabilities::DEBUG_DIFF)
5788 .union(CommandCapabilities::DEBUG_UNDO)
5789 .union(CommandCapabilities::DEBUG_DIAGNOSTICS)
5790 .union(CommandCapabilities::PERMISSIONS)
5791 .union(CommandCapabilities::CONFIG_STATUS)
5792 .union(CommandCapabilities::CONFIG)
5793 .union(CommandCapabilities::PET)
5794 .union(CommandCapabilities::TRUST)
5795 .union(CommandCapabilities::LOGIN)
5796 .union(CommandCapabilities::WORK_SURFACE)
5797 .union(CommandCapabilities::NAVIGATION)
5798 .union(CommandCapabilities::VOICE_INPUT);
5799 self.contexts(all_test_capabilities).into_parts()
5800 }
5801 }
5802
5803 impl App {
5804 /// Build an App-free capability envelope backed by authoritative TUI
5805 /// operations. The shared proxy is synchronous and local to one dispatch.
5806 #[cfg(test)]
5807 pub(crate) fn command_contexts(&mut self) -> CommandContextBundle<'_> {
5808 self.command_contexts_with_config(None)
5809 }
5810
5811 pub(crate) fn command_contexts_with_config<'a>(
5812 &'a mut self,
5813 config: Option<&'a codewhale_runtime::config::Config>,
5814 ) -> CommandContextBundle<'a> {
5815 let host = Rc::new(CommandHost {
5816 app: RefCell::new(self),
5817 config,
5818 });
5819 CommandContextBundle {
5820 session: SessionAdapter { host: host.clone() },
5821 composer: composer::ComposerAdapter { host: host.clone() },
5822 model: ModelAdapter { host: host.clone() },
5823 feedback: core_policy::PolicyAdapter { host: host.clone() },
5824 effort: core_policy::PolicyAdapter { host: host.clone() },
5825 clear: core_policy::PolicyAdapter { host: host.clone() },
5826 provider_routes: ModelAdapter { host: host.clone() },
5827 workflow_review: workflow::WorkflowAdapter { host: host.clone() },
5828 workflow: workflow::WorkflowAdapter { host: host.clone() },
5829 auto_review: workflow::WorkflowAdapter { host: host.clone() },
5830 model_selection: ModelAdapter { host: host.clone() },
5831 cost: CostAdapter { host: host.clone() },
5832 mode_policy: ModePolicyAdapter { host: host.clone() },
5833 system_prompt: SystemPromptAdapter { host: host.clone() },
5834 skills: SkillsAdapter { host: host.clone() },
5835 workspace: WorkspaceAdapter { host: host.clone() },
5836 presentation: PresentationAdapter { host: host.clone() },
5837 media: MediaAdapter { host: host.clone() },
5838 project: ProjectAdapter { host: host.clone() },
5839 memory: MemoryAdapter { host: host.clone() },
5840 skill_group: SkillGroupAdapter { host: host.clone() },
5841 plugin: PluginAdapter { host: host.clone() },
5842 lifecycle: SessionLifecycleAdapter { host: host.clone() },
5843 control: SessionControlAdapter { host: host.clone() },
5844 response_copy: SessionExportAdapter { host: host.clone() },
5845 export: SessionExportAdapter { host: host.clone() },
5846 structcopy: SessionStructcopyAdapter { host: host.clone() },
5847 debug_receipts: DebugOperationsAdapter { host: host.clone() },
5848 debug_change: DebugOperationsAdapter { host: host.clone() },
5849 debug_history: DebugOperationsAdapter { host: host.clone() },
5850 debug_diff: DebugOperationsAdapter { host: host.clone() },
5851 debug_undo: DebugOperationsAdapter { host: host.clone() },
5852 debug_diagnostics: DebugDiagnosticsAdapter { host: host.clone() },
5853 permissions: PermissionsAdapter { host: host.clone() },
5854 config_status: ConfigStatusAdapter { host: host.clone() },
5855 config: ConfigAdapter { host: host.clone() },
5856 pet: PetAdapter { host: host.clone() },
5857 trust: TrustAdapter { host: host.clone() },
5858 login: LoginAdapter { host: host.clone() },
5859 work_surface: WorkSurfaceAdapter { host: host.clone() },
5860 navigation: NavigationAdapter { host: host.clone() },
5861 voice_input: VoiceInputAdapter { host: host.clone() },
5862 fleet: FleetAdapter { host: host.clone() },
5863 lane: LaneAdapter { host: host.clone() },
5864 constitution: constitution::ConstitutionAdapter { host: host.clone() },
5865 hooks: hooks::HooksAdapter { host },
5866 }
5867 }
5868 }
5869
5870 #[cfg(test)]
5871 mod tests {
5872 use super::*;
5873 use codewhale_localization::Locale;
5874 use codewhale_models::Role;
5875 use tempfile::TempDir;
5876
5877 fn test_app() -> App {
5878 crate::tui::test_support::test_app_with_options(crate::tui::test_support::test_tui_options(
5879 PathBuf::from("."),
5880 ))
5881 }
5882
5883 #[test]
5884 fn skill_registry_sync_without_home_refuses_before_the_network_bridge() {
5885 // No Tokio runtime is present: entering run_async would panic rather
5886 // than downloading a registry into an undiscoverable temporary root.
5887 let result = sync_registry_to_cache(None);
5888 assert_eq!(
5889 result.unwrap_err(),
5890 "global skill mutations require a home directory"
5891 );
5892 }
5893
5894 /// A 1x1 PNG for media adapter tests.
5895 const PNG_1X1: &[u8] = &[
5896 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
5897 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f,
5898 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00,
5899 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49,
5900 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
5901 ];
5902
5903 #[test]
5904 fn pending_groups_is_sorted_unique_and_matches_checked_in_frontier() {
5905 let mut sorted = PENDING_GROUPS.to_vec();
5906 sorted.sort_unstable();
5907 assert_eq!(PENDING_GROUPS, sorted.as_slice(), "frontier must be sorted");
5908 let unique: std::collections::BTreeSet<&str> = PENDING_GROUPS.iter().copied().collect();
5909 assert_eq!(
5910 unique.len(),
5911 PENDING_GROUPS.len(),
5912 "frontier must be unique"
5913 );
5914
5915 let topology: serde_json::Value = serde_json::from_str(include_str!(
5916 "../../../../scripts/command-migration-topology.json"
5917 ))
5918 .expect("checked-in topology must be valid JSON");
5919 let frontier = topology["frontier"]
5920 .as_array()
5921 .expect("topology frontier")
5922 .iter()
5923 .map(|entry| entry.as_str().expect("string frontier entry"))
5924 .collect::<Vec<_>>();
5925 assert_eq!(PENDING_GROUPS, frontier.as_slice());
5926 }
5927
5928 #[test]
5929 fn boundary_mappings_cover_every_variant() {
5930 for mode in [AppMode::Agent, AppMode::Plan] {
5931 let command = to_command_mode(mode);
5932 assert_eq!(from_command_mode(command), mode);
5933 }
5934 for approval in [
5935 ApprovalMode::Auto,
5936 ApprovalMode::Bypass,
5937 ApprovalMode::Suggest,
5938 ApprovalMode::Never,
5939 ] {
5940 let _ = to_command_approval(approval);
5941 }
5942 for currency in [CostCurrency::Usd, CostCurrency::Cny] {
5943 let command = to_command_currency(currency);
5944 assert_eq!(from_command_currency(command), currency);
5945 }
5946 }
5947
5948 #[test]
5949 fn key_to_message_id_resolves_convention_keys_and_rejects_unknown() {
5950 assert_eq!(
5951 key_to_message_id("cmd_balance_description"),
5952 Some(MessageId::CmdBalanceDescription)
5953 );
5954 assert_eq!(
5955 key_to_message_id("cmd_voice_control_description"),
5956 Some(MessageId::CmdVoiceControlDescription)
5957 );
5958 assert_eq!(key_to_message_id("cmd_nonexistent_description"), None);
5959 assert_eq!(key_to_message_id(""), None);
5960 }
5961
5962 #[test]
5963 fn cost_adapter_delegates_totals_high_water_and_route_receipt_to_app() {
5964 let mut app = test_app();
5965 app.cost_currency = CostCurrency::Usd;
5966 {
5967 let mut bundle = app.command_contexts();
5968 let mut parts = bundle.parts();
5969 let cost = parts.cost.as_mut().expect("cost facet");
5970 cost.accrue_cost_estimate(3.0, CommandCurrency::Usd);
5971 cost.record_turn_cost(
5972 4.0,
5973 CommandCurrency::Cny,
5974 Some("provider=deepseek model=x".to_string()),
5975 );
5976 assert_eq!(cost.session_cost_for_currency(CommandCurrency::Usd), 3.0);
5977 assert_eq!(cost.session_cost_for_currency(CommandCurrency::Cny), 4.0);
5978 }
5979 assert_eq!(app.session_cost_for_currency(CostCurrency::Usd), 3.0);
5980 assert_eq!(app.session_cost_for_currency(CostCurrency::Cny), 4.0);
5981 assert_eq!(
5982 app.displayed_session_cost_for_currency(CostCurrency::Usd),
5983 3.0
5984 );
5985 assert!(
5986 app.session
5987 .cost_route_receipts
5988 .contains("provider=deepseek model=x")
5989 );
5990 }
5991
5992 #[test]
5993 fn session_adapter_delegates_message_and_queue_operations_to_app() {
5994 let mut app = test_app();
5995 app.current_session_id = Some("s1".to_string());
5996 app.session.total_tokens = 42;
5997 app.queue_message(crate::tui::app::QueuedMessage {
5998 display: "q".to_string(),
5999 skill_instruction: None,
6000 skill_provenance: None,
6001 extension_command: None,
6002 approved_plan: None,
6003 owner_input: false,
6004 history_echoed: false,
6005 });
6006 {
6007 let mut bundle = app.command_contexts();
6008 let mut parts = bundle.parts();
6009 let session = parts.session.as_mut().expect("session facet");
6010 assert_eq!(session.session_id().as_deref(), Some("s1"));
6011 session.add_message(Message {
6012 role: Role::User,
6013 content: vec![],
6014 });
6015 assert_eq!(session.api_messages().len(), 1);
6016 assert_eq!(session.queued_message_count(), 1);
6017 assert!(session.remove_queued_message(0).is_ok());
6018 assert!(session.remove_queued_message(5).is_err());
6019 assert_eq!(session.total_tokens(), 42);
6020 }
6021 assert_eq!(app.api_messages.len(), 1);
6022 assert_eq!(app.queued_message_count(), 0);
6023 }
6024
6025 #[test]
6026 fn model_adapter_delegates_selection_and_route_invalidation_to_app() {
6027 let mut app = test_app();
6028 app.last_effective_model = Some("stale-model".to_string());
6029 let config = codewhale_runtime::config::Config::default();
6030 {
6031 let mut bundle = app.command_contexts_with_config(Some(&config));
6032 let mut parts = bundle.parts();
6033 let model = parts.model.as_mut().expect("model facet");
6034 model.set_model_selection("auto".to_string(), Some(to_provider_id("deepseek")));
6035 assert!(model.auto_model());
6036 assert_eq!(model.current_model(), "auto");
6037 assert_eq!(
6038 model.provider_identity().map(|id| id.0).as_deref(),
6039 Some("deepseek")
6040 );
6041 }
6042 assert!(app.last_effective_model.is_none());
6043 assert_eq!(app.provider_identity_for_persistence(), "deepseek");
6044 }
6045
6046 #[test]
6047 fn model_adapter_admits_cross_provider_and_case_distinct_custom_routes_from_borrowed_config() {
6048 use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig};
6049 let config = {
6050 let __cw_config_init_0_0 = Some("openai".to_string());
6051 let __cw_config_init_0_1 = Some(ProvidersConfig {
6052 custom: [
6053 ("CustomA".to_string(), "http://127.0.0.1:4111/v1"),
6054 ("customa".to_string(), "http://127.0.0.1:4222/v1"),
6055 ]
6056 .into_iter()
6057 .map(|(key, endpoint)| {
6058 (
6059 key,
6060 ProviderConfig {
6061 kind: Some("openai-compatible".to_string()),
6062 base_url: Some(endpoint.to_string()),
6063 ..Default::default()
6064 },
6065 )
6066 })
6067 .collect(),
6068 ..Default::default()
6069 });
6070 let mut __cw_config_init_0_value: Config = Config::default();
6071 __cw_config_init_0_value.provider = __cw_config_init_0_0;
6072 __cw_config_init_0_value.providers = __cw_config_init_0_1;
6073 __cw_config_init_0_value
6074 };
6075 let mut app = test_app();
6076 app.set_provider_identity_record(config.active_provider_identity().unwrap());
6077 for (key, model) in [
6078 ("CustomA", "private-a"),
6079 ("customa", "private-b"),
6080 ("openai", "gpt-5.5"),
6081 ] {
6082 {
6083 let mut bundle = app.command_contexts_with_config(Some(&config));
6084 let mut parts = bundle.parts();
6085 parts
6086 .model
6087 .as_mut()
6088 .unwrap()
6089 .set_model_selection(model.to_string(), Some(to_provider_id(key)));
6090 }
6091 assert_eq!(
6092 app.admitted_provider_identity().unwrap(),
6093 &config.resolve_provider_identity(key).unwrap()
6094 );
6095 assert_eq!(app.provider_identity_for_persistence(), key);
6096 assert_eq!(app.model, model);
6097 }
6098 // Exact keys do not inherit a same-kind sibling or a generic custom route.
6099 for refused in ["CUSTOMA", "custom", "antigravity"] {
6100 let captured = app.admitted_provider_identity().unwrap().clone();
6101 {
6102 let mut bundle = app.command_contexts_with_config(Some(&config));
6103 let mut parts = bundle.parts();
6104 parts.model.as_mut().unwrap().set_model_selection(
6105 "must-not-apply".to_string(),
6106 Some(to_provider_id(refused)),
6107 );
6108 }
6109 assert_eq!(app.admitted_provider_identity().unwrap(), &captured);
6110 assert_eq!(app.model, "gpt-5.5");
6111 }
6112 }
6113
6114 #[test]
6115 fn model_adapter_without_active_config_refuses_before_route_or_model_mutation() {
6116 let mut app = test_app();
6117 let model = app.model.clone();
6118 let captured = app.admitted_provider_identity().unwrap().clone();
6119 app.last_effective_model = Some("captured-live-route".to_string());
6120 {
6121 let mut bundle = app.command_contexts();
6122 let mut parts = bundle.parts();
6123 let facet = parts.model.as_mut().unwrap();
6124 facet.set_model_selection("must-not-apply".to_string(), Some(to_provider_id("openai")));
6125 facet.set_model_selection("must-not-apply".to_string(), None);
6126 }
6127 assert_eq!(app.model, model);
6128 assert_eq!(app.admitted_provider_identity().unwrap(), &captured);
6129 assert_eq!(
6130 app.last_effective_model.as_deref(),
6131 Some("captured-live-route")
6132 );
6133 }
6134
6135 #[test]
6136 fn mode_policy_adapter_delegates_mode_and_shell_policy_to_app() {
6137 let mut app = test_app();
6138 app.set_agent_shell_access(false);
6139 {
6140 let mut bundle = app.command_contexts();
6141 let mut parts = bundle.parts();
6142 let policy = parts.mode_policy.as_mut().expect("mode facet");
6143 policy.set_mode(CommandMode::Plan);
6144 policy.set_shell_access(true);
6145 assert!(!policy.allow_shell(), "Plan stays read-only");
6146 assert_eq!(policy.mode(), CommandMode::Plan);
6147 }
6148 assert_eq!(
6149 app.mode,
6150 AppMode::Plan,
6151 "adapter delegates to App authority"
6152 );
6153 assert!(!app.allow_shell, "Plan ignores a shell grant");
6154 {
6155 let mut bundle = app.command_contexts();
6156 let mut parts = bundle.parts();
6157 let policy = parts.mode_policy.as_mut().expect("mode facet");
6158 policy.set_mode(CommandMode::Agent);
6159 policy.set_shell_access(true);
6160 assert!(policy.allow_shell(), "Work uses the shell baseline");
6161 }
6162 assert_eq!(app.mode, AppMode::Agent);
6163 assert!(app.allow_shell);
6164 }
6165
6166 #[test]
6167 fn system_prompt_adapter_returns_owned_prompt() {
6168 let mut app = test_app();
6169 app.system_prompt = Some(SystemPrompt::Text("system".to_string()));
6170 let mut bundle = app.command_contexts();
6171 let parts = bundle.parts();
6172 assert!(
6173 parts
6174 .system_prompt
6175 .expect("system prompt facet")
6176 .system_prompt()
6177 .is_some()
6178 );
6179 }
6180
6181 #[test]
6182 fn workspace_adapter_returns_path_and_snapshot() {
6183 let mut app = test_app();
6184 let expected = app.workspace.clone();
6185 let mut bundle = app.command_contexts();
6186 let parts = bundle.parts();
6187 let workspace = parts.workspace.expect("workspace facet");
6188 assert_eq!(workspace.workspace(), expected);
6189 assert!(workspace.work_state_snapshot().is_ok());
6190 }
6191
6192 #[test]
6193 fn envelope_exposes_all_facets_without_app_in_handler_surface() {
6194 let mut app = test_app();
6195 let mut bundle = app.command_contexts();
6196 let parts = bundle.parts();
6197 assert!(parts.session.is_some());
6198 assert!(parts.model.is_some());
6199 assert!(parts.cost.is_some());
6200 assert!(parts.mode_policy.is_some());
6201 assert!(parts.system_prompt.is_some());
6202 assert!(parts.skills.is_some());
6203 assert!(parts.workspace.is_some());
6204 assert!(parts.presentation.is_some());
6205 assert!(parts.media.is_some());
6206 }
6207
6208 #[test]
6209 fn diagnostics_envelope_exposes_only_declared_authority() {
6210 let mut harness =
6211 crate::commands::debug_diagnostics_test_support::DiagnosticsHarness::new();
6212 let mut bundle = harness.app.command_contexts();
6213 let parts = bundle
6214 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6215 .into_parts();
6216 assert!(parts.debug_diagnostics.is_some());
6217 for (name, present) in [
6218 ("session", parts.session.is_some()),
6219 ("model", parts.model.is_some()),
6220 ("cost", parts.cost.is_some()),
6221 ("mode_policy", parts.mode_policy.is_some()),
6222 ("system_prompt", parts.system_prompt.is_some()),
6223 ("skills", parts.skills.is_some()),
6224 ("workspace", parts.workspace.is_some()),
6225 ("presentation", parts.presentation.is_some()),
6226 ("media", parts.media.is_some()),
6227 ("memory", parts.memory.is_some()),
6228 ("project", parts.project.is_some()),
6229 ("skill_group", parts.skill_group.is_some()),
6230 ("plugin", parts.plugin.is_some()),
6231 ("lifecycle", parts.lifecycle.is_some()),
6232 ("control", parts.control.is_some()),
6233 ("export", parts.export.is_some()),
6234 ] {
6235 assert!(
6236 !present,
6237 "{name} must not be exposed to diagnostics-only commands"
6238 );
6239 }
6240 let parts = bundle.contexts(CommandCapabilities::NONE).into_parts();
6241 assert!(parts.debug_diagnostics.is_none());
6242 }
6243
6244 #[test]
6245 fn diagnostics_adapter_projects_host_balance_system_and_optional_usage() {
6246 let mut harness =
6247 crate::commands::debug_diagnostics_test_support::DiagnosticsHarness::new();
6248 harness.app.system_prompt = Some(SystemPrompt::Text("policy".to_string()));
6249 harness.app.session.last_prompt_tokens = None;
6250 harness.app.session.last_completion_tokens = Some(0);
6251 let expected_provider = harness
6252 .app
6253 .api_provider
6254 .provider()
6255 .display_name()
6256 .to_string();
6257 let expected_support =
6258 codewhale_runtime::config::provider_has_balance_api(harness.app.api_provider);
6259 let mut bundle = harness.app.command_contexts();
6260 let mut parts = bundle
6261 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6262 .into_parts();
6263 let diagnostics = parts
6264 .debug_diagnostics
6265 .as_mut()
6266 .expect("declared diagnostics");
6267 let balance = diagnostics.balance_projection();
6268 assert_eq!(balance.provider_display_name, expected_provider);
6269 assert_eq!(balance.supports_balance_api, expected_support);
6270 let system = diagnostics.system_projection();
6271 assert_eq!(
6272 system.prompt,
6273 codewhale_command_contract::facets::DebugSystemPrompt::Text("policy".into())
6274 );
6275 let usage = diagnostics.token_projection();
6276 assert_eq!(usage.last_input, None);
6277 assert_eq!(usage.last_output, Some(0));
6278 assert_eq!(usage.cost, diagnostics.cost_projection());
6279 assert!(diagnostics.tool_snapshot().is_none());
6280 assert!(diagnostics.cache_telemetry().history.is_empty());
6281 }
6282
6283 #[test]
6284 fn diagnostics_adapter_cost_and_cache_telemetry_preserve_real_distinctions() {
6285 let mut harness =
6286 crate::commands::debug_diagnostics_test_support::DiagnosticsHarness::new();
6287 let app = &mut harness.app;
6288 app.session.cost_priced_turns = 1;
6289 app.accrue_session_cost_estimate(codewhale_engine::pricing::CostEstimate {
6290 usd: 0.05,
6291 cny: 0.0,
6292 });
6293 app.accrue_subagent_cost_estimate(codewhale_engine::pricing::CostEstimate {
6294 usd: 0.02,
6295 cny: 0.0,
6296 });
6297 app.session.displayed_cost_high_water = 0.10;
6298 app.push_turn_cache_record(crate::tui::app::TurnCacheRecord {
6299 provider: None,
6300 provider_identity: None,
6301 model: None,
6302 auto_model: false,
6303 input_tokens: 120,
6304 output_tokens: 0,
6305 cache_hit_tokens: Some(0),
6306 cache_miss_tokens: None,
6307 cache_write_tokens: None,
6308 reasoning_tokens: None,
6309 reasoning_replay_tokens: None,
6310 cost_audit: None,
6311 recorded_at: std::time::Instant::now(),
6312 });
6313 let expected_total =
6314 app.displayed_session_cost_for_currency(codewhale_config::pricing::CostCurrency::Usd);
6315 let mut bundle = app.command_contexts();
6316 let mut parts = bundle
6317 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6318 .into_parts();
6319 let diagnostic = parts.debug_diagnostics.as_mut().unwrap();
6320 let cost = diagnostic.cost_projection();
6321 assert_eq!(cost.parent_turns, 0.05);
6322 assert_eq!(cost.subagents, 0.02);
6323 assert!(cost.display_floor > 0.0);
6324 assert_eq!(
6325 cost.parent_turns + cost.subagents + cost.display_floor,
6326 expected_total
6327 );
6328 let telemetry = diagnostic.cache_telemetry();
6329 assert_eq!(telemetry.history.len(), 1);
6330 let turn = &telemetry.history[0];
6331 assert_eq!(
6332 turn.cache_hit_tokens,
6333 Some(0),
6334 "reported zero is not missing telemetry"
6335 );
6336 assert_eq!(turn.cache_miss_tokens, None);
6337 assert_eq!(turn.priced_amount, None, "no audit is not priced zero");
6338 assert_eq!(turn.priced_cache_miss, 120);
6339 assert!(turn.age_seconds < 3);
6340 assert!(
6341 diagnostic.tool_snapshot().is_none(),
6342 "no request differs from an empty catalog"
6343 );
6344 }
6345
6346 #[test]
6347 fn diagnostics_adapter_limits_sensitive_content_to_declared_operations() {
6348 let mut harness =
6349 crate::commands::debug_diagnostics_test_support::DiagnosticsHarness::new();
6350 let secret = "DIAGNOSTICS-PRIVATE-SYSTEM-SENTINEL";
6351 harness.app.system_prompt = Some(SystemPrompt::Text(secret.into()));
6352 let mut bundle = harness.app.command_contexts();
6353 let mut parts = bundle
6354 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6355 .into_parts();
6356 let diagnostics = parts.debug_diagnostics.as_mut().unwrap();
6357 for public_projection in [
6358 format!("{:?}", diagnostics.balance_projection()),
6359 format!("{:?}", diagnostics.cost_projection()),
6360 format!("{:?}", diagnostics.token_projection()),
6361 format!("{:?}", diagnostics.cache_telemetry()),
6362 ] {
6363 assert!(
6364 !public_projection.contains(secret),
6365 "unrelated operation must not include the prompt"
6366 );
6367 }
6368 let system = diagnostics.system_projection();
6369 assert_eq!(
6370 system.prompt,
6371 codewhale_command_contract::facets::DebugSystemPrompt::Text(secret.into())
6372 );
6373 assert!(
6374 serde_json::to_string(&diagnostics.prompt_context())
6375 .unwrap()
6376 .contains(secret)
6377 );
6378 }
6379
6380 #[test]
6381 fn diagnostics_adapter_retains_full_tool_snapshot_schema() {
6382 let mut harness =
6383 crate::commands::debug_diagnostics_test_support::DiagnosticsHarness::new();
6384 let snapshot =
6385 codewhale_engine::tool_inspection::ToolInspectionSnapshot::from_prepared_request(
6386 "turn-1",
6387 2,
6388 Some(&[]),
6389 );
6390 harness.app.session.last_tool_request_snapshot = Some(snapshot.clone());
6391 let mut bundle = harness.app.command_contexts();
6392 let mut parts = bundle
6393 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6394 .into_parts();
6395 let projected = parts
6396 .debug_diagnostics
6397 .as_mut()
6398 .unwrap()
6399 .tool_snapshot()
6400 .unwrap();
6401 assert_eq!(
6402 serde_json::to_value(&projected).unwrap(),
6403 serde_json::to_value(&snapshot).unwrap()
6404 );
6405 assert_eq!(projected.tool_count, 0);
6406 }
6407
6408 #[test]
6409 fn diagnostics_adapter_projects_full_context_and_prepared_tool_json() {
6410 let mut harness =
6411 crate::commands::debug_diagnostics_test_support::DiagnosticsHarness::new();
6412 harness.app.system_prompt = Some(SystemPrompt::Text("source-map policy".into()));
6413 let tool = codewhale_models::Tool {
6414 tool_type: Some("function".into()),
6415 name: "search".into(),
6416 description: "Find records".into(),
6417 input_schema: serde_json::json!({"type":"object","properties":{"q":{"type":"string"}}}),
6418 allowed_callers: Some(vec!["assistant".into()]),
6419 defer_loading: Some(false),
6420 input_examples: None,
6421 strict: Some(true),
6422 cache_control: None,
6423 };
6424 harness.app.session.last_tool_catalog = Some(vec![tool.clone()]);
6425 let original_context = crate::context_report::build_prompt_context(&harness.app);
6426 let original_snapshot =
6427 codewhale_engine::tool_inspection::ToolInspectionSnapshot::from_prepared_request(
6428 "turn",
6429 3,
6430 Some(&[tool]),
6431 );
6432 harness.app.session.last_tool_request_snapshot = Some(original_snapshot.clone());
6433 let mut bundle = harness.app.command_contexts();
6434 let mut parts = bundle
6435 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6436 .into_parts();
6437 let diagnostics = parts.debug_diagnostics.as_mut().unwrap();
6438 let projected_context = diagnostics.prompt_context();
6439 let actual = crate::commands::debug_diagnostics_test_support::normalize_generated_at(
6440 &serde_json::to_string_pretty(&projected_context).unwrap(),
6441 );
6442 let expected = crate::commands::debug_diagnostics_test_support::normalize_generated_at(
6443 &serde_json::to_string_pretty(&original_context).unwrap(),
6444 );
6445 assert_eq!(projected_context.tools.len(), 1);
6446 assert_eq!(projected_context.tools[0].name, "search");
6447 assert_eq!(
6448 actual, expected,
6449 "projection retains the full ordered prompt JSON"
6450 );
6451 let projected_snapshot = diagnostics.tool_snapshot().unwrap();
6452 assert_eq!(
6453 serde_json::to_value(projected_snapshot).unwrap(),
6454 serde_json::to_value(original_snapshot).unwrap()
6455 );
6456 }
6457
6458 #[test]
6459 fn diagnostics_adapter_inspection_failure_does_not_write_and_success_commits_once() {
6460 let mut harness =
6461 crate::commands::debug_diagnostics_test_support::DiagnosticsHarness::new();
6462 harness.app.auto_model = true;
6463 harness.app.model = "auto".into();
6464 {
6465 let mut bundle = harness.app.command_contexts();
6466 let mut parts = bundle
6467 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6468 .into_parts();
6469 let diagnostics = parts.debug_diagnostics.as_mut().unwrap();
6470 assert_eq!(diagnostics.inspect_cache(), Err(codewhale_command_contract::facets::DebugCacheInspectionUnavailable::NoConcreteRoute));
6471 }
6472 assert!(harness.app.session.last_cache_inspection.is_none());
6473 harness.app.auto_model = false;
6474 harness.app.model = "deepseek-v4-pro".into();
6475 harness.app.active_route_base_url = "https://example.invalid/v1".into();
6476 let first = {
6477 let mut bundle = harness.app.command_contexts();
6478 let mut parts = bundle
6479 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6480 .into_parts();
6481 let diagnostics = parts.debug_diagnostics.as_mut().unwrap();
6482 let observation = diagnostics.inspect_cache().expect("concrete local route");
6483 assert!(observation.previous.is_none());
6484 assert!(
6485 diagnostics.inspect_cache().unwrap().previous.is_none(),
6486 "observation must not commit itself"
6487 );
6488 diagnostics.remember_cache_inspection(observation.current.clone());
6489 observation.current
6490 };
6491 assert_eq!(
6492 harness
6493 .app
6494 .session
6495 .last_cache_inspection
6496 .as_ref()
6497 .unwrap()
6498 .base_static_prefix_hash,
6499 first.base_static_prefix_hash
6500 );
6501 harness.app.active_route_base_url.clear();
6502 {
6503 let mut bundle = harness.app.command_contexts();
6504 let mut parts = bundle
6505 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6506 .into_parts();
6507 assert_eq!(
6508 parts.debug_diagnostics.as_mut().unwrap().inspect_cache(),
6509 Err(codewhale_command_contract::facets::DebugCacheInspectionUnavailable::MissingCapturedEndpoint),
6510 );
6511 }
6512 assert_eq!(
6513 harness
6514 .app
6515 .session
6516 .last_cache_inspection
6517 .as_ref()
6518 .unwrap()
6519 .base_static_prefix_hash,
6520 first.base_static_prefix_hash,
6521 "failed endpoint lookup must not write"
6522 );
6523 harness.app.active_route_base_url = "https://example.invalid/v1".into();
6524 harness.app.system_prompt = Some(SystemPrompt::Text("changed".into()));
6525 let mut bundle = harness.app.command_contexts();
6526 let mut parts = bundle
6527 .contexts(CommandCapabilities::DEBUG_DIAGNOSTICS)
6528 .into_parts();
6529 let observation = parts
6530 .debug_diagnostics
6531 .as_mut()
6532 .unwrap()
6533 .inspect_cache()
6534 .unwrap();
6535 assert_eq!(
6536 observation.previous.unwrap().base_static_prefix_hash,
6537 first.base_static_prefix_hash
6538 );
6539 assert_ne!(
6540 observation.current.base_static_prefix_hash,
6541 first.base_static_prefix_hash
6542 );
6543 }
6544
6545 // -----------------------------------------------------------------------
6546 // FEAT-018 adapter tests: presentation (D3), media (D4), digest (D5)
6547 // -----------------------------------------------------------------------
6548
6549 #[test]
6550 fn presentation_adapter_resolves_utility_keys_with_english_fallback() {
6551 let mut app = test_app();
6552 app.ui_locale = Locale::En;
6553 let mut bundle = app.command_contexts();
6554 let mut parts = bundle.parts();
6555 let presentation = parts.presentation.as_mut().expect("presentation facet");
6556
6557 // automation_usage has no placeholders.
6558 let usage = presentation
6559 .translate("automation_usage", &[])
6560 .expect("automation usage key");
6561 assert!(
6562 usage.contains("/automation"),
6563 "expected usage text, got {usage}"
6564 );
6565
6566 // mcp_recommended_unknown_id needs {recommendations_command}.
6567 let unknown = presentation
6568 .translate(
6569 "mcp_recommended_unknown_id",
6570 &[("recommendations_command", "/mcp recommendations")],
6571 )
6572 .expect("mcp unknown-id key");
6573 assert!(
6574 unknown.contains("/mcp recommendations"),
6575 "expected replacement text, got {unknown}"
6576 );
6577
6578 // mcp_recommendation_github needs {endpoint}, {login_command}, {add_command}.
6579 let github = presentation
6580 .translate(
6581 "mcp_recommendation_github",
6582 &[
6583 ("endpoint", "https://api.githubcopilot.com/mcp/"),
6584 ("login_command", "/mcp login github"),
6585 ("add_command", "/mcp add recommended github"),
6586 ],
6587 )
6588 .expect("github recommendation key");
6589 assert!(
6590 github.contains("https://api.githubcopilot.com/mcp/"),
6591 "{github}"
6592 );
6593 assert!(
6594 !github.contains("{endpoint}"),
6595 "placeholder must be replaced"
6596 );
6597 }
6598
6599 #[test]
6600 fn presentation_adapter_rejects_unknown_keys_and_invalid_replacements() {
6601 let mut app = test_app();
6602 app.ui_locale = Locale::En;
6603 let mut bundle = app.command_contexts();
6604 let mut parts = bundle.parts();
6605 let presentation = parts.presentation.as_mut().expect("presentation facet");
6606
6607 let unknown = presentation.translate("no_such_key", &[]);
6608 assert!(unknown.is_err(), "unknown key must fail safely");
6609 let err = unknown.unwrap_err();
6610 assert!(
6611 !err.contains("no_such_key"),
6612 "no raw lookup key exposure (D3): {err}"
6613 );
6614
6615 // Missing required replacement.
6616 assert!(
6617 presentation
6618 .translate("mcp_recommendation_github", &[])
6619 .is_err()
6620 );
6621 // Extra replacement not present in the template.
6622 assert!(
6623 presentation
6624 .translate("automation_usage", &[("no_such_placeholder", "value")],)
6625 .is_err()
6626 );
6627 // Duplicate replacement names.
6628 assert!(
6629 presentation
6630 .translate(
6631 "mcp_recommendation_github",
6632 &[
6633 ("endpoint", "a"),
6634 ("endpoint", "b"),
6635 ("login_command", "c"),
6636 ("add_command", "d"),
6637 ],
6638 )
6639 .is_err()
6640 );
6641 }
6642
6643 #[test]
6644 fn media_adapter_attaches_valid_image_and_preserves_confirm() {
6645 let tmpdir = tempfile::TempDir::new().expect("tempdir");
6646 let image_path = tmpdir.path().join("photo.png");
6647 std::fs::write(&image_path, PNG_1X1).expect("write image fixture");
6648
6649 let mut app = test_app();
6650 let mut bundle = app.command_contexts();
6651 let mut parts = bundle.parts();
6652 let media = parts.media.as_mut().expect("media facet");
6653 let receipt = media
6654 .attach_media(&image_path)
6655 .expect("valid image attaches");
6656 assert_eq!(receipt.kind, "image");
6657 assert_eq!(receipt.path, image_path.canonicalize().expect("canonical"));
6658 assert!(
6659 app.input.contains("[Attached image:"),
6660 "composer must contain the attachment reference"
6661 );
6662 }
6663
6664 #[test]
6665 fn media_adapter_rejects_invalid_media_atomically() {
6666 let tmpdir = tempfile::TempDir::new().expect("tempdir");
6667
6668 // Missing path.
6669 let mut app = test_app();
6670 {
6671 let mut bundle = app.command_contexts();
6672 let mut parts = bundle.parts();
6673 let media = parts.media.as_mut().expect("media facet");
6674 let missing = tmpdir.path().join("missing.png");
6675 let err = media.attach_media(&missing).unwrap_err();
6676 assert!(err.contains("Attachment not found"), "{err}");
6677 }
6678 assert!(
6679 app.input.is_empty(),
6680 "refused attachment must not reach composer"
6681 );
6682
6683 // Directory is not a file.
6684 {
6685 let mut bundle = app.command_contexts();
6686 let mut parts = bundle.parts();
6687 let media = parts.media.as_mut().expect("media facet");
6688 let dir = tmpdir.path().to_path_buf();
6689 let err = media.attach_media(&dir).unwrap_err();
6690 assert!(err.contains("Attachment is not a file"), "{err}");
6691 }
6692 assert!(app.input.is_empty());
6693
6694 // Unsupported extension.
6695 std::fs::write(tmpdir.path().join("notes.txt"), b"text").expect("write fixture");
6696 {
6697 let mut bundle = app.command_contexts();
6698 let mut parts = bundle.parts();
6699 let media = parts.media.as_mut().expect("media facet");
6700 let err = media
6701 .attach_media(&tmpdir.path().join("notes.txt"))
6702 .unwrap_err();
6703 assert!(err.contains("Unsupported attachment type"), "{err}");
6704 }
6705 assert!(app.input.is_empty());
6706
6707 // Corrupt image with a valid extension.
6708 std::fs::write(tmpdir.path().join("bad.png"), b"not an image").expect("write fixture");
6709 {
6710 let mut bundle = app.command_contexts();
6711 let mut parts = bundle.parts();
6712 let media = parts.media.as_mut().expect("media facet");
6713 let err = media
6714 .attach_media(&tmpdir.path().join("bad.png"))
6715 .unwrap_err();
6716 assert!(!err.is_empty(), "corrupt image must fail");
6717 }
6718 assert!(app.input.is_empty());
6719 }
6720
6721 #[test]
6722 fn media_adapter_attaches_valid_video_reference() {
6723 // A real (non-image) media file with a video extension passes the
6724 // extension gate without byte validation, matching baseline /attach.
6725 let tmpdir = tempfile::TempDir::new().expect("tempdir");
6726 let video_path = tmpdir.path().join("clip.mp4");
6727 std::fs::write(&video_path, b"not a real mp4 but extension-gated").expect("write");
6728
6729 let mut app = test_app();
6730 let mut bundle = app.command_contexts();
6731 let mut parts = bundle.parts();
6732 let media = parts.media.as_mut().expect("media facet");
6733 let receipt = media
6734 .attach_media(&video_path)
6735 .expect("video path attaches by extension");
6736 assert_eq!(receipt.kind, "video");
6737 assert!(app.input.contains("[Attached video:"), "{}", app.input);
6738 }
6739
6740 #[test]
6741 fn workspace_digest_adapter_preserves_no_active_and_failure_semantics() {
6742 let mut app = test_app();
6743 app.runtime_services.work = None;
6744 {
6745 let mut bundle = app.command_contexts();
6746 let mut parts = bundle.parts();
6747 let workspace = parts.workspace.as_mut().expect("workspace facet");
6748 assert_eq!(
6749 workspace.operation_digest().expect("no-runtime digest"),
6750 "No active operations or to-do items."
6751 );
6752 }
6753 }
6754
6755 #[test]
6756 fn bundle_construction_performs_no_eager_work() {
6757 let mut app = test_app();
6758 let input_before = app.input.clone();
6759 {
6760 let mut bundle = app.command_contexts();
6761 let parts = bundle.parts();
6762 // Merely constructing the bundle must not mutate composer state or
6763 // perform capability work; the adapters only run on method calls.
6764 let _ = parts.media.is_some();
6765 let _ = parts.presentation.is_some();
6766 let _ = parts.memory.is_some();
6767 let _ = parts.project.is_some();
6768 }
6769 assert_eq!(app.input, input_before, "no eager composer mutation");
6770 }
6771 // FEAT-021 project adapter tests
6772 // ---------------------------------------------------------------------
6773
6774 #[test]
6775 fn key_to_project_message_id_resolves_goal_runtime_keys_and_rejects_unknown() {
6776 // FEAT-021 D5: only /goal uses runtime translations via the project
6777 // key map; unknown keys fail safely.
6778 assert_eq!(
6779 key_to_project_message_id("goal_control_accepted"),
6780 Some(MessageId::GoalControlAccepted)
6781 );
6782 assert_eq!(
6783 key_to_project_message_id("goal_status_idle_hint"),
6784 Some(MessageId::GoalStatusIdleHint)
6785 );
6786 assert_eq!(key_to_project_message_id("goal_bogus_key"), None);
6787 assert_eq!(key_to_project_message_id(""), None);
6788 }
6789
6790 #[test]
6791 fn presentation_translate_resolves_project_keys_with_locale_and_fallback() {
6792 // The presentation facet resolves the project runtime keys through the
6793 // current catalog (authoritative English fallback preserved).
6794 let mut app = test_app();
6795 let mut bundle = app.command_contexts();
6796 let mut parts = bundle.parts();
6797 let presentation = parts.presentation.as_mut().expect("presentation facet");
6798 let accepted = presentation
6799 .translate("goal_control_accepted", &[])
6800 .expect("goal_control_accepted must resolve");
6801 assert!(
6802 accepted.contains("Goal control saved"),
6803 "English fallback text expected: {accepted}"
6804 );
6805 let hint = presentation
6806 .translate("goal_status_idle_hint", &[])
6807 .expect("goal_status_idle_hint must resolve");
6808 assert!(hint.contains("not running now"), "hint: {hint}");
6809 assert!(
6810 presentation.translate("goal_bogus", &[]).is_err(),
6811 "unknown key must fail safely"
6812 );
6813 }
6814
6815 // -----------------------------------------------------------------------
6816 // FEAT-019: memory adapter mappings (D6/D9)
6817 // -----------------------------------------------------------------------
6818
6819 /// App with an isolated temp memory file; memory feature enabled or not.
6820 fn memory_test_app(tmpdir: &TempDir, use_memory: bool) -> App {
6821 let options = crate::tui::test_support::test_tui_options(tmpdir.path());
6822 let options = crate::tui::app::TuiOptions {
6823 memory_path: tmpdir.path().join("memory.md"),
6824 use_memory,
6825 ..options
6826 };
6827 crate::tui::test_support::test_app_with_options(options)
6828 }
6829
6830 /// Give a temp workspace a git origin so workspace identity resolves.
6831 fn git_origin(workspace: &Path) {
6832 let init = std::process::Command::new("git")
6833 .arg("-C")
6834 .arg(workspace)
6835 .args(["init", "-q"])
6836 .status()
6837 .unwrap();
6838 assert!(init.success(), "git init must succeed");
6839 let remote = std::process::Command::new("git")
6840 .arg("-C")
6841 .arg(workspace)
6842 .args(["remote", "add", "origin", "https://example.test/repo.git"])
6843 .status()
6844 .unwrap();
6845 assert!(remote.success(), "git remote add must succeed");
6846 }
6847
6848 #[test]
6849 fn memory_adapter_maps_path_and_enablement() {
6850 let tmp = TempDir::new().unwrap();
6851 let mut enabled = memory_test_app(&tmp, true);
6852 let mut bundle = enabled.command_contexts();
6853 let memory = bundle.parts().memory.expect("memory facet must be present");
6854 assert_eq!(memory.memory_path(), tmp.path().join("memory.md"));
6855 assert!(memory.memory_enabled());
6856
6857 let mut disabled = memory_test_app(&tmp, false);
6858 let mut bundle = disabled.command_contexts();
6859 let memory = bundle.parts().memory.expect("memory facet must be present");
6860 assert!(!memory.memory_enabled());
6861 }
6862
6863 #[test]
6864 fn memory_adapter_status_and_path_map_native_store() {
6865 let tmp = TempDir::new().unwrap();
6866 let mut app = memory_test_app(&tmp, true);
6867 let mut bundle = app.command_contexts();
6868 let memory = bundle.parts().memory.expect("memory facet");
6869
6870 // Fallback root derivation mirrors the legacy handler: a plain
6871 // `memory.md` file is not a native global source, so the root is the
6872 // sibling `memory` directory.
6873 let status = memory.status().expect("status");
6874 assert_eq!(status.root, tmp.path().join("memory"));
6875 assert_eq!(
6876 status.source,
6877 tmp.path().join("memory").join("global").join("MEMORY.md")
6878 );
6879 assert_eq!(
6880 status.index,
6881 tmp.path().join("memory").join("store.sqlite3")
6882 );
6883 assert_eq!(memory.path().expect("path"), tmp.path().join("memory"));
6884 }
6885
6886 #[test]
6887 fn memory_adapter_workspace_identity_resolves_and_preserves_errors() {
6888 let tmp = TempDir::new().unwrap();
6889 git_origin(tmp.path());
6890 let mut app = memory_test_app(&tmp, true);
6891 let mut bundle = app.command_contexts();
6892 let memory = bundle.parts().memory.expect("memory facet");
6893 // A git origin resolves to a stable workspace identity (sha256 digest).
6894 let id = memory.workspace_id(tmp.path()).expect("workspace id");
6895 assert!(!id.is_empty());
6896 assert_eq!(id, memory.workspace_id(tmp.path()).expect("stable id"));
6897
6898 // A plain directory without a git origin still gets a stable identity.
6899 let plain = TempDir::new().unwrap();
6900 let plain_id = memory.workspace_id(plain.path()).expect("workspace id");
6901 assert!(!plain_id.is_empty());
6902 assert_ne!(plain_id, id);
6903 }
6904
6905 #[test]
6906 fn project_adapter_reports_lsp_state_from_the_config() {
6907 let mut app = test_app();
6908 app.lsp_config = None;
6909 let mut bundle = app.command_contexts();
6910 let project = bundle
6911 .parts()
6912 .project
6913 .expect("project facet must be present");
6914 assert!(project.lsp_status().contains("no `[lsp]` table"));
6915 assert!(project.lsp_approve(&["rust"]).is_err());
6916 }
6917
6918 #[test]
6919 fn project_adapter_approves_and_revokes_servers_for_the_trusted_workspace() {
6920 let folder = tempfile::tempdir().unwrap();
6921 let mut app = test_app();
6922 app.workspace = folder.path().to_path_buf();
6923 app.lsp_config = Some(codewhale_lsp::LspConfig::default());
6924 let mut bundle = app.command_contexts();
6925 let project = bundle
6926 .parts()
6927 .project
6928 .expect("project facet must be present");
6929
6930 assert!(project.lsp_approve(&["rust"]).is_err(), "needs saved trust");
6931 codewhale_runtime::test_support::trust_workspace(folder.path());
6932 assert!(project.lsp_approve(&["nonsense"]).is_err());
6933 assert!(project.lsp_approve(&[]).unwrap().contains("rust-analyzer"));
6934 project.lsp_approve(&["rust"]).unwrap();
6935 let status = project.lsp_status();
6936 let rust_line = status
6937 .lines()
6938 .find(|line| line.trim_start().starts_with("rust "))
6939 .unwrap();
6940 assert!(rust_line.contains("approved") && !rust_line.contains("not approved"));
6941 assert!(status.contains("/lsp approve go"));
6942 assert!(project.lsp_revoke(&["rust"]).unwrap().contains("Revoked"));
6943 assert!(project.lsp_status().contains("/lsp approve rust"));
6944 assert!(project.lsp_revoke(&[]).is_err());
6945 }
6946
6947 #[test]
6948 fn project_adapter_goal_projection_preserves_visible_and_effective_state() {
6949 let mut app = test_app();
6950 app.goal.objective = Some("Ship FEAT-021".to_string());
6951 app.goal.status = codewhale_engine::tools::goal::GoalStatus::Active;
6952 app.goal.time_used_seconds = 42;
6953 app.goal.token_budget = Some(50_000);
6954 app.goal.tokens_used = 1_000;
6955 app.goal.continuation_count = 3;
6956 app.session.total_conversation_tokens = 2_000;
6957 app.goal_continuation_waiting = true;
6958 app.is_loading = false;
6959 app.api_messages_mut().push(codewhale_models::Message {
6960 role: codewhale_models::Role::User,
6961 content: vec![codewhale_models::ContentBlock::Text {
6962 text: "work".to_string(),
6963 cache_control: None,
6964 }],
6965 });
6966
6967 let mut bundle = app.command_contexts();
6968 let project = bundle
6969 .parts()
6970 .project
6971 .expect("project facet must be present");
6972 let goal = project.goal_state();
6973 assert_eq!(goal.objective.as_deref(), Some("Ship FEAT-021"));
6974 assert_eq!(goal.status, ProjectGoalStatus::Active);
6975 assert_eq!(goal.time_used_seconds, 42);
6976 assert_eq!(goal.token_budget, Some(50_000));
6977 assert_eq!(goal.tokens_used, 1_000);
6978 assert_eq!(goal.session_total_tokens, 2_000);
6979 assert_eq!(goal.continuation_count, 3);
6980 assert!(!goal.pending_controls);
6981 assert!(goal.goal_continuation_waiting);
6982 assert!(goal.conversation_present);
6983
6984 // Pending controls flip the effective source to the durable state.
6985 app.pending_goal_controls
6986 .push_back(crate::tui::app::PendingGoalControl {
6987 goal_id: None,
6988 intent: crate::tui::app::GoalControlIntent::SetStatus {
6989 status: codewhale_engine::tools::goal::GoalStatus::Paused,
6990 clear: false,
6991 },
6992 dispatched: false,
6993 });
6994 app.last_known_goal_state = Some(codewhale_engine::session_manager::SessionGoalState {
6995 schema_version: 1,
6996 goal_id: None,
6997 last_gap_fingerprint: None,
6998 repeated_gap_count: 0,
6999 last_gap_pass: None,
7000 objective: "Durable objective".to_string(),
7001 status: codewhale_engine::session_manager::SessionGoalStatus::Paused,
7002 token_budget: None,
7003 tokens_used: 0,
7004 time_used_seconds: 0,
7005 continuation_count: 0,
7006 elapsed_seconds: 0,
7007 pause_reason: None,
7008 });
7009 let mut bundle = app.command_contexts();
7010 let project = bundle
7011 .parts()
7012 .project
7013 .expect("project facet must be present");
7014 let goal = project.goal_state();
7015 assert!(goal.pending_controls);
7016 assert_eq!(
7017 goal.last_known_objective.as_deref(),
7018 Some("Durable objective")
7019 );
7020 assert_eq!(goal.last_known_status, Some(ProjectGoalStatus::Paused));
7021 }
7022
7023 #[test]
7024 fn project_adapter_exposure_matches_main_envelope_model() {
7025 // main's envelope always populates every adapter (no capability
7026 // bitmask yet); the project facet is present and usable, and the
7027 // handlers destructure only the facets they need.
7028 let mut app = test_app();
7029 let mut bundle = app.command_contexts();
7030 let parts = bundle.parts();
7031 assert!(parts.project.is_some());
7032 assert!(parts.workspace.is_some());
7033 assert!(parts.presentation.is_some());
7034 }
7035
7036 #[test]
7037 fn memory_adapter_search_remember_get_export_reindex_work() {
7038 let tmp = TempDir::new().unwrap();
7039 let mut app = memory_test_app(&tmp, true);
7040 let mut bundle = app.command_contexts();
7041 let memory = bundle.parts().memory.expect("memory facet");
7042
7043 // Global remember produces a portable remembered location.
7044 let remembered = memory
7045 .remember(MemoryRememberTarget::Global, "alpha note")
7046 .expect("remember global");
7047 assert!(remembered.source.ends_with("global/MEMORY.md"));
7048 // Structured records have no line position; the anchor is the scope's
7049 // compatibility MEMORY.md path, not a byte offset into it.
7050 assert_eq!(remembered.line_start, 0);
7051
7052 // Workspace remember targets the workspace scope with the typed id.
7053 git_origin(tmp.path());
7054 let workspace_id = memory.workspace_id(tmp.path()).expect("id");
7055 let workspace_note = memory
7056 .remember(
7057 MemoryRememberTarget::Workspace { workspace_id },
7058 "workspace-only note",
7059 )
7060 .expect("remember workspace");
7061 assert!(
7062 workspace_note
7063 .source
7064 .to_string_lossy()
7065 .contains("workspace")
7066 );
7067
7068 // Search finds workspace-scoped content only for the given workspace.
7069 let hits = memory
7070 .search(tmp.path(), "workspace-only", 10)
7071 .expect("search");
7072 assert_eq!(hits.len(), 1);
7073 assert!(hits[0].text.contains("workspace-only note"));
7074 assert_eq!(hits[0].line_start, 0);
7075 // Empty results stay a typed empty vec, never an error.
7076 assert!(
7077 memory
7078 .search(tmp.path(), "zzz-no-match", 10)
7079 .expect("empty search")
7080 .is_empty()
7081 );
7082
7083 // Get distinguishes found from not-found (first rowid is 1).
7084 match memory.get(tmp.path(), 1) {
7085 Ok(MemoryGetOutcome::Found(hit)) => assert!(!hit.text.is_empty()),
7086 other => panic!("expected found entry, got {other:?}"),
7087 }
7088 assert_eq!(
7089 memory.get(tmp.path(), 999_999).expect("get"),
7090 MemoryGetOutcome::NotFound
7091 );
7092
7093 // Export carries the document; reindex reports the typed count.
7094 let exported = memory.export().expect("export");
7095 assert!(exported.content.contains("alpha note"));
7096 assert!(exported.content.contains("workspace-only note"));
7097 assert!(memory.reindex().expect("reindex").entry_count >= 1);
7098 }
7099
7100 #[test]
7101 fn memory_adapter_import_distinguishes_imported_from_skipped() {
7102 let tmp = TempDir::new().unwrap();
7103 let legacy = tmp.path().join("memory.md");
7104 std::fs::write(&legacy, "# legacy\n\n- imported line").unwrap();
7105 let mut app = memory_test_app(&tmp, true);
7106 let mut bundle = app.command_contexts();
7107 let memory = bundle.parts().memory.expect("memory facet");
7108
7109 let imported = memory.import().expect("import");
7110 let MemoryImportOutcome::Imported { destination } = imported else {
7111 panic!("first import must be imported");
7112 };
7113 assert!(destination.ends_with("global/MEMORY.md"));
7114
7115 // Idempotent: an existing global source reports skipped.
7116 assert_eq!(
7117 memory.import().expect("second"),
7118 MemoryImportOutcome::Skipped
7119 );
7120 }
7121
7122 #[test]
7123 fn memory_adapter_deletes_are_scoped_and_preserve_other_memory() {
7124 let tmp = TempDir::new().unwrap();
7125 git_origin(tmp.path());
7126 let mut app = memory_test_app(&tmp, true);
7127 let mut bundle = app.command_contexts();
7128 let memory = bundle.parts().memory.expect("memory facet");
7129
7130 memory
7131 .remember(MemoryRememberTarget::Global, "keep global")
7132 .expect("global");
7133 let workspace_id = memory.workspace_id(tmp.path()).expect("id");
7134 memory
7135 .remember(
7136 MemoryRememberTarget::Workspace { workspace_id },
7137 "remove workspace",
7138 )
7139 .expect("workspace");
7140
7141 // Workspace deletion removes only the workspace scope.
7142 memory
7143 .delete_workspace(tmp.path())
7144 .expect("workspace delete");
7145 assert!(
7146 memory
7147 .search(tmp.path(), "remove workspace", 10)
7148 .expect("search")
7149 .is_empty()
7150 );
7151 assert_eq!(
7152 memory.search(tmp.path(), "keep global", 10).unwrap().len(),
7153 1
7154 );
7155
7156 // Global deletion removes the global scope but keeps the workspace one.
7157 memory
7158 .remember(
7159 MemoryRememberTarget::Workspace {
7160 workspace_id: memory.workspace_id(tmp.path()).expect("id"),
7161 },
7162 "workspace survivor",
7163 )
7164 .expect("workspace again");
7165 memory
7166 .delete(MemoryDeleteScope::Global)
7167 .expect("global delete");
7168 assert!(
7169 memory
7170 .search(tmp.path(), "keep global", 10)
7171 .expect("search")
7172 .is_empty()
7173 );
7174 assert_eq!(
7175 memory
7176 .search(tmp.path(), "workspace survivor", 10)
7177 .unwrap()
7178 .len(),
7179 1
7180 );
7181
7182 // All deletion removes every scope.
7183 memory.delete(MemoryDeleteScope::All).expect("all delete");
7184 assert!(
7185 memory
7186 .search(tmp.path(), "workspace survivor", 10)
7187 .expect("search")
7188 .is_empty()
7189 );
7190 }
7191
7192 #[test]
7193 fn memory_adapter_deletes_workspace_without_an_origin() {
7194 let tmp = TempDir::new().unwrap();
7195 let mut app = memory_test_app(&tmp, true);
7196 let mut bundle = app.command_contexts();
7197 let memory = bundle.parts().memory.expect("memory facet");
7198 memory
7199 .delete_workspace(tmp.path())
7200 .expect("plain folder still has a workspace id");
7201 }
7202
7203 #[test]
7204 fn envelope_exposes_only_declared_capabilities() {
7205 let tmp = TempDir::new().unwrap();
7206 let mut app = memory_test_app(&tmp, true);
7207 let mut bundle = app.command_contexts();
7208
7209 // Memory-only: memory present, workspace/session absent.
7210 let parts = bundle.contexts(CommandCapabilities::MEMORY).into_parts();
7211 assert!(parts.memory.is_some());
7212 assert!(parts.workspace.is_none());
7213 assert!(parts.session.is_none());
7214
7215 // Workspace-only: memory absent.
7216 let parts = bundle.contexts(CommandCapabilities::WORKSPACE).into_parts();
7217 assert!(parts.workspace.is_some());
7218 assert!(parts.memory.is_none());
7219
7220 // Workspace | MEMORY: both present, presentation/media absent.
7221 let parts = bundle
7222 .contexts(CommandCapabilities::WORKSPACE.union(CommandCapabilities::MEMORY))
7223 .into_parts();
7224 assert!(parts.workspace.is_some());
7225 assert!(parts.memory.is_some());
7226 assert!(parts.presentation.is_none());
7227 assert!(parts.media.is_none());
7228
7229 // Lifecycle-only: lifecycle present and every unrelated slot absent.
7230 let parts = bundle
7231 .contexts(CommandCapabilities::SESSION_LIFECYCLE)
7232 .into_parts();
7233 assert!(parts.lifecycle.is_some());
7234 assert!(parts.session.is_none());
7235 assert!(parts.model.is_none());
7236 assert!(parts.cost.is_none());
7237 assert!(parts.mode_policy.is_none());
7238 assert!(parts.system_prompt.is_none());
7239 assert!(parts.skills.is_none());
7240 assert!(parts.workspace.is_none());
7241 assert!(parts.presentation.is_none());
7242 assert!(parts.media.is_none());
7243 assert!(parts.memory.is_none());
7244 assert!(parts.project.is_none());
7245 assert!(parts.skill_group.is_none());
7246 assert!(parts.plugin.is_none());
7247
7248 // Control-only: control present and every unrelated slot absent.
7249 let parts = bundle
7250 .contexts(CommandCapabilities::SESSION_CONTROL)
7251 .into_parts();
7252 assert!(parts.control.is_some());
7253 assert!(parts.session.is_none());
7254 assert!(parts.model.is_none());
7255 assert!(parts.cost.is_none());
7256 assert!(parts.mode_policy.is_none());
7257 assert!(parts.system_prompt.is_none());
7258 assert!(parts.skills.is_none());
7259 assert!(parts.workspace.is_none());
7260 assert!(parts.presentation.is_none());
7261 assert!(parts.media.is_none());
7262 assert!(parts.memory.is_none());
7263 assert!(parts.project.is_none());
7264 assert!(parts.skill_group.is_none());
7265 assert!(parts.plugin.is_none());
7266 assert!(parts.lifecycle.is_none());
7267
7268 // `/remote-env`: exactly control plus presentation.
7269 let parts = bundle
7270 .contexts(CommandCapabilities::SESSION_CONTROL.union(CommandCapabilities::PRESENTATION))
7271 .into_parts();
7272 assert!(parts.control.is_some());
7273 assert!(parts.presentation.is_some());
7274 assert!(parts.session.is_none());
7275 assert!(parts.workspace.is_none());
7276 assert!(parts.lifecycle.is_none());
7277 assert!(parts.plugin.is_none());
7278
7279 // Unrelated capability: memory, lifecycle, and control all absent.
7280 let parts = bundle.contexts(CommandCapabilities::SESSION).into_parts();
7281 assert!(parts.session.is_some());
7282 assert!(parts.memory.is_none());
7283 assert!(parts.lifecycle.is_none());
7284 assert!(parts.control.is_none());
7285 }
7286
7287 // ─── FEAT-022 skill-group adapter tests ───────────────────────────────────
7288
7289 /// Seals the user's home for the duration of the test under the
7290 /// crate-wide env mutex (keeps global skill/snapshot discovery hermetic).
7291 fn scoped_home(_workspace: &TempDir) -> crate::test_support::SealedHome {
7292 crate::test_support::SealedHome::new()
7293 }
7294
7295 /// The fixture's skills dir lives inside its workspace, so the workspace
7296 /// must be trusted for those skills to load.
7297 fn skill_test_app(tmp: &TempDir, skills_dir: &Path) -> App {
7298 crate::test_support::trust_workspace(tmp.path());
7299 let mut options = crate::tui::test_support::test_tui_options(tmp.path());
7300 options.skills_dir = skills_dir.to_path_buf();
7301 crate::tui::test_support::test_app_with_options(options)
7302 }
7303
7304 fn write_skill(dir: &Path, name: &str) {
7305 let skill_dir = dir.join(name);
7306 std::fs::create_dir_all(&skill_dir).unwrap();
7307 std::fs::write(
7308 skill_dir.join("SKILL.md"),
7309 format!("---\nname: {name}\ndescription: {name} skill\n---\n{name} instructions"),
7310 )
7311 .unwrap();
7312 }
7313
7314 #[test]
7315 fn skill_group_projection_maps_native_skills_and_dirs() {
7316 let tmp = TempDir::new().unwrap();
7317 let _home = scoped_home(&tmp);
7318 crate::test_support::trust_workspace(tmp.path());
7319 let skills_dir = tmp.path().join("skills");
7320 write_skill(&skills_dir, "demo");
7321 let mut app = skill_test_app(&tmp, &skills_dir);
7322 let mut bundle = app.command_contexts();
7323 let group = bundle
7324 .parts()
7325 .skill_group
7326 .expect("skill_group facet must be present");
7327 let projection = group.skill_registry_projection();
7328 assert_eq!(projection.total, 1);
7329 assert_eq!(projection.entries.len(), 1);
7330 assert_eq!(projection.entries[0].name, "demo");
7331 assert_eq!(projection.entries[0].description, "demo skill");
7332 assert_eq!(projection.entries[0].source, SkillSourceKind::Native);
7333 assert!(projection.entries[0].path.is_some());
7334 assert_eq!(projection.skills_dir, skills_dir.display().to_string());
7335 assert!(!projection.dirs.is_empty());
7336 assert!(projection.warnings.is_empty());
7337 }
7338
7339 #[test]
7340 fn skill_group_projection_reports_empty_registry() {
7341 let tmp = TempDir::new().unwrap();
7342 let _home = scoped_home(&tmp);
7343 let skills_dir = tmp.path().join("skills");
7344 std::fs::create_dir_all(&skills_dir).unwrap();
7345 let mut app = skill_test_app(&tmp, &skills_dir);
7346 let mut bundle = app.command_contexts();
7347 let group = bundle
7348 .parts()
7349 .skill_group
7350 .expect("skill_group facet must be present");
7351 let projection = group.skill_registry_projection();
7352 assert_eq!(projection.total, 0);
7353 assert!(projection.entries.is_empty());
7354 }
7355
7356 #[test]
7357 fn skill_group_activation_sets_active_skill_and_history() {
7358 let tmp = TempDir::new().unwrap();
7359 let _home = scoped_home(&tmp);
7360 let skills_dir = tmp.path().join("skills");
7361 write_skill(&skills_dir, "demo");
7362 let mut app = skill_test_app(&tmp, &skills_dir);
7363 {
7364 let mut bundle = app.command_contexts();
7365 let group = bundle
7366 .parts()
7367 .skill_group
7368 .expect("skill_group facet must be present");
7369 let outcome = group.activate_skill("demo").unwrap();
7370 assert_eq!(outcome.name, "demo");
7371 assert_eq!(outcome.description, "demo skill");
7372 }
7373 assert!(app.active_skill.is_some());
7374 assert!(
7375 app.active_skill
7376 .as_deref()
7377 .unwrap()
7378 .contains("# Skill: demo")
7379 );
7380 assert!(app.active_skill_provenance.is_none());
7381 assert!(!app.history.is_empty());
7382 }
7383
7384 #[test]
7385 fn skill_group_activation_looks_up_exact_name() {
7386 // The `/skill new` -> skill-creator alias is handler-side parsing
7387 // (Phase 4); the delegate performs an exact host lookup.
7388 let tmp = TempDir::new().unwrap();
7389 let _home = scoped_home(&tmp);
7390 let skills_dir = tmp.path().join("skills");
7391 write_skill(&skills_dir, "skill-creator");
7392 let mut app = skill_test_app(&tmp, &skills_dir);
7393 {
7394 let mut bundle = app.command_contexts();
7395 let group = bundle
7396 .parts()
7397 .skill_group
7398 .expect("skill_group facet must be present");
7399 let outcome = group.activate_skill("skill-creator").unwrap();
7400 assert_eq!(outcome.name, "skill-creator");
7401 }
7402 assert!(app.active_skill.is_some());
7403 }
7404
7405 #[test]
7406 fn skill_group_activation_not_found_lists_available() {
7407 let tmp = TempDir::new().unwrap();
7408 let _home = scoped_home(&tmp);
7409 let skills_dir = tmp.path().join("skills");
7410 write_skill(&skills_dir, "demo");
7411 let mut app = skill_test_app(&tmp, &skills_dir);
7412 {
7413 let mut bundle = app.command_contexts();
7414 let group = bundle
7415 .parts()
7416 .skill_group
7417 .expect("skill_group facet must be present");
7418 let err = group.activate_skill("missing").unwrap_err();
7419 match err {
7420 SkillActivationError::NotFound {
7421 requested,
7422 available,
7423 ..
7424 } => {
7425 assert_eq!(requested, "missing");
7426 assert!(available.contains(&"demo".to_string()));
7427 }
7428 _ => panic!("expected NotFound"),
7429 }
7430 }
7431 assert!(app.active_skill.is_none());
7432 }
7433
7434 #[test]
7435 fn skill_group_install_invalid_source_returns_safe_error() {
7436 let tmp = TempDir::new().unwrap();
7437 let _home = scoped_home(&tmp);
7438 let skills_dir = tmp.path().join("skills");
7439 std::fs::create_dir_all(&skills_dir).unwrap();
7440 let mut app = skill_test_app(&tmp, &skills_dir);
7441 {
7442 let mut bundle = app.command_contexts();
7443 let group = bundle
7444 .parts()
7445 .skill_group
7446 .expect("skill_group facet must be present");
7447 let err = group.install_skill(None, " ").unwrap_err();
7448 assert!(err.contains("Invalid install source"), "{err}");
7449 }
7450 }
7451
7452 #[test]
7453 fn skill_group_review_ready_sets_side_effects() {
7454 let tmp = TempDir::new().unwrap();
7455 let _home = scoped_home(&tmp);
7456 let skills_dir = tmp.path().join("skills");
7457 write_skill(&skills_dir, "review");
7458 let mut app = skill_test_app(&tmp, &skills_dir);
7459 {
7460 let mut bundle = app.command_contexts();
7461 let group = bundle
7462 .parts()
7463 .skill_group
7464 .expect("skill_group facet must be present");
7465 let outcome = group.run_review().unwrap();
7466 assert_eq!(outcome, ReviewOutcome::Ready);
7467 }
7468 assert!(app.active_skill.is_some());
7469 assert!(app.active_skill_provenance.is_none());
7470 assert!(!app.history.is_empty());
7471 }
7472
7473 #[test]
7474 fn skill_group_review_not_found_reports_searched_dirs() {
7475 let tmp = TempDir::new().unwrap();
7476 let _home = scoped_home(&tmp);
7477 let skills_dir = tmp.path().join("skills");
7478 std::fs::create_dir_all(&skills_dir).unwrap();
7479 let mut app = skill_test_app(&tmp, &skills_dir);
7480 {
7481 let mut bundle = app.command_contexts();
7482 let group = bundle
7483 .parts()
7484 .skill_group
7485 .expect("skill_group facet must be present");
7486 let outcome = group.run_review().unwrap();
7487 match outcome {
7488 ReviewOutcome::NotFound {
7489 skills_dir: found_dir,
7490 global_dir,
7491 warnings,
7492 } => {
7493 assert_eq!(found_dir, skills_dir.display().to_string());
7494 assert_eq!(
7495 global_dir,
7496 codewhale_skills::default_skills_dir().display().to_string()
7497 );
7498 assert!(warnings.is_empty());
7499 }
7500 _ => panic!("expected NotFound"),
7501 }
7502 }
7503 assert!(app.active_skill.is_none());
7504 }
7505
7506 #[test]
7507 fn skill_group_snapshot_list_and_restore_roundtrip() {
7508 for in_runtime in [false, true] {
7509 let tmp = TempDir::new().unwrap();
7510 let _home = scoped_home(&tmp);
7511 let skills_dir = tmp.path().join("skills");
7512 let file = tmp.path().join("a.txt");
7513 let repo = codewhale_snapshot::SnapshotRepo::open_or_init(tmp.path()).unwrap();
7514 std::fs::write(&file, b"v1").unwrap();
7515 repo.snapshot("pre-turn:1").unwrap();
7516 std::fs::write(&file, b"v2").unwrap();
7517 let mut app = skill_test_app(&tmp, &skills_dir);
7518 {
7519 let mut bundle = app.command_contexts();
7520 let group = bundle
7521 .parts()
7522 .skill_group
7523 .expect("skill_group facet must be present");
7524 let entries = group.snapshot_list(20).unwrap();
7525 assert_eq!(entries.len(), 1);
7526 assert_eq!(entries[0].label, "pre-turn:1");
7527 assert!(!entries[0].id.is_empty());
7528 let mut restore = || {
7529 group.restore_snapshot(&entries[0].id).unwrap();
7530 assert!(
7531 group
7532 .restore_snapshot("not-a-snapshot")
7533 .unwrap_err()
7534 .starts_with("Restore failed:")
7535 );
7536 };
7537 if in_runtime {
7538 tokio::runtime::Builder::new_multi_thread()
7539 .worker_threads(1)
7540 .enable_all()
7541 .build()
7542 .unwrap()
7543 .block_on(async { restore() });
7544 } else {
7545 restore();
7546 }
7547 }
7548 assert_eq!(std::fs::read_to_string(&file).unwrap(), "v1");
7549 }
7550 }
7551
7552 #[test]
7553 fn skill_group_approval_state_reflects_app_posture() {
7554 let tmp = TempDir::new().unwrap();
7555 let _home = scoped_home(&tmp);
7556 let skills_dir = tmp.path().join("skills");
7557 let mut app = skill_test_app(&tmp, &skills_dir);
7558 app.yolo = true;
7559 app.trust_mode = false;
7560 {
7561 let mut bundle = app.command_contexts();
7562 let group = bundle
7563 .parts()
7564 .skill_group
7565 .expect("skill_group facet must be present");
7566 let state = group.approval_state();
7567 assert!(state.yolo);
7568 assert!(!state.trust_mode);
7569 }
7570 app.yolo = false;
7571 app.trust_mode = true;
7572 {
7573 let mut bundle = app.command_contexts();
7574 let group = bundle
7575 .parts()
7576 .skill_group
7577 .expect("skill_group facet must be present");
7578 let state = group.approval_state();
7579 assert!(!state.yolo);
7580 assert!(state.trust_mode);
7581 }
7582 }
7583
7584 #[test]
7585 fn portable_scope_maps_both_scopes_and_none() {
7586 use codewhale_skills::mutation::SkillTargetScope as TuiScope;
7587 assert_eq!(
7588 portable_scope(Some(SkillTargetScope::Project)),
7589 Some(TuiScope::Project)
7590 );
7591 assert_eq!(
7592 portable_scope(Some(SkillTargetScope::Global)),
7593 Some(TuiScope::Global)
7594 );
7595 assert_eq!(portable_scope(None), None);
7596 }
7597
7598 #[test]
7599 fn portable_mutation_receipt_maps_distinct_outcomes() {
7600 use codewhale_skills::audit::SkillActionKind;
7601 use codewhale_skills::mutation::{
7602 SkillMutationOutcome as TuiOutcome, SkillMutationReceipt as TuiReceipt,
7603 };
7604 use codewhale_skills::roots::SkillScope;
7605 let make = |outcome: TuiOutcome| TuiReceipt {
7606 action: SkillActionKind::Install,
7607 name: "demo".to_string(),
7608 scope: SkillScope::Global,
7609 safe_target_path: "/tmp/demo".to_string(),
7610 outcome,
7611 };
7612 let installed = portable_mutation_receipt(&make(TuiOutcome::Installed));
7613 assert_eq!(installed.outcome, SkillMutationOutcome::Installed);
7614 assert_eq!(installed.name, "demo");
7615 assert_eq!(installed.safe_target_path, "/tmp/demo");
7616
7617 let approval =
7618 portable_mutation_receipt(&make(TuiOutcome::NeedsApproval("acme.com".to_string())));
7619 assert_eq!(
7620 approval.outcome,
7621 SkillMutationOutcome::NeedsApproval("acme.com".to_string())
7622 );
7623
7624 let denied =
7625 portable_mutation_receipt(&make(TuiOutcome::NetworkDenied("acme.com".to_string())));
7626 assert_eq!(
7627 denied.outcome,
7628 SkillMutationOutcome::NetworkDenied("acme.com".to_string())
7629 );
7630 assert_ne!(installed.outcome, denied.outcome);
7631 }
7632
7633 #[test]
7634 fn skill_group_adapter_exposure_matches_main_envelope_model() {
7635 // The envelope populates the skill_group slot alongside the other
7636 // adapters; handlers destructure only their declared facets (D4).
7637 let mut app = test_app();
7638 let mut bundle = app.command_contexts();
7639 let parts = bundle.parts();
7640 assert!(parts.skill_group.is_some());
7641 assert!(parts.project.is_some());
7642 assert!(parts.skills.is_some());
7643 }
7644
7645 // ------------------------------------------------------------------
7646 // FEAT-020 plugin adapter tests
7647 // ------------------------------------------------------------------
7648
7649 fn plugin_test_app(tmpdir: &TempDir) -> App {
7650 let options = crate::tui::test_support::test_tui_options(tmpdir.path());
7651 let mut app = crate::tui::test_support::test_app_with_options(options);
7652 app.ui_locale = Locale::En;
7653 app
7654 }
7655
7656 /// Write a minimal plugin bundle into the temp workspace's
7657 /// `.codewhale/plugins` so the adapter can read real host data.
7658 fn write_demo_bundle(root: &Path) {
7659 let bundle = root.join(".codewhale/plugins/demo");
7660 std::fs::create_dir_all(bundle.join("skills/hello")).unwrap();
7661 std::fs::write(
7662 bundle.join("plugin.toml"),
7663 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\ndescription = \"Import spreadsheet data safely\"\n[skills]\npath = \"skills\"\n",
7664 )
7665 .unwrap();
7666 std::fs::write(
7667 bundle.join("skills/hello/SKILL.md"),
7668 "---\nname: hello\ndescription: hello\n---\nbody\n",
7669 )
7670 .unwrap();
7671 }
7672
7673 #[test]
7674 fn plugin_adapter_summaries_and_detail_project_host_data() {
7675 let tmp = TempDir::new().unwrap();
7676 write_demo_bundle(tmp.path());
7677 let mut app = plugin_test_app(&tmp);
7678 // Discover only the demo bundle: the host's real `~/.codewhale/plugins`
7679 // and materialized builtin plugins must not leak diagnostics into this
7680 // assertion (they did on a shared CI agent).
7681 let plugin_config = codewhale_plugins::discovery::DiscoveryConfig {
7682 workspace: tmp.path().to_path_buf(),
7683 user_plugins_dir: tmp.path().join("user-plugins"),
7684 workspace_plugins_dir: tmp.path().join(".codewhale/plugins"),
7685 builtin_plugin_dirs: Vec::new(),
7686 state_path: tmp.path().join("user-plugins/state.json"),
7687 };
7688 let discovery = codewhale_plugins::PluginDiscoveryContext::from_config_and_environment(
7689 &plugin_config,
7690 codewhale_plugins::HostEnvironment::capture(),
7691 );
7692 app.plugin_registry = discovery.registry_for_workspace(tmp.path());
7693 let mut bundle = app.command_contexts();
7694 let mut parts = bundle
7695 .contexts(
7696 CommandCapabilities::WORKSPACE
7697 .union(CommandCapabilities::PRESENTATION)
7698 .union(CommandCapabilities::PLUGIN),
7699 )
7700 .into_parts();
7701 let plugin = parts.plugin.as_deref_mut().unwrap();
7702
7703 let summaries = plugin.summaries().unwrap();
7704 assert!(!summaries.is_empty());
7705 let summary = summaries
7706 .iter()
7707 .find(|s| s.name == "demo")
7708 .expect("demo summary");
7709 assert_eq!(summary.compatibility, "full");
7710 assert!(
7711 summary.inventory.starts_with("skills=1"),
7712 "inventory summary: {}",
7713 summary.inventory
7714 );
7715
7716 let detail = plugin.detail("demo").unwrap();
7717 assert_eq!(detail.name, "demo");
7718 assert_eq!(detail.version, "1.0.0");
7719 assert_eq!(detail.skills, vec!["demo:hello"]);
7720 assert_eq!(detail.trust_status, "not-reviewed");
7721
7722 // Unknown selector fails safely.
7723 assert!(plugin.detail("nope").is_err());
7724 // Registry diagnostics empty for a clean bundle.
7725 assert!(plugin.registry_diagnostics().is_empty());
7726 assert!(plugin.validation_is_clean());
7727 }
7728
7729 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7730 async fn plugin_adapter_dsh_preview_runs_from_live_runtime() {
7731 let _home = crate::test_support::SealedHome::new();
7732 if codewhale_engine::extension_host::test_support::node_for_tests(
7733 "plugin_adapter_dsh_preview_runs_from_live_runtime",
7734 )
7735 .is_none()
7736 {
7737 return;
7738 }
7739 let tmp = TempDir::new().unwrap();
7740 let mut app = plugin_test_app(&tmp);
7741 let before = app.plugin_registry.len();
7742 let package = codewhale_engine::extension_host::test_support::fixtures_dir()
7743 .join("raw-agent-presets/source");
7744 let mut bundle = app.command_contexts();
7745 let mut parts = bundle.contexts(CommandCapabilities::PLUGIN).into_parts();
7746 let plugin = parts.plugin.as_deref_mut().unwrap();
7747 let review = plugin
7748 .dsh_preview(&package)
7749 .expect("live TUI Native review");
7750 assert_eq!(review.plugin_name, "raw-agent-presets");
7751 assert_eq!(
7752 review.source_package.as_deref(),
7753 Some("@demo/raw-agent-presets")
7754 );
7755 assert_eq!(review.content_hash.len(), 64);
7756 assert!(review.manual_ports.is_empty(), "{:?}", review.manual_ports);
7757 assert_eq!(plugin.len(), before, "preview must not install a bundle");
7758 }
7759
7760 #[test]
7761 fn plugin_adapter_registry_mutations_and_suggest_are_behavior_faithful() {
7762 let tmp = TempDir::new().unwrap();
7763 write_demo_bundle(tmp.path());
7764 let mut app = plugin_test_app(&tmp);
7765 // Discover only the demo bundle: the host's real `~/.codewhale/plugins`
7766 // and materialized builtin plugins must not leak diagnostics into this
7767 // assertion (they did on a shared CI agent).
7768 let plugin_config = codewhale_plugins::discovery::DiscoveryConfig {
7769 workspace: tmp.path().to_path_buf(),
7770 user_plugins_dir: tmp.path().join("user-plugins"),
7771 workspace_plugins_dir: tmp.path().join(".codewhale/plugins"),
7772 builtin_plugin_dirs: Vec::new(),
7773 state_path: tmp.path().join("user-plugins/state.json"),
7774 };
7775 let discovery = codewhale_plugins::PluginDiscoveryContext::from_config_and_environment(
7776 &plugin_config,
7777 codewhale_plugins::HostEnvironment::capture(),
7778 );
7779 app.plugin_registry = discovery.registry_for_workspace(tmp.path());
7780 // Capture the review token before borrowing the mutable facet.
7781 let demo = app.plugin_registry.get("demo").unwrap();
7782 let token = format!("{}.{}", demo.content_hash, demo.capability_hash);
7783
7784 let mut bundle = app.command_contexts();
7785 let mut parts = bundle.contexts(CommandCapabilities::PLUGIN).into_parts();
7786 let plugin = parts.plugin.as_deref_mut().unwrap();
7787
7788 // Read-only suggest does not mutate anything.
7789 let before = plugin.len();
7790 let _ = plugin.suggest("spreadsheet");
7791 assert_eq!(plugin.len(), before);
7792 assert_eq!(plugin.summaries().unwrap().len(), before);
7793
7794 // enable on an untrusted bundle routes to review (safe error), not a mutation.
7795 let err = plugin.enable("demo").unwrap_err();
7796 assert!(err.contains("requires review"));
7797
7798 // trust with a wrong token fails safely.
7799 assert!(plugin.trust("demo", "bogus.token").is_err());
7800
7801 // trust with the exact token succeeds.
7802 plugin.trust("demo", &token).unwrap();
7803 assert!(plugin.detail("demo").unwrap().trusted);
7804
7805 // enable now succeeds.
7806 plugin.enable("demo").unwrap();
7807 assert!(plugin.detail("demo").unwrap().enabled);
7808
7809 // disable clears active skill and marks disabled.
7810 plugin.disable("demo").unwrap();
7811 assert!(!plugin.detail("demo").unwrap().enabled);
7812
7813 // revoke_trust flips trust back off.
7814 plugin.revoke_trust("demo").unwrap();
7815 assert!(!plugin.detail("demo").unwrap().trusted);
7816 }
7817
7818 #[test]
7819 fn plugin_adapter_exposure_is_exactly_declared_capabilities() {
7820 let tmp = TempDir::new().unwrap();
7821 let mut app = plugin_test_app(&tmp);
7822 let mut bundle = app.command_contexts();
7823
7824 // Plugin-only: plugin present, everything else absent.
7825 let parts = bundle.contexts(CommandCapabilities::PLUGIN).into_parts();
7826 assert!(parts.plugin.is_some());
7827 assert!(parts.workspace.is_none());
7828 assert!(parts.presentation.is_none());
7829 assert!(parts.memory.is_none());
7830
7831 // Workspace | PRESENTATION | PLUGIN: all three present, media/memory absent.
7832 let parts = bundle
7833 .contexts(
7834 CommandCapabilities::WORKSPACE
7835 .union(CommandCapabilities::PRESENTATION)
7836 .union(CommandCapabilities::PLUGIN),
7837 )
7838 .into_parts();
7839 assert!(parts.plugin.is_some());
7840 assert!(parts.workspace.is_some());
7841 assert!(parts.presentation.is_some());
7842 assert!(parts.media.is_none());
7843 assert!(parts.memory.is_none());
7844
7845 // Undeclared capability: plugin absent.
7846 let parts = bundle.contexts(CommandCapabilities::SESSION).into_parts();
7847 assert!(parts.session.is_some());
7848 assert!(parts.plugin.is_none());
7849 }
7850
7851 // ---------------------------------------------------------------------------
7852 // FEAT-023 Phase 3: SessionLifecycleAdapter tests (Tasks 3.2/3.4).
7853 // Every delegate is exercised over the real App with an isolated CODEWHALE_HOME
7854 // so SessionManager writes stay inside the temp directory. The bundle borrows
7855 // `App` for its whole life, so each test scopes the facet and re-reads `App`
7856 // only after dropping it (adapters borrow through the host `RefCell` at call
7857 // time, but the bundle itself holds the `&mut App`).
7858 // ---------------------------------------------------------------------------
7859
7860 fn lifecycle_test_app(tmpdir: &TempDir) -> App {
7861 let options = crate::tui::test_support::test_tui_options(tmpdir.path());
7862 App::new(options, &codewhale_runtime::config::Config::default())
7863 }
7864
7865 /// Point CODEWHALE_HOME at `tmp/home` with a pre-created sessions directory so
7866 /// `SessionManager::default_location()` resolves inside the temp sandbox.
7867 fn lifecycle_home_guard(tmpdir: &TempDir) -> crate::test_support::EnvVarGuard {
7868 let home = tmpdir.path().join("home");
7869 let sessions = home.join("sessions");
7870 std::fs::create_dir_all(&sessions).expect("create sandbox sessions dir");
7871 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home)
7872 }
7873
7874 fn user_message(text: &str) -> Message {
7875 Message {
7876 role: codewhale_models::Role::User,
7877 content: vec![codewhale_models::ContentBlock::Text {
7878 text: text.to_string(),
7879 cache_control: None,
7880 }],
7881 }
7882 }
7883
7884 #[test]
7885 fn lifecycle_dispatch_transition_blocking_wins_over_io() {
7886 let tmpdir = TempDir::new().unwrap();
7887 let _lock = crate::test_support::lock_test_env();
7888 let mut app = lifecycle_test_app(&tmpdir);
7889 app.is_loading = true;
7890 app.current_session_id = Some("active-session".to_string());
7891 app.api_messages_mut().push(user_message("in flight"));
7892
7893 for (command, expected) in [
7894 ("/fork", "Cannot fork a session"),
7895 ("/fork other-session", "Cannot fork a session"),
7896 ("/load does-not-exist.json", "Cannot load a session"),
7897 ("/new", "Cannot start a new session"),
7898 ("/branch entry-1", "Cannot branch"),
7899 ] {
7900 let result = crate::commands::execute(command, &mut app);
7901 assert!(result.is_error, "{command}: {result:?}");
7902 assert!(result.action.is_none(), "{command}: {result:?}");
7903 assert!(
7904 result
7905 .message
7906 .as_deref()
7907 .is_some_and(|text| text.contains(expected)),
7908 "{command}: {result:?}"
7909 );
7910 assert_eq!(app.current_session_id.as_deref(), Some("active-session"));
7911 assert_eq!(app.api_messages.len(), 1);
7912 }
7913 }
7914
7915 #[test]
7916 fn lifecycle_adapter_save_and_fork_roundtrip_preserves_history() {
7917 let tmpdir = TempDir::new().unwrap();
7918 let _lock = crate::test_support::lock_test_env();
7919 let _home = lifecycle_home_guard(&tmpdir);
7920 let mut app = lifecycle_test_app(&tmpdir);
7921 app.api_messages_mut()
7922 .push(user_message("try another path"));
7923
7924 let save_path = tmpdir.path().join("parent.json");
7925 {
7926 let mut bundle = app.command_contexts();
7927 let mut parts = bundle.parts();
7928 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
7929 let saved = facet
7930 .save_session(Some(save_path.display().to_string()))
7931 .expect("save ok");
7932 assert!(save_path.exists());
7933 assert!(!saved.display_path.is_empty());
7934 assert!(!saved.truncated_id.is_empty());
7935 }
7936 let parent_id = app
7937 .current_session_id
7938 .clone()
7939 .expect("save sets session id");
7940 {
7941 let mut bundle = app.command_contexts();
7942 let mut parts = bundle.parts();
7943 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
7944 let forked = facet.fork_active().expect("fork ok");
7945 assert!(!forked.parent_label.is_empty());
7946 assert!(!forked.fork_label.is_empty());
7947 assert!(forked.sync.session_id.is_some());
7948 assert_eq!(forked.sync.messages.len(), 1);
7949 assert_eq!(forked.sync.workspace, tmpdir.path());
7950 }
7951 let child_id = app
7952 .current_session_id
7953 .clone()
7954 .expect("fork switches session");
7955 assert_ne!(child_id, parent_id);
7956
7957 let manager =
7958 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
7959 let parent = manager.load_session(&parent_id).expect("parent loadable");
7960 let child = manager.load_session(&child_id).expect("child loadable");
7961 assert_eq!(parent.messages.len(), 1, "parent history preserved");
7962 assert_eq!(
7963 child.metadata.parent_session_id.as_deref(),
7964 Some(parent_id.as_str())
7965 );
7966 assert_eq!(child.metadata.forked_from_message_count, Some(1));
7967 }
7968
7969 #[test]
7970 fn lifecycle_adapter_explicit_fork_reports_spawn_depth_and_preserves_source() {
7971 let tmpdir = TempDir::new().unwrap();
7972 let _lock = crate::test_support::lock_test_env();
7973 let _home = lifecycle_home_guard(&tmpdir);
7974 let mut app = lifecycle_test_app(&tmpdir);
7975 app.api_messages_mut().push(user_message("parent turn"));
7976 {
7977 let mut bundle = app.command_contexts();
7978 let mut parts = bundle.parts();
7979 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
7980 let saved = facet.save_session(None).expect("save into managed dir");
7981 assert!(!saved.truncated_id.is_empty());
7982 }
7983 let parent_id = app
7984 .current_session_id
7985 .clone()
7986 .expect("save sets session id");
7987 let source_len = {
7988 let manager =
7989 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
7990 manager
7991 .load_session(&parent_id)
7992 .expect("saved parent")
7993 .messages
7994 .len()
7995 };
7996 app.add_message(HistoryCell::System {
7997 content: "another conversation".to_string(),
7998 });
7999 let config = codewhale_runtime::config::Config::default();
8000 {
8001 let mut bundle = app.command_contexts_with_config(Some(&config));
8002 let mut parts = bundle.parts();
8003 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8004 let forked = facet.fork_from(&parent_id).expect("explicit fork ok");
8005 assert_eq!(forked.spawn_depth, 1);
8006 assert_eq!(
8007 forked.parent_label,
8008 codewhale_engine::session_manager::truncate_id(&parent_id)
8009 );
8010 assert_eq!(forked.sync.messages.len(), 1);
8011 }
8012 assert!(matches!(
8013 app.history.as_slice(),
8014 [HistoryCell::User { content }] if content == "parent turn"
8015 ));
8016 let manager =
8017 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
8018 let reloaded = manager
8019 .load_session(&parent_id)
8020 .expect("source still loadable");
8021 assert_eq!(
8022 reloaded.messages.len(),
8023 source_len,
8024 "source history never rewritten by forking"
8025 );
8026 }
8027
8028 #[test]
8029 fn lifecycle_adapter_new_session_is_all_or_nothing_when_work_state_is_busy() {
8030 let tmpdir = TempDir::new().unwrap();
8031 let _lock = crate::test_support::lock_test_env();
8032 let _home = lifecycle_home_guard(&tmpdir);
8033 let mut app = lifecycle_test_app(&tmpdir);
8034 app.current_session_id = Some("current-session".to_string());
8035 app.api_messages_mut().push(user_message("work"));
8036 let todos = app.todos.clone();
8037 let _held = todos.try_lock().expect("hold todos lock");
8038
8039 {
8040 let mut bundle = app.command_contexts();
8041 let mut parts = bundle.parts();
8042 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8043 let err = facet
8044 .fresh_session(true, None)
8045 .expect_err("busy work state");
8046 assert!(err.contains("Work state is busy"), "{err}");
8047 }
8048 assert_eq!(app.api_messages.len(), 1);
8049 assert_eq!(app.current_session_id.as_deref(), Some("current-session"));
8050 }
8051
8052 #[test]
8053 fn lifecycle_adapter_new_session_blocks_unsent_input_without_force() {
8054 let tmpdir = TempDir::new().unwrap();
8055 let _lock = crate::test_support::lock_test_env();
8056 let _home = lifecycle_home_guard(&tmpdir);
8057 let mut app = lifecycle_test_app(&tmpdir);
8058 app.current_session_id = Some("old-session".to_string());
8059 app.input = "draft text".to_string();
8060 {
8061 let mut bundle = app.command_contexts();
8062 let mut parts = bundle.parts();
8063 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8064 let err = facet.fresh_session(false, None).expect_err("blocker text");
8065 assert!(err.contains("/new --force"), "{err}");
8066 }
8067 assert_eq!(app.input, "draft text");
8068 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
8069
8070 {
8071 let mut bundle = app.command_contexts();
8072 let mut parts = bundle.parts();
8073 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8074 let ok = facet
8075 .fresh_session(true, None)
8076 .expect("force prepares a new session");
8077 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
8078 assert_eq!(app.input, "draft text");
8079 assert_ne!(ok.sync.session_id.as_deref(), Some("old-session"));
8080 assert!(!ok.truncated_id.is_empty());
8081 assert!(ok.sync.messages.is_empty());
8082 }
8083 }
8084
8085 #[test]
8086 fn lifecycle_adapter_load_validates_shape_without_applying_state() {
8087 let tmpdir = TempDir::new().unwrap();
8088 let _lock = crate::test_support::lock_test_env();
8089 let _home = lifecycle_home_guard(&tmpdir);
8090 let mut app = lifecycle_test_app(&tmpdir);
8091 app.api_messages_mut().push(user_message("checkpoint"));
8092 let save_path = tmpdir.path().join("checkpoint.json");
8093 {
8094 let mut bundle = app.command_contexts();
8095 let mut parts = bundle.parts();
8096 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8097 facet
8098 .save_session(Some(save_path.display().to_string()))
8099 .expect("seed session file");
8100 }
8101 let before = app.api_messages.clone();
8102 {
8103 let mut bundle = app.command_contexts();
8104 let mut parts = bundle.parts();
8105 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8106 let missing = facet
8107 .load_session("does-not-exist.json")
8108 .expect_err("missing file");
8109 assert!(missing.contains("Failed to read session file"), "{missing}");
8110 let bad = tmpdir.path().join("bad.json");
8111 std::fs::write(&bad, "not json").unwrap();
8112 let parse = facet
8113 .load_session(bad.display().to_string().as_str())
8114 .expect_err("invalid json");
8115 assert!(parse.contains("Failed to parse session file"), "{parse}");
8116 let oversized = tmpdir.path().join("oversized.json");
8117 std::fs::File::create(&oversized)
8118 .unwrap()
8119 .set_len(MAX_LOAD_SESSION_BYTES + 1)
8120 .unwrap();
8121 let limit = facet
8122 .load_session(oversized.display().to_string().as_str())
8123 .expect_err("oversized file");
8124 assert!(
8125 limit.contains(&format!(
8126 "over the {MAX_LOAD_SESSION_BYTES}-byte load limit"
8127 )),
8128 "{limit}"
8129 );
8130 let resolved = facet
8131 .load_session(save_path.display().to_string().as_str())
8132 .expect("valid session resolves");
8133 assert_eq!(resolved, save_path);
8134 }
8135 assert_eq!(
8136 app.api_messages, before,
8137 "no state applied by /load delegate"
8138 );
8139 }
8140
8141 #[test]
8142 fn lifecycle_adapter_picker_archive_and_prune_behavior() {
8143 let tmpdir = TempDir::new().unwrap();
8144 let _lock = crate::test_support::lock_test_env();
8145 let _home = lifecycle_home_guard(&tmpdir);
8146 let mut app = lifecycle_test_app(&tmpdir);
8147 let before_kind = app.view_stack.top_kind();
8148 {
8149 let mut bundle = app.command_contexts();
8150 let mut parts = bundle.parts();
8151 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8152 facet.open_picker(None);
8153 facet.open_picker(Some("pick-me".to_string()));
8154 }
8155 {
8156 let mut bundle = app.command_contexts();
8157 let mut parts = bundle.parts();
8158 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8159 facet.save_session(None).expect("seed archive target");
8160 }
8161 let archived_id = app.current_session_id.clone().unwrap();
8162 {
8163 let mut bundle = app.command_contexts();
8164 let mut parts = bundle.parts();
8165 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8166 let receipt = facet.set_archived(&archived_id, true).expect("archive ok");
8167 assert_eq!(
8168 receipt.truncated_id,
8169 codewhale_engine::session_manager::truncate_id(&archived_id)
8170 );
8171 assert!(!receipt.title.is_empty());
8172 let restored = facet.set_archived(&archived_id, false).expect("restore ok");
8173 assert_eq!(restored.truncated_id, receipt.truncated_id);
8174 let pruned = facet.prune_sessions(36500).expect("prune runs");
8175 assert_eq!(pruned, 0, "no inactive session older than the window");
8176 }
8177 assert_ne!(
8178 app.view_stack.top_kind(),
8179 before_kind,
8180 "picker pushed a view"
8181 );
8182 let manager =
8183 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
8184 assert!(
8185 manager.load_session(&archived_id).is_ok(),
8186 "active session survives pruning"
8187 );
8188 }
8189
8190 #[test]
8191 fn lifecycle_adapter_tree_projections_cover_all_states() {
8192 let tmpdir = TempDir::new().unwrap();
8193 let _lock = crate::test_support::lock_test_env();
8194 let _home = lifecycle_home_guard(&tmpdir);
8195
8196 // No active session.
8197 let mut no_session_app = lifecycle_test_app(&tmpdir);
8198 {
8199 let mut bundle = no_session_app.command_contexts();
8200 let mut parts = bundle.parts();
8201 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8202 assert!(matches!(
8203 facet.tree_body().expect("tree ok"),
8204 TreeBodyProjection::NoSession
8205 ));
8206 }
8207
8208 // Active session with no messages and no saved journal.
8209 let mut empty_app = lifecycle_test_app(&tmpdir);
8210 empty_app.current_session_id = Some("empty-session".to_string());
8211 {
8212 let mut bundle = empty_app.command_contexts();
8213 let mut parts = bundle.parts();
8214 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8215 assert!(matches!(
8216 facet.tree_body().expect("tree ok"),
8217 TreeBodyProjection::EmptySession
8218 ));
8219 }
8220
8221 // Linear transcript before the journal exists.
8222 let mut linear_app = lifecycle_test_app(&tmpdir);
8223 linear_app.current_session_id = Some("linear-session".to_string());
8224 linear_app
8225 .api_messages_mut()
8226 .push(user_message("first message with a long tail"));
8227 {
8228 let mut bundle = linear_app.command_contexts();
8229 let mut parts = bundle.parts();
8230 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8231 match facet.tree_body().expect("tree ok") {
8232 TreeBodyProjection::Linear { rendered } => {
8233 assert!(rendered.contains("Active branch (linear"), "{rendered}");
8234 assert!(rendered.contains("[0]"), "{rendered}");
8235 }
8236 other => panic!("expected Linear projection, got {other:?}"),
8237 }
8238 }
8239
8240 // Journal projection once the session is saved with messages.
8241 let mut journal_app = lifecycle_test_app(&tmpdir);
8242 journal_app
8243 .api_messages_mut()
8244 .push(user_message("journaled turn"));
8245 {
8246 let mut bundle = journal_app.command_contexts();
8247 let mut parts = bundle.parts();
8248 let facet = parts.lifecycle.as_deref_mut().expect("lifecycle slot");
8249 facet.save_session(None).expect("seed journaled session");
8250 match facet.tree_body().expect("tree ok") {
8251 TreeBodyProjection::Journal { rendered } => {
8252 assert!(!rendered.is_empty());
8253 }
8254 other => panic!("expected Journal projection, got {other:?}"),
8255 }
8256 }
8257 }
8258
8259 // -------------------------------------------------------------------
8260 // FEAT-024 Phase 3: SessionControlAdapter tests (Tasks 3.2/3.4/3.6).
8261 // The bundle borrows `App` for its whole life, so each test scopes the
8262 // facet (via a bound `parts` value) and re-reads `App` only after
8263 // dropping it.
8264 // -------------------------------------------------------------------
8265
8266 fn control_test_app(tmpdir: &TempDir) -> App {
8267 lifecycle_test_app(tmpdir)
8268 }
8269
8270 fn control_home_guard(tmpdir: &TempDir) -> crate::test_support::EnvVarGuard {
8271 lifecycle_home_guard(tmpdir)
8272 }
8273
8274 fn save_control_session(tmpdir: &TempDir, id: &str) {
8275 let manager =
8276 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
8277 let mut session = codewhale_engine::session_manager::create_saved_session_with_mode(
8278 &[],
8279 "deepseek-v4-pro",
8280 tmpdir.path(),
8281 0,
8282 None,
8283 None,
8284 );
8285 session.metadata.id = id.to_string();
8286 session.metadata.title = "Control Session".to_string();
8287 manager.save_session(&session).unwrap();
8288 }
8289
8290 #[test]
8291 fn control_relay_projection_maps_authoritative_snapshot() {
8292 let tmpdir = TempDir::new().unwrap();
8293 let _lock = crate::test_support::lock_test_env();
8294 let mut app = control_test_app(&tmpdir);
8295 app.goal.objective = Some("ship the control slice".to_string());
8296 app.goal.token_budget = Some(42_000);
8297 let expected_workspace = app.workspace.display().to_string();
8298 let expected_mode = app.mode.label().to_string();
8299 let expected_model = app.model_display_label();
8300
8301 {
8302 let mut bundle = app.command_contexts();
8303 let mut parts = bundle.parts();
8304 let facet = parts.control.as_deref_mut().expect("control slot");
8305 let projection = facet.relay_projection();
8306 assert_eq!(projection.workspace, expected_workspace);
8307 assert_eq!(projection.mode, expected_mode);
8308 assert_eq!(projection.model, expected_model);
8309 assert_eq!(
8310 projection.goal_objective.as_deref(),
8311 Some("ship the control slice")
8312 );
8313 assert_eq!(projection.goal_token_budget, Some(42_000));
8314 assert_eq!(
8315 projection.compact_template.trim(),
8316 codewhale_engine::prompts::COMPACT_TEMPLATE.trim()
8317 );
8318 assert_eq!(
8319 projection.handoff_path,
8320 codewhale_engine::prompts::HANDOFF_RELATIVE_PATH
8321 );
8322 assert!(matches!(projection.todos, TodoProjection::Absent));
8323 assert!(matches!(projection.plan, PlanProjection::Absent));
8324 }
8325
8326 // Plan state held by another owner -> busy state is represented,
8327 // never a panic or lock wait.
8328 {
8329 let plan_state = app.plan_state.clone();
8330 let guard = plan_state.try_lock().unwrap();
8331 {
8332 let mut bundle = app.command_contexts();
8333 let mut parts = bundle.parts();
8334 let facet = parts.control.as_deref_mut().expect("control slot");
8335 assert!(matches!(
8336 facet.relay_projection().plan,
8337 PlanProjection::Busy
8338 ));
8339 }
8340 drop(guard);
8341 }
8342
8343 // Seeded plan sections transport the status label mapping.
8344 {
8345 let plan_state = app.plan_state.clone();
8346 let mut plan = plan_state.try_lock().unwrap();
8347 plan.update(codewhale_engine::tools::plan::UpdatePlanArgs {
8348 title: Some("Relay Plan".to_string()),
8349 plan: vec![codewhale_engine::tools::plan::PlanItemArg {
8350 step: "port the control slice".to_string(),
8351 status: codewhale_engine::tools::plan::StepStatus::InProgress,
8352 }],
8353 ..codewhale_engine::tools::plan::UpdatePlanArgs::default()
8354 });
8355 }
8356 {
8357 let mut bundle = app.command_contexts();
8358 let mut parts = bundle.parts();
8359 let facet = parts.control.as_deref_mut().expect("control slot");
8360 match facet.relay_projection().plan {
8361 PlanProjection::Sections(sections) => {
8362 assert_eq!(sections.title.as_deref(), Some("Relay Plan"));
8363 assert_eq!(sections.items.len(), 1);
8364 assert_eq!(sections.items[0].status, PlanStepStatus::InProgress);
8365 assert_eq!(sections.items[0].text, "port the control slice");
8366 }
8367 other => panic!("expected Sections plan after update, got {other:?}"),
8368 }
8369 }
8370 }
8371
8372 #[test]
8373 fn control_hosted_work_target_resolves_and_never_echoes_credentials() {
8374 let tmpdir = TempDir::new().unwrap();
8375 let _lock = crate::test_support::lock_test_env();
8376 let secret = "top-secret-token";
8377 let mut app = control_test_app(&tmpdir);
8378 init_control_git_repo(
8379 tmpdir.path(),
8380 &format!("https://hunter:{secret}@github.com/codewhale-hq/CodeWhale.git"),
8381 "main",
8382 );
8383
8384 {
8385 let mut bundle = app.command_contexts();
8386 let mut parts = bundle.parts();
8387 let facet = parts.control.as_deref_mut().expect("control slot");
8388 let target = facet.resolve_hosted_work_target().expect("target");
8389 assert_eq!(target.repo, "codewhale-hq/CodeWhale");
8390 assert_eq!(target.branch, "main");
8391 assert_eq!(
8392 target.url,
8393 "https://app.codewhale.net/work?repo=codewhale-hq%2FCodeWhale&branch=main"
8394 );
8395 assert!(!target.url.contains(secret));
8396 assert!(!target.repo.contains(secret));
8397 }
8398
8399 // Unsupported host resolves to None.
8400 init_control_git_repo(tmpdir.path(), "git@gitlab.com:acme/widgets.git", "main");
8401 {
8402 let mut bundle = app.command_contexts();
8403 let mut parts = bundle.parts();
8404 let facet = parts.control.as_deref_mut().expect("control slot");
8405 assert_eq!(facet.resolve_hosted_work_target(), None);
8406 }
8407 }
8408
8409 fn init_control_git_repo(dir: &Path, origin: &str, branch: &str) {
8410 let init = std::process::Command::new("git")
8411 .args(["init", "--quiet"])
8412 .arg(dir)
8413 .status()
8414 .expect("run git init");
8415 assert!(init.success());
8416 let set_origin = std::process::Command::new("git")
8417 .arg("-C")
8418 .arg(dir)
8419 .args(["config", "--local", "remote.origin.url", origin])
8420 .status()
8421 .expect("set origin");
8422 assert!(set_origin.success());
8423 let set_branch = std::process::Command::new("git")
8424 .arg("-C")
8425 .arg(dir)
8426 .args(["symbolic-ref", "HEAD"])
8427 .arg(format!("refs/heads/{branch}"))
8428 .status()
8429 .expect("set branch");
8430 assert!(set_branch.success());
8431 }
8432
8433 #[test]
8434 fn control_rename_session_persists_title_and_preserves_order() {
8435 let tmpdir = TempDir::new().unwrap();
8436 let _lock = crate::test_support::lock_test_env();
8437 let _home = control_home_guard(&tmpdir);
8438 save_control_session(&tmpdir, "rename-1");
8439 let mut app = control_test_app(&tmpdir);
8440 app.current_session_id = Some("rename-1".to_string());
8441 app.capture_session_fixture_source();
8442
8443 let receipt = {
8444 let mut bundle = app.command_contexts();
8445 let mut parts = bundle.parts();
8446 let facet = parts.control.as_deref_mut().expect("control slot");
8447 facet.rename_session("Brand New Title").expect("rename ok")
8448 };
8449 assert_eq!(receipt.title, "Brand New Title");
8450 assert_eq!(app.session_title.as_deref(), Some("Brand New Title"));
8451 let manager =
8452 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
8453 let reloaded = manager.load_session("rename-1").unwrap();
8454 assert_eq!(reloaded.metadata.title, "Brand New Title");
8455
8456 // The facet exposes the authoritative sanitizer while the portable
8457 // handler owns empty and length policy.
8458 let sanitized = {
8459 let mut bundle = app.command_contexts();
8460 let mut parts = bundle.parts();
8461 let facet = parts.control.as_deref_mut().expect("control slot");
8462 facet.sanitize_session_title("\u{1b}\u{7}\u{200b}")
8463 };
8464 assert!(sanitized.is_empty());
8465 assert_eq!(app.window_title, None);
8466 }
8467
8468 #[test]
8469 fn control_rename_recovers_first_snapshot_from_checkpoint() {
8470 let tmpdir = TempDir::new().unwrap();
8471 let _lock = crate::test_support::lock_test_env();
8472 let _home = control_home_guard(&tmpdir);
8473 let manager =
8474 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
8475 let mut checkpoint = codewhale_engine::session_manager::create_saved_session_with_mode(
8476 &[],
8477 "deepseek-v4-pro",
8478 tmpdir.path(),
8479 0,
8480 None,
8481 None,
8482 );
8483 checkpoint.metadata.id = "midturn-1".to_string();
8484 manager.save_checkpoint(&checkpoint).unwrap();
8485
8486 let mut app = control_test_app(&tmpdir);
8487 app.current_session_id = Some("midturn-1".to_string());
8488 app.capture_session_fixture_source();
8489 app.api_messages = std::sync::Arc::new(vec![user_message("first turn still streaming")]);
8490
8491 let receipt = {
8492 let mut bundle = app.command_contexts();
8493 let mut parts = bundle.parts();
8494 let facet = parts.control.as_deref_mut().expect("control slot");
8495 facet.rename_session("Midturn Rename").expect("rename ok")
8496 };
8497 assert_eq!(receipt.title, "Midturn Rename");
8498 assert_eq!(app.session_title.as_deref(), Some("Midturn Rename"));
8499 let persisted = manager.load_session("midturn-1").unwrap();
8500 assert_eq!(persisted.metadata.title, "Midturn Rename");
8501 assert_eq!(persisted.messages.len(), 1);
8502 }
8503
8504 #[test]
8505 fn control_rename_errors_match_the_baseline() {
8506 let tmpdir = TempDir::new().unwrap();
8507 let _lock = crate::test_support::lock_test_env();
8508 let _home = control_home_guard(&tmpdir);
8509 let mut app = control_test_app(&tmpdir);
8510 app.current_session_id = None;
8511 let err = {
8512 let mut bundle = app.command_contexts();
8513 let mut parts = bundle.parts();
8514 let facet = parts.control.as_deref_mut().expect("control slot");
8515 facet.rename_session("Anything").unwrap_err()
8516 };
8517 assert!(err.contains("No active session"));
8518 }
8519
8520 #[test]
8521 fn control_title_report_set_and_clear_preserve_semantics() {
8522 let tmpdir = TempDir::new().unwrap();
8523 let _lock = crate::test_support::lock_test_env();
8524 let _home = control_home_guard(&tmpdir);
8525 save_control_session(&tmpdir, "title-1");
8526 let mut app = control_test_app(&tmpdir);
8527 app.current_session_id = Some("title-1".to_string());
8528 app.capture_session_fixture_source();
8529
8530 // No session window title and no config default -> unset, no source.
8531 let report = {
8532 let mut bundle = app.command_contexts();
8533 let mut parts = bundle.parts();
8534 let facet = parts.control.as_deref_mut().expect("control slot");
8535 facet.title_report()
8536 };
8537 assert_eq!(report.effective, "unset");
8538 assert!(matches!(report.source, TitleSource::None));
8539
8540 // Set a window title: session name untouched, redraw requested.
8541 {
8542 let mut bundle = app.command_contexts();
8543 let mut parts = bundle.parts();
8544 let facet = parts.control.as_deref_mut().expect("control slot");
8545 facet
8546 .set_window_title("parallel-task".to_string())
8547 .expect("set ok");
8548 }
8549 assert_eq!(app.window_title.as_deref(), Some("parallel-task"));
8550 assert!(app.needs_redraw);
8551 assert_eq!(
8552 app.session_title, None,
8553 "/title never changes the session name"
8554 );
8555 let manager =
8556 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
8557 let reloaded = manager.load_session("title-1").unwrap();
8558 assert_eq!(reloaded.window_title.as_deref(), Some("parallel-task"));
8559 assert_eq!(reloaded.metadata.title, "Control Session");
8560
8561 // Control-char-only input is normalized to empty before the portable
8562 // handler applies its exact user-facing validation message.
8563 let sanitized = {
8564 let mut bundle = app.command_contexts();
8565 let mut parts = bundle.parts();
8566 let facet = parts.control.as_deref_mut().expect("control slot");
8567 facet.sanitize_session_title("\u{1b}\u{7}\u{200b}")
8568 };
8569 assert!(sanitized.is_empty());
8570
8571 // Clear removes the session-level title.
8572 {
8573 let mut bundle = app.command_contexts();
8574 let mut parts = bundle.parts();
8575 let facet = parts.control.as_deref_mut().expect("control slot");
8576 facet.clear_window_title().expect("clear ok");
8577 }
8578 assert_eq!(app.window_title, None);
8579 }
8580
8581 #[test]
8582 fn control_resume_gate_picker_and_resolution_routes() {
8583 let tmpdir = TempDir::new().unwrap();
8584 let _lock = crate::test_support::lock_test_env();
8585 let _home = control_home_guard(&tmpdir);
8586 save_control_session(&tmpdir, "resume-target-1");
8587 let mut app = control_test_app(&tmpdir);
8588
8589 // Transition gate mirrors the host state.
8590 app.is_loading = true;
8591 {
8592 let mut bundle = app.command_contexts();
8593 let mut parts = bundle.parts();
8594 let facet = parts.control.as_deref_mut().expect("control slot");
8595 assert!(facet.transition_blocked());
8596 }
8597 app.is_loading = false;
8598
8599 // Bare resume pushes the picker.
8600 assert!(app.view_stack.is_empty());
8601 {
8602 let mut bundle = app.command_contexts();
8603 let mut parts = bundle.parts();
8604 let facet = parts.control.as_deref_mut().expect("control slot");
8605 facet.open_resume_picker();
8606 }
8607 assert!(!app.view_stack.is_empty());
8608
8609 // Full id and prefix resolve to the durable session file.
8610 let by_id = {
8611 let mut bundle = app.command_contexts();
8612 let mut parts = bundle.parts();
8613 let facet = parts.control.as_deref_mut().expect("control slot");
8614 facet
8615 .resolve_resume_source("resume-target-1")
8616 .expect("resolve ok")
8617 };
8618 match by_id {
8619 ResumeSource::Session {
8620 load_path,
8621 truncated_id,
8622 title,
8623 } => {
8624 assert!(load_path.as_ref().is_some_and(|p| p.exists()));
8625 assert!(!truncated_id.is_empty());
8626 assert_eq!(title, "Control Session");
8627 }
8628 other => panic!("expected Session resolution, got {other:?}"),
8629 }
8630 let by_prefix = {
8631 let mut bundle = app.command_contexts();
8632 let mut parts = bundle.parts();
8633 let facet = parts.control.as_deref_mut().expect("control slot");
8634 facet
8635 .resolve_resume_source("resume-target")
8636 .expect("prefix ok")
8637 };
8638 assert!(matches!(by_prefix, ResumeSource::Session { .. }));
8639
8640 // A readable file resolves as the direct-file route.
8641 let export_file = tmpdir.path().join("session-export.json");
8642 std::fs::write(&export_file, "{}").unwrap();
8643 let as_file = {
8644 let mut bundle = app.command_contexts();
8645 let mut parts = bundle.parts();
8646 let facet = parts.control.as_deref_mut().expect("control slot");
8647 facet
8648 .resolve_resume_source(&export_file.display().to_string())
8649 .expect("file ok")
8650 };
8651 assert!(matches!(as_file, ResumeSource::File(_)));
8652
8653 // Unknown input resolves to NotFound with the raw value for the
8654 // handler's exact fallback message.
8655 let missing = {
8656 let mut bundle = app.command_contexts();
8657 let mut parts = bundle.parts();
8658 let facet = parts.control.as_deref_mut().expect("control slot");
8659 facet
8660 .resolve_resume_source("not-a-real-session-xyz")
8661 .expect("notfound ok")
8662 };
8663 match missing {
8664 ResumeSource::NotFound { raw, error } => {
8665 assert_eq!(raw, "not-a-real-session-xyz");
8666 assert!(!error.is_empty());
8667 }
8668 other => panic!("expected NotFound, got {other:?}"),
8669 }
8670 }
8671
8672 #[test]
8673 fn control_resume_import_rejects_unrecognized_and_applies_foreign() {
8674 let tmpdir = TempDir::new().unwrap();
8675 let _lock = crate::test_support::lock_test_env();
8676 let _home = control_home_guard(&tmpdir);
8677 let mut app = control_test_app(&tmpdir);
8678
8679 let bad_file = tmpdir.path().join("not-an-export.json");
8680 std::fs::write(&bad_file, "not session json at all").unwrap();
8681 let err = {
8682 let mut bundle = app.command_contexts();
8683 let mut parts = bundle.parts();
8684 let facet = parts.control.as_deref_mut().expect("control slot");
8685 facet.import_session_file(bad_file).unwrap_err()
8686 };
8687 assert!(err.contains("is not a recognized session export"), "{err}");
8688
8689 // A real export container round-trips through import and mutates the
8690 // active session atomically.
8691 let manager =
8692 codewhale_engine::session_manager::SessionManager::default_location().unwrap();
8693 let mut source = codewhale_engine::session_manager::create_saved_session_with_mode(
8694 &[],
8695 "deepseek-v4-pro",
8696 tmpdir.path(),
8697 0,
8698 None,
8699 None,
8700 );
8701 source.metadata.id = "foreign-source".to_string();
8702 source.metadata.title = "Foreign Name".to_string();
8703 let container = source.export_container("foreign");
8704 let json = serde_json::to_string(&container).expect("serialize container");
8705 let import_file = tmpdir.path().join("foreign-export.json");
8706 std::fs::write(&import_file, &json).unwrap();
8707
8708 // This window is on a non-default route; the import must bind to it.
8709 app.set_provider_identity_record(
8710 codewhale_runtime::config::Config::default()
8711 .resolve_provider_identity(codewhale_config::ProviderKind::Openai.as_str())
8712 .expect("captured fixture provider"),
8713 );
8714 let receipt = {
8715 let mut bundle = app.command_contexts();
8716 let mut parts = bundle.parts();
8717 let facet = parts.control.as_deref_mut().expect("control slot");
8718 facet.import_session_file(import_file).expect("import ok")
8719 };
8720 assert!(!receipt.truncated_id.is_empty());
8721 assert_eq!(receipt.entry_count, 0);
8722 assert_eq!(receipt.leaf_display, "(none)");
8723 let imported_id = app.current_session_id.clone().expect("active session");
8724 let saved = manager
8725 .load_session(&imported_id)
8726 .expect("import persisted");
8727 // Host import_foreign rebuilds the document with default metadata
8728 // (fresh id/title), matching the baseline import path exactly.
8729 assert_eq!(saved.metadata.title, "New Session");
8730 assert_ne!(saved.metadata.id, "foreign-source");
8731 assert_eq!(
8732 saved.metadata.model_provider, "openai",
8733 "an imported session runs on this window's route, not a default one"
8734 );
8735 assert!(
8736 manager
8737 .sessions_dir()
8738 .join(format!("{imported_id}.json"))
8739 .exists()
8740 );
8741 }
8742
8743 #[test]
8744 fn control_remote_state_and_routing_are_deterministic() {
8745 let tmpdir = TempDir::new().unwrap();
8746 let _lock = crate::test_support::lock_test_env();
8747 let mut app = control_test_app(&tmpdir);
8748
8749 // Off state: status line, no link, no browser open.
8750 {
8751 let mut bundle = app.command_contexts();
8752 let mut parts = bundle.parts();
8753 let facet = parts.control.as_deref_mut().expect("control slot");
8754 assert_eq!(facet.remote_status(), "Remote control: off");
8755 assert_eq!(facet.remote_link(), None);
8756 assert!(matches!(
8757 facet.remote_browser_open(),
8758 RemoteOpenOutcome::NoLink
8759 ));
8760 assert_eq!(facet.remote_stop_refusal(), None);
8761 }
8762
8763 // Start wording distinguishes the active-turn copy.
8764 app.is_loading = true;
8765 {
8766 let mut bundle = app.command_contexts();
8767 let mut parts = bundle.parts();
8768 let facet = parts.control.as_deref_mut().expect("control slot");
8769 assert!(facet.remote_start_info().connecting);
8770 }
8771 app.is_loading = false;
8772 {
8773 let mut bundle = app.command_contexts();
8774 let mut parts = bundle.parts();
8775 let facet = parts.control.as_deref_mut().expect("control slot");
8776 assert!(!facet.remote_start_info().connecting);
8777 }
8778
8779 // A live advertised link composes without spawning a browser.
8780 app.remote_control.install_live_link_for_test(
8781 "https://app.codewhale.net/session?run=run-1",
8782 Some("https://app.codewhale.net/settings"),
8783 );
8784 let link = {
8785 let mut bundle = app.command_contexts();
8786 let mut parts = bundle.parts();
8787 let facet = parts.control.as_deref_mut().expect("control slot");
8788 facet.remote_link().expect("live link")
8789 };
8790 assert_eq!(link.url, "https://app.codewhale.net/session?run=run-1");
8791 assert_eq!(
8792 link.computer_url.as_deref(),
8793 Some("https://app.codewhale.net/settings")
8794 );
8795 }
8796
8797 #[test]
8798 fn control_remote_stop_refusal_guards_active_turns() {
8799 let tmpdir = TempDir::new().unwrap();
8800 let _lock = crate::test_support::lock_test_env();
8801 let mut app = control_test_app(&tmpdir);
8802 app.remote_control
8803 .prepare_remote_control_session_journal(
8804 &tmpdir.path().join("remote-control-journal"),
8805 "control-test-target",
8806 "control-test-session",
8807 )
8808 .expect("durable remote-control journal");
8809 app.remote_control
8810 .activate_prompt("run-1", "turn-1")
8811 .unwrap();
8812 let refusal = {
8813 let mut bundle = app.command_contexts();
8814 let mut parts = bundle.parts();
8815 let facet = parts.control.as_deref_mut().expect("control slot");
8816 facet.remote_stop_refusal().expect("refusal present")
8817 };
8818 assert!(refusal.contains("active remote turn"), "{refusal}");
8819 }
8820
8821 #[test]
8822 fn control_browser_open_outcome_mapping_is_exact() {
8823 let url = "https://app.codewhale.net/session?run=run-9".to_string();
8824 assert!(matches!(
8825 map_browser_open_result(url.clone(), true),
8826 RemoteOpenOutcome::Opened { url: u } if u == url
8827 ));
8828 assert!(matches!(
8829 map_browser_open_result(url.clone(), false),
8830 RemoteOpenOutcome::LaunchFailed { url: u } if u == url
8831 ));
8832 }
8833 }
8834
8834 lines RUST