use std::collections::HashSet;
use chappi_core::{CognitiveState, NodeKind, Source, snapshot_source, validate};
use chappi_syntax::{Atom, Form, FormKind, parse_document};
fn decode(source: &str) -> CognitiveState {
CognitiveState::try_from(parse_document(source).expect("fixture syntax should parse"))
.expect("fixture semantics should decode")
}
#[test]
fn reports_duplicate_and_unresolved_node_references_at_their_source_forms() {
let state = decode(
r#"(chappi 1)
(entity self self persistent 100 person (self))
(claim c1 self working 50 likely (first))
(claim c1 self working 40 tentative (duplicate))
(claim orphan ghost working 30 plausible (orphan))
(claim wrong-owner c1 working 30 plausible (wrong owner kind))
(relationship r1 self persistent 50 missing trusted (missing target))
(perspective p1 self working 50 c1 likely (wrong target kind))
(affect a1 self transient 25 absent fondness weak (missing affect target))
(rel supports missing-source c1)
(rel supports c1 missing-target)
"#,
);
let diagnostics = validate(&state);
let observed = diagnostics
.iter()
.map(|item| {
(
item.code.as_str(),
item.span.start_line,
item.semantic_path
.iter()
.map(String::as_str)
.collect::<Vec<_>>(),
)
})
.collect::<Vec<_>>();
assert_eq!(
observed,
vec![
("duplicate-node-id", 4, vec!["nodes", "c1", "id"]),
("undefined-owner", 5, vec!["nodes", "orphan", "owner"]),
(
"invalid-owner-kind",
6,
vec!["nodes", "wrong-owner", "owner"]
),
("undefined-entity-target", 7, vec!["nodes", "r1", "target"]),
(
"invalid-entity-target-kind",
8,
vec!["nodes", "p1", "target"]
),
("undefined-entity-target", 9, vec!["nodes", "a1", "target"]),
(
"undefined-relation-source",
10,
vec!["relations", "supports", "missing-source", "c1", "source"]
),
(
"undefined-relation-target",
11,
vec!["relations", "supports", "c1", "missing-target", "target"]
),
]
);
}
#[test]
fn enforces_the_fixed_relation_endpoint_matrix() {
let state = decode(
r#"(chappi 1)
(entity self self persistent 100 person (self))
(claim c1 self persistent 80 likely (claim))
(evidence e1 self working 70 observation notebook (evidence))
(goal g1 self working 60 active (goal))
(constraint co1 self persistent 90 hard (constraint))
(desire d1 self transient 50 strong (desire))
(rel supports g1 c1)
(rel contradicts e1 g1)
(rel refines c1 g1)
(rel supersedes c1 g1)
(rel causes c1 self)
(rel about c1 c1)
(rel blocks c1 g1)
(rel blocks co1 c1)
"#,
);
let diagnostics = validate(&state);
assert_eq!(diagnostics.len(), 8);
assert!(
diagnostics
.iter()
.all(|item| item.code == "invalid-relation-endpoints")
);
assert_eq!(diagnostics[0].span.start_line, 8);
assert_eq!(
diagnostics[0].semantic_path,
["relations", "supports", "g1", "c1"]
);
assert_eq!(diagnostics[7].span.start_line, 15);
}
#[test]
fn accepts_every_allowed_relation_shape() {
let state = decode(
r#"(chappi 1)
(entity self self persistent 100 person (self))
(entity other self persistent 80 person (other))
(claim c1 self persistent 80 likely (claim one))
(claim c2 self persistent 70 settled (claim two))
(evidence e1 self working 70 observation notebook (evidence))
(goal g1 self working 60 active (goal))
(constraint co1 self persistent 90 hard (constraint))
(question q1 self working 55 open (question))
(desire d1 self transient 50 strong (desire))
(affect a1 self transient 45 other fondness moderate (affect))
(prediction p1 self transient 40 plausible pending (prediction))
(tension t1 self working 35 open (tension))
(association as1 self persistent 20 (association))
(rel supports e1 c1)
(rel contradicts c1 p1)
(rel refines c2 c1)
(rel causes as1 a1)
(rel supersedes c2 c1)
(rel about q1 other)
(rel blocks t1 d1)
(rel associates as1 co1)
"#,
);
assert!(validate(&state).is_empty());
}
#[test]
fn exhaustively_enforces_every_relation_kind_and_node_kind_endpoint_pair() {
const NODE_KINDS: [&str; 15] = [
"entity",
"claim",
"evidence",
"goal",
"constraint",
"question",
"relationship",
"desire",
"attention",
"association",
"tension",
"prediction",
"perspective",
"affect",
"metacognition",
];
const RELATION_KINDS: [&str; 8] = [
"supports",
"contradicts",
"refines",
"causes",
"supersedes",
"about",
"blocks",
"associates",
];
let mut nodes = String::from("(chappi 1)\n(entity self self persistent 100 person (self))\n");
for kind in NODE_KINDS {
nodes.push_str(&node_fixture(kind, &format!("a-{kind}")));
nodes.push_str(&node_fixture(kind, &format!("b-{kind}")));
}
for relation in RELATION_KINDS {
for source in NODE_KINDS {
for target in NODE_KINDS {
let state = decode(&format!("{nodes}(rel {relation} a-{source} b-{target})\n"));
let rejected = validate(&state)
.iter()
.any(|diagnostic| diagnostic.code == "invalid-relation-endpoints");
assert_eq!(
rejected,
!relation_pair_allowed(relation, source, target),
"unexpected matrix result for {relation}: {source} -> {target}"
);
}
}
}
}
fn node_fixture(kind: &str, id: &str) -> String {
let detail = match kind {
"entity" => "person",
"claim" => "likely",
"evidence" => "observation notebook",
"goal" => "active",
"constraint" => "hard",
"question" => "open",
"relationship" => "self trusted",
"desire" => "strong",
"attention" => "foreground",
"association" => "",
"tension" => "open",
"prediction" => "likely pending",
"perspective" => "self likely",
"affect" => "self fondness moderate",
"metacognition" => "monitoring",
_ => unreachable!("all fixtures name a known node kind"),
};
if detail.is_empty() {
format!("({kind} {id} self working 50 ({kind}))\n")
} else {
format!("({kind} {id} self working 50 {detail} ({kind}))\n")
}
}
fn relation_pair_allowed(relation: &str, source: &str, target: &str) -> bool {
match relation {
"supports" | "contradicts" => {
matches!(source, "evidence" | "claim") && matches!(target, "claim" | "prediction")
}
"refines" | "supersedes" => source == target,
"causes" => matches!(
target,
"claim" | "goal" | "desire" | "affect" | "prediction" | "tension"
),
"about" => target == "entity",
"blocks" => {
matches!(source, "constraint" | "tension" | "question")
&& matches!(target, "goal" | "desire")
}
"associates" => true,
_ => unreachable!("all fixtures name a known relation kind"),
}
}
#[test]
fn rejects_duplicate_relations() {
let state = decode(
r#"(chappi 1)
(entity self self persistent 100 person (self))
(claim c1 self persistent 80 likely (claim))
(evidence e1 self working 70 observation notebook (evidence))
(rel supports e1 c1)
(rel supports e1 c1)
"#,
);
let diagnostics = validate(&state);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].code, "duplicate-relation");
assert_eq!(diagnostics[0].span.start_line, 6);
}
#[test]
fn rejects_cyclic_supersession_and_cites_the_closing_edge() {
let state = decode(
r#"(chappi 1)
(entity self self persistent 100 person (self))
(claim a self persistent 80 likely (a))
(claim b self persistent 70 likely (b))
(claim c self persistent 60 likely (c))
(rel supersedes a b)
(rel supersedes b c)
(rel supersedes c a)
"#,
);
let diagnostics = validate(&state);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].code, "cyclic-supersession");
assert_eq!(diagnostics[0].span.start_line, 8);
assert_eq!(
diagnostics[0].semantic_path,
["relations", "supersedes", "c", "a"]
);
}
fn encoder_state() -> CognitiveState {
decode(
r#"(chappi 1)
(entity self self persistent 100 person (self))
(entity other self persistent 80 person (other))
(evidence ev self working 70 observation notebook (observed 1 1.5 "é"))
(relationship relationship self persistent 60 other trusted (relationship))
(affect affect self working 50 other fondness moderate (affect))
(rel about relationship other)
(focus work 0 self evoked none (fg ev) (bg relationship) (residue affect) (trigger "é"))
"#,
)
}
fn codes(state: &CognitiveState) -> HashSet<String> {
validate(state)
.into_iter()
.map(|diagnostic| diagnostic.code)
.collect()
}
#[test]
fn rejects_noncanonical_encoder_visible_model_fields() {
let mut wrong_version = encoder_state();
wrong_version.version = 2;
assert!(codes(&wrong_version).contains("invalid-version"));
let mut numeric_id = encoder_state();
numeric_id.nodes[0].id = "123".into();
numeric_id.nodes[0].owner = "123".into();
assert!(codes(&numeric_id).contains("noncanonical-symbol"));
let mut spaced_kind = encoder_state();
let NodeKind::Entity { entity_kind } = &mut spaced_kind.nodes[0].kind else {
panic!("fixture node must be an entity");
};
*entity_kind = "two words".into();
assert!(codes(&spaced_kind).contains("noncanonical-symbol"));
let mut symbol_source = encoder_state();
let NodeKind::Evidence { source, .. } = &mut symbol_source.nodes[2].kind else {
panic!("fixture node must be evidence");
};
*source = Source::Symbol("123".into());
assert!(codes(&symbol_source).contains("noncanonical-symbol"));
let mut text_source = encoder_state();
let NodeKind::Evidence { source, .. } = &mut text_source.nodes[2].kind else {
panic!("fixture node must be evidence");
};
*source = Source::String("e\u{301}".into());
assert!(codes(&text_source).contains("noncanonical-text"));
let mut free_status = encoder_state();
let NodeKind::Relationship { status, .. } = &mut free_status.nodes[3].kind else {
panic!("fixture node must be a relationship");
};
*status = "two words".into();
assert!(codes(&free_status).contains("noncanonical-symbol"));
let mut relation_endpoint = encoder_state();
relation_endpoint.relations[0].source = "123".into();
assert!(codes(&relation_endpoint).contains("noncanonical-symbol"));
let mut focus_values = encoder_state();
focus_values.focus_streams[0].id = "two words".into();
focus_values.focus_streams[0].frames[0].stream_id = "two words".into();
focus_values.focus_streams[0].frames[0].foreground[0] = "123".into();
assert!(codes(&focus_values).contains("noncanonical-symbol"));
}
#[test]
fn recursively_rejects_noncanonical_payload_and_trigger_atoms() {
let mut state = encoder_state();
let FormKind::List(payload) = &mut state.nodes[2].payload.kind else {
panic!("fixture payload must be a list");
};
payload.extend([
atom(Atom::Symbol("123".into())),
atom(Atom::Integer("01".into())),
atom(Atom::Decimal("1.50".into())),
atom(Atom::String("e\u{301}".into())),
]);
state.focus_streams[0].frames[0].trigger =
parse_document("(trigger (nested 01 1.50 \"e\u{301}\"))")
.unwrap()
.forms
.remove(0);
let codes = codes(&state);
assert!(codes.contains("noncanonical-symbol"));
assert!(codes.contains("noncanonical-integer"));
assert!(codes.contains("noncanonical-decimal"));
assert!(codes.contains("noncanonical-text"));
}
#[test]
fn every_validated_encoder_state_round_trips_through_snapshot_source() {
let state = encoder_state();
assert!(validate(&state).is_empty());
let source = snapshot_source(&state);
let decoded = CognitiveState::try_from(
parse_document(std::str::from_utf8(&source).unwrap()).expect("snapshot must parse"),
)
.expect("snapshot must decode");
assert!(validate(&decoded).is_empty());
assert_eq!(decoded, state);
}
fn atom(atom: Atom) -> Form {
Form {
span: chappi_syntax::Span {
start: 0,
end: 0,
start_line: 1,
start_column: 1,
end_line: 1,
end_column: 1,
},
kind: FormKind::Atom(atom),
}
}