Restore LF line endings in the files my last three commits rewrote as CRLF
The repo stores LF; a scripted edit on Windows wrote CRLF. No content change:
git diff -w d5fddc3 shows only the three commits' real edits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6df2a684ef
commit
126a914abb
5 changed files with 2424 additions and 2424 deletions
|
|
@ -1,50 +1,50 @@
|
|||
[package]
|
||||
name = "eureka-state"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
# The client core (`lib.rs`): one call over CultNet to a Huginn daemon. It owns
|
||||
# the transport and nothing of the mind. The operation envelope, the wire
|
||||
# vocabulary and the deferred-body bound are `huginn-mind`'s, so the client and
|
||||
# the daemon cannot spell them differently; the content fetch and its
|
||||
# verification are `cultnet-rs`'s.
|
||||
#
|
||||
# The crate is the client core (`lib.rs`) and its consumers: the `huginn` CLI
|
||||
# (`src/bin/huginn/`), the shell door every agent uses, and until
|
||||
# delete-eureka-state-mcp the MCP server (`main.rs`, the `eureka-state` binary).
|
||||
# Both hold no state.
|
||||
# `cli` (default) is the `huginn` binary's argument parser; a library consumer
|
||||
# takes `default-features = false` and compiles none of it.
|
||||
[features]
|
||||
default = ["cli"]
|
||||
cli = ["dep:clap"]
|
||||
|
||||
[[bin]]
|
||||
name = "huginn"
|
||||
path = "src/bin/huginn/main.rs"
|
||||
required-features = ["cli"]
|
||||
|
||||
[[test]]
|
||||
name = "cli"
|
||||
required-features = ["cli"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
clap = { version = "4", features = ["derive"], optional = true }
|
||||
cultnet-rs.workspace = true
|
||||
huginn-mind = { path = "../huginn-mind" }
|
||||
rmcp = { version = "2.2.0", default-features = false, features = ["server", "macros", "transport-io"] }
|
||||
rmp-serde = "1"
|
||||
schemars = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["rt", "macros", "io-std"] }
|
||||
|
||||
# Tests run a real daemon in-process against a temporary mind, and the real
|
||||
# binary against it.
|
||||
[dev-dependencies]
|
||||
chrono = "0.4.44"
|
||||
huginn-daemon = { path = "../huginn-daemon" }
|
||||
tempfile = "3"
|
||||
[package]
|
||||
name = "eureka-state"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
# The client core (`lib.rs`): one call over CultNet to a Huginn daemon. It owns
|
||||
# the transport and nothing of the mind. The operation envelope, the wire
|
||||
# vocabulary and the deferred-body bound are `huginn-mind`'s, so the client and
|
||||
# the daemon cannot spell them differently; the content fetch and its
|
||||
# verification are `cultnet-rs`'s.
|
||||
#
|
||||
# The crate is the client core (`lib.rs`) and its consumers: the `huginn` CLI
|
||||
# (`src/bin/huginn/`), the shell door every agent uses, and until
|
||||
# delete-eureka-state-mcp the MCP server (`main.rs`, the `eureka-state` binary).
|
||||
# Both hold no state.
|
||||
# `cli` (default) is the `huginn` binary's argument parser; a library consumer
|
||||
# takes `default-features = false` and compiles none of it.
|
||||
[features]
|
||||
default = ["cli"]
|
||||
cli = ["dep:clap"]
|
||||
|
||||
[[bin]]
|
||||
name = "huginn"
|
||||
path = "src/bin/huginn/main.rs"
|
||||
required-features = ["cli"]
|
||||
|
||||
[[test]]
|
||||
name = "cli"
|
||||
required-features = ["cli"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
clap = { version = "4", features = ["derive"], optional = true }
|
||||
cultnet-rs.workspace = true
|
||||
huginn-mind = { path = "../huginn-mind" }
|
||||
rmcp = { version = "2.2.0", default-features = false, features = ["server", "macros", "transport-io"] }
|
||||
rmp-serde = "1"
|
||||
schemars = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["rt", "macros", "io-std"] }
|
||||
|
||||
# Tests run a real daemon in-process against a temporary mind, and the real
|
||||
# binary against it.
|
||||
[dev-dependencies]
|
||||
chrono = "0.4.44"
|
||||
huginn-daemon = { path = "../huginn-daemon" }
|
||||
tempfile = "3"
|
||||
|
|
|
|||
|
|
@ -1,399 +1,399 @@
|
|||
//! `huginn`: the agents' door to Huginn's mind, as shell commands.
|
||||
//!
|
||||
//! A caller of `HuginnClient` and nothing else. It owns argument parsing, the
|
||||
//! strict decode of agent-written JSON into the leaf's types (`door`), the
|
||||
//! recipe selections (`recipes`), the text rendering (`render`), the exit code
|
||||
//! and the read-back after an admission. It owns no state, writes no file and
|
||||
//! reads no configuration but two environment variables: `EUREKA_INSTANCE`
|
||||
//! names the mind and `HUGINN_ENDPOINT` (`rudp://host:port`) the daemon that
|
||||
//! holds it. Each call is a new process; there is no retry inside it, the
|
||||
//! caller's rule retries `Unavailable` once.
|
||||
//!
|
||||
//! Answers go to stdout and the exit code says what the answer was: 0 answered,
|
||||
//! 1 the mind said no (a refusal, a conflict, an absent document). Troubles go
|
||||
//! to stderr as `<Code>: <detail>`: 2 the call is wrong, 3 Unavailable, 4 no
|
||||
//! answer and a retry cannot help, 5 the read-back after a committed admission
|
||||
//! differs from what was sent.
|
||||
|
||||
mod config;
|
||||
mod door;
|
||||
mod recipes;
|
||||
mod render;
|
||||
mod schema;
|
||||
mod trouble;
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
|
||||
use cultnet_rs::{PROJECTION_DOCUMENT, Selection};
|
||||
use huginn_mind::eureka_pipeline::{Line, PipelineDocument, PipelineRef, Short, Slug, pipeline_key};
|
||||
use huginn_mind::{
|
||||
BATCH_MAX, Faculty, HuginnMindRequest, HuginnMindResponse, MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome,
|
||||
PipelinePageItems, PipelineProvenance, PipelineSelectionPage, SemanticQuery,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use config::{Settings, TOOL};
|
||||
use recipes::Recipe;
|
||||
use trouble::Trouble;
|
||||
|
||||
/// The page size when a selection names none.
|
||||
const DEFAULT_LIMIT: u32 = 50;
|
||||
/// The neighbours `--near` asks for when `--top-k` is not given.
|
||||
const DEFAULT_TOP_K: u32 = 10;
|
||||
|
||||
const ADMIT_HELP: &str = "\
|
||||
The file is a JSON array of 1 to 64 documents, each {\"kind\": <kind>, \"value\": {...}}, or - for stdin; one document object alone is a batch of one. \
|
||||
`huginn schema` lists the kinds and `huginn schema <kind>` prints a value's JSON Schema. \
|
||||
Every key the schema does not know is refused (exit 2) with its path; nothing is sent. \
|
||||
After Committed or AlreadyAdmitted the batch is read back and compared with what was sent: `read back <n> equal`, or exit 5 with the ids and field paths that differ.";
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "huginn", about = "Huginn's mind: whoami, view, query, recipes, admit, schema", arg_required_else_help = true)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum Command {
|
||||
/// Who this process acts for and whether the daemon answers.
|
||||
Whoami,
|
||||
/// Read one document by id, with its admission facts and status.
|
||||
View {
|
||||
/// The document's id: <root>:<kind>:<local>.
|
||||
id: String,
|
||||
/// Print only the {kind, value} JSON, which `admit` accepts back.
|
||||
#[arg(long)]
|
||||
raw: bool,
|
||||
},
|
||||
/// Query the mind with a CultNet selection.
|
||||
Query {
|
||||
/// The selection JSON, @<file>, or - for stdin.
|
||||
selection: String,
|
||||
/// Rank by nearness to this text instead of ordering by key.
|
||||
#[arg(long)]
|
||||
near: Option<String>,
|
||||
/// How many neighbours (default 10).
|
||||
#[arg(long, requires = "near")]
|
||||
top_k: Option<u32>,
|
||||
/// Print each item as `view` does.
|
||||
#[arg(long)]
|
||||
documents: bool,
|
||||
},
|
||||
#[command(flatten)]
|
||||
Recipe(Recipe),
|
||||
/// Admit a batch of documents, whole or not at all, and read it back.
|
||||
#[command(after_help = ADMIT_HELP)]
|
||||
Admit {
|
||||
#[arg(long, value_parser = faculty)]
|
||||
faculty: Faculty,
|
||||
/// The admitting agent's name.
|
||||
#[arg(long)]
|
||||
agent: String,
|
||||
/// The admitting session.
|
||||
#[arg(long)]
|
||||
session: String,
|
||||
/// The documents file, or - for stdin.
|
||||
file: String,
|
||||
},
|
||||
/// The JSON Schema of a document kind or of a selection; no name lists them.
|
||||
Schema { name: Option<String> },
|
||||
}
|
||||
|
||||
fn faculty(text: &str) -> Result<Faculty, String> {
|
||||
serde_json::from_value(Value::String(text.to_string())).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// The version, then the sha the binary was built from.
|
||||
fn version() -> &'static str {
|
||||
static VERSION: OnceLock<String> = OnceLock::new();
|
||||
VERSION.get_or_init(|| format!("{} ({})", env!("CARGO_PKG_VERSION"), build_sha()))
|
||||
}
|
||||
|
||||
fn build_sha() -> &'static str {
|
||||
option_env!("HUGINN_BUILD_SHA").unwrap_or("unknown")
|
||||
}
|
||||
|
||||
/// The command line, or the exit code of having answered it (help, version) or
|
||||
/// refused it (usage, as `InvalidInput`).
|
||||
fn parse() -> Result<Cli, u8> {
|
||||
let mut command = Cli::command().version(version());
|
||||
for (name, text) in recipes::help() {
|
||||
command = command.mut_subcommand(name, |recipe| recipe.after_help(text));
|
||||
}
|
||||
match command.try_get_matches() {
|
||||
Ok(matches) => Cli::from_arg_matches(&matches).map_err(|error| usage(&error)),
|
||||
Err(error) => Err(usage(&error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage(error: &clap::Error) -> u8 {
|
||||
if error.use_stderr() {
|
||||
let text = error.to_string();
|
||||
eprintln!("InvalidInput: {}", text.trim_start_matches("error: ").trim_end());
|
||||
2
|
||||
} else {
|
||||
let _ = error.print();
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = match parse() {
|
||||
Ok(cli) => cli,
|
||||
Err(code) => return ExitCode::from(code),
|
||||
};
|
||||
match run(&Settings::from_env(), cli.command) {
|
||||
Ok(code) => ExitCode::from(code),
|
||||
Err(trouble) => {
|
||||
eprintln!("{trouble}");
|
||||
ExitCode::from(trouble.exit())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn say(text: impl std::fmt::Display) {
|
||||
let _ = writeln!(std::io::stdout(), "{text}");
|
||||
}
|
||||
|
||||
fn run(settings: &Settings, command: Command) -> Result<u8, Trouble> {
|
||||
match command {
|
||||
Command::Whoami => whoami(settings),
|
||||
Command::View { id, raw } => view(settings, &id, raw),
|
||||
Command::Query { selection, near, top_k, documents } => {
|
||||
let selection = door::selection(&door::argument(&selection)?)?;
|
||||
let semantic = near.map(|text| SemanticQuery { text: Line(text), top_k: top_k.unwrap_or(DEFAULT_TOP_K) });
|
||||
query(settings, selection, semantic, None, documents)
|
||||
}
|
||||
Command::Recipe(recipe) => {
|
||||
let ask = recipe.ask()?;
|
||||
query(settings, door::selection_value(&ask.selection)?, ask.semantic, ask.page.cursor, ask.page.documents)
|
||||
}
|
||||
Command::Admit { faculty, agent, session, file } => admit(settings, faculty, agent, session, &file),
|
||||
Command::Schema { name } => {
|
||||
let text = schema::text(name.as_deref())?;
|
||||
let _ = write!(std::io::stdout(), "{text}");
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn whoami(settings: &Settings) -> Result<u8, Trouble> {
|
||||
say(format_args!("instance {}", settings.instance.as_deref().unwrap_or("unset")));
|
||||
say(format_args!("endpoint {}", settings.endpoint.as_deref().unwrap_or("unset")));
|
||||
say(format_args!("client {}", build_sha()));
|
||||
match settings.ask(|_| HuginnMindRequest::Whoami) {
|
||||
Ok(HuginnMindResponse::Whoami(status)) => {
|
||||
say("reachable yes");
|
||||
say(format_args!(
|
||||
"documents {} receipts {} index {} epoch {}",
|
||||
status.documents,
|
||||
status.receipts,
|
||||
render::index_state(&status.index),
|
||||
status.schema_epoch
|
||||
));
|
||||
say(format_args!("persona {}", render::persona_state(&status.persona)));
|
||||
Ok(0)
|
||||
}
|
||||
Ok(other) => {
|
||||
say("reachable no");
|
||||
Err(unexpected(&other))
|
||||
}
|
||||
Err(trouble) => {
|
||||
say("reachable no");
|
||||
Err(trouble)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn view(settings: &Settings, id: &str, raw: bool) -> Result<u8, Trouble> {
|
||||
let reference = PipelineRef { kind: door::kind_of(id)?, id: Short(id.to_string()) };
|
||||
match settings.ask(|instance| HuginnMindRequest::View { instance: instance.clone(), id: reference })? {
|
||||
HuginnMindResponse::View(Some(found)) => {
|
||||
say(render::view(&found, raw));
|
||||
Ok(0)
|
||||
}
|
||||
HuginnMindResponse::View(None) => {
|
||||
say(format_args!("absent {id}"));
|
||||
Ok(1)
|
||||
}
|
||||
HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn query(
|
||||
settings: &Settings,
|
||||
mut selection: Selection,
|
||||
semantic: Option<SemanticQuery>,
|
||||
cursor: Option<String>,
|
||||
documents: bool,
|
||||
) -> Result<u8, Trouble> {
|
||||
if documents {
|
||||
selection.projection = PROJECTION_DOCUMENT.to_string();
|
||||
}
|
||||
if cursor.is_some() {
|
||||
selection.cursor = cursor;
|
||||
}
|
||||
selection.limit.get_or_insert(DEFAULT_LIMIT);
|
||||
match settings.ask(|instance| HuginnMindRequest::Query { instance: instance.clone(), selection, semantic })? {
|
||||
HuginnMindResponse::Query(page) => {
|
||||
show(&page);
|
||||
Ok(0)
|
||||
}
|
||||
HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn show(page: &PipelineSelectionPage) {
|
||||
match &page.items {
|
||||
PipelinePageItems::Headers(headers) => {
|
||||
for header in headers {
|
||||
say(render::header(header));
|
||||
}
|
||||
}
|
||||
PipelinePageItems::Documents(views) => {
|
||||
for (index, found) in views.iter().enumerate() {
|
||||
if index > 0 {
|
||||
say("");
|
||||
}
|
||||
say(render::view(found, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
say(format_args!("matched {} as_of {} next {}", page.matched, page.as_of, page.next.as_deref().unwrap_or("-")));
|
||||
}
|
||||
|
||||
fn admit(settings: &Settings, faculty: Faculty, agent: String, session: String, file: &str) -> Result<u8, Trouble> {
|
||||
let documents = door::documents(&door::file_or_stdin(file)?)?;
|
||||
if documents.is_empty() || documents.len() > BATCH_MAX {
|
||||
return Err(Trouble::invalid(format!("a batch is 1 to {BATCH_MAX} documents, this one has {}", documents.len())));
|
||||
}
|
||||
let sent = documents.clone();
|
||||
let provenance = PipelineProvenance { faculty, agent: Short(agent), session: Short(session), tool: Short(TOOL.to_string()) };
|
||||
let request = |instance: &Slug| {
|
||||
HuginnMindRequest::Admit(PipelineAdmissionBatch { instance: instance.clone(), provenance, documents })
|
||||
};
|
||||
match settings.ask(request)? {
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { receipt_id, committed_at, writes }) => {
|
||||
say(format_args!("Committed {receipt_id} at {committed_at}"));
|
||||
for write in &writes {
|
||||
say(format_args!("wrote {}", write.id.0));
|
||||
}
|
||||
read_back(settings, &sent)
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id }) => {
|
||||
say(format_args!("AlreadyAdmitted {receipt_id}"));
|
||||
read_back(settings, &sent)
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal)) | HuginnMindResponse::Refused(refusal) => {
|
||||
Ok(refused(&refusal))
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Conflict { identities }) => {
|
||||
say("Conflict");
|
||||
for identity in &identities {
|
||||
say(format_args!("conflicts {}", identity.id.0));
|
||||
}
|
||||
Ok(1)
|
||||
}
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The end-to-end check that the mind kept what was sent: one `keys` query,
|
||||
/// each stored document compared with the one sent. A difference is exit 5,
|
||||
/// not silence, whatever dropped it (an older leaf, a serde default, skew).
|
||||
fn read_back(settings: &Settings, sent: &[PipelineDocument]) -> Result<u8, Trouble> {
|
||||
let keys = sent
|
||||
.iter()
|
||||
.map(|document| pipeline_key(document).map_err(|refusal| Trouble::Internal(format!("a committed document has no key: {refusal:?}"))))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let selection = Selection {
|
||||
keys: Some(keys.clone()),
|
||||
projection: PROJECTION_DOCUMENT.to_string(),
|
||||
limit: Some(u32::try_from(keys.len()).unwrap_or(u32::MAX)),
|
||||
..Selection::default()
|
||||
};
|
||||
let page = match settings.ask(|instance| HuginnMindRequest::Query { instance: instance.clone(), selection, semantic: None })? {
|
||||
HuginnMindResponse::Query(page) => page,
|
||||
HuginnMindResponse::Refused(refusal) => return Ok(refused(&refusal)),
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
let PipelinePageItems::Documents(stored) = page.items else {
|
||||
return Err(Trouble::Internal("the read-back answered headers, not documents".to_string()));
|
||||
};
|
||||
let mut differing = Vec::new();
|
||||
for (key, document) in keys.iter().zip(sent) {
|
||||
let held = stored.iter().find(|found| &found.id.id.0 == key);
|
||||
match held {
|
||||
None => differing.push(format!("{key}: missing from the read-back")),
|
||||
Some(found) if found.document == *document => {}
|
||||
Some(found) => {
|
||||
let (mut paths, sent_value, held_value) = (Vec::new(), to_value(document), to_value(&found.document));
|
||||
differences(&sent_value, &held_value, "", &mut paths);
|
||||
let shown = if paths.is_empty() { "the document".to_string() } else { paths.join(", ") };
|
||||
differing.push(format!("{key}: {shown}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if differing.is_empty() {
|
||||
say(format_args!("read back {} equal", sent.len()));
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Trouble::ReadBackDiffers(format!(
|
||||
"{}; the batch is committed, so supersede the documents that differ",
|
||||
differing.join("; ")
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value(document: &PipelineDocument) -> Value {
|
||||
serde_json::to_value(document).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// The field paths at which two documents differ, including a field only one
|
||||
/// of them carries.
|
||||
fn differences(sent: &Value, held: &Value, path: &str, out: &mut Vec<String>) {
|
||||
match (sent, held) {
|
||||
(Value::Object(sent), Value::Object(held)) => {
|
||||
for key in sent.keys().chain(held.keys().filter(|key| !sent.contains_key(*key))) {
|
||||
let here = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
|
||||
match (sent.get(key), held.get(key)) {
|
||||
(Some(sent), Some(held)) => differences(sent, held, &here, out),
|
||||
_ => out.push(here),
|
||||
}
|
||||
}
|
||||
}
|
||||
(Value::Array(sent), Value::Array(held)) if sent.len() == held.len() => {
|
||||
for (index, (sent, held)) in sent.iter().zip(held).enumerate() {
|
||||
differences(sent, held, &format!("{path}[{index}]"), out);
|
||||
}
|
||||
}
|
||||
_ if sent == held => {}
|
||||
_ => out.push(path.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A refusal is the mind's answer: stdout, exit 1.
|
||||
fn refused(refusal: &MindRefusal) -> u8 {
|
||||
say(format_args!("Refused {refusal:?}"));
|
||||
1
|
||||
}
|
||||
|
||||
fn unexpected(answer: &HuginnMindResponse) -> Trouble {
|
||||
let name = match answer {
|
||||
HuginnMindResponse::Whoami(_) => "whoami",
|
||||
HuginnMindResponse::Admit(_) => "admit",
|
||||
HuginnMindResponse::View(_) => "view",
|
||||
HuginnMindResponse::Query(_) => "query",
|
||||
HuginnMindResponse::Persona(_) => "a persona",
|
||||
HuginnMindResponse::PersonaPut(_) => "a persona put",
|
||||
HuginnMindResponse::Refused(_) => "a refusal",
|
||||
HuginnMindResponse::Deferred(_) => "a deferral",
|
||||
};
|
||||
Trouble::Internal(format!("the daemon answered with {name}, which this call did not ask for"))
|
||||
}
|
||||
//! `huginn`: the agents' door to Huginn's mind, as shell commands.
|
||||
//!
|
||||
//! A caller of `HuginnClient` and nothing else. It owns argument parsing, the
|
||||
//! strict decode of agent-written JSON into the leaf's types (`door`), the
|
||||
//! recipe selections (`recipes`), the text rendering (`render`), the exit code
|
||||
//! and the read-back after an admission. It owns no state, writes no file and
|
||||
//! reads no configuration but two environment variables: `EUREKA_INSTANCE`
|
||||
//! names the mind and `HUGINN_ENDPOINT` (`rudp://host:port`) the daemon that
|
||||
//! holds it. Each call is a new process; there is no retry inside it, the
|
||||
//! caller's rule retries `Unavailable` once.
|
||||
//!
|
||||
//! Answers go to stdout and the exit code says what the answer was: 0 answered,
|
||||
//! 1 the mind said no (a refusal, a conflict, an absent document). Troubles go
|
||||
//! to stderr as `<Code>: <detail>`: 2 the call is wrong, 3 Unavailable, 4 no
|
||||
//! answer and a retry cannot help, 5 the read-back after a committed admission
|
||||
//! differs from what was sent.
|
||||
|
||||
mod config;
|
||||
mod door;
|
||||
mod recipes;
|
||||
mod render;
|
||||
mod schema;
|
||||
mod trouble;
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
|
||||
use cultnet_rs::{PROJECTION_DOCUMENT, Selection};
|
||||
use huginn_mind::eureka_pipeline::{Line, PipelineDocument, PipelineRef, Short, Slug, pipeline_key};
|
||||
use huginn_mind::{
|
||||
BATCH_MAX, Faculty, HuginnMindRequest, HuginnMindResponse, MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome,
|
||||
PipelinePageItems, PipelineProvenance, PipelineSelectionPage, SemanticQuery,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use config::{Settings, TOOL};
|
||||
use recipes::Recipe;
|
||||
use trouble::Trouble;
|
||||
|
||||
/// The page size when a selection names none.
|
||||
const DEFAULT_LIMIT: u32 = 50;
|
||||
/// The neighbours `--near` asks for when `--top-k` is not given.
|
||||
const DEFAULT_TOP_K: u32 = 10;
|
||||
|
||||
const ADMIT_HELP: &str = "\
|
||||
The file is a JSON array of 1 to 64 documents, each {\"kind\": <kind>, \"value\": {...}}, or - for stdin; one document object alone is a batch of one. \
|
||||
`huginn schema` lists the kinds and `huginn schema <kind>` prints a value's JSON Schema. \
|
||||
Every key the schema does not know is refused (exit 2) with its path; nothing is sent. \
|
||||
After Committed or AlreadyAdmitted the batch is read back and compared with what was sent: `read back <n> equal`, or exit 5 with the ids and field paths that differ.";
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "huginn", about = "Huginn's mind: whoami, view, query, recipes, admit, schema", arg_required_else_help = true)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum Command {
|
||||
/// Who this process acts for and whether the daemon answers.
|
||||
Whoami,
|
||||
/// Read one document by id, with its admission facts and status.
|
||||
View {
|
||||
/// The document's id: <root>:<kind>:<local>.
|
||||
id: String,
|
||||
/// Print only the {kind, value} JSON, which `admit` accepts back.
|
||||
#[arg(long)]
|
||||
raw: bool,
|
||||
},
|
||||
/// Query the mind with a CultNet selection.
|
||||
Query {
|
||||
/// The selection JSON, @<file>, or - for stdin.
|
||||
selection: String,
|
||||
/// Rank by nearness to this text instead of ordering by key.
|
||||
#[arg(long)]
|
||||
near: Option<String>,
|
||||
/// How many neighbours (default 10).
|
||||
#[arg(long, requires = "near")]
|
||||
top_k: Option<u32>,
|
||||
/// Print each item as `view` does.
|
||||
#[arg(long)]
|
||||
documents: bool,
|
||||
},
|
||||
#[command(flatten)]
|
||||
Recipe(Recipe),
|
||||
/// Admit a batch of documents, whole or not at all, and read it back.
|
||||
#[command(after_help = ADMIT_HELP)]
|
||||
Admit {
|
||||
#[arg(long, value_parser = faculty)]
|
||||
faculty: Faculty,
|
||||
/// The admitting agent's name.
|
||||
#[arg(long)]
|
||||
agent: String,
|
||||
/// The admitting session.
|
||||
#[arg(long)]
|
||||
session: String,
|
||||
/// The documents file, or - for stdin.
|
||||
file: String,
|
||||
},
|
||||
/// The JSON Schema of a document kind or of a selection; no name lists them.
|
||||
Schema { name: Option<String> },
|
||||
}
|
||||
|
||||
fn faculty(text: &str) -> Result<Faculty, String> {
|
||||
serde_json::from_value(Value::String(text.to_string())).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// The version, then the sha the binary was built from.
|
||||
fn version() -> &'static str {
|
||||
static VERSION: OnceLock<String> = OnceLock::new();
|
||||
VERSION.get_or_init(|| format!("{} ({})", env!("CARGO_PKG_VERSION"), build_sha()))
|
||||
}
|
||||
|
||||
fn build_sha() -> &'static str {
|
||||
option_env!("HUGINN_BUILD_SHA").unwrap_or("unknown")
|
||||
}
|
||||
|
||||
/// The command line, or the exit code of having answered it (help, version) or
|
||||
/// refused it (usage, as `InvalidInput`).
|
||||
fn parse() -> Result<Cli, u8> {
|
||||
let mut command = Cli::command().version(version());
|
||||
for (name, text) in recipes::help() {
|
||||
command = command.mut_subcommand(name, |recipe| recipe.after_help(text));
|
||||
}
|
||||
match command.try_get_matches() {
|
||||
Ok(matches) => Cli::from_arg_matches(&matches).map_err(|error| usage(&error)),
|
||||
Err(error) => Err(usage(&error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage(error: &clap::Error) -> u8 {
|
||||
if error.use_stderr() {
|
||||
let text = error.to_string();
|
||||
eprintln!("InvalidInput: {}", text.trim_start_matches("error: ").trim_end());
|
||||
2
|
||||
} else {
|
||||
let _ = error.print();
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = match parse() {
|
||||
Ok(cli) => cli,
|
||||
Err(code) => return ExitCode::from(code),
|
||||
};
|
||||
match run(&Settings::from_env(), cli.command) {
|
||||
Ok(code) => ExitCode::from(code),
|
||||
Err(trouble) => {
|
||||
eprintln!("{trouble}");
|
||||
ExitCode::from(trouble.exit())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn say(text: impl std::fmt::Display) {
|
||||
let _ = writeln!(std::io::stdout(), "{text}");
|
||||
}
|
||||
|
||||
fn run(settings: &Settings, command: Command) -> Result<u8, Trouble> {
|
||||
match command {
|
||||
Command::Whoami => whoami(settings),
|
||||
Command::View { id, raw } => view(settings, &id, raw),
|
||||
Command::Query { selection, near, top_k, documents } => {
|
||||
let selection = door::selection(&door::argument(&selection)?)?;
|
||||
let semantic = near.map(|text| SemanticQuery { text: Line(text), top_k: top_k.unwrap_or(DEFAULT_TOP_K) });
|
||||
query(settings, selection, semantic, None, documents)
|
||||
}
|
||||
Command::Recipe(recipe) => {
|
||||
let ask = recipe.ask()?;
|
||||
query(settings, door::selection_value(&ask.selection)?, ask.semantic, ask.page.cursor, ask.page.documents)
|
||||
}
|
||||
Command::Admit { faculty, agent, session, file } => admit(settings, faculty, agent, session, &file),
|
||||
Command::Schema { name } => {
|
||||
let text = schema::text(name.as_deref())?;
|
||||
let _ = write!(std::io::stdout(), "{text}");
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn whoami(settings: &Settings) -> Result<u8, Trouble> {
|
||||
say(format_args!("instance {}", settings.instance.as_deref().unwrap_or("unset")));
|
||||
say(format_args!("endpoint {}", settings.endpoint.as_deref().unwrap_or("unset")));
|
||||
say(format_args!("client {}", build_sha()));
|
||||
match settings.ask(|_| HuginnMindRequest::Whoami) {
|
||||
Ok(HuginnMindResponse::Whoami(status)) => {
|
||||
say("reachable yes");
|
||||
say(format_args!(
|
||||
"documents {} receipts {} index {} epoch {}",
|
||||
status.documents,
|
||||
status.receipts,
|
||||
render::index_state(&status.index),
|
||||
status.schema_epoch
|
||||
));
|
||||
say(format_args!("persona {}", render::persona_state(&status.persona)));
|
||||
Ok(0)
|
||||
}
|
||||
Ok(other) => {
|
||||
say("reachable no");
|
||||
Err(unexpected(&other))
|
||||
}
|
||||
Err(trouble) => {
|
||||
say("reachable no");
|
||||
Err(trouble)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn view(settings: &Settings, id: &str, raw: bool) -> Result<u8, Trouble> {
|
||||
let reference = PipelineRef { kind: door::kind_of(id)?, id: Short(id.to_string()) };
|
||||
match settings.ask(|instance| HuginnMindRequest::View { instance: instance.clone(), id: reference })? {
|
||||
HuginnMindResponse::View(Some(found)) => {
|
||||
say(render::view(&found, raw));
|
||||
Ok(0)
|
||||
}
|
||||
HuginnMindResponse::View(None) => {
|
||||
say(format_args!("absent {id}"));
|
||||
Ok(1)
|
||||
}
|
||||
HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn query(
|
||||
settings: &Settings,
|
||||
mut selection: Selection,
|
||||
semantic: Option<SemanticQuery>,
|
||||
cursor: Option<String>,
|
||||
documents: bool,
|
||||
) -> Result<u8, Trouble> {
|
||||
if documents {
|
||||
selection.projection = PROJECTION_DOCUMENT.to_string();
|
||||
}
|
||||
if cursor.is_some() {
|
||||
selection.cursor = cursor;
|
||||
}
|
||||
selection.limit.get_or_insert(DEFAULT_LIMIT);
|
||||
match settings.ask(|instance| HuginnMindRequest::Query { instance: instance.clone(), selection, semantic })? {
|
||||
HuginnMindResponse::Query(page) => {
|
||||
show(&page);
|
||||
Ok(0)
|
||||
}
|
||||
HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn show(page: &PipelineSelectionPage) {
|
||||
match &page.items {
|
||||
PipelinePageItems::Headers(headers) => {
|
||||
for header in headers {
|
||||
say(render::header(header));
|
||||
}
|
||||
}
|
||||
PipelinePageItems::Documents(views) => {
|
||||
for (index, found) in views.iter().enumerate() {
|
||||
if index > 0 {
|
||||
say("");
|
||||
}
|
||||
say(render::view(found, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
say(format_args!("matched {} as_of {} next {}", page.matched, page.as_of, page.next.as_deref().unwrap_or("-")));
|
||||
}
|
||||
|
||||
fn admit(settings: &Settings, faculty: Faculty, agent: String, session: String, file: &str) -> Result<u8, Trouble> {
|
||||
let documents = door::documents(&door::file_or_stdin(file)?)?;
|
||||
if documents.is_empty() || documents.len() > BATCH_MAX {
|
||||
return Err(Trouble::invalid(format!("a batch is 1 to {BATCH_MAX} documents, this one has {}", documents.len())));
|
||||
}
|
||||
let sent = documents.clone();
|
||||
let provenance = PipelineProvenance { faculty, agent: Short(agent), session: Short(session), tool: Short(TOOL.to_string()) };
|
||||
let request = |instance: &Slug| {
|
||||
HuginnMindRequest::Admit(PipelineAdmissionBatch { instance: instance.clone(), provenance, documents })
|
||||
};
|
||||
match settings.ask(request)? {
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { receipt_id, committed_at, writes }) => {
|
||||
say(format_args!("Committed {receipt_id} at {committed_at}"));
|
||||
for write in &writes {
|
||||
say(format_args!("wrote {}", write.id.0));
|
||||
}
|
||||
read_back(settings, &sent)
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id }) => {
|
||||
say(format_args!("AlreadyAdmitted {receipt_id}"));
|
||||
read_back(settings, &sent)
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal)) | HuginnMindResponse::Refused(refusal) => {
|
||||
Ok(refused(&refusal))
|
||||
}
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Conflict { identities }) => {
|
||||
say("Conflict");
|
||||
for identity in &identities {
|
||||
say(format_args!("conflicts {}", identity.id.0));
|
||||
}
|
||||
Ok(1)
|
||||
}
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The end-to-end check that the mind kept what was sent: one `keys` query,
|
||||
/// each stored document compared with the one sent. A difference is exit 5,
|
||||
/// not silence, whatever dropped it (an older leaf, a serde default, skew).
|
||||
fn read_back(settings: &Settings, sent: &[PipelineDocument]) -> Result<u8, Trouble> {
|
||||
let keys = sent
|
||||
.iter()
|
||||
.map(|document| pipeline_key(document).map_err(|refusal| Trouble::Internal(format!("a committed document has no key: {refusal:?}"))))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let selection = Selection {
|
||||
keys: Some(keys.clone()),
|
||||
projection: PROJECTION_DOCUMENT.to_string(),
|
||||
limit: Some(u32::try_from(keys.len()).unwrap_or(u32::MAX)),
|
||||
..Selection::default()
|
||||
};
|
||||
let page = match settings.ask(|instance| HuginnMindRequest::Query { instance: instance.clone(), selection, semantic: None })? {
|
||||
HuginnMindResponse::Query(page) => page,
|
||||
HuginnMindResponse::Refused(refusal) => return Ok(refused(&refusal)),
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
let PipelinePageItems::Documents(stored) = page.items else {
|
||||
return Err(Trouble::Internal("the read-back answered headers, not documents".to_string()));
|
||||
};
|
||||
let mut differing = Vec::new();
|
||||
for (key, document) in keys.iter().zip(sent) {
|
||||
let held = stored.iter().find(|found| &found.id.id.0 == key);
|
||||
match held {
|
||||
None => differing.push(format!("{key}: missing from the read-back")),
|
||||
Some(found) if found.document == *document => {}
|
||||
Some(found) => {
|
||||
let (mut paths, sent_value, held_value) = (Vec::new(), to_value(document), to_value(&found.document));
|
||||
differences(&sent_value, &held_value, "", &mut paths);
|
||||
let shown = if paths.is_empty() { "the document".to_string() } else { paths.join(", ") };
|
||||
differing.push(format!("{key}: {shown}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if differing.is_empty() {
|
||||
say(format_args!("read back {} equal", sent.len()));
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(Trouble::ReadBackDiffers(format!(
|
||||
"{}; the batch is committed, so supersede the documents that differ",
|
||||
differing.join("; ")
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value(document: &PipelineDocument) -> Value {
|
||||
serde_json::to_value(document).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// The field paths at which two documents differ, including a field only one
|
||||
/// of them carries.
|
||||
fn differences(sent: &Value, held: &Value, path: &str, out: &mut Vec<String>) {
|
||||
match (sent, held) {
|
||||
(Value::Object(sent), Value::Object(held)) => {
|
||||
for key in sent.keys().chain(held.keys().filter(|key| !sent.contains_key(*key))) {
|
||||
let here = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
|
||||
match (sent.get(key), held.get(key)) {
|
||||
(Some(sent), Some(held)) => differences(sent, held, &here, out),
|
||||
_ => out.push(here),
|
||||
}
|
||||
}
|
||||
}
|
||||
(Value::Array(sent), Value::Array(held)) if sent.len() == held.len() => {
|
||||
for (index, (sent, held)) in sent.iter().zip(held).enumerate() {
|
||||
differences(sent, held, &format!("{path}[{index}]"), out);
|
||||
}
|
||||
}
|
||||
_ if sent == held => {}
|
||||
_ => out.push(path.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A refusal is the mind's answer: stdout, exit 1.
|
||||
fn refused(refusal: &MindRefusal) -> u8 {
|
||||
say(format_args!("Refused {refusal:?}"));
|
||||
1
|
||||
}
|
||||
|
||||
fn unexpected(answer: &HuginnMindResponse) -> Trouble {
|
||||
let name = match answer {
|
||||
HuginnMindResponse::Whoami(_) => "whoami",
|
||||
HuginnMindResponse::Admit(_) => "admit",
|
||||
HuginnMindResponse::View(_) => "view",
|
||||
HuginnMindResponse::Query(_) => "query",
|
||||
HuginnMindResponse::Persona(_) => "a persona",
|
||||
HuginnMindResponse::PersonaPut(_) => "a persona put",
|
||||
HuginnMindResponse::Refused(_) => "a refusal",
|
||||
HuginnMindResponse::Deferred(_) => "a deferral",
|
||||
};
|
||||
Trouble::Internal(format!("the daemon answered with {name}, which this call did not ask for"))
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,343 +1,343 @@
|
|||
//! The organ's request and response vocabulary: one operation per `Mind`
|
||||
//! method and `whoami`. Payloads are the admission and read types unchanged.
|
||||
//! The daemon carries these in CultNet's operation envelope; the client
|
||||
//! constructs them. Nothing here validates a document, derives a status or
|
||||
//! names a transport.
|
||||
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultnet_rs::{CultMeshCdnArtifactManifest, Selection};
|
||||
use eureka_pipeline::{PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Slug};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::admission::{PipelineAdmissionBatch, PipelineAdmissionOutcome};
|
||||
use crate::mind::Mind;
|
||||
use crate::persona::{PersonaPutOutcome, PersonaStateView};
|
||||
use crate::query::{PipelineDocumentView, PipelineSelectionPage, SemanticQuery};
|
||||
use crate::receipt::{HuginnCommitReceipt, PipelineProvenance};
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::store::MindStore;
|
||||
|
||||
/// The envelope's `service_id`: one service, one mind, whichever mind the
|
||||
/// process opened.
|
||||
pub const MIND_SERVICE_ID: &str = "huginn.mind";
|
||||
pub const MIND_REQUEST_SCHEMA: &str = "huginn.mind_request.v1";
|
||||
pub const MIND_RESPONSE_SCHEMA: &str = "huginn.mind_response.v1";
|
||||
|
||||
/// The largest answer that is deferred rather than refused, measured on the
|
||||
/// encoded payload. The daemon refuses past it and a client caps its fetch at
|
||||
/// it, so both sides read one number.
|
||||
pub const MAX_DEFERRED_BODY_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
/// The published JSON schema of each wire type, as the catalog advertises it.
|
||||
/// The files are derived from the types below and pinned byte for byte by
|
||||
/// `published_wire_schemas_match_derivation`, so the catalog cannot advertise
|
||||
/// a shape the crate does not speak.
|
||||
pub const MIND_REQUEST_SCHEMA_JSON: &str =
|
||||
include_str!("../../../schemas/cultnet/huginn.mind_request.v1.schema.json");
|
||||
pub const MIND_RESPONSE_SCHEMA_JSON: &str =
|
||||
include_str!("../../../schemas/cultnet/huginn.mind_response.v1.schema.json");
|
||||
|
||||
/// The request's `selection` is CultNet's, and its published schema is
|
||||
/// CultLib's: a `$ref` to the `$id` it publishes, so one owner holds the
|
||||
/// selection's shape and nothing here copies it.
|
||||
fn selection_ref(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
schemars::json_schema!({
|
||||
"$ref": "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json"
|
||||
})
|
||||
}
|
||||
|
||||
/// The deferred answer's manifest is CultMesh's own type, a positional array
|
||||
/// the C# reference defines (`CultMeshCdnArtifactManifest`, schema version
|
||||
/// `gamecult.mesh.cdn_artifact_manifest.v1`). CultLib publishes no JSON schema
|
||||
/// for it, so the schema says what the reference says: an array of its ten
|
||||
/// fields in order, and nothing here copies their meaning.
|
||||
fn manifest_array(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
schemars::json_schema!({
|
||||
"description": "gamecult.mesh.cdn_artifact_manifest.v1, the C# reference's CultMeshCdnArtifactManifest as its positional array: [artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc, chunks[[chunkHash, offset, sizeBytes, recordKey]], tags, metadata].",
|
||||
"type": "array"
|
||||
})
|
||||
}
|
||||
|
||||
/// Every operation a mind answers. `Admit` carries the batch whole because the
|
||||
/// batch already names the instance and the asker; a second `instance` beside
|
||||
/// it would be two declarations. Every read names the instance because ruling
|
||||
/// 14 refuses another mind's identity whatever the transport, and a read of
|
||||
/// the wrong mind is that same collision on the read side. `Whoami` names
|
||||
/// none: it is how a client learns which mind it reached.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum HuginnMindRequest {
|
||||
Whoami,
|
||||
Admit(PipelineAdmissionBatch),
|
||||
View { instance: Slug, id: PipelineRef },
|
||||
Query {
|
||||
instance: Slug,
|
||||
#[schemars(schema_with = "selection_ref")]
|
||||
selection: Selection,
|
||||
semantic: Option<SemanticQuery>,
|
||||
},
|
||||
/// The mind's persona document, if one is stored.
|
||||
PersonaGet { instance: Slug },
|
||||
/// Replaces the mind's persona document whole. `expected_updated_at` is
|
||||
/// the stored document's `updatedAt`, none for the first put. The
|
||||
/// provenance is the asker's, as for `Admit`.
|
||||
PersonaPut {
|
||||
instance: Slug,
|
||||
provenance: PipelineProvenance,
|
||||
state: Value,
|
||||
expected_updated_at: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl HuginnMindRequest {
|
||||
/// The envelope's `operation`.
|
||||
pub fn operation(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Whoami => "whoami",
|
||||
Self::Admit(_) => "admit",
|
||||
Self::View { .. } => "view",
|
||||
Self::Query { .. } => "query",
|
||||
Self::PersonaGet { .. } => "persona_get",
|
||||
Self::PersonaPut { .. } => "persona_put",
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance the request declares; `Whoami` declares none.
|
||||
pub fn instance(&self) -> Option<&Slug> {
|
||||
match self {
|
||||
Self::Whoami => None,
|
||||
Self::Admit(batch) => Some(&batch.instance),
|
||||
Self::View { instance, .. }
|
||||
| Self::Query { instance, .. }
|
||||
| Self::PersonaGet { instance }
|
||||
| Self::PersonaPut { instance, .. } => Some(instance),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every answer a mind gives. A refusal is data in the response, never a
|
||||
/// transport failure: the read side carries `Refused`, the write side carries
|
||||
/// the outcome's own `Refused`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum HuginnMindResponse {
|
||||
Whoami(MindStatus),
|
||||
Admit(PipelineAdmissionOutcome),
|
||||
View(Option<Box<PipelineDocumentView>>),
|
||||
Query(PipelineSelectionPage),
|
||||
Refused(MindRefusal),
|
||||
Persona(Option<PersonaStateView>),
|
||||
PersonaPut(PersonaPutOutcome),
|
||||
/// The answer did not fit one send and is being held for the client to
|
||||
/// fetch. Nothing in a mind produces this: the daemon's serve module does,
|
||||
/// in place of an answer, and the answer it stands for is the named
|
||||
/// MessagePack of the `HuginnMindResponse` the mind gave.
|
||||
Deferred(DeferredAnswer),
|
||||
}
|
||||
|
||||
/// Where the body of an answer that did not fit one send can be fetched: the
|
||||
/// reference's own manifest, whose `contentHash` is the SHA-256 of the answer's
|
||||
/// encoded bytes and whose chunks are asked for, one at a time, on the session
|
||||
/// this arrived on. Row-level facts come from asking again with a header
|
||||
/// projection; there is no summary.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct DeferredAnswer {
|
||||
#[schemars(schema_with = "manifest_array")]
|
||||
pub manifest: CultMeshCdnArtifactManifest,
|
||||
}
|
||||
|
||||
impl HuginnMindResponse {
|
||||
/// The envelope's `status`, in the C# reference's vocabulary: `rejected`
|
||||
/// exactly for a refusal, `accepted` otherwise. `Conflict` and
|
||||
/// `AlreadyAdmitted` are answers about the mind, not refusals of the
|
||||
/// request. A `Deferred` is nominally `accepted`; the daemon sets the
|
||||
/// envelope of a deferred answer to the status of the answer it stands for.
|
||||
pub fn status(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Refused(_)
|
||||
| Self::Admit(PipelineAdmissionOutcome::Refused(_))
|
||||
| Self::PersonaPut(PersonaPutOutcome::Refused(_)) => "rejected",
|
||||
_ => "accepted",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the semantic index has caught up with the mind. The mind decides
|
||||
/// none of it: the daemon's index worker reports it, in memory, and a restart
|
||||
/// recomputes it. `pending` counts documents not yet known to be in the index.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum IndexStatus {
|
||||
/// The worker has not yet compared the mind with the collection.
|
||||
Reconciling { pending: u32 },
|
||||
/// Every indexable document is in the collection.
|
||||
Current,
|
||||
/// Reconciled, and indexing what is still pending.
|
||||
Behind { pending: u32 },
|
||||
/// The last attempt failed (the embedder or the vector store is
|
||||
/// unreachable, or refused); it is retried with a backoff and nothing is
|
||||
/// dropped. `attempts` counts consecutive failures.
|
||||
Failing { pending: u32, attempts: u32, error: String },
|
||||
/// The collection belongs to another writer. The worker never recreates
|
||||
/// it; it re-reads it on the same backoff.
|
||||
Refused { pending: u32, attempts: u32, reason: String },
|
||||
}
|
||||
|
||||
/// What a mind says about itself: the typed state a dashboard projects.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct MindStatus {
|
||||
pub instance: Slug,
|
||||
pub schema_epoch: String,
|
||||
/// Pipeline documents in the image; the epoch record and the receipts are
|
||||
/// not documents and are not counted here.
|
||||
pub documents: u32,
|
||||
pub receipts: u32,
|
||||
pub index: IndexStatus,
|
||||
/// The persona door as `PersonaGet` would find it.
|
||||
pub persona: PersonaStatus,
|
||||
}
|
||||
|
||||
/// What the persona door holds, in the one vocabulary the door itself answers
|
||||
/// in: nothing yet, a document with this `updatedAt`, or a stored document the
|
||||
/// door cannot read (`PersonaGet` and every put answer `Unavailable`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum PersonaStatus {
|
||||
Absent,
|
||||
Stored { updated_at: String },
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
impl<S: MindStore> Mind<S> {
|
||||
/// `whoami`, derived from the image every time it is asked, and from the
|
||||
/// index status the caller holds: the mind stores neither.
|
||||
pub fn status(&self, index: IndexStatus) -> MindStatus {
|
||||
let mut documents = 0_u32;
|
||||
let mut receipts = 0_u32;
|
||||
for envelope in self.envelopes() {
|
||||
if envelope.r#type == HuginnCommitReceipt::TYPE {
|
||||
receipts += 1;
|
||||
} else if PipelineKind::ALL.iter().any(|kind| kind.type_id() == envelope.r#type) {
|
||||
documents += 1;
|
||||
}
|
||||
}
|
||||
MindStatus {
|
||||
instance: self.instance().clone(),
|
||||
schema_epoch: PIPELINE_SCHEMA_EPOCH.to_string(),
|
||||
documents,
|
||||
receipts,
|
||||
index,
|
||||
persona: match self.persona() {
|
||||
Ok(None) => PersonaStatus::Absent,
|
||||
Ok(Some(view)) => PersonaStatus::Stored { updated_at: view.updated_at },
|
||||
Err(_) => PersonaStatus::Unreadable,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::query::PipelinePageItems;
|
||||
use crate::fixtures::{CAMPAIGN, INSTANCE, OTHER_INSTANCE, instance, provenance, r, seeded, slug};
|
||||
use crate::receipt::Faculty;
|
||||
|
||||
fn requests() -> Vec<HuginnMindRequest> {
|
||||
let batch = PipelineAdmissionBatch {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: provenance(Faculty::Hands),
|
||||
documents: vec![instance(INSTANCE)],
|
||||
};
|
||||
vec![
|
||||
HuginnMindRequest::Whoami,
|
||||
HuginnMindRequest::Admit(batch),
|
||||
HuginnMindRequest::View { instance: slug(INSTANCE), id: r(PipelineKind::Campaign, CAMPAIGN) },
|
||||
HuginnMindRequest::Query { instance: slug(OTHER_INSTANCE), selection: Selection::default(), semantic: None },
|
||||
HuginnMindRequest::PersonaGet { instance: slug(INSTANCE) },
|
||||
HuginnMindRequest::PersonaPut {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: provenance(Faculty::Hands),
|
||||
state: serde_json::json!({ "updatedAt": "2026-10-10T10:00:00Z", "n": [1, 2.5, null, "x"] }),
|
||||
expected_updated_at: Some("2026-10-10T09:00:00Z".into()),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn responses() -> Vec<HuginnMindResponse> {
|
||||
let refusal = MindRefusal::ForeignInstance { declared: OTHER_INSTANCE.into(), mind: INSTANCE.into() };
|
||||
vec![
|
||||
HuginnMindResponse::Whoami(seeded().status(IndexStatus::Current)),
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id: "r1".into() }),
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Conflict { identities: vec![] }),
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal.clone())),
|
||||
HuginnMindResponse::View(None),
|
||||
HuginnMindResponse::Query(PipelineSelectionPage {
|
||||
matched: 0,
|
||||
as_of: 1,
|
||||
next: None,
|
||||
items: PipelinePageItems::Headers(vec![]),
|
||||
edges: None,
|
||||
}),
|
||||
HuginnMindResponse::Refused(refusal),
|
||||
HuginnMindResponse::Persona(None),
|
||||
HuginnMindResponse::Persona(Some(PersonaStateView {
|
||||
value: serde_json::json!({ "personaId": INSTANCE }),
|
||||
updated_at: "2026-10-10T10:00:00Z".into(),
|
||||
receipt_id: "mind-commit-1".into(),
|
||||
})),
|
||||
HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed { receipt_id: "mind-commit-2".into() }),
|
||||
HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(MindRefusal::PersonaNotCanonical)),
|
||||
HuginnMindResponse::Deferred(DeferredAnswer {
|
||||
manifest: cultnet_rs::pack_content("huginn.mind_response", "package", "", "", "", b"body", 4)
|
||||
.unwrap()
|
||||
.0,
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
/// The vocabulary is the mind's methods, the declared instance is on every
|
||||
/// request that names a mind, and the envelope's status is derived from
|
||||
/// the response rather than chosen by whoever sends it.
|
||||
#[test]
|
||||
fn the_wire_vocabulary_is_the_minds_methods_and_status_is_derived_from_the_response() {
|
||||
let names: Vec<&str> = requests().iter().map(|request| request.operation()).collect();
|
||||
assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put"]);
|
||||
for request in requests() {
|
||||
let declared = request.instance().is_none();
|
||||
assert_eq!(declared, matches!(request, HuginnMindRequest::Whoami), "{request:?}");
|
||||
let bytes = rmp_serde::to_vec_named(&request).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<HuginnMindRequest>(&bytes).unwrap(), request);
|
||||
}
|
||||
assert_eq!(
|
||||
requests()[3].instance(),
|
||||
Some(&slug(OTHER_INSTANCE)),
|
||||
"the request's instance is the one it declares, not the mind's"
|
||||
);
|
||||
|
||||
for response in responses() {
|
||||
let rejected = matches!(
|
||||
response,
|
||||
HuginnMindResponse::Refused(_)
|
||||
| HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(_))
|
||||
| HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(_))
|
||||
);
|
||||
assert_eq!(response.status(), if rejected { "rejected" } else { "accepted" }, "{response:?}");
|
||||
let bytes = rmp_serde::to_vec_named(&response).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<HuginnMindResponse>(&bytes).unwrap(), response);
|
||||
}
|
||||
}
|
||||
|
||||
/// The two files the catalog publishes are the derivation of the two
|
||||
/// types, byte for byte.
|
||||
#[test]
|
||||
fn published_wire_schemas_match_derivation() {
|
||||
let request = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindRequest)).unwrap();
|
||||
let response = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindResponse)).unwrap();
|
||||
assert_eq!(MIND_REQUEST_SCHEMA_JSON.replace("\r\n", "\n"), request);
|
||||
assert_eq!(MIND_RESPONSE_SCHEMA_JSON.replace("\r\n", "\n"), response);
|
||||
// The selection is CultLib's, referenced by the `$id` it publishes and
|
||||
// not copied into this schema.
|
||||
let selection = "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json";
|
||||
assert!(request.contains(&format!("\"$ref\": \"{selection}\"")));
|
||||
assert!(!request.contains("\"cursor\""), "no second copy of the selection's shape");
|
||||
}
|
||||
}
|
||||
//! The organ's request and response vocabulary: one operation per `Mind`
|
||||
//! method and `whoami`. Payloads are the admission and read types unchanged.
|
||||
//! The daemon carries these in CultNet's operation envelope; the client
|
||||
//! constructs them. Nothing here validates a document, derives a status or
|
||||
//! names a transport.
|
||||
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultnet_rs::{CultMeshCdnArtifactManifest, Selection};
|
||||
use eureka_pipeline::{PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Slug};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::admission::{PipelineAdmissionBatch, PipelineAdmissionOutcome};
|
||||
use crate::mind::Mind;
|
||||
use crate::persona::{PersonaPutOutcome, PersonaStateView};
|
||||
use crate::query::{PipelineDocumentView, PipelineSelectionPage, SemanticQuery};
|
||||
use crate::receipt::{HuginnCommitReceipt, PipelineProvenance};
|
||||
use crate::refusal::MindRefusal;
|
||||
use crate::store::MindStore;
|
||||
|
||||
/// The envelope's `service_id`: one service, one mind, whichever mind the
|
||||
/// process opened.
|
||||
pub const MIND_SERVICE_ID: &str = "huginn.mind";
|
||||
pub const MIND_REQUEST_SCHEMA: &str = "huginn.mind_request.v1";
|
||||
pub const MIND_RESPONSE_SCHEMA: &str = "huginn.mind_response.v1";
|
||||
|
||||
/// The largest answer that is deferred rather than refused, measured on the
|
||||
/// encoded payload. The daemon refuses past it and a client caps its fetch at
|
||||
/// it, so both sides read one number.
|
||||
pub const MAX_DEFERRED_BODY_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
/// The published JSON schema of each wire type, as the catalog advertises it.
|
||||
/// The files are derived from the types below and pinned byte for byte by
|
||||
/// `published_wire_schemas_match_derivation`, so the catalog cannot advertise
|
||||
/// a shape the crate does not speak.
|
||||
pub const MIND_REQUEST_SCHEMA_JSON: &str =
|
||||
include_str!("../../../schemas/cultnet/huginn.mind_request.v1.schema.json");
|
||||
pub const MIND_RESPONSE_SCHEMA_JSON: &str =
|
||||
include_str!("../../../schemas/cultnet/huginn.mind_response.v1.schema.json");
|
||||
|
||||
/// The request's `selection` is CultNet's, and its published schema is
|
||||
/// CultLib's: a `$ref` to the `$id` it publishes, so one owner holds the
|
||||
/// selection's shape and nothing here copies it.
|
||||
fn selection_ref(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
schemars::json_schema!({
|
||||
"$ref": "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json"
|
||||
})
|
||||
}
|
||||
|
||||
/// The deferred answer's manifest is CultMesh's own type, a positional array
|
||||
/// the C# reference defines (`CultMeshCdnArtifactManifest`, schema version
|
||||
/// `gamecult.mesh.cdn_artifact_manifest.v1`). CultLib publishes no JSON schema
|
||||
/// for it, so the schema says what the reference says: an array of its ten
|
||||
/// fields in order, and nothing here copies their meaning.
|
||||
fn manifest_array(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
schemars::json_schema!({
|
||||
"description": "gamecult.mesh.cdn_artifact_manifest.v1, the C# reference's CultMeshCdnArtifactManifest as its positional array: [artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc, chunks[[chunkHash, offset, sizeBytes, recordKey]], tags, metadata].",
|
||||
"type": "array"
|
||||
})
|
||||
}
|
||||
|
||||
/// Every operation a mind answers. `Admit` carries the batch whole because the
|
||||
/// batch already names the instance and the asker; a second `instance` beside
|
||||
/// it would be two declarations. Every read names the instance because ruling
|
||||
/// 14 refuses another mind's identity whatever the transport, and a read of
|
||||
/// the wrong mind is that same collision on the read side. `Whoami` names
|
||||
/// none: it is how a client learns which mind it reached.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum HuginnMindRequest {
|
||||
Whoami,
|
||||
Admit(PipelineAdmissionBatch),
|
||||
View { instance: Slug, id: PipelineRef },
|
||||
Query {
|
||||
instance: Slug,
|
||||
#[schemars(schema_with = "selection_ref")]
|
||||
selection: Selection,
|
||||
semantic: Option<SemanticQuery>,
|
||||
},
|
||||
/// The mind's persona document, if one is stored.
|
||||
PersonaGet { instance: Slug },
|
||||
/// Replaces the mind's persona document whole. `expected_updated_at` is
|
||||
/// the stored document's `updatedAt`, none for the first put. The
|
||||
/// provenance is the asker's, as for `Admit`.
|
||||
PersonaPut {
|
||||
instance: Slug,
|
||||
provenance: PipelineProvenance,
|
||||
state: Value,
|
||||
expected_updated_at: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl HuginnMindRequest {
|
||||
/// The envelope's `operation`.
|
||||
pub fn operation(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Whoami => "whoami",
|
||||
Self::Admit(_) => "admit",
|
||||
Self::View { .. } => "view",
|
||||
Self::Query { .. } => "query",
|
||||
Self::PersonaGet { .. } => "persona_get",
|
||||
Self::PersonaPut { .. } => "persona_put",
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance the request declares; `Whoami` declares none.
|
||||
pub fn instance(&self) -> Option<&Slug> {
|
||||
match self {
|
||||
Self::Whoami => None,
|
||||
Self::Admit(batch) => Some(&batch.instance),
|
||||
Self::View { instance, .. }
|
||||
| Self::Query { instance, .. }
|
||||
| Self::PersonaGet { instance }
|
||||
| Self::PersonaPut { instance, .. } => Some(instance),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every answer a mind gives. A refusal is data in the response, never a
|
||||
/// transport failure: the read side carries `Refused`, the write side carries
|
||||
/// the outcome's own `Refused`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum HuginnMindResponse {
|
||||
Whoami(MindStatus),
|
||||
Admit(PipelineAdmissionOutcome),
|
||||
View(Option<Box<PipelineDocumentView>>),
|
||||
Query(PipelineSelectionPage),
|
||||
Refused(MindRefusal),
|
||||
Persona(Option<PersonaStateView>),
|
||||
PersonaPut(PersonaPutOutcome),
|
||||
/// The answer did not fit one send and is being held for the client to
|
||||
/// fetch. Nothing in a mind produces this: the daemon's serve module does,
|
||||
/// in place of an answer, and the answer it stands for is the named
|
||||
/// MessagePack of the `HuginnMindResponse` the mind gave.
|
||||
Deferred(DeferredAnswer),
|
||||
}
|
||||
|
||||
/// Where the body of an answer that did not fit one send can be fetched: the
|
||||
/// reference's own manifest, whose `contentHash` is the SHA-256 of the answer's
|
||||
/// encoded bytes and whose chunks are asked for, one at a time, on the session
|
||||
/// this arrived on. Row-level facts come from asking again with a header
|
||||
/// projection; there is no summary.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct DeferredAnswer {
|
||||
#[schemars(schema_with = "manifest_array")]
|
||||
pub manifest: CultMeshCdnArtifactManifest,
|
||||
}
|
||||
|
||||
impl HuginnMindResponse {
|
||||
/// The envelope's `status`, in the C# reference's vocabulary: `rejected`
|
||||
/// exactly for a refusal, `accepted` otherwise. `Conflict` and
|
||||
/// `AlreadyAdmitted` are answers about the mind, not refusals of the
|
||||
/// request. A `Deferred` is nominally `accepted`; the daemon sets the
|
||||
/// envelope of a deferred answer to the status of the answer it stands for.
|
||||
pub fn status(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Refused(_)
|
||||
| Self::Admit(PipelineAdmissionOutcome::Refused(_))
|
||||
| Self::PersonaPut(PersonaPutOutcome::Refused(_)) => "rejected",
|
||||
_ => "accepted",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the semantic index has caught up with the mind. The mind decides
|
||||
/// none of it: the daemon's index worker reports it, in memory, and a restart
|
||||
/// recomputes it. `pending` counts documents not yet known to be in the index.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum IndexStatus {
|
||||
/// The worker has not yet compared the mind with the collection.
|
||||
Reconciling { pending: u32 },
|
||||
/// Every indexable document is in the collection.
|
||||
Current,
|
||||
/// Reconciled, and indexing what is still pending.
|
||||
Behind { pending: u32 },
|
||||
/// The last attempt failed (the embedder or the vector store is
|
||||
/// unreachable, or refused); it is retried with a backoff and nothing is
|
||||
/// dropped. `attempts` counts consecutive failures.
|
||||
Failing { pending: u32, attempts: u32, error: String },
|
||||
/// The collection belongs to another writer. The worker never recreates
|
||||
/// it; it re-reads it on the same backoff.
|
||||
Refused { pending: u32, attempts: u32, reason: String },
|
||||
}
|
||||
|
||||
/// What a mind says about itself: the typed state a dashboard projects.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct MindStatus {
|
||||
pub instance: Slug,
|
||||
pub schema_epoch: String,
|
||||
/// Pipeline documents in the image; the epoch record and the receipts are
|
||||
/// not documents and are not counted here.
|
||||
pub documents: u32,
|
||||
pub receipts: u32,
|
||||
pub index: IndexStatus,
|
||||
/// The persona door as `PersonaGet` would find it.
|
||||
pub persona: PersonaStatus,
|
||||
}
|
||||
|
||||
/// What the persona door holds, in the one vocabulary the door itself answers
|
||||
/// in: nothing yet, a document with this `updatedAt`, or a stored document the
|
||||
/// door cannot read (`PersonaGet` and every put answer `Unavailable`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum PersonaStatus {
|
||||
Absent,
|
||||
Stored { updated_at: String },
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
impl<S: MindStore> Mind<S> {
|
||||
/// `whoami`, derived from the image every time it is asked, and from the
|
||||
/// index status the caller holds: the mind stores neither.
|
||||
pub fn status(&self, index: IndexStatus) -> MindStatus {
|
||||
let mut documents = 0_u32;
|
||||
let mut receipts = 0_u32;
|
||||
for envelope in self.envelopes() {
|
||||
if envelope.r#type == HuginnCommitReceipt::TYPE {
|
||||
receipts += 1;
|
||||
} else if PipelineKind::ALL.iter().any(|kind| kind.type_id() == envelope.r#type) {
|
||||
documents += 1;
|
||||
}
|
||||
}
|
||||
MindStatus {
|
||||
instance: self.instance().clone(),
|
||||
schema_epoch: PIPELINE_SCHEMA_EPOCH.to_string(),
|
||||
documents,
|
||||
receipts,
|
||||
index,
|
||||
persona: match self.persona() {
|
||||
Ok(None) => PersonaStatus::Absent,
|
||||
Ok(Some(view)) => PersonaStatus::Stored { updated_at: view.updated_at },
|
||||
Err(_) => PersonaStatus::Unreadable,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::query::PipelinePageItems;
|
||||
use crate::fixtures::{CAMPAIGN, INSTANCE, OTHER_INSTANCE, instance, provenance, r, seeded, slug};
|
||||
use crate::receipt::Faculty;
|
||||
|
||||
fn requests() -> Vec<HuginnMindRequest> {
|
||||
let batch = PipelineAdmissionBatch {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: provenance(Faculty::Hands),
|
||||
documents: vec![instance(INSTANCE)],
|
||||
};
|
||||
vec![
|
||||
HuginnMindRequest::Whoami,
|
||||
HuginnMindRequest::Admit(batch),
|
||||
HuginnMindRequest::View { instance: slug(INSTANCE), id: r(PipelineKind::Campaign, CAMPAIGN) },
|
||||
HuginnMindRequest::Query { instance: slug(OTHER_INSTANCE), selection: Selection::default(), semantic: None },
|
||||
HuginnMindRequest::PersonaGet { instance: slug(INSTANCE) },
|
||||
HuginnMindRequest::PersonaPut {
|
||||
instance: slug(INSTANCE),
|
||||
provenance: provenance(Faculty::Hands),
|
||||
state: serde_json::json!({ "updatedAt": "2026-10-10T10:00:00Z", "n": [1, 2.5, null, "x"] }),
|
||||
expected_updated_at: Some("2026-10-10T09:00:00Z".into()),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn responses() -> Vec<HuginnMindResponse> {
|
||||
let refusal = MindRefusal::ForeignInstance { declared: OTHER_INSTANCE.into(), mind: INSTANCE.into() };
|
||||
vec![
|
||||
HuginnMindResponse::Whoami(seeded().status(IndexStatus::Current)),
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id: "r1".into() }),
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Conflict { identities: vec![] }),
|
||||
HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal.clone())),
|
||||
HuginnMindResponse::View(None),
|
||||
HuginnMindResponse::Query(PipelineSelectionPage {
|
||||
matched: 0,
|
||||
as_of: 1,
|
||||
next: None,
|
||||
items: PipelinePageItems::Headers(vec![]),
|
||||
edges: None,
|
||||
}),
|
||||
HuginnMindResponse::Refused(refusal),
|
||||
HuginnMindResponse::Persona(None),
|
||||
HuginnMindResponse::Persona(Some(PersonaStateView {
|
||||
value: serde_json::json!({ "personaId": INSTANCE }),
|
||||
updated_at: "2026-10-10T10:00:00Z".into(),
|
||||
receipt_id: "mind-commit-1".into(),
|
||||
})),
|
||||
HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed { receipt_id: "mind-commit-2".into() }),
|
||||
HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(MindRefusal::PersonaNotCanonical)),
|
||||
HuginnMindResponse::Deferred(DeferredAnswer {
|
||||
manifest: cultnet_rs::pack_content("huginn.mind_response", "package", "", "", "", b"body", 4)
|
||||
.unwrap()
|
||||
.0,
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
/// The vocabulary is the mind's methods, the declared instance is on every
|
||||
/// request that names a mind, and the envelope's status is derived from
|
||||
/// the response rather than chosen by whoever sends it.
|
||||
#[test]
|
||||
fn the_wire_vocabulary_is_the_minds_methods_and_status_is_derived_from_the_response() {
|
||||
let names: Vec<&str> = requests().iter().map(|request| request.operation()).collect();
|
||||
assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put"]);
|
||||
for request in requests() {
|
||||
let declared = request.instance().is_none();
|
||||
assert_eq!(declared, matches!(request, HuginnMindRequest::Whoami), "{request:?}");
|
||||
let bytes = rmp_serde::to_vec_named(&request).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<HuginnMindRequest>(&bytes).unwrap(), request);
|
||||
}
|
||||
assert_eq!(
|
||||
requests()[3].instance(),
|
||||
Some(&slug(OTHER_INSTANCE)),
|
||||
"the request's instance is the one it declares, not the mind's"
|
||||
);
|
||||
|
||||
for response in responses() {
|
||||
let rejected = matches!(
|
||||
response,
|
||||
HuginnMindResponse::Refused(_)
|
||||
| HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(_))
|
||||
| HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(_))
|
||||
);
|
||||
assert_eq!(response.status(), if rejected { "rejected" } else { "accepted" }, "{response:?}");
|
||||
let bytes = rmp_serde::to_vec_named(&response).unwrap();
|
||||
assert_eq!(rmp_serde::from_slice::<HuginnMindResponse>(&bytes).unwrap(), response);
|
||||
}
|
||||
}
|
||||
|
||||
/// The two files the catalog publishes are the derivation of the two
|
||||
/// types, byte for byte.
|
||||
#[test]
|
||||
fn published_wire_schemas_match_derivation() {
|
||||
let request = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindRequest)).unwrap();
|
||||
let response = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindResponse)).unwrap();
|
||||
assert_eq!(MIND_REQUEST_SCHEMA_JSON.replace("\r\n", "\n"), request);
|
||||
assert_eq!(MIND_RESPONSE_SCHEMA_JSON.replace("\r\n", "\n"), response);
|
||||
// The selection is CultLib's, referenced by the `$id` it publishes and
|
||||
// not copied into this schema.
|
||||
let selection = "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json";
|
||||
assert!(request.contains(&format!("\"$ref\": \"{selection}\"")));
|
||||
assert!(!request.contains("\"cursor\""), "no second copy of the selection's shape");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue