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