diff --git a/README.md b/README.md index 1947fef..80eece8 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,8 @@ the PGN's tags, a game read back whole, a game deleted, and games imported in ba listed, made, and restored with the restore's own backup to undo it. [Draft-1 knowledge](spec/knowledge.md) and `cnp::knowledge` add importing puzzles, evaluated positions and test positions from files a client downloaded: started at once, checked against -their checksum, resumable, and reported as they run. These are +their checksum, resumable, and reported as they run; and read back, with each answer naming +its source. These are proposals, not released CNP domains. ## Using it diff --git a/conformance/README.md b/conformance/README.md index 8821749..e785f23 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's import: what it refuses, with no import started (`spec/knowledge.md`) | Nodes that import puzzles and positions | +| `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 (`spec/knowledge.md`) | Nodes that import puzzles and positions | 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/read-refusals.jsonl b/conformance/knowledge/read-refusals.jsonl new file mode 100644 index 0000000..5701c01 --- /dev/null +++ b/conformance/knowledge/read-refusals.jsonl @@ -0,0 +1,29 @@ +{"session":"knowledge-read-refusals","description":"draft-1 knowledge: reads answer with arrays even when nothing is imported, an analysis of a position says which position it is of, and malformed reads are refused (spec/knowledge.md, Reading)","requires":["knowledge.read"]} +{"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}}}}} +{"send":{"jsonrpc":"2.0","id":2,"method":"knowledge/puzzles"}} +{"expect":{"id":2,"result":{"puzzles":"$array","sources":"$array"}}} +{"send":{"jsonrpc":"2.0","id":3,"method":"knowledge/puzzles","params":{"theme":"noSuchThemeAnywhere","minRating":0,"maxRating":4000,"limit":5}}} +{"expect":{"id":3,"result":{"puzzles":[],"sources":[]}}} +{"send":{"jsonrpc":"2.0","id":4,"method":"knowledge/exercises","params":{"theme":"noSuchThemeAnywhere"}}} +{"expect":{"id":4,"result":{"exercises":[],"sources":[]}}} +{"comment":"A position with no analysis: the position as the node identifies it (the counters are not part of it), and no analyses."} +{"send":{"jsonrpc":"2.0","id":5,"method":"knowledge/analyses","params":{"fen":"4k3/8/8/8/8/8/4P3/4K3 w - - 12 34"}}} +{"expect":{"id":5,"result":{"position":"4k3/8/8/8/8/8/4P3/4K3 w - -","analyses":[],"sources":[]}}} +{"comment":"Refused: a limit of 0, a theme that isn't one, a ratings range backwards, a cursor the node never gave, an illegal position, and a FEN of the wrong shape."} +{"send":{"jsonrpc":"2.0","id":6,"method":"knowledge/puzzles","params":{"limit":0}}} +{"expect":{"id":6,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":7,"method":"knowledge/puzzles","params":{"theme":"mate in 1"}}} +{"expect":{"id":7,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":8,"method":"knowledge/puzzles","params":{"minRating":2000,"maxRating":1000}}} +{"expect":{"id":8,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":9,"method":"knowledge/puzzles","params":{"after":"this was never a cursor"}}} +{"expect":{"id":9,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":10,"method":"knowledge/analyses","params":{"fen":"4k3/8/8/8/8/8/8/8 w - -"}}} +{"expect":{"id":10,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":11,"method":"knowledge/analyses","params":{"fen":"not a fen"}}} +{"expect":{"id":11,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":12,"method":"shutdown"}} +{"expect":{"id":12,"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 ebceb28..c79df42 100644 --- a/crates/cnp/src/knowledge.rs +++ b/crates/cnp/src/knowledge.rs @@ -2,10 +2,11 @@ //! positions from outside sources, which a client hands to the node as downloaded files //! (`spec/knowledge.md`). It doesn't change the CNP 1.0 transport. //! -//! Draft 1 is the import half: [`StartImport`] gives the node a file and a [`Manifest`] saying -//! where it is from, answers at once, and the import runs on; [`ListImports`] reports where -//! each has got to, and [`CancelImport`] stops one. Reading what was imported is the next -//! draft. +//! The import half: [`StartImport`] gives the node a file and a [`Manifest`] saying where it is +//! from, answers at once, and the import runs on; [`ListImports`] reports where each has got +//! to, and [`CancelImport`] stops one. The read half: [`FindPuzzles`] by theme and rating, +//! [`FindAnalyses`] of a position, and [`FindExercises`] by theme, each from complete imports +//! only and naming its [`Source`]s. //! //! **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 @@ -15,6 +16,10 @@ //! **Pitfall: a counted record is a committed record.** [`Import`]'s counts are what has been //! durably stored, so a client that shows progress shows what survives a crash. //! +//! **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. +//! //! **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 //! [`Import::checksum`]; a node never converts one's scores to another's scale. @@ -30,6 +35,16 @@ pub const KIND_LICHESS_PUZZLES: &str = "lichess-puzzles"; pub const KIND_LICHESS_EVALS: &str = "lichess-evals"; /// Kind: a Strategic Test Suite EPD file. pub const KIND_STS_EPD: &str = "sts-epd"; +/// The most items a read answers with, and the largest `limit`. +pub const MAX_LIMIT: u32 = 100; +/// How many items a read answers with when `limit` is left out. +pub const DEFAULT_LIMIT: u32 = 20; +/// The longest theme, in bytes. +pub const MAX_THEME_BYTES: usize = 64; +/// The longest cursor, in bytes. +pub const MAX_CURSOR_BYTES: usize = 256; +/// The longest FEN a read takes, in bytes. +pub const MAX_FEN_BYTES: usize = 128; /// The longest [`ImportParams::path`], in bytes. pub const MAX_PATH_BYTES: usize = 4096; /// The longest manifest text field, in bytes. @@ -52,6 +67,9 @@ pub struct Capabilities { /// `knowledge/import`, `knowledge/status` and `knowledge/cancel` are available. #[serde(default)] pub import: bool, + /// `knowledge/puzzles`, `knowledge/analyses` and `knowledge/exercises` are available. + #[serde(default)] + pub read: bool, /// The kinds of file the node can import ([`KIND_LICHESS_PUZZLES`] and the like). #[serde(default)] pub kinds: Vec, @@ -262,8 +280,10 @@ impl RequestMethod for StartImport { #[serde(from = "Option")] pub struct StatusParams { /// Only imports of this kind. + #[serde(skip_serializing_if = "Option::is_none")] pub kind: Option, /// Only the import with this checksum. + #[serde(skip_serializing_if = "Option::is_none")] pub checksum: Option, } @@ -318,3 +338,344 @@ impl RequestMethod for CancelImport { type Params = CancelParams; type Result = ImportResult; } + +/// One imported file, as a read names where its items came from. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Source { + /// The file's checksum: what an item's `source` says. + pub checksum: String, + /// The kind of file. + pub kind: String, + /// The manifest's `name`. + pub name: String, + /// The manifest's `release`. + pub release: String, + /// The manifest's `license`. + pub license: String, + /// The manifest's `attribution`: shown wherever the source's data is. + pub attribution: String, +} + +/// Whether `text` is a theme: 1 to [`MAX_THEME_BYTES`] letters and digits. +pub fn valid_theme(text: &str) -> bool { + (1..=MAX_THEME_BYTES).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_alphanumeric()) +} + +/// Checks a read's `limit`, `after` and `theme`, or says what is wrong. +fn valid_page( + limit: Option, + after: &Option, + theme: &Option, +) -> Result<(), String> { + if limit.is_some_and(|l| !(1..=MAX_LIMIT).contains(&l)) { + return Err(format!("a limit is 1 to {MAX_LIMIT}")); + } + if after.as_ref().is_some_and(|a| { + a.is_empty() || a.len() > MAX_CURSOR_BYTES || a.chars().any(char::is_control) + }) { + return Err("not a cursor the node gave".into()); + } + if theme.as_ref().is_some_and(|t| !valid_theme(t)) { + return Err(format!( + "a theme is 1 to {MAX_THEME_BYTES} letters and digits" + )); + } + Ok(()) +} + +/// `knowledge/puzzles`' params: all optional, and the params may be left out. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "Option", rename_all = "camelCase")] +pub struct PuzzlesParams { + /// Only puzzles with this theme. + #[serde(skip_serializing_if = "Option::is_none")] + pub theme: Option, + /// Only puzzles rated at least this. + #[serde(skip_serializing_if = "Option::is_none")] + pub min_rating: Option, + /// Only puzzles rated at most this. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_rating: Option, + /// Where the page starts: a `next` the node gave. + #[serde(skip_serializing_if = "Option::is_none")] + pub after: Option, + /// How many, 1 to [`MAX_LIMIT`]; [`DEFAULT_LIMIT`] if left out. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// [`PuzzlesParams`] as they are read, from an object or from nothing. +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct PuzzlesFields { + #[serde(default)] + theme: Option, + #[serde(default)] + min_rating: Option, + #[serde(default)] + max_rating: Option, + #[serde(default)] + after: Option, + #[serde(default)] + limit: Option, +} + +impl From> for PuzzlesParams { + fn from(fields: Option) -> PuzzlesParams { + let f = fields.unwrap_or_default(); + PuzzlesParams { + theme: f.theme, + min_rating: f.min_rating, + max_rating: f.max_rating, + after: f.after, + limit: f.limit, + } + } +} + +impl PuzzlesParams { + /// Checks the params' shapes, or says what is wrong. + pub fn validate(&self) -> Result<(), String> { + valid_page(self.limit, &self.after, &self.theme)?; + if let (Some(min), Some(max)) = (self.min_rating, self.max_rating) + && min > max + { + return Err("minRating is no more than maxRating".into()); + } + Ok(()) + } +} + +/// A puzzle. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Puzzle { + /// The source's identity for it. + pub id: String, + /// The checksum of the [`Source`] it came from. + pub source: String, + /// The position the solver is given: the setup with the first of `moves` played. + pub fen: String, + /// The position before the opponent's move, as the source gave it. + pub setup_fen: String, + /// All the moves in UCI as the source wrote them: the first is the opponent's, the second + /// begins the solution. + pub moves: Vec, + /// The source's rating. + pub rating: i64, + /// The source's rating deviation. + pub rating_deviation: i64, + /// The source's popularity, 100 (best) to -100. + pub popularity: i64, + /// How many times it was played. + pub plays: i64, + /// Its themes, as the source writes them. + pub themes: Vec, + /// The game it comes from, when the source gave one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub game_url: Option, + /// Its opening, when the source gave one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opening_tags: Option, +} + +/// `knowledge/puzzles`' result. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PuzzlesResult { + /// The puzzles, easiest first. + pub puzzles: Vec, + /// The sources of these puzzles. + pub sources: Vec, + /// Where the next page starts, if more may follow. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next: Option, +} + +/// Puzzles from complete imports, easiest first, by theme and rating. +pub enum FindPuzzles {} +impl RequestMethod for FindPuzzles { + const NAME: &'static str = "knowledge/puzzles"; + type Params = PuzzlesParams; + type Result = PuzzlesResult; +} + +/// `knowledge/analyses`' params. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AnalysesParams { + /// A position of four to six fields; counters are ignored. + pub fen: String, + /// How many analyses, 1 to [`MAX_LIMIT`]; [`DEFAULT_LIMIT`] if left out. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +impl AnalysesParams { + /// Checks the params' shapes (not whether the position is legal), or says what is wrong. + pub fn validate(&self) -> Result<(), String> { + valid_page(self.limit, &None, &None)?; + 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(()) + } +} + +/// Whose point of view a score is from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Perspective { + /// White's. + White, + /// The side to move's. + SideToMove, + /// The source doesn't say. Neither sign is to be assumed. + Unspecified, +} + +/// A principal variation of an analysis: a score and the moves. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Line { + /// Centipawns, if it isn't a mate. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cp: Option, + /// Moves to mate, if it is one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mate: Option, + /// The moves in UCI, space-separated, as the source wrote them. + pub moves: String, +} + +/// One analysis of a position: a source's search, with its lines. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Analysis { + /// The checksum of the [`Source`] it came from. + pub source: String, + /// The depth the source reached. + pub depth: i64, + /// Kilonodes the source searched. + pub knodes: i64, + /// Whose point of view the scores are from. + pub perspective: Perspective, + /// The lines, best first as the source ordered them. + pub lines: Vec, +} + +/// `knowledge/analyses`' result. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AnalysesResult { + /// The position as the node identifies it: placement, side to move, castling rights and an + /// en-passant square only if a pawn can use it. A client applies the answer only to a + /// position it matches. + pub position: String, + /// The analyses, deepest first; empty if the sources hold none. + pub analyses: Vec, + /// The sources of these analyses. + pub sources: Vec, +} + +/// What the sources hold of a position. +pub enum FindAnalyses {} +impl RequestMethod for FindAnalyses { + const NAME: &'static str = "knowledge/analyses"; + type Params = AnalysesParams; + type Result = AnalysesResult; +} + +/// `knowledge/exercises`' params: all optional, and the params may be left out. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "Option")] +pub struct ExercisesParams { + /// Only exercises of this theme. + #[serde(skip_serializing_if = "Option::is_none")] + pub theme: Option, + /// Where the page starts: a `next` the node gave. + #[serde(skip_serializing_if = "Option::is_none")] + pub after: Option, + /// How many, 1 to [`MAX_LIMIT`]; [`DEFAULT_LIMIT`] if left out. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// [`ExercisesParams`] as they are read, from an object or from nothing. +#[derive(Default, Deserialize)] +struct ExercisesFields { + #[serde(default)] + theme: Option, + #[serde(default)] + after: Option, + #[serde(default)] + limit: Option, +} + +impl From> for ExercisesParams { + fn from(fields: Option) -> ExercisesParams { + let f = fields.unwrap_or_default(); + ExercisesParams { + theme: f.theme, + after: f.after, + limit: f.limit, + } + } +} + +impl ExercisesParams { + /// Checks the params' shapes, or says what is wrong. + pub fn validate(&self) -> Result<(), String> { + valid_page(self.limit, &self.after, &self.theme) + } +} + +/// A graded candidate move of an exercise. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Candidate { + /// The move in UCI. + #[serde(rename = "move")] + pub uci: String, + /// The points the source's file gave it, on that file's scale. + pub points: i64, +} + +/// A strategic exercise. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Exercise { + /// The source's identity for it, such as `STS(v1.0) Undermine.001`. + pub id: String, + /// The checksum of the [`Source`] it came from. + pub source: String, + /// The suite's own label inside the id. + pub suite: String, + /// Its theme. + pub theme: String, + /// The position: placement, side to move, castling and en passant. + pub fen: String, + /// The best move as the source wrote it (SAN). + pub best: String, + /// The graded candidates in the source's order; a move may appear twice. + pub candidates: Vec, + /// The source's scores as it wrote them, when it did. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scores_text: Option, +} + +/// `knowledge/exercises`' result. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExercisesResult { + /// The exercises. + pub exercises: Vec, + /// The sources of these exercises. + pub sources: Vec, + /// Where the next page starts, if more may follow. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next: Option, +} + +/// Strategic exercises from complete imports, by theme. +pub enum FindExercises {} +impl RequestMethod for FindExercises { + const NAME: &'static str = "knowledge/exercises"; + type Params = ExercisesParams; + type Result = ExercisesResult; +} diff --git a/crates/cnp/tests/knowledge.rs b/crates/cnp/tests/knowledge.rs index f2295a9..f77c2b9 100644 --- a/crates/cnp/tests/knowledge.rs +++ b/crates/cnp/tests/knowledge.rs @@ -8,6 +8,11 @@ fn manifest() -> serde_json::Value { "license":"CC0-1.0","attribution":"Lichess"}) } +fn source() -> serde_json::Value { + json!({"checksum":"a".repeat(64),"kind":"lichess-puzzles","name":"Lichess puzzles", + "release":"2026-11","license":"CC0-1.0","attribution":"Lichess"}) +} + fn params() -> knowledge::ImportParams { serde_json::from_value(json!({"kind":"lichess-puzzles", "path":"/Users/carlos/Downloads/lichess_db_puzzle.csv.zst","manifest":manifest()})) @@ -155,6 +160,8 @@ fn the_specs_json_examples_are_valid() { let text = block .replace("3f1c0d…64 hex digits…9a", &full) .replace("3f1c0d…9a", &full) + .replace("{ ... a source ... }", &source().to_string()) + .replace("\"next\": \"…\"", "\"next\": \"x\"") .replace("{ ... a manifest ... }", &manifest().to_string()) .replace("{ ... an import, verifying ... }", "{\"kind\":\"k\",\"checksum\":\"a\",\"name\":\"n\",\"release\":\"r\",\"state\":\"verifying\",\"read\":0,\"accepted\":0,\"rejected\":0,\"duplicate\":0,\"startedAt\":\"2026-11-13T10:05:00.000Z\"}") .replace("{ ... an import ... }", "{\"kind\":\"k\",\"checksum\":\"a\",\"name\":\"n\",\"release\":\"r\",\"state\":\"complete\",\"read\":0,\"accepted\":0,\"rejected\":0,\"duplicate\":0,\"startedAt\":\"2026-11-13T10:05:00.000Z\"}"); @@ -172,6 +179,34 @@ fn the_specs_json_examples_are_valid() { serde_json::from_value::(value).unwrap(); } else if value.get("imports").is_some() { serde_json::from_value::(value).unwrap(); + } 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("analyses").is_some() { + let r: knowledge::AnalysesResult = serde_json::from_value(value).unwrap(); + assert_eq!( + r.analyses[0].perspective, + knowledge::Perspective::Unspecified + ); + } 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"); + } else if value.get("minRating").is_some() { + serde_json::from_value::(value) + .unwrap() + .validate() + .unwrap(); + } else if value.get("fen").is_some() { + serde_json::from_value::(value) + .unwrap() + .validate() + .unwrap(); + } else if value.get("checksum").is_some() + && value.get("kind").is_some() + && value.get("attribution").is_some() + && value.get("state").is_none() + { + serde_json::from_value::(value).unwrap(); } else if value.get("license").is_some() { serde_json::from_value::(value) .unwrap() @@ -179,10 +214,119 @@ fn the_specs_json_examples_are_valid() { .unwrap(); } else if value.get("state").is_some() { serde_json::from_value::(value).unwrap(); + } else if value.get("theme").is_some() { + serde_json::from_value::(value) + .unwrap() + .validate() + .unwrap(); } else if value.get("path").is_none() { serde_json::from_value::(value).unwrap(); } checked += 1; } - assert!(checked >= 7, "only {checked} examples"); + assert!(checked >= 14, "only {checked} examples"); +} + +#[test] +fn the_read_capability_is_separate_from_import() { + let c: knowledge::Capabilities = + serde_json::from_value(json!({"import":true,"contract":"draft-1"})).unwrap(); + assert!(c.import && !c.read); + let c: knowledge::Capabilities = + serde_json::from_value(json!({"read":true,"kinds":["sts-epd"],"contract":"draft-1"})) + .unwrap(); + assert!(c.read && !c.import); +} + +#[test] +fn read_params_may_be_left_out_are_checked_and_skip_what_isnt_set() { + let none: knowledge::PuzzlesParams = serde_json::from_value(json!(null)).unwrap(); + assert_eq!(none, knowledge::PuzzlesParams::default()); + assert!(none.validate().is_ok()); + assert_eq!(serde_json::to_value(&none).unwrap(), json!({})); + let p: knowledge::PuzzlesParams = serde_json::from_value( + json!({"theme":"mateIn1","minRating":1000,"maxRating":1400,"limit":10,"future":1}), + ) + .unwrap(); + assert_eq!( + (p.min_rating, p.max_rating, p.limit), + (Some(1000), Some(1400), Some(10)) + ); + let request = Request::new::(1, &p); + assert_eq!(request.method, "knowledge/puzzles"); + assert_eq!(request.params::().unwrap(), p); + for bad in [ + json!({"limit":0}), + json!({"limit":101}), + json!({"theme":"mate in 1"}), + json!({"theme":""}), + json!({"minRating":1500,"maxRating":1000}), + json!({"after":""}), + json!({"after":"x".repeat(knowledge::MAX_CURSOR_BYTES + 1)}), + ] { + let params: knowledge::PuzzlesParams = serde_json::from_value(bad.clone()).unwrap(); + assert!(params.validate().is_err(), "{bad}"); + } + let e: knowledge::ExercisesParams = serde_json::from_value(json!(null)).unwrap(); + assert!(e.validate().is_ok()); + assert!( + knowledge::ExercisesParams { + limit: Some(0), + ..e + } + .validate() + .is_err() + ); +} + +#[test] +fn analyses_params_need_a_fen_of_four_or_six_fields() { + let ok = |fen: &str| { + knowledge::AnalysesParams { + fen: fen.into(), + limit: None, + } + .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()); + assert!( + knowledge::AnalysesParams { + fen: "a b c d".into(), + limit: Some(0) + } + .validate() + .is_err() + ); + let missing: Result = serde_json::from_value(json!({"limit":5})); + assert!(missing.is_err()); +} + +#[test] +fn perspectives_and_candidates_are_written_as_the_spec_has_them() { + for (p, text) in [ + (knowledge::Perspective::White, "white"), + (knowledge::Perspective::SideToMove, "sideToMove"), + (knowledge::Perspective::Unspecified, "unspecified"), + ] { + assert_eq!(serde_json::to_value(p).unwrap(), json!(text)); + } + let c = knowledge::Candidate { + uci: "e2e4".into(), + points: 10, + }; + assert_eq!( + serde_json::to_value(&c).unwrap(), + json!({"move":"e2e4","points":10}) + ); + // A mate line has no cp; a centipawn line has no mate. + let line: knowledge::Line = serde_json::from_value(json!({"mate":1,"moves":"h5f7"})).unwrap(); + assert_eq!((line.cp, line.mate), (None, Some(1))); + assert_eq!( + serde_json::to_value(&line).unwrap(), + json!({"mate":1,"moves":"h5f7"}) + ); } diff --git a/spec/knowledge.md b/spec/knowledge.md index 83a3a02..a4fec41 100644 --- a/spec/knowledge.md +++ b/spec/knowledge.md @@ -8,9 +8,10 @@ program's data, such as chessdb, beside the [preferences](preferences.md), [game and [backups](backups.md) extensions. The knowledge is what the player didn't make: puzzles, evaluated positions and strategic test -positions from outside sources. Draft 1 has the first half of the domain: **a client hands the -node a file it has downloaded, and the node imports it.** Asking for what was imported (puzzles -by theme and rating, the analyses of a position) is the next draft. +positions from outside sources. The domain has two halves: **a client hands the node a file it +has downloaded, and the node imports it** (`import`), and **a client asks for what was +imported** (`read`): puzzles by theme and rating, the analyses of a position, and strategic +exercises by theme. The node doesn't download. The client fetches the file, where it can show the licence, the size and the progress, and tells the node where the file is. The node checks the file against @@ -19,12 +20,13 @@ the checksum the client says it has, so a damaged or swapped download is refused ## Capability ```json -{"capabilities": {"knowledge": {"import": true, +{"capabilities": {"knowledge": {"import": true, "read": true, "kinds": ["lichess-puzzles", "lichess-evals", "sts-epd"], "contract": "draft-1"}}} ``` -`import` offers `knowledge/import`, `knowledge/status` and `knowledge/cancel`. A missing switch -is false. `kinds` are the kinds of file the node can import; a request for another kind is +`import` offers `knowledge/import`, `knowledge/status` and `knowledge/cancel`; `read` offers +`knowledge/puzzles`, `knowledge/analyses` and `knowledge/exercises`. 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). @@ -157,6 +159,104 @@ with the import, `cancelled`. What it committed stays, and importing the file ag Cancelling an import that isn't running answers with its state unchanged; one the node has no record of is -32025. +## Reading + +Reads answer from **complete imports only**: a file that is half imported, cancelled or failed +doesn't make a corpus that looks whole. Every result names where its items came from, so a +client can show the licence and attribution the manifest gave. + +A **source** is one imported file: + +```json +{"checksum": "3f1c0d…9a", "kind": "lichess-puzzles", "name": "Lichess puzzles", + "release": "2026-11", "license": "CC0-1.0", "attribution": "Lichess"} +``` + +Each result has `sources`, the sources of the items in it, and each item's `source` is a +source's `checksum`. A client must show a source's `attribution` wherever it shows its data. + +Lists are **paged by an opaque cursor**: a result's `next`, present when more may follow, is +passed back as `after`. A cursor is the node's own; one it didn't give, or one from another +kind of request, is -32602. `limit` is 1–100, 20 if left out. + +### `knowledge/puzzles` + +```json +{"theme": "mateIn1", "minRating": 1000, "maxRating": 1400, "limit": 10} +``` + +Every field is optional. `theme` is a theme as the source writes it (1–64 letters and digits); +the ratings are whole numbers, `minRating` no more than `maxRating`. Puzzles come **easiest +first** (by rating, then by identity). Answers: + +```json +{"puzzles": [{"id": "00008", "source": "3f1c0d…9a", + "fen": "r6k/pp2r2p/4Rp1Q/3p4/8/1N1P2b1/PqP3PP/7K w - - 0 25", + "setupFen": "r6k/pp2r2p/4Rp1Q/3p4/8/1N1P2R1/PqP2bPP/7K b - - 0 24", + "moves": ["f2g3", "e6e7", "b2b1", "b3c1", "b1c1", "h6c1"], "rating": 1819, + "ratingDeviation": 77, "popularity": 95, "plays": 10446, + "themes": ["crushing", "hangingPiece", "long", "middlegame"], + "gameUrl": "https://lichess.org/game/787zsVup/black#48"}], + "sources": [{ ... a source ... }], "next": "…"} +``` + +`fen` is the position **the solver is given**: the setup with the first of `moves` played, the +opponent's move. `setupFen` is the position before it, as the source gave it, and `moves` are +all the moves in UCI as the source wrote them: the first is the opponent's, and the second +begins the solution. (Every move of the solution is the only move, but for a mate in one, where +any mate does; that is the source's rule, and the node keeps no chess to check it.) +`ratingDeviation`, `popularity` and `plays` are the source's. `gameUrl` and `openingTags` are +there when the source gave them. + +### `knowledge/analyses` + +```json +{"fen": "r1bqkb1r/pppp1ppp/2n2n2/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR w KQkq -", "limit": 5} +``` + +`fen` is a position of four to six fields; the counters, if any, are ignored. Answers with what +the sources hold of **that position**, deepest first: + +```json +{"position": "r1bqkb1r/pppp1ppp/2n2n2/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR w KQkq -", + "analyses": [{"source": "3f1c0d…9a", "depth": 20, "knodes": 10, "perspective": "unspecified", + "lines": [{"mate": 1, "moves": "h5f7"}]}], "sources": [{ ... a source ... }]} +``` + +`position` is the position as the node identifies it: placement, side to move, castling rights +and an en-passant square only if a pawn can use it (the counters aren't part of it). **A client +applies an answer only to the position it asked about**: it compares `position` with its own +current position, since a game can move on while the answer is on its way, and an analysis of +another position must not be shown against it. + +An analysis is the source's search, not this node's: its `depth`, `knodes` and `lines` as the +source gave them, each line with a `cp` (centipawns) or a `mate` score and its moves in UCI. +`perspective` says whose point of view a score is from: `white`, `sideToMove`, or +`unspecified` when the source doesn't say (Lichess doesn't). A client doesn't treat an +`unspecified` score's sign as either. An analysis is of a position without its history, so a +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/exercises` + +```json +{"theme": "Undermine", "limit": 10} +``` + +Strategic exercises, by theme if given, in the order of their sources and identities: + +```json +{"exercises": [{"id": "STS(v1.0) Undermine.001", "source": "3f1c0d…9a", "suite": "STS(v1.0)", + "theme": "Undermine", "fen": "1kr5/3n4/q3p2p/p2n2p1/PppB1P2/5BP1/1P2Q2P/3R2K1 w - -", + "best": "f5", "candidates": [{"move": "f4f5", "points": 10}, {"move": "d4e5", "points": 2}], + "scoresText": "f5=10, Be5+=2"}], "sources": [{ ... a source ... }], "next": "…"} +``` + +`candidates` are the graded moves in UCI with the points **the source's file gave them**, in its +order; a move may appear twice with different points, as the published files have it. Points +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. + ## Pitfalls - **The path is the client's.** A node reads whatever file its client names, and the client @@ -176,7 +276,7 @@ record of is -32025. | Error | Meaning | Client action | | --- | --- | --- | -| -32602 | Invalid params: an unknown kind, or a malformed path, manifest or checksum | Correct the request | +| -32602 | Invalid params: an unknown kind, or a malformed path, manifest, checksum, theme, rating, limit, cursor or FEN | Correct the request | | -32013 | Busy: another import is running | Wait for it, or cancel it | | -32022 | Storage or I/O failed | Ask `knowledge/status` for the import's state | | -32025 | No import with that identity | List the imports | @@ -185,6 +285,5 @@ record of is -32025. ## Not in draft 1 -Reading the knowledge (puzzles by theme and rating, the analyses of a position, strategic -exercises), progress notifications in place of polling, reading the records an import -rejected, removing an import's knowledge, and Lumbra's OTB games. +Progress notifications in place of polling, reading the records an import rejected, removing +an import's knowledge, searching puzzles by opening or by a position, and Lumbra's OTB games.