diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e31791..eb9b1db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -271,6 +271,15 @@ All notable changes to this project are documented here. The format follows `invalid_document` errors name these roots. Old rubric history stays readable. ### Fixed +- Core reads: one mistyped value in a node text field no longer fails the + whole exploration tree with `ARA100` (0.1.35, plan 24, #130). `evidence:` + keeps a plain scalar's source spelling like every other text field, so an + all-digit commit SHA (`7258910`) or `0123456` stays text. A value the parser + cannot take as text (a bare numeric `evidence:` scalar, or a mapping or list + such as the plain item `- a (rejected: b)`) is read as its exact source text + and warns `ARA230 non-text-tree-field`; reads stay complete and exit 0. + Identity fields stay strict. New fixable format rule `ARA008 + unquoted-tree-scalar`: `ara check --fix` single-quotes one-line values. - Core reads: experiment and heuristic headings accept the separators claims accept (`## E01 — Title`, `## H03 – Title`, `## E02 - Title`) and a bracketed status before the separator (`## E02 [in progress]: Title`), which becomes diff --git a/Cargo.lock b/Cargo.lock index 61ee662..13b1bb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,7 +112,7 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" [[package]] name = "ara-cli" -version = "0.1.34" +version = "0.1.35" dependencies = [ "ara-core", "arc-swap", @@ -138,7 +138,7 @@ dependencies = [ [[package]] name = "ara-core" -version = "0.1.34" +version = "0.1.35" dependencies = [ "base64", "dagre-dgl-rs", @@ -154,7 +154,7 @@ dependencies = [ [[package]] name = "ara-viewer" -version = "0.1.34" +version = "0.1.35" dependencies = [ "ara-core", "console_error_panic_hook", @@ -172,7 +172,7 @@ dependencies = [ [[package]] name = "ara-wasm" -version = "0.1.34" +version = "0.1.35" [[package]] name = "arc-swap" diff --git a/Cargo.toml b/Cargo.toml index cd13332..7bedbb2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.1.34" +version = "0.1.35" edition = "2024" license = "MPL-2.0" repository = "https://github.com/ARA-Labs/ara-cli" diff --git a/crates/ara-cli/tests/agent_reads.rs b/crates/ara-cli/tests/agent_reads.rs index 98c45ed..cfd3b8e 100644 --- a/crates/ara-cli/tests/agent_reads.rs +++ b/crates/ara-cli/tests/agent_reads.rs @@ -804,7 +804,9 @@ fn identity_lookup_does_not_require_a_representable_current_body() { artifact(dir.path(), "Parent"); std::fs::write( dir.path().join("trace/exploration_tree.yaml"), - "tree:\n - id: N01\n type: question\n title: Retained identity\n description: {opaque: invalid-shape}\n", + // `isolated` is a boolean, not a text field, so a mapping there still + // fails the tree load; text fields read such values as text (#130). + "tree:\n - id: N01\n type: question\n title: Retained identity\n isolated: {opaque: invalid-shape}\n", ) .unwrap(); let before = std::fs::read(dir.path().join("trace/exploration_tree.yaml")).unwrap(); diff --git a/crates/ara-cli/tests/agent_tree_field_tolerance.rs b/crates/ara-cli/tests/agent_tree_field_tolerance.rs new file mode 100644 index 0000000..bf8ce4c --- /dev/null +++ b/crates/ara-cli/tests/agent_tree_field_tolerance.rs @@ -0,0 +1,80 @@ +//! #130: one mistyped value in `trace/exploration_tree.yaml` no longer fails +//! the whole tree (`ARA100`). Reads go through and exit 0; a value read as +//! its source text warns `ARA230`. +use assert_cmd::Command; +use serde_json::Value; +use std::path::Path; +use tempfile::TempDir; + +fn ara() -> Command { + let mut command = Command::cargo_bin("ara").unwrap(); + command.env_remove("ARA_DIR"); + command +} +fn tree(node_fields: &str) -> TempDir { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("trace/exploration_tree.yaml"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let source = format!("tree:\n - id: N01\n type: decision\n title: Q\n{node_fields}"); + std::fs::write(path, source).unwrap(); + dir +} +/// `show N01 --full --json` stdout; panics with stderr on a refusal. +fn show(root: &Path) -> Value { + let output = ara() + .arg("-C") + .arg(root) + .args(["show", "N01", "--full", "--json"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() +} +fn decision(shown: &Value) -> &Value { + &shown["entries"][0]["fields"]["decision"] +} + +#[test] +fn text_fields_already_keep_scalar_spelling() { + // Guard: plain text fields take a numeric scalar's source spelling. + let dir = tree(" rationale: 1e5\n alternatives: [0x1F, 1.50, true]\n"); + let shown = show(dir.path()); + assert_eq!(decision(&shown)["rationale"], "1e5"); + assert_eq!( + decision(&shown)["alternatives"], + serde_json::json!(["0x1F", "1.50", "true"]) + ); +} + +#[test] +fn all_digit_commit_sha_in_evidence_keeps_its_spelling() { + let dir = tree(" evidence:\n - be13e96\n - 7258910\n - 0123456\n"); + let shown = show(dir.path()); + let notes = shown["entries"][0]["evidence_notes"].to_string(); + for sha in ["be13e96", "7258910", "0123456"] { + assert!(notes.contains(sha), "{sha} missing from {notes}"); + } +} + +#[test] +fn colon_in_plain_alternative_does_not_fail_the_tree() { + let dir = tree( + " alternatives:\n - Build on Debian 12 like the task images (rejected: its glibc is above the floor).\n - Static linking\n", + ); + let shown = show(dir.path()); + assert_eq!( + decision(&shown)["alternatives"], + serde_json::json!([ + "Build on Debian 12 like the task images (rejected: its glibc is above the floor).", + "Static linking" + ]) + ); + let warning = &shown["diagnostics"]["warnings"][0]; + assert_eq!(warning["code"], "ARA230"); + assert_eq!(warning["path"], "trace/exploration_tree.yaml:6"); + assert!(shown.get("incomplete").is_none(), "{shown}"); +} diff --git a/crates/ara-core/src/fix.rs b/crates/ara-core/src/fix.rs index ad09d4b..629d609 100644 --- a/crates/ara-core/src/fix.rs +++ b/crates/ara-core/src/fix.rs @@ -317,6 +317,7 @@ impl Applier { LintRuleId::ClaimHeaderStyle => { self.guard_ara004(diag, &base, &cand, new_claims.as_deref()) } + LintRuleId::UnquotedTreeScalar => guard_ara008(&base, &cand), }; if !accept { self.fail(diag, guard_rejection_reason(diag.rule, &base, &cand)); @@ -441,6 +442,23 @@ impl Applier { /// ARA001 structural guard: both parses must be clean normalized outcomes and /// the root→tree rewrite must be a semantic no-op. +/// Quoting a recovered value keeps every normalized field: the quoted text is +/// the text the parser already recovered. It adds no error and removes one +/// `ARA230`. +fn guard_ara008(base: &ParseOutcome, cand: &ParseOutcome) -> bool { + let (ParseOutcome::Normalized(mb, rb), ParseOutcome::Normalized(mc, rc)) = (base, cand) else { + return false; + }; + let recovered = |report: &crate::ParseReport| { + report + .warnings() + .iter() + .filter(|d| d.code == crate::RuleCode::NonTextTreeField) + .count() + }; + errors_subset(cand, base) && mb == mc && recovered(rc) < recovered(rb) +} + fn guard_ara001(base: &ParseOutcome, cand: &ParseOutcome) -> bool { match (base, cand) { (ParseOutcome::Normalized(mb, rb), ParseOutcome::Normalized(mc, rc)) => { @@ -698,6 +716,9 @@ fn applied_desc(rule: LintRuleId) -> String { LintRuleId::PivotTriggerAlias => { "renamed `trigger:` to `reason:` on a pivot node".to_string() } + LintRuleId::UnquotedTreeScalar => { + "quoted a node text value YAML did not read as a string".to_string() + } } } @@ -725,6 +746,9 @@ fn guard_rejection_reason(rule: LintRuleId, base: &ParseOutcome, cand: &ParseOut "claim-header rewrite would introduce a new parse error occurrence; left unchanged" .to_string() } + LintRuleId::UnquotedTreeScalar => { + "quoting would introduce a new parse error occurrence; left unchanged".to_string() + } LintRuleId::RootDialect => guard_reason(rule), }; } @@ -749,6 +773,9 @@ fn guard_reason(rule: LintRuleId) -> String { "claim-header rewrite would change more than the recovered claim; left unchanged" .to_string() } + LintRuleId::UnquotedTreeScalar => { + "quoting would change the parsed manifest; left unchanged".to_string() + } } } diff --git a/crates/ara-core/src/flat_yaml.rs b/crates/ara-core/src/flat_yaml.rs index dce387b..6bacd51 100644 --- a/crates/ara-core/src/flat_yaml.rs +++ b/crates/ara-core/src/flat_yaml.rs @@ -42,7 +42,41 @@ struct Arena<'a> { entries: Vec>, anchors: BTreeMap, visits: Cell, + /// Non-text values read as their source text in node text fields. + recovered: std::cell::RefCell>, } + +/// Exploration-node fields whose values are text. A value of one of these +/// that YAML did not type as a string is read as its exact source text on the +/// recovery path ([`parse`]); identity fields (`id`, `type`, `parent`, +/// `also_depends_on`) are not listed and stay strict. +const TEXT_FIELDS: [&str; 25] = [ + "title", + "support_level", + "source_refs", + "description", + "thinking", + "provenance", + "timestamp", + "result", + "status", + "exploration", + "outcome", + "why_failed", + "hypothesis", + "failure_mode", + "lesson", + "from", + "to", + "trigger", + "prior_direction", + "new_direction", + "reason", + "choice", + "alternatives", + "rationale", + "evidence", +]; impl<'a> Arena<'a> { fn parse(source: &'a str, shallow_tags: bool) -> Result { let options = serde_saphyr::granit_parser::options! { block_nesting_limit: MAX_YAML_DEPTH + 1, flow_nesting_limit: MAX_YAML_DEPTH, emit_comments: false }; @@ -51,6 +85,7 @@ impl<'a> Arena<'a> { entries: Vec::new(), anchors: BTreeMap::new(), visits: Cell::new(0), + recovered: Default::default(), }; let mut pending: Vec = Vec::new(); let mut roots = 0; @@ -254,7 +289,60 @@ impl<'a> Arena<'a> { index, omit, depth, + node: false, + text: false, + } + } + /// End byte of `index`'s source: a scalar's span end, or a collection's + /// last descendant plus a closing flow bracket. + fn source_end(&self, index: usize, budget: &mut usize) -> Option { + *budget = budget.checked_sub(1)?; + let entry = &self.entries[index]; + let start = entry.span.byte_range()?.start; + let mut end = entry.span.byte_range()?.end; + if let Kind::Sequence(items) | Kind::Mapping(items) = &entry.kind { + for &item in items { + end = end.max(self.source_end(item, budget)?); + } + let close = match self.source.get(start..)?.chars().next() { + Some('[') => Some(']'), + Some('{') => Some('}'), + _ => None, + }; + if let Some(close) = close { + let rest = self.source.get(end..)?; + let skipped = + rest.len() - rest.trim_start_matches([' ', '\t', '\r', '\n', ',']).len(); + if rest[skipped..].starts_with(close) { + end += skipped + close.len_utf8(); + } + } } + Some(end) + } + /// The exact source text of a value, recorded for an `ARA230` warning. + fn recover_text(&self, index: usize) -> Result { + let span = self.entries[index].span; + let start = span + .byte_range() + .ok_or_else(|| error("YAML byte offsets unavailable"))? + .start; + let end = self + .source_end(index, &mut 100_000) + .ok_or_else(|| error("YAML value too large to read as text"))?; + let text = self + .source + .get(start..end) + .ok_or_else(|| error("invalid YAML value span"))? + .trim_end() + .to_owned(); + let line_start = self.source[..start].rfind('\n').map_or(0, |i| i + 1); + self.recovered.borrow_mut().push(RecoveredText { + line: span.start.line(), + col: start - line_start, + text: text.clone(), + }); + Ok(text) } fn nodes(&self, roots: &[usize]) -> Result, Error> { struct Frame<'a> { @@ -295,7 +383,11 @@ impl<'a> Arena<'a> { if count > MAX_NODES { return Err(error("expanded exploration node budget exceeded")); } - let node = RawNode::deserialize(self.view(index, &["children"], 0)).map_err(|e| { + let view = View { + node: true, + ..self.view(index, &["children"], 0) + }; + let node = RawNode::deserialize(view).map_err(|e| { let span = self.entries[index].span; error(format!( "{e} (node at line {}, column {})", @@ -332,6 +424,10 @@ struct View<'v, 'a> { index: usize, omit: &'static [&'static str], depth: usize, + /// This view is an exploration node's mapping. + node: bool, + /// This value belongs to a node text field ([`TEXT_FIELDS`]). + text: bool, } impl<'v, 'a> View<'v, 'a> { fn resolved(self) -> Result { @@ -382,9 +478,14 @@ impl<'v, 'a> View<'v, 'a> { index, omit: &[], depth: self.depth + 1, + node: false, ..self } } + /// Whether a non-string value here is read as its source text. + fn recovers(&self) -> bool { + self.text && !matches!(self.arena.entries[self.index].kind, Kind::Alias(_)) + } } macro_rules! scalar_method { ($($name:ident),* $(,)?) => {$ ( @@ -405,6 +506,11 @@ impl<'v, 'a> Deserializer<'a> for View<'v, 'a> { if let Some(value) = this.string_scalar() { return visitor.visit_string(value.clone().into_owned()); } + // A plain scalar or a mapping in a text field reads as source text; a + // sequence stays a sequence so text lists (`evidence`) keep their items. + if this.recovers() && !matches!(this.arena.entries[this.index].kind, Kind::Sequence(_)) { + return visitor.visit_string(this.arena.recover_text(this.index)?); + } match &this.arena.entries[this.index].kind { Kind::Scalar(..) => serde_saphyr::with_deserializer_from_str(this.scalar()?, |de| { de.deserialize_any(visitor) @@ -418,6 +524,7 @@ impl<'v, 'a> Deserializer<'a> for View<'v, 'a> { view: this, items: this.arena.fields(this.index)?.chunks_exact(2), value: None, + text: false, }), Kind::Alias(_) => Err(error("unresolved YAML alias")), } @@ -426,6 +533,13 @@ impl<'v, 'a> Deserializer<'a> for View<'v, 'a> { let this = self.resolved()?; if this.string_scalar().is_some() { visitor.visit_some(this) + } else if this.recovers() + && matches!(this.arena.entries[this.index].kind, Kind::Scalar(..)) + && !matches!(this.scalar()?, "" | "~" | "null" | "Null" | "NULL") + { + // Keep a text field's plain scalar on this view, so it is read as + // source text rather than as a typed number. + visitor.visit_some(this) } else if matches!(this.arena.entries[this.index].kind, Kind::Scalar(..)) { serde_saphyr::with_deserializer_from_str(this.scalar()?, |de| { de.deserialize_option(visitor) @@ -490,8 +604,6 @@ impl<'v, 'a> Deserializer<'a> for View<'v, 'a> { deserialize_f32, deserialize_f64, deserialize_char, - deserialize_str, - deserialize_string, deserialize_bytes, deserialize_byte_buf, deserialize_unit, @@ -500,6 +612,26 @@ impl<'v, 'a> Deserializer<'a> for View<'v, 'a> { deserialize_identifier, deserialize_ignored_any ); + fn deserialize_str>(self, visitor: V) -> Result { + self.deserialize_string(visitor) + } + fn deserialize_string>(self, visitor: V) -> Result { + let this = self.resolved()?; + if let Some(value) = this.string_scalar() { + visitor.visit_string(value.clone().into_owned()) + } else if matches!(this.arena.entries[this.index].kind, Kind::Scalar(..)) { + serde_saphyr::with_deserializer_from_str(this.scalar()?, |de| { + de.deserialize_string(visitor) + }) + .map_err(error) + } else if this.recovers() { + // A mapping or sequence where text is expected, such as the plain + // item `- a (rejected: b)`: read its exact source text. + visitor.visit_string(this.arena.recover_text(this.index)?) + } else { + this.deserialize_any(visitor) + } + } fn deserialize_unit_struct>( self, _: &'static str, @@ -528,6 +660,8 @@ struct Mapping<'v, 'a> { view: View<'v, 'a>, items: std::slice::ChunksExact<'v, usize>, value: Option, + /// The pending value belongs to a node text field. + text: bool, } impl<'v, 'a> MapAccess<'a> for Mapping<'v, 'a> { type Error = Error; @@ -536,22 +670,25 @@ impl<'v, 'a> MapAccess<'a> for Mapping<'v, 'a> { seed: T, ) -> Result, Error> { for pair in self.items.by_ref() { - if self.view.omit.contains(&self.view.arena.key(pair[0])?) { + let key = self.view.arena.key(pair[0])?; + if self.view.omit.contains(&key) { continue; } + self.text = self.view.node && TEXT_FIELDS.contains(&key); self.value = Some(pair[1]); return seed.deserialize(self.view.child(pair[0])).map(Some); } Ok(None) } fn next_value_seed>(&mut self, seed: T) -> Result { - seed.deserialize( - self.view.child( - self.value - .take() - .ok_or_else(|| error("missing mapping value"))?, - ), - ) + let index = self + .value + .take() + .ok_or_else(|| error("missing mapping value"))?; + seed.deserialize(View { + text: self.text, + ..self.view.child(index) + }) } } @@ -711,6 +848,17 @@ impl<'de> Deserialize<'de> for JsonKey<'de> { } } +/// A node text-field value YAML did not type as a string, read as its exact +/// source text (`ARA230`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct RecoveredText { + /// One-based source line where the value starts. + pub line: usize, + /// Zero-based byte column of the value's start within that line. + pub col: usize, + pub text: String, +} + pub(crate) fn parse(source: &str) -> Result { #[cfg(feature = "native")] if let Some(doc) = json_doc(source) { @@ -719,8 +867,21 @@ pub(crate) fn parse(source: &str) -> Result { let depth = inspected_depth(source)?; // Preserve the existing bounded YAML semantics without deeply recursive serde. if depth <= MAX_METADATA_DEPTH { - return serde_saphyr::from_str::(source).map_err(|e| e.to_string()); + return serde_saphyr::from_str::(source).or_else(|e| { + // Only a document that recovers a non-text value takes the arena + // result; any other failure keeps the original error. + arena_doc(source) + .ok() + .filter(|doc| !doc.recovered.is_empty()) + .ok_or_else(|| e.to_string()) + }); } + arena_doc(source) +} + +/// [`parse`] through the arena, which bounds depth without recursive serde +/// and reads non-text values in node text fields as source text. +fn arena_doc(source: &str) -> Result { let arena = Arena::parse(source, false)?; let mut doc = RawDoc::deserialize(arena.view(0, &["tree", "root"], 0)).map_err(|e| e.to_string())?; @@ -750,6 +911,7 @@ pub(crate) fn parse(source: &str) -> Result { .map_err(|e| e.to_string())?; } } + doc.recovered = arena.recovered.take(); Ok(doc) } diff --git a/crates/ara-core/src/lint.rs b/crates/ara-core/src/lint.rs index 4e8b6e0..1b88003 100644 --- a/crates/ara-core/src/lint.rs +++ b/crates/ara-core/src/lint.rs @@ -51,6 +51,10 @@ pub enum LintRuleId { /// `ARA007`: `trigger:` key on a `pivot` node (canonical `reason:`). #[serde(rename = "ARA007")] PivotTriggerAlias, + /// `ARA008`: a node text field holds an unquoted value that YAML reads as + /// a number, boolean, mapping or list (`ARA230` reads it as source text). + #[serde(rename = "ARA008")] + UnquotedTreeScalar, } impl LintRuleId { @@ -64,6 +68,7 @@ impl LintRuleId { LintRuleId::PivotFromAlias => RuleCode::PivotFromAlias, LintRuleId::PivotToAlias => RuleCode::PivotToAlias, LintRuleId::PivotTriggerAlias => RuleCode::PivotTriggerAlias, + LintRuleId::UnquotedTreeScalar => RuleCode::UnquotedTreeScalar, } } @@ -494,9 +499,43 @@ fn lint_tree(text: &str) -> Vec { } } + diags.extend(unquoted_tree_scalars(text)); diags } +/// `ARA008`: each node text-field value the parser read as source text +/// (`ARA230`). A one-line value gets a fix that single-quotes it, doubling +/// inner `'`, so it parses to the same text; a multi-line value is reported +/// without a fix. +#[cfg(feature = "native")] +fn unquoted_tree_scalars(text: &str) -> Vec { + let Ok(doc) = crate::flat_yaml::parse(text) else { + return Vec::new(); + }; + doc.recovered + .into_iter() + .map(|value| { + let fix = (!value.text.contains('\n')).then(|| FixCandidate::ReplaceInLine { + line: value.line - 1, + start_col: value.col, + end_col: value.col + value.text.len(), + replacement: format!("'{}'", value.text.replace('\'', "''")), + }); + LintDiagnostic { + rule: LintRuleId::UnquotedTreeScalar, + message: format!( + "line {}: unquoted `{}` is not a YAML string; quote it to keep it text", + value.line, + value.text.lines().next().unwrap_or_default() + ), + file: LintFile::Tree, + fixable: fix.is_some(), + fix, + } + }) + .collect() +} + /// Runs the claims-file rule (ARA004) over raw Markdown text. #[cfg(feature = "native")] fn lint_claims(text: &str) -> Vec { diff --git a/crates/ara-core/src/parse.rs b/crates/ara-core/src/parse.rs index 1bc786f..e44ad29 100644 --- a/crates/ara-core/src/parse.rs +++ b/crates/ara-core/src/parse.rs @@ -83,6 +83,17 @@ pub(crate) fn parse_sources_detailed_with_claim_redirects( format!("unknown field `{key}`"), ); } + for recovered in &doc.recovered { + let mut shown: String = recovered.text.chars().take(120).collect(); + if shown.len() < recovered.text.len() { + shown.push('…'); + } + report.warn( + RuleCode::NonTextTreeField, + format!("trace/exploration_tree.yaml:{}", recovered.line), + format!("value read as its source text `{shown}`; quote it to keep it text"), + ); + } let roots: Vec = match (doc.tree, doc.root) { (Some(_), Some(_)) => { diff --git a/crates/ara-core/src/rules.rs b/crates/ara-core/src/rules.rs index 5303304..f6d2121 100644 --- a/crates/ara-core/src/rules.rs +++ b/crates/ara-core/src/rules.rs @@ -125,6 +125,9 @@ rules! { /// `trigger:` on a `pivot` node (canonical `reason:`). PivotTriggerAlias => ("ARA007", "pivot-trigger-alias", Format, Error, true, "`trigger:` on a `pivot` node (canonical `reason:`)"), + /// A node text field holds an unquoted non-string value (`ARA230`). + UnquotedTreeScalar => ("ARA008", "unquoted-tree-scalar", Format, Warning, true, + "a node text field holds an unquoted value YAML reads as a number, boolean, mapping or list (quote it)"), // ---- ARA1xx: structural/reference errors (validate layer) ---- /// `trace/exploration_tree.yaml` is not valid YAML or not the expected shape. @@ -251,6 +254,10 @@ rules! { /// A Markdown document's unclosed leading `---` hides the rest of it. UnclosedFrontmatter => ("ARA229", "unclosed-frontmatter", Validate, Warning, false, "an unclosed leading `---` fence hides the rest of a Markdown document as frontmatter"), + /// A node text field holds a value YAML did not type as a string; it is + /// read as its exact source text. + NonTextTreeField => ("ARA230", "non-text-tree-field", Validate, Warning, false, + "a node text field holds a non-string YAML value (read as its source text; quote it)"), } impl RuleCode { diff --git a/crates/ara-core/src/schema.rs b/crates/ara-core/src/schema.rs index 4b55d76..8c1b8f3 100644 --- a/crates/ara-core/src/schema.rs +++ b/crates/ara-core/src/schema.rs @@ -27,6 +27,9 @@ pub(crate) struct RawDoc { /// Unknown top-level keys → warnings. #[serde(flatten)] pub extra: BTreeMap, + /// Node text-field values read as source text on the recovery path. + #[serde(skip)] + pub recovered: Vec, } /// Raw node with every canonical field modeled. Type-specific body fields are @@ -131,13 +134,49 @@ impl Drop for RawNode { /// `evidence:` is either a bare scalar (`"Table 3 ..."`) or a mixed list /// (`[C01, "Table 2"]`). Each list element is a string; `C##` vs prose is /// classified in `parse.rs`. -#[derive(Debug, Deserialize)] -#[serde(untagged)] +/// +/// Scalars are read as text, so an unquoted all-digit commit SHA (`7258910`) +/// or `1e5` keeps its source spelling, as in every other text field. An +/// untagged enum cannot do this: it buffers the parsed number, not the text. +#[derive(Debug)] pub(crate) enum Evidence { One(String), Many(Vec), } +impl<'de> Deserialize<'de> for Evidence { + fn deserialize>(deserializer: D) -> Result { + struct EvidenceVisitor; + impl<'de> serde::de::Visitor<'de> for EvidenceVisitor { + type Value = Evidence; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a scalar or a list of scalars") + } + fn visit_str(self, value: &str) -> Result { + Ok(Evidence::One(value.to_owned())) + } + fn visit_string(self, value: String) -> Result { + Ok(Evidence::One(value)) + } + fn visit_seq>( + self, + mut seq: A, + ) -> Result { + let mut entries = Vec::new(); + while let Some(entry) = seq.next_element::()? { + entries.push(entry); + } + Ok(Evidence::Many(entries)) + } + } + // List items deserialize as `String`, which keeps a plain scalar's + // source spelling. A bare numeric scalar has lost its spelling here, + // so it is refused and the tree parser retries on its recovery path, + // which reads it as source text. + deserializer.deserialize_any(EvidenceVisitor) + } +} + impl Evidence { /// Flattens to a list of raw string entries in source order. pub(crate) fn entries(&self) -> Vec { diff --git a/crates/ara-core/tests/rule_codes.rs b/crates/ara-core/tests/rule_codes.rs index 081798b..24686c3 100644 --- a/crates/ara-core/tests/rule_codes.rs +++ b/crates/ara-core/tests/rule_codes.rs @@ -345,6 +345,14 @@ fn tree_cases() -> Vec<(RuleCode, &'static str, Files)> { "", vec![(tree, Q), ("logic/problem.md", "---\ntitle: x\n## Gap\n")], ), + ( + RuleCode::NonTextTreeField, + "", + vec![( + tree, + "tree:\n - id: N01\n type: question\n title: Q\n evidence: 0123456\n", + )], + ), ] } diff --git a/crates/ara-core/tests/tree_field_tolerance.rs b/crates/ara-core/tests/tree_field_tolerance.rs new file mode 100644 index 0000000..5090b9c --- /dev/null +++ b/crates/ara-core/tests/tree_field_tolerance.rs @@ -0,0 +1,174 @@ +//! #130: one mistyped value in a node text field no longer fails the tree. +//! Numeric evidence keeps its spelling; a mapping or list where text is +//! expected reads as its exact source text with `ARA230`; `ARA008 --fix` +//! quotes it. Identity fields stay strict. +#![cfg(feature = "native")] + +use ara_core::{ + LintRuleId, Manifest, ParseReport, RuleCode, check_sources, fix_dir, parse_sources, +}; +use std::fmt::Write; + +fn decision(fields: &str) -> String { + format!("tree:\n - id: N01\n type: decision\n title: Q\n{fields}") +} +fn parsed(source: &str) -> (Manifest, ParseReport) { + parse_sources(source, None).unwrap_or_else(|report| panic!("{report}")) +} +fn recovered(report: &ParseReport) -> Vec<(String, String)> { + report + .warnings() + .iter() + .filter(|d| d.code == RuleCode::NonTextTreeField) + .map(|d| (d.path.clone(), d.message.clone())) + .collect() +} +fn decision_fields(manifest: &Manifest) -> (Option, Vec, Option) { + match &manifest.nodes[0].fields { + ara_core::NodeFields::Decision { + choice, + alternatives, + rationale, + .. + } => (choice.clone(), alternatives.clone(), rationale.clone()), + other => panic!("not a decision: {other:?}"), + } +} + +#[test] +fn evidence_list_scalars_keep_their_spelling_without_a_warning() { + let (manifest, report) = parsed(&decision( + " evidence: [be13e96, 7258910, 0123456, 1e5, true]\n", + )); + assert_eq!( + manifest.nodes[0].evidence_notes, + ["be13e96", "7258910", "0123456", "1e5", "true"] + ); + assert!(recovered(&report).is_empty(), "{report}"); +} + +#[test] +fn bare_numeric_evidence_keeps_its_spelling_with_a_warning() { + for value in ["0123456", "7258910", "1e5"] { + let (manifest, report) = parsed(&decision(&format!(" evidence: {value}\n"))); + assert_eq!(manifest.nodes[0].evidence_notes, [value]); + assert_eq!(recovered(&report).len(), 1, "{value}"); + } + let (manifest, report) = parsed(&decision(" evidence: ~\n")); + assert!(manifest.nodes[0].evidence_notes.is_empty()); + assert!(recovered(&report).is_empty()); +} + +#[test] +fn mappings_and_lists_in_text_fields_read_as_exact_source_text() { + let (manifest, report) = parsed(&decision( + " choice: [a, {b: c}]\n alternatives:\n - Build on Debian 12 (rejected: its glibc is above the floor). # note\n - Static linking\n", + )); + let (choice, alternatives, _) = decision_fields(&manifest); + assert_eq!(choice.as_deref(), Some("[a, {b: c}]")); + assert_eq!( + alternatives, + [ + "Build on Debian 12 (rejected: its glibc is above the floor).", + "Static linking" + ] + ); + let paths: Vec = recovered(&report).into_iter().map(|(p, _)| p).collect(); + assert_eq!( + paths, + [ + "trace/exploration_tree.yaml:5", + "trace/exploration_tree.yaml:7" + ] + ); +} + +#[test] +fn multi_line_mapping_reads_as_its_source_lines() { + let (manifest, report) = parsed(&decision( + " rationale:\n first: a\n second: b\n", + )); + let (_, _, rationale) = decision_fields(&manifest); + assert_eq!(rationale.as_deref(), Some("first: a\n second: b")); + assert_eq!(recovered(&report).len(), 1); +} + +#[test] +fn identity_fields_stay_strict() { + for fields in [ + " parent: {a: b}\n", + " also_depends_on: [{a: b}]\n", + " isolated: {a: b}\n", + ] { + let refused = parse_sources(&decision(fields), None).unwrap_err(); + assert!( + refused + .errors() + .iter() + .any(|d| d.code == RuleCode::MalformedTree), + "{fields}: {refused}" + ); + } + let refused = parse_sources("tree:\n - id: {a: b}\n type: question\n", None).unwrap_err(); + assert!( + refused + .errors() + .iter() + .any(|d| d.code == RuleCode::MalformedTree) + ); +} + +#[test] +fn deep_trees_recover_on_the_arena_path() { + let mut source = String::from("tree: [\n"); + for id in (1..=70).rev() { + writeln!(source, "{{id: N{id}, type: question, children: [").unwrap(); + } + source.push_str("{id: N999, type: decision, title: plain title, rationale: 12, choice: ok, alternatives: [a (rejected: b), plain], evidence: 0123}"); + source.push_str(&"]}\n".repeat(70)); + source.push_str("]\n"); + let (manifest, report) = parsed(&source); + let leaf = manifest + .nodes + .iter() + .find(|n| n.id.as_str() == "N999") + .unwrap(); + assert_eq!(leaf.evidence_notes, ["0123"]); + assert_eq!(leaf.label.as_deref(), Some("plain title")); + // Ordinary plain text is not reported; only the two non-text values are. + assert_eq!(recovered(&report).len(), 2, "{report}"); +} + +#[test] +fn ara008_quotes_one_line_values_and_reports_multi_line_ones() { + let source = decision( + " choice: [a, {b: c}]\n alternatives:\n - Debian (rejected: it's old).\n evidence: 0123\n rationale:\n k: v\n j: w\n", + ); + let lint: Vec<_> = check_sources(&source, None) + .diagnostics() + .iter() + .filter(|d| d.rule == LintRuleId::UnquotedTreeScalar) + .cloned() + .collect(); + assert_eq!(lint.len(), 4, "{lint:?}"); + assert_eq!(lint.iter().filter(|d| d.fixable).count(), 3); + + let dir = tempfile::TempDir::new().unwrap(); + let tree = dir.path().join("trace/exploration_tree.yaml"); + std::fs::create_dir_all(tree.parent().unwrap()).unwrap(); + std::fs::write(&tree, &source).unwrap(); + let (before, _) = parsed(&source); + let outcome = fix_dir(dir.path()); + assert_eq!(outcome.applied.len(), 3, "{outcome:?}"); + let fixed = std::fs::read_to_string(&tree).unwrap(); + assert!(fixed.contains(" choice: '[a, {b: c}]'\n"), "{fixed}"); + assert!( + fixed.contains(" - 'Debian (rejected: it''s old).'\n"), + "{fixed}" + ); + assert!(fixed.contains(" evidence: '0123'\n"), "{fixed}"); + let (after, report) = parsed(&fixed); + assert_eq!(before, after); + // Only the multi-line value is left to quote by hand. + assert_eq!(recovered(&report).len(), 1); +} diff --git a/docs/agent-cli-interface/24-tree-field-tolerance.md b/docs/agent-cli-interface/24-tree-field-tolerance.md new file mode 100644 index 0000000..2afc3a4 --- /dev/null +++ b/docs/agent-cli-interface/24-tree-field-tolerance.md @@ -0,0 +1,88 @@ +# 24: one mistyped tree value no longer fails the whole tree + +Shipped in workspace 0.1.35 for [#130](https://github.com/ARA-Labs/ara-cli/issues/130), +stacked on [23](23-optional-layer-tolerance.md). Parse rules are in +[stage-1](../stage-1-core-parse-validate.md#validation-severity); the rule +table is in [stage-5](../stage-5-check.md). + +## Problem + +After #128, two research ARAs still failed to load their whole exploration +tree (`ARA100`), so every structural read refused them: + +| ARA | Source | YAML value | Error | +|---|---|---|---| +| DissClaimer | `evidence:` item `- 7258910` (a short git SHA) | integer | `did not match any variant of untagged enum Evidence` | +| MSI | `alternatives:` item `- Build on Debian 12 … (rejected: its glibc is above the floor).` | one-key mapping | `expected string scalar` | + +About 4% of 7-character SHAs are all digits, so any ARA citing commits in +`evidence:` eventually hits the first case. + +Plain `String` fields already took a numeric or boolean scalar's source +spelling (`1e5`, `0x1F`, `true`). Only `evidence:`, an untagged enum, did not: +untagged matching buffers the parsed number, not its text. + +## Design + +### `evidence` scalars + +`Evidence` has a hand-written `Deserialize`. List items deserialize as +`String`, so `[be13e96, 7258910, 0123456]` keeps every spelling with no +warning, like any text field. A bare numeric scalar (`evidence: 0123456`) has +lost its spelling by the time a visitor sees it, so it is refused and the tree +is re-read on the recovery path below. + +### Recovery path + +`flat_yaml::parse` first parses a shallow tree with serde-saphyr as before. +Only if that fails does it retry through the `flat_yaml` arena, and it takes +the arena result only when the arena recovered at least one value; any other +failure keeps the original `ARA100`. Deep trees (over 64 levels) always use +the arena. Trees that loaded before load byte-identically. + +In the arena, a value of a node text field (`TEXT_FIELDS`: `title`, +`description`, body fields, `alternatives`, `evidence`, `source_refs`, …) that +YAML did not type as a string is read as its exact source text: a plain +scalar, a mapping such as `a (rejected: b)`, or a list in a scalar field +(`choice: [a, {b: c}]`). The text runs from the value's start to its last +descendant, plus a closing flow bracket; comments are excluded. Each +recovery warns `ARA230 non-text-tree-field` at +`trace/exploration_tree.yaml:line`. Identity fields (`id`, `type`, `parent`, +`also_depends_on`) and non-text fields (`isolated`, `same_as`, `artifacts`, +`concepts`) are not in `TEXT_FIELDS` and stay strict. + +The plan placed recovery in `flat_yaml` spans for every tree. Shallow trees +never reach that code (serde-saphyr parses them directly), so recovery is a +failure-only fallback instead, which also guarantees no change for trees that +already loaded. + +### Decisions + +- **D1 (a):** `ARA230` does not refuse reads or mark them `incomplete`. The + recovered text is exactly what the author wrote, so the node is fully + represented; reads exit 0 with the warning in `diagnostics`. +- **D2:** `ARA008` covers the tree only. + +### `ARA008 unquoted-tree-scalar` + +The format rule reports each `ARA230` recovery. A one-line value gets a +`ReplaceInLine` fix that single-quotes it and doubles inner `'`; a multi-line +value is reported without a fix. The fix guard accepts a candidate only if it +adds no error, leaves the normalized manifest equal, and removes an `ARA230`. +The plan also proposed quoting numeric `evidence:` list items; those now read +correctly without a warning, so `ARA008` follows the parser's recoveries +instead of a separate scan. + +## Verification + +- `crates/ara-core/tests/tree_field_tolerance.rs`: list and bare evidence + spellings, nulls, mappings and flow lists, multi-line values, strict + identity fields, the deep-tree arena path (plain text not reported), and + `ARA008` lint plus `fix_dir` with manifest equality. +- `crates/ara-cli/tests/agent_tree_field_tolerance.rs`: the two #130 + reproductions (failing on 0.1.34) and a spelling guard. +- `agent_reads.rs`: the identity-lookup fixture that relied on a mapping in + `description` failing now uses `isolated`, which stays strict. +- Real ARAs, 0.1.34 → 0.1.35: DissClaimer and MSI go from `invalid_artifact` + (`ARA100`) to readable. DissClaimer reports no `ARA230`; MSI reports one at + line 5859, and `ara check --fix` on a copy quotes exactly that line. diff --git a/docs/agent-cli-interface/README.md b/docs/agent-cli-interface/README.md index 8fc9786..80dccb6 100644 --- a/docs/agent-cli-interface/README.md +++ b/docs/agent-cli-interface/README.md @@ -24,6 +24,7 @@ verification report for the current evidence. - [21-reader-round-trips](./21-reader-round-trips.md) - [22-reader-turn-overhead](./22-reader-turn-overhead.md) - [23-optional-layer-tolerance](./23-optional-layer-tolerance.md) +- [24-tree-field-tolerance](./24-tree-field-tolerance.md) Plan 15 is deferred. Conditional 16/17 are closed for this delivery because their experiment evidence gates have not fired; no implementation is claimed. diff --git a/docs/agent-cli.md b/docs/agent-cli.md index 1e90d8a..c7f2ff3 100644 --- a/docs/agent-cli.md +++ b/docs/agent-cli.md @@ -589,6 +589,12 @@ claims,depends_on` omits it and `show --with refs`/`show` on the missing ID retu IDs are null, whenever any error exists. `check` and `validate` still fail on these errors. +A node text-field value read as its source text (`ARA230`, see +[stage-1](stage-1-core-parse-validate.md#validation-severity)) does not refuse +or mark a read incomplete: the recovered text is exactly what the author +wrote, so the node is fully represented, and the warning stays in +`diagnostics`. + ### Incomplete optional layers An `ARA217` or `ARA218` warning about one optional-layer file does not refuse diff --git a/docs/stage-1-core-parse-validate.md b/docs/stage-1-core-parse-validate.md index b69ea1b..c60196b 100644 --- a/docs/stage-1-core-parse-validate.md +++ b/docs/stage-1-core-parse-validate.md @@ -146,6 +146,22 @@ even error ordering is hash-seed independent. Nothing is sorted by id. metadata) or null (a heading-only block). Metadata-like content, comments or heading-only blocks never qualify ([`stray_fence.rs`](../crates/ara-core/src/stray_fence.rs)). +- **WARNING, non-text tree value (`ARA230`, #130):** node text fields + (`title`, `description`, `choice`, `alternatives`, `evidence`, `rationale`, + the other body fields, `source_refs`, `provenance`, `timestamp`, `status`, + `support_level`) take a plain scalar's source spelling, so `7258910`, + `0123456` and `1e5` stay text. `evidence:` list items do so silently, as + every text field always has. A value the parser cannot take as text (a bare + numeric `evidence:` scalar, or a mapping or list such as the plain item + `- a (rejected: b)`) makes the direct parse fail; the tree is then re-read + through the `flat_yaml` arena, which takes the value's exact source text + (comments excluded, flow brackets included) and warns `ARA230` at + `trace/exploration_tree.yaml:line`. The arena result is used only when it + recovered such a value; any other failure keeps its original `ARA100`. + Identity fields (`id`, `type`, `parent`, `also_depends_on`) and non-text + fields (`isolated`, `same_as`, `artifacts`, `concepts`) stay strict. + `ara check --fix` (`ARA008`) single-quotes one-line values; a multi-line + value is reported for hand quoting. - **IGNORED (stored raw):** `Proof:[E##]` — no evidence registry exists yet (tracked as `T-EVIDENCE`). diff --git a/docs/stage-5-check.md b/docs/stage-5-check.md index a7a9feb..ae8f75c 100644 --- a/docs/stage-5-check.md +++ b/docs/stage-5-check.md @@ -150,6 +150,7 @@ retired rule keeps its number). The code space is split by layer: | `ARA005` | pivot-from-alias | `from:` on a `pivot` node (canonical `prior_direction:`) | error | yes | | `ARA006` | pivot-to-alias | `to:` on a `pivot` node (canonical `new_direction:`) | error | yes | | `ARA007` | pivot-trigger-alias | `trigger:` on a `pivot` node (canonical `reason:`) | error | yes | +| `ARA008` | unquoted-tree-scalar | a node text field holds an unquoted value YAML reads as a number, boolean, mapping or list; `--fix` single-quotes a one-line value (`ARA230` reads it meanwhile) | warning | yes | | `ARA100` | malformed-tree | `trace/exploration_tree.yaml` fails to parse (invalid YAML, multi-document, non-mapping root, wrong field types) | error | no | | `ARA101` | unreadable-tree | `trace/exploration_tree.yaml` cannot be read | error | no | | `ARA102` | tree-and-root | both `tree:` and `root:` are present | error | no | @@ -180,6 +181,7 @@ retired rule keeps its number). The code space is split by layer: | `ARA216` | invalid-figure-image | a figure image declaration is missing, unsafe, unsupported, or ambiguous | warning | no | | `ARA228` | recovered-stray-fence | an unclosed leading `---` in a logic document is a stray line before its title (content after it is read) | warning | no | | `ARA229` | unclosed-frontmatter | an unclosed leading `---` fence hides the rest of a Markdown document as frontmatter | warning | no | +| `ARA230` | non-text-tree-field | a node text field holds a non-string YAML value; it is read as its exact source text at `trace/exploration_tree.yaml:line` | warning | no | Some drift fires one rule in each layer: `reason:` on a `dead_end` is both `ARA002` (fixable) and `ARA206`; `justification:` / pivot `from:` / `to:` / diff --git a/plans/agent-cli-interface/README.md b/plans/agent-cli-interface/README.md index b8c7d08..6dc7a12 100644 --- a/plans/agent-cli-interface/README.md +++ b/plans/agent-cli-interface/README.md @@ -23,6 +23,7 @@ is separate from historical reproduction, human protocol approval, and experimen | [21](../../docs/agent-cli-interface/21-reader-round-trips.md) | Approved 2026-10-08; reader-only access guide, Files grounding rule and fewer-requests guidance shipped in 0.1.28 as skill-only changes; conditional `find --show` not implemented; the completed design replaces the plan | | [22](../../docs/agent-cli-interface/22-reader-turn-overhead.md) | Approved 2026-10-14; stray-`---` recovery (0.1.29), one-step reader startup (0.1.30, skill only), partial multi-address `show` with addressed `find` hits and bare entry IDs (0.1.31), and bounded `find` (0.1.32) shipped; paired pilots measured CLI ÷ Files cost 0.94 and time 1.07 at equal accuracy; the completed design replaces the plan | | [23](../../docs/agent-cli-interface/23-optional-layer-tolerance.md) | Approved 2026-10-18 for [#128](https://github.com/ARA-Labs/ara-cli/issues/128); shared dash/bracket entry headings and optional-layer read-through shipped in 0.1.34; the completed design replaces the plan | +| [24](../../docs/agent-cli-interface/24-tree-field-tolerance.md) | Approved 2026-10-18 for [#130](https://github.com/ARA-Labs/ara-cli/issues/130) (D1 a, D2 tree only); `evidence` spelling, failure-only text recovery (`ARA230`) and `ARA008` quoting shipped in 0.1.35; the completed design replaces the plan | Plan 18's CLI and skill changes are implemented; its external changes and pilot follow-ups remain separate, so it stays a plan. Plan 18 supersedes the parent plan's default-JSON agent workflow with brief text while retaining programmatic JSON access, and [the command reference](../../docs/agent-cli.md) documents the shipped behavior. Plan 19's CLI sub-PRs are implemented; its repeated skill audit and upstream event-target review remain pending. Mechanical recording does not delegate research judgment to the CLI.