Skip to main content

codewhale_command_contract/
handler.rs

1//! Generic handler transport for staged command migration.
2//!
3//! The output type is generic so FEAT-014 does not move or duplicate the
4//! TUI-owned `CommandResult`. During in-place adoption, the TUI instantiates
5//! `CommandHandler<crate::commands::CommandResult>`.
6
7use crate::facets::{
8    CommandConfigStatusContext, CommandCostContext, CommandDebugChangeContext,
9    CommandDebugDiagnosticsContext, CommandDebugDiffContext, CommandDebugHistoryContext,
10    CommandDebugReceiptsContext, CommandDebugUndoContext, CommandMediaContext,
11    CommandMemoryContext, CommandModePolicyContext, CommandModelContext, CommandPermissionsContext,
12    CommandPluginContext, CommandPresentationContext, CommandProjectContext, CommandSessionContext,
13    CommandSessionControlContext, CommandSessionExportContext, CommandSessionLifecycleContext,
14    CommandSessionStructcopyContext, CommandSkillGroupContext, CommandSkillsContext,
15    CommandSystemPromptContext, CommandWorkspaceContext,
16};
17
18/// Exact host capabilities exposed to one contextual command handler.
19///
20/// The set lives in the external contract crate so command registrations can
21/// declare least authority without naming the TUI host. The dispatcher uses
22/// the declaration to populate only those slots in [`CommandContexts`].
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub struct CommandCapabilities(u32);
25
26impl CommandCapabilities {
27    pub const NONE: Self = Self(0);
28    pub const SESSION: Self = Self(1 << 0);
29    pub const MODEL: Self = Self(1 << 1);
30    pub const COST: Self = Self(1 << 2);
31    pub const MODE_POLICY: Self = Self(1 << 3);
32    pub const SYSTEM_PROMPT: Self = Self(1 << 4);
33    pub const SKILLS: Self = Self(1 << 5);
34    pub const WORKSPACE: Self = Self(1 << 6);
35    pub const PRESENTATION: Self = Self(1 << 7);
36    pub const MEDIA: Self = Self(1 << 8);
37    /// Memory-group host data (FEAT-019 D1).
38    pub const MEMORY: Self = Self(1 << 9);
39    /// Project-group host data (FEAT-021 D1).
40    pub const PROJECT: Self = Self(1 << 10);
41    /// Skills-group host data (FEAT-022 D1).
42    pub const SKILL_GROUP: Self = Self(1 << 11);
43    /// Plugin-group host data (FEAT-020 D1), appended after current main capabilities.
44    pub const PLUGIN: Self = Self(1 << 12);
45    /// Session-lifecycle host data (FEAT-023 D3), the next non-conflicting bit
46    /// after `PLUGIN`. Required only by the seven host-dependent lifecycle
47    /// commands; `/compact` and `/purge` remain pure. Never widened by the
48    /// basic session capability.
49    pub const SESSION_LIFECYCLE: Self = Self(1 << 13);
50    /// Session-control host data (FEAT-024 D3), the next non-conflicting bit
51    /// after `SESSION_LIFECYCLE`. Required only by the six host-dependent
52    /// control commands (`/relay`, `/rename`, `/resume`, `/rc`, `/remote-env`,
53    /// `/title`); `/remote-env` also declares `PRESENTATION`. Bit 14 fit the
54    /// original `u16` backing without speculative widening in FEAT-023.
55    pub const SESSION_CONTROL: Self = Self(1 << 14);
56    /// Session-export host data (FEAT-025 D1), the next non-conflicting bit
57    /// after `SESSION_CONTROL`. Required only by the host-dependent `/export`
58    /// command (and its `/daochu` alias) and by `/share`, which publishes the
59    /// same redacted projection; every concrete App, snapshot, clipboard,
60    /// filesystem, history, and turn-handoff access stays behind the TUI export
61    /// adapter.
62    ///
63    /// This filled the original 16-bit space. FEAT-029 widened the backing
64    /// storage before allocating the next independent diagnostics authority;
65    /// the published identity of this bit remains unchanged.
66    pub const SESSION_EXPORT: Self = Self(1 << 15);
67    /// Debug diagnostics host data (FEAT-029 D3/D4). This is the first bit in
68    /// the widened backing storage; other debug commands retain their own independent
69    /// authority and do not borrow this facet.
70    pub const DEBUG_DIAGNOSTICS: Self = Self(1 << 16);
71
72    /// Debug receipts authority; independent from diagnostics and other debug operations.
73    pub const DEBUG_RECEIPTS: Self = Self(1 << 17);
74    /// Debug change authority; independent from diagnostics and other debug operations.
75    pub const DEBUG_CHANGE: Self = Self(1 << 18);
76    /// Debug history authority; independent from diagnostics and other debug operations.
77    pub const DEBUG_HISTORY: Self = Self(1 << 19);
78    /// Debug diff authority; independent from diagnostics and other debug operations.
79    pub const DEBUG_DIFF: Self = Self(1 << 20);
80    /// Debug undo authority; independent from diagnostics and other debug operations.
81    pub const DEBUG_UNDO: Self = Self(1 << 21);
82
83    /// One human-selected structural copy; independent from export/recovery.
84    pub const SESSION_STRUCTCOPY: Self = Self(1 << 22);
85    /// Permission observations and token-checked removal, independent of status.
86    pub const PERMISSIONS: Self = Self(1 << 23);
87    /// Read-only status observations, with no permission mutation authority.
88    pub const CONFIG_STATUS: Self = Self(1 << 24);
89
90    /// Raw bit pattern, for tests that pin the capability-space capacity.
91    ///
92    /// Kept `#[cfg(test)]` so the `u32` backing stays an implementation detail
93    /// and nothing can widen it accidentally through a public accessor.
94    #[cfg(test)]
95    pub(crate) const fn bits_for_test(self) -> u32 {
96        self.0
97    }
98
99    pub const fn union(self, other: Self) -> Self {
100        Self(self.0 | other.0)
101    }
102
103    pub const fn contains(self, capability: Self) -> bool {
104        !capability.is_empty() && self.0 & capability.0 == capability.0
105    }
106
107    pub const fn is_empty(self) -> bool {
108        self.0 == 0
109    }
110}
111
112impl std::ops::BitOr for CommandCapabilities {
113    type Output = Self;
114
115    fn bitor(self, rhs: Self) -> Self::Output {
116        self.union(rhs)
117    }
118}
119
120/// A command handler that is either argument-only or capability-scoped.
121#[derive(Clone, Copy)]
122pub enum CommandHandler<R> {
123    Pure(fn(Option<&str>) -> R),
124    Contextual {
125        capabilities: CommandCapabilities,
126        handler: fn(CommandContexts<'_>, Option<&str>) -> R,
127    },
128}
129
130/// Transport envelope with one independently optional facet slot.
131pub struct CommandContexts<'a> {
132    session: Option<&'a mut dyn CommandSessionContext>,
133    model: Option<&'a mut dyn CommandModelContext>,
134    cost: Option<&'a mut dyn CommandCostContext>,
135    mode_policy: Option<&'a mut dyn CommandModePolicyContext>,
136    system_prompt: Option<&'a mut dyn CommandSystemPromptContext>,
137    skills: Option<&'a mut dyn CommandSkillsContext>,
138    workspace: Option<&'a mut dyn CommandWorkspaceContext>,
139    presentation: Option<&'a mut dyn CommandPresentationContext>,
140    media: Option<&'a mut dyn CommandMediaContext>,
141    memory: Option<&'a mut dyn CommandMemoryContext>,
142    project: Option<&'a mut dyn CommandProjectContext>,
143    skill_group: Option<&'a mut dyn CommandSkillGroupContext>,
144    plugin: Option<&'a mut dyn CommandPluginContext>,
145    lifecycle: Option<&'a mut dyn CommandSessionLifecycleContext>,
146    control: Option<&'a mut dyn CommandSessionControlContext>,
147    export: Option<&'a mut dyn CommandSessionExportContext>,
148    structcopy: Option<&'a mut dyn CommandSessionStructcopyContext>,
149    debug_receipts: Option<&'a mut dyn CommandDebugReceiptsContext>,
150    debug_change: Option<&'a mut dyn CommandDebugChangeContext>,
151    debug_history: Option<&'a mut dyn CommandDebugHistoryContext>,
152    debug_diff: Option<&'a mut dyn CommandDebugDiffContext>,
153    debug_undo: Option<&'a mut dyn CommandDebugUndoContext>,
154    debug_diagnostics: Option<&'a mut dyn CommandDebugDiagnosticsContext>,
155    permissions: Option<&'a mut dyn CommandPermissionsContext>,
156    config_status: Option<&'a mut dyn CommandConfigStatusContext>,
157}
158
159/// Consumed envelope used when one handler needs several independent facets.
160pub struct ContextParts<'a> {
161    pub session: Option<&'a mut dyn CommandSessionContext>,
162    pub model: Option<&'a mut dyn CommandModelContext>,
163    pub cost: Option<&'a mut dyn CommandCostContext>,
164    pub mode_policy: Option<&'a mut dyn CommandModePolicyContext>,
165    pub system_prompt: Option<&'a mut dyn CommandSystemPromptContext>,
166    pub skills: Option<&'a mut dyn CommandSkillsContext>,
167    pub workspace: Option<&'a mut dyn CommandWorkspaceContext>,
168    pub presentation: Option<&'a mut dyn CommandPresentationContext>,
169    pub media: Option<&'a mut dyn CommandMediaContext>,
170    pub memory: Option<&'a mut dyn CommandMemoryContext>,
171    pub project: Option<&'a mut dyn CommandProjectContext>,
172    pub skill_group: Option<&'a mut dyn CommandSkillGroupContext>,
173    pub plugin: Option<&'a mut dyn CommandPluginContext>,
174    pub lifecycle: Option<&'a mut dyn CommandSessionLifecycleContext>,
175    pub control: Option<&'a mut dyn CommandSessionControlContext>,
176    pub export: Option<&'a mut dyn CommandSessionExportContext>,
177    pub structcopy: Option<&'a mut dyn CommandSessionStructcopyContext>,
178    pub debug_receipts: Option<&'a mut dyn CommandDebugReceiptsContext>,
179    pub debug_change: Option<&'a mut dyn CommandDebugChangeContext>,
180    pub debug_history: Option<&'a mut dyn CommandDebugHistoryContext>,
181    pub debug_diff: Option<&'a mut dyn CommandDebugDiffContext>,
182    pub debug_undo: Option<&'a mut dyn CommandDebugUndoContext>,
183    pub debug_diagnostics: Option<&'a mut dyn CommandDebugDiagnosticsContext>,
184    pub permissions: Option<&'a mut dyn CommandPermissionsContext>,
185    pub config_status: Option<&'a mut dyn CommandConfigStatusContext>,
186}
187
188impl<'a> CommandContexts<'a> {
189    pub fn empty() -> Self {
190        Self {
191            session: None,
192            model: None,
193            cost: None,
194            mode_policy: None,
195            system_prompt: None,
196            skills: None,
197            workspace: None,
198            presentation: None,
199            media: None,
200            memory: None,
201            project: None,
202            skill_group: None,
203            plugin: None,
204            lifecycle: None,
205            control: None,
206            export: None,
207            structcopy: None,
208            debug_receipts: None,
209            debug_change: None,
210            debug_history: None,
211            debug_diff: None,
212            debug_undo: None,
213            debug_diagnostics: None,
214            permissions: None,
215            config_status: None,
216        }
217    }
218
219    pub fn into_parts(self) -> ContextParts<'a> {
220        ContextParts {
221            session: self.session,
222            model: self.model,
223            cost: self.cost,
224            mode_policy: self.mode_policy,
225            system_prompt: self.system_prompt,
226            skills: self.skills,
227            workspace: self.workspace,
228            presentation: self.presentation,
229            media: self.media,
230            memory: self.memory,
231            project: self.project,
232            skill_group: self.skill_group,
233            plugin: self.plugin,
234            lifecycle: self.lifecycle,
235            control: self.control,
236            export: self.export,
237            structcopy: self.structcopy,
238            debug_receipts: self.debug_receipts,
239            debug_change: self.debug_change,
240            debug_history: self.debug_history,
241            debug_diff: self.debug_diff,
242            debug_undo: self.debug_undo,
243            debug_diagnostics: self.debug_diagnostics,
244            permissions: self.permissions,
245            config_status: self.config_status,
246        }
247    }
248
249    pub fn with_permissions(mut self, value: &'a mut dyn CommandPermissionsContext) -> Self {
250        assert!(
251            self.permissions.replace(value).is_none(),
252            "permissions facet already set"
253        );
254        self
255    }
256    pub fn with_config_status(mut self, value: &'a mut dyn CommandConfigStatusContext) -> Self {
257        assert!(
258            self.config_status.replace(value).is_none(),
259            "config status facet already set"
260        );
261        self
262    }
263
264    pub fn with_session(mut self, value: &'a mut dyn CommandSessionContext) -> Self {
265        assert!(
266            self.session.replace(value).is_none(),
267            "session facet already set"
268        );
269        self
270    }
271
272    pub fn with_model(mut self, value: &'a mut dyn CommandModelContext) -> Self {
273        assert!(
274            self.model.replace(value).is_none(),
275            "model facet already set"
276        );
277        self
278    }
279
280    pub fn with_cost(mut self, value: &'a mut dyn CommandCostContext) -> Self {
281        assert!(self.cost.replace(value).is_none(), "cost facet already set");
282        self
283    }
284
285    pub fn with_mode_policy(mut self, value: &'a mut dyn CommandModePolicyContext) -> Self {
286        assert!(
287            self.mode_policy.replace(value).is_none(),
288            "mode-policy facet already set"
289        );
290        self
291    }
292
293    pub fn with_system_prompt(mut self, value: &'a mut dyn CommandSystemPromptContext) -> Self {
294        assert!(
295            self.system_prompt.replace(value).is_none(),
296            "system-prompt facet already set"
297        );
298        self
299    }
300
301    pub fn with_skills(mut self, value: &'a mut dyn CommandSkillsContext) -> Self {
302        assert!(
303            self.skills.replace(value).is_none(),
304            "skills facet already set"
305        );
306        self
307    }
308
309    pub fn with_workspace(mut self, value: &'a mut dyn CommandWorkspaceContext) -> Self {
310        assert!(
311            self.workspace.replace(value).is_none(),
312            "workspace facet already set"
313        );
314        self
315    }
316
317    pub fn with_presentation(mut self, value: &'a mut dyn CommandPresentationContext) -> Self {
318        assert!(
319            self.presentation.replace(value).is_none(),
320            "presentation facet already set"
321        );
322        self
323    }
324
325    pub fn with_media(mut self, value: &'a mut dyn CommandMediaContext) -> Self {
326        assert!(
327            self.media.replace(value).is_none(),
328            "media facet already set"
329        );
330        self
331    }
332
333    pub fn with_memory(mut self, value: &'a mut dyn CommandMemoryContext) -> Self {
334        assert!(
335            self.memory.replace(value).is_none(),
336            "memory facet already set"
337        );
338        self
339    }
340
341    pub fn with_project(mut self, value: &'a mut dyn CommandProjectContext) -> Self {
342        assert!(
343            self.project.replace(value).is_none(),
344            "project facet already set"
345        );
346        self
347    }
348
349    pub fn with_skill_group(mut self, value: &'a mut dyn CommandSkillGroupContext) -> Self {
350        assert!(
351            self.skill_group.replace(value).is_none(),
352            "skill-group facet already set"
353        );
354        self
355    }
356
357    pub fn with_plugin(mut self, value: &'a mut dyn CommandPluginContext) -> Self {
358        assert!(
359            self.plugin.replace(value).is_none(),
360            "plugin facet already set"
361        );
362        self
363    }
364
365    pub fn with_lifecycle(mut self, value: &'a mut dyn CommandSessionLifecycleContext) -> Self {
366        assert!(
367            self.lifecycle.replace(value).is_none(),
368            "lifecycle facet already set"
369        );
370        self
371    }
372
373    pub fn with_control(mut self, value: &'a mut dyn CommandSessionControlContext) -> Self {
374        assert!(
375            self.control.replace(value).is_none(),
376            "control facet already set"
377        );
378        self
379    }
380
381    pub fn with_structcopy(mut self, value: &'a mut dyn CommandSessionStructcopyContext) -> Self {
382        assert!(
383            self.structcopy.replace(value).is_none(),
384            "structcopy facet already set"
385        );
386        self
387    }
388
389    pub fn with_export(mut self, value: &'a mut dyn CommandSessionExportContext) -> Self {
390        assert!(
391            self.export.replace(value).is_none(),
392            "export facet already set"
393        );
394        self
395    }
396
397    pub fn with_debug_receipts(mut self, value: &'a mut dyn CommandDebugReceiptsContext) -> Self {
398        assert!(
399            self.debug_receipts.replace(value).is_none(),
400            "debug_receipts facet already set"
401        );
402        self
403    }
404
405    pub fn with_debug_change(mut self, value: &'a mut dyn CommandDebugChangeContext) -> Self {
406        assert!(
407            self.debug_change.replace(value).is_none(),
408            "debug_change facet already set"
409        );
410        self
411    }
412
413    pub fn with_debug_history(mut self, value: &'a mut dyn CommandDebugHistoryContext) -> Self {
414        assert!(
415            self.debug_history.replace(value).is_none(),
416            "debug_history facet already set"
417        );
418        self
419    }
420
421    pub fn with_debug_diff(mut self, value: &'a mut dyn CommandDebugDiffContext) -> Self {
422        assert!(
423            self.debug_diff.replace(value).is_none(),
424            "debug_diff facet already set"
425        );
426        self
427    }
428
429    pub fn with_debug_undo(mut self, value: &'a mut dyn CommandDebugUndoContext) -> Self {
430        assert!(
431            self.debug_undo.replace(value).is_none(),
432            "debug_undo facet already set"
433        );
434        self
435    }
436
437    pub fn with_debug_diagnostics(
438        mut self,
439        value: &'a mut dyn CommandDebugDiagnosticsContext,
440    ) -> Self {
441        assert!(
442            self.debug_diagnostics.replace(value).is_none(),
443            "debug diagnostics facet already set"
444        );
445        self
446    }
447}
448
449impl Default for CommandContexts<'_> {
450    fn default() -> Self {
451        Self::empty()
452    }
453}