memstead-base 0.27.1

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! The proof schemas (grounding, uniqueness and vocabulary) end to
//! end through create, update and health, plus the required-outgoing
//! warnings on create and update.

use super::*;

fn proof_create(
    engine: &mut Engine,
    entity_type: &str,
    title: &str,
    metadata: &[(&str, &str)],
    relations: Vec<crate::ops::RelateArg>,
) -> Result<CreateEntityOutcome, EngineError> {
    let (actor, client) = cli_actor();
    let mut sections = IndexMap::new();
    sections.insert("body".to_string(), format!("{title} body."));
    let mut md = IndexMap::new();
    for (k, v) in metadata {
        md.insert(k.to_string(), v.to_string());
    }
    engine.create_entity(
        CreateEntityArgs {
            anchors: Vec::new(),
            mem: "proof".to_string(),
            title: title.to_string(),
            entity_type: entity_type.to_string(),
            sections,
            metadata: md,
            relations,
            dry_run: false,
        },
        actor,
        Some(&client),
        None,
    )
}

const GROUNDING_MANIFEST: &str = r#"name: grounding
version: 0.1.0
description: grounding proof schema
when_to_use: constraint-proof tests
types:
  - anchor
  - tradeoff
relationships:
  mode: strict
  definitions:
    - name: FOLLOWS_FROM
      description: stands on
      default_weight: 3.0
    - name: SUPPORTS
      description: pro
      default_weight: 1.0
    - name: OPPOSES
      description: contra
      default_weight: 1.0
    - name: PART_OF
      description: hier
      default_weight: 1.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#;

const GROUNDING_ANCHOR: &str = r#"name: anchor
description: a judgment standing on others
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields:
  - key: status
    description: lifecycle
    field_type: string
    enum_values: [open, checked, fallen]
  - key: checked_by
    description: who checked
    field_type: string
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
  - status
  - checked_by
health_required_fields:
  - body
staleness_threshold_days: 90
constraints:
  - kind: requires_when
    field: checked_by
    when_field: status
    when_value: checked
  - kind: status_propagation
    field: status
    value: fallen
    relationships: [FOLLOWS_FROM]
    direction: in
write_rules: []
"#;

const GROUNDING_TRADEOFF: &str = r#"name: tradeoff
description: a claim with two sides
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields: []
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
required_outgoing:
  - relationships: [SUPPORTS]
    cardinality: at_least_one
  - relationships: [OPPOSES]
    cardinality: at_least_one
write_rules: []
"#;

/// The grounding proof: a schema of judgments standing on other
/// judgments answers three chain-check questions from health output
/// alone, where a project would otherwise script them: which entities
/// descend from a fallen one, which trade-off has one side only, and
/// which entity is marked checked without naming its checker.
#[test]
fn grounding_schema_answers_chain_check_questions_from_health() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_proof_schema(
        &tmp,
        "grounding",
        GROUNDING_MANIFEST,
        &[
            ("anchor", GROUNDING_ANCHOR),
            ("tradeoff", GROUNDING_TRADEOFF),
        ],
    );

    // A fallen root, a child standing on it, a grandchild standing
    // on the child (transitive), plus an untainted sibling chain.
    let root = proof_create(
        &mut engine,
        "anchor",
        "Root",
        &[("status", "fallen")],
        vec![],
    )
    .unwrap();
    let child = proof_create(
        &mut engine,
        "anchor",
        "Child",
        &[],
        vec![rel(&root.id.0, "FOLLOWS_FROM")],
    )
    .unwrap();
    let grandchild = proof_create(
        &mut engine,
        "anchor",
        "Grandchild",
        &[],
        vec![rel(&child.id.0, "FOLLOWS_FROM")],
    )
    .unwrap();
    let standing = proof_create(
        &mut engine,
        "anchor",
        "Standing Root",
        &[("status", "open")],
        vec![],
    )
    .unwrap();
    let standing_child = proof_create(
        &mut engine,
        "anchor",
        "Standing Child",
        &[],
        vec![rel(&standing.id.0, "FOLLOWS_FROM")],
    )
    .unwrap();
    // Question 3's subject: checked without a checker.
    let unchecked = proof_create(
        &mut engine,
        "anchor",
        "Checked No Checker",
        &[("status", "checked")],
        vec![],
    )
    .unwrap();
    // Question 2's subject: a one-sided trade-off.
    let onesided = proof_create(
        &mut engine,
        "tradeoff",
        "One Sided",
        &[],
        vec![rel(&standing.id.0, "SUPPORTS")],
    )
    .unwrap();

    // Question 1 — descendants of the fallen anchor are flagged,
    // naming their ancestor; the standing chain is not.
    let findings = crate::ops::health::collect_constraint_findings(
        engine.store(),
        None,
        engine.schemas(),
        None,
    );
    let tainted_of = |id: &crate::entity::EntityId| -> Vec<String> {
        findings
            .iter()
            .filter(|r| &r.id == id)
            .flat_map(|r| &r.violations)
            .filter_map(|v| match v {
                crate::ops::health::UnsatisfiedConstraint::StatusPropagation {
                    tainted_by, ..
                } => Some(tainted_by.clone()),
                _ => None,
            })
            .collect()
    };
    assert_eq!(tainted_of(&child.id), vec![root.id.to_string()]);
    assert_eq!(
        tainted_of(&grandchild.id),
        vec![root.id.to_string()],
        "the taint is transitive and names the terminal ancestor"
    );
    assert!(tainted_of(&standing_child.id).is_empty());
    assert!(
        tainted_of(&root.id).is_empty(),
        "the source is not its own finding"
    );

    // Question 3 — checked-without-checker is flagged.
    assert!(
        findings.iter().any(|r| r.id == unchecked.id
            && r.violations.iter().any(|v| matches!(
                v,
                crate::ops::health::UnsatisfiedConstraint::RequiresWhen { field, .. }
                    if field == "checked_by"
            ))),
        "checked-without-checker must be a health finding"
    );

    // Question 2 — the one-sided trade-off is flagged missing its
    // OPPOSES block (form 4 at warn), from health output alone.
    let missing = crate::ops::health::collect_missing_required_outgoing(
        engine.store(),
        None,
        engine.schemas(),
    );
    let onesided_report = missing
        .iter()
        .find(|r| r.id == onesided.id)
        .expect("one-sided trade-off flagged");
    assert_eq!(onesided_report.missing.len(), 1);
    assert_eq!(onesided_report.missing[0].relationships, vec!["OPPOSES"]);
}

const RECORD_MANIFEST: &str = r#"name: record-proof
version: 0.1.0
description: uniqueness and vocabulary proof schema
when_to_use: constraint-proof tests
types:
  - record
  - vocabulary
relationships:
  mode: strict
  definitions:
    - name: REFERENCES
      description: soft ref
      default_weight: 0.5
    - name: PART_OF
      description: hier
      default_weight: 1.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#;

fn record_type(unique_severity: &str) -> String {
    format!(
        r#"name: record
description: one imported record
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields:
  - key: record_id
    description: source id
    field_type: string
  - key: record_sha256
    description: content hash
    field_type: string
  - key: category
    description: category from the shared vocabulary
    field_type: string
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
  - record_id
  - record_sha256
  - category
health_required_fields:
  - body
staleness_threshold_days: 90
constraints:
  - kind: unique
    fields: [record_id, record_sha256]
    severity: {unique_severity}
  - kind: enum_from_neighbour
    field: category
    relationships: [REFERENCES]
    section: terms
write_rules: []
"#
    )
}

const RECORD_VOCABULARY: &str = r#"name: vocabulary
description: the shared term list
when_to_use: tests
sections:
  - key: terms
    heading: Terms
    required: false
    search_weight: 5.0
    catch_all: false
    write_rules: []
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields: []
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
  - terms
health_required_fields:
  - body
staleness_threshold_days: 90
write_rules: []
"#;

/// The record proof, uniqueness half: a
/// second create with the same declared key tuple refuses with a
/// typed code naming the colliding entity, so an import that repeats
/// a source record bounces at the engine. Health reports a pre-existing
/// violation planted under a warn-tier variant.
#[test]
fn unique_constraint_refuses_duplicates_and_health_reports_planted_ones() {
    // Block tier: the duplicate refuses, naming the collider.
    let tmp = TempDir::new().unwrap();
    let record = record_type("block");
    let mut engine = engine_with_proof_schema(
        &tmp,
        "record-proof",
        RECORD_MANIFEST,
        &[("record", &record), ("vocabulary", RECORD_VOCABULARY)],
    );
    let first = proof_create(
        &mut engine,
        "record",
        "Record One",
        &[("record_id", "19-42"), ("record_sha256", "abc123")],
        vec![],
    )
    .unwrap();
    let err = proof_create(
        &mut engine,
        "record",
        "Record One Duplicate",
        &[("record_id", "19-42"), ("record_sha256", "abc123")],
        vec![],
    )
    .unwrap_err();
    assert_eq!(err.code(), "CONSTRAINT_UNSATISFIED");
    assert_eq!(
        err.details()["violations"][0]["colliding"],
        first.id.to_string(),
        "the refusal names the colliding entity"
    );
    // A different tuple passes.
    proof_create(
        &mut engine,
        "record",
        "Record Two",
        &[("record_id", "19-43"), ("record_sha256", "def456")],
        vec![],
    )
    .unwrap();

    // Warn tier: plant the duplicate, health reports it.
    let tmp = TempDir::new().unwrap();
    let record = record_type("warn");
    let mut engine = engine_with_proof_schema(
        &tmp,
        "record-proof",
        RECORD_MANIFEST,
        &[("record", &record), ("vocabulary", RECORD_VOCABULARY)],
    );
    proof_create(
        &mut engine,
        "record",
        "Planted A",
        &[("record_id", "19-42"), ("record_sha256", "abc123")],
        vec![],
    )
    .unwrap();
    let planted = proof_create(
        &mut engine,
        "record",
        "Planted B",
        &[("record_id", "19-42"), ("record_sha256", "abc123")],
        vec![],
    )
    .unwrap();
    assert!(
        planted
            .warnings
            .iter()
            .any(|w| matches!(w, WarningHint::ConstraintUnsatisfied { .. })),
        "warn tier surfaces the duplicate as a warning and commits"
    );
    let findings = crate::ops::health::collect_constraint_findings(
        engine.store(),
        None,
        engine.schemas(),
        None,
    );
    assert_eq!(
        findings.len(),
        2,
        "both sides of the planted duplicate are findings: {findings:?}"
    );
}

/// The record proof, enum-from-neighbour half: renaming a value in the neighbour's section makes
/// every stale holder a health finding.
#[test]
fn enum_from_neighbour_flags_stale_holders_after_rename() {
    let tmp = TempDir::new().unwrap();
    let record = record_type("warn");
    let mut engine = engine_with_proof_schema(
        &tmp,
        "record-proof",
        RECORD_MANIFEST,
        &[("record", &record), ("vocabulary", RECORD_VOCABULARY)],
    );
    let (actor, client) = cli_actor();

    // The vocabulary entity enumerates the legal categories.
    let mut sections = IndexMap::new();
    sections.insert("body".to_string(), "the term list.".to_string());
    sections.insert("terms".to_string(), "- red\n- green\n".to_string());
    let vocab = engine
        .create_entity(
            CreateEntityArgs {
                anchors: Vec::new(),
                mem: "proof".to_string(),
                title: "Categories".to_string(),
                entity_type: "vocabulary".to_string(),
                sections,
                metadata: IndexMap::new(),
                relations: vec![],
                dry_run: false,
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    // A holder whose value is backed: clean.
    let holder = proof_create(
        &mut engine,
        "record",
        "Holder",
        &[("category", "red")],
        vec![rel(&vocab.id.0, "REFERENCES")],
    )
    .unwrap();
    let findings = crate::ops::health::collect_constraint_findings(
        engine.store(),
        None,
        engine.schemas(),
        None,
    );
    assert!(
        findings.iter().all(|r| r.id != holder.id),
        "backed value produces no finding: {findings:?}"
    );

    // Rename the value in the neighbour's section — the holder
    // goes stale and health flags it.
    let current = engine.get_entity(&vocab.id).unwrap().content_hash.clone();
    let mut sections = IndexMap::new();
    sections.insert("terms".to_string(), "- crimson\n- green\n".to_string());
    engine
        .update_entity(
            crate::engine::UpdateEntityArgs {
                anchors: Vec::new(),
                id: vocab.id.clone(),
                expected_hash: crate::ExpectedHash::Current(current),
                sections,
                append_sections: IndexMap::new(),
                patch_sections: IndexMap::new(),
                sections_unset: Vec::new(),
                metadata: IndexMap::new(),
                metadata_unset: Vec::new(),
                declare_relations: vec![],
                dry_run: false,
                relations_unset: Vec::new(),
                anchors_unset: Vec::new(),
            },
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let findings = crate::ops::health::collect_constraint_findings(
        engine.store(),
        None,
        engine.schemas(),
        None,
    );
    let stale = findings
        .iter()
        .find(|r| r.id == holder.id)
        .expect("stale holder is flagged after the rename");
    assert!(stale.violations.iter().any(|v| matches!(
        v,
        crate::ops::health::UnsatisfiedConstraint::EnumFromNeighbour { value, .. }
            if value == "red"
    )));
}

/// The advertised mutation warning is real: a create leaving a
/// required-outgoing block unsatisfied returns
/// `MISSING_REQUIRED_OUTGOING` naming the block with cardinality —
/// and still commits. Complements: a create satisfying the block
/// via inline `relations` emits no such warning; the health sweep
/// reports exactly the same unsatisfied blocks (shared evaluation).
#[test]
fn create_warns_missing_required_outgoing_and_still_commits() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_required_outgoing_schema(&tmp);
    let (actor, client) = cli_actor();

    let outcome = engine
        .create_entity(
            task_create_args("Orphan Task", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert!(
        !outcome.write_id.is_empty(),
        "the warning never blocks the mutation"
    );
    let blocks = missing_outgoing_of(&outcome.warnings);
    assert_eq!(
        blocks,
        vec![(vec!["PART_OF".to_string()], "at_least_one".to_string())],
        "warning names the unsatisfied block with cardinality; warnings = {:?}",
        outcome.warnings
    );

    // Health-path parity: the sweep reports the same entity with
    // the same block — the two surfaces share one evaluation.
    let reports = crate::ops::health::collect_missing_required_outgoing(
        engine.store(),
        None,
        engine.schemas(),
    );
    assert_eq!(reports.len(), 1);
    assert_eq!(reports[0].id, outcome.id);
    assert_eq!(reports[0].missing.len(), 1);
    assert_eq!(reports[0].missing[0].relationships, vec!["PART_OF"]);
    assert_eq!(reports[0].missing[0].cardinality, "at_least_one");

    // Complement: a create whose inline relation satisfies the
    // block emits no MISSING_REQUIRED_OUTGOING.
    let satisfied = engine
        .create_entity(
            task_create_args(
                "Child Task",
                vec![crate::ops::RelateArg {
                    target: outcome.id.clone(),
                    rel_type: "PART_OF".to_string(),
                    description: None,
                }],
            ),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    assert!(
        missing_outgoing_of(&satisfied.warnings).is_empty(),
        "satisfied block emits no warning: {:?}",
        satisfied.warnings
    );
}

/// Update-side mirror: a section-only update on an entity with an
/// unsatisfied block warns; declaring the satisfying relation in
/// the same update clears it.
#[test]
fn update_warns_missing_required_outgoing_until_satisfied() {
    let tmp = TempDir::new().unwrap();
    let mut engine = engine_with_required_outgoing_schema(&tmp);
    let (actor, client) = cli_actor();
    let a = engine
        .create_entity(
            task_create_args("Task A", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();
    let b = engine
        .create_entity(
            task_create_args("Task B", vec![]),
            actor,
            Some(&client),
            None,
        )
        .unwrap();

    let update =
        |engine: &mut Engine, id: &crate::entity::EntityId, declare: Vec<crate::ops::RelateArg>| {
            let current = engine.get_entity(id).unwrap().content_hash.clone();
            let mut sections = IndexMap::new();
            sections.insert("body".to_string(), format!("edited at {:?}", declare.len()));
            engine
                .update_entity(
                    crate::engine::UpdateEntityArgs {
                        anchors: Vec::new(),
                        id: id.clone(),
                        expected_hash: crate::ExpectedHash::Current(current),
                        sections,
                        append_sections: IndexMap::new(),
                        patch_sections: IndexMap::new(),
                        sections_unset: Vec::new(),
                        metadata: IndexMap::new(),
                        metadata_unset: Vec::new(),
                        declare_relations: declare,
                        dry_run: false,
                        relations_unset: Vec::new(),
                        anchors_unset: Vec::new(),
                    },
                    actor,
                    Some(&client),
                    None,
                )
                .unwrap()
        };

    // Section-only update on an unsatisfied entity: warning fires,
    // mutation commits.
    let outcome = update(&mut engine, &a.id, vec![]);
    assert!(!outcome.write_id.is_empty());
    assert_eq!(
        missing_outgoing_of(&outcome.warnings),
        vec![(vec!["PART_OF".to_string()], "at_least_one".to_string())]
    );

    // Declaring the satisfying relation in the update clears it.
    let outcome = update(
        &mut engine,
        &a.id,
        vec![crate::ops::RelateArg {
            target: b.id.clone(),
            rel_type: "PART_OF".to_string(),
            description: None,
        }],
    );
    assert!(
        missing_outgoing_of(&outcome.warnings).is_empty(),
        "satisfied block emits no warning: {:?}",
        outcome.warnings
    );
}