diff --git a/conformance/README.md b/conformance/README.md index 59940be..0f9c3a5 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -20,7 +20,7 @@ conforms to CNP 1.0 if it passes every session that applies to it. | `preferences/` | The draft preferences extension's read (`spec/preferences.md`) | Nodes that keep preferences | | `games/` | The draft games extension: a save, its retry, a reused version, get, list, searching, deleting, importing and a game's source (`spec/games.md`) | Nodes that keep games (searching, deleting, importing and sources: those that offer them) | | `backups/` | The draft backups extension: the day's automatic backup once, a backup made, restored and the restore undone (`spec/backups.md`) | Nodes that back up what they keep | -| `knowledge/` | The draft knowledge extension: an import's refusals, with none started, and reads on an empty library: arrays, the position an analysis is of, and refusals; its space: usage, and refusing a removal (`spec/knowledge.md`) | Nodes that import puzzles and positions (space: those that offer it) | +| `knowledge/` | The draft knowledge extension: an import's refusals, with none started, and reads on an empty library: arrays, the position an analysis is of, and refusals; its space: usage, and refusing a removal; an opening explorer's answer, a position it doesn't hold, and its refusals (`spec/knowledge.md`) | Nodes that import puzzles and positions (space and the explorer: those that offer them) | The voice sessions check only what doesn't need a model to be ready. A voice node's own tests check its speech and transcription. diff --git a/conformance/knowledge/explorer.jsonl b/conformance/knowledge/explorer.jsonl new file mode 100644 index 0000000..b0c17c5 --- /dev/null +++ b/conformance/knowledge/explorer.jsonl @@ -0,0 +1,20 @@ +{"session":"knowledge-explorer","description":"draft-1 knowledge: an opening explorer says which position its answer is of and how its games ended, answers a position it doesn't hold with no games and no error, and refuses a malformed one (spec/knowledge.md, knowledge/explorer)","requires":["knowledge.explorer"]} +{"send":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocol":"1.0","client":{"name":"cnp-conformance","version":"1.0"}}}} +{"expect":{"id":1,"result":{"capabilities":{"knowledge":{"contract":"draft-1","read":true,"explorer":true}}}}} +{"comment":"The starting position: the position as the node identifies it (the counters are not part of it), and the answer's fields, whatever the node holds."} +{"send":{"jsonrpc":"2.0","id":2,"method":"knowledge/explorer","params":{"fen":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}}} +{"expect":{"id":2,"result":{"position":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -","games":"$integer","whiteWins":"$integer","draws":"$integer","blackWins":"$integer","moves":"$array","top":"$array","sources":"$array"}}} +{"comment":"A position no opening reaches is out of book: no games, no moves, no strongest games, and no error. It has no name either: eco and opening, when a node sends them, are a named line's end position's, and this one ends none."} +{"send":{"jsonrpc":"2.0","id":3,"method":"knowledge/explorer","params":{"fen":"4k3/8/8/8/8/8/4P3/4K3 w - - 12 34"}}} +{"expect":{"id":3,"result":{"position":"4k3/8/8/8/8/8/4P3/4K3 w - -","games":0,"whiteWins":0,"draws":0,"blackWins":0,"moves":[],"top":[]}}} +{"comment":"Refused: an illegal position, a FEN of the wrong shape, and no FEN."} +{"send":{"jsonrpc":"2.0","id":4,"method":"knowledge/explorer","params":{"fen":"4k3/8/8/8/8/8/8/8 w - -"}}} +{"expect":{"id":4,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":5,"method":"knowledge/explorer","params":{"fen":"not a fen"}}} +{"expect":{"id":5,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":6,"method":"knowledge/explorer","params":{}}} +{"expect":{"id":6,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":7,"method":"shutdown"}} +{"expect":{"id":7,"result":null}} +{"send":{"jsonrpc":"2.0","method":"exit"}} +{"expectExit":0} diff --git a/crates/cnp/src/knowledge.rs b/crates/cnp/src/knowledge.rs index 66ba7e0..677c8bf 100644 --- a/crates/cnp/src/knowledge.rs +++ b/crates/cnp/src/knowledge.rs @@ -86,6 +86,10 @@ pub struct Capabilities { /// node that doesn't offer it. #[serde(default)] pub space: bool, + /// `knowledge/explorer` is available. Needs [`Capabilities::read`]. A client sends it to + /// no node that doesn't offer it. + #[serde(default)] + pub explorer: bool, /// The kinds of file the node can import ([`KIND_LICHESS_PUZZLES`] and the like). #[serde(default)] pub kinds: Vec, @@ -829,6 +833,108 @@ impl RequestMethod for FindAnalyses { type Result = AnalysesResult; } +/// `knowledge/explorer`'s params. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExplorerParams { + /// A position of four or six fields; counters are ignored. + pub fen: String, +} + +impl ExplorerParams { + /// Checks the params' shapes (not whether the position is legal), or says what is wrong. + pub fn validate(&self) -> Result<(), String> { + let fields = self.fen.split_ascii_whitespace().count(); + if self.fen.len() > MAX_FEN_BYTES || !matches!(fields, 4 | 6) { + return Err("a FEN has four or six fields".into()); + } + Ok(()) + } +} + +/// A move played from an explorer's position, over the games that played it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExplorerMove { + /// The move, in UCI. + pub uci: String, + /// How many games played it. + pub games: u64, + /// Of them, White's wins. + pub white_wins: u64, + /// Of them, draws. + pub draws: u64, + /// Of them, Black's wins. + pub black_wins: u64, + /// The mean, over those games, of the two players' mean rating. + pub elo: i64, +} + +/// One of the strongest games that reached an explorer's position. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExplorerGame { + /// The game's identity, with where it is from before a colon: `lichess:AbCdEf12`. + pub id: String, + /// White's name, when the source gave one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub white: Option, + /// Black's name, when the source gave one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub black: Option, + /// White's rating. + pub white_elo: i64, + /// Black's rating. + pub black_elo: i64, + /// How it ended: `1-0`, `0-1` or `1/2-1/2`. + pub result: String, + /// The day it was played, `YYYY-MM-DD`, when the source gave one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub date: Option, + /// The move it played from this position, in UCI. + pub uci: String, +} + +/// `knowledge/explorer`'s result. A position the node doesn't hold has no games, moves or +/// strongest games: out of book, not an error. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExplorerResult { + /// The position as the node identifies it, as in [`AnalysesResult::position`]. A client + /// applies the answer only to a position it matches. + pub position: String, + /// The position's ECO code, `B00`, when a named line ends there; with + /// [`ExplorerResult::opening`] or not at all. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub eco: Option, + /// The opening's name, `King's Pawn Game`, when a named line ends at the position; with + /// [`ExplorerResult::eco`] or not at all. A position without one is named by the client, if + /// it likes, after the last named position along the moves it knows led there. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opening: Option, + /// How many games reached the position, each counted once. + pub games: u64, + /// Of them, White's wins. + pub white_wins: u64, + /// Of them, draws. + pub draws: u64, + /// Of them, Black's wins. + pub black_wins: u64, + /// Every move those games played from it, most played first. + pub moves: Vec, + /// The strongest games that reached it, strongest first. + pub top: Vec, + /// The sources of the games counted. + pub sources: Vec, +} + +/// What the sources' games played from a position. +pub enum FindExplorer {} +impl RequestMethod for FindExplorer { + const NAME: &'static str = "knowledge/explorer"; + type Params = ExplorerParams; + type Result = ExplorerResult; +} + /// `knowledge/exercises`' params: all optional, and the params may be left out. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(from = "Option")] diff --git a/crates/cnp/tests/knowledge.rs b/crates/cnp/tests/knowledge.rs index 79d0ef8..d67b43f 100644 --- a/crates/cnp/tests/knowledge.rs +++ b/crates/cnp/tests/knowledge.rs @@ -192,6 +192,14 @@ fn the_specs_json_examples_are_valid() { r.analyses[0].perspective, knowledge::Perspective::Unspecified ); + } else if value.get("top").is_some() { + let r: knowledge::ExplorerResult = serde_json::from_value(value).unwrap(); + assert_eq!(r.games, r.white_wins + r.draws + r.black_wins); + assert_eq!(r.moves[0].uci, "c7c5"); + assert!(r.moves[0].games >= r.moves[1].games, "most played first"); + assert_eq!(r.top[0].id, "lichess:AbCdEf12"); + assert_eq!(r.eco.as_deref(), Some("B00")); + assert_eq!(r.opening.as_deref(), Some("King's Pawn Game")); } else if value.get("exercises").is_some() { let r: knowledge::ExercisesResult = serde_json::from_value(value).unwrap(); assert_eq!(r.exercises[0].candidates[0].uci, "f4f5"); @@ -241,7 +249,7 @@ fn the_specs_json_examples_are_valid() { } checked += 1; } - assert!(checked >= 14, "only {checked} examples"); + assert!(checked >= 16, "only {checked} examples"); } #[test] @@ -592,3 +600,108 @@ fn a_removal_names_an_identity_and_answers_the_import_it_removed() { assert_eq!(answer.removed.accepted, 6_193_530); assert_eq!(answer.bytes, 49_098_752); } + +#[test] +fn the_explorer_capability_is_its_own_switch_and_older_nodes_lack_it() { + let older: knowledge::Capabilities = + serde_json::from_value(json!({"read":true,"contract":"draft-1"})).unwrap(); + assert!(older.read && !older.explorer); + let newer: knowledge::Capabilities = + serde_json::from_value(json!({"read":true,"explorer":true,"contract":"draft-1"})).unwrap(); + assert!(newer.explorer); + assert_eq!( + serde_json::to_value(&newer).unwrap()["explorer"], + json!(true) + ); +} + +#[test] +fn explorer_params_need_a_fen_of_four_or_six_fields() { + use cnp::RequestMethod; + assert_eq!(knowledge::FindExplorer::NAME, "knowledge/explorer"); + let ok = |fen: &str| knowledge::ExplorerParams { fen: fen.into() }.validate(); + assert!(ok("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -").is_ok()); + assert!(ok("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").is_ok()); + assert!(ok("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq").is_err()); + assert!(ok("").is_err()); + assert!(ok(&"x ".repeat(100)).is_err()); + let missing: Result = serde_json::from_value(json!({})); + assert!(missing.is_err()); +} + +#[test] +fn an_explorers_answer_is_written_as_the_spec_has_it() { + let game = knowledge::ExplorerGame { + id: "lichess:AbCdEf12".into(), + white: Some("Alice".into()), + black: None, + white_elo: 2688, + black_elo: 2564, + result: "1-0".into(), + date: None, + uci: "c7c5".into(), + }; + let written = serde_json::to_value(&game).unwrap(); + assert_eq!( + written, + json!({"id":"lichess:AbCdEf12","white":"Alice","whiteElo":2688,"blackElo":2564, + "result":"1-0","uci":"c7c5"}), + "a name or a date the source didn't give is left out" + ); + assert_eq!( + serde_json::from_value::(written).unwrap(), + game + ); + + let mv = knowledge::ExplorerMove { + uci: "c7c5".into(), + games: 3, + white_wins: 1, + draws: 1, + black_wins: 1, + elo: 1934, + }; + assert_eq!( + serde_json::to_value(&mv).unwrap(), + json!({"uci":"c7c5","games":3,"whiteWins":1,"draws":1,"blackWins":1,"elo":1934}) + ); + + // Out of book: the position, and nothing played from it. + let empty: knowledge::ExplorerResult = serde_json::from_value(json!({ + "position":"4k3/8/8/8/8/8/4P3/4K3 w - -","games":0,"whiteWins":0,"draws":0, + "blackWins":0,"moves":[],"top":[],"sources":[] + })) + .unwrap(); + assert_eq!(empty.games, 0); + assert!(empty.moves.is_empty() && empty.top.is_empty()); + assert_eq!( + (empty.eco, empty.opening), + (None, None), + "an older node's answer" + ); +} + +#[test] +fn an_explorers_position_is_named_only_when_a_named_line_ends_there() { + let named = knowledge::ExplorerResult { + position: "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq -".into(), + eco: Some("B20".into()), + opening: Some("Sicilian Defense".into()), + ..Default::default() + }; + let written = serde_json::to_value(&named).unwrap(); + assert_eq!(written["eco"], json!("B20")); + assert_eq!(written["opening"], json!("Sicilian Defense")); + assert_eq!( + serde_json::from_value::(written).unwrap(), + named + ); + + // A position no named line ends at: no name, and neither attribute is written. + let unnamed = knowledge::ExplorerResult { + position: "4k3/8/8/8/8/8/4P3/4K3 w - -".into(), + ..Default::default() + }; + let written = serde_json::to_value(&unnamed).unwrap(); + assert!(written.get("eco").is_none() && written.get("opening").is_none()); +} diff --git a/spec/knowledge.md b/spec/knowledge.md index 0350f70..7269669 100644 --- a/spec/knowledge.md +++ b/spec/knowledge.md @@ -22,7 +22,8 @@ the checksum the client says it has, so a damaged or swapped download is refused ```json {"capabilities": {"knowledge": {"import": true, "read": true, "puzzleSelection": true, - "puzzleFilters": true, "space": true, "kinds": ["lichess-puzzles", "lichess-evals", "sts-epd"], + "puzzleFilters": true, "space": true, "explorer": true, + "kinds": ["lichess-puzzles", "lichess-evals", "sts-epd"], "contract": "draft-1"}}} ``` @@ -31,7 +32,8 @@ the checksum the client says it has, so a damaged or swapped download is refused `knowledge/puzzles`' `order`, `seed` and `quality`, and `knowledge/puzzleFacets`; `puzzleFilters` (which needs `puzzleSelection`) offers `knowledge/puzzles`' `opening` and `daily`, and the `openings` of `knowledge/puzzleFacets`; `space` offers `knowledge/usage` and -`knowledge/remove`. A missing switch is false. `kinds` are the kinds of file the node can import; a request for another kind is +`knowledge/remove`; `explorer` (which needs `read`) offers `knowledge/explorer`. A missing +switch is false. `kinds` are the kinds of file the node can import; a request for another kind is refused. A client sends knowledge requests only to a node whose `contract` is `draft-1`. A node without the domain answers them with Method not found (-32601). @@ -379,6 +381,65 @@ source gave them, each line with a `cp` (centipawns) or a `mate` score and its m score may differ from the same position reached in a game where repetition matters. A position with no analysis answers with an empty `analyses`. An illegal position is -32602. +### `knowledge/explorer` + +What was played from a position, and how it went: the moves the sources' games chose there, +each with its games, their results and how strong they were, and the strongest of those games. +A node that offers `explorer` answers it; a client sends it to no other node. + +```json +{"fen": "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1"} +``` + +`fen` is a position of four or six fields, as in `knowledge/analyses`. Answers (abridged to two +moves and one game, with illustrative counts): + +```json +{"position": "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq -", + "eco": "B00", "opening": "King's Pawn Game", + "games": 61999, "whiteWins": 30113, "draws": 3120, "blackWins": 28766, + "moves": [{"uci": "c7c5", "games": 15552, "whiteWins": 7400, "draws": 710, "blackWins": 7442, + "elo": 1934}, + {"uci": "e7e5", "games": 15192, "whiteWins": 7702, "draws": 801, "blackWins": 6689, + "elo": 1921}], + "top": [{"id": "lichess:AbCdEf12", "white": "Alice", "black": "Bob", "whiteElo": 2688, + "blackElo": 2564, "result": "1-0", "date": "2014-07-12", "uci": "c7c5"}], + "sources": [{ ... a source ... }]} +``` + +- `position` is the position as the node identifies it, as in `knowledge/analyses`, and a + client applies the answer only to the position it asked about. +- `eco` and `opening` are the position's name, when it has one: its ECO code (a letter `A` to + `E` and two digits) and the opening's name, as a list of named lines such as Lichess's + `chess-openings` gives them, `Family: Variation, Subvariation`. A position is named when a + named line **ends** there, whatever move order reached it, so a transposition is named too. + Most positions have no name of their own, and both are then absent: a client that wants a + name for every position shows the last named position along the moves that led to it, as + only it knows them. The two come together or not at all. +- `games` is how many of the sources' games reached the position, and `whiteWins`, `draws` and + `blackWins` how they ended: the three add up to `games`. **A game counts once**, however + often it came back to the position, with the first move it played from it. +- `moves` are the moves those games played from it, **most played first**, each in UCI with + its own `games` and results, and `elo`: the mean, over the games that played it, of the two + players' mean rating. Every move played is listed, so the moves' `games` add up to the + position's. +- `top` are the strongest games that reached it, **strongest first** (by the two players' mean + rating), as many as the node keeps for a position. Each has an `id`, the game's identity + with where it is from before a colon (`lichess:AbCdEf12`); `whiteElo`, `blackElo` and + `result` (`1-0`, `0-1` or `1/2-1/2`); `uci`, the move it played **from this position**; and + `white`, `black` (the players' names) and `date` (the day it was played, `YYYY-MM-DD`) when + the source gave them. +- `sources` are the sources of the games counted. + +**A position the node doesn't hold is out of book, not an error**: it answers with `games` 0 +and empty `moves` and `top`. An explorer holds the positions its builder kept, which is the +builder's choice and usually leaves out a position too deep in a game or reached by too few of +them; a client can't tell "never played" from "not kept", and needn't. An illegal position is +-32602. + +An explorer's numbers say what the sources' players chose and how their games ended. They are +not an evaluation: a move most games lost with may be the best one. + ### `knowledge/exercises` ```json @@ -429,10 +490,19 @@ exercise names its `source`, and a client never mixes the points of two sources. Several themes in one request (and excluding a theme), progress notifications in place of polling, reading the records an import rejected, removing part of an import's knowledge, -searching puzzles by a position, and Lumbra's OTB games. +searching puzzles by a position, Lumbra's OTB games, reading the game a `top` entry of +`knowledge/explorer` names, and how a node comes to hold an explorer's positions (a kind of file +to import, or a cache of an online service's answers: cjus/chessdb#48). ## Changes +- **draft 1, 2026-11-14**, added to the draft: **the opening explorer** (capability `explorer`, + `knowledge/explorer`): the moves played from a position with their games, results and mean + rating, and the strongest games that reached it (cjus/chessgui#656); and, 2026-11-17, the + position's name, `eco` and `opening`, when it has one (cjus/chessdb#73). Optional: a node + that doesn't offer it is unchanged. How a node comes to hold the positions is not in the + draft yet. + - **draft 1, 2026-11-16**, clarified: a node that offers `puzzleFilters` answers `knowledge/puzzleFacets`' `openings` even when it is empty, as the conformance session already expected; `cnp`'s `FacetsResult::openings` is now an `Option`, so a node built on it