From 1db7ff3946596122482a7f845114e0759395ee30 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 10 Oct 2026 08:06:56 +0200 Subject: [PATCH] huginn CLI: decode errors report category and position, never serde's message; a refused read-back is the mind's no; clap behind a default cli feature Co-Authored-By: Claude Opus 5.5 --- crates/eureka-state/Cargo.toml | 17 ++++- crates/eureka-state/src/bin/huginn/door.rs | 79 +++++++++++++++------- crates/eureka-state/src/bin/huginn/main.rs | 3 +- crates/eureka-state/tests/cli.rs | 58 +++++++++++++++- 4 files changed, 127 insertions(+), 30 deletions(-) diff --git a/crates/eureka-state/Cargo.toml b/crates/eureka-state/Cargo.toml index fd7f720..986bbf4 100644 --- a/crates/eureka-state/Cargo.toml +++ b/crates/eureka-state/Cargo.toml @@ -15,9 +15,24 @@ publish.workspace = true # (`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"] } +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"] } diff --git a/crates/eureka-state/src/bin/huginn/door.rs b/crates/eureka-state/src/bin/huginn/door.rs index 67620b6..d460da1 100644 --- a/crates/eureka-state/src/bin/huginn/door.rs +++ b/crates/eureka-state/src/bin/huginn/door.rs @@ -11,7 +11,7 @@ use cultnet_rs::Selection; use huginn_mind::eureka_pipeline::{PipelineDocument, PipelineKind}; use serde::Serialize; use serde::de::DeserializeOwned; -use serde_json::Value; +use serde_json::{Value, error::Category}; use crate::trouble::Trouble; @@ -43,30 +43,36 @@ fn stdin() -> Result { /// A batch: a JSON array of `{kind, value}` documents, or one such object. pub fn documents(text: &str) -> Result, Trouble> { - let items = match parse(text)? { - Value::Array(items) => items, - object @ Value::Object(_) => vec![object], + let value = parse(text)?; + let (items, typed): (&[Value], Vec) = match &value { + Value::Array(items) => (items.as_slice(), objects(items).and_then(|()| from_text(text, "documents"))?), + Value::Object(_) => (std::slice::from_ref(&value), vec![from_text(text, "documents[0]")?]), _ => return Err(Trouble::invalid("the documents must be a JSON array of {kind, value} objects")), }; - let mut typed = Vec::with_capacity(items.len()); + let kept = reserialise(&typed, "documents")?; let mut lost = Vec::new(); - for (index, item) in items.into_iter().enumerate() { - let (document, paths) = decode(item, &format!("documents[{index}]"))?; - typed.push(document); - lost.extend(paths); + for (index, (given, held)) in items.iter().zip(&kept).enumerate() { + dropped(given, held, &format!("documents[{index}]"), &mut lost); } refuse_lost(&lost)?; Ok(typed) } pub fn selection(text: &str) -> Result { - selection_value(parse(text)?) + let value = parse(text)?; + if !value.is_object() { + return Err(Trouble::invalid("selection must be a JSON object")); + } + let typed: Selection = from_text(text, "selection")?; + let kept = reserialise(std::slice::from_ref(&typed), "selection")?; + let mut lost = Vec::new(); + dropped(&value, &kept[0], "selection", &mut lost); + refuse_lost(&lost)?; + Ok(typed) } -pub fn selection_value(value: Value) -> Result { - let (selection, lost) = decode(value, "selection")?; - refuse_lost(&lost)?; - Ok(selection) +pub fn selection_value(value: &Value) -> Result { + selection(&value.to_string()) } /// The kind a pipeline id names in its middle segment (`::`). @@ -83,21 +89,42 @@ pub fn kind_of(id: &str) -> Result { } fn parse(text: &str) -> Result { - serde_json::from_str(text).map_err(|error| Trouble::invalid(format!("not JSON: {error}"))) + serde_json::from_str(text).map_err(|error| Trouble::invalid(format!("not JSON: {}", place(&error)))) } -/// The typed value of one JSON object and the paths its decode lost. Serde -/// would also read a struct from an array, positionally, so only an object -/// is a document or a selection. -fn decode(input: Value, at: &str) -> Result<(T, Vec), Trouble> { - if !input.is_object() { - return Err(Trouble::invalid(format!("{at} must be a JSON object"))); +/// Where and what kind of failure a decode hit, never what the input said: +/// serde's own message quotes the offending value whole. +fn place(error: &serde_json::Error) -> String { + let category = match error.classify() { + Category::Io => "unreadable input", + Category::Syntax => "syntax", + Category::Data => "a value of the wrong type, an unknown variant or a missing field", + Category::Eof => "unexpected end", + }; + format!("{category} at line {} column {}", error.line(), error.column()) +} + +/// Serde would also read a struct from an array, positionally, so only an +/// object is a document or a selection. +fn objects(items: &[Value]) -> Result<(), Trouble> { + match items.iter().position(|item| !item.is_object()) { + None => Ok(()), + Some(index) => Err(Trouble::invalid(format!("documents[{index}] must be a JSON object"))), } - let typed: T = serde_json::from_value(input.clone()).map_err(|error| Trouble::invalid(format!("{at} does not decode: {error}")))?; - let kept = serde_json::to_value(&typed).map_err(|error| Trouble::Internal(format!("{at} does not re-serialise: {error}")))?; - let mut paths = Vec::new(); - dropped(&input, &kept, at, &mut paths); - Ok((typed, paths)) +} + +/// The typed value of the text, decoded from the text itself so the failure +/// has a real line and column. +fn from_text(text: &str, at: &str) -> Result { + serde_json::from_str(text).map_err(|error| Trouble::invalid(format!("{at} does not decode: {}", place(&error)))) +} + +/// What the typed values hold, as the JSON items to compare with the input. +fn reserialise(typed: &[T], at: &str) -> Result, Trouble> { + typed + .iter() + .map(|item| serde_json::to_value(item).map_err(|_| Trouble::Internal(format!("{at} does not re-serialise")))) + .collect() } fn refuse_lost(paths: &[String]) -> Result<(), Trouble> { diff --git a/crates/eureka-state/src/bin/huginn/main.rs b/crates/eureka-state/src/bin/huginn/main.rs index a6a0232..c457f92 100644 --- a/crates/eureka-state/src/bin/huginn/main.rs +++ b/crates/eureka-state/src/bin/huginn/main.rs @@ -170,7 +170,7 @@ fn run(settings: &Settings, command: Command) -> Result { } Command::Recipe(recipe) => { let ask = recipe.ask()?; - query(settings, door::selection_value(ask.selection)?, ask.semantic, ask.page.cursor, ask.page.documents) + 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 } => { @@ -319,6 +319,7 @@ fn read_back(settings: &Settings, sent: &[PipelineDocument]) -> Result page, + HuginnMindResponse::Refused(refusal) => return Ok(refused(&refusal)), other => return Err(unexpected(&other)), }; let PipelinePageItems::Documents(stored) = page.items else { diff --git a/crates/eureka-state/tests/cli.rs b/crates/eureka-state/tests/cli.rs index 68e7c89..f83a584 100644 --- a/crates/eureka-state/tests/cli.rs +++ b/crates/eureka-state/tests/cli.rs @@ -16,7 +16,7 @@ use huginn_mind::eureka_pipeline::{ StructuralDelta, pipeline_key, }; use huginn_mind::{ - AdmissionFacts, HuginnMindRequest, HuginnMindResponse, IndexStatus, MindStatus, PipelineAdmissionOutcome, PipelineDocumentView, + AdmissionFacts, HuginnMindRequest, HuginnMindResponse, IndexStatus, MindRefusal, MindStatus, PipelineAdmissionOutcome, PipelineDocumentView, PipelinePageItems, PipelineProvenance, PipelineSelectionPage, PipelineStatus, }; use serde_json::{Value, json}; @@ -392,7 +392,7 @@ fn a_falsy_unknown_value_is_still_a_loss() { fn a_document_that_does_not_decode_is_invalid_input() { let dir = tempfile::tempdir().unwrap(); let cases = [ - (json!([{ "kind": "nonsense", "value": {} }]), "documents[0] does not decode"), + (json!([{ "kind": "nonsense", "value": {} }]), "documents does not decode"), (json!("text"), "JSON array"), (json!([[]]), "documents[0] must be a JSON object"), (json!([]), "1 to 64"), @@ -413,6 +413,60 @@ fn a_document_that_does_not_decode_is_invalid_input() { assert!(missing.err.contains("cannot read /no/such/file.json"), "{}", missing.err); } +#[test] +fn a_document_that_does_not_decode_never_echoes_its_values() { + let dir = tempfile::tempdir().unwrap(); + let mut string_for_number = report("canary"); + string_for_number["value"]["attempt"] = json!("CANARY-NUMBER"); + let mut long_string_for_list = campaign_json(); + long_string_for_list["value"]["repos"] = json!(format!("CANARY-LIST{}", "x".repeat(60_000))); + let unknown_kind = json!({ "kind": "CANARY-KIND", "value": {} }); + let mut unknown_variant = serde_json::to_value(ruling(None)).unwrap(); + unknown_variant["value"]["authority"] = json!("CANARY-VARIANT"); + for (n, document) in [string_for_number, long_string_for_list, unknown_kind, unknown_variant].into_iter().enumerate() { + let file = write(&dir, &format!("canary{n}.json"), &json!([document])); + let ran = at(closed_port(), &admit_args(&file), None); + assert_eq!(ran.code, 2, "case {n}: {}", ran.err); + assert!(ran.err.starts_with("InvalidInput: documents does not decode: "), "case {n}: {}", ran.err); + assert!(ran.err.contains(" at line 1 column "), "case {n}: {}", ran.err); + assert!(!ran.err.contains("CANARY") && !ran.out.contains("CANARY"), "case {n}: {}", ran.err); + assert!(ran.err.len() < 300, "stderr is bounded whatever the input: {} bytes", ran.err.len()); + } + let ran = at(closed_port(), &["query", r#"{"limit": "CANARY-LIMIT"}"#], None); + assert_eq!(ran.code, 2); + assert!(ran.err.starts_with("InvalidInput: selection does not decode: "), "{}", ran.err); + assert!(!ran.err.contains("CANARY") && ran.err.len() < 300, "{}", ran.err); + let ran = at(closed_port(), &admit_args("-"), Some(r#"[{"kind": "campaign", "value": CANARY-SYNTAX}]"#)); + assert_eq!(ran.code, 2); + assert!(ran.err.starts_with("InvalidInput: not JSON: syntax at line 1 column "), "{}", ran.err); + assert!(!ran.err.contains("CANARY"), "{}", ran.err); +} + +#[test] +fn a_refused_read_back_is_the_minds_no_with_the_receipt_printed() { + let dir = tempfile::tempdir().unwrap(); + let file = write(&dir, "ruling.json", &json!([ruling(None)])); + let server = scripted(|message| { + let (_, request) = decode_request(message).expect("a mind request"); + match request { + HuginnMindRequest::Admit(_) => answer( + "admit", + &HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { + receipt_id: "mind-commit-x".into(), + committed_at: "2026-10-10T00:00:00Z".into(), + writes: vec![], + }), + ), + _ => answer("query", &HuginnMindResponse::Refused(MindRefusal::MissingIdentity)), + } + }); + let ran = at(server.addr, &admit_args(&file), None); + assert_eq!(ran.code, 1, "{}", ran.err); + assert!(ran.out.starts_with("Committed mind-commit-x at "), "{}", ran.out); + assert!(ran.out.contains("Refused MissingIdentity"), "{}", ran.out); + assert_eq!(ran.err, ""); +} + fn view_of(document: &PipelineDocument) -> PipelineDocumentView { PipelineDocumentView { id: PipelineRef { kind: document.kind(), id: Short(pipeline_key(document).unwrap()) },