Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
25 changes: 25 additions & 0 deletions conformance/knowledge/import-refusals.jsonl
Original file line number Diff line number Diff line change
@@ -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}
320 changes: 320 additions & 0 deletions crates/cnp/src/knowledge.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
/// The contract the node implements, [`CONTRACT`]; absent means don't send knowledge
/// requests.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub contract: Option<String>,
}

/// 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<Failure>,
/// 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<String>,
}

/// 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<StatusFields>")]
pub struct StatusParams {
/// Only imports of this kind.
pub kind: Option<String>,
/// Only the import with this checksum.
pub checksum: Option<String>,
}

/// [`StatusParams`] as they are read, from an object or from nothing.
#[derive(Default, Deserialize)]
struct StatusFields {
#[serde(default)]
kind: Option<String>,
#[serde(default)]
checksum: Option<String>,
}

impl From<Option<StatusFields>> for StatusParams {
fn from(fields: Option<StatusFields>) -> 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<Import>,
}

/// 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;
}
8 changes: 5 additions & 3 deletions crates/cnp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions crates/cnp/src/lifecycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<crate::backups::Capabilities>,
/// Proposed draft knowledge domain (`knowledge/…`); clients must also check its contract.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub knowledge: Option<crate::knowledge::Capabilities>,
/// The engine domain (`engine/…`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub engine: Option<EngineCapabilities>,
Expand Down
Loading
Loading