diff --git a/README.md b/README.md index b95ba82..1947fef 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,10 @@ revision-checked patches and durable retry receipts for review with chessdb. that are safe to repeat, a list newest first that can be searched by the players' names and the PGN's tags, a game read back whole, a game deleted, and games imported in batches. [Draft-1 backups](spec/backups.md) and `cnp::backups` add snapshots of all a node keeps, -listed, made, and restored with the restore's own backup to undo it. These are +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 proposals, not released CNP domains. ## Using it diff --git a/conformance/README.md b/conformance/README.md index 3a6b8ca..8821749 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -20,6 +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 | 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/import-refusals.jsonl b/conformance/knowledge/import-refusals.jsonl new file mode 100644 index 0000000..f6b97b3 --- /dev/null +++ b/conformance/knowledge/import-refusals.jsonl @@ -0,0 +1,25 @@ +{"session":"knowledge-import-refusals","description":"draft-1 knowledge: no imports to start with, a malformed or relative request is refused, a file that isn't there is refused with no import started, and an import that doesn't exist can't be cancelled (spec/knowledge.md)","requires":["knowledge.import"]} +{"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","import":true,"kinds":"$array"}}}}} +{"send":{"jsonrpc":"2.0","id":2,"method":"knowledge/status"}} +{"expect":{"id":2,"result":{"imports":"$array"}}} +{"comment":"A path that isn't absolute is invalid params."} +{"send":{"jsonrpc":"2.0","id":3,"method":"knowledge/import","params":{"kind":"lichess-puzzles","path":"Downloads/puzzles.csv.zst","manifest":{"name":"Lichess puzzles","release":"2026-11","url":"https://database.lichess.org/","retrievedAt":"2026-11-13T10:02:11.000Z","checksum":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","license":"CC0-1.0","attribution":"Lichess"}}}} +{"expect":{"id":3,"error":{"code":-32602}}} +{"comment":"A checksum that isn't 64 hex digits is invalid params."} +{"send":{"jsonrpc":"2.0","id":4,"method":"knowledge/import","params":{"kind":"lichess-puzzles","path":"/cnp-conformance/no-such-file.csv.zst","manifest":{"name":"Lichess puzzles","release":"2026-11","url":"https://database.lichess.org/","retrievedAt":"2026-11-13T10:02:11.000Z","checksum":"abc","license":"CC0-1.0","attribution":"Lichess"}}}} +{"expect":{"id":4,"error":{"code":-32602}}} +{"comment":"A kind no node lists is invalid params."} +{"send":{"jsonrpc":"2.0","id":5,"method":"knowledge/import","params":{"kind":"no-such-kind","path":"/cnp-conformance/no-such-file","manifest":{"name":"x","release":"1","url":"https://example.com/","retrievedAt":"2026-11-13T10:02:11.000Z","checksum":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","license":"CC0-1.0","attribution":"x"}}}} +{"expect":{"id":5,"error":{"code":-32602}}} +{"comment":"A file that isn't there: refused, and no import is started."} +{"send":{"jsonrpc":"2.0","id":6,"method":"knowledge/import","params":{"kind":"lichess-puzzles","path":"/cnp-conformance/no-such-file.csv.zst","manifest":{"name":"Lichess puzzles","release":"2026-11","url":"https://database.lichess.org/","retrievedAt":"2026-11-13T10:02:11.000Z","checksum":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","license":"CC0-1.0","attribution":"Lichess"}}}} +{"expect":{"id":6,"error":{"code":-32027}}} +{"send":{"jsonrpc":"2.0","id":7,"method":"knowledge/status","params":{"kind":"lichess-puzzles","checksum":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}} +{"expect":{"id":7,"error":{"code":-32025}}} +{"send":{"jsonrpc":"2.0","id":8,"method":"knowledge/cancel","params":{"kind":"lichess-puzzles","checksum":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}} +{"expect":{"id":8,"error":{"code":-32025}}} +{"send":{"jsonrpc":"2.0","id":9,"method":"shutdown"}} +{"expect":{"id":9,"result":null}} +{"send":{"jsonrpc":"2.0","method":"exit"}} +{"expectExit":0} diff --git a/crates/cnp/src/knowledge.rs b/crates/cnp/src/knowledge.rs new file mode 100644 index 0000000..ebceb28 --- /dev/null +++ b/crates/cnp/src/knowledge.rs @@ -0,0 +1,320 @@ +//! Proposed draft-1 knowledge extension: puzzles, evaluated positions and strategic test +//! 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 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 +//! reading a record ([`State::Verifying`]), so a damaged or swapped download is +//! [`FailureCode::Checksum`], not imported. +//! +//! **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: 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. +use crate::RequestMethod; +use serde::{Deserialize, Serialize}; + +/// Review identifier, in [`Capabilities::contract`]. Clients must check it before sending +/// knowledge requests. +pub const CONTRACT: &str = "draft-1"; +/// Kind: Lichess's puzzle database (CSV). +pub const KIND_LICHESS_PUZZLES: &str = "lichess-puzzles"; +/// Kind: Lichess's evaluations (JSON Lines). +pub const KIND_LICHESS_EVALS: &str = "lichess-evals"; +/// Kind: a Strategic Test Suite EPD file. +pub const KIND_STS_EPD: &str = "sts-epd"; +/// The longest [`ImportParams::path`], in bytes. +pub const MAX_PATH_BYTES: usize = 4096; +/// The longest manifest text field, in bytes. +pub const MAX_FIELD_BYTES: usize = 1024; +/// The length of a checksum: SHA-256 in hexadecimal. +pub const CHECKSUM_LEN: usize = 64; +/// The most imports one [`ListImports`] answer holds: the newest. +pub const MAX_LISTED: usize = 100; +/// Storage or I/O failed. +pub const STORAGE_FAILURE: i64 = -32022; +/// No import has the identity asked for. +pub const NOT_FOUND: i64 = -32025; +/// The file doesn't exist, isn't a file, or can't be read: no import started. +pub const FILE_UNREADABLE: i64 = -32027; + +/// The optional knowledge domain. Missing switches mean false. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Capabilities { + /// `knowledge/import`, `knowledge/status` and `knowledge/cancel` are available. + #[serde(default)] + pub import: bool, + /// The kinds of file the node can import ([`KIND_LICHESS_PUZZLES`] and the like). + #[serde(default)] + pub kinds: Vec, + /// The contract the node implements, [`CONTRACT`]; absent means don't send knowledge + /// requests. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub contract: Option, +} + +/// Where a file is from, kept by the node with everything it imports. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Manifest { + /// The source, such as `Lichess puzzles`. + pub name: String, + /// Its release, such as `2026-11`. + pub release: String, + /// Where it was downloaded from. + pub url: String, + /// When it was downloaded: UTC, RFC 3339 with milliseconds. + pub retrieved_at: String, + /// SHA-256 of the file as downloaded (the compressed file, for `.zst`): 64 hexadecimal + /// digits, either case. + pub checksum: String, + /// An SPDX identifier, such as `CC0-1.0`. + pub license: String, + /// What to credit, to show wherever the data is used. + pub attribution: String, +} + +/// Whether `text` is a field of a manifest: 1 to [`MAX_FIELD_BYTES`] bytes, no control +/// characters. +fn valid_field(text: &str) -> bool { + (1..=MAX_FIELD_BYTES).contains(&text.len()) && !text.chars().any(char::is_control) +} + +/// Whether `text` is a checksum: [`CHECKSUM_LEN`] hexadecimal digits. +pub fn valid_checksum(text: &str) -> bool { + text.len() == CHECKSUM_LEN && text.bytes().all(|b| b.is_ascii_hexdigit()) +} + +impl Manifest { + /// Checks the manifest's shapes, or says what is wrong. + pub fn validate(&self) -> Result<(), String> { + for (name, text) in [ + ("name", &self.name), + ("release", &self.release), + ("url", &self.url), + ("retrievedAt", &self.retrieved_at), + ("license", &self.license), + ("attribution", &self.attribution), + ] { + if !valid_field(text) { + return Err(format!( + "a manifest's {name} is 1 to {MAX_FIELD_BYTES} bytes without control characters" + )); + } + } + if !valid_checksum(&self.checksum) { + return Err(format!( + "a manifest's checksum is {CHECKSUM_LEN} hexadecimal digits (SHA-256)" + )); + } + Ok(()) + } +} + +/// `knowledge/import`'s params. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ImportParams { + /// The kind of file ([`KIND_LICHESS_PUZZLES`] and the like): one the node lists. + pub kind: String, + /// An absolute path, on the computer the node runs on, of the file as downloaded. The node + /// only reads it. + pub path: String, + /// Where the file is from. + pub manifest: Manifest, +} + +impl ImportParams { + /// Checks the params' shapes (not whether the node offers the kind), or says what is wrong. + pub fn validate(&self) -> Result<(), String> { + if self.kind.is_empty() + || self.kind.len() > 32 + || !self + .kind + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + { + return Err("a kind is up to 32 lowercase letters, digits and hyphens".into()); + } + if self.path.is_empty() || self.path.len() > MAX_PATH_BYTES || self.path.contains('\0') { + return Err(format!("a path is 1 to {MAX_PATH_BYTES} bytes without NUL")); + } + if !is_absolute(&self.path) { + return Err("a path is absolute".into()); + } + self.manifest.validate() + } +} + +/// Whether `path` is absolute on Unix (`/…`) or Windows (`C:\…`, `C:/…`, `\\server\…`). +fn is_absolute(path: &str) -> bool { + let bytes = path.as_bytes(); + path.starts_with('/') + || path.starts_with("\\\\") + || (bytes.len() >= 3 + && bytes[0].is_ascii_alphabetic() + && bytes[1] == b':' + && (bytes[2] == b'\\' || bytes[2] == b'/')) +} + +/// Where an import is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum State { + /// The node is reading the whole file to check its checksum, before any record. + Verifying, + /// Records are being read and stored. + Importing, + /// The file was read to its end. + Complete, + /// Stopped by a client or the node's shutdown, or found interrupted when the node started. + /// Importing the file again resumes it. + Cancelled, + /// Stopped by a failure ([`Import::failure`]). Importing the file again resumes it. + Failed, +} + +/// Why an import failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FailureCode { + /// The file isn't the one the manifest describes. + Checksum, + /// The file stopped being readable. + Unreadable, + /// The file isn't of the kind, or all of it was rejected. + Format, + /// There isn't enough free space. + Disk, + /// Reading the file failed part-way, as a truncated download does. + Stream, + /// The node's own storage failed. + Storage, +} + +/// A failed import's reason. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Failure { + /// The reason, for a client to act on. + pub code: FailureCode, + /// The reason, for a person. + pub message: String, +} + +/// An import: one file of one kind, and what has become of it so far. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Import { + /// The kind of file. + pub kind: String, + /// The file's checksum, from its manifest: with the kind, the import's identity. + pub checksum: String, + /// The manifest's `name`. + pub name: String, + /// The manifest's `release`. + pub release: String, + /// Where it is. + pub state: State, + /// Records read so far, the rejected included: `accepted + rejected + duplicate`. + pub read: u64, + /// Records stored. + pub accepted: u64, + /// Records found invalid, kept apart by the node and not stored as knowledge. + pub rejected: u64, + /// Records already stored. + pub duplicate: u64, + /// Why it failed, when [`State::Failed`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure: Option, + /// When it started: UTC, RFC 3339 with milliseconds. + pub started_at: String, + /// When it completed, once [`State::Complete`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finished_at: Option, +} + +/// The result of `knowledge/import` and `knowledge/cancel`: the import. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ImportResult { + /// The import, as it is when the node answers. + pub import: Import, +} + +/// Starts an import of a downloaded file, or resumes or reports the one with the same kind and +/// checksum. Answers at once; the import runs on. One import runs at a time: another is Busy +/// (-32013). A file that can't be read is [`FILE_UNREADABLE`]. +pub enum StartImport {} +impl RequestMethod for StartImport { + const NAME: &'static str = "knowledge/import"; + type Params = ImportParams; + type Result = ImportResult; +} + +/// `knowledge/status`'s params: both fields optional, and the params may be left out. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "Option")] +pub struct StatusParams { + /// Only imports of this kind. + pub kind: Option, + /// Only the import with this checksum. + pub checksum: Option, +} + +/// [`StatusParams`] as they are read, from an object or from nothing. +#[derive(Default, Deserialize)] +struct StatusFields { + #[serde(default)] + kind: Option, + #[serde(default)] + checksum: Option, +} + +impl From> for StatusParams { + fn from(fields: Option) -> StatusParams { + let fields = fields.unwrap_or_default(); + StatusParams { + kind: fields.kind, + checksum: fields.checksum, + } + } +} + +/// `knowledge/status`'s result: the imports, newest first, at most [`MAX_LISTED`]. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StatusResult { + /// The imports. + pub imports: Vec, +} + +/// Reports imports. With a kind and a checksum, that import ([`NOT_FOUND`] if there is none). +pub enum ListImports {} +impl RequestMethod for ListImports { + const NAME: &'static str = "knowledge/status"; + type Params = StatusParams; + type Result = StatusResult; +} + +/// `knowledge/cancel`'s params: the import's identity. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CancelParams { + /// The kind of file. + pub kind: String, + /// The file's checksum. + pub checksum: String, +} + +/// Stops an import at its next batch and answers when it has stopped. What it committed stays. +/// Cancelling one that isn't running answers with its state unchanged. +pub enum CancelImport {} +impl RequestMethod for CancelImport { + const NAME: &'static str = "knowledge/cancel"; + type Params = CancelParams; + type Result = ImportResult; +} diff --git a/crates/cnp/src/lib.rs b/crates/cnp/src/lib.rs index 00b429e..21c995e 100644 --- a/crates/cnp/src/lib.rs +++ b/crates/cnp/src/lib.rs @@ -12,9 +12,10 @@ //! - [`engine`]: searching positions (`engine/…`); //! - [`voice`]: text to speech, speech to text, and listening to speech as it comes //! (`voice/…`); -//! - [`preferences`], [`games`] and [`backups`]: proposed draft extensions for a node that -//! keeps a program's settings and its library of games, and backs them up -//! (`preferences/…`, `games/…`, `backups/…`); +//! - [`preferences`], [`games`], [`backups`] and [`knowledge`]: proposed draft extensions for a +//! node that keeps a program's settings and its library of games, backs them up, and imports +//! puzzles and positions from outside sources (`preferences/…`, `games/…`, `backups/…`, +//! `knowledge/…`); //! - [`stdio`]: reading and writing messages, one per line. //! //! The crate has no runtime and no threads of its own: a program reads messages in a loop of @@ -47,6 +48,7 @@ pub mod backups; pub mod engine; pub mod games; +pub mod knowledge; pub mod lifecycle; pub mod message; pub mod method; diff --git a/crates/cnp/src/lifecycle.rs b/crates/cnp/src/lifecycle.rs index 0b683b1..1d7b8b2 100644 --- a/crates/cnp/src/lifecycle.rs +++ b/crates/cnp/src/lifecycle.rs @@ -180,6 +180,9 @@ pub struct Capabilities { /// Proposed draft backups domain (`backups/…`); clients must also check its contract. #[serde(default, skip_serializing_if = "Option::is_none")] pub backups: Option, + /// Proposed draft knowledge domain (`knowledge/…`); clients must also check its contract. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub knowledge: Option, /// The engine domain (`engine/…`). #[serde(default, skip_serializing_if = "Option::is_none")] pub engine: Option, diff --git a/crates/cnp/tests/knowledge.rs b/crates/cnp/tests/knowledge.rs new file mode 100644 index 0000000..f2295a9 --- /dev/null +++ b/crates/cnp/tests/knowledge.rs @@ -0,0 +1,188 @@ +//! Draft knowledge wire compatibility and typed round trips. +use cnp::{Request, knowledge, lifecycle}; +use serde_json::json; + +fn manifest() -> serde_json::Value { + json!({"name":"Lichess puzzles","release":"2026-11","url":"https://database.lichess.org/", + "retrievedAt":"2026-11-13T10:02:11.000Z","checksum":"a".repeat(64), + "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()})) + .unwrap() +} + +#[test] +fn the_capability_names_its_kinds_and_contract_and_older_nodes_have_none() { + let value = json!({"protocol":"1.0","node":{"name":"chessdb","version":"0.1","license":"x"}, + "capabilities":{"knowledge":{"import":true,"kinds":["lichess-puzzles","sts-epd"], + "contract":"draft-1","future":1}}}); + let result: lifecycle::InitializeResult = serde_json::from_value(value).unwrap(); + let offered = result.capabilities.knowledge.unwrap(); + assert!(offered.import); + assert_eq!(offered.kinds, ["lichess-puzzles", "sts-epd"]); + assert_eq!(offered.contract.as_deref(), Some(knowledge::CONTRACT)); + let older: lifecycle::InitializeResult = serde_json::from_value(json!({"protocol":"1.0", + "node":{"name":"chessdb","version":"0.1","license":"x"},"capabilities":{"backups":{}}})) + .unwrap(); + assert!(older.capabilities.knowledge.is_none()); +} + +#[test] +fn an_import_request_reads_as_the_spec_writes_it() { + let p = params(); + assert!(p.validate().is_ok()); + let request = Request::new::(1, &p); + assert_eq!(request.method, "knowledge/import"); + assert_eq!(request.params::().unwrap(), p); + assert_eq!(serde_json::to_value(&p.manifest).unwrap(), manifest()); +} + +#[test] +fn params_with_a_bad_shape_say_what_is_wrong() { + let mut p = params(); + p.path = "Downloads/x.zst".into(); + assert!(p.validate().unwrap_err().contains("absolute")); + for ok in ["/a", "C:\\Users\\x", "D:/x", "\\\\server\\share\\x"] { + p.path = ok.into(); + assert!(p.validate().is_ok(), "{ok}"); + } + for bad in [ + "", + "a\0b", + "relative/x", + &format!("/{}", "x".repeat(knowledge::MAX_PATH_BYTES)), + ] { + p.path = bad.into(); + assert!(p.validate().is_err(), "{bad:?}"); + } + p = params(); + p.kind = "Lichess Puzzles".into(); + assert!(p.validate().is_err()); + for edit in [ + |m: &mut knowledge::Manifest| m.checksum = "abc".into(), + |m: &mut knowledge::Manifest| m.checksum = "z".repeat(64), + |m: &mut knowledge::Manifest| m.license = " ".repeat(0), + |m: &mut knowledge::Manifest| m.attribution = "a\nb".into(), + |m: &mut knowledge::Manifest| m.url = "u".repeat(knowledge::MAX_FIELD_BYTES + 1), + ] { + p = params(); + edit(&mut p.manifest); + assert!(p.validate().is_err()); + } + // Either case of hex is a checksum. + assert!(knowledge::valid_checksum(&"Ab".repeat(32))); +} + +#[test] +fn an_import_reads_and_writes_with_its_state_and_failure() { + let value = json!({"kind":"lichess-puzzles","checksum":"a".repeat(64),"name":"Lichess puzzles", + "release":"2026-11","state":"importing","read":120000,"accepted":119871,"rejected":3, + "duplicate":126,"startedAt":"2026-11-13T10:05:00.000Z","future":true}); + let import: knowledge::Import = serde_json::from_value(value).unwrap(); + assert_eq!(import.state, knowledge::State::Importing); + assert_eq!( + import.read, + import.accepted + import.rejected + import.duplicate + ); + assert!(import.failure.is_none() && import.finished_at.is_none()); + let written = serde_json::to_value(&import).unwrap(); + assert!(written.get("failure").is_none() && written.get("finishedAt").is_none()); + for (state, text) in [ + (knowledge::State::Verifying, "verifying"), + (knowledge::State::Importing, "importing"), + (knowledge::State::Complete, "complete"), + (knowledge::State::Cancelled, "cancelled"), + (knowledge::State::Failed, "failed"), + ] { + assert_eq!(serde_json::to_value(state).unwrap(), json!(text)); + } + let failed: knowledge::Import = serde_json::from_value(json!({"kind":"sts-epd", + "checksum":"b".repeat(64),"name":"STS","release":"v3","state":"failed","read":0, + "accepted":0,"rejected":0,"duplicate":0, + "failure":{"code":"checksum","message":"not the file the manifest describes"}, + "startedAt":"2026-11-13T10:05:00.000Z"})) + .unwrap(); + assert_eq!( + failed.failure.unwrap().code, + knowledge::FailureCode::Checksum + ); +} + +#[test] +fn status_params_may_be_left_out_and_cancel_names_an_identity() { + let none = Request::new::(2, &knowledge::StatusParams::default()); + assert_eq!(none.method, "knowledge/status"); + let from_nothing: knowledge::StatusParams = serde_json::from_value(json!(null)).unwrap(); + assert_eq!(from_nothing, knowledge::StatusParams::default()); + let one: knowledge::StatusParams = + serde_json::from_value(json!({"kind":"sts-epd","checksum":"b".repeat(64)})).unwrap(); + assert_eq!(one.kind.as_deref(), Some("sts-epd")); + let cancel = Request::new::( + 3, + &knowledge::CancelParams { + kind: "sts-epd".into(), + checksum: "b".repeat(64), + }, + ); + assert_eq!(cancel.method, "knowledge/cancel"); + let bad: Result = serde_json::from_value(json!({"kind":"x"})); + assert!(bad.is_err()); +} + +#[test] +fn the_specs_json_examples_are_valid() { + const SPEC: &str = include_str!("../../../spec/knowledge.md"); + let mut blocks = Vec::new(); + let mut open: Option = None; + for line in SPEC.lines() { + match (&mut open, line.trim_end()) { + (None, "```json") => open = Some(String::new()), + (Some(_), "```") => blocks.push(open.take().unwrap()), + (Some(text), l) => { + text.push_str(l); + text.push('\n'); + } + _ => {} + } + } + // Blocks with `…` are abridged on purpose (a checksum); fill them in before parsing. + let full = "a".repeat(64); + let mut checked = 0; + for block in blocks { + let text = block + .replace("3f1c0d…64 hex digits…9a", &full) + .replace("3f1c0d…9a", &full) + .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\"}"); + let value: serde_json::Value = + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}: {text}")); + if let Some(c) = value.pointer("/capabilities/knowledge") { + let c: knowledge::Capabilities = serde_json::from_value(c.clone()).unwrap(); + assert_eq!(c.contract.as_deref(), Some(knowledge::CONTRACT)); + } else if value.get("manifest").is_some() { + serde_json::from_value::(value) + .unwrap() + .validate() + .unwrap(); + } else if value.get("import").is_some() { + serde_json::from_value::(value).unwrap(); + } else if value.get("imports").is_some() { + serde_json::from_value::(value).unwrap(); + } else if value.get("license").is_some() { + serde_json::from_value::(value) + .unwrap() + .validate() + .unwrap(); + } else if value.get("state").is_some() { + serde_json::from_value::(value).unwrap(); + } else if value.get("path").is_none() { + serde_json::from_value::(value).unwrap(); + } + checked += 1; + } + assert!(checked >= 7, "only {checked} examples"); +} diff --git a/spec/knowledge.md b/spec/knowledge.md new file mode 100644 index 0000000..83a3a02 --- /dev/null +++ b/spec/knowledge.md @@ -0,0 +1,190 @@ +# Knowledge over CNP — draft 1 + +This is a **proposed CNP extension**, submitted for review alongside chessdb's knowledge +library (cjus/chessdb#2) and Solrac's downloads (cjus/chessgui). It is not an accepted addition +to upstream CNP. It uses CNP 1.0's transport, lifecycle, envelopes and error codes unchanged; +the typed Rust markers and limits are `cnp::knowledge`. It is served by a node that keeps a +program's data, such as chessdb, beside the [preferences](preferences.md), [games](games.md) +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. + +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 +the checksum the client says it has, so a damaged or swapped download is refused, not imported. + +## Capability + +```json +{"capabilities": {"knowledge": {"import": 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 +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). + +## Kinds of file + +| Kind | The file | +| --- | --- | +| `lichess-puzzles` | Lichess's puzzle database, CSV, as published (`lichess_db_puzzle.csv.zst`) | +| `lichess-evals` | Lichess's evaluations, JSON Lines (`lichess_db_eval.jsonl.zst`) | +| `sts-epd` | A Strategic Test Suite EPD file, one of STS-Rating's variants | + +A file whose name ends in `.zst` is Zstandard-compressed and the node reads it so; the client +never decompresses a file to give it to the node. A kind's variants are different sources, not +versions of one: the checksum tells them apart, and a node doesn't convert one's scores to +another's scale. + +## The manifest + +Every file comes with where it is from, which the node keeps with everything it imports: + +```json +{"name": "Lichess puzzles", "release": "2026-11", "url": "https://database.lichess.org/", + "retrievedAt": "2026-11-13T10:02:11.000Z", + "checksum": "3f1c0d…64 hex digits…9a", "license": "CC0-1.0", "attribution": "Lichess"} +``` + +| Field | What it is | +| --- | --- | +| `name`, `release`, `url` | The source, its release, and where it was downloaded from | +| `retrievedAt` | When it was downloaded: UTC, RFC 3339 with milliseconds | +| `checksum` | SHA-256 of the file **as downloaded** (the compressed file, for `.zst`), 64 hexadecimal digits, either case | +| `license` | An SPDX identifier, such as `CC0-1.0` | +| `attribution` | What to credit, to show wherever the data is used | + +Each is required, 1–1024 bytes without control characters (`checksum` is exactly 64). A client +must not offer a corpus whose licence it hasn't cleared for the player's use. + +## An import + +```json +{"kind": "lichess-puzzles", "checksum": "3f1c0d…9a", "name": "Lichess puzzles", + "release": "2026-11", "state": "importing", "read": 120000, "accepted": 119871, + "rejected": 3, "duplicate": 126, "startedAt": "2026-11-13T10:05:00.000Z"} +``` + +| Field | What it is | +| --- | --- | +| `kind`, `checksum` | Its identity: one file of one kind. Another variant or release has another checksum, so is another import | +| `name`, `release` | From the manifest | +| `state` | `verifying`, `importing`, `complete`, `cancelled` or `failed` | +| `read` | Records read so far, the rejected ones included | +| `accepted`, `rejected`, `duplicate` | What became of them: stored, found invalid (kept apart by the node, with where and why, not stored as knowledge), and already stored | +| `failure` | When `failed`: `{"code": …, "message": …}`, see below | +| `startedAt`, `finishedAt` | UTC, RFC 3339 with milliseconds; `finishedAt` once `complete` | + +The counts are of what has been **durably committed**; a node never reports a record it could +still lose. `read` = `accepted` + `rejected` + `duplicate`. + +States: `verifying` (the node is reading the whole file to check its checksum, before any +record is read), `importing`, `complete` (the file was read to its end), `cancelled` (stopped +by a client or by the node's shutdown, or found interrupted when the node started again), and +`failed`. `cancelled` and `failed` imports keep everything committed and can be resumed. + +A `failure`'s `code` is one of `checksum` (the file isn't the one the manifest describes), +`unreadable` (it stopped being readable), `format` (it isn't a file of this kind), `disk` (not +enough free space), `stream` (reading it failed part-way, as a truncated download does) or +`storage` (the node's own storage failed). + +## Requests + +### `knowledge/import` + +```json +{"kind": "lichess-puzzles", "path": "/Users/carlos/Downloads/lichess_db_puzzle.csv.zst", + "manifest": { ... a manifest ... }} +``` + +`path` is an absolute path, on the computer the node runs on, of the file as downloaded +(1–4096 bytes, no NUL). The node only reads it: it never writes, moves or deletes a client's +file. + +The request starts the import and **answers at once**, without waiting for it; an import runs +for minutes or hours. It answers with the import: + +```json +{"import": { ... an import, verifying ... }} +``` + +**Imports are safe to repeat.** The identity is the kind and the checksum: + +- not seen before: the import starts, `verifying`; +- `complete`: nothing is read again, and the answer is the complete import; +- running (`verifying` or `importing`): the answer is its state, and `path` is ignored; +- `cancelled` or `failed`: the import **resumes**, after the last record it committed, with + `path` (which may differ from before, and is verified again). + +A resumed or repeated import never stores a record twice. + +The node runs one import at a time, and answers a second with Busy (-32013) until the first is +finished or cancelled. An import doesn't slow the node's other requests: preferences, games and +backups are answered while it runs. + +A kind the node doesn't list is -32602, as is a malformed manifest or path. A file that doesn't +exist, isn't a file, or can't be read is -32027, and no import starts. + +### `knowledge/status` + +```json +{"kind": "lichess-puzzles", "checksum": "3f1c0d…9a"} +``` + +Both fields are optional and the params may be left out. With both, it answers with that import +(-32025 if there is none); with one, those that match; with neither, every import. Imports come +newest first, at most 100: + +```json +{"imports": [{ ... an import ... }]} +``` + +A client polls while it shows progress, no more often than once a second. + +### `knowledge/cancel` + +```json +{"kind": "lichess-puzzles", "checksum": "3f1c0d…9a"} +``` + +Stops an import at its next batch (a node's batches are short) and answers when it has stopped, +with the import, `cancelled`. What it committed stays, and importing the file again resumes it. +Cancelling an import that isn't running answers with its state unchanged; one the node has no +record of is -32025. + +## Pitfalls + +- **The path is the client's.** A node reads whatever file its client names, and the client + already has the node's own privileges, so this adds nothing a client couldn't do. A node + never *writes* where a request says, and where it keeps its knowledge is its launch + configuration, as it is for backups. +- **A counted record is a committed record.** A client that shows "120,000 of 4,000,000" shows + what survives a crash, not what was parsed. +- **Not everything in a file is knowledge.** A record that fails the node's checks (an illegal + move, a bad score) is counted as `rejected` and kept apart; a file with a few rejects is still + `complete`. A file that isn't of the kind at all, or whose rejects are all of it, is `failed` + with `format`. +- **Knowledge is rebuildable.** It is not the player's data and is not in a backup + ([backups](backups.md)); importing the files again makes it. + +## Errors + +| Error | Meaning | Client action | +| --- | --- | --- | +| -32602 | Invalid params: an unknown kind, or a malformed path, manifest or checksum | 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 | +| -32027 | The file doesn't exist, isn't a file, or can't be read | Ask the player for the file again | +| -32800 | Cancelled before the request was done | Nothing changed | + +## 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.