| 1 | use std::collections::BTreeMap; |
| 2 | use std::io::{self, Write}; |
| 3 | |
| 4 | use anyhow::Result; |
| 5 | use codewhale_config::hooks::ALL_HOOK_EVENTS; |
| 6 | use codewhale_config::route::ProvidersExport; |
| 7 | use codewhale_config::settings_schema::{SETTINGS_SCHEMA, SettingKind, SettingRowKind}; |
| 8 | use codewhale_execpolicy::canonical_action::CANONICAL_ACTION_ALIASES; |
| 9 | use codewhale_runtime::config_keys::{ConfigKeyHome, config_key_home}; |
| 10 | use codewhale_runtime::features::FEATURES; |
| 11 | use codewhale_telemetry::{ |
| 12 | Batch, Counters, Errors, Event, ModelCounters, NOTICE_VERSION, ProductCounters, |
| 13 | SCHEMA_VERSION as TELEMETRY_SCHEMA_VERSION, TurnWall, event::TOOL_NAMES, |
| 14 | }; |
| 15 | use serde_json::{Map, Value, json}; |
| 16 | |
| 17 | const SCHEMA_VERSION: u32 = 1; |
| 18 | |
| 19 | pub(crate) fn print() -> Result<()> { |
| 20 | let mut rendered = serde_json::to_string_pretty(&render())?; |
| 21 | rendered.push('\n'); |
| 22 | let mut stdout = io::stdout(); |
| 23 | match stdout |
| 24 | .write_all(rendered.as_bytes()) |
| 25 | .and_then(|()| stdout.flush()) |
| 26 | { |
| 27 | Err(err) if err.kind() == io::ErrorKind::BrokenPipe => Ok(()), |
| 28 | other => other.map_err(Into::into), |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | fn render() -> Value { |
| 33 | sorted(json!({ |
| 34 | "schema_version": SCHEMA_VERSION, |
| 35 | "version": env!("CODEWHALE_BUILD_VERSION"), |
| 36 | "msrv": env!("CARGO_PKG_RUST_VERSION"), |
| 37 | "cli": command_tree(&super::command_with_open_gates()), |
| 38 | "config": config(), |
| 39 | "slash_commands": codewhale_tui::docs_manifest::slash_commands(), |
| 40 | "keybindings": codewhale_tui::docs_manifest::keybindings(), |
| 41 | "hooks": hooks(), |
| 42 | "permissions": permissions(), |
| 43 | "providers": providers(), |
| 44 | "features": features(), |
| 45 | "telemetry": telemetry(), |
| 46 | })) |
| 47 | } |
| 48 | |
| 49 | fn sorted(value: Value) -> Value { |
| 50 | match value { |
| 51 | Value::Object(map) => { |
| 52 | let entries: BTreeMap<String, Value> = map.into_iter().collect(); |
| 53 | Value::Object( |
| 54 | entries |
| 55 | .into_iter() |
| 56 | .map(|(key, value)| (key, sorted(value))) |
| 57 | .collect::<Map<_, _>>(), |
| 58 | ) |
| 59 | } |
| 60 | Value::Array(items) => Value::Array(items.into_iter().map(sorted).collect()), |
| 61 | other => other, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn command_tree(command: &clap::Command) -> Value { |
| 66 | let mut args: Vec<&clap::Arg> = command |
| 67 | .get_arguments() |
| 68 | .filter(|arg| !arg.is_hide_set()) |
| 69 | .collect(); |
| 70 | args.sort_by_key(|arg| arg.get_id().as_str()); |
| 71 | let mut subcommands: Vec<&clap::Command> = command |
| 72 | .get_subcommands() |
| 73 | .filter(|subcommand| !subcommand.is_hide_set()) |
| 74 | .collect(); |
| 75 | subcommands.sort_by_key(|subcommand| subcommand.get_name()); |
| 76 | json!({ |
| 77 | "name": command.get_name(), |
| 78 | "aliases": command.get_visible_aliases().collect::<Vec<_>>(), |
| 79 | "about": command.get_about().map(ToString::to_string), |
| 80 | "args": args.into_iter().map(arg_entry).collect::<Vec<_>>(), |
| 81 | "subcommands": subcommands.into_iter().map(command_tree).collect::<Vec<_>>(), |
| 82 | }) |
| 83 | } |
| 84 | |
| 85 | fn arg_entry(arg: &clap::Arg) -> Value { |
| 86 | json!({ |
| 87 | "id": arg.get_id().as_str(), |
| 88 | "long": arg.get_long(), |
| 89 | "short": arg.get_short().map(String::from), |
| 90 | "aliases": arg.get_visible_aliases().unwrap_or_default(), |
| 91 | "value_names": arg |
| 92 | .get_value_names() |
| 93 | .map(|names| names.iter().map(ToString::to_string).collect::<Vec<_>>()) |
| 94 | .unwrap_or_default(), |
| 95 | "defaults": arg |
| 96 | .get_default_values() |
| 97 | .iter() |
| 98 | .map(|value| value.to_string_lossy().into_owned()) |
| 99 | .collect::<Vec<_>>(), |
| 100 | "possible_values": arg |
| 101 | .get_possible_values() |
| 102 | .iter() |
| 103 | .filter(|value| !value.is_hide_set()) |
| 104 | .map(|value| value.get_name().to_string()) |
| 105 | .collect::<Vec<_>>(), |
| 106 | "help": arg.get_help().map(ToString::to_string), |
| 107 | "required": arg.is_required_set(), |
| 108 | "positional": arg.is_positional(), |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | fn config() -> Value { |
| 113 | let mut settings: Vec<Value> = SETTINGS_SCHEMA |
| 114 | .iter() |
| 115 | .map(|def| { |
| 116 | let file = match config_key_home(def.key) { |
| 117 | ConfigKeyHome::ConfigToml => Some("config.toml"), |
| 118 | ConfigKeyHome::SettingsToml => Some("settings.toml"), |
| 119 | ConfigKeyHome::Unknown => None, |
| 120 | }; |
| 121 | let kind = match def.kind { |
| 122 | SettingKind::Bool(_) => "bool", |
| 123 | SettingKind::Int => "int", |
| 124 | SettingKind::Float => "float", |
| 125 | SettingKind::Enum(_) => "enum", |
| 126 | SettingKind::String => "string", |
| 127 | }; |
| 128 | let tab = def.ui.map(|u| u.tab); |
| 129 | let group = def.ui.map(|u| u.group); |
| 130 | let row_kind = def.ui.map(|u| match u.row { |
| 131 | SettingRowKind::Setting => "setting", |
| 132 | SettingRowKind::Action => "action", |
| 133 | SettingRowKind::Diagnostic => "diagnostic", |
| 134 | SettingRowKind::Session => "session", |
| 135 | }); |
| 136 | json!({ |
| 137 | "key": def.key, |
| 138 | "type": kind, |
| 139 | "default": def.default, |
| 140 | "values": def.values().unwrap_or_default(), |
| 141 | "file": file, |
| 142 | "tab": tab, |
| 143 | "group": group, |
| 144 | "row_kind": row_kind, |
| 145 | }) |
| 146 | }) |
| 147 | .collect(); |
| 148 | settings.sort_by(|a, b| a["key"].as_str().cmp(&b["key"].as_str())); |
| 149 | Value::Array(settings) |
| 150 | } |
| 151 | |
| 152 | fn hooks() -> Value { |
| 153 | ALL_HOOK_EVENTS |
| 154 | .iter() |
| 155 | .map(|event| { |
| 156 | json!({ |
| 157 | "name": event.as_str(), |
| 158 | "steering": format!("{:?}", event.steering()), |
| 159 | }) |
| 160 | }) |
| 161 | .collect() |
| 162 | } |
| 163 | |
| 164 | fn permissions() -> Value { |
| 165 | let mut tools: BTreeMap<&str, Vec<Value>> = BTreeMap::new(); |
| 166 | for &(tool, action, legacy_name) in CANONICAL_ACTION_ALIASES { |
| 167 | tools |
| 168 | .entry(tool) |
| 169 | .or_default() |
| 170 | .push(json!({ "action": action, "legacy_name": legacy_name })); |
| 171 | } |
| 172 | tools |
| 173 | .into_iter() |
| 174 | .map(|(tool, actions)| json!({ "tool": tool, "actions": actions })) |
| 175 | .collect() |
| 176 | } |
| 177 | |
| 178 | fn providers() -> Value { |
| 179 | ProvidersExport::from_registry(env!("CODEWHALE_BUILD_VERSION")) |
| 180 | .routes |
| 181 | .into_iter() |
| 182 | .map(|route| { |
| 183 | json!({ |
| 184 | "id": route.id, |
| 185 | "label": route.label, |
| 186 | "family": route.family, |
| 187 | "endpoint": route.endpoint, |
| 188 | "wire": route.wire, |
| 189 | "default_model": route.default_model, |
| 190 | "env_vars": route.env_vars, |
| 191 | }) |
| 192 | }) |
| 193 | .collect() |
| 194 | } |
| 195 | |
| 196 | fn features() -> Value { |
| 197 | let mut features: Vec<_> = FEATURES.iter().collect(); |
| 198 | features.sort_by_key(|feature| feature.key); |
| 199 | features |
| 200 | .into_iter() |
| 201 | .map(|feature| { |
| 202 | json!({ |
| 203 | "key": feature.key, |
| 204 | "stage": feature.stage.as_str(), |
| 205 | "default_enabled": feature.default_enabled, |
| 206 | }) |
| 207 | }) |
| 208 | .collect() |
| 209 | } |
| 210 | |
| 211 | fn telemetry() -> Value { |
| 212 | let mut events: Vec<Value> = Event::sample_all() |
| 213 | .into_iter() |
| 214 | .map(|event| { |
| 215 | let name = event.name(); |
| 216 | let value = serde_json::to_value(&event).expect("telemetry event serializes"); |
| 217 | let mut fields: Vec<String> = value |
| 218 | .as_object() |
| 219 | .map(|map| map.keys().cloned().collect()) |
| 220 | .unwrap_or_default(); |
| 221 | fields.sort(); |
| 222 | json!({ |
| 223 | "name": name, |
| 224 | "fields": fields, |
| 225 | }) |
| 226 | }) |
| 227 | .collect(); |
| 228 | events.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); |
| 229 | json!({ |
| 230 | "schema_version": TELEMETRY_SCHEMA_VERSION, |
| 231 | "notice_version": NOTICE_VERSION, |
| 232 | "envelope_fields": Batch::FIELDS, |
| 233 | "counters_fields": Counters::FIELDS, |
| 234 | "product_counters_fields": ProductCounters::FIELDS, |
| 235 | "model_counters_fields": ModelCounters::FIELDS, |
| 236 | "errors_fields": Errors::FIELDS, |
| 237 | "turn_wall_fields": TurnWall::FIELDS, |
| 238 | "tool_names": TOOL_NAMES, |
| 239 | "events": events, |
| 240 | }) |
| 241 | } |
| 242 | |
| 243 | #[cfg(test)] |
| 244 | mod tests { |
| 245 | use super::*; |
| 246 | |
| 247 | fn keys_sorted(value: &Value) -> bool { |
| 248 | match value { |
| 249 | Value::Object(map) => { |
| 250 | map.keys().zip(map.keys().skip(1)).all(|(a, b)| a < b) |
| 251 | && map.values().all(keys_sorted) |
| 252 | } |
| 253 | Value::Array(items) => items.iter().all(keys_sorted), |
| 254 | _ => true, |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | fn names<'a>(entries: &'a Value, field: &str) -> Vec<&'a str> { |
| 259 | entries |
| 260 | .as_array() |
| 261 | .unwrap_or_else(|| panic!("{field} section is an array")) |
| 262 | .iter() |
| 263 | .map(|entry| entry[field].as_str().expect("string name")) |
| 264 | .collect() |
| 265 | } |
| 266 | |
| 267 | fn assert_sorted(entries: &Value, field: &str) { |
| 268 | let names = names(entries, field); |
| 269 | assert!(!names.is_empty(), "no `{field}` entries"); |
| 270 | assert!( |
| 271 | names.windows(2).all(|pair| pair[0] <= pair[1]), |
| 272 | "entries not sorted by `{field}`: {names:?}" |
| 273 | ); |
| 274 | } |
| 275 | |
| 276 | #[test] |
| 277 | fn docs_manifest_is_deterministic_sorted_and_populated() { |
| 278 | let manifest = render(); |
| 279 | assert_eq!( |
| 280 | serde_json::to_string_pretty(&manifest).unwrap(), |
| 281 | serde_json::to_string_pretty(&render()).unwrap() |
| 282 | ); |
| 283 | assert!(keys_sorted(&manifest)); |
| 284 | assert_eq!(manifest["schema_version"], SCHEMA_VERSION); |
| 285 | assert_eq!(manifest["version"], env!("CODEWHALE_BUILD_VERSION")); |
| 286 | assert_eq!(manifest["msrv"], env!("CARGO_PKG_RUST_VERSION")); |
| 287 | |
| 288 | let cli = &manifest["cli"]; |
| 289 | assert_eq!(cli["name"], "codewhale"); |
| 290 | assert_sorted(&cli["subcommands"], "name"); |
| 291 | assert_sorted(&cli["args"], "id"); |
| 292 | let commands = names(&cli["subcommands"], "name"); |
| 293 | for expected in ["docs-manifest", "exec", "config", "providers"] { |
| 294 | assert!(commands.contains(&expected), "cli lacks {expected}"); |
| 295 | } |
| 296 | assert!(!commands.contains(&"workflow-tool"), "hidden commands leak"); |
| 297 | if !codewhale_account_cli::ACCOUNT_SIGN_IN_OPEN { |
| 298 | assert!(!commands.contains(&"login"), "closed login leaks"); |
| 299 | let account = cli["subcommands"] |
| 300 | .as_array() |
| 301 | .unwrap() |
| 302 | .iter() |
| 303 | .find(|entry| entry["name"] == "account") |
| 304 | .expect("account command"); |
| 305 | assert!( |
| 306 | !names(&account["subcommands"], "name").contains(&"login"), |
| 307 | "closed account login leaks" |
| 308 | ); |
| 309 | } |
| 310 | |
| 311 | let config = &manifest["config"]; |
| 312 | assert_sorted(config, "key"); |
| 313 | let theme = config |
| 314 | .as_array() |
| 315 | .unwrap() |
| 316 | .iter() |
| 317 | .find(|entry| entry["key"] == "theme") |
| 318 | .expect("theme setting"); |
| 319 | assert_eq!( |
| 320 | theme["default"], |
| 321 | codewhale_config::settings_schema::DEFAULT_TUI_THEME |
| 322 | ); |
| 323 | assert_eq!(theme["tab"], "appearance"); |
| 324 | assert_eq!(theme["group"], "display"); |
| 325 | assert_eq!(theme["row_kind"], "setting"); |
| 326 | let hidden = config |
| 327 | .as_array() |
| 328 | .unwrap() |
| 329 | .iter() |
| 330 | .find(|entry| entry["key"] == "focus_texture") |
| 331 | .expect("focus_texture setting"); |
| 332 | assert!(hidden["tab"].is_null()); |
| 333 | assert!(hidden["group"].is_null()); |
| 334 | assert!(hidden["row_kind"].is_null()); |
| 335 | for entry in config.as_array().unwrap() { |
| 336 | assert!( |
| 337 | entry["row_kind"].is_null() |
| 338 | || matches!( |
| 339 | entry["row_kind"].as_str(), |
| 340 | Some("setting" | "action" | "diagnostic" | "session") |
| 341 | ), |
| 342 | "unexpected row_kind: {entry}" |
| 343 | ); |
| 344 | assert_eq!(entry["tab"].is_null(), entry["group"].is_null()); |
| 345 | assert_eq!(entry["tab"].is_null(), entry["row_kind"].is_null()); |
| 346 | } |
| 347 | |
| 348 | let slash = &manifest["slash_commands"]; |
| 349 | assert_sorted(slash, "name"); |
| 350 | let commands = slash.as_array().unwrap(); |
| 351 | let command = |name: &str| commands.iter().find(|entry| entry["name"] == name).unwrap(); |
| 352 | assert!(names(slash, "name").contains(&"help")); |
| 353 | assert_eq!(command("view-plan")["aliases"], json!(["view_plan"])); |
| 354 | assert_eq!(command("worktree")["usage"], "/worktree"); |
| 355 | for (name, verb) in [ |
| 356 | ("fleet", "context"), |
| 357 | ("fleet", "board"), |
| 358 | ("context", "limit"), |
| 359 | ("workspace", "worktrees"), |
| 360 | ("view-plan", "edit"), |
| 361 | ] { |
| 362 | assert!( |
| 363 | command(name)["subcommands"] |
| 364 | .as_array() |
| 365 | .unwrap() |
| 366 | .contains(&json!(verb)), |
| 367 | "/{name} {verb}" |
| 368 | ); |
| 369 | } |
| 370 | assert!(!names(slash, "name").contains(&"lane"), "unlisted leaks"); |
| 371 | |
| 372 | assert!(names(&manifest["keybindings"], "id").contains(&"Help")); |
| 373 | |
| 374 | assert_eq!( |
| 375 | names(&manifest["hooks"], "name"), |
| 376 | ALL_HOOK_EVENTS.map(|event| event.as_str()) |
| 377 | ); |
| 378 | |
| 379 | let permissions = &manifest["permissions"]; |
| 380 | assert_sorted(permissions, "tool"); |
| 381 | let file = permissions |
| 382 | .as_array() |
| 383 | .unwrap() |
| 384 | .iter() |
| 385 | .find(|entry| entry["tool"] == "File") |
| 386 | .expect("File family"); |
| 387 | assert!( |
| 388 | file["actions"] |
| 389 | .as_array() |
| 390 | .unwrap() |
| 391 | .iter() |
| 392 | .any(|action| action["action"] == "read" && action["legacy_name"] == "read_file") |
| 393 | ); |
| 394 | |
| 395 | let providers = &manifest["providers"]; |
| 396 | assert_sorted(providers, "id"); |
| 397 | assert_eq!( |
| 398 | names(providers, "id"), |
| 399 | ProvidersExport::from_registry("test").route_ids() |
| 400 | ); |
| 401 | |
| 402 | let features = &manifest["features"]; |
| 403 | assert_sorted(features, "key"); |
| 404 | assert!(names(features, "key").contains(&"shell_tool")); |
| 405 | |
| 406 | let telemetry = &manifest["telemetry"]; |
| 407 | assert_eq!(telemetry["schema_version"], TELEMETRY_SCHEMA_VERSION); |
| 408 | assert_eq!(telemetry["envelope_fields"], json!(Batch::FIELDS)); |
| 409 | assert_eq!(telemetry["counters_fields"], json!(Counters::FIELDS)); |
| 410 | assert_eq!(telemetry["errors_fields"], json!(Errors::FIELDS)); |
| 411 | assert_sorted(&telemetry["events"], "name"); |
| 412 | assert_eq!( |
| 413 | telemetry["events"].as_array().unwrap().len(), |
| 414 | Event::sample_all().len() |
| 415 | ); |
| 416 | } |
| 417 | } |
| 418 |