eclipse-core 0.13.2

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
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
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
//! Layered context files: `AGENT.md`, `USER.md`, `MEMORY.md`.
//!
//! Three questions, three files, three scopes:
//!
//! | File | Who writes it | Scope | Purpose |
//! |---|---|---|---|
//! | `AGENT.md` | the user | global or per project | how to work here: conventions, commands, gotchas |
//! | `USER.md` | the user | per profile | who the operator is: preferences, environment, standing rules |
//! | `MEMORY.md` | the agent | per profile | durable facts it learned; `§`-separated, budgeted |
//!
//! A fourth layer, the skills index, comes after them. It is not a file and has its own budget
//! (`[skills] index_budget_chars`), so it neither counts against the file budget nor is dropped by
//! it; see [`crate::skills`].
//!
//! Everything here is pure: paths in, labelled text out. Nothing is written by this module
//! except through [`crate::memory`], which owns `MEMORY.md`'s budget and lock.

use std::io::Read;
use std::path::{Path, PathBuf};

/// Per-file ceiling before truncation, in characters.
pub const DEFAULT_MAX_FILE_CHARS: usize = 6000;
/// Ceiling across all the file layers, in characters.
pub const DEFAULT_BUDGET_CHARS: usize = 12000;
/// Below this much room, clipping the last file would leave a stub not worth sending, so it
/// is dropped and said so.
const MIN_CLIP: usize = 120;
/// Deepest directory walk when looking for a project `AGENT.md`. A guard against a
/// pathological tree, not a real limit.
const MAX_WALK: usize = 64;
/// The most of a context file that is read into memory, in bytes.
///
/// A context file is prose, and reading one is an allocation that happens before any budget
/// applies — the clip only caps what enters the prompt. So the read itself is capped: a
/// `AGENTS.md` that points at a disk image or a log must not become a startup allocation (`#358`).
const MAX_LAYER_BYTES: u64 = 1 << 20;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Budget {
    /// Truncate a single file past this many characters.
    pub max_file_chars: usize,
    /// Drop whole layers past this total.
    pub total_chars: usize,
}

impl Default for Budget {
    fn default() -> Self {
        Self {
            max_file_chars: DEFAULT_MAX_FILE_CHARS,
            total_chars: DEFAULT_BUDGET_CHARS,
        }
    }
}

/// One context file as it will be injected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layer {
    /// The file's name as the model sees it: `AGENT.md`, `USER.md`, `MEMORY.md`.
    pub name: String,
    pub path: PathBuf,
    /// The text to inject — possibly truncated, and then it says so.
    pub body: String,
    /// Characters kept.
    pub chars: usize,
    /// Characters the file actually has, for `context show` to compare against.
    pub original_chars: usize,
}

impl Layer {
    pub fn truncated(&self) -> bool {
        self.original_chars > self.chars
    }
}

/// Everything gathered for one run, already in injection order.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Context {
    /// `AGENT.md` layers: the global one, then project ones from the outermost (repo root)
    /// to the innermost (the workspace), so the nearest file gets the last word.
    pub instructions: Vec<Layer>,
    pub user: Option<Layer>,
    pub memory: Option<Layer>,
    /// The skills index, after `MEMORY.md`. Absent when there are no skills to list, or when
    /// the budget leaves room for none (and then `skill_notes` says so).
    pub skills: Option<crate::skills::Index>,
    /// What was truncated or dropped, in plain words, for the user and for `context show`.
    pub notes: Vec<String>,
    /// The same for skills: what the index left out, and every skill that is broken. Kept apart
    /// from `notes` because the CLI warns about these when it starts, and a dropped context
    /// file is not something it has ever warned about.
    pub skill_notes: Vec<String>,
    /// The standing instructions that go straight after the configured prompt (`#244`), resolved
    /// for the model in force. Empty when `[agent] prompt_blocks = "off"` or no gate matched —
    /// which is exactly "send only the prompt and these files", the issue's own wording.
    pub guidance: String,
}

impl Context {
    /// Resolve the standing blocks for the model in force (`#244`).
    ///
    /// `[provider] model` is what a request will name, and it is read here rather than passed in
    /// because every caller of [`for_config`] is asking the same question: what does *this*
    /// configuration put in front of the model.
    fn with_guidance(mut self, cfg: &crate::config::Config) -> Self {
        self.guidance = cfg.agent.prompt_blocks.guidance(&cfg.provider.model);
        self
    }

    /// Every layer that survived the budget, in injection order.
    pub fn layers(&self) -> impl Iterator<Item = &Layer> {
        self.instructions
            .iter()
            .chain(self.user.iter())
            .chain(self.memory.iter())
    }

    pub fn total_chars(&self) -> usize {
        self.layers().map(|l| l.chars).sum()
    }

    pub fn is_empty(&self) -> bool {
        self.layers().next().is_none() && self.skills.is_none()
    }

    /// Add the skills index for `report`, within `budget` characters (0 = no cap).
    pub fn with_skills(mut self, report: &crate::skills::Report, budget: usize) -> Self {
        let (index, notes) = crate::skills::index(report, budget);
        self.skills = index;
        self.skill_notes = notes;
        self
    }
}

/// Where the files may be found. Separate from [`Config`](crate::config::Config) so the
/// discovery rules can be tested without a config file on disk.
pub struct Sources<'a> {
    /// The config directory: holds the global `AGENT.md`.
    pub config_dir: Option<&'a Path>,
    /// Where `USER.md` / `MEMORY.md` live (the profile's directory).
    pub profile_dir: Option<&'a Path>,
    /// Where the agent was started: the project walk begins here.
    pub workspace: &'a Path,
    /// Never walk above this directory.
    pub home: Option<&'a Path>,
    /// File names, so a profile can point at different ones.
    pub user_file: &'a str,
    pub memory_file: &'a str,
}

/// Gather every context file for a run.
pub fn gather(sources: &Sources<'_>, budget: Budget) -> Context {
    let mut ctx = Context::default();

    if let Some(dir) = sources.config_dir {
        if let Some(path) = context_file_in(dir) {
            let name = layer_name(&path);
            push_layer(
                &mut ctx.instructions,
                &name,
                path,
                None,
                budget,
                &mut ctx.notes,
            );
        }
    }
    // A project file is read only from inside the tree the walk covered: the same boundary
    // `read_file` enforces, so a repository cannot use a symlink to put something else into the
    // system prompt (`#358`). The profile's own files above and below may still be links — they
    // are the operator's, not a clone's.
    let (project, root) = project_walk(sources.workspace, sources.home);
    for path in project {
        let name = layer_name(&path);
        push_layer(
            &mut ctx.instructions,
            &name,
            path,
            Some(&root),
            budget,
            &mut ctx.notes,
        );
    }
    if let Some(dir) = sources.profile_dir {
        ctx.user = read_layer(
            sources.user_file,
            dir.join(sources.user_file),
            None,
            budget,
            &mut ctx.notes,
        );
        ctx.memory = read_layer(
            sources.memory_file,
            dir.join(sources.memory_file),
            None,
            budget,
            &mut ctx.notes,
        )
        .map(render_memory);
    }
    apply_total(&mut ctx, budget.total_chars);
    ctx
}

/// The `AGENT.md` files between the workspace and its repository root (or `$HOME`),
/// outermost first so the nearest one can override.
///
/// Stops *after* the directory that holds `.git` — that directory is the repo root and its
/// file belongs to the project. Stops at `$HOME` without going above it. Both
/// `AGENT.md` and `.eclipse/AGENT.md` count; `AGENT.md` wins when both exist.
pub fn project_files(workspace: &Path, home: Option<&Path>) -> Vec<PathBuf> {
    project_walk(workspace, home).0
}

/// [`project_files`], plus the directory the walk stopped at.
///
/// That directory is the boundary for a project layer: a symlink is followed only when its target
/// stays inside this tree, which is the rule `read_file`'s `confine` already applies (`#358`).
pub fn project_walk(workspace: &Path, home: Option<&Path>) -> (Vec<PathBuf>, PathBuf) {
    let home = home.and_then(|h| std::fs::canonicalize(h).ok().or(Some(h.to_path_buf())));
    let mut dir = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
    let mut found: Vec<PathBuf> = Vec::new();
    for _ in 0..MAX_WALK {
        if let Some(path) = agent_file_in(&dir) {
            found.push(path);
        }
        // A repository root is the top of the project: include it, then stop.
        if dir.join(".git").exists() {
            break;
        }
        let Some(parent) = dir.parent() else { break };
        // Never above `$HOME`. Written as `starts_with`, not `==`: a workspace that is not under
        // `$HOME` at all (a mount, a sandbox, a sibling tree) never equals it, and equality let the
        // walk climb to `/`, collecting the `AGENT.md` of every unrelated project on the way. The
        // guard sits on the step *down* the tree, so a workspace outside `$HOME` still contributes
        // its own file before the walk stops.
        if let Some(ref home) = home {
            if !parent.starts_with(home) {
                break;
            }
        }
        dir = parent.to_path_buf();
    }
    found.reverse();
    // `dir` is canonical by construction whenever the workspace could be resolved; resolve it
    // again so a workspace that could not be is compared against a real path rather than a
    // lexical one that no layer would ever live under.
    let top = std::fs::canonicalize(&dir).unwrap_or(dir);
    (found, top)
}

fn agent_file_in(dir: &Path) -> Option<PathBuf> {
    // `AGENT.md` is the documented name and wins over the alias; the dotted copy wins over the
    // plain alias, because `.eclipse/` is this program's own shelf. `AGENTS.md` is the plural most
    // people arrive with (it is what Codex and Cursor read) and it is read as a fallback: a file
    // that exists and is silently ignored is the worse failure of the two.
    [
        dir.join("AGENT.md"),
        dir.join(".eclipse").join("AGENT.md"),
        dir.join("AGENTS.md"),
        dir.join(".eclipse").join("AGENTS.md"),
    ]
    .into_iter()
    .find(|candidate| candidate.is_file())
}

/// The config directory's copy: `AGENT.md`, or `AGENTS.md` beside it. No `.eclipse/` here — the
/// config directory *is* the shelf.
fn context_file_in(dir: &Path) -> Option<PathBuf> {
    ["AGENT.md", "AGENTS.md"]
        .iter()
        .map(|name| dir.join(*name))
        .find(|path| path.is_file())
}

/// What the prompt calls this layer: the name the file actually has, so an alias is not reported
/// as the file it is standing in for.
fn layer_name(path: &Path) -> String {
    path.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "AGENT.md".to_string())
}

/// Inject `MEMORY.md` as a readable list rather than as the file it is stored in: `§` on its
/// own line is a storage detail, and a model reading `§` between facts is a model reading
/// noise. Multi-line entries keep their shape under a hanging indent.
fn render_memory(layer: Layer) -> Layer {
    let entries = crate::memory::parse(&layer.body);
    let body = entries
        .iter()
        .map(|entry| {
            let mut lines = entry.lines();
            let mut out = format!("- {}", lines.next().unwrap_or("").trim());
            for line in lines {
                out.push_str("\n  ");
                out.push_str(line.trim());
            }
            out
        })
        .collect::<Vec<_>>()
        .join("\n");
    Layer {
        chars: body.chars().count(),
        original_chars: layer.original_chars,
        body,
        ..layer
    }
}

fn push_layer(
    into: &mut Vec<Layer>,
    name: &str,
    path: PathBuf,
    boundary: Option<&Path>,
    budget: Budget,
    notes: &mut Vec<String>,
) {
    if let Some(layer) = read_layer(name, path, boundary, budget, notes) {
        into.push(layer);
    }
}

/// Read one context file, or say in `notes` why it was not read.
///
/// `boundary` is the tree a symlink's target has to stay inside. Project layers pass the top of the
/// walk; the operator's own files (the global `AGENT.md`, `USER.md`, `MEMORY.md`) pass `None` and may
/// point anywhere, because those are not files a cloned repository gets to write (`#358`).
///
/// Three refusals, all of them before anything is allocated:
///
/// - a target that is not a regular file — a FIFO would block startup forever, a device or a
///   directory is not prose;
/// - a symlink that resolves outside the boundary — `AGENTS.md -> ~/.ssh/id_rsa` in a repository
///   would otherwise put a key in the system prompt, with no tool call for an approval, hook or
///   redaction rule to stop;
/// - anything past [`MAX_LAYER_BYTES`], which is read no further than the cap and said so.
fn read_layer(
    name: &str,
    path: PathBuf,
    boundary: Option<&Path>,
    budget: Budget,
    notes: &mut Vec<String>,
) -> Option<Layer> {
    let shown = path.display().to_string();
    // `metadata` follows a link; `symlink_metadata` would describe the link itself. What is wanted
    // is "wherever this ends up, is it a file", because the check is about reading, not about links.
    match std::fs::metadata(&path) {
        Ok(meta) if meta.is_file() => {}
        Ok(_) => {
            notes.push(format!("{name} at {shown} is not a regular file; not read"));
            return None;
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
        Err(e) => {
            notes.push(format!("{name} at {shown} could not be read: {e}"));
            return None;
        }
    }
    // `repo/sub/../../home/...` in a prompt label helps nobody: use the real path.
    let path = std::fs::canonicalize(&path).unwrap_or(path);
    if let Some(root) = boundary {
        if !path.starts_with(root) {
            notes.push(format!(
                "{name} at {shown} points outside the project ({}); not read",
                path.display()
            ));
            return None;
        }
    }
    let raw = read_capped(&path, name, notes)?;
    let original = raw.chars().count();
    if raw.trim().is_empty() {
        return None; // an empty file contributes nothing; do not print an empty section
    }
    let body = clip(&raw, budget.max_file_chars);
    let chars = body.chars().count();
    Some(Layer {
        name: name.to_string(),
        path,
        body,
        chars,
        original_chars: original,
    })
}

/// The file's text, up to [`MAX_LAYER_BYTES`].
///
/// `take` is what bounds the allocation: the clip in [`clip`] runs on the string this returns, so
/// without a cap the whole file is in memory before a single character is budgeted. A cut in the
/// middle of a character is this function's own doing and is dropped; a malformed byte anywhere else
/// means the file is not text, which is how a context file has always been refused.
fn read_capped(path: &Path, name: &str, notes: &mut Vec<String>) -> Option<String> {
    let file = std::fs::File::open(path).ok()?;
    let mut bytes = Vec::new();
    file.take(MAX_LAYER_BYTES + 1)
        .read_to_end(&mut bytes)
        .ok()?;
    let cut = bytes.len() as u64 > MAX_LAYER_BYTES;
    if cut {
        bytes.truncate(MAX_LAYER_BYTES as usize);
    }
    let text = match String::from_utf8(bytes) {
        Ok(text) => text,
        Err(e) => {
            if !cut || e.utf8_error().error_len().is_some() {
                return None;
            }
            let valid = e.utf8_error().valid_up_to();
            let bytes = e.into_bytes();
            String::from_utf8_lossy(&bytes[..valid]).into_owned()
        }
    };
    if cut {
        notes.push(format!(
            "{name} is larger than {} KB and was read only to that point",
            MAX_LAYER_BYTES / 1024
        ));
    }
    Some(text)
}

/// Head and tail, with a marker in the middle saying how much went. Never silent, never
/// cutting a multi-byte character in half, and never longer than `max` **including** the
/// marker — a cap that the marker itself pushes past is not a cap.
fn clip(text: &str, max: usize) -> String {
    let total = text.chars().count();
    if total <= max || max == 0 {
        return text.to_string();
    }
    let full = |removed: usize| format!("\n\n[… truncated: {removed} chars …]\n\n");
    // When the cap is smaller than a sentence, say it in as few characters as possible — a
    // stub that names the count beats a stub that says nothing.
    let tight = format!("[…{total}c…]");
    let mut room = max.saturating_sub(full(total).chars().count());
    if room < 12 {
        return if tight.chars().count() <= max {
            tight
        } else {
            tight.chars().take(max).collect()
        };
    }
    // The marker's own length depends on the number it prints, which depends on how much is
    // kept: one pass to guess, then a pass that is computed from the real marker.
    loop {
        let head_budget = room / 2;
        let tail_budget = room - head_budget;
        let removed = total.saturating_sub(head_budget + tail_budget);
        let marker = full(removed);
        let fits = head_budget + tail_budget + marker.chars().count();
        if fits <= max {
            let head: String = text.chars().take(head_budget).collect();
            let tail: String = text
                .chars()
                .rev()
                .take(tail_budget)
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            return format!("{head}{marker}{tail}");
        }
        let next = max.saturating_sub(marker.chars().count() + 1);
        if next >= room {
            return tight;
        }
        room = next;
    }
}

/// Keep the total under `total`, cheapest first.
///
/// The drop order is the injection order reversed: the broadest `AGENT.md` goes first, then
/// the narrower ones, then `MEMORY.md`, then `USER.md`. The last file is **clipped to whatever
/// is left** rather than dropped — a 9000-character `USER.md` losing its tail is recoverable,
/// an agent that no longer knows who it is talking to is not. Nothing is dropped or cut
/// silently: every decision lands in `notes`.
fn apply_total(ctx: &mut Context, total: usize) {
    if total == 0 || ctx.total_chars() <= total {
        return;
    }
    let mut notes = Vec::new();
    while ctx.total_chars() > total && !ctx.instructions.is_empty() {
        let layer = ctx.instructions.remove(0);
        notes.push(dropped(&layer, total));
    }
    if ctx.total_chars() > total {
        if let Some(layer) = ctx.memory.take() {
            notes.push(dropped(&layer, total));
        }
    }
    if ctx.total_chars() > total {
        if let Some(mut layer) = ctx.user.take() {
            let left = total.saturating_sub(ctx.total_chars());
            if left >= MIN_CLIP {
                let body = clip(&layer.body, left);
                notes.push(format!(
                    "clipped {} to {left} chars to fit the {total} char budget",
                    layer.path.display()
                ));
                layer.chars = body.chars().count();
                layer.body = body;
                ctx.user = Some(layer);
            } else {
                notes.push(dropped(&layer, total));
            }
        }
    }
    ctx.notes.extend(notes);
}

fn dropped(layer: &Layer, total: usize) -> String {
    format!(
        "dropped {} ({} chars): over the {total} char budget",
        layer.path.display(),
        layer.chars
    )
}

/// Gather the context files and the skills index this configuration describes — the one entry
/// point both the runtime and `eclipse context show` use, so what the CLI prints is what gets
/// injected. `plugins` is what loaded: a plugin's own skills are part of the index.
pub fn for_config(
    cfg: &crate::config::Config,
    env: crate::config::EnvFn,
    plugins: &crate::plugins::Plugins,
) -> Context {
    for_config_with(cfg, env, plugins, None)
}

/// [`for_config`], with the skills index narrowed to `only` when it is set (`#509`).
///
/// The index is what a bot *sees it can ask for*; the `skill_*` tools read the same filter, so a
/// skill that is absent from the index is also refused by name. `None` is every root's skill.
pub fn for_config_with(
    cfg: &crate::config::Config,
    env: crate::config::EnvFn,
    plugins: &crate::plugins::Plugins,
    only: Option<&[String]>,
) -> Context {
    let workspace = cfg.workspace_root(env);
    let ctx = gather_for(cfg, env);
    let report = crate::skills::discover_only(
        &crate::skills::roots_for(cfg, env, plugins, &workspace),
        only,
    );
    ctx.with_skills(&report, cfg.skills.index_budget_chars)
}

/// The file layers alone, with the budget this configuration asks for — the half of
/// [`for_config`] that reads the three files and nothing else. The dashboard's context editor
/// (#268) uses it directly: it edits what is injected, so it has to see what is injected.
fn gather_for(cfg: &crate::config::Config, env: crate::config::EnvFn) -> Context {
    let workspace = cfg.workspace_root(env);
    // AGENT.md, USER.md and MEMORY.md are one folder: `memory/`. The global one is the profile's
    // own, which for the default profile is the root's — one rule instead of two.
    let config_root = cfg.memory_dir(env);
    let profile_dir = config_root.clone();
    let home = cfg.home(env);
    let sources = Sources {
        config_dir: config_root.as_deref(),
        profile_dir: profile_dir.as_deref(),
        workspace: &workspace,
        home: home.as_deref(),
        user_file: &cfg.user.file,
        memory_file: &cfg.user.memory_file,
    };
    gather(
        &sources,
        Budget {
            max_file_chars: cfg.agent.context_file_max_chars,
            total_chars: cfg.agent.context_files_budget_chars,
        },
    )
    .with_guidance(cfg)
}

/// Which of the three files a request means. A fixed set, never a path: the dashboard cannot ask
/// for a file the loader would not inject, and there is no way to spell `../../.ssh/id_rsa` here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Which {
    /// `AGENT.md` — the file this workspace injects last, or the profile's own when it has none.
    Agent,
    /// `USER.md`.
    User,
    /// `MEMORY.md`, whose writer is [`crate::memory::Memory`].
    Memory,
}

impl Which {
    /// The id a request uses. Deliberately not the file name: `AGENT.md` can be `AGENTS.md` or
    /// `.eclipse/AGENT.md` on disk, and a request that names a file is a request that can name
    /// another one.
    pub fn id(self) -> &'static str {
        match self {
            Which::Agent => "agent",
            Which::User => "user",
            Which::Memory => "memory",
        }
    }

    pub fn from_id(id: &str) -> Option<Self> {
        match id {
            "agent" => Some(Which::Agent),
            "user" => Some(Which::User),
            "memory" => Some(Which::Memory),
            _ => None,
        }
    }
}

/// One of the three files, as the dashboard's editor needs it: where it is, what is in it, what the
/// prompt will do with it, and the budget it is measured against.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Editable {
    pub which: Which,
    /// What the file is called on disk — `AGENT.md`, or the alias it is actually standing in for.
    pub file: String,
    /// The resolved path. Canonicalised when the file exists; a prediction when it does not, so the
    /// first save has somewhere to go.
    pub path: PathBuf,
    pub exists: bool,
    /// The text as stored. For `MEMORY.md` that is the `§`-separated file, not the rendered list:
    /// the editor shows what the writer wrote.
    pub text: String,
    /// Characters in the file.
    pub chars: usize,
    /// Characters the prompt will keep — below `chars` when the file is being clipped right now.
    pub kept: usize,
    /// The per-file ceiling (`agent.context_file_max_chars`); 0 when there is none.
    pub max_chars: usize,
    /// `MEMORY.md`'s own ceiling, which its writer refuses past rather than clipping. `None` for the
    /// two prose files, which have no such thing.
    pub own_budget: Option<usize>,
    /// Every file layer as it will be injected, and the ceiling for all of them together.
    pub total: usize,
    pub total_budget: usize,
    /// Where this file sits in the drop order, 1-based, among the layers that survived.
    pub position: Option<usize>,
    /// How many *other* `AGENT.md` layers are also injected above this one.
    pub others: usize,
}

impl Editable {
    pub fn truncated(&self) -> bool {
        self.kept < self.chars
    }
}

/// The three files, resolved by the loader's own discovery, with what the prompt does with them.
///
/// This is the only way the dashboard learns a path: `Which` is a closed set and the discovery walks
/// the same tree [`for_config`] walks, so the page can edit exactly what would be injected and
/// nothing else. A file that does not exist yet is reported with where it *would* be created —
/// `AGENT.md` in the profile's `memory/` when this workspace has none, `USER.md` and `MEMORY.md`
/// beside it.
pub fn editable(cfg: &crate::config::Config, env: crate::config::EnvFn) -> Vec<Editable> {
    let ctx = gather_for(cfg, env);
    let total = ctx.total_chars();
    let total_budget = cfg.agent.context_files_budget_chars;
    let max_chars = cfg.agent.context_file_max_chars;
    let dir = cfg.memory_dir(env);

    let layers: Vec<&Layer> = ctx.layers().collect();
    let position_of = |path: &Path| layers.iter().position(|l| l.path == path).map(|i| i + 1);

    let workspace = cfg.workspace_root(env);
    // The walk's own boundary, which is the rule `gather` confines a project layer to (`#358`) —
    // and the editor used to skip it (`#559`). A cloned repository whose `AGENT.md` is a symlink to
    // `~/.ssh/id_rsa` was refused by the prompt and served here in full, then written through on
    // save. `project_walk` already answers "where did the walk stop", so this is the loader's rule
    // and not a second one that could drift. A link that resolves inside the tree — the dotfiles
    // shape — is still offered.
    let (project, boundary) = project_walk(&workspace, cfg.home(env).as_deref());
    let project: Vec<PathBuf> = project
        .into_iter()
        .filter(|path| canonical_or(path).starts_with(&boundary))
        .collect();

    let mut rows = Vec::new();

    // `AGENT.md`: the nearest one this workspace injects, because it gets the last word and is
    // therefore the one a person means. With none in the tree, the profile's own — which the first
    // save creates, and which the prompt reads first.
    let agent = project
        .last()
        .cloned()
        .or_else(|| Some(dir.as_ref()?.join("AGENT.md")));
    if let Some(path) = agent {
        let layer = layers.iter().find(|l| l.path == canonical_or(&path));
        // How many *other* `AGENT.md` layers ride above this one: the global file, and any wider
        // workspace file. Not every layer — `USER.md` and `MEMORY.md` come after and are not this
        // file's business.
        let agents = layers
            .iter()
            .filter(|l| l.name.starts_with("AGENT"))
            .count();
        let others = agents.saturating_sub(usize::from(layer.is_some()));
        rows.push(row_from(
            Which::Agent,
            path,
            layer.copied(),
            max_chars,
            None,
            total,
            total_budget,
            position_of,
            others,
        ));
    }
    if let Some(dir) = dir.as_deref() {
        for (which, file, own_budget) in [
            (Which::User, cfg.user.file.clone(), None),
            (
                Which::Memory,
                cfg.user.memory_file.clone(),
                Some(cfg.user.memory_budget_chars),
            ),
        ] {
            let path = dir.join(&file);
            let layer = layers.iter().find(|l| l.path == canonical_or(&path));
            rows.push(row_from(
                which,
                path,
                layer.copied(),
                max_chars,
                own_budget,
                total,
                total_budget,
                position_of,
                0,
            ));
        }
    }
    rows
}

#[allow(clippy::too_many_arguments)]
fn row_from(
    which: Which,
    path: PathBuf,
    layer: Option<&Layer>,
    max_chars: usize,
    own_budget: Option<usize>,
    total: usize,
    total_budget: usize,
    position_of: impl Fn(&Path) -> Option<usize>,
    others: usize,
) -> Editable {
    let canonical = canonical_or(&path);
    let text = std::fs::read_to_string(&canonical).unwrap_or_default();
    let chars = text.chars().count();
    let kept = layer.map_or(chars, |l| l.chars);
    Editable {
        which,
        position: position_of(&canonical),
        file: path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| format!("{}.md", which.id())),
        exists: canonical.is_file(),
        chars,
        kept,
        max_chars,
        own_budget,
        total,
        total_budget,
        others,
        path: canonical,
        text,
    }
}

fn canonical_or(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

/// Write one of the three, then answer with the file as it now stands.
///
/// The two prose files go through [`crate::memory::write_file_atomically`] — temp in the same
/// directory, then rename. `MEMORY.md` goes through [`crate::memory::Memory`], because that type
/// owns its lock and its budget: a third writer with its own `fs::write` would be a writer the
/// `memory` tool cannot see, and the lock would be theatre.
///
/// `text` is stored as given. For `MEMORY.md` that means the `§`-separated file the page was shown;
/// it is parsed and re-rendered by the same functions the tool uses, so a save cannot invent a
/// separator style of its own.
pub fn write_file(
    cfg: &crate::config::Config,
    env: crate::config::EnvFn,
    which: Which,
    text: &str,
) -> crate::error::Result<Editable> {
    let Some(row) = editable(cfg, env).into_iter().find(|r| r.which == which) else {
        return Err(crate::error::Error::Config(format!(
            "this configuration has no {} file to write",
            which.id()
        )));
    };
    match which {
        Which::Memory => {
            let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
            if let crate::memory::Outcome::Full {
                chars,
                budget,
                entries,
            } = memory.replace(crate::memory::parse(text))?
            {
                return Err(crate::error::Error::Config(format!(
                    "{} would be {chars} chars and its budget is {budget}; it holds {} entr{} now — \
                     remove or shorten one here instead",
                    row.file,
                    entries.len(),
                    if entries.len() == 1 { "y" } else { "ies" }
                )));
            }
        }
        Which::Agent | Which::User => {
            crate::atomic::write_file_atomically(&row.path, text)
                .map_err(|e| crate::error::Error::io(&row.path, e))?;
        }
    }
    let after = editable(cfg, env);
    after.into_iter().find(|r| r.which == which).ok_or_else(|| {
        crate::error::Error::Config("the file vanished while it was being written".into())
    })
}

/// The system prompt: the configured base, then the instruction files, then plugin prompt
/// fragments, then the user model, then memory, then the skills index.
///
/// Every file layer is labelled `## <file> (<path>)` so the model can tell a project rule
/// from a global one, and so a bad rule is traceable to the path it came from.
pub fn assemble(base: &str, ctx: &Context, fragments: &[String]) -> String {
    let mut parts: Vec<String> = Vec::new();
    let base = base.trim();
    if !base.is_empty() {
        parts.push(base.to_string());
    }
    // The standing blocks (`#244`) come first, right after the configured sentence: they are how to
    // behave, and the files after them are what to know. `off` leaves this empty and the prompt is
    // then the sentence plus the files, which is what it was before they existed.
    let guidance = ctx.guidance.trim();
    if !guidance.is_empty() {
        parts.push(guidance.to_string());
    }
    for layer in &ctx.instructions {
        parts.push(labelled(layer));
    }
    for fragment in fragments {
        let fragment = fragment.trim();
        if !fragment.is_empty() {
            parts.push(fragment.to_string());
        }
    }
    if let Some(user) = &ctx.user {
        parts.push(labelled(user));
    }
    if let Some(memory) = &ctx.memory {
        parts.push(labelled(memory));
    }
    if let Some(skills) = &ctx.skills {
        // No path in the label: the index is drawn from several directories, and each entry's
        // origin is one `skill_view` away.
        parts.push(format!("## Skills\n\n{}", skills.body));
    }
    parts.join("\n\n")
}

fn labelled(layer: &Layer) -> String {
    format!(
        "## {} ({})\n\n{}",
        layer.name,
        layer.path.display(),
        layer.body.trim_end()
    )
}

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

    fn write(path: &Path, body: &str) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, body).unwrap();
    }

    /// Config, profile and workspace directories under one temp dir, all present.
    fn three(
        tmp: &tempfile::TempDir,
    ) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
        let config = tmp.path().join("config");
        let profile = tmp.path().join("profile");
        let workspace = tmp.path().join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        (config, profile, workspace)
    }

    fn sources<'a>(config: &'a Path, profile: &'a Path, workspace: &'a Path) -> Sources<'a> {
        Sources {
            config_dir: Some(config),
            profile_dir: Some(profile),
            workspace,
            home: None,
            user_file: "USER.md",
            memory_file: "MEMORY.md",
        }
    }

    /// A config that points at `home`, with the workspace under it — the shape the dashboard's
    /// editor resolves against (#268).
    fn cfg_in(home: &Path, workspace: &Path) -> crate::config::Config {
        let mut cfg = crate::config::Config::default();
        cfg.tools.workspace_root = Some(workspace.to_path_buf());
        cfg.profile = None;
        let _ = home;
        cfg
    }

    /// `HOME` only, so the config directory is `<home>/.eclipse` and the three files are in
    /// `<home>/.eclipse/memory`.
    fn home_env(home: &Path) -> impl Fn(&str) -> Option<String> + '_ {
        move |key: &str| match key {
            "HOME" => Some(home.display().to_string()),
            _ => None,
        }
    }

    /// `#244`: the blocks reach the prompt that is actually assembled — and `off` reaches it as
    /// nothing at all, which is the issue's "send only system_prompt and these files".
    #[test]
    fn the_standing_blocks_reach_the_assembled_prompt_and_off_removes_them() {
        use crate::prompt_blocks::Choice;

        let plugins = crate::plugins::Plugins::default();
        let mut cfg = crate::config::Config::default();
        cfg.provider.model = "gpt-oss:120b".into();
        // No environment at all: this is about the prompt, not about where the files live.
        let env: crate::config::EnvFn = &|_: &str| None;

        let on = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
        assert!(
            on.contains("you are eclipse"),
            "the configured sentence survives: {on}"
        );
        assert!(
            on.contains("## task-completion") && on.contains("## execution-guidance"),
            "the gated blocks are in the prompt: {on}"
        );

        cfg.agent.prompt_blocks = Choice::Off;
        let off = assemble("you are eclipse", &for_config(&cfg, env, &plugins), &[]);
        assert_eq!(
            off.trim(),
            "you are eclipse",
            "off leaves the sentence and nothing else"
        );
    }

    #[test]
    fn the_three_files_are_found_with_their_budgets_and_the_missing_ones_are_predicted() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let workspace = home.join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let memory = home.join(".eclipse/memory");
        write(&memory.join("USER.md"), "USER FACT: one line");
        write(&memory.join("MEMORY.md"), "first fact\n§\nsecond fact");

        let cfg = cfg_in(home, &workspace);
        let env = home_env(home);
        let rows = editable(&cfg, &env);
        assert_eq!(rows.len(), 3, "{rows:#?}");
        assert_eq!(
            rows.iter().map(|r| r.which.id()).collect::<Vec<_>>(),
            vec!["agent", "user", "memory"]
        );

        let agent = &rows[0];
        // No `AGENT.md` in the tree, so the row promises where a save would create it — beside the
        // other two, in the profile's `memory/`, which is where the prompt reads it.
        assert!(!agent.exists);
        assert_eq!(
            agent.others, 0,
            "the one file this row would create is the only one"
        );
        assert_eq!(agent.path, memory.join("AGENT.md"));
        assert_eq!(agent.text, "");
        assert_eq!(agent.position, None);
        assert_eq!(agent.max_chars, DEFAULT_MAX_FILE_CHARS);
        assert!(
            agent.own_budget.is_none(),
            "prose files have no budget of their own"
        );

        let user = &rows[1];
        assert!(user.exists);
        assert_eq!(user.chars, "USER FACT: one line".chars().count());
        assert_eq!(user.kept, user.chars, "nothing is clipped");
        assert!(!user.truncated());

        let mem = &rows[2];
        assert_eq!(mem.file, "MEMORY.md");
        assert_eq!(mem.chars, "first fact\n§\nsecond fact".chars().count());
        // The editor shows the file, `§` and all — it is what the writer writes.
        assert!(mem.text.contains('§'));
        assert_eq!(mem.own_budget, Some(crate::memory::DEFAULT_BUDGET_CHARS));
        // Both files are injected, so each has a place in the drop order and neither is a stranger.
        assert_eq!(user.position, Some(1));
        assert_eq!(mem.position, Some(2));
    }

    #[test]
    fn the_nearest_agent_file_is_the_one_to_edit_and_the_wider_ones_are_counted() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let repo = home.join("repo");
        let leaf = repo.join("crates/app");
        std::fs::create_dir_all(repo.join(".git")).unwrap();
        std::fs::create_dir_all(&leaf).unwrap();
        write(&repo.join("AGENT.md"), "REPO RULE");
        write(&leaf.join("AGENT.md"), "LEAF RULE");
        write(&home.join(".eclipse/memory/AGENT.md"), "GLOBAL RULE");

        let cfg = cfg_in(home, &leaf);
        let env = home_env(home);
        let agent = editable(&cfg, &env)
            .into_iter()
            .find(|r| r.which == Which::Agent)
            .unwrap();
        // The one that gets the last word, not the widest one.
        assert_eq!(
            agent.path,
            std::fs::canonicalize(leaf.join("AGENT.md")).unwrap()
        );
        assert_eq!(agent.text, "LEAF RULE");
        // ...and the page can say that two more AGENT.md layers are also injected above it.
        assert_eq!(agent.others, 2);
        assert_eq!(agent.position, Some(3), "global, repo, leaf");
    }

    /// A cloned repository is untrusted input, and the editor is a second reader of the very file
    /// the prompt confines: `AGENT.md -> ~/.ssh/id_rsa` was refused by `gather` and served in full
    /// by the dashboard, which then wrote through the link on save (`#559`).
    #[test]
    fn a_project_agent_file_that_points_outside_the_tree_is_not_offered_for_editing() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let workspace = home.join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let secret = tmp.path().join("id_rsa");
        write(&secret, "-----BEGIN OPENSSH PRIVATE KEY-----\n");
        std::os::unix::fs::symlink(&secret, workspace.join("AGENT.md")).unwrap();

        let cfg = cfg_in(&home, &workspace);
        let env = home_env(&home);
        let agent = editable(&cfg, &env)
            .into_iter()
            .find(|r| r.which == Which::Agent)
            .expect("the row still exists: it promises the file a save would create");
        assert!(
            !agent.text.contains("PRIVATE KEY"),
            "the key is not served: {:?}",
            agent.text
        );
        // The row is the profile's own file — the one the prompt reads after refusing the project
        // one, and the one a save creates.
        assert_eq!(agent.path, home.join(".eclipse/memory/AGENT.md"));
        assert!(!agent.exists);

        // ...and the save cannot reach the secret either, because the row it writes is that one.
        write_file(&cfg, &env, Which::Agent, "my rules\n").unwrap();
        assert_eq!(
            std::fs::read_to_string(&secret).unwrap(),
            "-----BEGIN OPENSSH PRIVATE KEY-----\n",
            "the key was not written through"
        );
        assert_eq!(
            std::fs::read_to_string(home.join(".eclipse/memory/AGENT.md")).unwrap(),
            "my rules\n"
        );
    }

    /// The boundary is the target's location, not "symlinks are refused": a link to a file inside
    /// the project is the dotfiles shape and stays editable.
    #[test]
    fn a_project_agent_file_that_points_inside_the_tree_is_still_offered() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let workspace = home.join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        write(&workspace.join("docs/conventions.md"), "run make\n");
        std::os::unix::fs::symlink(
            workspace.join("docs/conventions.md"),
            workspace.join("AGENT.md"),
        )
        .unwrap();

        let cfg = cfg_in(&home, &workspace);
        let env = home_env(&home);
        let agent = editable(&cfg, &env)
            .into_iter()
            .find(|r| r.which == Which::Agent)
            .unwrap();
        assert_eq!(agent.text, "run make\n");
        assert_eq!(
            agent.path,
            std::fs::canonicalize(workspace.join("docs/conventions.md")).unwrap()
        );
    }

    #[test]
    fn a_file_past_the_per_file_ceiling_is_reported_as_clipped() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let workspace = home.join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let memory = home.join(".eclipse/memory");
        write(&memory.join("USER.md"), &"x".repeat(200));

        let mut cfg = cfg_in(home, &workspace);
        cfg.agent.context_file_max_chars = 100;
        let env = home_env(home);
        let user = editable(&cfg, &env)
            .into_iter()
            .find(|r| r.which == Which::User)
            .unwrap();
        assert_eq!(user.chars, 200);
        assert!(
            user.kept < user.chars,
            "the prompt keeps less than the file"
        );
        assert!(user.truncated());
        // The page has to be able to say this before the save, not after it.
        assert_eq!(user.max_chars, 100);
    }

    #[test]
    fn a_save_creates_the_file_it_promised_and_leaves_no_temp_behind() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let workspace = home.join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let cfg = cfg_in(home, &workspace);
        let env = home_env(home);

        let row = write_file(&cfg, &env, Which::Agent, "RULE: one\n").unwrap();
        assert!(
            row.exists,
            "the row it answers with is the file it just created"
        );
        assert_eq!(row.path, home.join(".eclipse/memory/AGENT.md"));
        assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: one\n");
        // Nothing half-written is left in the directory.
        let leftovers: Vec<_> = std::fs::read_dir(home.join(".eclipse/memory"))
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.contains("tmp"))
            .collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");

        // A second save replaces it, rather than appending.
        let row = write_file(&cfg, &env, Which::Agent, "RULE: two\n").unwrap();
        assert_eq!(row.chars, "RULE: two\n".chars().count());
        assert_eq!(std::fs::read_to_string(&row.path).unwrap(), "RULE: two\n");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&row.path).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode, 0o600, "a file the page created is not world-readable");
        }
    }

    #[test]
    fn a_memory_save_goes_through_the_memory_writer_and_is_refused_past_its_budget() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let workspace = home.join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let cfg = cfg_in(home, &workspace);
        let env = home_env(home);

        // Two entries, in the storage format the page shows.
        let row = write_file(&cfg, &env, Which::Memory, "fact one\n§\nfact two\n").unwrap();
        let entries = crate::memory::parse(&std::fs::read_to_string(&row.path).unwrap());
        assert_eq!(entries, vec!["fact one", "fact two"], "{entries:?}");
        // ...and `eclipse memory list` sees the same thing, because it is the same type.
        let memory = crate::memory::Memory::new(&row.path, cfg.user.memory_budget_chars);
        assert_eq!(memory.read().unwrap().len(), 2);

        let mut small = cfg_in(home, &workspace);
        small.user.memory_budget_chars = 20;
        let err = write_file(&small, &env, Which::Memory, &"y".repeat(200)).unwrap_err();
        let said = err.to_string();
        assert!(said.contains("budget"), "{said}");
        assert!(said.contains("remove or shorten"), "{said}");
        // The refusal left the two entries it found alone.
        assert_eq!(memory.read().unwrap().len(), 2);
    }

    /// `AGENTS.md` is what people type — it is the name Codex and Cursor read — and a file that
    /// exists while the program reads nothing is the worst failure a doc can produce. It is read
    /// as a fallback, under its own name in the prompt label.
    #[test]
    fn the_plural_agents_md_is_read_when_the_singular_is_absent() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        write(&workspace.join("AGENTS.md"), "plural rules\n");

        let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
        let instructions = ctx
            .instructions
            .iter()
            .map(|l| (l.name.as_str(), l.body.as_str()))
            .collect::<Vec<_>>();
        assert!(
            instructions
                .iter()
                .any(|(name, body)| *name == "AGENTS.md" && body.contains("plural rules")),
            "the alias is read and reported under its own name: {instructions:?}"
        );
    }

    /// Both present: the documented name wins, so adding an alias never changes what an existing
    /// install reads.
    #[test]
    fn the_singular_wins_over_the_alias_in_the_same_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        write(&workspace.join("AGENT.md"), "singular rules\n");
        write(&workspace.join("AGENTS.md"), "plural rules\n");

        let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
        let names = ctx
            .instructions
            .iter()
            .map(|l| l.name.clone())
            .collect::<Vec<_>>();
        let bodies = ctx
            .instructions
            .iter()
            .map(|l| l.body.clone())
            .collect::<Vec<_>>();
        assert_eq!(
            names.iter().filter(|n| n.ends_with(".md")).count(),
            names.len()
        );
        assert!(
            !bodies.iter().any(|b| b.contains("plural rules")),
            "one file per directory, and it is the singular: {bodies:?}"
        );
    }

    /// `.eclipse/` is this program's own shelf, so its singular still beats a plain alias — the
    /// alias is a fallback, not a new precedence rule.
    #[test]
    fn the_dotted_singular_wins_over_a_plain_alias() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        write(
            &workspace.join(".eclipse").join("AGENT.md"),
            "dotted rules\n",
        );
        write(&workspace.join("AGENTS.md"), "plural rules\n");

        let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
        let bodies = ctx
            .instructions
            .iter()
            .map(|l| l.body.clone())
            .collect::<Vec<_>>();
        assert!(
            bodies.iter().any(|b| b.contains("dotted rules")),
            "{bodies:?}"
        );
        assert!(
            !bodies.iter().any(|b| b.contains("plural rules")),
            "{bodies:?}"
        );
    }

    /// The config directory takes the alias too — that is the copy a fresh install writes.
    #[test]
    fn the_config_directory_accepts_the_alias() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        write(&config.join("AGENTS.md"), "install-wide rules\n");

        let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
        let bodies = ctx
            .instructions
            .iter()
            .map(|l| l.body.clone())
            .collect::<Vec<_>>();
        assert!(
            bodies.iter().any(|b| b.contains("install-wide rules")),
            "{bodies:?}"
        );
    }

    #[test]
    fn a_blank_or_empty_file_contributes_no_section() {
        let tmp = tempfile::tempdir().unwrap();
        let profile = tmp.path().join("profile");
        std::fs::create_dir_all(&profile).unwrap();
        // A seeded-but-unedited MEMORY.md: empty, and no section should be printed for it.
        std::fs::write(profile.join("MEMORY.md"), "").unwrap();
        // A blank USER.md: whitespace-only counts as empty too.
        std::fs::write(profile.join("USER.md"), "\n  \n\t\n").unwrap();
        let workspace = profile.clone();
        let sources = Sources {
            config_dir: Some(&profile),
            profile_dir: Some(&profile),
            workspace: &workspace,
            home: None,
            user_file: "USER.md",
            memory_file: "MEMORY.md",
        };
        let ctx = gather(
            &sources,
            Budget {
                max_file_chars: 6000,
                total_chars: 12000,
            },
        );
        assert!(
            ctx.user.is_none(),
            "a whitespace-only USER.md is not a layer"
        );
        assert!(ctx.memory.is_none(), "an empty MEMORY.md is not a layer");
        assert!(ctx.is_empty(), "nothing to inject: {ctx:?}");
    }

    #[test]
    fn a_project_file_is_found_from_a_subdirectory_up_to_the_repository_root() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write(&root.join(".git/HEAD"), "ref: refs/heads/main");
        write(&root.join("AGENT.md"), "repo rules");
        write(&root.join("sub/deeper/AGENT.md"), "leaf rules");
        let workspace = root.join("sub/deeper");

        let found = project_files(&workspace, None);
        let names: Vec<_> = found
            .iter()
            .map(|p| p.strip_prefix(root).unwrap().to_string_lossy().to_string())
            .collect();
        assert_eq!(
            names,
            ["AGENT.md", "sub/deeper/AGENT.md"],
            "outermost first, so the nearest file has the last word"
        );
    }

    #[test]
    fn walking_up_stops_at_the_home_boundary_instead_of_reaching_root() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let deep = home.join("work/proj");
        std::fs::create_dir_all(&deep).unwrap();
        write(&home.join("AGENT.md"), "home rules");
        write(&deep.join("AGENT.md"), "project rules");

        let found = project_files(&deep, Some(&home));
        assert_eq!(found.len(), 2, "{found:?}");
        // ...and nothing above $HOME was picked up (a file there is ignored).
        write(&tmp.path().join("AGENT.md"), "above home");
        let found = project_files(&deep, Some(&home));
        assert_eq!(found.len(), 2, "{found:?}");
        assert!(found.iter().all(|p| p.starts_with(&home)));
        // A directory that is not under `home` at all: the walk must stop there. Comparing for
        // equality with `home` never fires in that case, and the loop used to climb to `/`,
        // collecting the `AGENT.md` of every unrelated project above the workspace.
        let elsewhere = tmp.path().join("elsewhere/a/b/proj");
        std::fs::create_dir_all(&elsewhere).unwrap();
        write(
            &tmp.path().join("elsewhere/AGENT.md"),
            "an unrelated project",
        );
        write(
            &tmp.path().join("elsewhere/a/AGENT.md"),
            "another unrelated project",
        );
        write(&elsewhere.join("AGENT.md"), "project rules");
        assert_eq!(
            project_files(&elsewhere, Some(&home)),
            [elsewhere.join("AGENT.md")],
            "the workspace's own file, and nothing from the trees above it"
        );
    }

    #[test]
    fn a_dot_eclipse_file_is_used_when_there_is_no_agent_md() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write(&root.join(".git/HEAD"), "ref: refs/heads/main");
        write(&root.join(".eclipse/AGENT.md"), "hidden rules");
        let found = project_files(root, None);
        assert_eq!(found, [root.join(".eclipse/AGENT.md")]);
    }

    #[test]
    fn a_plain_agent_md_wins_over_the_hidden_one() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write(&root.join(".git/HEAD"), "ref: refs/heads/main");
        write(&root.join(".eclipse/AGENT.md"), "hidden rules");
        write(&root.join("AGENT.md"), "visible rules");
        assert_eq!(project_files(root, None), [root.join("AGENT.md")]);
    }

    #[test]
    fn every_file_kind_lands_in_its_layer_and_in_injection_order() {
        let tmp = tempfile::tempdir().unwrap();
        let config = tmp.path().join("config");
        let profile = config.join("profiles/work");
        let repo = tmp.path().join("repo");
        write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
        write(&config.join("AGENT.md"), "global rules");
        write(&repo.join("AGENT.md"), "repo rules");
        write(&profile.join("USER.md"), "I am Max, be direct");
        write(&profile.join("MEMORY.md"), "the fleet is two servers");
        let workspace = repo.join("crates");

        let ctx = gather(&sources(&config, &profile, &workspace), Budget::default());
        assert_eq!(ctx.instructions.len(), 2);
        assert!(
            ctx.instructions[0].path.starts_with(&config),
            "global first"
        );
        assert!(ctx.instructions[1].path.starts_with(&repo), "then project");
        assert_eq!(ctx.user.as_ref().unwrap().body, "I am Max, be direct");
        // Memory is injected as a list: `§` is how the file stores entries, not how a model
        // should have to read them.
        assert_eq!(
            ctx.memory.as_ref().unwrap().body,
            "- the fleet is two servers"
        );

        let prompt = assemble("You are Eclipse.", &ctx, &["plugin says hi".into()]);
        let order: Vec<&str> = [
            "You are Eclipse.",
            "global rules",
            "repo rules",
            "plugin says hi",
            "I am Max, be direct",
            "the fleet is two servers",
        ]
        .to_vec();
        let mut at = 0;
        for needle in order {
            let found = prompt[at..]
                .find(needle)
                .unwrap_or_else(|| panic!("{needle:?} missing or out of order in:\n{prompt}"));
            at += found;
        }
        // ...and every file layer is labelled with its own path.
        assert!(prompt.contains("## AGENT.md ("), "{prompt}");
        assert!(prompt.contains("## USER.md ("), "{prompt}");
        assert!(prompt.contains("## MEMORY.md ("), "{prompt}");
    }

    #[test]
    fn a_long_file_keeps_its_head_and_its_tail_and_says_what_went() {
        let tmp = tempfile::tempdir().unwrap();
        let config = tmp.path().join("config");
        let profile = config.join("profiles/default");
        let workspace = tmp.path().join("ws");
        std::fs::create_dir_all(&workspace).unwrap();
        let body = format!("HEAD{}{}TAIL", "x".repeat(500), "y".repeat(500));
        write(&profile.join("USER.md"), &body);

        let budget = Budget {
            max_file_chars: 200,
            total_chars: 10_000,
        };
        let ctx = gather(&sources(&config, &profile, &workspace), budget);
        let user = ctx.user.unwrap();
        assert!(user.truncated());
        assert_eq!(user.original_chars, body.chars().count());
        assert!(user.body.starts_with("HEAD"), "{}", user.body);
        assert!(user.body.ends_with("TAIL"), "{}", user.body);
        assert!(
            user.body.contains("[… truncated:") && user.body.contains("chars …]"),
            "the cut is visible: {}",
            user.body
        );
        assert!(
            user.chars <= 200,
            "the cap includes the marker: {} chars",
            user.chars
        );
    }

    #[test]
    fn the_cap_is_a_hard_cap_marker_included() {
        for max in [60usize, 120, 200, 1000] {
            let text = "x".repeat(5000);
            let out = clip(&text, max);
            assert!(
                out.chars().count() <= max,
                "clip({max}) produced {} chars",
                out.chars().count()
            );
            assert!(out.contains("[… truncated:"), "{out}");
        }
        // Short text is untouched.
        assert_eq!(clip("short", 100), "short");
    }

    #[test]
    fn truncation_never_splits_a_character() {
        let text = "é".repeat(100);
        let clipped = clip(&text, 80);
        assert!(clipped.starts_with("éé"), "{clipped}");
        assert!(clipped.ends_with('é'), "{clipped}");
        assert!(clipped.chars().count() <= 80);
        assert!(clipped.is_char_boundary(clipped.len()));

        // Below the size of the marker itself there is nothing honest to keep: say so rather
        // than silently handing back the whole file or half a character.
        // With a cap smaller than the marker, the count is said in as few characters as
        // possible — but it is still said.
        let cramped = clip(&text, 21);
        assert!(cramped.chars().count() <= 21, "{cramped}");
        assert!(cramped.contains("100"), "{cramped}");
        assert!(!cramped.is_empty() && cramped.is_char_boundary(cramped.len()));
    }

    #[test]
    fn over_the_total_the_broadest_file_goes_first_and_the_drop_is_named() {
        let tmp = tempfile::tempdir().unwrap();
        let config = tmp.path().join("config");
        let profile = config.join("profiles/default");
        let repo = tmp.path().join("repo");
        write(&repo.join(".git/HEAD"), "ref: refs/heads/main");
        write(&config.join("AGENT.md"), &"g".repeat(400));
        write(&repo.join("AGENT.md"), &"r".repeat(400));
        write(&profile.join("USER.md"), "user");
        write(&profile.join("MEMORY.md"), "memory");

        let budget = Budget {
            max_file_chars: 6000,
            total_chars: 900,
        };
        let ctx = gather(&sources(&config, &profile, &repo), budget);
        // 400 + 400 + 4 + 6 = 810, under the cap: nothing dropped.
        assert_eq!(ctx.instructions.len(), 2);
        assert!(ctx.notes.is_empty(), "{:?}", ctx.notes);

        let budget = Budget {
            max_file_chars: 6000,
            total_chars: 500,
        };
        let ctx = gather(&sources(&config, &profile, &repo), budget);
        assert_eq!(ctx.instructions.len(), 1, "the global file went first");
        assert!(ctx.instructions[0].path.starts_with(&repo));
        assert!(ctx.user.is_some() && ctx.memory.is_some());
        assert!(
            ctx.notes
                .iter()
                .any(|n| n.contains("dropped") && n.contains("chars")),
            "{:?}",
            ctx.notes
        );
    }

    #[test]
    fn a_missing_config_directory_is_not_an_error() {
        let workspace = tempfile::tempdir().unwrap();
        let ctx = gather(
            &Sources {
                config_dir: Some(Path::new("/nonexistent/eclipse")),
                profile_dir: Some(Path::new("/nonexistent/eclipse/profiles/default")),
                workspace: workspace.path(),
                home: None,
                user_file: "USER.md",
                memory_file: "MEMORY.md",
            },
            Budget::default(),
        );
        assert!(ctx.is_empty());
        assert_eq!(assemble("base", &ctx, &[]), "base");
    }

    #[test]
    fn the_fragments_sit_between_the_instruction_files_and_the_user_model() {
        let ctx = Context {
            instructions: vec![Layer {
                name: "AGENT.md".into(),
                path: PathBuf::from("/r/AGENT.md"),
                body: "rules".into(),
                chars: 5,
                original_chars: 5,
            }],
            user: Some(Layer {
                name: "USER.md".into(),
                path: PathBuf::from("/p/USER.md"),
                body: "who".into(),
                chars: 3,
                original_chars: 3,
            }),
            memory: None,
            skills: None,
            notes: Vec::new(),
            skill_notes: Vec::new(),
            guidance: String::new(),
        };
        let prompt = assemble("base", &ctx, &["frag".into(), "  ".into()]);
        let prompt = prompt.replace("\n", " ");
        let compact = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
        assert!(
            compact.ends_with("rules frag ## USER.md (/p/USER.md) who"),
            "{compact}"
        );
        assert_eq!(ctx.total_chars(), 8);
    }

    fn skill(dir: &Path, name: &str, description: &str) {
        write(
            &dir.join(name).join("SKILL.md"),
            &format!("---\nname: {name}\ndescription: {description}\n---\nDo {name}.\n"),
        );
    }

    fn env_for(home: &Path) -> impl Fn(&str) -> Option<String> {
        let home = home.display().to_string();
        move |key: &str| (key == "HOME").then(|| home.clone())
    }

    #[test]
    fn the_skills_index_is_the_last_labelled_layer_after_memory() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = (
            tmp.path().join("c"),
            tmp.path().join("p"),
            tmp.path().join("w"),
        );
        write(&config.join("AGENT.md"), "RULES");
        write(&profile.join("USER.md"), "WHO");
        write(&profile.join("MEMORY.md"), "a fact");
        skill(&config.join("skills"), "backup", "back things up");
        let report = crate::skills::discover(&[crate::skills::Root {
            source: crate::skills::Source::Shared,
            dir: config.join("skills"),
        }]);
        let ctx = gather(&sources(&config, &profile, &workspace), Budget::default())
            .with_skills(&report, 4000);

        let prompt = assemble("base", &ctx, &[]);
        let at = |needle: &str| {
            prompt
                .find(needle)
                .unwrap_or_else(|| panic!("{needle}: {prompt}"))
        };
        assert!(at("a fact") < at("## Skills"), "after MEMORY.md: {prompt}");
        assert!(prompt.contains("- backup: back things up"), "{prompt}");
        assert!(
            !prompt.contains("Do backup."),
            "the body is loaded on demand: {prompt}"
        );
        assert!(prompt.trim_end().ends_with("back things up"), "{prompt}");
        assert!(!ctx.is_empty());
        assert_eq!(
            ctx.total_chars(),
            "RULES".len() + "WHO".len() + "- a fact".len()
        );
    }

    #[test]
    fn the_config_reaches_the_shared_profile_and_workspace_skills_and_the_budget() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let config = home.join(".eclipse");
        let workspace = home.join("ws");
        skill(&config.join("skills"), "backup", "the shared one");
        skill(&config.join("skills"), "other", "shared only");
        skill(
            &config.join("profiles/work/skills"),
            "backup",
            "the profile one",
        );
        skill(&workspace.join(".eclipse/skills"), "deploy", "this project");

        let mut cfg = crate::config::Config {
            profile: Some("work".into()),
            ..Default::default()
        };
        cfg.tools.workspace_root = Some(workspace.clone());
        let env = env_for(home);
        let plugins = crate::plugins::Plugins::default();

        let ctx = for_config(&cfg, &env, &plugins);
        let index = ctx.skills.as_ref().unwrap();
        assert!(index.body.contains("the profile one"), "{}", index.body);
        assert!(
            !index.body.contains("the shared one"),
            "the profile shadows it"
        );
        assert!(index.body.contains("- deploy: this project"));
        assert!(index.body.contains("- other: shared only"));
        assert!(ctx.skill_notes.is_empty(), "{:?}", ctx.skill_notes);

        cfg.skills.index_budget_chars = index.chars - 10;
        let ctx = for_config(&cfg, &env, &plugins);
        assert_eq!(ctx.skills.as_ref().unwrap().names.len(), 2);
        assert!(
            ctx.skill_notes
                .iter()
                .any(|n| n.contains("left out 1 of 3")),
            "{:?}",
            ctx.skill_notes
        );
    }

    // -- what a workspace may hand the prompt (`#358`) --------------------------------------------

    /// `sources` with a `$HOME`, so the walk has the boundary a real run has.
    fn under_home<'a>(
        config: &'a Path,
        profile: &'a Path,
        workspace: &'a Path,
        home: &'a Path,
    ) -> Sources<'a> {
        Sources {
            config_dir: Some(config),
            profile_dir: Some(profile),
            workspace,
            home: Some(home),
            user_file: "USER.md",
            memory_file: "MEMORY.md",
        }
    }

    /// A repository is untrusted input. `AGENTS.md -> ../id_rsa` used to put the target's text into
    /// the system prompt with no tool call — and so no approval, hook or redaction rule — in the way.
    #[test]
    fn a_project_file_that_points_outside_the_tree_is_not_read() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let workspace = home.join("work");
        std::fs::create_dir_all(&workspace).unwrap();
        let config = tmp.path().join("config");
        let profile = tmp.path().join("profile");
        // The key lives outside `$HOME`, so it is outside the tree the walk covered.
        let secret = tmp.path().join("id_rsa");
        write(&secret, "-----BEGIN OPENSSH PRIVATE KEY-----\n");
        std::os::unix::fs::symlink(&secret, workspace.join("AGENTS.md")).unwrap();

        let ctx = gather(
            &under_home(&config, &profile, &workspace, &home),
            Budget::default(),
        );
        assert!(
            ctx.instructions.is_empty(),
            "nothing from the link: {:?}",
            ctx.instructions
        );
        assert!(
            ctx.notes
                .iter()
                .any(|n| n.contains("points outside the project")),
            "{:?}",
            ctx.notes
        );
    }

    /// The rule is the target's location, not "symlinks are refused": a link to a file in the same
    /// project is the shape a dotfiles checkout has, and it keeps working.
    #[test]
    fn a_project_file_that_points_inside_the_tree_is_still_read() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        write(
            &workspace.join("docs/conventions.md"),
            "run make, never cargo test\n",
        );
        std::os::unix::fs::symlink(
            workspace.join("docs/conventions.md"),
            workspace.join("AGENTS.md"),
        )
        .unwrap();

        let ctx = gather(
            &under_home(&config, &profile, &workspace, tmp.path()),
            Budget::default(),
        );
        assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
        assert!(ctx.instructions[0].body.contains("run make"));
        assert_eq!(
            ctx.instructions[0].path,
            std::fs::canonicalize(workspace.join("docs/conventions.md")).unwrap(),
            "the label names the file that was read"
        );
    }

    /// The operator's own files are not a clone's: the global `AGENT.md` may be a link wherever the
    /// person keeps it.
    #[test]
    fn the_operators_own_agent_file_may_still_be_a_symlink() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        let shared = tmp.path().join("dotfiles/AGENT.md");
        write(&shared, "my rules, kept outside any project\n");
        std::fs::create_dir_all(&config).unwrap();
        std::os::unix::fs::symlink(&shared, config.join("AGENT.md")).unwrap();

        let ctx = gather(
            &under_home(&config, &profile, &workspace, tmp.path()),
            Budget::default(),
        );
        assert_eq!(ctx.instructions.len(), 1, "{:?}", ctx.notes);
        assert!(ctx.instructions[0].body.contains("my rules"));
    }

    /// A FIFO would block the read forever: `AGENT.md` selection already rejects one, but `USER.md`
    /// and `MEMORY.md` are opened by name, so the reader is where that has to be decided.
    #[test]
    fn a_context_file_that_is_not_a_regular_file_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        std::fs::create_dir_all(&profile).unwrap();
        let fifo = profile.join("USER.md");
        let made = std::process::Command::new("mkfifo").arg(&fifo).status();
        assert!(
            matches!(made, Ok(s) if s.success()),
            "mkfifo is how this test makes the case: {made:?}"
        );

        let ctx = gather(
            &under_home(&config, &profile, &workspace, tmp.path()),
            Budget::default(),
        );
        assert!(ctx.user.is_none(), "no section, and no hang");
        assert!(
            ctx.notes
                .iter()
                .any(|n| n.contains("is not a regular file")),
            "{:?}",
            ctx.notes
        );
    }

    /// The clip bounds what is injected; it never bounded what was read. A context file that is
    /// gigabytes is not prose, so the read itself stops at the cap and says so (`#358`).
    #[test]
    fn an_enormous_context_file_is_read_only_to_the_cap() {
        let tmp = tempfile::tempdir().unwrap();
        let (config, profile, workspace) = three(&tmp);
        std::fs::create_dir_all(&profile).unwrap();
        // Two megapixels of 'a', so the cap lands in the middle of the second half.
        let body = "a".repeat(2 * 1024 * 1024);
        std::fs::write(profile.join("USER.md"), &body).unwrap();

        let mut ctx = gather(
            &under_home(&config, &profile, &workspace, tmp.path()),
            Budget::default(),
        );
        let layer = ctx.user.take().expect("the head of it is still read");
        assert!(layer.truncated(), "the injected body is clipped");
        assert_eq!(
            layer.original_chars,
            (MAX_LAYER_BYTES) as usize,
            "read exactly to the cap, not to the end of the file"
        );
        assert!(
            ctx.notes
                .iter()
                .any(|n| n.contains("read only to that point")),
            "{:?}",
            ctx.notes
        );
    }
}