Skip to main content

codewhale_runtime/
features.rs

1//! Feature flags and metadata for codewhale.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fmt::{self, Write as _};
5
6use serde::{Deserialize, Deserializer, Serialize, de};
7
8/// Lifecycle stage for a feature flag.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Stage {
11    Experimental,
12    Beta,
13    Stable,
14}
15
16impl Stage {
17    pub fn as_str(self) -> &'static str {
18        match self {
19            Self::Experimental => "experimental",
20            Self::Beta => "beta",
21            Self::Stable => "stable",
22        }
23    }
24}
25
26/// Unique features toggled via configuration.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub enum Feature {
29    /// Enable the default shell tool.
30    ShellTool,
31    /// Enable background sub-agent tooling.
32    Subagents,
33    /// Enable web search tool.
34    WebSearch,
35    /// Enable apply_patch tool.
36    ApplyPatch,
37    /// Enable MCP tools.
38    Mcp,
39    /// Enable execpolicy integration/tooling.
40    ExecPolicy,
41    /// Enable vision model for image analysis.
42    VisionModel,
43    /// Enable the agent-callable `verify` adversarial self-critique tool (#4196).
44    Verify,
45    /// Expose `execute_tools` eagerly so the model composes by default (CodeMode).
46    CodeMode,
47    /// Run reviewed plugins' `native` host code in the TypeScript extension
48    /// host (experimental). Toggling it changes the plugin activation policy,
49    /// so every plugin is re-reviewed after a restart, in either direction.
50    ExtensionHost,
51    /// Use the pinned TypeScript finance normalization adapter; no runtime fallback.
52    FinanceHost,
53    /// Use the pinned TypeScript data validation presenter; no runtime fallback.
54    DataHost,
55    /// Use pinned speech preparation for the CLI and tool; no runtime fallback.
56    SpeechHost,
57    /// Pinned PDF outcome orchestration; Core retains process and document bytes.
58    PdfHost,
59    /// Pinned Native/Tesseract selection; Core retains image/process authority.
60    OcrHost,
61    /// Pinned web query/provider adapters; Core retains all HTTP and policy.
62    WebSearchHost,
63    /// Pinned HTML region selection; complete document bytes stay in Core.
64    WebExtractHost,
65    /// Pinned GitHub and local report presentation; Core retains effects and disclosure.
66    GithubHost,
67    /// Captured review presentation; Core retains provider, evidence and publication.
68    ReviewHost,
69    PluginCreator,
70}
71
72impl fmt::Display for Stage {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(self.as_str())
75    }
76}
77
78/// Holds the effective set of enabled features.
79#[derive(Debug, Clone, Default, PartialEq)]
80pub struct Features {
81    enabled: BTreeSet<Feature>,
82}
83
84impl Features {
85    /// Starts with built-in defaults.
86    pub fn with_defaults() -> Self {
87        let mut set = BTreeSet::new();
88        for spec in FEATURES {
89            if spec.default_enabled {
90                set.insert(spec.id);
91            }
92        }
93        Self { enabled: set }
94    }
95
96    pub fn enabled(&self, feature: Feature) -> bool {
97        self.enabled.contains(&feature)
98    }
99
100    pub fn enable(&mut self, feature: Feature) -> &mut Self {
101        self.enabled.insert(feature);
102        self
103    }
104
105    pub fn disable(&mut self, feature: Feature) -> &mut Self {
106        self.enabled.remove(&feature);
107        self
108    }
109
110    pub fn apply_map(&mut self, entries: &BTreeMap<String, bool>) {
111        for (key, enabled) in entries {
112            if let Some(feature) = feature_from_key(key) {
113                if *enabled {
114                    self.enable(feature);
115                } else {
116                    self.disable(feature);
117                }
118            }
119        }
120    }
121}
122
123/// Keys accepted in `[features]` tables.
124pub fn is_known_feature_key(key: &str) -> bool {
125    FEATURES.iter().any(|spec| spec.key == key)
126}
127
128pub fn feature_from_key(key: &str) -> Option<Feature> {
129    FEATURES
130        .iter()
131        .find(|spec| spec.key == key)
132        .map(|spec| spec.id)
133}
134
135pub fn render_feature_table(features: &Features) -> String {
136    let mut output = String::from("feature\tstage\tenabled\n");
137    for spec in FEATURES {
138        let _ = writeln!(
139            output,
140            "{}\t{}\t{}",
141            spec.key,
142            spec.stage,
143            features.enabled(spec.id)
144        );
145    }
146    output
147}
148
149/// Deserializable features table for TOML.
150#[derive(Serialize, Debug, Clone, Default, PartialEq)]
151pub struct FeaturesToml {
152    #[serde(flatten)]
153    pub entries: BTreeMap<String, bool>,
154}
155
156impl<'de> Deserialize<'de> for FeaturesToml {
157    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
158    where
159        D: Deserializer<'de>,
160    {
161        let raw = BTreeMap::<String, toml::Value>::deserialize(deserializer)?;
162        let mut entries = BTreeMap::new();
163
164        for (key, value) in raw {
165            match value {
166                toml::Value::Boolean(enabled) => {
167                    entries.insert(key, enabled);
168                }
169                toml::Value::Table(table) if key == "enabled" => {
170                    for (feature_key, feature_value) in table {
171                        match feature_value {
172                            toml::Value::Boolean(enabled) => {
173                                entries.insert(feature_key, enabled);
174                            }
175                            other => {
176                                return Err(de::Error::custom(format!(
177                                    "features.enabled.{feature_key} must be a boolean, got {other:?}"
178                                )));
179                            }
180                        }
181                    }
182                }
183                other if is_known_feature_key(&key) => {
184                    return Err(de::Error::custom(format!(
185                        "features.{key} must be a boolean, got {other:?}"
186                    )));
187                }
188                _ => {}
189            }
190        }
191
192        Ok(Self { entries })
193    }
194}
195
196/// Single registry of all feature definitions.
197#[derive(Debug, Clone, Copy)]
198pub struct FeatureSpec {
199    pub id: Feature,
200    pub key: &'static str,
201    pub stage: Stage,
202    pub default_enabled: bool,
203}
204
205pub const FEATURES: &[FeatureSpec] = &[
206    FeatureSpec {
207        id: Feature::ShellTool,
208        key: "shell_tool",
209        stage: Stage::Stable,
210        default_enabled: true,
211    },
212    FeatureSpec {
213        id: Feature::Subagents,
214        key: "subagents",
215        stage: Stage::Stable,
216        default_enabled: true,
217    },
218    FeatureSpec {
219        id: Feature::WebSearch,
220        key: "web_search",
221        stage: Stage::Stable,
222        default_enabled: true,
223    },
224    FeatureSpec {
225        id: Feature::ApplyPatch,
226        key: "apply_patch",
227        stage: Stage::Stable,
228        default_enabled: true,
229    },
230    FeatureSpec {
231        id: Feature::Mcp,
232        key: "mcp",
233        stage: Stage::Stable,
234        default_enabled: true,
235    },
236    FeatureSpec {
237        id: Feature::ExecPolicy,
238        key: "exec_policy",
239        stage: Stage::Stable,
240        default_enabled: true,
241    },
242    FeatureSpec {
243        id: Feature::VisionModel,
244        key: "vision_model",
245        stage: Stage::Beta,
246        default_enabled: false,
247    },
248    FeatureSpec {
249        id: Feature::Verify,
250        key: "verify_tool",
251        stage: Stage::Stable,
252        default_enabled: true,
253    },
254    FeatureSpec {
255        id: Feature::CodeMode,
256        key: "code_mode",
257        // Stays listed as experimental so `/config` shows the escape hatch.
258        stage: Stage::Experimental,
259        // #6562: code mode is the default way MCP and plugin tools compose.
260        // `[features] code_mode = false` is the escape hatch: execute_tools
261        // goes back to deferred (reachable through tool_search).
262        default_enabled: true,
263    },
264    FeatureSpec {
265        id: Feature::FinanceHost,
266        key: "finance_host",
267        stage: Stage::Experimental,
268        default_enabled: false,
269    },
270    FeatureSpec {
271        id: Feature::DataHost,
272        key: "data_host",
273        stage: Stage::Experimental,
274        default_enabled: false,
275    },
276    FeatureSpec {
277        id: Feature::SpeechHost,
278        key: "speech_host",
279        stage: Stage::Experimental,
280        default_enabled: false,
281    },
282    FeatureSpec {
283        id: Feature::PdfHost,
284        key: "pdf_host",
285        stage: Stage::Experimental,
286        default_enabled: false,
287    },
288    FeatureSpec {
289        id: Feature::OcrHost,
290        key: "ocr_host",
291        stage: Stage::Experimental,
292        default_enabled: false,
293    },
294    FeatureSpec {
295        id: Feature::GithubHost,
296        key: "github_host",
297        stage: Stage::Experimental,
298        default_enabled: false,
299    },
300    FeatureSpec {
301        id: Feature::WebSearchHost,
302        key: "web_search_host",
303        stage: Stage::Experimental,
304        default_enabled: false,
305    },
306    FeatureSpec {
307        id: Feature::WebExtractHost,
308        key: "web_extract_host",
309        stage: Stage::Experimental,
310        default_enabled: false,
311    },
312    FeatureSpec {
313        id: Feature::ReviewHost,
314        key: "review_host",
315        stage: Stage::Experimental,
316        default_enabled: false,
317    },
318    FeatureSpec {
319        id: Feature::ExtensionHost,
320        key: "extension_host",
321        stage: Stage::Experimental,
322        default_enabled: false,
323    },
324    FeatureSpec {
325        id: Feature::PluginCreator,
326        key: "plugin_creator",
327        stage: Stage::Beta,
328        default_enabled: true,
329    },
330];
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn apply_map_toggles_known_features_and_ignores_unknown_keys() {
338        let mut features = Features::with_defaults();
339        let entries = BTreeMap::from([
340            ("mcp".to_string(), false),
341            ("shell_tool".to_string(), false),
342            ("not_real".to_string(), false),
343        ]);
344
345        features.apply_map(&entries);
346
347        assert!(!features.enabled(Feature::Mcp));
348        assert!(!features.enabled(Feature::ShellTool));
349        assert_eq!(feature_from_key("not_real"), None);
350    }
351
352    #[test]
353    fn code_mode_flag_parses_and_defaults_on_with_an_off_switch() {
354        assert_eq!(feature_from_key("code_mode"), Some(Feature::CodeMode));
355        let mut features = Features::with_defaults();
356        assert!(features.enabled(Feature::CodeMode));
357        features.apply_map(&BTreeMap::from([("code_mode".to_string(), false)]));
358        assert!(!features.enabled(Feature::CodeMode));
359    }
360
361    #[test]
362    fn extension_host_flag_parses_and_defaults_off() {
363        assert_eq!(
364            feature_from_key("extension_host"),
365            Some(Feature::ExtensionHost)
366        );
367        assert!(!Features::with_defaults().enabled(Feature::ExtensionHost));
368    }
369
370    #[test]
371    fn render_feature_table_uses_registry_order_and_effective_state() {
372        let mut features = Features::with_defaults();
373        features.disable(Feature::Mcp);
374
375        let table = render_feature_table(&features);
376        let lines = table.lines().collect::<Vec<_>>();
377
378        assert_eq!(lines.first(), Some(&"feature\tstage\tenabled"));
379        assert!(lines.contains(&"shell_tool\tstable\ttrue"));
380        assert!(lines.contains(&"mcp\tstable\tfalse"));
381    }
382}