qexo 1.4.2

qexo — the Exocortex coordinator, phext-native: all node state lives in one phext (system /var/lib/qexo or per-user ~/.qexo; Layer 2 addressing over phext)
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
//! Lattice — access to the node's one state file, addressed per
//! Layer 2 (docs/LAYER2.md, v2).
//!
//! The rules this module implements, from the corrected spec:
//! - Addresses are PLACES, chosen for meaning, and a coordinate
//!   is always 9D — all nine components, every time; there are
//!   no partial addresses anywhere in this crate's output. Each
//!   state family gets a patterned, roomy homeland, named by its
//!   anchor (the full 9D address of its index scroll):
//!   1.1.1/1.1.1/1.1.1 home/index/identity, 2.2.2/2.2.2/2.2.2
//!   keys & trust, 3.3.3/3.3.3/3.3.3 peers, 4.4.4/4.4.4/4.4.4
//!   personas, 5.5.5/5.5.5/5.5.5 plan, 6.6.6/6.6.6/6.6.6 ledgers,
//!   7.7.7/7.7.7/7.7.7 mailbox & sessions, 8.8.8/8.8.8/8.8.8
//!   telemetry, 9.9.9/9.9.9/9.9.9 config & wiring, and — added in
//!   v1.4.0, the tens — 10.10.10/10.10.10/10.10.10 lessons &
//!   learning (the `qexo learn` curriculum deck). Records live
//!   at full 9D addresses in the anchor's vicinity. No
//!   hash-derived coordinates, no counters-as-addresses, no
//!   arithmetic sequence splits.
//! - A record is ONE scroll; its fields are plain text lines
//!   inside it (`key: value`), the way CYOA records carry theirs.
//!   Documents cite-able in parts take adjacent scroll runs.
//! - The home scroll (1.1.1/1.1.1/1.1.1) is a prose INDEX of the
//!   homelands; each homeland's first scroll is its own index.
//!   Records are truth; indexes are derived prose, regenerated
//!   from the records by `regen_indexes` — commands call it after
//!   every mutation, and `qexo doctor --fix` calls it to repair.
//! - Growth is by adjacency: a new record takes the next free
//!   Book in its family's cluster, beside its kin. Identity
//!   (names, fingerprints) lives as text inside the records and
//!   the index scrolls — finding is navigation plus the index.
//! - Revisions edit scrolls in place; git carries history.
//!   Retirement is a `status:` line in the record.
//! - A state is topped up on write (v1.4.1): `save` seeds any
//!   index scroll the current layout defines that the document
//!   lacks — a state born under an older binary becomes whole
//!   under the new layout on its first write, and nothing it
//!   already carries is ever touched by the seeding.
//! - Which file IS the state is resolved intent-aware
//!   (v1.4.1): a write-intending verb in unprivileged hands
//!   never adopts a system state it cannot write; it selects
//!   the per-user state instead. Read-only verbs keep the
//!   v1.4.0 order unchanged. And `qexo learn` prefers an
//!   existing per-user deck (v1.4.2) — the deck is the
//!   operator's own. The full order is stated at
//!   `pick_state_path`.
//!
//! The state's substance: every scrap of node state — metadata,
//! keys, grants, personas, plan, ledgers, sessions — is scrolls
//! in this one file. qexo has no other state format. (The rule,
//! stated once: no JSON anywhere in qexo's own machinery; the
//! single foreign edge that speaks it is `infer`.)

use crate::phext::{Coord, Phext};
use std::path::PathBuf;

// ----------------------------------------------------------------
// Homelands (Layer 2): [Library, Shelf, Series] prefixes.
// ----------------------------------------------------------------

pub const HL_HOME: [u32; 3] = [1, 1, 1];
pub const HL_KEYS: [u32; 3] = [2, 2, 2];
pub const HL_PEERS: [u32; 3] = [3, 3, 3];
pub const HL_PERSONAS: [u32; 3] = [4, 4, 4];
pub const HL_PLAN: [u32; 3] = [5, 5, 5];
pub const HL_LEDGERS: [u32; 3] = [6, 6, 6];
pub const HL_MAIL: [u32; 3] = [7, 7, 7];
pub const HL_TELEMETRY: [u32; 3] = [8, 8, 8];
pub const HL_CONFIG: [u32; 3] = [9, 9, 9];
/// Lessons & learning (v1.4.0): the tens — practice, repeated.
/// The anchor pattern extends by one: where the nine ones-to-nines
/// homelands were the node's records of the world, the tens are
/// the node's record of its operator's practice.
pub const HL_LEARN: [u32; 3] = [10, 10, 10];

/// The curriculum deck's cluster inside the learn homeland: one
/// Book per card, grown by adjacency (Layer 2 growth rule).
pub const LEARN_DECK_C: u32 = 2;

/// The home scroll: prose index of the whole state file.
pub const HOME: Coord = [1, 1, 1, 1, 1, 1, 1, 1, 1];
/// Node identity record, adjacent to home in the home run.
pub const IDENTITY: Coord = [1, 1, 1, 1, 1, 1, 1, 1, 2];

/// Clusters (Collection) inside keys & trust (anchor 2.2.2/2.2.2/2.2.2), neighboring
/// runs in the order the brief names them: the node key first,
/// then persona keys, peer keys, grants, delegations, policy.
pub const KEYS_INDEX_C: u32 = 1;
pub const KEYS_NODE_C: u32 = 2;
pub const KEYS_PERSONA_C: u32 = 3;
pub const KEYS_PEER_C: u32 = 4;
pub const KEYS_GRANTS_C: u32 = 5;
pub const KEYS_DELEGATIONS_C: u32 = 6;
pub const KEYS_POLICY_C: u32 = 7;

/// The node key record and its armored public key (adjacent scroll).
pub const NODE_KEY_RECORD: Coord = [2, 2, 2, KEYS_NODE_C, 1, 1, 1, 1, 1];
pub const NODE_KEY_PUBLIC: Coord = [2, 2, 2, KEYS_NODE_C, 1, 1, 1, 1, 2];

/// Ledger kinds as clusters (Collection) inside 6.6.6.
pub const LEDGER_RECEIPTS: u32 = 2;
pub const LEDGER_TELEPORTS: u32 = 3;
pub const LEDGER_INSTANCES: u32 = 4;
pub const LEDGER_EMOTION: u32 = 5;
pub const LEDGER_GOAL_ACTIVITY: u32 = 6;
pub const LEDGER_SYNC: u32 = 7;
/// Release announcements (v1.1.0): one Book per announced release
/// — the manifest record at Scroll 1, its detached signature at
/// Scroll 2. The manifest is the phextnet's trust object: it is
/// what travels and what gets verified; the binary bytes ride
/// the wire beside the state file, never inside it.
pub const LEDGER_RELEASES: u32 = 8;

pub fn ledger_kind_name(cluster: u32) -> Option<&'static str> {
    match cluster {
        LEDGER_RECEIPTS => Some("receipts"),
        LEDGER_TELEPORTS => Some("teleports"),
        LEDGER_INSTANCES => Some("instances"),
        LEDGER_EMOTION => Some("emotion"),
        LEDGER_GOAL_ACTIVITY => Some("goal-activity"),
        LEDGER_SYNC => Some("sync-receipts"),
        LEDGER_RELEASES => Some("releases"),
        _ => None,
    }
}

/// Sessions (Collection 2) and mailbox (Collection 3) inside 7.7.7.
pub const MAIL_SESSIONS_C: u32 = 2;
pub const MAIL_BOX_C: u32 = 3;

/// Telemetry: disk observations (Collection 2) inside 8.8.8.
pub const TELEM_DISK_C: u32 = 2;

/// Plan (anchor 5.5.5/5.5.5/5.5.5): the current plan lives in Collection 2 (fields at
/// Scroll 1, the human rendering at Scroll 2, adjacent); history is
/// a run of Books in Collection 3, one Book per emitted plan.
pub const PLAN_CURRENT: Coord = [5, 5, 5, 2, 1, 1, 1, 1, 1];
pub const PLAN_CURRENT_RENDER: Coord = [5, 5, 5, 2, 1, 1, 1, 1, 2];
pub const PLAN_HISTORY_C: u32 = 3;

/// qexo's own config record: the node's settings as field lines —
/// no config file anywhere else. It lives at Collection 2 of the
/// 9.9.9/9.9.9/9.9.9 homeland; Collection 1's first scroll is the homeland
/// index, here as in every homeland (the two must never collide:
/// an index that reports on the config record cannot BE it).
pub const CONFIG_RECORD: Coord = [9, 9, 9, 2, 1, 1, 1, 1, 1];

// ----------------------------------------------------------------
// Address helpers
// ----------------------------------------------------------------

/// Compose an address from a homeland and the remaining six
/// components [Collection, Volume, Book, Chapter, Section, Scroll].
pub fn at(h: [u32; 3], rest: [u32; 6]) -> Coord {
    [h[0], h[1], h[2], rest[0], rest[1], rest[2], rest[3], rest[4], rest[5]]
}

/// A homeland's ANCHOR: the full 9D address of its index scroll —
/// the patterned address the region is named by (Layer 2 v2):
/// the homeland digit in all nine components, e.g. keys & trust
/// anchors at 2.2.2/2.2.2/2.2.2. (For the home homeland this is
/// 1.1.1/1.1.1/1.1.1 itself — the home scroll IS its anchor.)
/// Records live in the anchor's vicinity: they share the homeland
/// triple and place themselves in the remaining six components,
/// which never reach the anchor's own full-pattern address.
pub fn index_addr(h: [u32; 3]) -> Coord {
    [h[0], h[1], h[2], h[0], h[1], h[2], h[0], h[1], h[2]]
}

/// Every scroll whose address starts with `prefix`, in ascending
/// (coordinate) order — the range read of a run or a homeland.
pub fn prefix_scrolls<'a>(px: &'a Phext, prefix: &[u32]) -> Vec<(Coord, &'a String)> {
    px.scrolls
        .iter()
        .filter(|(c, _)| c[..prefix.len()] == *prefix)
        .map(|(c, t)| (*c, t))
        .collect()
}

/// Distinct values of component `idx` among scrolls under
/// `prefix`, sorted — e.g. the Books present in a cluster.
pub fn component_values(px: &Phext, prefix: &[u32], idx: usize) -> Vec<u32> {
    let mut out: Vec<u32> = prefix_scrolls(px, prefix).iter().map(|(c, _)| c[idx]).collect();
    out.sort_unstable();
    out.dedup();
    out
}

/// The next free Book (>= start) in the cluster addressed by
/// [Library, Shelf, Series, Collection, Volume]: the adjacency
/// rule — a new record goes beside its kin, at the end of the
/// family's local run.
pub fn next_free_book(px: &Phext, first5: [u32; 5], start: u32) -> u32 {
    let used = component_values(px, &first5, 5);
    let mut b = start.max(1);
    while used.contains(&b) {
        b += 1;
    }
    b
}

/// The next free Collection (>= start) in a homeland: a new
/// entity cluster beside the existing ones. A cluster counts as
/// used when anything lives under [homeland, cluster, Volume 1]
/// — records and their runs all sit at Volume 1, while the
/// homeland's anchor scroll (at the full-pattern address, whose
/// Volume is the homeland digit) never masquerades as a record
/// cluster.
pub fn next_free_cluster(px: &Phext, h: [u32; 3], start: u32) -> u32 {
    let mut c = start.max(1);
    loop {
        if prefix_scrolls(px, &[h[0], h[1], h[2], c, 1]).is_empty() {
            return c;
        }
        c += 1;
    }
}

/// The next free Scroll (>= start) in the run addressed by the
/// first eight components.
pub fn next_free_scroll(px: &Phext, first8: [u32; 8], start: u32) -> Coord {
    let mut s = start.max(1);
    loop {
        let c: Coord = [first8[0], first8[1], first8[2], first8[3], first8[4], first8[5], first8[6], first8[7], s];
        if !px.scrolls.contains_key(&c) {
            return c;
        }
        s += 1;
    }
}

// ----------------------------------------------------------------
// Record fields: plain text lines inside one scroll.
// ----------------------------------------------------------------

/// Read `key` from a record scroll's `key: value` lines.
pub fn field(text: &str, key: &str) -> Option<String> {
    let prefix = format!("{}:", key);
    for line in text.lines() {
        if let Some(rest) = line.trim_start().strip_prefix(&prefix) {
            return Some(rest.trim().to_string());
        }
    }
    None
}

/// Set `key` in a record scroll: replace its line if present,
/// append it if not. Edits the scroll in place, as Layer 2 asks.
pub fn set_field(text: &str, key: &str, value: &str) -> String {
    let prefix = format!("{}:", key);
    let mut out: Vec<String> = Vec::new();
    let mut done = false;
    for line in text.lines() {
        if !done && line.trim_start().starts_with(&prefix) {
            out.push(format!("{}: {}", key, value));
            done = true;
        } else {
            out.push(line.to_string());
        }
    }
    if !done {
        out.push(format!("{}: {}", key, value));
    }
    let mut s = out.join("\n");
    s.push('\n');
    s
}

/// Build a record scroll from field lines.
pub fn record(fields: &[(&str, &str)]) -> String {
    let mut s = String::new();
    for (k, v) in fields {
        s.push_str(&format!("{}: {}\n", k, v));
    }
    s
}

/// (v1.4.1: the fp_short helper is gone. Will's ruling from the
/// v1.4.0 field test — "public keys shouldn't be shortened" —
/// fingerprints print in full, all 40 hex characters, everywhere
/// a human reads them. Callers use the fingerprint itself.)

// ----------------------------------------------------------------
// Record enumeration (truth lives in the records; doctor and the
// index regenerator share this scan)
// ----------------------------------------------------------------

pub struct RecordRef {
    pub kind: &'static str,
    pub name: String,
    pub coord: Coord,
    pub status: String,
}

/// Enumerate peer, persona, and session records across the
/// homelands, in address order.
pub fn records(px: &Phext) -> Vec<RecordRef> {
    let mut out = Vec::new();
    for c in component_values(px, &HL_PEERS, 3) {
        if c < 2 {
            continue;
        }
        let addr = at(HL_PEERS, [c, 1, 1, 1, 1, 1]);
        if let Some(t) = px.get(&addr) {
            out.push(RecordRef {
                kind: "peer",
                name: field(t, "name").unwrap_or_default(),
                coord: addr,
                status: field(t, "status").unwrap_or_default(),
            });
        }
    }
    for c in component_values(px, &HL_PERSONAS, 3) {
        if c < 2 {
            continue;
        }
        let addr = at(HL_PERSONAS, [c, 1, 1, 1, 1, 1]);
        if let Some(t) = px.get(&addr) {
            out.push(RecordRef {
                kind: "persona",
                name: field(t, "name").unwrap_or_default(),
                coord: addr,
                status: field(t, "status").unwrap_or_default(),
            });
        }
    }
    for b in component_values(px, &[7, 7, 7, MAIL_SESSIONS_C, 1], 5) {
        let addr = at(HL_MAIL, [MAIL_SESSIONS_C, 1, b, 1, 1, 1]);
        if let Some(t) = px.get(&addr) {
            out.push(RecordRef {
                kind: "session",
                name: field(t, "persona").unwrap_or_default(),
                coord: addr,
                status: field(t, "status").unwrap_or_default(),
            });
        }
    }
    out
}

// ----------------------------------------------------------------
// Index regeneration: derived prose, rebuilt from the records.
// ----------------------------------------------------------------

fn count_cluster_books(px: &Phext, first5: [u32; 5]) -> usize {
    component_values(px, &first5, 5).len()
}

/// Regenerate the home index and every homeland index scroll from
/// the records present. Called by config at birth, by commands
/// after every mutation, and by `doctor --fix` as its repair.
pub fn regen_indexes(px: &mut Phext) {
    let recs = records(px);
    let peers: Vec<&RecordRef> = recs.iter().filter(|r| r.kind == "peer").collect();
    let personas: Vec<&RecordRef> = recs.iter().filter(|r| r.kind == "persona").collect();
    let sessions: Vec<&RecordRef> = recs.iter().filter(|r| r.kind == "session" && r.status == "open").collect();

    // ---- keys & trust index ----
    let mut keys = String::new();
    keys.push_str("keys & trust — homeland anchor 2.2.2/2.2.2/2.2.2\n\n");
    keys.push_str("Two parties, a key between them: the node's own key first,\nthen persona keys, peer keys, grants, delegations, and policy,\nas neighboring runs.\n\n");
    if let Some(t) = px.get(&NODE_KEY_RECORD) {
        keys.push_str(&format!(
            "- node key {} — fingerprint {} — status {}\n",
            crate::phext::fmt_coord(&NODE_KEY_RECORD),
            field(t, "fingerprint").unwrap_or_default(),
            field(t, "status").unwrap_or_default()
        ));
    } else {
        keys.push_str("- node key: not generated yet\n");
    }
    for (c, label) in [
        (KEYS_PERSONA_C, "persona key"),
        (KEYS_PEER_C, "peer key"),
        (KEYS_GRANTS_C, "grant"),
        (KEYS_DELEGATIONS_C, "delegation"),
    ] {
        for b in component_values(px, &[2, 2, 2, c, 1], 5) {
            let addr = at(HL_KEYS, [c, 1, b, 1, 1, 1]);
            if let Some(t) = px.get(&addr) {
                keys.push_str(&format!(
                    "- {} {} — {} {}\n",
                    label,
                    crate::phext::fmt_coord(&addr),
                    field(t, "name").or_else(|| field(t, "persona")).or_else(|| field(t, "peer")).unwrap_or_default(),
                    field(t, "fingerprint").map(|f| format!("fingerprint {}", f)).unwrap_or_default()
                ));
            }
        }
    }
    let policy_rules = prefix_scrolls(px, &[2, 2, 2, KEYS_POLICY_C, 1, 1, 1, 1]).len();
    keys.push_str(&format!(
        "- policy: {} rule scroll(s) in the run from {}\n",
        policy_rules,
        crate::phext::fmt_coord(&at(HL_KEYS, [KEYS_POLICY_C, 1, 1, 1, 1, 1]))
    ));
    px.insert(index_addr(HL_KEYS), keys);

    // ---- peers index ----
    let mut peers_txt = String::new();
    peers_txt.push_str("peers — homeland anchor 3.3.3/3.3.3/3.3.3\n\n");
    peers_txt.push_str("Three-way handshake country: one cluster per registered peer,\nits record first and its armored public key beside it.\n\n");
    if peers.is_empty() {
        peers_txt.push_str("no peers registered yet — qexo register <pubkey> adds one.\n");
    }
    for r in &peers {
        peers_txt.push_str(&format!("- {} — {} — status {}\n", r.name, crate::phext::fmt_coord(&r.coord), r.status));
    }
    px.insert(index_addr(HL_PEERS), peers_txt);

    // ---- personas index ----
    let mut per = String::new();
    per.push_str("personas — homeland anchor 4.4.4/4.4.4/4.4.4\n\n");
    per.push_str("One cluster per persona: record, boot text as an adjacent\nscroll run, live state, and transcript.\n\n");
    if personas.is_empty() {
        per.push_str("no personas yet — qexo host <persona> brings one home.\n");
    }
    for r in &personas {
        per.push_str(&format!("- {} — {} — status {}\n", r.name, crate::phext::fmt_coord(&r.coord), r.status));
    }
    px.insert(index_addr(HL_PERSONAS), per);

    // ---- plan index ----
    let mut plan_txt = String::new();
    plan_txt.push_str("plan — homeland anchor 5.5.5/5.5.5/5.5.5\n\n");
    if let Some(t) = px.get(&PLAN_CURRENT) {
        plan_txt.push_str(&format!(
            "current plan: {} (rendering beside it, at {})\n",
            crate::phext::fmt_coord(&PLAN_CURRENT),
            crate::phext::fmt_coord(&PLAN_CURRENT_RENDER)
        ));
        plan_txt.push_str(&format!(
            "emitted: {}\ndisk gate: {}\nopen tasks: {}\n",
            field(t, "emitted").unwrap_or_default(),
            field(t, "disk gate").unwrap_or_default(),
            field(t, "open tasks").unwrap_or_default()
        ));
    } else {
        plan_txt.push_str("no plan emitted yet — bare qexo computes the first.\n");
    }
    plan_txt.push_str(&format!(
        "history: {} emitted plan(s) in the run from {}\n",
        count_cluster_books(px, [5, 5, 5, PLAN_HISTORY_C, 1]),
        crate::phext::fmt_coord(&at(HL_PLAN, [PLAN_HISTORY_C, 1, 1, 1, 1, 1]))
    ));
    px.insert(index_addr(HL_PLAN), plan_txt);

    // ---- ledgers index ----
    let mut led = String::new();
    led.push_str("ledgers & receipts — homeland anchor 6.6.6/6.6.6/6.6.6\n\nThe beast keeps the books: each kind its own run of entry\nscrolls, appended beside its kin.\n\n");
    for c in [LEDGER_RECEIPTS, LEDGER_TELEPORTS, LEDGER_INSTANCES, LEDGER_EMOTION, LEDGER_GOAL_ACTIVITY, LEDGER_SYNC, LEDGER_RELEASES] {
        led.push_str(&format!(
            "- {}: {} entr(ies) from {}\n",
            ledger_kind_name(c).unwrap_or("?"),
            count_cluster_books(px, [6, 6, 6, c, 1]),
            crate::phext::fmt_coord(&at(HL_LEDGERS, [c, 1, 1, 1, 1, 1]))
        ));
    }
    px.insert(index_addr(HL_LEDGERS), led);

    // ---- mailbox & sessions index ----
    let mut mail = String::new();
    mail.push_str("mailbox & sessions — homeland anchor 7.7.7/7.7.7/7.7.7\n\n");
    if sessions.is_empty() {
        mail.push_str("hosted now: none.\n");
    }
    for r in &sessions {
        mail.push_str(&format!("- hosted: {} — session {} — status {}\n", r.name, crate::phext::fmt_coord(&r.coord), r.status));
    }
    mail.push_str(&format!(
        "mailbox: {} message scroll(s) in the run from {}\n",
        count_cluster_books(px, [7, 7, 7, MAIL_BOX_C, 1]),
        crate::phext::fmt_coord(&at(HL_MAIL, [MAIL_BOX_C, 1, 1, 1, 1, 1]))
    ));
    px.insert(index_addr(HL_MAIL), mail);

    // ---- telemetry index ----
    let obs = component_values(px, &[8, 8, 8, TELEM_DISK_C, 1], 5);
    let mut tel = String::new();
    tel.push_str("telemetry & forecasts — homeland anchor 8.8.8/8.8.8/8.8.8\n\nSignals country: disk observations as a run of scrolls; the\nforecast gate reads the last two, as it always has.\n\n");
    tel.push_str(&format!("disk observations: {}\n", obs.len()));
    if let Some(last) = obs.last() {
        let addr = at(HL_TELEMETRY, [TELEM_DISK_C, 1, *last, 1, 1, 1]);
        if let Some(t) = px.get(&addr) {
            tel.push_str(&format!(
                "latest: {} — day {}, {} GB, {} files\n",
                crate::phext::fmt_coord(&addr),
                field(t, "day").unwrap_or_default(),
                field(t, "used_gb").unwrap_or_default(),
                field(t, "files").unwrap_or_default()
            ));
        }
    }
    px.insert(index_addr(HL_TELEMETRY), tel);

    // ---- config & wiring index ----
    let mut cfg = String::new();
    cfg.push_str("config & wiring — homeland anchor 9.9.9/9.9.9/9.9.9\n\nThe far corner is the machine room: qexo's own settings live\nin the config record here, as field lines — there is no config\nfile anywhere else. The wiring registry (one scroll per module)\nfollows it.\n\n");
    if px.get(&CONFIG_RECORD).is_some() {
        cfg.push_str(&format!("config record: {}\n", crate::phext::fmt_coord(&CONFIG_RECORD)));
    } else {
        cfg.push_str("config record: not written yet\n");
    }
    px.insert(index_addr(HL_CONFIG), cfg);

    // ---- lessons & learning index ----
    let card_books = component_values(px, &[10, 10, 10, LEARN_DECK_C, 1], 5);
    let mut lrn = String::new();
    lrn.push_str("lessons & learning — homeland anchor 10.10.10/10.10.10/10.10.10\n\n");
    lrn.push_str("The tens: practice, repeated. The curriculum deck lives\nin the run beside this index — one scroll per card, front\nand back as field lines, the scheduling fields (due,\ninterval_days, ease, reps, lapses) updated in place by\n`qexo learn` as the operator practices.\n\n");
    lrn.push_str(&format!("cards: {}\n", card_books.len()));
    for b in &card_books {
        let addr = at(HL_LEARN, [LEARN_DECK_C, 1, *b, 1, 1, 1]);
        if let Some(t) = px.get(&addr) {
            lrn.push_str(&format!(
                "- {} — {}\n",
                field(t, "id").unwrap_or_default(),
                crate::phext::fmt_coord(&addr)
            ));
        }
    }
    px.insert(index_addr(HL_LEARN), lrn);

    // ---- home index (written last: it summarizes the rest) ----
    let id = px.get(&IDENTITY);
    let (node_line, born_line) = match id {
        Some(t) => (
            format!(
                "{} ({})",
                field(t, "name").unwrap_or_else(|| "unnamed".into()),
                field(t, "node").unwrap_or_default()
            ),
            field(t, "born").unwrap_or_default(),
        ),
        None => ("(not born)".to_string(), String::new()),
    };
    let mut home = String::new();
    home.push_str("qexo state — one address space\n\n");
    home.push_str("This file is the node's whole state: every scrap of it —\nmetadata, keys, grants, personas, plan, ledgers, sessions —\nas scrolls in one phext, addressed by meaning (Layer 2).\nAddresses are places; this scroll is the map, and the code\nkeeps it current. Records are truth; indexes are derived\nprose, rebuilt from the records by `qexo doctor --fix`.\n\n");
    home.push_str(&format!("node: {}\nborn: {}\nidentity: {}\n\n", node_line, born_line, crate::phext::fmt_coord(&IDENTITY)));
    home.push_str("Homelands:\n");
    home.push_str(&format!(
        "1.1.1/1.1.1/1.1.1 — this index; node identity beside it at {}\n",
        crate::phext::fmt_coord(&IDENTITY)
    ));
    home.push_str(&format!(
        "{} — keys & trust: node key {}, {} record(s) in the neighboring runs\n",
        crate::phext::fmt_coord(&index_addr(HL_KEYS)),
        px.get(&NODE_KEY_RECORD)
            .and_then(|t| field(t, "fingerprint"))
            .unwrap_or_else(|| "none".into()),
        count_cluster_books(px, [2, 2, 2, KEYS_PERSONA_C, 1])
            + count_cluster_books(px, [2, 2, 2, KEYS_PEER_C, 1])
            + count_cluster_books(px, [2, 2, 2, KEYS_GRANTS_C, 1])
            + count_cluster_books(px, [2, 2, 2, KEYS_DELEGATIONS_C, 1])
    ));
    home.push_str(&format!(
        "{} — peers: {} registered\n",
        crate::phext::fmt_coord(&index_addr(HL_PEERS)),
        peers.len()
    ));
    home.push_str(&format!(
        "{} — personas: {}\n",
        crate::phext::fmt_coord(&index_addr(HL_PERSONAS)),
        if personas.is_empty() {
            "none yet".to_string()
        } else {
            personas.iter().map(|r| r.name.clone()).collect::<Vec<_>>().join(", ")
        }
    ));
    home.push_str(&format!(
        "{} — plan: {}\n",
        crate::phext::fmt_coord(&index_addr(HL_PLAN)),
        if px.get(&PLAN_CURRENT).is_some() { "current plan present" } else { "no plan yet" }
    ));
    let ledger_total: usize = [LEDGER_RECEIPTS, LEDGER_TELEPORTS, LEDGER_INSTANCES, LEDGER_EMOTION, LEDGER_GOAL_ACTIVITY, LEDGER_SYNC, LEDGER_RELEASES]
        .iter()
        .map(|c| count_cluster_books(px, [6, 6, 6, *c, 1]))
        .sum();
    home.push_str(&format!(
        "{} — ledgers & receipts: {} entr(ies) across all kinds\n",
        crate::phext::fmt_coord(&index_addr(HL_LEDGERS)),
        ledger_total
    ));
    home.push_str(&format!(
        "{} — mailbox & sessions: {} hosted now\n",
        crate::phext::fmt_coord(&index_addr(HL_MAIL)),
        sessions.len()
    ));
    home.push_str(&format!(
        "{} — telemetry & forecasts: {} disk observation(s)\n",
        crate::phext::fmt_coord(&index_addr(HL_TELEMETRY)),
        obs.len()
    ));
    home.push_str(&format!(
        "{} — config & wiring: the machine room\n",
        crate::phext::fmt_coord(&index_addr(HL_CONFIG))
    ));
    home.push_str(&format!(
        "{} — lessons & learning: {} card(s) in the deck\n",
        crate::phext::fmt_coord(&index_addr(HL_LEARN)),
        card_books.len()
    ));
    px.insert(HOME, home);
}

/// Every index scroll the current Layer 2 layout defines: the
/// home index plus each homeland's anchor scroll, the tens
/// included. This is the whole set a state must carry to be
/// whole under the running binary's layout.
pub fn index_addresses() -> Vec<Coord> {
    let mut out = vec![HOME];
    for h in [HL_KEYS, HL_PEERS, HL_PERSONAS, HL_PLAN, HL_LEDGERS, HL_MAIL, HL_TELEMETRY, HL_CONFIG, HL_LEARN] {
        out.push(index_addr(h));
    }
    out
}

/// The state top-up (v1.4.1): seed any index scroll the current
/// layout defines that this document lacks, with exactly the
/// text `regen_indexes` would give it. Born of the v1.4.0 fleet
/// refusal: states born under 1.3.0 carry no lessons homeland,
/// so the new layout's index is missing through no damage of
/// theirs — an upgraded state becomes whole by the running
/// binary's own hand the first time it writes. Surgical by
/// construction: an index that EXISTS is never touched (records
/// and indexes alike), a missing one is copied from a scratch
/// regeneration of this same document. Idempotent — a whole
/// state seeds nothing. Returns the addresses seeded.
pub fn seed_missing_indexes(px: &mut Phext) -> Vec<Coord> {
    let missing: Vec<Coord> = index_addresses().into_iter().filter(|a| px.get(a).is_none()).collect();
    if missing.is_empty() {
        return Vec::new();
    }
    let mut scratch = px.clone();
    regen_indexes(&mut scratch);
    let mut seeded = Vec::new();
    for a in missing {
        if let Some(t) = scratch.get(&a) {
            px.insert(a, t.clone());
            seeded.push(a);
        }
    }
    seeded
}

/// The system state path: /var/lib/qexo/state.phext — canonical
/// for system installs (root-run services, the ranch fleet).
pub fn system_state_path() -> PathBuf {
    PathBuf::from("/var/lib/qexo/state.phext")
}

/// The per-user state path (v1.4.0): $HOME/.qexo/state.phext —
/// on Windows, under the user profile (%USERPROFILE%, falling
/// back to HOME), resolved the same cfg way the codebase splits
/// platforms elsewhere. A node installed by an unprivileged user
/// (a plain `cargo install qexo`) lives here, whole: state file
/// and GPG keyring side by side, no sudo anywhere in its life.
pub fn user_state_path() -> Option<PathBuf> {
    user_home().map(|h| h.join(".qexo").join("state.phext"))
}

fn user_home() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        if let Some(p) = std::env::var_os("USERPROFILE").filter(|v| !v.is_empty()) {
            return Some(PathBuf::from(p));
        }
    }
    std::env::var_os("HOME").filter(|v| !v.is_empty()).map(PathBuf::from)
}

/// The facts the resolution order reads. Probed from the live
/// system by `state_path`; supplied directly by tests.
#[derive(Clone, Copy, Debug, Default)]
pub struct StateFacts {
    /// The system state file exists.
    pub system_exists: bool,
    /// The system state file can be opened for reading by this
    /// process (only meaningful when it exists).
    pub system_readable: bool,
    /// The system state file can be opened for writing by this
    /// process (only meaningful when it exists). Probed with an
    /// append-open, which grants or refuses on the file's own
    /// permissions without altering a byte.
    pub system_writable: bool,
    /// The per-user state file exists.
    pub user_exists: bool,
    /// This process runs privileged (effective uid 0 on Unix;
    /// never assumed on Windows).
    pub privileged: bool,
    /// The running verb intends to WRITE state (v1.4.1): set by
    /// main() from the parsed command — see `set_write_intent`.
    pub write_intent: bool,
    /// The running verb is `qexo learn` (v1.4.2): set by main()
    /// — see `set_learn_preference`.
    pub learn_pref: bool,
}

/// The process's intent, declared once by main() before any
/// state is touched: some verbs only read the node (list,
/// status, doctor's check pass, the --check modes), and the
/// rest write it (config, register, learn, plan, the apply
/// modes, doctor --fix). Resolution is intent-aware (v1.4.1)
/// because existence-plus-readability is the wrong test for a
/// verb that will write: it handed a standard user the
/// fleet's root-owned state to read, and the first write —
/// qexo learn saving a graded card — died on permissions.
static WRITE_INTENT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

pub fn set_write_intent() {
    WRITE_INTENT.store(true, std::sync::atomic::Ordering::Relaxed);
}

pub fn write_intent() -> bool {
    WRITE_INTENT.load(std::sync::atomic::Ordering::Relaxed)
}

/// The learn preference (v1.4.2): the deck is the operator's
/// OWN — when a per-user state exists, `qexo learn` reads and
/// writes it in preference to the system state, because
/// practice is personal even on a shared machine. v1.4.1
/// classified both learn forms as write-intending, which made
/// `learn --status` on a machine with a readable system state
/// but NO per-user state yet divert to the missing per-user
/// path and error "not born" — where v1.4.0 answered from the
/// readable deck. The preference therefore applies only when
/// a per-user state EXISTS; with none, learn falls through to
/// the shipped order and answers.
static LEARN_PREF: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

pub fn set_learn_preference() {
    LEARN_PREF.store(true, std::sync::atomic::Ordering::Relaxed);
}

pub fn learn_preference() -> bool {
    LEARN_PREF.load(std::sync::atomic::Ordering::Relaxed)
}

/// The resolution order (v1.4.1), stated exactly as shipped:
///   1. QEXO_STATE, when set non-empty (the caller's word).
///   2. THE WRITE-INTENT RULE (new in v1.4.1): a write-intending
///      verb in unprivileged hands, facing a system state it
///      cannot write, selects the per-user path instead —
///      existing or to be born there by config. The system
///      state belongs to its owner; this user's node is their
///      own. (Read-only verbs are untouched by this rule and
///      keep the order below exactly as v1.4.0 shipped it.)
///   2b. THE LEARN RULE (new in v1.4.2): `qexo learn` in
///      unprivileged hands, when a per-user state EXISTS,
///      selects the per-user path — the deck belongs to the
///      operator, not to the machine's owner. With no
///      per-user state, learn falls through to the order
///      below like any reader (v1.4.1 diverted it to the
///      missing path and errored; v1.4.0 answered).
///   3. The system path, when the system state exists and this
///      process can read it — a system install stays canonical,
///      byte-for-byte, and read-only verbs never fail on its
///      permissions when a per-user state exists instead (rule 4
///      is what they fall to).
///   4. The per-user path, when a per-user state exists.
///   5. The system path again when it exists but cannot be read
///      and no per-user state exists — the honest error names
///      the real file rather than inventing an empty node.
///   6. Nothing exists: the system path for a privileged
///      process, the per-user path otherwise (a fresh
///      `qexo config` as a normal user births a per-user node);
///      with no home directory to anchor to, the system path.
/// A node has ONE state: the resolution finds the first that
/// exists, and `qexo status` names which path is live.
pub fn pick_state_path(facts: StateFacts, system: &std::path::Path, user: Option<&std::path::Path>) -> PathBuf {
    if facts.write_intent && !facts.privileged && facts.system_exists && !facts.system_writable {
        if let Some(u) = user {
            return u.to_path_buf();
        }
    }
    if facts.learn_pref && !facts.privileged && facts.user_exists {
        if let Some(u) = user {
            return u.to_path_buf();
        }
    }
    if facts.system_exists && facts.system_readable {
        return system.to_path_buf();
    }
    if facts.user_exists {
        if let Some(u) = user {
            return u.to_path_buf();
        }
    }
    if facts.system_exists {
        return system.to_path_buf();
    }
    if facts.privileged {
        return system.to_path_buf();
    }
    match user {
        Some(u) => u.to_path_buf(),
        None => system.to_path_buf(),
    }
}

/// Effective-uid-0 probe. Linux/Android read /proc/self/status;
/// other Unix falls back to USER=root; Windows never assumes
/// privilege (an elevated install names its state explicitly —
/// QEXO_STATE or a pre-created system file, both of which the
/// resolution honors before this probe matters).
#[cfg(unix)]
fn is_privileged() -> bool {
    if let Ok(s) = std::fs::read_to_string("/proc/self/status") {
        for line in s.lines() {
            if let Some(rest) = line.strip_prefix("Uid:") {
                let f: Vec<&str> = rest.split_whitespace().collect();
                if f.len() >= 2 {
                    return f[1] == "0";
                }
            }
        }
    }
    std::env::var("USER").map(|u| u == "root").unwrap_or(false)
}

#[cfg(not(unix))]
fn is_privileged() -> bool {
    false
}

fn probe_facts(user: &Option<PathBuf>) -> StateFacts {
    let system = system_state_path();
    let system_exists = system.exists();
    StateFacts {
        system_exists,
        system_readable: system_exists && std::fs::File::open(&system).is_ok(),
        // Append-open: asks the file's own permissions whether
        // this process may write, without altering a byte and
        // without creating anything (no create flag).
        system_writable: system_exists
            && std::fs::OpenOptions::new().append(true).open(&system).is_ok(),
        user_exists: user.as_ref().map(|u| u.exists()).unwrap_or(false),
        privileged: is_privileged(),
        write_intent: write_intent(),
        learn_pref: learn_preference(),
    }
}

/// The node's state path, resolved by the order above.
pub fn state_path() -> PathBuf {
    match std::env::var("QEXO_STATE") {
        Ok(p) if !p.is_empty() => PathBuf::from(p),
        _ => {
            let user = user_state_path();
            pick_state_path(probe_facts(&user), &system_state_path(), user.as_deref())
        }
    }
}

/// The path a birth should use, with the fallback applied: when
/// resolution chose the system path for a state that does not
/// exist yet and the system directory cannot be created by this
/// user, the birth falls back to the per-user path — returned as
/// (path, fell_back) so the caller can say so out loud, the way
/// the Android home fallback always has. An env-chosen path is
/// the operator's word and is never second-guessed.
pub fn birth_path() -> (PathBuf, bool) {
    let p = state_path();
    let env_chosen = std::env::var("QEXO_STATE").map(|v| !v.is_empty()).unwrap_or(false);
    if !env_chosen && p == system_state_path() && !p.exists() {
        let dir = p.parent().unwrap_or(std::path::Path::new("/var/lib/qexo"));
        // Reachable means: the directory can be created AND a
        // file can actually be written in it. (create_dir_all
        // alone succeeds on an existing read-only directory —
        // the parked-root-dir case — and a birth that lands
        // there would die at its first save.)
        let reachable = std::fs::create_dir_all(dir).is_ok() && probe_writable(dir);
        if !reachable {
            if let Some(u) = user_state_path() {
                if let Some(parent) = u.parent() {
                    let _ = std::fs::create_dir_all(parent);
                }
                return (u, true);
            }
        }
    }
    (p, false)
}

/// Can this process actually write a file in `dir`? Probed with
/// a create-and-remove, the only honest test.
fn probe_writable(dir: &std::path::Path) -> bool {
    let probe = dir.join(".qexo-write-probe");
    match std::fs::File::create(&probe) {
        Ok(_) => {
            let _ = std::fs::remove_file(&probe);
            true
        }
        Err(_) => false,
    }
}

/// The directory holding the state file (and the GPG keyring, which
/// is the gpg tool's own machinery and lives beside the file it
/// serves).
pub fn state_dir() -> PathBuf {
    state_path()
        .parent()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| PathBuf::from("/var/lib/qexo"))
}

/// The loaded state document. All reads and writes of node state go
/// through this type; no other module touches the file directly.
pub struct Lattice {
    pub px: Phext,
    path: PathBuf,
}

impl Lattice {
    /// An unborn state document bound to `path` (config's birth).
    pub fn born(path: PathBuf) -> Lattice {
        Lattice { px: Phext::new(), path }
    }

    /// Load the state file if it exists. Ok(None) = not born yet
    /// (no file): callers treat that as "run config", never as an
    /// occasion to invent a substitute store.
    pub fn load() -> Result<Option<Lattice>, String> {
        Self::load_from(&state_path())
    }

    /// Load from an explicit path (tests, doctor).
    pub fn load_from(path: &PathBuf) -> Result<Option<Lattice>, String> {
        if !path.exists() {
            return Ok(None);
        }
        let text = std::fs::read_to_string(path)
            .map_err(|e| format!("{}: {}", path.display(), e))?;
        Ok(Some(Lattice { px: Phext::parse(&text), path: path.clone() }))
    }

    pub fn path(&self) -> &PathBuf {
        &self.path
    }

    /// Persist the whole document. Phext serializes canonically
    /// (ascending coordinates, delimiter ladder), so a save is a
    /// rewrite of one file — the format's write model, accepted.
    ///
    /// Every save first runs the state top-up (v1.4.1):
    /// `seed_missing_indexes` makes the document whole under
    /// the running binary's Layer 2 layout before it is written.
    /// save() is the write boundary — every mutating verb ends
    /// here, and no read or --check path ever reaches it (their
    /// byte-inert guarantees are untouched) — so an inherited
    /// state gains the homelands its birth binary predates on
    /// the first write the new binary makes, whichever verb
    /// that write belongs to.
    pub fn save(&mut self) -> Result<(), String> {
        seed_missing_indexes(&mut self.px);
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("{}: {}", parent.display(), e))?;
        }
        std::fs::write(&self.path, self.px.serialize())
            .map_err(|e| format!("{}: {}", self.path.display(), e))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn save_load_roundtrip() {
        let dir = std::env::temp_dir().join(format!("qexo-lattice-test-{}", std::process::id()));
        let path = dir.join("state.phext");
        let mut px = Phext::new();
        px.insert(HOME, "home".to_string());
        px.insert(IDENTITY, "second".to_string());
        let mut lat = Lattice { px, path: path.clone() };
        lat.save().unwrap();
        let back = Lattice::load_from(&path).unwrap().expect("state exists");
        assert_eq!(back.px.scrolls, lat.px.scrolls);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn missing_file_is_none_not_error() {
        let path = std::env::temp_dir().join("qexo-lattice-definitely-absent-xyz/state.phext");
        assert!(Lattice::load_from(&path).unwrap().is_none());
    }

    #[test]
    fn fields_roundtrip_and_edit_in_place() {
        let t = record(&[("kind", "peer"), ("name", "peer-1"), ("status", "registered")]);
        assert_eq!(field(&t, "name").as_deref(), Some("peer-1"));
        let t2 = set_field(&t, "status", "retired");
        assert_eq!(field(&t2, "status").as_deref(), Some("retired"));
        assert_eq!(field(&t2, "name").as_deref(), Some("peer-1"));
        let t3 = set_field(&t2, "closed", "later");
        assert_eq!(field(&t3, "closed").as_deref(), Some("later"));
    }

    #[test]
    fn adjacency_helpers_find_next_free() {
        let mut px = Phext::new();
        px.insert(at(HL_PEERS, [2, 1, 1, 1, 1, 1]), "a".into());
        px.insert(at(HL_PEERS, [3, 1, 1, 1, 1, 1]), "b".into());
        assert_eq!(next_free_cluster(&px, HL_PEERS, 2), 4);
        px.insert(at(HL_LEDGERS, [LEDGER_RECEIPTS, 1, 1, 1, 1, 1]), "r1".into());
        px.insert(at(HL_LEDGERS, [LEDGER_RECEIPTS, 1, 2, 1, 1, 1]), "r2".into());
        assert_eq!(next_free_book(&px, [6, 6, 6, LEDGER_RECEIPTS, 1], 1), 3);
        let run8 = [3, 3, 3, 2, 1, 1, 1, 1];
        px.insert([3, 3, 3, 2, 1, 1, 1, 1, 1], "x".into());
        assert_eq!(next_free_scroll(&px, run8, 1), [3, 3, 3, 2, 1, 1, 1, 1, 2]);
    }

    #[test]
    fn indexes_regenerate_from_records() {
        let mut px = Phext::new();
        px.insert(IDENTITY, record(&[("name", "Test Node"), ("node", "testbox"), ("born", "now")]));
        px.insert(at(HL_PEERS, [2, 1, 1, 1, 1, 1]), record(&[("kind", "peer"), ("name", "peer-ABCD"), ("fingerprint", "FF".repeat(20).as_str()), ("status", "registered")]));
        regen_indexes(&mut px);
        let home = px.get(&HOME).expect("home index written");
        assert!(home.contains("3.3.3/3.3.3/3.3.3 — peers"), "{}", home);
        assert!(!home.contains("/…"), "no partial addresses anywhere: {}", home);
        // the peers index lives at the homeland's full 9D anchor
        assert!(px.get(&[3, 3, 3, 3, 3, 3, 3, 3, 3]).is_some());
        assert_eq!(index_addr(HL_PEERS), [3, 3, 3, 3, 3, 3, 3, 3, 3]);
        assert_eq!(index_addr(HL_KEYS), [2, 2, 2, 2, 2, 2, 2, 2, 2]);
        assert_eq!(index_addr(HL_CONFIG), [9, 9, 9, 9, 9, 9, 9, 9, 9]);
        assert_eq!(index_addr(HL_HOME), HOME);
        assert!(home.contains("1 registered"), "{}", home);
        let peers_idx = px.get(&index_addr(HL_PEERS)).expect("peers index");
        assert!(peers_idx.contains("peer-ABCD"), "{}", peers_idx);
        assert!(peers_idx.contains("3.3.3/2.1.1/1.1.1"), "{}", peers_idx);
        // idempotent: regenerating again changes nothing
        let before = px.serialize();
        regen_indexes(&mut px);
        assert_eq!(px.serialize(), before);
    }

    // ---- state resolution (v1.4.0) ----

    fn facts(se: bool, sr: bool, ue: bool, priv_: bool) -> StateFacts {
        // read intent (v1.4.0's rows): writability is not probed
        // into the decision, so its value here is inert.
        StateFacts { system_exists: se, system_readable: sr, system_writable: true, user_exists: ue, privileged: priv_, write_intent: false, learn_pref: false }
    }

    fn facts_w(se: bool, sr: bool, sw: bool, ue: bool, priv_: bool) -> StateFacts {
        StateFacts { system_exists: se, system_readable: sr, system_writable: sw, user_exists: ue, privileged: priv_, write_intent: true, learn_pref: false }
    }

    fn facts_learn(se: bool, sr: bool, ue: bool, priv_: bool) -> StateFacts {
        // `qexo learn --status`: the learn preference without
        // write intent (a session carries both flags; the
        // preference rows are the same when a deck exists).
        StateFacts { system_exists: se, system_readable: sr, system_writable: true, user_exists: ue, privileged: priv_, write_intent: false, learn_pref: true }
    }

    #[test]
    fn resolution_order_is_the_shipped_order() {
        let sys = std::path::Path::new("/var/lib/qexo/state.phext");
        let usr = std::path::Path::new("/home/op/.qexo/state.phext");
        // system exists + readable: canonical, whoever asks
        assert_eq!(pick_state_path(facts(true, true, true, false), sys, Some(usr)), sys);
        assert_eq!(pick_state_path(facts(true, true, false, true), sys, Some(usr)), sys);
        // system exists but unreadable, per-user state exists:
        // read-only verbs land on the per-user state, never fail
        assert_eq!(pick_state_path(facts(true, false, true, false), sys, Some(usr)), usr);
        // only the per-user state exists
        assert_eq!(pick_state_path(facts(false, false, true, false), sys, Some(usr)), usr);
        // system exists, unreadable, no per-user state: the real
        // file is named (its error will say so), not shadowed
        assert_eq!(pick_state_path(facts(true, false, false, false), sys, Some(usr)), sys);
        // nothing exists: privileged births system, plain users
        // birth per-user; no home at all falls back to system
        assert_eq!(pick_state_path(facts(false, false, false, true), sys, Some(usr)), sys);
        assert_eq!(pick_state_path(facts(false, false, false, false), sys, Some(usr)), usr);
        assert_eq!(pick_state_path(facts(false, false, false, false), sys, None), sys);
    }

    #[test]
    fn resolution_write_intent_never_adopts_an_unwritable_system_state() {
        let sys = std::path::Path::new("/var/lib/qexo/state.phext");
        let usr = std::path::Path::new("/home/op/.qexo/state.phext");
        // THE v1.4.1 DEFECT ROW: system state exists, is readable,
        // is NOT writable by this unprivileged process, and the
        // verb intends to write (learn on a fleet node) — the
        // per-user state is selected, whether or not it exists yet
        assert_eq!(pick_state_path(facts_w(true, true, false, true, false), sys, Some(usr)), usr);
        assert_eq!(pick_state_path(facts_w(true, true, false, false, false), sys, Some(usr)), usr);
        // a system state this user CAN write stays canonical
        assert_eq!(pick_state_path(facts_w(true, true, true, false, false), sys, Some(usr)), sys);
        // root is never diverted (the fleet's behavior is unchanged)
        assert_eq!(pick_state_path(facts_w(true, true, false, true, true), sys, Some(usr)), sys);
        // nothing exists yet: the v1.4.0 birth order is untouched
        assert_eq!(pick_state_path(facts_w(false, false, false, false, false), sys, Some(usr)), usr);
        assert_eq!(pick_state_path(facts_w(false, false, false, false, true), sys, Some(usr)), sys);
        // no home to anchor to: fall through to the honest path
        assert_eq!(pick_state_path(facts_w(true, true, false, false, false), sys, None), sys);
    }

    #[test]
    fn resolution_learn_prefers_an_existing_per_user_deck() {
        let sys = std::path::Path::new("/var/lib/qexo/state.phext");
        let usr = std::path::Path::new("/home/op/.qexo/state.phext");
        // the operator HAS a deck: learn reads it, not the
        // machine owner's — even though the system state is
        // readable (v1.4.0's order showed the owner's deck)
        assert_eq!(pick_state_path(facts_learn(true, true, true, false), sys, Some(usr)), usr);
        // THE v1.4.1 REGRESSION ROW: no per-user state yet —
        // learn falls through to the shipped order and the
        // readable system deck ANSWERS (v1.4.1 diverted to the
        // missing path and errored "not born")
        assert_eq!(pick_state_path(facts_learn(true, true, false, false), sys, Some(usr)), sys);
        // root's learn is root's own: never diverted
        assert_eq!(pick_state_path(facts_learn(true, true, true, true), sys, Some(usr)), sys);
        // nothing anywhere: the birth order decides, as shipped
        assert_eq!(pick_state_path(facts_learn(false, false, false, false), sys, Some(usr)), usr);
    }

    #[test]
    fn topup_seeds_only_what_is_missing() {
        // a document carrying every index but the tens (the
        // 1.3.0-born shape): exactly one seed, and every scroll
        // it already held is byte-identical afterwards
        let mut px = Phext::new();
        px.insert(IDENTITY, record(&[("kind", "identity"), ("node", "topup-test")]));
        regen_indexes(&mut px);
        px.scrolls.remove(&index_addr(HL_LEARN));
        let before = px.clone();
        let seeded = seed_missing_indexes(&mut px);
        assert_eq!(seeded, vec![index_addr(HL_LEARN)]);
        for (a, t) in &before.scrolls {
            assert_eq!(px.get(a), Some(t), "existing scroll at {:?} was touched", a);
        }
        assert!(px.get(&index_addr(HL_LEARN)).is_some());
        // idempotent: a whole state seeds nothing
        assert!(seed_missing_indexes(&mut px).is_empty());
    }

    #[test]
    fn fixture_state_born_under_130_tops_up_on_save() {
        // THE STANDING REGRESSION (v1.4.1): a real state born by
        // the published 1.3.0 binary (tests/fixtures/, generated
        // by that binary's own `qexo config`, never hand-edited)
        // predates the lessons homeland. Loading it and saving —
        // any write verb's ending — must top it up: the learn
        // index appears, doctor's lattice check goes clean, and
        // every scroll the 1.3.0 binary wrote survives untouched.
        let text = include_str!("../tests/fixtures/state-1.3.0.phext");
        let dir = std::env::temp_dir().join(format!("qexo-fixture-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("state.phext");
        std::fs::write(&path, text).unwrap();
        let mut lat = Lattice::load_from(&path).unwrap().expect("fixture loads");
        assert!(lat.px.get(&index_addr(HL_LEARN)).is_none(), "fixture must predate the learn homeland");
        let report = crate::doctor::check_lattice(&lat);
        assert_eq!(report.problems(), 1, "the only complaint is the missing learn index: {}", report.render());
        assert!(report.findings.iter().any(|f| !f.ok && f.fixable && f.item.contains("lessons")), "{}", report.render());
        let before = lat.px.clone();
        lat.save().unwrap();
        let back = Lattice::load_from(&path).unwrap().expect("saved state loads");
        assert!(back.px.get(&index_addr(HL_LEARN)).is_some(), "learn index topped up");
        assert!(crate::doctor::check_lattice(&back).ok(), "doctor clean after the top-up");
        for (a, t) in &before.scrolls {
            assert_eq!(back.px.get(a), Some(t), "predecessor scroll at {:?} was touched", a);
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolution_system_path_is_byte_identical_to_v130() {
        // system installs keep working byte-for-byte: the system
        // path is the same string v1.3.0 used.
        assert_eq!(system_state_path(), PathBuf::from("/var/lib/qexo/state.phext"));
    }

    #[test]
    fn learn_homeland_regenerates_its_index() {
        let mut px = Phext::new();
        px.insert(
            at(HL_LEARN, [LEARN_DECK_C, 1, 1, 1, 1, 1]),
            record(&[("kind", "learn card"), ("id", "verbs-config"), ("front", "f"), ("back", "b"), ("due", "10"), ("interval_days", "1"), ("ease", "2.5"), ("reps", "0"), ("lapses", "0")]),
        );
        regen_indexes(&mut px);
        let idx = px.get(&index_addr(HL_LEARN)).expect("learn index written");
        assert!(idx.contains("10.10.10/10.10.10/10.10.10"), "{}", idx);
        assert!(idx.contains("verbs-config"), "{}", idx);
        assert!(idx.contains("cards: 1"), "{}", idx);
        let home = px.get(&HOME).expect("home index");
        assert!(home.contains("lessons & learning: 1 card(s)"), "{}", home);
        assert_eq!(index_addr(HL_LEARN), [10, 10, 10, 10, 10, 10, 10, 10, 10]);
    }
}