chappi-core 0.1.0

Typed cognitive graph, patch, reentry, projection, and measurement engine for Chappi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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),
    }
}