From 4fb226e557c40a4f02831f99dcca6ccaebb35c01 Mon Sep 17 00:00:00 2001 From: cjus Date: Wed, 18 Nov 2026 09:54:25 -0700 Subject: [PATCH] Knowledge: knowledge/openingName, the opening of a line of moves (draft-1) A node that offers openingNames names the last named position along a line (fen + UCI moves) from a list it holds itself, such as Lichess's chess-openings (CC0): position, and eco, opening and ply together or not at all. It needs no import. For cjus/chessgui#755's follow-up: names offline, for any position, with none skipped. Co-Authored-By: Claude Opus 5.5 --- conformance/README.md | 2 +- conformance/knowledge/opening-names.jsonl | 21 ++++++ crates/cnp/src/knowledge.rs | 89 ++++++++++++++++++++++- crates/cnp/tests/knowledge.rs | 66 +++++++++++++++++ spec/knowledge.md | 55 +++++++++++++- 5 files changed, 227 insertions(+), 6 deletions(-) create mode 100644 conformance/knowledge/opening-names.jsonl diff --git a/conformance/README.md b/conformance/README.md index 59940be..d1d4edc 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; opening names: the last named position along a line, a transposition, a line nothing names, and refusals (`spec/knowledge.md`) | Nodes that import puzzles and positions (space, opening names: 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/opening-names.jsonl b/conformance/knowledge/opening-names.jsonl new file mode 100644 index 0000000..ccf6a42 --- /dev/null +++ b/conformance/knowledge/opening-names.jsonl @@ -0,0 +1,21 @@ +{"session":"knowledge-opening-names","description":"draft-1 knowledge/openingName names the last named position along a line, matched by position so a transposition is named too; a line nothing names answers its position alone; an illegal move or a malformed FEN is invalid params (spec/knowledge.md, Naming openings)","requires":["knowledge.openingNames"]} +{"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","openingNames":true}}}}} +{"comment":"The Morphy Defense: named at 3... a6, and no listed line ends at 4. Ba4 or 4... Nf6."} +{"send":{"jsonrpc":"2.0","id":2,"method":"knowledge/openingName","params":{"fen":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1","moves":["e2e4","e7e5","g1f3","b8c6","f1b5","a7a6","b5a4","g8f6"]}}} +{"expect":{"id":2,"result":{"position":"r1bqkb1r/1ppp1ppp/p1n2n2/4p3/B3P3/5N2/PPPP1PPP/RNBQK2R w KQkq -","eco":"C70","opening":"Ruy Lopez: Morphy Defense","ply":6}}} +{"comment":"D35 by another move order."} +{"send":{"jsonrpc":"2.0","id":3,"method":"knowledge/openingName","params":{"fen":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1","moves":["d2d4","g8f6","c2c4","e7e6","b1c3","d7d5"]}}} +{"expect":{"id":3,"result":{"eco":"D35","opening":"Queen's Gambit Declined: Normal Defense","ply":6}}} +{"comment":"The start, with no moves: no listed line ends there."} +{"send":{"jsonrpc":"2.0","id":4,"method":"knowledge/openingName","params":{"fen":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -","moves":[]}}} +{"expect":{"id":4,"result":{"position":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -","eco":"$absent","opening":"$absent","ply":"$absent"}}} +{"comment":"A move that isn't legal where it is played."} +{"send":{"jsonrpc":"2.0","id":5,"method":"knowledge/openingName","params":{"fen":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1","moves":["e2e4","e2e4"]}}} +{"expect":{"id":5,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":6,"method":"knowledge/openingName","params":{"fen":"not a fen","moves":[]}}} +{"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..7b9ad28 100644 --- a/crates/cnp/src/knowledge.rs +++ b/crates/cnp/src/knowledge.rs @@ -10,6 +10,8 @@ //! first, or from a random point, and only the reliable ones if asked), [`FindPuzzleFacets`] //! for how many there are of each theme and rating band, [`FindAnalyses`] of a position, and //! [`FindExercises`] by theme, each from complete imports only and naming its [`Source`]s. +//! Beside them, [`NameOpening`] names the opening of a line of moves from the node's own list +//! of named openings, not from imports. //! //! **The node doesn't download.** The client fetches the file, where it can show the licence, //! the size and the progress. The node verifies the file against the manifest's checksum before @@ -21,7 +23,8 @@ //! //! **Pitfall: apply an answer only to the position it is of.** [`AnalysesResult::position`] is //! the position as the node identifies it; a client compares it with its own current position -//! before it shows the answer. +//! before it shows the answer. An opening's name depends on the whole line, not only where it +//! ends, so a client applies an [`OpeningNameResult`] only to the line it asked about. //! //! **Pitfall: variants aren't versions.** A kind's variants (a puzzle database's releases, the //! Strategic Test Suite's differently scored files) are different sources, told apart by @@ -86,6 +89,10 @@ pub struct Capabilities { /// node that doesn't offer it. #[serde(default)] pub space: bool, + /// `knowledge/openingName` is available: the node names the opening of a line of moves + /// from a list of named openings it holds itself. It needs no import and no other switch. + #[serde(default)] + pub opening_names: bool, /// The kinds of file the node can import ([`KIND_LICHESS_PUZZLES`] and the like). #[serde(default)] pub kinds: Vec, @@ -829,6 +836,86 @@ impl RequestMethod for FindAnalyses { type Result = AnalysesResult; } +/// The most moves a `knowledge/openingName` line has: far more than any game. +pub const MAX_LINE_MOVES: usize = 1024; + +/// `knowledge/openingName`'s params: a line of moves from a position. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OpeningNameParams { + /// Where the line starts: a position of four to six fields (counters are ignored), such as + /// a game's start. + pub fen: String, + /// The line's moves from `fen`, in UCI, at most [`MAX_LINE_MOVES`]; empty names `fen` + /// itself. + #[serde(default)] + pub moves: Vec, +} + +impl OpeningNameParams { + /// Checks the params' shapes (not whether the position or the moves are 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 to six fields".into()); + } + if self.moves.len() > MAX_LINE_MOVES { + return Err(format!("at most {MAX_LINE_MOVES} moves")); + } + if let Some(bad) = self.moves.iter().find(|mv| !looks_like_uci(mv)) { + return Err(format!("{bad:?} isn't a move in UCI")); + } + Ok(()) + } +} + +/// Whether `text` has a UCI move's shape: two squares and an optional promotion piece. +fn looks_like_uci(text: &str) -> bool { + let b = text.as_bytes(); + let square = + |file: u8, rank: u8| (b'a'..=b'h').contains(&file) && (b'1'..=b'8').contains(&rank); + matches!(b.len(), 4 | 5) + && square(b[0], b[1]) + && square(b[2], b[3]) + && b.get(4).is_none_or(|piece| b"nbrq".contains(piece)) +} + +/// `knowledge/openingName`'s result: the name of the last named position along the line. +/// +/// `eco`, `opening` and `ply` are there together or not at all: all absent when no position +/// along the line, its start included, is named. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OpeningNameResult { + /// The position the line ends at, as the node identifies it (as + /// [`AnalysesResult::position`]). + pub position: String, + /// The named position's ECO code, `C60`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub eco: Option, + /// The named position's opening, `Ruy Lopez`, or `Family: Variation, Subvariation`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opening: Option, + /// How many of the line's moves lead to the named position: 0 for the start, the number + /// of moves for the position the line ends at. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ply: Option, +} + +impl OpeningNameResult { + /// The name, as its ECO code and opening, if the answer has both. + pub fn name(&self) -> Option<(&str, &str)> { + Some((self.eco.as_deref()?, self.opening.as_deref()?)) + } +} + +/// The opening of a line of moves, from the node's list of named openings. +pub enum NameOpening {} +impl RequestMethod for NameOpening { + const NAME: &'static str = "knowledge/openingName"; + type Params = OpeningNameParams; + type Result = OpeningNameResult; +} + /// `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..afb62ef 100644 --- a/crates/cnp/tests/knowledge.rs +++ b/crates/cnp/tests/knowledge.rs @@ -186,6 +186,15 @@ fn the_specs_json_examples_are_valid() { } else if value.get("puzzles").is_some() { let r: knowledge::PuzzlesResult = serde_json::from_value(value).unwrap(); assert_eq!(r.puzzles[0].moves.len(), 6); + } else if value.get("position").is_some() && value.get("analyses").is_none() { + let r: knowledge::OpeningNameResult = serde_json::from_value(value).unwrap(); + // The three are there together or not at all. + assert_eq!(r.name().is_some(), r.ply.is_some(), "{r:?}"); + } else if value.get("moves").is_some() && value.get("fen").is_some() { + serde_json::from_value::(value) + .unwrap() + .validate() + .unwrap(); } else if value.get("analyses").is_some() { let r: knowledge::AnalysesResult = serde_json::from_value(value).unwrap(); assert_eq!( @@ -592,3 +601,60 @@ 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_opening_names_capability_is_its_own_switch_and_older_nodes_lack_it() { + let c: knowledge::Capabilities = + serde_json::from_value(json!({"openingNames": true, "contract": "draft-1"})).unwrap(); + assert!(c.opening_names && !c.read && !c.import); + let older: knowledge::Capabilities = + serde_json::from_value(json!({"read": true, "contract": "draft-1"})).unwrap(); + assert!(!older.opening_names); + assert_eq!( + serde_json::to_value(&c).unwrap()["openingNames"], + json!(true) + ); +} + +#[test] +fn opening_name_params_are_a_fen_and_moves_in_uci() { + let start = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; + let params = |fen: &str, moves: &[&str]| knowledge::OpeningNameParams { + fen: fen.into(), + moves: moves.iter().map(|m| m.to_string()).collect(), + }; + assert_eq!(params(start, &["e2e4", "e7e5", "e7e8q"]).validate(), Ok(())); + assert_eq!(params(start, &[]).validate(), Ok(()), "the start itself"); + assert!(params("8/8/8/8/8/8/8/8 w -", &[]).validate().is_err()); + for bad in ["e2e9", "i2e4", "e2e4k", "O-O", "e2", "Nf3", ""] { + assert!(params(start, &[bad]).validate().is_err(), "{bad:?}"); + } + let long = vec!["e2e4"; knowledge::MAX_LINE_MOVES + 1]; + assert!(params(start, &long).validate().is_err()); + let no_moves: knowledge::OpeningNameParams = + serde_json::from_value(json!({"fen": start})).unwrap(); + assert!(no_moves.moves.is_empty()); + use cnp::RequestMethod; + assert_eq!(knowledge::NameOpening::NAME, "knowledge/openingName"); +} + +#[test] +fn an_opening_name_answer_leaves_out_what_it_hasnt() { + let named: knowledge::OpeningNameResult = serde_json::from_value(json!({ + "position": "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq -", + "eco": "C60", "opening": "Ruy Lopez", "ply": 5 + })) + .unwrap(); + assert_eq!(named.name(), Some(("C60", "Ruy Lopez"))); + let unnamed = knowledge::OpeningNameResult { + position: "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -".into(), + eco: None, + opening: None, + ply: None, + }; + assert_eq!(unnamed.name(), None); + assert_eq!( + serde_json::to_value(&unnamed).unwrap(), + json!({"position": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -"}) + ); +} diff --git a/spec/knowledge.md b/spec/knowledge.md index 0350f70..bf6bc63 100644 --- a/spec/knowledge.md +++ b/spec/knowledge.md @@ -22,8 +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"], - "contract": "draft-1"}}} + "puzzleFilters": true, "space": true, "openingNames": true, + "kinds": ["lichess-puzzles", "lichess-evals", "sts-epd"], "contract": "draft-1"}}} ``` `import` offers `knowledge/import`, `knowledge/status` and `knowledge/cancel`; `read` offers @@ -31,7 +31,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`; `openingNames` offers `knowledge/openingName`, which needs no import and +no other switch. 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). @@ -399,6 +400,47 @@ order; a move may appear twice with different points, as the published files hav on the files' different scales (0 to 10, 1 to 100) are not comparable, which is why every exercise names its `source`, and a client never mixes the points of two sources. +## Naming openings + +A node that offers `openingNames` holds a list of named openings of its own, such as Lichess's +[`chess-openings`](https://github.com/lichess-org/chess-openings) (CC0): an ECO code and a name +for each line, and so for the position each line ends at. Unlike the reads, it answers from +that list, not from imports, so it answers the same with nothing imported. + +### `knowledge/openingName` + +```json +{"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "moves": ["e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4", "g8f6"]} +``` + +`fen` is where the line starts, of four to six fields (the counters, if any, are ignored), such +as a game's start; `moves` are the line's moves from it in UCI, at most 1,024 (empty names `fen` +itself). Answers with the name of **the last named position along the line**: the position the +moves end at if a listed line ends there, or else the one before it, and so on back to `fen`, +as lichess.org names a game's opening: + +```json +{"position": "r1bqkb1r/1ppp1ppp/p1n2n2/4p3/B3P3/5N2/PPPP1PPP/RNBQK2R w KQkq -", + "eco": "C70", "opening": "Ruy Lopez: Morphy Defense", "ply": 6} +``` + +`position` is the position the line ends at, as `knowledge/analyses` identifies one. `ply` is +how many of the moves lead to the named position: here the sixth, `3... a6`, since no listed +line ends at `4. Ba4` or `4... Nf6`. `eco`, `opening` and `ply` are there together or not at +all: when no position along the line, `fen` included, is named, the answer has only `position`: + +```json +{"position": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -"} +``` + +A position is matched by its identity, not by the moves that reached it, so a transposition is +named too: `1. d4 Nf6 2. c4 e6 3. Nc3 d5` reaches D35 Queen's Gambit Declined: Normal Defense, +listed as `1. d4 d5 2. c4 e6 3. Nc3 Nf6`. **A client applies an answer only to the line it +asked about**: the name depends on every position along the line, not only where it ends, so +comparing `position` isn't enough. An illegal position, or a move that isn't legal where it is +played, is -32602. + ## Pitfalls - **The path is the client's.** A node reads whatever file its client names, and the client @@ -418,7 +460,7 @@ exercise names its `source`, and a client never mixes the points of two sources. | Error | Meaning | Client action | | --- | --- | --- | -| -32602 | Invalid params: an unknown kind, or a malformed path, manifest, checksum, theme, rating, limit, cursor, FEN, order or quality, or a seed with any order but random | Correct the request | +| -32602 | Invalid params: an unknown kind, or a malformed path, manifest, checksum, theme, rating, limit, cursor, FEN, order or quality, a seed with any order but random, or a line of moves too long or with a move that isn't legal where it is played | Correct the request | | -32013 | Busy: an import or a removal is running, or the import to remove is | Wait for it, or cancel the import | | -32022 | Storage or I/O failed | Ask `knowledge/status` for the import's state | | -32025 | No import with that identity | List the imports | @@ -433,6 +475,11 @@ searching puzzles by a position, and Lumbra's OTB games. ## Changes +- **draft 1, 2026-11-18**, added to the draft: **opening names** (capability `openingNames`, + `knowledge/openingName`), so a client can name the opening of any line of moves, offline and + with no position skipped, from a list the node holds (cjus/chessgui#755's follow-up). All + optional: a node that doesn't offer it, or a client that doesn't send it, is unchanged. + - **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