memstead-base 0.25.0

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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
//! Per-entity history — the narrative query behind an inspector's
//! "how did this entity get this way".
//!
//! The engine already records everything a story needs (commit
//! subjects, provenance trailers, agent notes, batch entity lists,
//! rename chains) but exposed it only as branch-wide feeds; every
//! consumer filtered client-side. This module owns the per-entity
//! filter, rename-chain attribution, and pagination — one semantic for
//! every surface.
//!
//! Data sources per backend, all pre-existing:
//! - git-branch: the commit-note walk that already rides
//!   `changes_since` (`BackendChanges::notes`, newest-first) — full
//!   fidelity: sha, subject, trailers, batch `Entities:` lists,
//!   authoritative rename pairs in the subject.
//! - folder / in-memory: `MemBackend::read_provenance` (the
//!   `.memstead/changes.jsonl` line scan / its in-memory analogue,
//!   oldest-first) — same story, coarser: no batch entity lists, and
//!   rename records carry only the post-rename id, so chains are not
//!   stitchable. Both gaps surface as stated `limitations`, never as
//!   silently absent entries.
//! - archive: the seam records no history — typed refusal, never a
//!   fabricated empty story.
//!
//! This query is read-only and mutates nothing; it deliberately stays
//! narrative-only (content-level diffs per touch are the pairwise
//! `diff` op's job, git-branch consumers only).

use serde::Serialize;

use super::{Engine, EngineError};
use crate::workspace::MountStorage;

/// Default page size when the caller passes `None`.
pub const HISTORY_PAGE_DEFAULT: usize = 50;
/// Hard page-size cap; larger requests clamp here.
pub const HISTORY_PAGE_MAX: usize = 200;

/// One recorded touch of an entity, newest-first in the report.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct EntityTouch {
    /// Backend-native reference for this touch: the commit SHA on
    /// git-branch mems, the changelog RFC-3339 timestamp on folder /
    /// in-memory mems. Also the basis of the page cursor.
    pub reference: String,
    /// Touch time, seconds since unix epoch.
    pub timestamp: i64,
    /// The entity's id when this touch happened — pre-rename touches
    /// carry their then-current id (criterion: the story starts at the
    /// first appearance under any prior id).
    pub id_at_touch: String,
    /// Mutation verb (`create` / `update` / `delete` / `relate` /
    /// `rename` / `batch_update`…). `None` when the record predates
    /// the subject convention or the commit is external.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verb: Option<String>,
    /// Commit subject line (git-branch only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// The agent's stated intent, where one was written.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client: Option<String>,
    /// `Tool:` trailer (git-branch only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool: Option<String>,
    /// On a rename touch: the id before the rename. `None` on
    /// non-rename touches — and on folder-backend rename records,
    /// which don't carry the pre-rename id (a stated limitation).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub renamed_from: Option<String>,
    /// On a rename touch: the id after the rename.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub renamed_to: Option<String>,
    /// Every id a multi-entity commit touched (batch context — names
    /// the commit's scope without those entities' own stories
    /// appearing here). Empty for single-entity touches.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub batch_entity_ids: Vec<String>,
    /// Correlation id linking commits of one logical operation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logical_op: Option<String>,
    /// Caller-declared role this touch was performed in. Absent = unspecified — recorded as absence, never
    /// defaulted to a real role.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Caller-declared identity this touch was performed under
    ///. Absent = undeclared — recorded as
    /// absence, never inferred from actor or client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identity: Option<String>,
    /// On a proposal merge (or amend) touch: the merger's identity from
    /// the `Merged-By:` trailer, beside `identity` (the proposer on the
    /// merge commit). Never compared by the independence gate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merged_by: Option<String>,
    /// On a proposal merge (or amend) touch: the proposal's id from the
    /// `Proposal:` trailer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proposal: Option<String>,
    /// True when this touch is a proposal merge that created the entity
    /// in the target (the id sits in the commit's `Created:` trailer):
    /// the story's birth, as a `create` would be.
    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
    pub created_by_merge: bool,
}

/// Where the returned story starts — the visible-truncation contract:
/// whatever the record cannot reach is stated, never silent.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum StoryStart {
    /// The oldest recorded touch is the entity's creation — the full
    /// recorded story is reachable through the pages.
    Recorded,
    /// The story stops before the entity's first appearance, and here
    /// is why (unstitchable rename, records predating the changelog,
    /// an adopted mem with no history…).
    Truncated { reason: String },
}

/// Result of [`Engine::entity_history`] — one page of the newest-first
/// touch feed plus the explicit bounds of what it omits.
#[derive(Debug, Clone, Serialize)]
pub struct EntityHistoryReport {
    pub mem: String,
    /// The entity's current id (the query key).
    pub entity_id: String,
    /// This page's touches, newest first.
    pub touches: Vec<EntityTouch>,
    /// Total recorded touches across all pages — with `next_cursor`,
    /// this states exactly what a page omits.
    pub total_recorded: usize,
    /// Opaque continuation: pass back as `cursor` for the next page.
    /// `None` = this page ends the recorded story.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
    /// Where the recorded story starts (visible-truncation contract).
    pub story_start: StoryStart,
    /// Stated per-backend gaps (folder rename stitching, batch
    /// attribution). Empty on full-fidelity backends.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub limitations: Vec<String>,
}

/// Split a rename record's `entity_id` field (`"old → new"`) into the
/// pair. Cross-mem peer rewrites (parenthetical qualifier) and
/// malformed values return `None` — they modify wiki-link bodies in a
/// peer mem, never the entity itself.
pub(crate) fn parse_rename_pair(field: &str) -> Option<(String, String)> {
    if field.contains("(cross-mem rewrite") {
        return None;
    }
    let mut parts = field.splitn(2, " → ");
    let old = parts.next()?.trim();
    let new = parts.next()?.trim();
    if old.is_empty() || new.is_empty() {
        return None;
    }
    Some((old.to_string(), new.to_string()))
}

/// One derived provenance record — who performed a boundary touch of
/// an entity's story, in what declared role, when. Served by the entity read's opt-in provenance block.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ProvenanceRecord {
    /// Actor category (`agent` / `cli` / `app` / `external` /
    /// `unknown`), from the recorded trailer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// Client identity (`name@version`) when recorded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client: Option<String>,
    /// The caller-declared role, or `"unspecified"` — absence is
    /// served as the explicit cannot-confirm value, never as any
    /// real role.
    pub role: String,
    /// The caller-declared identity, when one was recorded — the
    /// independence gate's only comparator.
    /// Absence downgrades comparisons to `unconfirmable`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identity: Option<String>,
    /// Touch time, seconds since unix epoch.
    pub timestamp: i64,
    /// Backend-native reference (commit sha / ledger timestamp).
    pub reference: String,
    /// The mutation verb of the touch (`create` / `update` / `rename` /
    /// `retype` / `relate` / …), when the record carries one — so a
    /// reader can tell a type change from an edit without opening the
    /// commit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verb: Option<String>,
    /// On a touch a proposal merge made: the merger's identity
    /// (`Merged-By:`), beside `identity`, which names the proposer on
    /// the merge commit and the merger on the amend commit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merged_by: Option<String>,
    /// On a touch a proposal merge made: the proposal's id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proposal: Option<String>,
    /// On a touch a proposal merge made: the disposition the target's
    /// proposal record holds for this entity under that proposal
    /// (`adopt` or `adopt_with_changes`), when the record carries it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disposition: Option<String>,
    /// On a touch a proposal merge made: the proposal in the owner's
    /// words, when the target's proposal record carries a description
    /// for that proposal.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proposal_description: Option<String>,
}

/// The entity read's derived provenance block: created-by and
/// last-modified-by, derived from the append-only history record —
/// never from anything an agent can edit after the fact.
#[derive(Debug, Clone, serde::Serialize)]
pub struct EntityProvenance {
    /// The creation record. `None` when the recorded story does not
    /// start at the entity's creation (adopted/migrated mems) — the
    /// honesty pattern: absence stated, never fabricated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by: Option<ProvenanceRecord>,
    /// The newest recorded touch.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_modified_by: Option<ProvenanceRecord>,
    /// True when the recorded story is truncated (its oldest touch is
    /// not the creation) — `created_by` is then absent.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub story_truncated: bool,
    /// Derived `verification` check state:
    /// `never_checked` | `checked_ok` | `check_failed` | `check_stale`
    /// — computed by comparing the newest verification record's
    /// entity-hash against the current one, never stamped. Kind-scoped:
    /// a conformance record never supersedes it.
    pub check_state: String,
    /// The newest `verification` record, when one exists.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_check: Option<crate::check::CheckRecord>,
    /// The trust class of the CHECK PROSE on this entity: the `method`
    /// notes that every surface renders verbatim, across the verification
    /// record, the conformance record and each foreign kind.
    /// `Some("third-party")` when ANY of them was written by a party other
    /// than this workspace.
    ///
    /// The note is written by whatever agent recorded the check, which in a
    /// workspace that points a foreign model at its ledger, or that
    /// transcribes an outside finding under the outsider's handle, is not
    /// the workspace itself. On an archive mount the value is the one the
    /// exporting workspace SEALED ([`crate::check::SealedCheck::origin`]),
    /// because only that workspace knew which identities were its own; on
    /// every other mount it is derived from this deployment's declared
    /// identities ([`crate::Engine::check_row_origin_class`]).
    ///
    /// One field for all of them, and set if any one is foreign, so a
    /// renderer contains every note it prints rather than guessing per
    /// line. That over-contains the owner's own note on an entity that also
    /// carries a stranger's, which is the safe direction: the alternative
    /// is a stranger's sentence printed as the report's own voice.
    ///
    /// Absent when nothing foreign was recorded, so every response that has
    /// nothing to warn about is byte-unchanged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub check_prose_origin: Option<String>,
    /// Derived `conformance` state — the same four values, computed
    /// against the newest conformance record with pin-awareness (a
    /// schema re-pin stales it). `never_checked` when no conformance
    /// record exists, which is every pre-kind workspace.
    pub conformance_state: String,
    /// The newest `conformance` record, when one exists.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_conformance_check: Option<crate::check::CheckRecord>,
    /// The newest record per foreign `x-<name>` kind, in kind order:
    /// recorded verbatim, listed here, never aggregated into a state.
    /// Empty (and absent from the JSON) when none was recorded.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub foreign_checks: Vec<crate::check::CheckRecord>,
    /// On an archive mount: the authoring rationale the archive seals
    /// for this entity (`.memstead/provenance.json`), in place of the
    /// recorded touches an archive does not carry. Absent on source
    /// mems.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sealed: Option<SealedProvenance>,
}

/// The per-entity authoring rationale an installed archive carries,
/// read from the payload `export` seals; the reader never modifies the
/// archive. `carried: false` says so explicitly when the archive ships
/// no payload, or a payload with no entry for this entity: absence is
/// stated, never substituted.
#[derive(Debug, Clone, serde::Serialize)]
pub struct SealedProvenance {
    /// Whether the archive carries a rationale for this entity.
    pub carried: bool,
    /// The payload's history disposition (`summarised`) when a payload
    /// exists at all.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub history: Option<String>,
    /// The entity's authoring rationale (the most recent mutation note
    /// sealed for it).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rationale: Option<String>,
    /// The mutation kind that note rode on (`create` / `update` / ...).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// When it was recorded, RFC 3339 as sealed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
    /// The actor category recorded with it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// Whether the archive seals a check record for this entity
    /// (`.memstead/checks.json`). The check states above derive from
    /// those records alone on an archive mount; when `false` every
    /// state reads `never_checked` and `checks_reason` says why.
    pub checks_carried: bool,
    /// Why no sealed check record answers for this entity: the archive
    /// carries no check records at all, or none for this entity. Absent
    /// when one is carried.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checks_reason: Option<String>,
}

fn touch_to_record(t: &EntityTouch) -> ProvenanceRecord {
    ProvenanceRecord {
        actor: t.actor.clone(),
        client: t.client.clone(),
        role: t.role.clone().unwrap_or_else(|| "unspecified".to_string()),
        identity: t.identity.clone(),
        timestamp: t.timestamp,
        reference: t.reference.clone(),
        verb: t.verb.clone(),
        merged_by: t.merged_by.clone(),
        proposal: t.proposal.clone(),
        disposition: None,
        proposal_description: None,
    }
}

impl Engine {
    /// Derive an entity's provenance block:
    /// created-by (the oldest recorded touch, only when it IS the
    /// creation) and last-modified-by (the newest touch), each with
    /// actor identity, client, declared role, and timestamp — read
    /// from the same append-only record `entity_history` serves, so
    /// no verb can alter it after the fact. Pages through the full
    /// story to reach the creation record when histories exceed one
    /// page.
    pub fn entity_provenance(
        &self,
        mem: &str,
        entity_id: &str,
    ) -> Result<EntityProvenance, EngineError> {
        // An archive records no touches at the engine seam, but it
        // carries the rationale `export` sealed per entity: that is the
        // provenance an installed mem can answer with.
        if matches!(
            self.find_mount(mem)?.mount.storage,
            MountStorage::Archive { .. }
        ) {
            return self.sealed_provenance(mem, entity_id);
        }
        let mut report = self.entity_history(mem, entity_id, Some(HISTORY_PAGE_MAX), None)?;
        let newest = report.touches.first().cloned();
        // Walk to the last page for the oldest touch.
        while let Some(cursor) = report.next_cursor.clone() {
            report = self.entity_history(mem, entity_id, Some(HISTORY_PAGE_MAX), Some(&cursor))?;
        }
        let oldest = report.touches.last().or(newest.as_ref()).cloned();
        let truncated = !matches!(report.story_start, StoryStart::Recorded);
        let (check_state, last_check) = self.entity_check_state(mem, entity_id)?;
        let (conformance_state, last_conformance_check) =
            self.entity_conformance_state(mem, entity_id)?;
        // A touch a proposal merge made names its proposal; the
        // disposition it landed under and the proposal's description
        // are read from the target's own record, never from the commit
        // (the record is the merge's second write, in the same commit).
        let record = if oldest.as_ref().is_some_and(|t| t.proposal.is_some())
            || newest.as_ref().is_some_and(|t| t.proposal.is_some())
        {
            self.read_proposal_record(mem).ok().flatten()
        } else {
            None
        };
        let slug = crate::EntityId(entity_id.to_string()).path().to_string();
        let with_disposition = |t: &EntityTouch| -> ProvenanceRecord {
            let mut rec = touch_to_record(t);
            if let (Some(pid), Some(record)) = (t.proposal.as_deref(), record.as_ref())
                && let Some(entry) = record.proposals.iter().find(|p| p.id == pid)
            {
                rec.disposition = entry.entities.get(&slug).map(|d| d.disposition.clone());
                rec.proposal_description = entry.description.clone();
            }
            rec
        };
        Ok(EntityProvenance {
            created_by: match (&oldest, truncated) {
                (Some(t), false) => Some(with_disposition(t)),
                _ => None,
            },
            last_modified_by: newest.as_ref().map(with_disposition),
            story_truncated: truncated,
            check_state: check_state.as_str().to_string(),
            check_prose_origin: self.foreign_check_prose_marker(
                mem,
                entity_id,
                [last_check.as_ref(), last_conformance_check.as_ref()],
            ),
            last_check,
            conformance_state: conformance_state.as_str().to_string(),
            last_conformance_check,
            foreign_checks: self.latest_foreign_checks(mem, entity_id),
            sealed: None,
        })
    }

    /// The provenance block of an entity on an archive mount: the sealed
    /// rationale where the payload carries one, `carried: false` where
    /// it does not, and the check states derived from the sealed check
    /// records (`.memstead/checks.json`) the same way a workspace derives
    /// them from its ledger: the sealed record's hash against the sealed
    /// entity's content hash, so a record carried across a later edit
    /// reads stale. An archive without the member, or without a record
    /// for this entity, reads `never_checked` with the reason stated
    /// (`checks_carried: false`, `checks_reason`); a workspace ledger
    /// beside the mount is never consulted. Refuses `ENTITY_NOT_FOUND`
    /// for an id the mount does not serve, as the history read does.
    fn sealed_provenance(
        &self,
        mem: &str,
        entity_id: &str,
    ) -> Result<EntityProvenance, EngineError> {
        let known = self
            .store
            .all_entities()
            .any(|e| e.mem == mem && e.id.0 == entity_id);
        if !known {
            return Err(EngineError::NotFound {
                id: entity_id.to_string(),
            });
        }
        let id = crate::EntityId(entity_id.to_string());
        let (checks_carried, checks_reason) = match self.archive_checks_for(mem) {
            None => (
                false,
                Some(
                    "the archive carries no check records; every state reads never_checked"
                        .to_string(),
                ),
            ),
            Some(sealed) if sealed.kinds_of(id.path()).next().is_none() => (
                false,
                Some("the archive carries no check record for this entity".to_string()),
            ),
            Some(_) => (true, None),
        };
        let sealed = match self.archive_provenance_for(mem) {
            Some(payload) => {
                let history = Some(
                    serde_json::to_value(payload.history)
                        .ok()
                        .and_then(|v| v.as_str().map(str::to_string))
                        .unwrap_or_else(|| "unknown".to_string()),
                );
                match payload.entity(id.path()) {
                    Some(rec) => SealedProvenance {
                        carried: rec.rationale.is_some(),
                        history,
                        rationale: rec.rationale.clone(),
                        kind: rec.kind.clone(),
                        timestamp: rec.timestamp.clone(),
                        actor: rec.actor.clone(),
                        checks_carried,
                        checks_reason: checks_reason.clone(),
                    },
                    None => SealedProvenance {
                        carried: false,
                        history,
                        rationale: None,
                        kind: None,
                        timestamp: None,
                        actor: None,
                        checks_carried,
                        checks_reason: checks_reason.clone(),
                    },
                }
            }
            None => SealedProvenance {
                carried: false,
                history: None,
                rationale: None,
                kind: None,
                timestamp: None,
                actor: None,
                checks_carried,
                checks_reason: checks_reason.clone(),
            },
        };
        let (check_state, last_check) = self.entity_check_state(mem, entity_id)?;
        let (conformance_state, last_conformance_check) =
            self.entity_conformance_state(mem, entity_id)?;
        Ok(EntityProvenance {
            created_by: None,
            last_modified_by: None,
            story_truncated: false,
            check_state: check_state.as_str().to_string(),
            check_prose_origin: self.foreign_check_prose_marker(
                mem,
                entity_id,
                [last_check.as_ref(), last_conformance_check.as_ref()],
            ),
            last_check,
            conformance_state: conformance_state.as_str().to_string(),
            last_conformance_check,
            foreign_checks: self.latest_foreign_checks(mem, entity_id),
            sealed: Some(sealed),
        })
    }

    /// The trust class to report for a check record's own prose, and only
    /// when it is the foreign one: `Some("third-party")` where the note was
    /// written by a party other than this workspace, `None` otherwise, so
    /// the field appears exactly where it warns and every other response is
    /// byte-unchanged.
    ///
    /// On an archive mount the answer is the one the exporting workspace
    /// sealed beside the row, because that workspace is the only party that
    /// knew which identities were its own; a member sealed without the field
    /// falls through to this deployment's reading, as it did before the
    /// field existed. This is the reader that makes
    /// [`crate::check::SealedCheck::origin`] load-bearing: the sealed
    /// `method` note is carried into the record every surface renders, so
    /// without it a publisher's checker prose reaches a reading agent as the
    /// consumer's own.
    fn foreign_check_prose_marker(
        &self,
        mem: &str,
        entity_id: &str,
        records: [Option<&crate::check::CheckRecord>; 2],
    ) -> Option<String> {
        // Nothing can be foreign in the default deployment: with no declared
        // owner identities on a first-party mem every row reads as the
        // workspace's own, and only an archive mount can carry a sealed class.
        // Leaving early keeps the marker from re-reading and re-parsing the
        // whole check ledger once more per provenance read.
        if !self.declares_owner_identities()
            && !self.is_archive_mount(mem)
            && !self.mem_origin_class(mem).is_third_party()
        {
            return None;
        }
        let foreign = |rec: &crate::check::CheckRecord| {
            self.check_row_prose_origin(mem, entity_id, rec)
                .is_third_party()
        };
        let any_foreign = records.into_iter().flatten().any(foreign)
            || self
                .latest_foreign_checks(mem, entity_id)
                .iter()
                .any(foreign);
        any_foreign.then(|| crate::render::OriginClass::ThirdParty.as_wire().to_string())
    }

    /// An entity's recorded history: every touch, newest-first, with
    /// rename chains followed so the story starts at the entity's
    /// first appearance under any prior id. Bounded and pageable —
    /// `page_size` clamps to [`HISTORY_PAGE_MAX`], `cursor` continues
    /// a prior page (`INVALID_CURSOR` when it matches no touch).
    ///
    /// Refusals: `UNKNOWN_MEM`, `ENTITY_NOT_FOUND` (an unknown id
    /// never yields an empty story), `INVALID_INPUT` on archive
    /// mounts (their seam records no history — refusing beats
    /// fabricating emptiness).
    pub fn entity_history(
        &self,
        mem: &str,
        entity_id: &str,
        page_size: Option<usize>,
        cursor: Option<&str>,
    ) -> Result<EntityHistoryReport, EngineError> {
        let m = self.find_mount(mem)?;

        // An unknown entity refuses — marklessness-style honesty: the
        // caller learns "no such entity", never an empty history that
        // reads as "exists, untouched".
        let known = self
            .store
            .all_entities()
            .any(|e| e.mem == mem && e.id.0 == entity_id);
        if !known {
            return Err(EngineError::NotFound {
                id: entity_id.to_string(),
            });
        }

        let mut limitations: Vec<String> = Vec::new();

        // ---- Collect the raw record, newest-first, per backend ----
        let touches: Vec<EntityTouch> = match &m.mount.storage {
            MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
                Some(hook) => {
                    let backend_changes = (hook.changes_since)(
                        gitdir,
                        branch,
                        mem,
                        crate::ops::EMPTY_TREE_SHA,
                        crate::ops::RENAME_SIMILARITY_DEFAULT,
                    )
                    .map_err(EngineError::Backend)?;
                    filter_notes_for_entity(entity_id, &backend_changes.notes)
                }
                None => {
                    limitations.push(
                        "this build carries no git-branch history walk — the recorded story \
                         is not reachable"
                            .to_string(),
                    );
                    Vec::new()
                }
            },
            MountStorage::Folder { .. } | MountStorage::InMemory => {
                limitations.push(
                    "changelog-backed history: rename records carry only the post-rename id \
                     (prior-id chains are not stitchable) and batch mutations record no \
                     per-entity attribution on this backend"
                        .to_string(),
                );
                let records = m
                    .backend
                    .read_provenance(None)
                    .map_err(EngineError::Backend)?;
                filter_provenance_for_entity(entity_id, &records)
            }
            MountStorage::Archive { .. } => {
                return Err(EngineError::InvalidInput(format!(
                    "mem '{mem}' is an archive mount — archives record no history at the \
                     engine seam; open the source mem for the entity's story"
                )));
            }
        };

        // ---- Visible-truncation verdict ----
        // The recorded story is complete exactly when its oldest touch
        // is the entity's creation. Anything else — empty record,
        // oldest touch mid-stream — states where and why it stops.
        let story_start = match touches.last() {
            // `batch-create` IS this entity's creation when it is the
            // oldest touch — a batch-authored entity carries the same
            // append-only provenance (role, identity trailers) as a
            // single create, and treating it as truncation erased
            // `created_by` for every batch-authored entity, which
            // silently degraded the checks independence gate to
            // `unconfirmable` (found 2026-08-28, graph-plans pilot).
            // A proposal merge that lists the id under `Created:` brought
            // the entity into the target: its creation, under the
            // proposer's identity (plan-proposal 03).
            Some(oldest)
                if matches!(
                    oldest.verb.as_deref(),
                    Some("create") | Some("batch-create")
                ) || oldest.created_by_merge =>
            {
                StoryStart::Recorded
            }
            Some(oldest) => StoryStart::Truncated {
                reason: format!(
                    "oldest recorded touch is a {} of `{}`, not the entity's creation — \
                     earlier history (an unrecorded prior id, or records predating the \
                     provenance log) is not reachable",
                    oldest.verb.as_deref().unwrap_or("touch"),
                    oldest.id_at_touch
                ),
            },
            None => StoryStart::Truncated {
                reason: "no touches recorded — the entity predates this mem's provenance \
                         record (an adopted or migrated mem)"
                    .to_string(),
            },
        };

        // ---- Page ----
        let size = page_size
            .unwrap_or(HISTORY_PAGE_DEFAULT)
            .clamp(1, HISTORY_PAGE_MAX);
        let start_idx = match cursor {
            None => 0,
            Some(c) => {
                let pos = parse_cursor(c).and_then(|(reference, k)| {
                    touches
                        .iter()
                        .enumerate()
                        .filter(|(_, t)| t.reference == reference)
                        .nth(k)
                        .map(|(i, _)| i + 1)
                });
                pos.ok_or_else(|| EngineError::InvalidChangesCursor {
                    mem: mem.to_string(),
                    since: c.to_string(),
                })?
            }
        };
        let total_recorded = touches.len();
        let page: Vec<EntityTouch> = touches[start_idx.min(total_recorded)..]
            .iter()
            .take(size)
            .cloned()
            .collect();
        let next_cursor = if start_idx + page.len() < total_recorded {
            page.last().map(|last| {
                let k = touches[..start_idx + page.len()]
                    .iter()
                    .filter(|t| t.reference == last.reference)
                    .count()
                    - 1;
                format!("{}@{k}", last.reference)
            })
        } else {
            None
        };

        Ok(EntityHistoryReport {
            mem: mem.to_string(),
            entity_id: entity_id.to_string(),
            touches: page,
            total_recorded,
            next_cursor,
            story_start,
            limitations,
        })
    }
}

/// Cursor wire form: `<reference>@<occurrence>` where `occurrence`
/// disambiguates touches sharing a reference (same-millisecond folder
/// changelog lines; impossible for commit SHAs but the format stays
/// uniform). Opaque to callers.
fn parse_cursor(c: &str) -> Option<(String, usize)> {
    let (reference, k) = c.rsplit_once('@')?;
    if reference.is_empty() {
        return None;
    }
    Some((reference.to_string(), k.parse().ok()?))
}

/// Newest→oldest single pass over the commit-note walk, tracking the
/// entity's id backwards through authoritative rename records:
/// `current` starts at the queried id; a rename whose *new* id equals
/// `current` is that entity's rename touch and flips `current` to the
/// old id, so every older touch is matched under its then-current id.
/// A rename whose *old* id equals `current` is a different entity's
/// departure from an id later reused — deliberately not a touch.
///
/// The walk STOPS at the entity's creation: a `create` of the tracked
/// id is the story's birth, and anything older under the same id
/// belonged to a previous holder of a reused slug (renamed away or
/// deleted before this entity existed) — absorbing it would attribute
/// a stranger's touches to this entity and present the polluted story
/// as `Recorded` (found by plan 03/02's grading gate).
pub(crate) fn filter_notes_for_entity(
    entity_id: &str,
    notes: &[crate::ops::agent_notes::CommitNote],
) -> Vec<EntityTouch> {
    let mut current = entity_id.to_string();
    let mut out: Vec<EntityTouch> = Vec::new();
    for n in notes {
        let base = |id_at: &str| EntityTouch {
            reference: n.sha.clone(),
            timestamp: n.timestamp,
            id_at_touch: id_at.to_string(),
            verb: n.tool_verb.clone(),
            subject: Some(n.subject.clone()),
            note: n.note.clone(),
            actor: n.actor.clone(),
            client: n.client.clone(),
            tool: n.tool.clone(),
            renamed_from: None,
            renamed_to: None,
            batch_entity_ids: Vec::new(),
            logical_op: n.logical_operation_id.clone(),
            role: n.role.clone(),
            identity: n.identity.clone(),
            merged_by: n.merged_by.clone(),
            proposal: n.proposal.clone(),
            created_by_merge: false,
        };
        if n.tool_verb.as_deref() == Some("rename") {
            if let Some((old, new)) = n.entity_id.as_deref().and_then(parse_rename_pair)
                && new == current
            {
                let mut touch = base(&new);
                touch.renamed_from = Some(old.clone());
                touch.renamed_to = Some(new);
                out.push(touch);
                current = old;
            }
            continue;
        }
        if n.entity_id.as_deref() == Some(current.as_str()) {
            let is_create = n.tool_verb.as_deref() == Some("create");
            out.push(base(&current));
            if is_create {
                break;
            }
        } else if n.entity_ids.iter().any(|id| id == &current) {
            let mut touch = base(&current);
            touch.batch_entity_ids = n.entity_ids.clone();
            // A proposal merge that lists this id under `Created:`
            // brought it into the target: its creation, same stop.
            let created_by_merge = n.created_ids.iter().any(|id| id == &current);
            touch.created_by_merge = created_by_merge;
            out.push(touch);
            // A batch-create that lists this entity is its creation —
            // nothing older can touch it, same stop as single create.
            if n.tool_verb.as_deref() == Some("batch-create") || created_by_merge {
                break;
            }
        }
    }
    out
}

/// Changelog-backed record (folder / in-memory): filter the
/// oldest-first provenance feed to the entity's id and reverse to
/// newest-first. Rename records match only when they carry this
/// entity's (post-rename) id — the pre-rename chain is not recorded
/// on this backend (stated limitation upstream).
///
/// Reused-id guard, symmetric with the git-branch walk: the story
/// starts at the id's NEWEST `create` record — older records under the
/// same id belonged to a previous holder of the slug, never to this
/// entity.
fn filter_provenance_for_entity(
    entity_id: &str,
    records: &[crate::provenance::Provenance],
) -> Vec<EntityTouch> {
    let matching: Vec<&crate::provenance::Provenance> = records
        .iter()
        .filter(|p| p.entity.as_deref() == Some(entity_id))
        .collect();
    let birth = matching
        .iter()
        .rposition(|p| matches!(p.kind, crate::provenance::ProvenanceKind::Create))
        .unwrap_or(0);
    let mut out: Vec<EntityTouch> = matching[birth..]
        .iter()
        .map(|p| {
            let is_rename = matches!(p.kind, crate::provenance::ProvenanceKind::Rename);
            EntityTouch {
                reference: crate::filesystem::changelog::format_rfc3339_utc(p.timestamp),
                timestamp: p
                    .timestamp
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs() as i64)
                    .unwrap_or(0),
                id_at_touch: entity_id.to_string(),
                verb: Some(p.kind.as_str().to_string()),
                subject: None,
                note: p.note.clone(),
                actor: Some(p.actor.as_trailer().to_string()),
                client: p
                    .client
                    .as_ref()
                    .map(|c| format!("{}@{}", c.name, c.version)),
                tool: None,
                renamed_from: None,
                renamed_to: is_rename.then(|| entity_id.to_string()),
                batch_entity_ids: Vec::new(),
                logical_op: p.logical_operation_id.clone(),
                role: p.role.as_trailer().map(str::to_string),
                identity: p.identity.clone(),
                merged_by: None,
                proposal: None,
                created_by_merge: false,
            }
        })
        .collect();
    out.reverse();
    out
}

#[cfg(test)]
mod tests {
    use crate::backend::MemBackend;

    /// A `batch-create` commit that lists the entity IS its creation:
    /// the filter stops walking older history there (regression: an
    /// older unrelated note must not attach), and the touch keeps the
    /// `batch-create` verb the story-start check accepts — before the
    /// 2026-08-28 fix every batch-authored entity read as truncated,
    /// which erased `created_by` and degraded the checks independence
    /// gate to `unconfirmable`.
    #[test]
    fn batch_create_note_is_the_entitys_creation() {
        use crate::ops::agent_notes::CommitNote;
        let note = |sha: &str, verb: &str, entity_id: Option<&str>, ids: Vec<&str>| CommitNote {
            mem: "m".into(),
            sha: sha.into(),
            subject: format!("memstead: {verb}"),
            tool_verb: Some(verb.into()),
            entity_id: entity_id.map(str::to_string),
            note: None,
            actor: Some("cli".into()),
            tool: None,
            client: None,
            logical_operation_id: None,
            role: Some("author".into()),
            identity: Some("author-x".into()),
            entity_ids: ids.into_iter().map(str::to_string).collect(),
            merged_by: None,
            proposal: None,
            created_ids: Vec::new(),
            timestamp: 1,
        };
        // Newest-first: an update, then the batch create, then an
        // unrelated older note that must never be reached.
        let notes = vec![
            note("c3", "update", Some("m--thing"), vec![]),
            note("c2", "batch-create", None, vec!["m--other", "m--thing"]),
            note("c1", "update", Some("m--thing"), vec![]),
        ];
        let touches = super::filter_notes_for_entity("m--thing", &notes);
        assert_eq!(
            touches.len(),
            2,
            "the walk stops at the batch create: {touches:?}"
        );
        let oldest = touches.last().unwrap();
        assert_eq!(oldest.verb.as_deref(), Some("batch-create"));
        assert_eq!(oldest.identity.as_deref(), Some("author-x"));
        assert!(
            matches!(
                oldest.verb.as_deref(),
                Some("create") | Some("batch-create")
            ),
            "the story-start acceptance covers the batch verb"
        );
    }

    /// Plan-proposal 03: a `proposal-merge` note that lists the id under
    /// `Created:` is the entity's creation (the walk stops there and the
    /// story reads `Recorded`); one that lists it only under `Entities:`
    /// is an update touch and the walk continues to the older create.
    #[test]
    fn proposal_merge_note_creates_or_touches() {
        use crate::ops::agent_notes::CommitNote;
        let merge = |sha: &str, ids: Vec<&str>, created: Vec<&str>| CommitNote {
            mem: "m".into(),
            sha: sha.into(),
            subject: "memstead: proposal-merge f@b".into(),
            tool_verb: Some("proposal-merge".into()),
            entity_id: Some("f@b".into()),
            note: None,
            actor: Some("cli".into()),
            tool: Some("proposal_merge".into()),
            client: None,
            logical_operation_id: None,
            role: None,
            identity: Some("proposer-p1".into()),
            entity_ids: ids.into_iter().map(str::to_string).collect(),
            merged_by: Some("owner".into()),
            proposal: Some("f@b".into()),
            created_ids: created.into_iter().map(str::to_string).collect(),
            timestamp: 2,
        };
        let create = CommitNote {
            mem: "m".into(),
            sha: "c1".into(),
            subject: "memstead: create m--beta".into(),
            tool_verb: Some("create".into()),
            entity_id: Some("m--beta".into()),
            note: None,
            actor: Some("cli".into()),
            tool: None,
            client: None,
            logical_operation_id: None,
            role: None,
            identity: Some("owner".into()),
            entity_ids: Vec::new(),
            merged_by: None,
            proposal: None,
            created_ids: Vec::new(),
            timestamp: 1,
        };
        let notes = vec![
            merge("c2", vec!["m--beta", "m--eta"], vec!["m--eta"]),
            create.clone(),
        ];
        // eta: created by the merge; the walk stops at the merge.
        let eta = super::filter_notes_for_entity("m--eta", &notes);
        assert_eq!(eta.len(), 1);
        assert!(eta[0].created_by_merge);
        assert_eq!(eta[0].identity.as_deref(), Some("proposer-p1"));
        assert_eq!(eta[0].merged_by.as_deref(), Some("owner"));
        assert_eq!(eta[0].proposal.as_deref(), Some("f@b"));
        // beta: touched by the merge, created earlier.
        let beta = super::filter_notes_for_entity("m--beta", &notes);
        assert_eq!(beta.len(), 2);
        assert!(!beta[0].created_by_merge);
        assert_eq!(beta[1].verb.as_deref(), Some("create"));
        let _ = create;
    }

    const SEED: &str = "---\ntype: spec\ncreated_date: 2026-01-01\nlast_modified: 2026-01-01\nlevel: M0\n---\n# Seed\n\n## Identity\n\nSeed.\n";

    /// Folder-backed engine with one pre-existing entity written
    /// outside the engine (no changelog record) — mirrors the review
    /// module's fixture.
    fn folder_engine(tmp: &tempfile::TempDir) -> crate::Engine {
        let dir = tmp.path().join("specs");
        if !dir.exists() {
            std::fs::create_dir_all(&dir).unwrap();
            let writer = crate::storage::FilesystemBackend::new(dir.clone());
            MemBackend::write_entity(&writer, std::path::Path::new("seed.md"), SEED.as_bytes())
                .unwrap();
            MemBackend::commit(&writer, "seed", &crate::vcs::CommitContext::internal()).unwrap();
        }
        let mount = crate::Mount {
            mem: "specs".to_string(),
            schema: Some(memstead_schema::SchemaRef::new(
                "default",
                semver::Version::new(1, 0, 0),
            )),
            storage: crate::MountStorage::Folder { path: dir.clone() },
            capability: crate::MountCapability::Write,
            lifecycle: crate::MountLifecycle::Eager,
            cross_linkable: false,
            migration_target: None,
        };
        let backend =
            Box::new(crate::storage::FilesystemBackend::new(dir)) as Box<dyn crate::MemBackend>;
        crate::Engine::from_mounts(vec![(mount, backend)]).unwrap()
    }

    fn create(engine: &mut crate::Engine, title: &str, note: &str) -> String {
        let outcome = engine
            .create_entity(
                crate::CreateEntityArgs {
                    mem: "specs".to_string(),
                    title: title.to_string(),
                    entity_type: "spec".to_string(),
                    sections: [
                        ("identity".to_string(), "x".to_string()),
                        ("purpose".to_string(), "y".to_string()),
                    ]
                    .into_iter()
                    .collect(),
                    metadata: Default::default(),
                    relations: Vec::new(),
                    anchors: Vec::new(),
                    dry_run: false,
                },
                crate::vcs::Actor::Cli,
                None,
                Some(note),
            )
            .unwrap();
        outcome.id.0
    }

    fn update(engine: &mut crate::Engine, id: &str, note: &str) {
        engine
            .update_entity(
                crate::UpdateEntityArgs {
                    id: crate::EntityId(id.to_string()),
                    expected_hash: None,
                    sections: [("identity".to_string(), format!("touched: {note}"))]
                        .into_iter()
                        .collect(),
                    append_sections: Default::default(),
                    patch_sections: Default::default(),
                    sections_unset: Vec::new(),
                    metadata: Default::default(),
                    metadata_unset: Vec::new(),
                    dry_run: false,
                    declare_relations: Vec::new(),
                    anchors: Vec::new(),
                    relations_unset: Vec::new(),
                    anchors_unset: Vec::new(),
                },
                crate::vcs::Actor::App,
                None,
                Some(note),
            )
            .unwrap();
    }

    #[test]
    fn folder_history_serves_touches_with_stated_limitations() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = folder_engine(&tmp);
        let id = create(&mut engine, "Story", "born");
        update(&mut engine, &id, "grew");

        let report = engine.entity_history("specs", &id, None, None).unwrap();
        assert_eq!(report.total_recorded, 2);
        assert_eq!(report.touches.len(), 2);
        // Newest first: the update, then the create.
        assert_eq!(report.touches[0].verb.as_deref(), Some("update"));
        assert_eq!(report.touches[0].note.as_deref(), Some("grew"));
        assert_eq!(report.touches[0].actor.as_deref(), Some("app"));
        assert_eq!(report.touches[1].verb.as_deref(), Some("create"));
        assert_eq!(report.touches[1].actor.as_deref(), Some("cli"));
        assert_eq!(report.story_start, super::StoryStart::Recorded);
        assert!(
            report
                .limitations
                .iter()
                .any(|l| l.contains("rename records carry only the post-rename id")),
            "folder limitations must be stated: {:?}",
            report.limitations
        );
        // Touches of the *other* entity (the seed) never appear.
        assert!(report.touches.iter().all(|t| t.id_at_touch == id));
    }

    #[test]
    fn folder_rename_truncates_visibly_not_silently() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = folder_engine(&tmp);
        let id = create(&mut engine, "Before Rename", "born");
        let outcome = engine
            .rename_entity(
                crate::RenameEntityArgs {
                    id: crate::EntityId(id.clone()),
                    expected_hash: None,
                    new_title: "After Rename".to_string(),
                },
                crate::vcs::Actor::Cli,
                None,
                Some("renamed"),
            )
            .unwrap();
        let new_id = outcome.new_id.0;

        // The folder changelog records renames under the post-rename
        // id only — the story under the new id starts at the rename
        // and SAYS so (never an unexplained short history).
        let report = engine.entity_history("specs", &new_id, None, None).unwrap();
        assert_eq!(report.touches[0].verb.as_deref(), Some("rename"));
        assert!(report.touches[0].renamed_from.is_none());
        match &report.story_start {
            super::StoryStart::Truncated { reason } => {
                assert!(
                    reason.contains("not the entity's creation"),
                    "reason must explain the truncation: {reason}"
                );
            }
            other => panic!("expected visible truncation, got {other:?}"),
        }
    }

    #[test]
    fn reused_id_never_absorbs_the_previous_holders_story() {
        // Rename an entity away, then create a NEW entity under the
        // freed slug: the newcomer's story must start at ITS create —
        // pre-fix it absorbed the previous holder's touches and
        // presented the polluted story as `Recorded` (grading-gate
        // finding, plan 03/02).
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = folder_engine(&tmp);
        let id = create(&mut engine, "Slot", "first holder");
        update(&mut engine, &id, "first holder grew");
        engine
            .rename_entity(
                crate::RenameEntityArgs {
                    id: crate::EntityId(id.clone()),
                    expected_hash: None,
                    new_title: "Slot Moved".to_string(),
                },
                crate::vcs::Actor::Cli,
                None,
                Some("moved away"),
            )
            .unwrap();
        let reused = create(&mut engine, "Slot", "second holder");
        assert_eq!(reused, id, "the slug is reused");

        let report = engine.entity_history("specs", &reused, None, None).unwrap();
        assert_eq!(report.total_recorded, 1, "only its own birth: {report:#?}");
        assert_eq!(report.touches[0].verb.as_deref(), Some("create"));
        assert_eq!(report.touches[0].note.as_deref(), Some("second holder"));
        assert!(matches!(report.story_start, super::StoryStart::Recorded));
    }

    #[test]
    fn refusals_are_typed_never_empty_stories() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = folder_engine(&tmp);
        let id = create(&mut engine, "Real", "born");

        // Unknown mem.
        let err = engine.entity_history("ghost", &id, None, None).unwrap_err();
        assert_eq!(err.code(), "UNKNOWN_MEM");
        // Unknown entity — never an empty history.
        let err = engine
            .entity_history("specs", "specs--nope", None, None)
            .unwrap_err();
        assert_eq!(err.code(), "ENTITY_NOT_FOUND");
        // Garbage cursor.
        let err = engine
            .entity_history("specs", &id, None, Some("zzz@0"))
            .unwrap_err();
        assert_eq!(err.code(), "INVALID_CURSOR");
        let err = engine
            .entity_history("specs", &id, None, Some("no-separator"))
            .unwrap_err();
        assert_eq!(err.code(), "INVALID_CURSOR");
    }

    #[test]
    fn pre_changelog_entity_states_the_empty_record() {
        // The seed entity was written outside the engine — no
        // changelog line exists for it. Its story is empty AND says
        // why, distinguishable from "exists, untouched" by the stated
        // truncation.
        let tmp = tempfile::TempDir::new().unwrap();
        let engine = folder_engine(&tmp);
        let report = engine
            .entity_history("specs", "specs--seed", None, None)
            .unwrap();
        assert!(report.touches.is_empty());
        assert!(matches!(
            report.story_start,
            super::StoryStart::Truncated { .. }
        ));
    }

    /// An archive mount answers the provenance read with the rationale
    /// it seals per entity; where the payload carries no entry, or the
    /// archive ships no payload, the block says so instead of refusing.
    /// The history read keeps refusing: an archive records no touches.
    #[test]
    fn archive_mounts_serve_the_sealed_rationale_as_provenance() {
        struct SealedBackend {
            inner: crate::storage::InMemoryBackend,
            payload: Option<Vec<u8>>,
        }
        impl crate::backend::MemBackend for SealedBackend {
            fn list_entities(
                &self,
            ) -> Result<Vec<std::path::PathBuf>, crate::backend::BackendError> {
                self.inner.list_entities()
            }
            fn read_entity(
                &self,
                rel: &std::path::Path,
            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
                self.inner.read_entity(rel)
            }
            fn write_entity(
                &self,
                p: &std::path::Path,
                b: &[u8],
            ) -> Result<(), crate::backend::BackendError> {
                self.inner.write_entity(p, b)
            }
            fn delete_entity(
                &self,
                p: &std::path::Path,
            ) -> Result<(), crate::backend::BackendError> {
                self.inner.delete_entity(p)
            }
            fn move_entity(
                &self,
                f: &std::path::Path,
                t: &std::path::Path,
            ) -> Result<(), crate::backend::BackendError> {
                self.inner.move_entity(f, t)
            }
            fn commit(
                &self,
                m: &str,
                c: &crate::vcs::CommitContext<'_>,
            ) -> Result<crate::storage::CommitId, crate::backend::BackendError> {
                self.inner.commit(m, c)
            }
            fn append_provenance(
                &self,
                r: &crate::provenance::Provenance,
            ) -> Result<(), crate::backend::BackendError> {
                self.inner.append_provenance(r)
            }
            fn read_provenance(
                &self,
                c: Option<&str>,
            ) -> Result<Vec<crate::provenance::Provenance>, crate::backend::BackendError>
            {
                self.inner.read_provenance(c)
            }
            fn read_archive_provenance(
                &self,
            ) -> Result<Option<Vec<u8>>, crate::backend::BackendError> {
                Ok(self.payload.clone())
            }
        }
        fn engine_with(payload: Option<Vec<u8>>) -> crate::Engine {
            let dir = tempfile::TempDir::new().unwrap();
            let inner = crate::storage::InMemoryBackend::new();
            crate::backend::MemBackend::write_entity(
                &inner,
                std::path::Path::new("seed.md"),
                SEED.as_bytes(),
            )
            .unwrap();
            crate::backend::MemBackend::write_entity(
                &inner,
                std::path::Path::new("bare.md"),
                SEED.replace("# Seed", "# Bare").as_bytes(),
            )
            .unwrap();
            crate::backend::MemBackend::commit(
                &inner,
                "seed",
                &crate::vcs::CommitContext::internal(),
            )
            .unwrap();
            let mount = crate::Mount {
                mem: "specs".to_string(),
                schema: Some(memstead_schema::SchemaRef::new(
                    "default",
                    semver::Version::new(1, 0, 0),
                )),
                storage: crate::MountStorage::Archive {
                    path: dir.path().join("sealed.mem"),
                },
                capability: crate::MountCapability::Write,
                lifecycle: crate::MountLifecycle::Eager,
                cross_linkable: false,
                migration_target: None,
            };
            crate::Engine::from_mounts(vec![(
                mount,
                Box::new(SealedBackend { inner, payload }) as Box<dyn crate::MemBackend>,
            )])
            .unwrap()
        }
        let payload = serde_json::json!({
            "format": 1,
            "history": "summarised",
            "entities": {
                "seed": {
                    "rationale": "seeded so the graph starts non-empty",
                    "kind": "create",
                    "timestamp": "2026-06-24T11:32:02Z",
                    "actor": "agent"
                }
            }
        });
        let engine = engine_with(Some(serde_json::to_vec(&payload).unwrap()));
        let prov = engine.entity_provenance("specs", "specs--seed").unwrap();
        let sealed = prov.sealed.expect("archive mount serves the sealed block");
        assert!(sealed.carried);
        assert_eq!(
            sealed.rationale.as_deref(),
            Some("seeded so the graph starts non-empty")
        );
        assert_eq!(sealed.kind.as_deref(), Some("create"));
        assert_eq!(sealed.actor.as_deref(), Some("agent"));
        assert_eq!(sealed.history.as_deref(), Some("summarised"));
        assert!(prov.created_by.is_none() && prov.last_modified_by.is_none());
        // An entity the payload does not name: stated as not carried.
        let bare = engine.entity_provenance("specs", "specs--bare").unwrap();
        let sealed = bare.sealed.unwrap();
        assert!(!sealed.carried && sealed.rationale.is_none());
        assert_eq!(sealed.history.as_deref(), Some("summarised"));
        // An unknown id still refuses, as the history read does.
        assert_eq!(
            engine
                .entity_provenance("specs", "specs--ghost")
                .unwrap_err()
                .code(),
            "ENTITY_NOT_FOUND"
        );
        // An archive with no payload at all: not carried, no history word.
        let engine = engine_with(None);
        let none = engine.entity_provenance("specs", "specs--seed").unwrap();
        let sealed = none.sealed.unwrap();
        assert!(!sealed.carried && sealed.history.is_none());
        // The history read keeps its refusal.
        assert_eq!(
            engine
                .entity_history("specs", "specs--seed", None, None)
                .unwrap_err()
                .code(),
            "INVALID_INPUT"
        );
    }

    #[test]
    fn archive_mounts_refuse_rather_than_fabricate_emptiness() {
        // An archive-declared mount whose backend nonetheless serves
        // the store: the storage arm must refuse before the seam's
        // history-free `read_provenance` can masquerade as an empty
        // story.
        let dir = tempfile::TempDir::new().unwrap();
        let backend = crate::storage::InMemoryBackend::new();
        crate::backend::MemBackend::write_entity(
            &backend,
            std::path::Path::new("seed.md"),
            SEED.as_bytes(),
        )
        .unwrap();
        crate::backend::MemBackend::commit(
            &backend,
            "seed",
            &crate::vcs::CommitContext::internal(),
        )
        .unwrap();
        let mount = crate::Mount {
            mem: "specs".to_string(),
            schema: Some(memstead_schema::SchemaRef::new(
                "default",
                semver::Version::new(1, 0, 0),
            )),
            storage: crate::MountStorage::Archive {
                path: dir.path().join("sealed.mem"),
            },
            capability: crate::MountCapability::Write,
            lifecycle: crate::MountLifecycle::Eager,
            cross_linkable: false,
            migration_target: None,
        };
        let engine = crate::Engine::from_mounts(vec![(
            mount,
            Box::new(backend) as Box<dyn crate::MemBackend>,
        )])
        .unwrap();
        let err = engine
            .entity_history("specs", "specs--seed", None, None)
            .unwrap_err();
        assert_eq!(err.code(), "INVALID_INPUT");
    }

    #[test]
    fn pages_compose_without_gaps_or_duplicates() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut engine = folder_engine(&tmp);
        let id = create(&mut engine, "Paged", "born");
        for i in 0..5 {
            update(&mut engine, &id, &format!("touch {i}"));
        }

        let full = engine.entity_history("specs", &id, None, None).unwrap();
        assert_eq!(full.total_recorded, 6);
        assert!(full.next_cursor.is_none());

        // Walk in pages of 2 and re-compose.
        let mut collected: Vec<super::EntityTouch> = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let page = engine
                .entity_history("specs", &id, Some(2), cursor.as_deref())
                .unwrap();
            assert!(page.touches.len() <= 2);
            assert_eq!(page.total_recorded, 6, "every page states the whole");
            collected.extend(page.touches.clone());
            match page.next_cursor {
                Some(c) => cursor = Some(c),
                None => break,
            }
        }
        assert_eq!(
            collected, full.touches,
            "paged walk must equal the single-page story exactly"
        );
    }
}