mindfork 0.11.0

A terminal AI chat written in Rust: local models via llama.cpp or OpenAI, Anthropic, Gemini and Grok in the cloud, with persistent memory, notes, RAG and tools.
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
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
//! The agent's "self-model" — a per-profile representation of itself, its goals,
//! and the interlocutor. Lives in SQLite (like notes/RAG), isolated by `profile_id`.
//! A minimal MVP probe: free-form text + goals + a user model, no numeric
//! "belief strengths". See [docs/history/self-model-mvp.md](../../docs/history/self-model-mvp.md).

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::shared::config::{NoteOrder, SelfModelSettings};
use crate::shared::i18n::Locale;

/// Render/storage parameters for the "self-model" (from `config.self_model`). Passed
/// into the entity's methods instead of hardcoded constants, so the user can tune
/// the narrative size and the prompt-injection volume. An analogue of
/// [`ChunkParams`](crate::features::tools::rag::ChunkParams) for RAG.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelfModelParams {
    /// How many recent observations (self-notes) to pull in for a full model read
    /// (`get_self_model`/`reflect`). Observations moved into notes — there's no
    /// longer a FIFO storage cap; the parameter only bounds the read size. The
    /// historical field name is kept for `settings.json` compatibility.
    pub max_narrative: usize,
    /// How many fresh observations go into the system prompt (injection).
    pub narrative_in_prompt: usize,
    /// The character ceiling for rendering the model into the system prompt.
    pub prompt_cap: usize,
    /// How many closed goals to keep in the structure (the oldest beyond this — into
    /// a narrative scar).
    pub max_closed_goals: usize,
    /// A size target for the self-description (summary): beyond it,
    /// [`SelfModel::summary_fill_hint`] returns a soft hint to shorten it. A gate,
    /// not a ceiling.
    pub summary_target_chars: usize,
}

impl Default for SelfModelParams {
    fn default() -> Self {
        Self::from_settings(&SelfModelSettings::default())
    }
}

impl SelfModelParams {
    /// Builds parameters from settings, sanitizing values (protection against
    /// zeros and inconsistency: at least 1 insight is stored, no more goes into the
    /// prompt than is stored, a readable minimum prompt character count).
    pub fn from_settings(s: &SelfModelSettings) -> Self {
        let max_narrative = s.max_narrative.max(1);
        Self {
            max_narrative,
            narrative_in_prompt: s.narrative_in_prompt.min(max_narrative),
            prompt_cap: s.prompt_cap.max(100),
            max_closed_goals: s.max_closed_goals.max(1),
            summary_target_chars: s.summary_target_chars.max(200),
        }
    }
}

/// The agent's representation of itself (one instance per profile).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SelfModel {
    pub profile_id: Uuid,
    /// Grows on every save — a rough indicator of "how much it's changed".
    #[serde(default)]
    pub version: u64,
    /// Free-form "about me" text (who I am, what I value, how I behave).
    #[serde(default)]
    pub summary: String,
    #[serde(default)]
    pub goals: Vec<Goal>,
    #[serde(default)]
    pub user_model: UserModel,
    /// A "self over time" narrative: short insights/observations (including noticed
    /// contradictions — plain prose, no separate type). Append-only with a cap.
    #[serde(default)]
    pub narrative: Vec<NarrativeSegment>,
    pub updated_at: DateTime<Utc>,
}

/// A narrative fragment: a short observation/insight of the agent, timestamped.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NarrativeSegment {
    pub id: Uuid,
    pub text: String,
    pub created_at: DateTime<Utc>,
}

/// Orders observations for **display** (the `F3` screen, spec §17.7) by their
/// own `created_at` — the date each row shows — so the dates read monotonically
/// down the list whichever direction the reader picked. Deliberately not the
/// order the snapshot arrives in: that one is `updated_at`-descending (it is what
/// caps the list by recency, `self_model.max_narrative`), and a revised
/// observation would jump to the top under a date that says otherwise. The sort
/// is stable — segments stamped in the same instant keep the incoming order.
pub fn order_narrative(narrative: &[NarrativeSegment], order: NoteOrder) -> Vec<&NarrativeSegment> {
    let mut out: Vec<&NarrativeSegment> = narrative.iter().collect();
    match order {
        NoteOrder::NewestFirst => out.sort_by_key(|s| std::cmp::Reverse(s.created_at)),
        NoteOrder::OldestFirst => out.sort_by_key(|s| s.created_at),
    }
    out
}

/// A long-term goal/intention of the agent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Goal {
    pub id: Uuid,
    pub description: String,
    pub status: GoalStatus,
    pub created_at: DateTime<Utc>,
    /// When the goal left `Active` (for a closed goal's age and folding old closed
    /// ones). `None` for active goals and old records (no migration —
    /// `#[serde(default)]`). A closed goal's age is counted from it, otherwise from
    /// `created_at`.
    #[serde(default)]
    pub closed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum GoalStatus {
    Active,
    Completed,
    Abandoned,
}

/// How many recent completed/stale goals to show on a full read (`render_full`) —
/// the lifecycle is visible, but the list doesn't grow without bound.
const CLOSED_GOALS_SHOWN: usize = 5;

/// Per-section shares of the injection budget, in percent, in render order
/// (docs/history/self-model-injection-budget.md). They sum to 100; unused room flows
/// forward, so a short section makes the next one richer, while a bloated one
/// cannot reach past its own share. See [`SelfModel::render_for_prompt`].
const SHARE_SUMMARY: usize = 40;
const SHARE_GOALS: usize = 20;
const SHARE_USER: usize = 20;
const SHARE_OBSERVATIONS: usize = 20;

/// Room held back for the "+N more" marker while filling a list, so reporting the
/// dropped items cannot itself overflow the section. Approximate on purpose — the
/// marker's length is localized, and the block's final truncation is the backstop.
const MORE_MARKER_RESERVE: usize = 12;

/// The result of resolving a goal reference by its "handle" (a short `#id` or a
/// full UUID). See [`SelfModel::match_goal`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GoalMatch {
    /// A goal was found unambiguously.
    One(Uuid),
    /// No matches.
    None,
    /// The prefix is ambiguous (several goals matched).
    Ambiguous,
}

/// A short human-readable goal id: the first 6 hex characters of the UUID. Shown in
/// reads and accepted by `complete_goals`/`abandon_goals` (a full UUID too). At a
/// handful of goals, a collision is virtually impossible, and `match_goal` catches
/// ambiguity regardless.
fn short_hex(id: &Uuid) -> String {
    id.simple().to_string()[..6].to_string()
}

/// A public short id for tool echoes (the first 6 hex chars of the UUID, the same
/// format as `#id` in `render_full` reads). A wrapper over [`short_hex`] — so the
/// edit-delta echo (stage 4, docs/summary-as-snapshot.md) refers to goals by the
/// same handles they're closed with.
pub fn short_id(id: &Uuid) -> String {
    short_hex(id)
}

/// Assigns a trimmed string field; `false` (no change) when the trimmed value
/// is already there.
fn assign_trimmed(slot: &mut String, value: &str) -> bool {
    let value = value.trim().to_string();
    if *slot == value {
        return false;
    }
    *slot = value;
    true
}

/// Replaces a list wholesale; `false` when the new list is identical.
fn assign_list(slot: &mut Vec<String>, value: Vec<String>) -> bool {
    if *slot == value {
        return false;
    }
    *slot = value;
    true
}

/// Sets/clears a goal's `closed_at` based on its current status: on leaving
/// `Active` — stamps the moment (if not already stamped), on returning to `Active`
/// — clears it.
fn stamp_closed(g: &mut Goal) {
    match g.status {
        GoalStatus::Active => g.closed_at = None,
        _ => {
            if g.closed_at.is_none() {
                g.closed_at = Some(Utc::now());
            }
        }
    }
}

/// A coarse human-readable age label for a record (day granularity). Within one
/// day the text is stable — so the "self-model" injection into the system prompt
/// doesn't change turn to turn (the local model's prefix cache suffers no more
/// than once a day, beyond actual model edits). A negative difference (hours ahead
/// due to clock skew) is treated as "today".
fn age_label(at: DateTime<Utc>, now: DateTime<Utc>, loc: &Locale) -> String {
    let days = (now - at).num_days();
    match days {
        d if d <= 0 => loc.t("selfmodel.age.today").to_string(),
        1 => loc.t("selfmodel.age.yesterday").to_string(),
        2..=6 => loc.tf("selfmodel.age.days", &[("n", &days.to_string())]),
        7..=30 => loc.tf("selfmodel.age.weeks", &[("n", &(days / 7).to_string())]),
        31..=364 => loc.tf("selfmodel.age.months", &[("n", &(days / 30).to_string())]),
        _ => loc.tf("selfmodel.age.years", &[("n", &(days / 365).to_string())]),
    }
}

/// Resolves a "handle" (a full UUID or a short hex prefix, with or without a
/// leading `#`; case-insensitive) among a set of ids. Shared logic for goals and
/// observations.
fn resolve_handle(handle: &str, ids: &[Uuid]) -> GoalMatch {
    let h = handle.trim().trim_start_matches('#').to_lowercase();
    if h.is_empty() {
        return GoalMatch::None;
    }
    // A full UUID (with or without dashes).
    if let Ok(u) = Uuid::parse_str(&h) {
        return if ids.contains(&u) {
            GoalMatch::One(u)
        } else {
            GoalMatch::None
        };
    }
    // Otherwise — a prefix of the id's hex representation (the first `simple()` characters).
    let mut found: Option<Uuid> = None;
    for id in ids {
        if id.simple().to_string().starts_with(&h) {
            if found.is_some() {
                return GoalMatch::Ambiguous;
            }
            found = Some(*id);
        }
    }
    found.map_or(GoalMatch::None, GoalMatch::One)
}

/// A manual edit to the "self-model" from the UI editor (`F3`). Applied by the
/// entity ([`SelfModel::apply_edit`]); the orchestrator saves it. UI↔orchestrator contract.
#[derive(Debug, Clone, PartialEq)]
pub enum SelfModelEdit {
    /// Replace the short self-description.
    SetSummary(String),
    /// Add a new active goal.
    AddGoal(String),
    /// Change a goal's text by id.
    SetGoalText { id: Uuid, text: String },
    /// Cycle a goal's status (Active→Completed→Abandoned→Active).
    CycleGoalStatus(Uuid),
    /// Delete a goal by id.
    DeleteGoal(Uuid),
    /// Replace the list of perceived interlocutor traits.
    SetTraits(Vec<String>),
    /// Replace the list of the interlocutor's current interests.
    SetInterests(Vec<String>),
    /// Replace the relationship-dynamic description.
    SetRelationship(String),
    /// Delete a narrative insight by id.
    DeleteInsight(Uuid),
    /// Clear the whole model (description/goals/interlocutor/narrative).
    Clear,
}

/// The agent's representation of the interlocutor (free-form lists/text, no id).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct UserModel {
    #[serde(default)]
    pub perceived_traits: Vec<String>,
    #[serde(default)]
    pub current_interests: Vec<String>,
    #[serde(default)]
    pub relationship_dynamic: String,
}

impl SelfModel {
    /// An empty model for a profile.
    pub fn new(profile_id: Uuid) -> Self {
        Self {
            profile_id,
            version: 0,
            summary: String::new(),
            goals: Vec::new(),
            user_model: UserModel::default(),
            narrative: Vec::new(),
            updated_at: Utc::now(),
        }
    }

    /// Whether the **structural** part of the model is empty: an empty description,
    /// no active goals (only those are rendered), and an empty interlocutor model.
    /// The narrative is **not accounted for** here — it moved into notes (`@self`,
    /// see docs/history/narrative-as-notes.md) and is passed into the render via
    /// the `recent` parameter; the caller checks for observations
    /// (`is_empty() && recent.is_empty()`). Completed goals alone don't make an
    /// otherwise "empty" model informative.
    pub fn is_empty(&self) -> bool {
        self.summary.trim().is_empty()
            && self.active_goals().next().is_none()
            && self.user_model.is_empty()
    }

    /// Active goals (for rendering/reading).
    pub fn active_goals(&self) -> impl Iterator<Item = &Goal> {
        self.goals.iter().filter(|g| g.status == GoalStatus::Active)
    }

    /// Adds a new active goal.
    pub fn add_goal(&mut self, description: impl Into<String>) {
        let description = description.into().trim().to_string();
        if description.is_empty() {
            return;
        }
        self.goals.push(Goal {
            id: Uuid::new_v4(),
            description,
            status: GoalStatus::Active,
            created_at: Utc::now(),
            closed_at: None,
        });
    }

    /// Sets a goal's status (by id). Returns `true` if the goal was found.
    /// Sets/clears `closed_at` on leaving `Active`/reactivation.
    pub fn set_goal_status(&mut self, id: Uuid, status: GoalStatus) -> bool {
        if let Some(g) = self.goals.iter_mut().find(|g| g.id == id) {
            g.status = status;
            stamp_closed(g);
            true
        } else {
            false
        }
    }

    /// Cycles a goal's status Active→Completed→Abandoned→Active (by id).
    /// Returns `true` if the goal was found.
    pub fn cycle_goal_status(&mut self, id: Uuid) -> bool {
        if let Some(g) = self.goals.iter_mut().find(|g| g.id == id) {
            g.status = match g.status {
                GoalStatus::Active => GoalStatus::Completed,
                GoalStatus::Completed => GoalStatus::Abandoned,
                GoalStatus::Abandoned => GoalStatus::Active,
            };
            stamp_closed(g);
            true
        } else {
            false
        }
    }

    /// Applies a manual edit from the UI editor (`F3`). Returns `true` if the model
    /// changed (whether the orchestrator should save it). Pure logic — testable
    /// without an orchestrator. Trait/interest lists are replaced wholesale.
    pub fn apply_edit(&mut self, edit: SelfModelEdit) -> bool {
        match edit {
            SelfModelEdit::SetSummary(s) => assign_trimmed(&mut self.summary, &s),
            SelfModelEdit::AddGoal(desc) => {
                let before = self.goals.len();
                self.add_goal(desc);
                self.goals.len() != before
            }
            SelfModelEdit::SetGoalText { id, text } => self.set_goal_text(id, &text),
            SelfModelEdit::CycleGoalStatus(id) => self.cycle_goal_status(id),
            SelfModelEdit::DeleteGoal(id) => {
                let before = self.goals.len();
                self.goals.retain(|g| g.id != id);
                self.goals.len() != before
            }
            SelfModelEdit::SetTraits(v) => assign_list(&mut self.user_model.perceived_traits, v),
            SelfModelEdit::SetInterests(v) => {
                assign_list(&mut self.user_model.current_interests, v)
            }
            SelfModelEdit::SetRelationship(s) => {
                assign_trimmed(&mut self.user_model.relationship_dynamic, &s)
            }
            SelfModelEdit::DeleteInsight(id) => {
                let before = self.narrative.len();
                self.narrative.retain(|n| n.id != id);
                self.narrative.len() != before
            }
            SelfModelEdit::Clear => self.clear_all(),
        }
    }

    /// [`SelfModelEdit::SetGoalText`]: renames a goal by id. An empty or
    /// unchanged text, or an unknown id, is a no-op (`false`).
    fn set_goal_text(&mut self, id: Uuid, text: &str) -> bool {
        let text = text.trim().to_string();
        if let Some(g) = self.goals.iter_mut().find(|g| g.id == id) {
            if text.is_empty() || g.description == text {
                return false;
            }
            g.description = text;
            true
        } else {
            false
        }
    }

    /// [`SelfModelEdit::Clear`]: wipes every part of the model; `false` when
    /// there was nothing to wipe.
    fn clear_all(&mut self) -> bool {
        if self.is_empty() && self.summary.is_empty() && self.goals.is_empty() {
            return false;
        }
        self.summary.clear();
        self.goals.clear();
        self.user_model = UserModel::default();
        self.narrative.clear();
        true
    }

    /// Folds old closed goals into "scar" observations and removes them from
    /// `goals`, keeping no more than `keep` of the most recently closed (by
    /// `closed_at`/`created_at`). **Returns** the scar texts ("[goal archive] …") —
    /// the caller records them as self-notes (observations moved into notes, see
    /// docs/history/narrative-as-notes.md). Doesn't touch active goals. This is
    /// integration, not loss: a closed goal leaves as a scar observation rather
    /// than being silently deleted.
    pub fn fold_closed_goals(&mut self, keep: usize, loc: &Locale) -> Vec<String> {
        let freshness = |g: &Goal| g.closed_at.unwrap_or(g.created_at);
        let mut closed: Vec<(Uuid, DateTime<Utc>)> = self
            .goals
            .iter()
            .filter(|g| g.status != GoalStatus::Active)
            .map(|g| (g.id, freshness(g)))
            .collect();
        if closed.len() <= keep {
            return Vec::new();
        }
        closed.sort_by_key(|(_, at)| std::cmp::Reverse(*at)); // newest first
        let fold_ids: std::collections::HashSet<Uuid> =
            closed[keep..].iter().map(|(id, _)| *id).collect();

        let scars: Vec<String> = self
            .goals
            .iter()
            .filter(|g| fold_ids.contains(&g.id))
            .map(|g| {
                let verb = loc.t(match g.status {
                    GoalStatus::Completed => "selfmodel.status.completed",
                    GoalStatus::Abandoned => "selfmodel.status.abandoned",
                    GoalStatus::Active => "selfmodel.status.active",
                });
                loc.tf(
                    "selfmodel.goal_archive",
                    &[("verb", verb), ("text", g.description.trim())],
                )
            })
            .collect();
        self.goals.retain(|g| !fold_ids.contains(&g.id));
        scars
    }

    /// A soft hint about a bloated self-description: `None` while `summary` stays
    /// within the target `target`; otherwise text with the current size and the
    /// target, directing event-like content into observations. A direct analogue
    /// of the former `narrative_fill_hint`, but for `summary` — the one organ that
    /// had no size feedback. A gate, not a ceiling: doesn't truncate or block
    /// anything. See docs/summary-as-snapshot.md (stage 2).
    pub fn summary_fill_hint(&self, target: usize, loc: &Locale) -> Option<String> {
        let n = self.summary.chars().count();
        (n > target).then(|| {
            loc.tf(
                "selfmodel.summary_hint",
                &[("n", &n.to_string()), ("target", &target.to_string())],
            )
        })
    }

    /// A compact human-readable block for system-prompt injection.
    /// `None` if the structural part is empty **and** there are no observations.
    /// Observations (`recent` — self-notes, newest first, prepared by the caller)
    /// go into the block, `narrative_in_prompt` freshest ones. `now` — the
    /// reference point for age labels (day granularity, stable within a day —
    /// see [`age_label`]).
    ///
    /// **Every section has a budget** (`SHARE_*`, docs/history/self-model-injection-budget.md):
    /// a share of `max_chars` plus whatever earlier sections did not use. A share
    /// is a *ceiling*, so a bloated description or a long trait list cannot starve
    /// the sections after it — which is how the later ones get a floor without a
    /// second mechanism. Before this, only the description was bounded and the
    /// rest was a queue: measured on a real profile, the description and goals
    /// took everything and neither the interlocutor model nor the observations
    /// were injected at all.
    ///
    /// Lists lose **whole items** rather than being cut mid-item, and say how many
    /// were dropped, so the model knows it is seeing a part and can read the rest
    /// with `get_self_model` — which renders untruncated ([`Self::render_full`]).
    pub fn render_for_prompt(
        &self,
        max_chars: usize,
        narrative_in_prompt: usize,
        now: DateTime<Utc>,
        recent: &[NarrativeSegment],
        loc: &Locale,
    ) -> Option<String> {
        if self.is_empty() && recent.is_empty() {
            return None;
        }
        let mut out = format!("{}\n", loc.t("selfmodel.render.header"));
        // Unused room flows forward, so a short section makes the next one richer.
        let share = |pct: usize| max_chars * pct / 100;
        let mut carry = 0usize;

        let budget = share(SHARE_SUMMARY) + carry;
        carry = budget;
        if !self.summary.trim().is_empty() {
            let text = truncate_chars_word(self.summary.trim(), budget);
            carry = budget.saturating_sub(text.chars().count());
            out.push_str(loc.t("selfmodel.render.about"));
            out.push_str(&text);
            out.push('\n');
        }

        let budget = share(SHARE_GOALS) + carry;
        carry = budget;
        let active: Vec<&Goal> = self.active_goals().collect();
        if !active.is_empty() {
            let items: Vec<String> = active
                .iter()
                .map(|g| {
                    loc.tf(
                        "selfmodel.item.goal_prompt",
                        &[
                            ("desc", g.description.trim()),
                            ("age", &age_label(g.created_at, now, loc)),
                        ],
                    )
                })
                .collect();
            let (text, used) = fit_lines(&items, budget, loc);
            carry = budget.saturating_sub(used);
            out.push_str(loc.t("selfmodel.render.goals_active"));
            out.push('\n');
            out.push_str(&text);
        }

        let budget = share(SHARE_USER) + carry;
        carry = budget;
        if !self.user_model.is_empty() {
            let used = render_user_model(&mut out, &self.user_model, budget, loc);
            carry = budget.saturating_sub(used);
        }

        if !recent.is_empty() && narrative_in_prompt > 0 {
            let budget = share(SHARE_OBSERVATIONS) + carry;
            let items: Vec<String> = recent
                .iter()
                .take(narrative_in_prompt)
                .map(|seg| {
                    loc.tf(
                        "selfmodel.item.obs_prompt",
                        &[
                            ("age", &age_label(seg.created_at, now, loc)),
                            ("text", seg.text.trim()),
                        ],
                    )
                })
                .collect();
            let (text, _) = fit_lines(&items, budget, loc);
            out.push_str(loc.t("selfmodel.render.observations_recent"));
            out.push('\n');
            out.push_str(&text);
        }
        // A safety net only: the budgets above count content, not the fixed labels
        // around it, so the assembled block can still overshoot by a little.
        Some(truncate_chars(out.trim_end(), max_chars))
    }

    /// Resolves a goal reference by "handle": a full UUID or a short hex prefix
    /// (with or without a leading `#`). Case-insensitive. Searches only among the
    /// model's goals.
    pub fn match_goal(&self, handle: &str) -> GoalMatch {
        let ids: Vec<Uuid> = self.goals.iter().map(|g| g.id).collect();
        resolve_handle(handle, &ids)
    }

    /// A full human-readable read of the model — for tools (`get_self_model`,
    /// `reflect`, an echo after edits). Unlike [`Self::render_for_prompt`] (a
    /// compact injection), **truncates nothing**, shows all observations
    /// (`recent` — self-notes, newest first, prepared by the caller) and goals with
    /// their status. Goals — with a short `#id` (resolved by `update_self_model`'s
    /// resolver); observations — with the **full** id (they're notes, rewritten/
    /// replaced by note_revise/note_supersede using the full id). Marks an empty
    /// model explicitly. See docs/history/self-model-mvp.md, docs/history/narrative-as-notes.md.
    pub fn render_full(
        &self,
        now: DateTime<Utc>,
        recent: &[NarrativeSegment],
        loc: &Locale,
    ) -> String {
        let header = loc.t("selfmodel.render.header");
        let mut out = format!("{header}\n");
        if !self.summary.trim().is_empty() {
            out.push_str(loc.t("selfmodel.render.about"));
            out.push_str(self.summary.trim());
            out.push('\n');
        }
        let active: Vec<&Goal> = self.active_goals().collect();
        let closed: Vec<&Goal> = self
            .goals
            .iter()
            .filter(|g| g.status != GoalStatus::Active)
            .collect();
        if !active.is_empty() || !closed.is_empty() {
            out.push_str(loc.t("selfmodel.render.goals_ref"));
            out.push('\n');
            let active_st = loc.t("selfmodel.status.active");
            for g in &active {
                out.push_str(&loc.tf(
                    "selfmodel.item.goal_full",
                    &[
                        ("id", &short_hex(&g.id)),
                        ("status", active_st),
                        ("age", &age_label(g.created_at, now, loc)),
                        ("text", g.description.trim()),
                    ],
                ));
                out.push('\n');
            }
            // Recent closed ones — compact, newest first. Age — from the moment of
            // closing (`closed_at`), otherwise from creation.
            for g in closed.iter().rev().take(CLOSED_GOALS_SHOWN) {
                let st = loc.t(match g.status {
                    GoalStatus::Completed => "selfmodel.status.completed",
                    GoalStatus::Abandoned => "selfmodel.status.stale",
                    GoalStatus::Active => "selfmodel.status.active",
                });
                out.push_str(&loc.tf(
                    "selfmodel.item.goal_full",
                    &[
                        ("id", &short_hex(&g.id)),
                        ("status", st),
                        (
                            "age",
                            &age_label(g.closed_at.unwrap_or(g.created_at), now, loc),
                        ),
                        ("text", g.description.trim()),
                    ],
                ));
                out.push('\n');
            }
        }
        // A full read is deliberately not truncated (this is what `get_self_model`
        // returns and `F3` shows), so the interlocutor model gets an unbounded budget.
        render_user_model(&mut out, &self.user_model, usize::MAX, loc);
        // Observations (self-notes) in full, newest first — no truncation. Full id:
        // an observation is rewritten/replaced by note tools using the full id.
        if !recent.is_empty() {
            out.push_str(&loc.tf(
                "selfmodel.render.observations",
                &[("n", &recent.len().to_string())],
            ));
            out.push('\n');
            for seg in recent {
                out.push_str(&loc.tf(
                    "selfmodel.item.obs_full",
                    &[
                        ("id", &seg.id.to_string()),
                        ("age", &age_label(seg.created_at, now, loc)),
                        ("text", seg.text.trim()),
                    ],
                ));
                out.push('\n');
            }
        }
        let body = out.trim_end();
        if body == header {
            return loc.t("selfmodel.render.empty").to_string();
        }
        body.to_string()
    }
}

/// The "About the interlocutor" block — shared by [`SelfModel::render_for_prompt`]
/// and [`SelfModel::render_full`] (byte-for-byte in both). The `, ` and `;`
/// separators are punctuation, language-neutral and stay in the code; only the
/// label captions are localized.
/// Renders the interlocutor model within `budget` characters of content and
/// returns how many it used.
///
/// The three parts share the budget in order (traits → interests → dynamic), so
/// a long trait list cannot swallow the dynamic entirely: each part gets at most
/// half of what is left when it starts, except the last, which takes the
/// remainder. Lists lose whole items and say how many (see [`fit_items`]).
fn render_user_model(out: &mut String, u: &UserModel, budget: usize, loc: &Locale) -> usize {
    if u.is_empty() {
        return 0;
    }
    let mut used = 0usize;
    let mut body = String::new();
    let mut left = budget;
    if !u.perceived_traits.is_empty() {
        let (text, n) = fit_items(&u.perceived_traits, left.div_ceil(2), loc);
        if !text.is_empty() {
            body.push_str(loc.t("selfmodel.render.user.traits"));
            body.push_str(&text);
            body.push(';');
            used += n;
            left = left.saturating_sub(n);
        }
    }
    if !u.current_interests.is_empty() {
        let (text, n) = fit_items(&u.current_interests, left.div_ceil(2), loc);
        if !text.is_empty() {
            body.push_str(loc.t("selfmodel.render.user.interests"));
            body.push_str(&text);
            body.push(';');
            used += n;
            left = left.saturating_sub(n);
        }
    }
    let dynamic = u.relationship_dynamic.trim();
    if !dynamic.is_empty() && left > 0 {
        let text = truncate_chars_word(dynamic, left);
        body.push_str(loc.t("selfmodel.render.user.relationship"));
        body.push_str(&text);
        used += text.chars().count();
    }
    if body.is_empty() {
        return 0;
    }
    out.push_str(loc.t("selfmodel.render.user"));
    out.push_str(&body);
    out.push('\n');
    used
}

/// Joins list items with `, ` while they fit into `budget`, then reports how
/// many were dropped ("… +N more"). Returns the text and the characters used.
///
/// Whole items only (decision D3): a trait cut in half reads as a different
/// trait, and the count tells the model it is seeing a part — the full list is
/// one `get_self_model` away.
fn fit_items(items: &[String], budget: usize, loc: &Locale) -> (String, usize) {
    fit_parts(items, ", ", budget, loc)
}

/// [`fit_items`] for whole lines (goals, observations), newline-separated. The
/// returned text ends with a newline when non-empty, matching the previous
/// line-by-line rendering.
fn fit_lines(items: &[String], budget: usize, loc: &Locale) -> (String, usize) {
    let (text, used) = fit_parts(items, "\n", budget, loc);
    if text.is_empty() {
        (text, used)
    } else {
        (format!("{text}\n"), used)
    }
}

fn fit_parts(items: &[String], sep: &str, budget: usize, loc: &Locale) -> (String, usize) {
    let mut out = String::new();
    let mut used = 0usize;
    let mut taken = 0usize;
    for item in items {
        let item = item.trim();
        let extra = item.chars().count() + if taken == 0 { 0 } else { sep.chars().count() };
        // Room must be left for the "+N more" marker, unless this is the last item.
        let marker = if taken + 1 == items.len() {
            0
        } else {
            MORE_MARKER_RESERVE
        };
        if used + extra + marker > budget {
            break;
        }
        if taken > 0 {
            out.push_str(sep);
        }
        out.push_str(item);
        used += extra;
        taken += 1;
    }
    if taken == 0 {
        // Nothing fits whole: degrade to a character cut of the first item rather
        // than dropping the section — an empty section would read as "no traits".
        let head = truncate_chars_word(items[0].trim(), budget);
        used = head.chars().count();
        out = head;
        taken = 1;
    }
    if taken < items.len() {
        let more = loc.tf(
            "selfmodel.render.more",
            &[("n", &(items.len() - taken).to_string())],
        );
        used += more.chars().count();
        out.push_str(&more);
    }
    (out, used)
}

impl UserModel {
    pub fn is_empty(&self) -> bool {
        self.perceived_traits.is_empty()
            && self.current_interests.is_empty()
            && self.relationship_dynamic.trim().is_empty()
    }

    /// A compact hint for impersonation (`Ctrl+U`): the agent writes a reply **on
    /// behalf of** the person, and `UserModel` is a model of that person, so mixing
    /// it into the impersonation system prompt makes the voice more accurate. This
    /// is a prompt fragment (text the *model* reads) — localized via `loc` in the
    /// agent-scaffold language (axis A), like [`render_user_model`] above.
    /// `None` if the model is empty; the result is truncated to `max_chars` characters.
    pub fn render_for_impersonation(&self, max_chars: usize, loc: &Locale) -> Option<String> {
        if self.is_empty() {
            return None;
        }
        let mut out = loc.t("selfmodel.render.impersonation.intro").to_string();
        if !self.perceived_traits.is_empty() {
            out.push_str(loc.t("selfmodel.render.impersonation.traits"));
            out.push_str(&self.perceived_traits.join(", "));
            out.push(';');
        }
        if !self.current_interests.is_empty() {
            out.push_str(loc.t("selfmodel.render.impersonation.interests"));
            out.push_str(&self.current_interests.join(", "));
            out.push(';');
        }
        if !self.relationship_dynamic.trim().is_empty() {
            out.push_str(loc.t("selfmodel.render.impersonation.relationship"));
            out.push_str(self.relationship_dynamic.trim());
        }
        Some(truncate_chars(out.trim_end_matches([';', ' ']), max_chars))
    }

    /// Adds traits (case-insensitive dedup, empty ones dropped). Returns whether
    /// the list changed. **Merge, not replace** — the edit doesn't overwrite prior data.
    pub fn add_traits(&mut self, items: Vec<String>) -> bool {
        merge_into(&mut self.perceived_traits, items)
    }
    /// Removes traits by match (case-insensitive). Returns whether it changed.
    pub fn remove_traits(&mut self, items: &[String]) -> bool {
        remove_from(&mut self.perceived_traits, items)
    }
    /// Adds interests (case-insensitive dedup). Returns whether it changed.
    pub fn add_interests(&mut self, items: Vec<String>) -> bool {
        merge_into(&mut self.current_interests, items)
    }
    /// Removes interests by match (case-insensitive). Returns whether it changed.
    pub fn remove_interests(&mut self, items: &[String]) -> bool {
        remove_from(&mut self.current_interests, items)
    }
}

/// Adds items to a list with case-insensitive dedup (Unicode). Empty-after-trim
/// items are dropped. Returns `true` if anything was added.
fn merge_into(list: &mut Vec<String>, items: Vec<String>) -> bool {
    let mut changed = false;
    for it in items {
        let it = it.trim().to_string();
        if it.is_empty() {
            continue;
        }
        let lc = it.to_lowercase();
        if !list.iter().any(|x| x.to_lowercase() == lc) {
            list.push(it);
            changed = true;
        }
    }
    changed
}

/// Removes items from the list matching (case-insensitive) any of `items`.
/// Returns `true` if the list changed.
fn remove_from(list: &mut Vec<String>, items: &[String]) -> bool {
    let targets: Vec<String> = items
        .iter()
        .map(|s| s.trim().to_lowercase())
        .filter(|s| !s.is_empty())
        .collect();
    if targets.is_empty() {
        return false;
    }
    let before = list.len();
    list.retain(|x| !targets.contains(&x.to_lowercase()));
    list.len() != before
}

/// Truncation by characters (not bytes — Cyrillic) with an ellipsis.
fn truncate_chars(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        return s.to_string();
    }
    let take = max_chars.saturating_sub(1);
    let mut out: String = s.chars().take(take).collect();
    out.push('');
    out
}

/// Truncation at a word boundary: like [`truncate_chars`], but rolls back to the
/// last space within the limit, so as not to tear a word mid-way ("…" inside a word
/// reads as corrupted memory). If there's no space (one long word) — cuts by
/// character. The result, like [`truncate_chars`]'s, is no longer than `max_chars`
/// characters.
fn truncate_chars_word(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        return s.to_string();
    }
    let take = max_chars.saturating_sub(1);
    let head: String = s.chars().take(take).collect();
    // rfind gives the byte index of the space (valid for slicing at a char boundary).
    let base = match head.rfind(char::is_whitespace) {
        Some(idx) => head[..idx].trim_end(),
        None => head.as_str(),
    };
    // The rollback ate everything (a leading space) — fall back to the char-wise head.
    let base = if base.is_empty() { head.as_str() } else { base };
    format!("{base}")
}

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

    /// Default render/storage parameters for tests.
    fn p() -> SelfModelParams {
        SelfModelParams::default()
    }

    /// A time reference point for render tests (matches the record-creation moment
    /// → fresh ones show as "today").
    fn now() -> DateTime<Utc> {
        Utc::now()
    }

    /// A reference locale (ru) for render tests: asserting Russian substrings
    /// simultaneously pins the ru bundle's content. Per-language checks — below
    /// (`render_localized_for_all_langs`, `age_label_localized_for_all_langs`).
    fn loc() -> &'static Locale {
        crate::shared::i18n::locale(crate::shared::i18n::Lang::Ru)
    }

    /// An observation (self-note) for render tests: id + text + "now".
    /// Observations moved into notes and are passed into the render via the `recent` parameter.
    fn seg(text: &str) -> NarrativeSegment {
        NarrativeSegment {
            id: Uuid::new_v4(),
            text: text.into(),
            created_at: Utc::now(),
        }
    }

    #[test]
    fn empty_model_renders_none() {
        let m = SelfModel::new(Uuid::new_v4());
        assert!(m.is_empty());
        // Empty both structurally and by observations → None.
        assert!(
            m.render_for_prompt(p().prompt_cap, p().narrative_in_prompt, now(), &[], loc())
                .is_none()
        );
    }

    #[test]
    fn render_includes_recent_observations() {
        // Only observations (recent), the structural part is empty → the model is informative.
        let m = SelfModel::new(Uuid::new_v4());
        let recent = [seg("заметил напряжение между «кратко» и «полно»")];
        let r = m
            .render_for_prompt(
                p().prompt_cap,
                p().narrative_in_prompt,
                now(),
                &recent,
                loc(),
            )
            .unwrap();
        assert!(r.contains("Недавние наблюдения:"));
        assert!(r.contains("напряжение"));
    }

    #[test]
    fn render_for_prompt_takes_freshest_n() {
        // recent — newest first; only narrative_in_prompt freshest go into the prompt.
        let params = SelfModelParams::from_settings(&SelfModelSettings {
            narrative_in_prompt: 2,
            prompt_cap: 1000,
            ..SelfModelSettings::default()
        });
        let m = SelfModel::new(Uuid::new_v4());
        let recent: Vec<NarrativeSegment> =
            (0..10).rev().map(|i| seg(&format!("инсайт {i}"))).collect();
        let r = m
            .render_for_prompt(
                params.prompt_cap,
                params.narrative_in_prompt,
                now(),
                &recent,
                loc(),
            )
            .unwrap();
        assert_eq!(r.matches("инсайт ").count(), 2);
        // The first two (newest) — indices 9 and 8.
        assert!(r.contains("инсайт 9"));
        assert!(r.contains("инсайт 8"));
    }

    #[test]
    fn add_and_complete_goals() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.add_goal("помочь с рефакторингом");
        m.add_goal("  "); // empty one is ignored
        assert_eq!(m.goals.len(), 1);
        assert_eq!(m.active_goals().count(), 1);

        let id = m.goals[0].id;
        assert!(m.set_goal_status(id, GoalStatus::Completed));
        assert_eq!(m.active_goals().count(), 0);
        // a nonexistent goal
        assert!(!m.set_goal_status(Uuid::new_v4(), GoalStatus::Abandoned));
    }

    /// A model shaped like the measured dev profile: a description over its share,
    /// five goals, sixteen traits, sixteen interests. See
    /// docs/history/self-model-injection-budget.md §1.
    fn bloated_model() -> SelfModel {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.summary = "описание ".repeat(150); // 1350 chars
        for i in 0..5 {
            m.add_goal(format!("цель номер {i} с довольно длинной формулировкой"));
        }
        m.user_model.perceived_traits = (0..16)
            .map(|i| format!("черта номер {i} с пояснением на сотню символов примерно вот так"))
            .collect();
        m.user_model.current_interests = (0..16).map(|i| format!("интерес номер {i}")).collect();
        m.user_model.relationship_dynamic = "рабочие, доверительные".into();
        m
    }

    /// The defect this budget exists for: with only the description bounded, the
    /// goals ate the remainder and neither the interlocutor model nor the
    /// observations reached the prompt at all.
    #[test]
    fn every_section_survives_a_bloated_model() {
        let m = bloated_model();
        let recent = vec![seg("наблюдение про кэш")];
        let r = m.render_for_prompt(4000, 3, now(), &recent, loc()).unwrap();
        assert!(r.contains("О себе:"), "{r}");
        assert!(r.contains("цель номер 0"), "goals present: {r}");
        assert!(r.contains("черта номер 0"), "interlocutor present: {r}");
        assert!(
            r.contains("наблюдение про кэш"),
            "observations present: {r}"
        );
        assert!(r.chars().count() <= 4000);
    }

    /// The same at the old, tighter budget: every section still gets something,
    /// rather than the first two taking everything.
    #[test]
    fn every_section_survives_a_small_budget() {
        let m = bloated_model();
        let recent = vec![seg("наблюдение про кэш")];
        let r = m.render_for_prompt(1200, 3, now(), &recent, loc()).unwrap();
        assert!(r.contains("О себе:"), "{r}");
        assert!(r.contains("цель номер 0"), "{r}");
        assert!(r.contains("черта номер 0"), "{r}");
        assert!(r.contains("наблюдение про кэш"), "{r}");
    }

    #[test]
    fn unused_room_flows_to_the_next_section() {
        let mut short = bloated_model();
        short.summary = "коротко".into();
        let long = bloated_model();
        let goals_of = |m: &SelfModel| {
            let r = m.render_for_prompt(1200, 0, now(), &[], loc()).unwrap();
            (0..5)
                .filter(|i| r.contains(&format!("цель номер {i}")))
                .count()
        };
        assert!(
            goals_of(&short) > goals_of(&long),
            "a short description leaves the goals more room: {} vs {}",
            goals_of(&short),
            goals_of(&long)
        );
    }

    /// Lists lose whole items and say how many — a trait cut in half reads as a
    /// different trait, and the count tells the model the list is partial.
    #[test]
    fn lists_drop_whole_items_and_report_the_count() {
        let m = bloated_model();
        let r = m.render_for_prompt(1200, 0, now(), &[], loc()).unwrap();
        let traits = r
            .split("черты: ")
            .nth(1)
            .expect("traits section")
            .split(';')
            .next()
            .unwrap();
        assert!(traits.contains("ещё "), "dropped count reported: {traits}");
        // The marker is appended to the last item, so strip it before checking
        // that every rendered trait is whole.
        let listed = traits.split('').next().unwrap();
        for part in listed.split(", ") {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            assert!(
                m.user_model.perceived_traits.iter().any(|t| t == part),
                "a partial item leaked into the list: {part:?}"
            );
        }
    }

    /// A single item larger than the whole section still renders (cut), rather
    /// than the section vanishing — an empty section reads as "no traits".
    #[test]
    fn an_oversized_single_item_degrades_to_a_cut() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.user_model.perceived_traits = vec!["очень длинная черта ".repeat(50)];
        let r = m.render_for_prompt(400, 0, now(), &[], loc()).unwrap();
        assert!(r.contains("черты: очень длинная"), "{r}");
        assert!(r.chars().count() <= 400);
    }

    #[test]
    fn render_includes_sections() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.summary = "ценю честность".into();
        m.add_goal("разобраться в коде");
        m.user_model.perceived_traits = vec!["любопытный".into()];
        m.user_model.current_interests = vec!["Rust".into()];
        m.user_model.relationship_dynamic = "доверительные".into();

        let r = m
            .render_for_prompt(p().prompt_cap, p().narrative_in_prompt, now(), &[], loc())
            .unwrap();
        assert!(r.contains("О себе: ценю честность"));
        assert!(r.contains("разобраться в коде"));
        assert!(r.contains("черты: любопытный"));
        assert!(r.contains("интересы: Rust"));
        assert!(r.contains("отношения: доверительные"));
    }

    /// A segment stamped `mins` minutes after a fixed epoch, labeled by that offset.
    fn dated_seg(mins: i64) -> NarrativeSegment {
        NarrativeSegment {
            id: Uuid::new_v4(),
            text: format!("obs {mins}"),
            created_at: chrono::TimeZone::timestamp_opt(&Utc, mins * 60, 0).unwrap(),
        }
    }

    #[test]
    fn narrative_is_ordered_by_its_own_date_both_ways() {
        // The input order is deliberately neither: what the F3 snapshot brings is
        // `updated_at`-descending, and the rows show `created_at` (spec §17.7).
        let input = vec![dated_seg(20), dated_seg(5), dated_seg(30), dated_seg(10)];
        let texts = |order| {
            order_narrative(&input, order)
                .into_iter()
                .map(|s| s.text.clone())
                .collect::<Vec<_>>()
        };
        assert_eq!(
            texts(NoteOrder::NewestFirst),
            ["obs 30", "obs 20", "obs 10", "obs 5"]
        );
        assert_eq!(
            texts(NoteOrder::OldestFirst),
            ["obs 5", "obs 10", "obs 20", "obs 30"]
        );
        // The default is what a person opens the screen for — the newest.
        assert_eq!(texts(NoteOrder::default()), texts(NoteOrder::NewestFirst));
    }

    #[test]
    fn same_instant_segments_keep_the_incoming_order() {
        // A stable sort: two observations recorded in the same instant (a batch
        // write) must not shuffle between renders.
        let (a, b) = (dated_seg(7), dated_seg(7));
        let input = vec![
            NarrativeSegment {
                text: "first".into(),
                ..a
            },
            NarrativeSegment {
                text: "second".into(),
                ..b
            },
        ];
        for order in [NoteOrder::NewestFirst, NoteOrder::OldestFirst] {
            let texts: Vec<&str> = order_narrative(&input, order)
                .into_iter()
                .map(|s| s.text.as_str())
                .collect();
            assert_eq!(texts, ["first", "second"], "{order:?}");
        }
    }

    #[test]
    fn params_sanitize_inconsistent_settings() {
        // Zero max → a minimum of 1; in_prompt no more than max; a tiny cap → the floor.
        let params = SelfModelParams::from_settings(&SelfModelSettings {
            max_narrative: 0,
            narrative_in_prompt: 99,
            prompt_cap: 1,
            ..SelfModelSettings::default()
        });
        assert_eq!(params.max_narrative, 1);
        assert_eq!(params.narrative_in_prompt, 1);
        assert_eq!(params.prompt_cap, 100);
    }

    #[test]
    fn summary_target_sanitized_to_floor() {
        // A tiny target → a floor of 200 (protection against a meaninglessly small value).
        let params = SelfModelParams::from_settings(&SelfModelSettings {
            summary_target_chars: 10,
            ..SelfModelSettings::default()
        });
        assert_eq!(params.summary_target_chars, 200);
    }

    #[test]
    fn summary_fill_hint_only_over_target() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.summary = "к".repeat(50);
        // Within the target — no hint.
        assert!(m.summary_fill_hint(100, loc()).is_none());
        // Beyond the target — a hint with the numbers.
        m.summary = "к".repeat(150);
        let hint = m.summary_fill_hint(100, loc()).unwrap();
        assert!(hint.contains("150"));
        assert!(hint.contains("100"));
        assert!(hint.contains("add_insight"));
    }

    #[test]
    fn completed_goals_not_rendered() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.add_goal("старая цель");
        let id = m.goals[0].id;
        m.set_goal_status(id, GoalStatus::Completed);
        // only a completed goal → the model is "empty" for rendering
        assert!(m.is_empty());
        assert!(
            m.render_for_prompt(p().prompt_cap, p().narrative_in_prompt, now(), &[], loc())
                .is_none()
        );
    }

    #[test]
    fn apply_edit_covers_operations() {
        let mut m = SelfModel::new(Uuid::new_v4());
        assert!(m.apply_edit(SelfModelEdit::SetSummary("я краток".into())));
        assert_eq!(m.summary, "я краток");
        // repeating the same — no change
        assert!(!m.apply_edit(SelfModelEdit::SetSummary("я краток".into())));

        assert!(m.apply_edit(SelfModelEdit::AddGoal("помочь".into())));
        let gid = m.goals[0].id;
        assert!(m.apply_edit(SelfModelEdit::SetGoalText {
            id: gid,
            text: "помочь лучше".into()
        }));
        assert_eq!(m.goals[0].description, "помочь лучше");
        // status cycle: Active → Completed
        assert!(m.apply_edit(SelfModelEdit::CycleGoalStatus(gid)));
        assert_eq!(m.goals[0].status, GoalStatus::Completed);
        assert!(m.apply_edit(SelfModelEdit::DeleteGoal(gid)));
        assert!(m.goals.is_empty());

        assert!(m.apply_edit(SelfModelEdit::SetTraits(vec!["скептик".into()])));
        assert!(m.apply_edit(SelfModelEdit::SetInterests(vec!["Rust".into()])));
        assert!(m.apply_edit(SelfModelEdit::SetRelationship("рабочие".into())));
        assert_eq!(m.user_model.perceived_traits, vec!["скептик".to_string()]);

        // DeleteInsight in apply_edit operates on the `narrative` field (in
        // production the orchestrator intercepts it and deletes the self-note; the
        // field is kept for reconstructing the `F3` snapshot and compatibility).
        // Populate the field directly.
        m.narrative.push(seg("наблюдение"));
        let iid = m.narrative[0].id;
        assert!(m.apply_edit(SelfModelEdit::DeleteInsight(iid)));
        assert!(m.narrative.is_empty());

        // Clear resets everything; a repeat Clear on an empty model — a no-op.
        assert!(m.apply_edit(SelfModelEdit::Clear));
        assert!(m.is_empty());
        assert!(!m.apply_edit(SelfModelEdit::Clear));
        // nonexistent ids — a no-op
        assert!(!m.apply_edit(SelfModelEdit::DeleteGoal(Uuid::new_v4())));
    }

    #[test]
    fn bloated_summary_does_not_starve_sections() {
        // Stage 3: a bloated description doesn't crowd goals/interlocutor/
        // observations out of the injection (a per-section budget: summary ≤ half the limit).
        let mut m = SelfModel::new(Uuid::new_v4());
        m.summary = "слово ".repeat(400); // ~2400 chars, many words
        m.add_goal("активная цель");
        m.user_model.perceived_traits = vec!["внимательный".into()];
        let recent = [seg("свежее наблюдение о стиле")];

        let r = m.render_for_prompt(1200, 3, now(), &recent, loc()).unwrap();
        // All sections are present despite the bloated description.
        assert!(r.contains("Активные цели:"), "goals crowded out: {r}");
        assert!(
            r.contains("О собеседнике:"),
            "interlocutor crowded out: {r}"
        );
        assert!(
            r.contains("Недавние наблюдения:"),
            "observations crowded out: {r}"
        );
        // The block is within the limit; the description is truncated (beyond half the budget).
        assert!(r.chars().count() <= 1200);
        assert!(r.contains("О себе: "));
    }

    #[test]
    fn small_summary_not_truncated() {
        // A small description passes through with no "…" (unchanged behavior for
        // non-bloated models).
        let mut m = SelfModel::new(Uuid::new_v4());
        m.summary = "ценю ясность и краткость".into();
        let r = m
            .render_for_prompt(1200, p().narrative_in_prompt, now(), &[], loc())
            .unwrap();
        assert!(r.contains("О себе: ценю ясность и краткость"));
        assert!(!r.contains(''));
    }

    #[test]
    fn truncate_word_does_not_split_word() {
        // Truncation at a word boundary doesn't tear a word mid-way.
        let s = "первое второе третье четвёртое пятое";
        let out = truncate_chars_word(s, 20);
        assert!(out.ends_with(''));
        assert!(out.chars().count() <= 20);
        // Trimming at a word boundary: without "…" the result is a prefix of whole words.
        let body = out.trim_end_matches('');
        assert!(s.starts_with(body.trim_end()));
        assert!(!body.trim_end().is_empty());
        // One long word with no spaces — falls back to char-wise truncation.
        let long = "я".repeat(50);
        let out = truncate_chars_word(&long, 10);
        assert_eq!(out.chars().count(), 10);
        assert!(out.ends_with(''));
    }

    #[test]
    fn render_truncates_to_cap() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.summary = "я".repeat(500);
        let r = m
            .render_for_prompt(50, p().narrative_in_prompt, now(), &[], loc())
            .unwrap();
        // No longer *equal* to the cap: the description's own section budget (40%)
        // cuts it before the block-wide truncation can, which is the point of
        // docs/history/self-model-injection-budget.md. The invariant is the ceiling.
        assert!(r.chars().count() <= 50, "{r:?}");
        assert!(r.ends_with(''), "the description was truncated: {r:?}");
    }

    #[test]
    fn render_full_shows_goal_ids_and_full_observation_ids() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.summary = "я".repeat(500);
        m.add_goal("активная цель");
        m.add_goal("завершённая цель");
        let done = m.goals[1].id;
        m.set_goal_status(done, GoalStatus::Completed);
        // Many observations (recent, newest first) — a full read shows all of them.
        let recent: Vec<NarrativeSegment> =
            (0..12).rev().map(|i| seg(&format!("инсайт {i}"))).collect();

        let full = m.render_full(now(), &recent, loc());
        assert!(!full.ends_with(''), "a full read isn't truncated");
        // The active goal — with a short #id, status, and age label ("today").
        let short = short_hex(&m.goals[0].id);
        assert!(full.contains(&format!("#{short} (активна · сегодня) активная цель")));
        // The completed one is also visible (lifecycle), with age from closing.
        assert!(full.contains("(выполнена · сегодня) завершённая цель"));
        // All observations (not just narrative_in_prompt=3), with the FULL id (for
        // note_revise/note_supersede).
        assert_eq!(full.matches("инсайт ").count(), 12);
        assert!(full.contains("Наблюдения (12"));
        assert!(full.contains(&format!("(id={})", recent[0].id)));
        // The full self-description in its entirety (not truncated to prompt_cap).
        assert!(full.contains(&"я".repeat(500)));
    }

    #[test]
    fn render_full_on_empty_marks_empty() {
        let m = SelfModel::new(Uuid::new_v4());
        assert_eq!(m.render_full(now(), &[], loc()), "(модель себя пока пуста)");
    }

    #[test]
    fn match_goal_by_prefix_full_and_ambiguous() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.add_goal("первая");
        let id = m.goals[0].id;
        // A full UUID.
        assert_eq!(m.match_goal(&id.to_string()), GoalMatch::One(id));
        // A short hex prefix, with a leading '#'.
        let short = short_hex(&id);
        assert_eq!(m.match_goal(&format!("#{short}")), GoalMatch::One(id));
        // Case-insensitive.
        assert_eq!(m.match_goal(&short.to_uppercase()), GoalMatch::One(id));
        // A nonexistent one.
        assert_eq!(m.match_goal("zzzzzz"), GoalMatch::None);
        assert_eq!(m.match_goal(""), GoalMatch::None);
        // An empty prefix (after stripping '#') would match everything → ambiguous.
        m.add_goal("вторая");
        assert_eq!(m.match_goal("#"), GoalMatch::None); // empty → None, not Ambiguous
    }

    #[test]
    fn user_model_merge_add_remove() {
        let mut u = UserModel::default();
        assert!(u.add_traits(vec!["добрый".into(), "Добрый".into(), "  ".into()]));
        // Case-insensitive dedup + dropping the empty one.
        assert_eq!(u.perceived_traits, vec!["добрый".to_string()]);
        // A new edit doesn't overwrite — merge.
        assert!(u.add_traits(vec!["прямолинейный".into()]));
        assert_eq!(u.perceived_traits.len(), 2);
        // Repeating an already-known one — no change.
        assert!(!u.add_traits(vec!["добрый".into()]));
        // Removal by case-insensitive match.
        assert!(u.remove_traits(&["ДОБРЫЙ".into()]));
        assert_eq!(u.perceived_traits, vec!["прямолинейный".to_string()]);
        // Removing a nonexistent one — a no-op.
        assert!(!u.remove_traits(&["нет такого".into()]));
    }

    #[test]
    fn user_model_render_for_impersonation() {
        // Empty → None.
        assert!(
            UserModel::default()
                .render_for_impersonation(500, loc())
                .is_none()
        );
        let u = UserModel {
            perceived_traits: vec!["скептик".into(), "любопытный".into()],
            current_interests: vec!["Rust".into()],
            relationship_dynamic: "доверительные, на равных".into(),
        };
        let r = u.render_for_impersonation(500, loc()).unwrap();
        assert!(r.contains("за которого ты пишешь"));
        assert!(r.contains("черты — скептик, любопытный"));
        assert!(r.contains("интересы — Rust"));
        assert!(r.contains("отношения с собеседником — доверительные, на равных"));
    }

    /// Per-locale coverage (docs/history/i18n.md §3.5): rendering under EVERY built-in
    /// language, no unsubstituted `{…}`, and no Cyrillic leaking into `en`.
    #[test]
    fn render_for_impersonation_localized_for_all_langs() {
        let u = UserModel {
            perceived_traits: vec!["skeptic".into()],
            current_interests: vec!["Rust".into()],
            relationship_dynamic: "trusting, as equals".into(),
        };
        for &lang in crate::shared::i18n::Lang::ALL {
            let l = crate::shared::i18n::locale(lang);
            let r = u.render_for_impersonation(500, l).unwrap();
            assert!(!r.contains('{') && !r.contains('}'), "{lang:?}: {r}");
            if lang == crate::shared::i18n::Lang::En {
                assert!(
                    !r.chars().any(|c| ('\u{0400}'..='\u{04FF}').contains(&c)),
                    "Cyrillic leaked into en: {r}"
                );
            }
        }
    }

    /// Per-language coverage (§3.5 docs/history/i18n.md): rendering under EVERY
    /// built-in language — sections/observations are tagged with headers from that
    /// language's bundle, placeholders are substituted (catches a broken/incomplete
    /// translation and `{…}` gaps in a specific language).
    #[test]
    fn render_localized_for_all_langs() {
        for &lang in crate::shared::i18n::Lang::ALL {
            let l = crate::shared::i18n::locale(lang);
            let mut m = SelfModel::new(Uuid::new_v4());
            m.summary = "s".into();
            m.add_goal("g");
            m.user_model.perceived_traits = vec!["t".into()];
            let recent = [seg("obs")];
            let r = m
                .render_for_prompt(p().prompt_cap, p().narrative_in_prompt, now(), &recent, l)
                .unwrap();
            assert!(r.contains(l.t("selfmodel.render.header")), "{lang:?}: {r}");
            assert!(r.contains(l.t("selfmodel.render.goals_active")), "{lang:?}");
            assert!(r.contains(l.t("selfmodel.render.user")), "{lang:?}");
            assert!(
                r.contains(l.t("selfmodel.render.observations_recent")),
                "{lang:?}"
            );
            // The "today" age is substituted with no leftover `{…}`.
            assert!(!r.contains('{'), "{lang:?}: leftover placeholder: {r}");
            // A full read in the same language — its own header, no truncation.
            let full = m.render_full(now(), &recent, l);
            assert!(full.contains(l.t("selfmodel.render.goals_ref")), "{lang:?}");
            assert!(!full.contains('{'), "{lang:?}: placeholder in full: {full}");
        }
    }

    /// Per-language age labels: every bucket variant substitutes `{n}` and leaves
    /// no placeholder — across all built-in languages.
    #[test]
    fn age_label_localized_for_all_langs() {
        use chrono::Duration;
        let base = Utc::now();
        for &lang in crate::shared::i18n::Lang::ALL {
            let l = crate::shared::i18n::locale(lang);
            for d in [0i64, 1, 3, 10, 40, 400] {
                let s = age_label(base - Duration::days(d), base, l);
                assert!(!s.contains('{'), "{lang:?} d={d}: {s}");
                assert!(!s.is_empty());
            }
        }
    }

    #[test]
    fn age_label_buckets() {
        use chrono::Duration;
        let base = Utc::now();
        let ago = |d: i64| base - Duration::days(d);
        assert_eq!(age_label(base, base, loc()), "сегодня");
        assert_eq!(age_label(ago(1), base, loc()), "вчера");
        assert_eq!(age_label(ago(3), base, loc()), "3 дн.");
        assert_eq!(age_label(ago(6), base, loc()), "6 дн.");
        assert_eq!(age_label(ago(7), base, loc()), "1 нед.");
        assert_eq!(age_label(ago(20), base, loc()), "2 нед.");
        assert_eq!(age_label(ago(31), base, loc()), "1 мес.");
        assert_eq!(age_label(ago(200), base, loc()), "6 мес.");
        assert_eq!(age_label(ago(365), base, loc()), "1 г.");
        assert_eq!(age_label(ago(800), base, loc()), "2 г.");
        // A time "from the future" (clock skew) → falls back to the "today" bucket, not a panic.
        assert_eq!(age_label(base + Duration::hours(5), base, loc()), "сегодня");
    }

    #[test]
    fn set_goal_status_stamps_and_clears_closed_at() {
        let mut m = SelfModel::new(Uuid::new_v4());
        m.add_goal("цель");
        let id = m.goals[0].id;
        assert!(m.goals[0].closed_at.is_none()); // active — no stamp
        m.set_goal_status(id, GoalStatus::Completed);
        let closed = m.goals[0].closed_at;
        assert!(closed.is_some()); // closing stamped the moment
        // A repeat closing (to a different status) doesn't shift the moment.
        m.set_goal_status(id, GoalStatus::Abandoned);
        assert_eq!(m.goals[0].closed_at, closed);
        // Reactivation clears the stamp.
        m.set_goal_status(id, GoalStatus::Active);
        assert!(m.goals[0].closed_at.is_none());
    }

    #[test]
    fn fold_closed_goals_returns_scars_beyond_keep() {
        use chrono::Duration;
        let mut m = SelfModel::new(Uuid::new_v4());
        // Five closed goals with different closing times + one active.
        for i in 0..5 {
            m.add_goal(format!("закрытая {i}"));
        }
        m.add_goal("активная");
        // Close the first five, stamping different closed_at (older ones — earlier).
        for i in 0..5 {
            let id = m.goals[i].id;
            m.set_goal_status(id, GoalStatus::Completed);
            m.goals[i].closed_at = Some(Utc::now() - Duration::days((5 - i) as i64));
        }
        // Keep the 2 freshest closed, the other 3 → come back as scars (the caller
        // records them as self-notes).
        let scars = m.fold_closed_goals(2, loc());
        assert_eq!(scars.len(), 3);
        // The active one is untouched; total goals: 2 closed + 1 active.
        assert_eq!(m.goals.len(), 3);
        assert_eq!(m.active_goals().count(), 1);
        // Scars — "goal archive" entries; the oldest closed one is among them.
        assert!(scars.iter().all(|s| s.starts_with("[архив цели]")));
        assert!(scars.iter().any(|s| s.contains("закрытая 0")));
        // Fewer than keep closed → empty.
        assert!(m.fold_closed_goals(2, loc()).is_empty());
    }
}