| 1 | #[path = "../src/codegen/mod.rs"] |
| 2 | mod codegen; |
| 3 | |
| 4 | use codewhale_app_server_protocol::methods::{ |
| 5 | self, ClientNotificationMethod, ClientRequestMethod, Disposition, ServerNotificationMethod, |
| 6 | ServerRequestMethod, Tier, error_code, |
| 7 | }; |
| 8 | use codewhale_app_server_protocol::rpc::RpcCall; |
| 9 | use codewhale_app_server_protocol::v2; |
| 10 | use serde_json::{Map, Value, json}; |
| 11 | use std::collections::{BTreeMap, BTreeSet}; |
| 12 | |
| 13 | const MANIFEST: &str = include_str!("../contract/codex-v2.json"); |
| 14 | const PINNED: &str = include_str!("pinned/codex/codex_app_server_protocol.schemas.json"); |
| 15 | const COMMON: &str = include_str!("pinned/codex/common.rs"); |
| 16 | |
| 17 | fn manifest() -> Value { |
| 18 | serde_json::from_str(MANIFEST).unwrap() |
| 19 | } |
| 20 | |
| 21 | fn pinned() -> Value { |
| 22 | serde_json::from_str(PINNED).unwrap() |
| 23 | } |
| 24 | |
| 25 | #[test] |
| 26 | fn generated_outputs_have_not_drifted_from_the_manifest_and_pinned_export() { |
| 27 | let package = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); |
| 28 | let read = |path: &str| std::fs::read_to_string(package.join(path)).unwrap(); |
| 29 | assert_eq!(read(codegen::MANIFEST_PATH), MANIFEST); |
| 30 | assert_eq!(read(codegen::PINNED_SCHEMA_PATH), PINNED); |
| 31 | let outputs = codegen::generate(MANIFEST, PINNED).unwrap(); |
| 32 | let committed: BTreeMap<&str, &str> = BTreeMap::from([ |
| 33 | ("src/methods.rs", include_str!("../src/methods.rs")), |
| 34 | ("src/v2.rs", include_str!("../src/v2.rs")), |
| 35 | ("METHODS.md", include_str!("../METHODS.md")), |
| 36 | ( |
| 37 | "schema/json/codex-v2.schema.json", |
| 38 | include_str!("../schema/json/codex-v2.schema.json"), |
| 39 | ), |
| 40 | ( |
| 41 | "schema/typescript/codex-v2.d.ts", |
| 42 | include_str!("../schema/typescript/codex-v2.d.ts"), |
| 43 | ), |
| 44 | ]); |
| 45 | assert_eq!(outputs.files.len(), committed.len()); |
| 46 | for (path, text) in outputs.files { |
| 47 | assert!( |
| 48 | committed[path] == text, |
| 49 | "{path} drifted; run cargo run -p codewhale-app-server-protocol --bin codewhale-codex-contract -- --write" |
| 50 | ); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | const KINDS: [(&str, &str, &str); 4] = [ |
| 55 | ( |
| 56 | "clientRequests", |
| 57 | include_str!("pinned/codex/ClientRequest.ts"), |
| 58 | "ClientRequest", |
| 59 | ), |
| 60 | ( |
| 61 | "clientNotifications", |
| 62 | include_str!("pinned/codex/ClientNotification.ts"), |
| 63 | "ClientNotification", |
| 64 | ), |
| 65 | ( |
| 66 | "serverRequests", |
| 67 | include_str!("pinned/codex/ServerRequest.ts"), |
| 68 | "ServerRequest", |
| 69 | ), |
| 70 | ( |
| 71 | "serverNotifications", |
| 72 | include_str!("pinned/codex/ServerNotification.ts"), |
| 73 | "ServerNotification", |
| 74 | ), |
| 75 | ]; |
| 76 | |
| 77 | fn pinned_ts_methods(source: &str) -> Vec<&str> { |
| 78 | source |
| 79 | .split("\"method\": \"") |
| 80 | .skip(1) |
| 81 | .map(|rest| rest.split('"').next().unwrap()) |
| 82 | .collect() |
| 83 | } |
| 84 | |
| 85 | fn typed(kind: &str) -> Vec<(&'static str, Tier)> { |
| 86 | match kind { |
| 87 | "clientRequests" => ClientRequestMethod::ALL |
| 88 | .iter() |
| 89 | .map(|method| (method.method(), method.tier())) |
| 90 | .collect(), |
| 91 | "clientNotifications" => ClientNotificationMethod::ALL |
| 92 | .iter() |
| 93 | .map(|method| (method.method(), method.tier())) |
| 94 | .collect(), |
| 95 | "serverRequests" => ServerRequestMethod::ALL |
| 96 | .iter() |
| 97 | .map(|method| (method.method(), method.tier())) |
| 98 | .collect(), |
| 99 | _ => ServerNotificationMethod::ALL |
| 100 | .iter() |
| 101 | .map(|method| (method.method(), method.tier())) |
| 102 | .collect(), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | fn disposition(kind: &str, method: &str) -> Option<Disposition> { |
| 107 | match kind { |
| 108 | "clientRequests" => methods::client_request_disposition(method), |
| 109 | "clientNotifications" => methods::client_notification_disposition(method), |
| 110 | "serverRequests" => methods::server_request_disposition(method), |
| 111 | _ => methods::server_notification_disposition(method), |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn upstream_response(method: &str) -> String { |
| 116 | let marker = format!("=> \"{method}\" {{"); |
| 117 | let start = COMMON |
| 118 | .find(&marker) |
| 119 | .unwrap_or_else(|| panic!("pinned common.rs has no {method}")); |
| 120 | let rest = &COMMON[start..]; |
| 121 | let end = rest.find("\n },").unwrap(); |
| 122 | let body = &rest[..end]; |
| 123 | let response = body |
| 124 | .split("response: ") |
| 125 | .nth(1) |
| 126 | .unwrap_or_else(|| panic!("{method} has no response in common.rs")); |
| 127 | let ty = response.split(',').next().unwrap().trim(); |
| 128 | ty.rsplit("::").next().unwrap().to_owned() |
| 129 | } |
| 130 | |
| 131 | fn pinned_union_params(pinned: &Value, union: &str, method: &str) -> Option<String> { |
| 132 | pinned["definitions"][union]["oneOf"] |
| 133 | .as_array() |
| 134 | .unwrap() |
| 135 | .iter() |
| 136 | .find(|variant| variant["properties"]["method"]["enum"][0] == method) |
| 137 | .unwrap_or_else(|| panic!("pinned {union} has no {method}"))["properties"]["params"]["$ref"] |
| 138 | .as_str() |
| 139 | .map(|reference| reference.rsplit('/').next().unwrap().to_owned()) |
| 140 | } |
| 141 | |
| 142 | #[test] |
| 143 | fn manifest_inventory_matches_the_pinned_method_sets_and_typed_enums() { |
| 144 | let manifest = manifest(); |
| 145 | let pinned = pinned(); |
| 146 | let mut totals: BTreeMap<String, usize> = BTreeMap::new(); |
| 147 | for (kind, ts, union) in KINDS { |
| 148 | let pinned_methods = pinned_ts_methods(ts); |
| 149 | let pinned_set: BTreeSet<&str> = pinned_methods.iter().copied().collect(); |
| 150 | assert_eq!(pinned_methods.len(), pinned_set.len(), "{kind}: duplicate"); |
| 151 | let rows = manifest["methods"][kind].as_array().unwrap(); |
| 152 | let mut seen = BTreeSet::new(); |
| 153 | for row in rows { |
| 154 | let method = row["method"].as_str().unwrap(); |
| 155 | let tier = row["tier"].as_str().unwrap(); |
| 156 | let status = row["status"].as_str().unwrap(); |
| 157 | assert!(seen.insert(method), "{kind}: {method} twice"); |
| 158 | assert!(pinned_set.contains(method), "{kind}: {method} not pinned"); |
| 159 | assert!(matches!(tier, "A" | "B" | "C" | "undecided")); |
| 160 | assert!(matches!( |
| 161 | status, |
| 162 | "implemented" | "partial" | "missing" | "method-not-found" | "never-sent" |
| 163 | )); |
| 164 | assert_eq!( |
| 165 | tier == "C", |
| 166 | matches!(status, "method-not-found" | "never-sent"), |
| 167 | "{kind}: {method} status {status} does not fit tier {tier}" |
| 168 | ); |
| 169 | assert_eq!( |
| 170 | row.get("recommended").is_some(), |
| 171 | tier == "undecided", |
| 172 | "{kind}: {method} recommendation belongs to undecided rows only" |
| 173 | ); |
| 174 | let expected = match tier { |
| 175 | "A" => Disposition::Selected(Tier::A), |
| 176 | "B" => Disposition::Selected(Tier::B), |
| 177 | "C" => Disposition::C, |
| 178 | _ => Disposition::Undecided, |
| 179 | }; |
| 180 | assert_eq!( |
| 181 | disposition(kind, method), |
| 182 | Some(expected), |
| 183 | "{kind}: {method}" |
| 184 | ); |
| 185 | *totals.entry(format!("{kind}/{tier}")).or_default() += 1; |
| 186 | if matches!(tier, "A" | "B") { |
| 187 | let params = pinned_union_params(&pinned, union, method); |
| 188 | assert_eq!( |
| 189 | row["params"].as_str().map(str::to_owned), |
| 190 | params, |
| 191 | "{kind}: {method} params disagree with the pinned {union} union" |
| 192 | ); |
| 193 | if matches!(kind, "clientRequests" | "serverRequests") { |
| 194 | assert_eq!( |
| 195 | row["response"].as_str().unwrap(), |
| 196 | upstream_response(method), |
| 197 | "{kind}: {method} result disagrees with pinned common.rs" |
| 198 | ); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | assert_eq!( |
| 203 | seen, pinned_set, |
| 204 | "{kind}: manifest and pinned export differ" |
| 205 | ); |
| 206 | let typed_set: BTreeSet<&str> = typed(kind).iter().map(|(method, _)| *method).collect(); |
| 207 | let selected: BTreeSet<&str> = rows |
| 208 | .iter() |
| 209 | .filter(|row| matches!(row["tier"].as_str(), Some("A" | "B"))) |
| 210 | .map(|row| row["method"].as_str().unwrap()) |
| 211 | .collect(); |
| 212 | assert_eq!( |
| 213 | typed_set, selected, |
| 214 | "{kind}: typed enum and selected rows differ" |
| 215 | ); |
| 216 | } |
| 217 | eprintln!("inventory totals: {totals:?}"); |
| 218 | assert_eq!(totals["clientRequests/A"] + totals["clientRequests/B"], 44); |
| 219 | assert_eq!(totals["serverRequests/A"], 5); |
| 220 | assert_eq!( |
| 221 | totals["serverNotifications/A"] + totals["serverNotifications/B"], |
| 222 | 33 |
| 223 | ); |
| 224 | } |
| 225 | |
| 226 | #[test] |
| 227 | fn typed_methods_round_trip_their_wire_names() { |
| 228 | for method in ClientRequestMethod::ALL { |
| 229 | assert_eq!( |
| 230 | ClientRequestMethod::from_method(method.method()), |
| 231 | Some(*method) |
| 232 | ); |
| 233 | let wire = serde_json::to_value(method).unwrap(); |
| 234 | assert_eq!(wire, method.method()); |
| 235 | assert_eq!( |
| 236 | serde_json::from_value::<ClientRequestMethod>(wire).unwrap(), |
| 237 | *method |
| 238 | ); |
| 239 | } |
| 240 | for method in ServerNotificationMethod::ALL { |
| 241 | assert_eq!( |
| 242 | ServerNotificationMethod::from_method(method.method()), |
| 243 | Some(*method) |
| 244 | ); |
| 245 | } |
| 246 | for method in ServerRequestMethod::ALL { |
| 247 | assert_eq!( |
| 248 | ServerRequestMethod::from_method(method.method()), |
| 249 | Some(*method) |
| 250 | ); |
| 251 | } |
| 252 | assert!(serde_json::from_value::<ClientRequestMethod>("feedback/upload".into()).is_err()); |
| 253 | } |
| 254 | |
| 255 | #[derive(Clone, Copy, PartialEq)] |
| 256 | enum Mode { |
| 257 | Full, |
| 258 | Minimal, |
| 259 | } |
| 260 | |
| 261 | struct Instances { |
| 262 | definitions: Value, |
| 263 | } |
| 264 | |
| 265 | const DEPTH: usize = 5; |
| 266 | |
| 267 | impl Instances { |
| 268 | fn new() -> Self { |
| 269 | let mut definitions = pinned()["definitions"].clone(); |
| 270 | definitions["codewhale"] = manifest()["extensions"]["definitions"].clone(); |
| 271 | Instances { definitions } |
| 272 | } |
| 273 | |
| 274 | fn resolve(&self, reference: &str) -> &Value { |
| 275 | let mut node = &self.definitions; |
| 276 | for part in reference.trim_start_matches("#/definitions/").split('/') { |
| 277 | node = &node[part]; |
| 278 | } |
| 279 | assert!(!node.is_null(), "unresolved {reference}"); |
| 280 | node |
| 281 | } |
| 282 | |
| 283 | fn lookup(&self, name: &str) -> Option<(String, &Value)> { |
| 284 | for namespace in ["v2/", "", "codewhale/"] { |
| 285 | let reference = format!("#/definitions/{namespace}{name}"); |
| 286 | let mut node = &self.definitions; |
| 287 | for part in reference.trim_start_matches("#/definitions/").split('/') { |
| 288 | node = &node[part]; |
| 289 | } |
| 290 | if !node.is_null() && !(namespace.is_empty() && name == "v2") { |
| 291 | return Some((reference, node)); |
| 292 | } |
| 293 | } |
| 294 | None |
| 295 | } |
| 296 | |
| 297 | fn validator(&self, reference: &str) -> jsonschema::Validator { |
| 298 | let schema = json!({ |
| 299 | "$schema": "http://json-schema.org/draft-07/schema#", |
| 300 | "definitions": self.definitions, |
| 301 | "allOf": [{"$ref": reference}], |
| 302 | }); |
| 303 | jsonschema::validator_for(&schema).unwrap() |
| 304 | } |
| 305 | |
| 306 | fn members<'a>(&self, schema: &'a Value) -> Option<&'a Vec<Value>> { |
| 307 | schema["oneOf"].as_array().or(schema["anyOf"].as_array()) |
| 308 | } |
| 309 | |
| 310 | fn value(&self, schema: &Value, mode: Mode, depth: usize) -> Value { |
| 311 | if schema == &Value::Bool(true) { |
| 312 | return json!({"any": [1, "x"]}); |
| 313 | } |
| 314 | if let Some(reference) = schema["$ref"].as_str() { |
| 315 | return self.value(self.resolve(reference), mode, depth + 1); |
| 316 | } |
| 317 | if let Some(all) = schema["allOf"].as_array() { |
| 318 | return self.value(&all[0], mode, depth); |
| 319 | } |
| 320 | if let Some(members) = self.members(schema) { |
| 321 | let member = members |
| 322 | .iter() |
| 323 | .find(|member| member["type"] != "null") |
| 324 | .unwrap(); |
| 325 | return self.member_value(schema, member, mode, depth); |
| 326 | } |
| 327 | if let Some(values) = schema["enum"].as_array() { |
| 328 | return values[0].clone(); |
| 329 | } |
| 330 | let ty = match &schema["type"] { |
| 331 | Value::String(ty) => ty.clone(), |
| 332 | Value::Array(list) => list |
| 333 | .iter() |
| 334 | .find(|ty| *ty != "null") |
| 335 | .and_then(Value::as_str) |
| 336 | .unwrap() |
| 337 | .to_owned(), |
| 338 | _ => return json!({"any": [1, "x"]}), |
| 339 | }; |
| 340 | match ty.as_str() { |
| 341 | "string" => json!("s"), |
| 342 | "integer" => json!(1), |
| 343 | "boolean" => json!(true), |
| 344 | "array" => { |
| 345 | if mode == Mode::Full && depth < DEPTH { |
| 346 | json!([self.value(&schema["items"], mode, depth + 1)]) |
| 347 | } else { |
| 348 | json!([]) |
| 349 | } |
| 350 | } |
| 351 | "object" => self.object(schema, mode, depth), |
| 352 | other => panic!("unsupported type {other}"), |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | fn object(&self, schema: &Value, mode: Mode, depth: usize) -> Value { |
| 357 | let mut out = Map::new(); |
| 358 | let required: BTreeSet<&str> = schema["required"] |
| 359 | .as_array() |
| 360 | .map(|names| names.iter().filter_map(Value::as_str).collect()) |
| 361 | .unwrap_or_default(); |
| 362 | let full = mode == Mode::Full && depth < DEPTH; |
| 363 | if let Some(properties) = schema["properties"].as_object() { |
| 364 | for (name, property) in properties { |
| 365 | if required.contains(name.as_str()) || full { |
| 366 | out.insert(name.clone(), self.value(property, mode, depth + 1)); |
| 367 | } else if let Some(default) = |
| 368 | property.get("default").filter(|value| !value.is_null()) |
| 369 | { |
| 370 | out.insert(name.clone(), default.clone()); |
| 371 | } |
| 372 | } |
| 373 | if full && schema["additionalProperties"] == true { |
| 374 | out.insert("x-additional".into(), json!(1)); |
| 375 | } |
| 376 | } else if full { |
| 377 | match &schema["additionalProperties"] { |
| 378 | Value::Object(_) => { |
| 379 | out.insert( |
| 380 | "k".into(), |
| 381 | self.value(&schema["additionalProperties"], mode, depth + 1), |
| 382 | ); |
| 383 | } |
| 384 | Value::Bool(true) => { |
| 385 | out.insert("k".into(), json!(1)); |
| 386 | } |
| 387 | _ => {} |
| 388 | } |
| 389 | } |
| 390 | Value::Object(out) |
| 391 | } |
| 392 | |
| 393 | fn member_value(&self, schema: &Value, member: &Value, mode: Mode, depth: usize) -> Value { |
| 394 | let mut value = self.value(member, mode, depth); |
| 395 | if schema.get("properties").is_some() |
| 396 | && let (Value::Object(base), Value::Object(extra)) = |
| 397 | (self.object(schema, mode, depth), &mut value) |
| 398 | { |
| 399 | for (key, field) in base { |
| 400 | extra.entry(key).or_insert(field); |
| 401 | } |
| 402 | } |
| 403 | value |
| 404 | } |
| 405 | |
| 406 | fn cases(&self, schema: &Value) -> Vec<(String, Value)> { |
| 407 | let mut cases = vec![ |
| 408 | ("full".to_owned(), self.value(schema, Mode::Full, 0)), |
| 409 | ("minimal".to_owned(), self.value(schema, Mode::Minimal, 0)), |
| 410 | ]; |
| 411 | if let Some(members) = self.members(schema) { |
| 412 | for (index, member) in members.iter().enumerate() { |
| 413 | if member["type"] == "null" { |
| 414 | continue; |
| 415 | } |
| 416 | if let Some(values) = member["enum"].as_array() { |
| 417 | for value in values { |
| 418 | cases.push((format!("member {index} {value}"), value.clone())); |
| 419 | } |
| 420 | } else { |
| 421 | cases.push(( |
| 422 | format!("member {index} full"), |
| 423 | self.member_value(schema, member, Mode::Full, 0), |
| 424 | )); |
| 425 | cases.push(( |
| 426 | format!("member {index} minimal"), |
| 427 | self.member_value(schema, member, Mode::Minimal, 0), |
| 428 | )); |
| 429 | } |
| 430 | } |
| 431 | } else if let Some(values) = schema["enum"].as_array() { |
| 432 | for value in values { |
| 433 | cases.push((format!("enum {value}"), value.clone())); |
| 434 | } |
| 435 | } |
| 436 | cases |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn every_selected_shape_round_trips_against_the_pinned_schema() { |
| 442 | let instances = Instances::new(); |
| 443 | let mut checked = 0usize; |
| 444 | let mut typed = 0usize; |
| 445 | let mut inline = Vec::new(); |
| 446 | for name in v2::TYPE_NAMES { |
| 447 | let Some((reference, schema)) = instances.lookup(name) else { |
| 448 | inline.push(*name); |
| 449 | continue; |
| 450 | }; |
| 451 | typed += 1; |
| 452 | let validator = instances.validator(&reference); |
| 453 | for (case, value) in instances.cases(schema) { |
| 454 | assert!( |
| 455 | validator.is_valid(&value), |
| 456 | "{name} {case}: generated instance is not valid upstream: {value}" |
| 457 | ); |
| 458 | let again = v2::round_trip(name, value.clone()) |
| 459 | .unwrap() |
| 460 | .unwrap_or_else(|error| { |
| 461 | panic!("{name} {case}: typed decode failed: {error}: {value}") |
| 462 | }); |
| 463 | assert!( |
| 464 | validator.is_valid(&again), |
| 465 | "{name} {case}: typed output is not valid upstream: {again}" |
| 466 | ); |
| 467 | assert_eq!( |
| 468 | again, value, |
| 469 | "{name} {case}: typed round trip changed the value" |
| 470 | ); |
| 471 | checked += 1; |
| 472 | } |
| 473 | } |
| 474 | eprintln!( |
| 475 | "typed definitions with a pinned schema: {typed}; inline helper types: {}; round-tripped instances: {checked}", |
| 476 | inline.len() |
| 477 | ); |
| 478 | assert!(typed > 250 && checked > typed * 2); |
| 479 | } |
| 480 | |
| 481 | #[test] |
| 482 | fn typed_envelopes_match_the_pinned_unions_without_jsonrpc() { |
| 483 | let instances = Instances::new(); |
| 484 | let client_request = instances.validator("#/definitions/ClientRequest"); |
| 485 | let server_request = instances.validator("#/definitions/ServerRequest"); |
| 486 | let server_notification = instances.validator("#/definitions/ServerNotification"); |
| 487 | let client_notification = instances.validator("#/definitions/ClientNotification"); |
| 488 | let mut counts = BTreeMap::new(); |
| 489 | for method in ClientRequestMethod::ALL { |
| 490 | let (_, params_schema) = instances.lookup(method.params_type().unwrap()).unwrap(); |
| 491 | let (_, result_schema) = instances.lookup(method.response_type()).unwrap(); |
| 492 | for mode in [Mode::Full, Mode::Minimal] { |
| 493 | let params = instances.value(params_schema, mode, 0); |
| 494 | let envelope = json!({"id": 7, "method": method.method(), "params": params}); |
| 495 | assert!(client_request.is_valid(&envelope), "{method}: {envelope}"); |
| 496 | let call: RpcCall = serde_json::from_value(envelope).unwrap(); |
| 497 | let typed: v2::ClientRequestParams = |
| 498 | serde_json::from_value(json!({"method": call.method, "params": call.params})) |
| 499 | .unwrap_or_else(|error| panic!("{method}: {error}")); |
| 500 | assert_eq!(typed.method(), *method); |
| 501 | let encoded = serde_json::to_value(&typed).unwrap(); |
| 502 | assert!(encoded.get("jsonrpc").is_none()); |
| 503 | assert_eq!(encoded["params"], params); |
| 504 | let result = instances.value(result_schema, mode, 0); |
| 505 | let response = v2::ClientResponse::decode(*method, result.clone()).unwrap(); |
| 506 | assert_eq!(response.method(), *method); |
| 507 | assert_eq!(serde_json::to_value(&response).unwrap(), result); |
| 508 | } |
| 509 | *counts.entry("client requests").or_insert(0) += 1; |
| 510 | } |
| 511 | for method in ServerRequestMethod::ALL { |
| 512 | let (_, params_schema) = instances.lookup(method.params_type().unwrap()).unwrap(); |
| 513 | let (_, result_schema) = instances.lookup(method.response_type()).unwrap(); |
| 514 | for mode in [Mode::Full, Mode::Minimal] { |
| 515 | let params = instances.value(params_schema, mode, 0); |
| 516 | let typed: v2::ServerRequestParams = |
| 517 | serde_json::from_value(json!({"method": method.method(), "params": params})) |
| 518 | .unwrap(); |
| 519 | let mut encoded = serde_json::to_value(&typed).unwrap(); |
| 520 | encoded["id"] = json!("server-1"); |
| 521 | assert!(server_request.is_valid(&encoded), "{method}: {encoded}"); |
| 522 | let result = instances.value(result_schema, mode, 0); |
| 523 | let answer = v2::ServerRequestResponse::decode(*method, result.clone()).unwrap(); |
| 524 | assert_eq!(answer.method(), *method); |
| 525 | assert_eq!(serde_json::to_value(&answer).unwrap(), result); |
| 526 | } |
| 527 | *counts.entry("server requests").or_insert(0) += 1; |
| 528 | } |
| 529 | for method in ServerNotificationMethod::ALL { |
| 530 | let (_, params_schema) = instances.lookup(method.params_type().unwrap()).unwrap(); |
| 531 | for mode in [Mode::Full, Mode::Minimal] { |
| 532 | let params = instances.value(params_schema, mode, 0); |
| 533 | let typed: v2::ServerNotification = |
| 534 | serde_json::from_value(json!({"method": method.method(), "params": params})) |
| 535 | .unwrap(); |
| 536 | assert_eq!(typed.method(), *method); |
| 537 | let encoded = serde_json::to_value(&typed).unwrap(); |
| 538 | assert!(encoded.get("jsonrpc").is_none() && encoded.get("id").is_none()); |
| 539 | assert!( |
| 540 | server_notification.is_valid(&encoded), |
| 541 | "{method}: {encoded}" |
| 542 | ); |
| 543 | } |
| 544 | *counts.entry("server notifications").or_insert(0) += 1; |
| 545 | } |
| 546 | let initialized = serde_json::to_value(v2::ClientNotification::Initialized).unwrap(); |
| 547 | assert_eq!(initialized, json!({"method": "initialized"})); |
| 548 | assert!(client_notification.is_valid(&initialized)); |
| 549 | eprintln!("typed envelopes checked: {counts:?}"); |
| 550 | assert_eq!(counts["client requests"], 44); |
| 551 | assert_eq!(counts["server requests"], 5); |
| 552 | assert_eq!(counts["server notifications"], 33); |
| 553 | } |
| 554 | |
| 555 | #[test] |
| 556 | fn tier_c_and_undecided_methods_are_method_not_found_and_never_typed() { |
| 557 | let manifest = manifest(); |
| 558 | let mut refused = 0; |
| 559 | for (kind, _, _) in KINDS { |
| 560 | for row in manifest["methods"][kind].as_array().unwrap() { |
| 561 | if matches!(row["tier"].as_str(), Some("A" | "B")) { |
| 562 | continue; |
| 563 | } |
| 564 | let method = row["method"].as_str().unwrap(); |
| 565 | assert!(!disposition(kind, method).unwrap().selected()); |
| 566 | let envelope = json!({"method": method, "params": {}}); |
| 567 | match kind { |
| 568 | "clientRequests" => { |
| 569 | assert_eq!( |
| 570 | methods::unselected_request_error(method), |
| 571 | Some(error_code::METHOD_NOT_FOUND) |
| 572 | ); |
| 573 | assert!(ClientRequestMethod::from_method(method).is_none()); |
| 574 | assert!(serde_json::from_value::<v2::ClientRequestParams>(envelope).is_err()); |
| 575 | } |
| 576 | "serverRequests" => { |
| 577 | assert!(ServerRequestMethod::from_method(method).is_none()); |
| 578 | assert!(serde_json::from_value::<v2::ServerRequestParams>(envelope).is_err()); |
| 579 | } |
| 580 | "serverNotifications" => { |
| 581 | assert!(ServerNotificationMethod::from_method(method).is_none()); |
| 582 | assert!(serde_json::from_value::<v2::ServerNotification>(envelope).is_err()); |
| 583 | } |
| 584 | _ => {} |
| 585 | } |
| 586 | refused += 1; |
| 587 | } |
| 588 | } |
| 589 | assert_eq!(error_code::METHOD_NOT_FOUND, -32601); |
| 590 | assert_eq!(methods::unselected_request_error("thread/start"), None); |
| 591 | assert_eq!( |
| 592 | methods::unselected_request_error("not/in/the/export"), |
| 593 | Some(error_code::METHOD_NOT_FOUND) |
| 594 | ); |
| 595 | eprintln!("unselected methods refused: {refused}"); |
| 596 | assert!(refused > 100); |
| 597 | } |
| 598 | |
| 599 | #[test] |
| 600 | fn codewhale_extensions_stay_optional_and_valid_upstream() { |
| 601 | let instances = Instances::new(); |
| 602 | let thread = instances.validator("#/definitions/v2/Thread"); |
| 603 | let (_, schema) = instances.lookup("Thread").unwrap(); |
| 604 | let mut value = instances.value(schema, Mode::Minimal, 0); |
| 605 | let plain: v2::Thread = serde_json::from_value(value.clone()).unwrap(); |
| 606 | assert!(plain.executor.is_none() && plain.environment.is_none()); |
| 607 | assert_eq!(serde_json::to_value(&plain).unwrap(), value); |
| 608 | value["executor"] = json!({"kind": "acp", "agentId": "claude", "agentName": "Claude"}); |
| 609 | value["environment"] = json!({"id": "env-1", "providerKind": "remote"}); |
| 610 | assert!(thread.is_valid(&value)); |
| 611 | let placed: v2::Thread = serde_json::from_value(value.clone()).unwrap(); |
| 612 | assert_eq!(placed.executor.as_ref().unwrap().agent_id, "claude"); |
| 613 | assert_eq!(serde_json::to_value(&placed).unwrap(), value); |
| 614 | let refusal = instances.validator("#/definitions/codewhale/CapabilityRefusalData"); |
| 615 | let data = serde_json::to_value(v2::CapabilityRefusalData { |
| 616 | codewhale_refusal: v2::CapabilityRefusal { |
| 617 | code: v2::CapabilityRefusalCode::EnvironmentNotSupported, |
| 618 | method: Some("turn/start".into()), |
| 619 | thread_id: Some("thread-1".into()), |
| 620 | }, |
| 621 | }) |
| 622 | .unwrap(); |
| 623 | assert!(refusal.is_valid(&data)); |
| 624 | assert_eq!( |
| 625 | data["codewhaleRefusal"]["code"], |
| 626 | "environment_not_supported" |
| 627 | ); |
| 628 | assert_eq!(error_code::CAPABILITY_UNSUPPORTED, -32020); |
| 629 | assert!( |
| 630 | serde_json::from_value::<v2::CapabilityRefusal>(json!({"code": "no_acp", "token": "x"})) |
| 631 | .is_err() |
| 632 | ); |
| 633 | } |
| 634 |