cargo-teksilo 0.14.3

Agent tooling for apps built on the teksilo GUI framework: symbol lookup, doc search, and the automation probe harness
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Agent instruction formats, detection, explicit selection, and installation.
//!
//! Detection is used only when no targets are named. Explicit selection creates
//! missing directories. User scope is available only through `agent install
//! --user`; project initialization never falls back to the home directory.

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

use include_dir::{Dir, include_dir};

/// The merged skill, embedded at build time.
///
/// A copy of `.claude/skills/teksilo/`; CI enforces that they stay identical,
/// which is what replaced the hand-run `cp` the previous skill depended on.
static SKILL: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/embedded/skill");

/// The skill's directory name wherever it is installed.
const SKILL_NAME: &str = "teksilo";

// ---------------------------------------------------------------------------
// The brief
// ---------------------------------------------------------------------------

/// The condensed briefing, for every agent that cannot load the skill.
///
/// Self-contained on purpose. It is the *only* teksilo instruction those
/// agents will ever see, so it has to carry what teksilo is, what the tool
/// does, and — above all — the one rule that a search hit is read with
/// `cargo teksilo show` and not fetched from GitHub, because `blob/main`
/// tracks `main` and this app pinned something else.
pub const BRIEF: &str = r##"# Teksilo — read this before writing GUI code in this app

This app depends on **Teksilo**, a pure-Rust desktop GUI framework: a retained
widget tree, SwiftUI-style layout negotiation, `Signal`/`Prop` reactivity,
AccessKit accessibility, wgpu rendering.

`cargo teksilo` is a cargo subcommand that answers for the exact Teksilo
version **this app resolved** — read from its dependency graph, never from
whatever is newest. Install it at that version:

```bash
cargo install cargo-teksilo --version <the teksilo version this app pins>
```

**There is a floor: this tool's first release is 0.13.0.** It is newer than the
framework it serves, so an app on teksilo 0.12 or older has no matching tool —
that version of it was never published, and no `--version 0.12.x` will resolve.
Such an app has to move to teksilo 0.13 first. Until it does, this briefing
describes a command that cannot run here: use `cargo doc -p teksilo-widgets`
and the compiler, and say the version is unserved rather than answering from
memory.

It refuses to answer when its own minor or major differs from the app's
Teksilo, and warns when only the patch differs. That is deliberate:
`SplitView` was deleted outright in favour of `Splitter` between two minors,
and a wrong answer reads exactly like a right one.

## Commands

- `cargo teksilo symbol <Name>`: public API from resolved crate sources.
- `cargo teksilo search "<query>"`: guides and examples; `--json` for structured hits.
- `cargo teksilo show <path>`: full document; `--lines A-B` for a 1-based range.
- `cargo teksilo init --agent codex --agent claude -y`: install the harness and
  selected instructions, creating directories without detection markers.
- `cargo teksilo agent install <agents...>`: instructions only. `--user` supports
  claude, vibe, and opencode. `agent list` shows targets and installation state.
- `cargo teksilo probe install`: install the automation harness in scripts/teksilo_probe/.
- `cargo teksilo model fetch`: explicitly download the search model. Search uses
  BM25 until cached; init and search never download weights.
- `cargo teksilo status --json`: project version and tooling state.

Use `--force` to replace conflicting generated files, `--quiet` to suppress
informational output, and `--verbose` for diagnostics. Shared instructions
outside the managed region are preserved.

## The rule that matters most

**Read a search result with `cargo teksilo show <path>`. Do not fetch it from
GitHub.** The path a hit prints is real in the *framework* repository and
absent from this one, so both tempting moves are wrong: opening it locally
finds nothing, and `blob/main/` — or the published book — serves `main`, which
is a different Teksilo from the one this app pinned. `show` is offline and
version-matched.

## Working in this app

1. **Conceptual question** ("which data model do I want?", "how does
   drag-and-drop escalate to the OS?") → `cargo teksilo search "<question>"`,
   then `cargo teksilo show <path>` to read the hit in full rather than
   working from its snippet.
2. **Before using a type** → `cargo teksilo symbol <Name>`.
3. **Compile:** `cargo check -p <app-crate>`. If it fails twice on the same
   item, re-extract that type's API before a third attempt — the mental model
   is wrong, not the compiler.
4. **Verify behaviour** where it matters: headless widget tests for layout and
   state logic, a probe for "the user clicks this and that happens on screen".

If `cargo teksilo` is not installed, fall back to
`cargo doc -p teksilo-widgets --no-deps --open`, or docs.rs at the pinned
version, and to the compiler. Both are slower and the second is
version-approximate — say so rather than guessing.
"##;

/// Opening delimiter of the region this tool owns inside a shared file.
pub const BEGIN: &str = "<!-- BEGIN teksilo -->";
/// Closing delimiter of that region.
pub const END: &str = "<!-- END teksilo -->";

/// The brief wrapped in its delimiters.
pub fn region_block() -> String {
    format!("{BEGIN}\n{}\n{END}", BRIEF.trim_end())
}

/// Replace the teksilo region in `existing`, or append one.
///
/// Pure, so the property that matters — *nothing outside the markers moves* —
/// is testable without a filesystem. `AGENTS.md` and
/// `.github/copilot-instructions.md` belong to the project, not to this tool:
/// a second run must be a byte-for-byte no-op, and a run after someone edits
/// the rest of the file must leave their edit alone.
pub fn upsert_region(existing: &str, block: &str) -> String {
    if let Some(start) = existing.find(BEGIN)
        && let Some(end_offset) = existing[start..].find(END)
    {
        let end = start + end_offset + END.len();
        let mut out = String::with_capacity(existing.len() + block.len());
        out.push_str(&existing[..start]);
        out.push_str(block);
        out.push_str(&existing[end..]);
        return out;
    }

    // Appending: keep what is there byte for byte and separate the region with
    // one blank line, so it reads as its own section rather than running into
    // whatever paragraph happened to end the file.
    let mut out = existing.to_string();
    if !out.is_empty() {
        if !out.ends_with('\n') {
            out.push('\n');
        }
        if !out.ends_with("\n\n") {
            out.push('\n');
        }
    }
    out.push_str(block);
    out.push('\n');
    out
}

// ---------------------------------------------------------------------------
// What gets written, and where
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum SetupError {
    #[error("could not install the agent instructions: {0}")]
    Io(#[from] std::io::Error),

    #[error(transparent)]
    Probe(#[from] crate::probe::ProbeError),

    #[error(
        "stdin is not a terminal, so there is nobody to answer this prompt.\n\
         Pass {hint} to run non-interactively."
    )]
    NotATerminal { hint: &'static str },

    #[error("could not find a home directory (neither $HOME nor %USERPROFILE% is set)")]
    NoHome,

    #[error(
        "{0} exists but is not valid UTF-8, so its teksilo section cannot be edited \
         without discarding the rest of the file.\n\
         This tool owns only the text between its markers; fix the file's encoding \
         and re-run."
    )]
    NotUtf8(PathBuf),
}

/// How one agent's instructions are shaped on disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Form {
    /// The whole four-file skill directory, replaced as a unit.
    Skill,
    /// A file this tool owns outright: vendor frontmatter, then the brief.
    OwnFile { frontmatter: &'static str },
    /// A delimited region inside a file the project also writes.
    Region,
}

/// One agent, detected, with the single path setup will write for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    /// The vendor's own name for itself.
    pub agent: &'static str,
    /// What was found that made this agent count as configured.
    pub marker: &'static str,
    /// The one path this target writes.
    pub path: PathBuf,
    pub form: Form,
}

/// Cursor's documented frontmatter: `description`, `globs`, `alwaysApply`.
///
/// `alwaysApply: false` with a `.rs` glob rather than always-on: this is
/// advice about Rust GUI code, and a rule that fires while editing the CI YAML
/// is the kind of noise that gets a rules file deleted.
const CURSOR_FRONTMATTER: &str = "\
---
description: Teksilo GUI framework — use `cargo teksilo` for version-matched API and docs
globs: **/*.rs
alwaysApply: false
---
";

/// Windsurf's documented frontmatter: `trigger`, `globs`, `description`.
const WINDSURF_FRONTMATTER: &str = "\
---
trigger: glob
globs: **/*.rs
description: Teksilo GUI framework — use `cargo teksilo` for version-matched API and docs
---
";

/// Where a vendor's brief goes, and in what shape.
///
/// Most vendors know both at compile time. One does not: Cline reads two
/// different directories plus a legacy file, and which of them a project has
/// decides the path *and* the form — so the table has to be able to ask the
/// disk rather than only state a constant.
enum Shape {
    /// One path, one form, decided here.
    Fixed { path: &'static str, form: Form },
    /// Resolved from the project, by [`cline_layout`].
    Cline,
}

/// Every project-scope agent this tool knows how to write for.
///
/// `marker` is what must already exist for the agent to count as configured
/// here, and is also the label printed when it is missing. Ordered as the plan
/// prints them.
struct Vendor {
    agent: &'static str,
    marker: &'static str,
    shape: Shape,
}

const VENDORS: &[Vendor] = &[
    Vendor {
        agent: "Claude Code",
        marker: ".claude/",
        shape: Shape::Fixed {
            path: ".claude/skills/teksilo",
            form: Form::Skill,
        },
    },
    Vendor {
        agent: "Cursor",
        marker: ".cursor/",
        shape: Shape::Fixed {
            path: ".cursor/rules/teksilo.mdc",
            form: Form::OwnFile {
                frontmatter: CURSOR_FRONTMATTER,
            },
        },
    },
    Vendor {
        agent: "Windsurf",
        marker: ".windsurf/",
        shape: Shape::Fixed {
            path: ".windsurf/rules/teksilo.md",
            form: Form::OwnFile {
                frontmatter: WINDSURF_FRONTMATTER,
            },
        },
    },
    Vendor {
        agent: "Cline",
        // The label names the directory every Cline surface reads today, and
        // the one Cline's own UI creates — not the newest one.
        // The label names the directory every Cline surface reads today, and
        // the one Cline's own UI creates — not the newest one.
        marker: ".clinerules/",
        shape: Shape::Cline,
    },
    Vendor {
        agent: "GitHub Copilot",
        marker: ".github/",
        shape: Shape::Fixed {
            path: ".github/copilot-instructions.md",
            form: Form::Region,
        },
    },
    Vendor {
        agent: "Codex / AGENTS.md",
        marker: "AGENTS.md",
        shape: Shape::Fixed {
            path: "AGENTS.md",
            form: Form::Region,
        },
    },
];

/// Where one project keeps its Cline rules, if it keeps any.
///
/// Returns `(marker label, marker path, target path, form)`.
///
/// Cline has three project layouts, and the order they are tried in is the
/// one decision in this function worth arguing about.
///
/// `.clinerules/` comes **first**, even though Cline's own source binds it to
/// a constant named `DEPRECATED_CONFIG_DIR` while `.cline` is
/// `CLINE_CONFIG_DIR`. Deprecated names the direction of travel, not what is
/// read today: the VS Code extension was hardcoded to `.clinerules` and
/// ignored `.cline/rules/` entirely (cline/cline#14186), the cross-surface fix
/// landed on `main` only in September 2026 and is in no released build yet,
/// and Cline's own documentation still says the VS Code Rules panel *creates*
/// new workspace rules in `.clinerules/`.
///
/// So preferring the modern path would install, in the most widely used Cline
/// surface, a file nothing reads — which this module holds to be worse than
/// installing nothing, because it reports success. Reachability beats recency.
/// When `.cline/` is the only layout present the project has clearly chosen
/// it, and it is honoured rather than second-guessed with a top-level
/// directory it did not ask for; that case is the one to revisit once the
/// extension fix ships.
///
/// The legacy form may be a plain **file** rather than a directory, in which
/// case there is nowhere to put a file of our own and the brief goes into a
/// marker region — the same treatment `AGENTS.md` gets, and for the same
/// reason: the file is the project's, not ours. Cline reads such a file in
/// place; if its UI later folds it into a directory it carries our region
/// along with the rest of the content.
///
/// No frontmatter in any case. Cline's rules are plain markdown, and its docs
/// state that a rule without frontmatter is always active; adding one would
/// make the brief conditional for no gain.
fn cline_layout(root: &Path) -> Option<(&'static str, PathBuf, PathBuf, Form)> {
    let legacy = root.join(".clinerules");
    if legacy.is_dir() {
        let target = legacy.join("teksilo.md");
        return Some((
            ".clinerules/",
            legacy,
            target,
            Form::OwnFile { frontmatter: "" },
        ));
    }
    if legacy.is_file() {
        return Some((".clinerules", legacy.clone(), legacy, Form::Region));
    }
    let modern = root.join(".cline");
    if modern.is_dir() {
        let target = modern.join("rules").join("teksilo.md");
        return Some((".cline/", modern, target, Form::OwnFile { frontmatter: "" }));
    }
    None
}

/// The nearest ancestor of `start` (inclusive) holding a `Cargo.toml`.
///
/// `cargo metadata` walks up on its own, but setup has to answer the question
/// *before* asking cargo anything: with no manifest anywhere there is no
/// project to set up, and the right move is to say so and ask — not to fail,
/// and emphatically not to quietly write the home directory instead.
pub fn find_project_root(start: &Path) -> Option<PathBuf> {
    let mut dir = Some(start);
    while let Some(d) = dir {
        if d.join("Cargo.toml").is_file() {
            return Some(d.to_path_buf());
        }
        dir = d.parent();
    }
    None
}

/// One project-scope agent, with the marker that decides whether it is here.
///
/// Every project vendor, found or not, in the table's order — so the install
/// list, the "nothing was written for these" report and `status` all read one
/// list and cannot disagree about either the order or the detection rule.
pub struct ProjectCandidate {
    pub target: Target,
    /// The path whose existence means "this agent is configured here".
    pub marker_path: PathBuf,
}

impl ProjectCandidate {
    /// `exists`, not `is_dir`: one marker (`AGENTS.md`) is a file.
    pub fn detected(&self) -> bool {
        self.marker_path.exists()
    }
}

/// Every project vendor, detected or not.
pub fn project_candidates(root: &Path) -> Vec<ProjectCandidate> {
    VENDORS
        .iter()
        .map(|vendor| match &vendor.shape {
            Shape::Fixed { path, form } => ProjectCandidate {
                target: Target {
                    agent: vendor.agent,
                    marker: vendor.marker,
                    path: root.join(path),
                    form: *form,
                },
                marker_path: root.join(vendor.marker.trim_end_matches('/')),
            },
            Shape::Cline => match cline_layout(root) {
                Some((marker, marker_path, path, form)) => ProjectCandidate {
                    target: Target {
                        agent: vendor.agent,
                        marker,
                        path,
                        form,
                    },
                    marker_path,
                },
                // Nothing on disk: the candidate still exists so the closing
                // report can name what to create, and `marker_path` points at
                // `.clinerules/` — the directory the label names — precisely
                // because it does NOT exist, which is what makes `detected()`
                // false.
                None => ProjectCandidate {
                    target: Target {
                        agent: vendor.agent,
                        marker: vendor.marker,
                        path: root.join(".clinerules/teksilo.md"),
                        form: Form::OwnFile { frontmatter: "" },
                    },
                    marker_path: root.join(".clinerules"),
                },
            },
        })
        .collect()
}

/// The agents configured in this project.
pub fn project_targets(root: &Path) -> Vec<Target> {
    project_candidates(root)
        .into_iter()
        .filter(ProjectCandidate::detected)
        .map(|c| c.target)
        .collect()
}

/// The project-scope agents that were *not* found, for the closing report.
#[cfg(test)]
pub fn project_undetected(root: &Path) -> Vec<(&'static str, &'static str)> {
    project_candidates(root)
        .into_iter()
        .filter(|c| !c.detected())
        .map(|c| (c.target.agent, c.target.marker))
        .collect()
}

// ---------------------------------------------------------------------------
// User scope
// ---------------------------------------------------------------------------

/// `$VIBE_HOME`, or `~/.vibe`.
///
/// Vibe relocates its **whole** state directory through `VIBE_HOME`, not a
/// sub-path of it, so honouring the variable is the difference between writing
/// the file Vibe reads and writing a `~/.vibe/` it will never open.
pub fn vibe_home(home: &Path) -> PathBuf {
    match std::env::var_os("VIBE_HOME") {
        Some(v) if !v.is_empty() => PathBuf::from(v),
        _ => home.join(".vibe"),
    }
}

/// `$XDG_CONFIG_HOME/opencode`, or `~/.config/opencode`.
///
/// opencode resolves its config through the XDG base directories, so the
/// override is read here too. A machine where it landed somewhere this does
/// not predict is not a failure mode: the directory is simply not found,
/// nothing is written, and the closing report names the path that was looked
/// at — which is the one thing that makes the miss fixable.
pub fn opencode_config(home: &Path) -> PathBuf {
    match std::env::var_os("XDG_CONFIG_HOME") {
        Some(v) if !v.is_empty() => PathBuf::from(v).join("opencode"),
        _ => home.join(".config").join("opencode"),
    }
}

/// One user-scope agent, with the directory whose existence is the evidence
/// that this agent is configured on this machine.
pub struct UserCandidate {
    pub target: Target,
    pub dir: PathBuf,
}

impl UserCandidate {
    pub fn detected(&self) -> bool {
        self.dir.is_dir()
    }
}

/// Every user-scope agent this tool knows how to write for, found or not.
///
/// The env-resolved directories are **parameters, not reads**: a test can then
/// pin them to a temporary directory instead of mutating process-wide
/// environment variables, which two tests running concurrently in one process
/// cannot do safely.
pub fn user_candidates(home: &Path, vibe: &Path, opencode: &Path) -> Vec<UserCandidate> {
    vec![
        UserCandidate {
            target: Target {
                agent: "Claude Code",
                marker: "~/.claude/",
                path: home.join(".claude").join("skills").join(SKILL_NAME),
                form: Form::Skill,
            },
            dir: home.join(".claude"),
        },
        // Vibe and opencode both read an `AGENTS.md` at their config root, and
        // that file is the user's own — it may already hold global
        // instructions that have nothing to do with teksilo. Hence `Region`
        // rather than `OwnFile`: this tool owns the bytes between its markers
        // and nothing else in either file.
        UserCandidate {
            target: Target {
                agent: "Mistral Vibe",
                marker: "~/.vibe/",
                path: vibe.join("AGENTS.md"),
                form: Form::Region,
            },
            dir: vibe.to_path_buf(),
        },
        UserCandidate {
            target: Target {
                agent: "opencode",
                marker: "~/.config/opencode/",
                path: opencode.join("AGENTS.md"),
                form: Form::Region,
            },
            dir: opencode.to_path_buf(),
        },
    ]
}

/// The agents configured for this user.
///
/// Same conservative rule as project scope, and for a sharper reason here: the
/// directory must **already exist**. Creating `~/.vibe/` for someone who has
/// never run Vibe writes a config directory for a tool they may not have, in
/// their home rather than in a repository they can throw away.
pub fn user_targets(home: &Path) -> Vec<Target> {
    user_targets_in(home, &vibe_home(home), &opencode_config(home))
}

/// [`user_targets`] against explicitly given directories.
pub fn user_targets_in(home: &Path, vibe: &Path, opencode: &Path) -> Vec<Target> {
    user_candidates(home, vibe, opencode)
        .into_iter()
        .filter(UserCandidate::detected)
        .map(|c| c.target)
        .collect()
}

/// The user-scope agents that were *not* found, and where this looked.
///
/// The path is returned rather than the marker label because for two of the
/// three it is env-dependent: told "no ~/.vibe/", a user with `VIBE_HOME` set
/// would go and look in the wrong place.
#[cfg(test)]
pub fn user_undetected_in(
    home: &Path,
    vibe: &Path,
    opencode: &Path,
) -> Vec<(&'static str, PathBuf)> {
    user_candidates(home, vibe, opencode)
        .into_iter()
        .filter(|c| !c.detected())
        .map(|c| (c.target.agent, c.dir))
        .collect()
}

/// The agents with no user-level file this tool writes, and why not.
///
/// Data rather than prose because two commands need it: `setup --user` prints
/// it as a closing note, and `status` renders each entry as an `n/a` row. A
/// second hand-written copy is a second thing to forget.
///
/// Windsurf is the awkward member and is listed deliberately: it *does* keep a
/// global file, and this tool still does not write it — one shared file with
/// no delimiter convention is not somewhere to append unasked. Saying "n/a"
/// without the reason would read as "Windsurf has nothing", which is false.
#[cfg(test)]
pub const USER_NOT_APPLICABLE: &[(&str, &str)] = &[
    (
        "Cursor",
        "user rules are edited in Customize → Rules, not stored as a file",
    ),
    (
        "GitHub Copilot",
        "personal instructions live in your github.com settings",
    ),
    (
        "Windsurf",
        "one global file, ~/.codeium/windsurf/memories/global_rules.md — paste the brief there by hand",
    ),
    (
        "Codex / AGENTS.md",
        "a repository-root AGENTS.md is per-repository by definition",
    ),
];

/// Why `--user` reaches three agents and not seven.
///
/// Printed rather than silently skipped, because "Cursor was not installed for
/// you" and "Cursor has nowhere for this to go" are different facts and a user
/// with Cursor open deserves the second one.
#[cfg(test)]
pub fn user_scope_note() -> String {
    let mut out = String::from("The rest keep no user-level file this tool can write:\n");
    for (agent, why) in USER_NOT_APPLICABLE {
        out.push_str(&format!("  {agent:<18}{why}.\n"));
    }
    // Counted, not spelled: the last time a number in prose was typed by hand
    // here it went stale the moment the list grew.
    out.push_str(&format!(
        "Run `cargo teksilo init` inside each project for those {}.",
        USER_NOT_APPLICABLE.len()
    ));
    out
}

/// What a written file is, and is not.
///
/// Shared by `setup` and `status` so the two cannot come to promise different
/// things. Every line either command prints reports a file **on disk**;
/// whether an agent then reads it is that agent's decision, and at least one
/// will not straight away — Grok Build wants the folder trusted first, and any
/// of them skips a gitignored instruction file without saying so.
pub fn home_dir() -> Result<PathBuf, SetupError> {
    std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
        .map(PathBuf::from)
        .ok_or(SetupError::NoHome)
}

// ---------------------------------------------------------------------------
// Writing
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Change {
    Created,
    Updated,
    Unchanged,
}

impl Change {
    pub fn describe(&self) -> &'static str {
        match self {
            Change::Created => "created",
            Change::Updated => "updated",
            Change::Unchanged => "unchanged",
        }
    }
}

/// What one target's write actually did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outcome {
    pub agent: &'static str,
    pub path: PathBuf,
    pub change: Change,
    /// Files written for this target — 4 for the skill, 1 otherwise.
    pub files: usize,
}

/// The whole contents of a file this tool owns outright.
///
/// A function rather than an inline `format!` so [`apply`] and [`inspect`]
/// cannot drift about what "installed and current" means.
fn own_file(frontmatter: &str) -> String {
    // An empty frontmatter means the vendor wants none, not that it wants a
    // blank first line. Cline is the case: its rules are plain markdown, and
    // its own docs say a rule *without* frontmatter is always active — so the
    // absence is what keeps the brief unconditional.
    if frontmatter.is_empty() {
        BRIEF.to_string()
    } else {
        format!("{frontmatter}\n{BRIEF}")
    }
}

/// Read a file this tool shares with the project, for [`Form::Region`].
///
/// A missing file is the empty one — `upsert_region` then appends, and
/// `write_if_changed` reports it as created. Every *other* failure is an
/// error, which is the whole point of this function existing.
///
/// It replaced `read_to_string(..).unwrap_or_default()`, which mapped a
/// decode failure onto "the file is empty" and so rewrote a project's
/// `AGENTS.md` down to nothing but our own region. One byte of Latin-1 in a
/// file this tool does not own was enough to destroy it, silently, while
/// reporting success — against a module whose stated promise is that "a run
/// after someone edits the rest of the file must leave their edit alone".
fn read_shared(path: &Path) -> Result<String, SetupError> {
    match std::fs::read(path) {
        Ok(bytes) => String::from_utf8(bytes).map_err(|_| SetupError::NotUtf8(path.to_path_buf())),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(e) => Err(e.into()),
    }
}

/// Write one target, reporting whether anything actually moved.
pub fn apply(target: &Target) -> Result<Outcome, SetupError> {
    let (change, files) = match target.form {
        Form::Skill => install_skill(&target.path)?,
        Form::OwnFile { frontmatter } => {
            (write_if_changed(&target.path, &own_file(frontmatter))?, 1)
        }
        Form::Region => {
            let existing = read_shared(&target.path)?;
            let updated = upsert_region(&existing, &region_block());
            (write_if_changed(&target.path, &updated)?, 1)
        }
    };
    Ok(Outcome {
        agent: target.agent,
        path: target.path.clone(),
        change,
        files,
    })
}

/// Whether this tool's own content is at a target, and whether it is current.
///
/// The contract, which the `inspect_matches_apply` test pins for every form:
/// **`inspect` returns [`Current`](Presence::Current) exactly when `apply`
/// would return [`Change::Unchanged`]**. That equivalence is the whole point
/// of the type — `status` is the dry run of `setup`, and a status that
/// computed "installed" its own way would eventually disagree with the
/// command it claims to predict.
///
/// The other two are not symmetrical with `Change`, and deliberately so:
/// [`Absent`](Presence::Absent) becomes `Created` for a file that does not
/// exist but `Updated` for one that exists without our region. `Presence`
/// describes *our* content; `Change` describes the file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Presence {
    /// Byte-for-byte what this build writes.
    Current,
    /// Ours, but not this build's — an older release wrote it.
    Stale,
    /// Nothing of ours is here.
    Absent,
    /// `apply` would fail here rather than install: the reason, in a phrase.
    ///
    /// Distinct from `Absent` because the two lead somewhere different. An
    /// absent brief is installed by running `setup`; a blocked one is not, and
    /// reporting it as merely missing would send a reader to a command that
    /// will refuse — the same "advice that does nothing" this type exists to
    /// prevent.
    Blocked(&'static str),
}

/// What [`apply`] would find, without writing anything.
///
/// Every arm mirrors the corresponding arm of `apply` and shares its content
/// computation, so the two are one decision expressed twice rather than two
/// decisions that happen to agree today.
pub fn inspect(target: &Target) -> Presence {
    match target.form {
        Form::Skill => inspect_skill(&target.path),
        Form::OwnFile { frontmatter } => match std::fs::read(&target.path) {
            Ok(current) if current == own_file(frontmatter).as_bytes() => Presence::Current,
            // A file at our exclusive path that is not what we write is ours
            // from an older release. Nothing else puts a file there.
            Ok(_) => Presence::Stale,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Presence::Absent,
            // A directory at the path, or no permission: `apply` errors here,
            // so claiming "not installed, run setup" would be false advice.
            Err(_) => Presence::Blocked("cannot be read"),
        },
        Form::Region => {
            let existing = match read_shared(&target.path) {
                Ok(text) => text,
                Err(SetupError::NotUtf8(_)) => return Presence::Blocked("is not valid UTF-8"),
                Err(_) => return Presence::Blocked("cannot be read"),
            };
            // The marker, not the file, is the evidence: this file belongs to
            // the project and usually exists without us having written a word.
            if !existing.contains(BEGIN) {
                return Presence::Absent;
            }
            if existing == upsert_region(&existing, &region_block()) {
                Presence::Current
            } else {
                Presence::Stale
            }
        }
    }
}

/// [`inspect`] for a skill tree: current iff every file matches and no strays.
fn inspect_skill(dest: &Path) -> Presence {
    if !dest.exists() {
        return Presence::Absent;
    }
    let mut wanted = Vec::new();
    collect(&SKILL, Path::new(""), &mut wanted);

    let mut any = false;
    let mut all = true;
    for (relative, bytes) in &wanted {
        match std::fs::read(dest.join(relative)) {
            Ok(current) if current == *bytes => any = true,
            _ => all = false,
        }
    }
    if !any {
        // A directory of this name holding none of our files is not a stale
        // install — it is somebody else's directory, and saying "installed,
        // outdated" about it would be a claim we have no evidence for.
        return Presence::Absent;
    }

    let keep: Vec<&Path> = wanted.iter().map(|(p, _)| p.as_path()).collect();
    if all && !has_strays(dest, dest, &keep) {
        Presence::Current
    } else {
        Presence::Stale
    }
}

/// The read-only twin of [`remove_strays`]: is there a file we would delete?
///
/// Files only, matching `remove_strays`, which prunes an emptied directory but
/// does not count it as a change — so an empty leftover directory must not
/// make this report `Stale` either, or `status` would advertise work that
/// `setup` would then report as `unchanged`.
fn has_strays(root: &Path, dir: &Path, keep: &[&Path]) -> bool {
    let Ok(entries) = std::fs::read_dir(dir) else {
        // Cannot look, so cannot claim there is nothing. `Current` means
        // "verified identical"; an unreadable subtree is not that.
        return true;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            if has_strays(root, &path, keep) {
                return true;
            }
        } else if let Ok(relative) = path.strip_prefix(root)
            && !is_wanted(relative, keep)
        {
            return true;
        }
    }
    false
}

/// Whether a file found on disk is one the embedded skill ships.
///
/// Case-**insensitive**, which is the safe direction rather than the tidy one.
///
/// The skill is written with `fs::write(dest.join("SKILL.md"))` and audited
/// with `read_dir`. On a case-insensitive filesystem — APFS and NTFS, so most
/// desktops — those two disagree: the write resolves onto an existing
/// `skill.md`, while `read_dir` still reports the entry under the case stored
/// on disk. An exact `Path` comparison therefore classified a file we had
/// *just written* as a leftover and deleted it, leaving the skill with no
/// `SKILL.md` while `apply` reported `Updated`, and `status` had sent the user
/// there by calling the install stale.
///
/// Folding can only err the other way, and only on a case-sensitive
/// filesystem: a genuine leftover whose name differs from a shipped file's by
/// case alone survives a reinstall. A stale file kept is recoverable. A live
/// file deleted is not.
///
/// ASCII folding is enough because every shipped path is ASCII, and a fold
/// that guessed at non-ASCII case would be a second way to be wrong.
fn is_wanted(relative: &Path, keep: &[&Path]) -> bool {
    let found = relative.as_os_str().to_string_lossy();
    keep.iter()
        .any(|k| k.as_os_str().to_string_lossy().eq_ignore_ascii_case(&found))
}

/// Write `content` only when it differs, so a re-run is a genuine no-op.
///
/// Not just cosmetic: rewriting identical bytes bumps the mtime, which is
/// enough to make a watcher rebuild and a `git status` look no different while
/// every incremental tool disagrees.
fn write_if_changed(path: &Path, content: &str) -> Result<Change, SetupError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    match std::fs::read(path) {
        Ok(current) if current == content.as_bytes() => Ok(Change::Unchanged),
        Ok(_) => {
            std::fs::write(path, content)?;
            Ok(Change::Updated)
        }
        Err(_) => {
            std::fs::write(path, content)?;
            Ok(Change::Created)
        }
    }
}

/// Install the skill tree at `dest`, replacing it as a unit.
///
/// A skill is one document in four files: a file dropped between releases must
/// not survive to shadow what the new one says. Stale files are removed rather
/// than the whole directory being deleted first, so an unchanged reinstall
/// touches nothing at all.
fn install_skill(dest: &Path) -> Result<(Change, usize), SetupError> {
    let existed = dest.exists();
    let mut wanted = Vec::new();
    collect(&SKILL, Path::new(""), &mut wanted);

    let mut moved = false;
    for (relative, bytes) in &wanted {
        let target = dest.join(relative);
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)?;
        }
        match std::fs::read(&target) {
            Ok(current) if current == *bytes => {}
            _ => {
                std::fs::write(&target, bytes)?;
                moved = true;
            }
        }
    }

    let keep: Vec<&Path> = wanted.iter().map(|(p, _)| p.as_path()).collect();
    if existed {
        moved |= remove_strays(dest, dest, &keep)?;
    }

    let change = match (existed, moved) {
        (false, _) => Change::Created,
        (true, true) => Change::Updated,
        (true, false) => Change::Unchanged,
    };
    Ok((change, wanted.len()))
}

fn collect<'a>(dir: &Dir<'a>, prefix: &Path, out: &mut Vec<(PathBuf, &'a [u8])>) {
    for file in dir.files() {
        let name = file.path().file_name().unwrap_or_default();
        out.push((prefix.join(name), file.contents()));
    }
    for sub in dir.dirs() {
        let name = sub.path().file_name().unwrap_or_default();
        collect(sub, &prefix.join(name), out);
    }
}

/// Delete anything under `dir` the embedded skill no longer ships.
fn remove_strays(root: &Path, dir: &Path, keep: &[&Path]) -> Result<bool, SetupError> {
    let mut removed = false;
    for entry in std::fs::read_dir(dir)? {
        let path = entry?.path();
        if path.is_dir() {
            removed |= remove_strays(root, &path, keep)?;
            // An emptied directory is as much a leftover as the file was.
            if std::fs::read_dir(&path)?.next().is_none() {
                std::fs::remove_dir(&path)?;
            }
        } else if let Ok(relative) = path.strip_prefix(root)
            && !is_wanted(relative, keep)
        {
            std::fs::remove_file(&path)?;
            removed = true;
        }
    }
    Ok(removed)
}

// ---------------------------------------------------------------------------
// Asking
// ---------------------------------------------------------------------------

/// Refuse to prompt when nobody can answer.
///
/// CI and coding agents run this command. A blocking `read_line` against a
/// closed stdin hangs until something kills it, which is strictly worse than
/// an error — so the error names the flag that would have avoided the question.
pub fn require_interactive(hint: &'static str) -> Result<(), SetupError> {
    if std::io::stdin().is_terminal() {
        Ok(())
    } else {
        Err(SetupError::NotATerminal { hint })
    }
}

/// Ask a yes/no question, defaulting to no.
///
/// Defaulting to no because every caller is about to write files: a bare
/// Return should leave the disk alone.
pub fn confirm(question: &str, hint: &'static str) -> Result<bool, SetupError> {
    use std::io::Write;

    require_interactive(hint)?;
    print!("{question} [y/N] ");
    std::io::stdout().flush()?;
    let mut answer = String::new();
    std::io::stdin().read_line(&mut answer)?;
    Ok(matches!(
        answer.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}

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

    fn temp() -> tempfile::TempDir {
        tempfile::tempdir().unwrap()
    }

    // --- detection ---------------------------------------------------------

    #[test]
    fn a_missing_directory_is_not_invented() {
        // Installing where nothing looks is indistinguishable from not
        // installing, except that it reports success.
        let t = temp();
        assert!(project_targets(t.path()).is_empty());
        assert!(
            !t.path().join(".claude").exists(),
            "must not create anything"
        );
        assert!(!t.path().join("AGENTS.md").exists());
    }

    #[test]
    fn each_vendor_is_detected_by_its_own_marker() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        std::fs::create_dir_all(t.path().join(".cursor")).unwrap();
        std::fs::create_dir_all(t.path().join(".windsurf")).unwrap();
        std::fs::create_dir_all(t.path().join(".cline")).unwrap();
        std::fs::create_dir_all(t.path().join(".github")).unwrap();
        std::fs::write(t.path().join("AGENTS.md"), "# Agents\n").unwrap();

        let found = project_targets(t.path());
        let agents: Vec<_> = found.iter().map(|t| t.agent).collect();
        assert_eq!(
            agents,
            [
                "Claude Code",
                "Cursor",
                "Windsurf",
                "Cline",
                "GitHub Copilot",
                "Codex / AGENTS.md"
            ]
        );
        assert!(project_undetected(t.path()).is_empty());
    }

    #[test]
    fn two_vendors_in_one_project_both_get_a_target() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        std::fs::create_dir_all(t.path().join(".github")).unwrap();
        let found = project_targets(t.path());
        assert_eq!(found.len(), 2);
        assert_eq!(found[0].form, Form::Skill);
        assert_eq!(found[1].form, Form::Region);
        assert_eq!(
            project_undetected(t.path())
                .iter()
                .map(|(a, _)| *a)
                .collect::<Vec<_>>(),
            ["Cursor", "Windsurf", "Cline", "Codex / AGENTS.md"]
        );
    }

    #[test]
    fn project_scope_never_resolves_a_path_under_home() {
        // The regression this rewrite exists for: a project-scoped run used to
        // fall back to ~/.claude when the project had no .claude of its own.
        let t = temp();
        let home = temp();
        std::fs::create_dir_all(home.path().join(".claude")).unwrap();
        // Nothing in the project, everything in the "home": still nothing.
        assert!(project_targets(t.path()).is_empty());
        for target in project_targets(t.path()) {
            assert!(target.path.starts_with(t.path()));
        }
    }

    // --- user scope --------------------------------------------------------

    /// The three user-scope directories, none of them created.
    ///
    /// Tests pass these explicitly rather than setting `VIBE_HOME` /
    /// `XDG_CONFIG_HOME`: the process environment is shared by every test in
    /// the binary, and `cargo test` runs them concurrently.
    fn user_dirs(home: &Path) -> (PathBuf, PathBuf) {
        (home.join(".vibe"), home.join(".config/opencode"))
    }

    #[test]
    fn a_home_with_nothing_in_it_gets_nothing_written() {
        // The gate the whole of user scope turns on: a directory that does not
        // exist is a tool that was never run, and this command does not create
        // a config directory in someone's home on the chance they might.
        let home = temp();
        let (vibe, opencode) = user_dirs(home.path());
        assert!(user_targets_in(home.path(), &vibe, &opencode).is_empty());
        assert!(!vibe.exists());
        assert!(!opencode.exists());
        assert!(!home.path().join(".claude").exists());

        let missing: Vec<_> = user_undetected_in(home.path(), &vibe, &opencode)
            .into_iter()
            .map(|(a, _)| a)
            .collect();
        assert_eq!(missing, ["Claude Code", "Mistral Vibe", "opencode"]);
    }

    #[test]
    fn each_user_agent_is_detected_by_its_own_directory() {
        let home = temp();
        let (vibe, opencode) = user_dirs(home.path());
        std::fs::create_dir_all(home.path().join(".claude")).unwrap();
        std::fs::create_dir_all(&vibe).unwrap();
        std::fs::create_dir_all(&opencode).unwrap();

        let found = user_targets_in(home.path(), &vibe, &opencode);
        assert_eq!(
            found.iter().map(|t| t.agent).collect::<Vec<_>>(),
            ["Claude Code", "Mistral Vibe", "opencode"]
        );
        assert_eq!(found[0].path, home.path().join(".claude/skills/teksilo"));
        assert_eq!(found[0].form, Form::Skill);
        assert_eq!(found[1].path, vibe.join("AGENTS.md"));
        assert_eq!(found[1].form, Form::Region);
        assert_eq!(found[2].path, opencode.join("AGENTS.md"));
        assert_eq!(found[2].form, Form::Region);
        assert!(user_undetected_in(home.path(), &vibe, &opencode).is_empty());
    }

    #[test]
    fn one_installed_agent_does_not_pull_in_the_other_two() {
        let home = temp();
        let (vibe, opencode) = user_dirs(home.path());
        std::fs::create_dir_all(&vibe).unwrap();

        let found = user_targets_in(home.path(), &vibe, &opencode);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].agent, "Mistral Vibe");
        assert_eq!(
            user_undetected_in(home.path(), &vibe, &opencode)
                .into_iter()
                .map(|(a, _)| a)
                .collect::<Vec<_>>(),
            ["Claude Code", "opencode"]
        );
    }

    #[test]
    fn a_relocated_config_directory_is_where_the_file_lands() {
        // `VIBE_HOME` moves Vibe's whole state directory and opencode follows
        // `XDG_CONFIG_HOME`. Writing `~/.vibe/AGENTS.md` for a user who
        // relocated theirs is a file nothing reads — the failure this tool
        // exists to avoid, in the one scope where it lands in $HOME.
        let elsewhere = temp();
        let home = temp();
        let vibe = elsewhere.path().join("vibe-state");
        let opencode = elsewhere.path().join("xdg/opencode");
        std::fs::create_dir_all(&vibe).unwrap();
        std::fs::create_dir_all(&opencode).unwrap();

        let found = user_targets_in(home.path(), &vibe, &opencode);
        assert_eq!(found.len(), 2);
        assert_eq!(found[0].path, vibe.join("AGENTS.md"));
        assert_eq!(found[1].path, opencode.join("AGENTS.md"));
        assert!(
            !home.path().join(".vibe").exists() && !home.path().join(".config").exists(),
            "the default locations must not be touched when the env moved them"
        );
    }

    #[test]
    fn the_defaults_are_the_documented_ones() {
        // Guards the fallback arm of both resolvers — the path taken on every
        // machine that sets neither variable, which is most of them.
        let home = Path::new("/home/someone");
        // SAFETY-adjacent: these read the ambient environment, so assert only
        // what holds either way — the suffix under whatever base was chosen.
        assert!(vibe_home(home).ends_with(".vibe") || std::env::var_os("VIBE_HOME").is_some());
        assert!(
            opencode_config(home).ends_with("opencode"),
            "opencode always lives in a directory of its own name"
        );
    }

    // --- finding the project ----------------------------------------------

    #[test]
    fn the_project_root_is_the_nearest_manifest_above() {
        let t = temp();
        std::fs::write(t.path().join("Cargo.toml"), "[package]\n").unwrap();
        let deep = t.path().join("crates/app/src");
        std::fs::create_dir_all(&deep).unwrap();
        assert_eq!(
            find_project_root(&deep).unwrap().canonicalize().unwrap(),
            t.path().canonicalize().unwrap()
        );
    }

    #[test]
    fn no_manifest_anywhere_is_none_rather_than_a_guess() {
        let t = temp();
        assert_eq!(find_project_root(t.path()), None);
    }

    // --- the shared-file region -------------------------------------------

    #[test]
    fn a_region_is_appended_to_a_file_that_has_none() {
        let out = upsert_region(
            "# My project\n\nRules here.\n",
            "<!-- BEGIN teksilo -->\nX\n<!-- END teksilo -->",
        );
        assert!(out.starts_with("# My project\n\nRules here.\n\n"));
        assert!(out.contains(BEGIN) && out.contains(END));
    }

    #[test]
    fn a_second_run_changes_nothing() {
        let block = region_block();
        let once = upsert_region("# My project\n", &block);
        let twice = upsert_region(&once, &block);
        assert_eq!(once, twice, "setup must be idempotent on a shared file");
    }

    #[test]
    fn nothing_outside_the_markers_is_disturbed() {
        let before = format!("head\n\n{BEGIN}\nstale brief\n{END}\n\ntail\n");
        let after = upsert_region(&before, &format!("{BEGIN}\nfresh brief\n{END}"));
        assert_eq!(
            after,
            format!("head\n\n{BEGIN}\nfresh brief\n{END}\n\ntail\n")
        );
    }

    #[test]
    fn an_empty_file_gets_no_leading_blank_line() {
        let out = upsert_region("", &region_block());
        assert!(out.starts_with(BEGIN));
    }

    // --- Cline's three layouts --------------------------------------------

    fn cline_target(root: &Path) -> Option<Target> {
        project_targets(root)
            .into_iter()
            .find(|t| t.agent == "Cline")
    }

    #[test]
    fn clinerules_wins_over_cline_because_it_is_the_one_that_is_read() {
        // The order is the point, and it is deliberately NOT newest-first.
        // Cline's source calls `.clinerules` DEPRECATED_CONFIG_DIR, but the VS
        // Code extension was hardcoded to it and ignored `.cline/rules/`
        // entirely (cline/cline#14186); the cross-surface fix is not in a
        // released build, and Cline's docs still say its Rules panel creates
        // new workspace rules in `.clinerules/`. Choosing the newer path would
        // install a file the most-used Cline surface does not read — worse
        // than installing nothing, because it reports success.
        //
        // If this test is failing because someone "modernised" the order,
        // check whether the extension fix has shipped before changing it.
        let t = temp();
        std::fs::create_dir_all(t.path().join(".clinerules")).unwrap();
        std::fs::create_dir_all(t.path().join(".cline")).unwrap();

        let target = cline_target(t.path()).expect("detected");
        assert_eq!(
            target.path,
            t.path().join(".clinerules/teksilo.md"),
            "with both present, write the one every surface reads"
        );
        apply(&target).unwrap();
        assert!(
            !t.path().join(".cline/rules").exists(),
            "and do not also write the one that may be ignored"
        );
    }

    #[test]
    fn a_cline_only_project_is_honoured_rather_than_given_a_new_directory() {
        // `.cline/` alone is a deliberate choice by that project. Respect it
        // instead of creating a top-level `.clinerules/` it did not ask for.
        let t = temp();
        std::fs::create_dir_all(t.path().join(".cline")).unwrap();
        let target = cline_target(t.path()).expect("detected");
        assert_eq!(target.path, t.path().join(".cline/rules/teksilo.md"));
        assert_eq!(target.form, Form::OwnFile { frontmatter: "" });

        apply(&target).unwrap();
        let written = std::fs::read_to_string(&target.path).unwrap();
        assert!(
            written.starts_with("# Teksilo"),
            "no frontmatter: a Cline rule without one is always active"
        );
        assert_eq!(inspect(&target), Presence::Current);
        assert!(
            !t.path().join(".clinerules").exists(),
            "must not invent the other layout beside the one in use"
        );
    }

    #[test]
    fn a_legacy_clinerules_file_gets_a_region_not_a_child_path() {
        // The legacy form can be a plain FILE. Treating it as a directory
        // would make `create_dir_all` fail with NotADirectory; treating it as
        // ours would discard the user's rules.
        let t = temp();
        let path = t.path().join(".clinerules");
        std::fs::write(&path, "# My own rules\n\nAlways use tabs.\n").unwrap();

        let target = cline_target(t.path()).expect("detected");
        assert_eq!(target.path, path);
        assert_eq!(target.form, Form::Region);

        apply(&target).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(after.contains("Always use tabs."), "their rules survive");
        assert!(after.contains(BEGIN), "and ours is appended in a region");
        assert_eq!(apply(&target).unwrap().change, Change::Unchanged);
    }

    #[test]
    fn a_project_with_no_cline_anything_is_not_detected_and_names_the_modern_dir() {
        let t = temp();
        assert!(cline_target(t.path()).is_none());
        let missing = project_undetected(t.path());
        assert!(
            missing.contains(&("Cline", ".clinerules/")),
            "the label must name the directory every Cline surface reads, and \
             the one Cline's own UI creates: {missing:?}"
        );
        assert!(!t.path().join(".cline").exists());
        assert!(!t.path().join(".clinerules").exists());
    }

    // --- data loss, found by review and reproduced ------------------------

    #[test]
    fn a_shared_file_that_is_not_utf8_stops_setup_instead_of_being_destroyed() {
        // Found by review and reproduced against the real binary: one Latin-1
        // byte in a project's AGENTS.md and `setup -y` replaced the whole file
        // with nothing but our region. `read_to_string(..).unwrap_or_default()`
        // read "cannot decode" as "the file is empty".
        let t = temp();
        let path = t.path().join("AGENTS.md");
        let original = b"# My project rules\n\nNever delete this. \xff\n";
        std::fs::write(&path, original).unwrap();

        let target = project_targets(t.path())
            .into_iter()
            .find(|t| t.form == Form::Region)
            .unwrap();

        assert!(
            matches!(inspect(&target), Presence::Blocked(_)),
            "an undecodable shared file is not `Absent` — setup cannot install here"
        );
        assert!(
            matches!(apply(&target), Err(SetupError::NotUtf8(_))),
            "setup must refuse rather than rewrite a file it cannot read whole"
        );
        assert_eq!(
            std::fs::read(&path).unwrap(),
            original,
            "the project's own bytes must survive untouched"
        );
    }

    #[test]
    fn a_missing_shared_file_is_still_created() {
        // The other half of the same change: `read_shared` must keep treating
        // "not found" as the empty file, or Region targets stop installing.
        let t = temp();
        std::fs::write(t.path().join("AGENTS.md"), "seed").unwrap();
        let target = project_targets(t.path())
            .into_iter()
            .find(|t| t.form == Form::Region)
            .unwrap();
        std::fs::remove_file(&target.path).unwrap();

        assert_eq!(inspect(&target), Presence::Absent);
        assert_eq!(apply(&target).unwrap().change, Change::Created);
        assert_eq!(inspect(&target), Presence::Current);
    }

    #[test]
    fn a_differently_cased_skill_file_is_not_deleted() {
        // Found by review and reproduced against the real binary on APFS:
        // `status` called the install stale, and the `setup` it recommended
        // then DELETED SKILL.md and reported success. The write resolves
        // case-insensitively onto the existing entry; `read_dir` reports the
        // case on disk; an exact comparison called it a stray.
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        let target = project_targets(t.path()).remove(0);
        apply(&target).unwrap();

        let upper = target.path.join("SKILL.md");
        let body = std::fs::read(&upper).unwrap();
        std::fs::remove_file(&upper).unwrap();
        std::fs::write(target.path.join("skill.md"), &body).unwrap();

        // On a case-insensitive filesystem this is the same file under another
        // name, so nothing is stale and nothing may be removed. On a
        // case-sensitive one it is a genuinely separate file — also not to be
        // deleted, since folding errs only towards keeping.
        apply(&target).unwrap();
        assert!(
            std::fs::read(target.path.join("SKILL.md")).is_ok(),
            "the skill's own SKILL.md must survive a reinstall"
        );
    }

    #[test]
    fn a_real_stray_is_still_removed() {
        // The case fold must not turn `remove_strays` into a no-op.
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        let target = project_targets(t.path()).remove(0);
        apply(&target).unwrap();

        let stray = target.path.join("reference/from_an_older_release.md");
        std::fs::write(&stray, b"x").unwrap();
        assert_eq!(inspect(&target), Presence::Stale);
        assert_eq!(apply(&target).unwrap().change, Change::Updated);
        assert!(!stray.exists(), "a genuine leftover is still pruned");
    }

    // --- inspect is the dry run of apply -----------------------------------

    /// Every project form, for the equivalence test below.
    fn one_of_each_form(root: &Path) -> Vec<Target> {
        std::fs::create_dir_all(root.join(".claude")).unwrap();
        std::fs::create_dir_all(root.join(".cursor")).unwrap();
        std::fs::write(root.join("AGENTS.md"), "# Ours\n\nKeep this.\n").unwrap();
        let targets = project_targets(root);
        let forms: Vec<Form> = targets.iter().map(|t| t.form).collect();
        assert!(forms.contains(&Form::Skill), "need a Skill target");
        assert!(forms.contains(&Form::Region), "need a Region target");
        assert!(
            forms.iter().any(|f| matches!(f, Form::OwnFile { .. })),
            "need an OwnFile target"
        );
        targets
    }

    #[test]
    fn inspect_matches_apply() {
        // The contract `Presence` exists for: `status` predicts `setup`.
        // Checked for every form, in all three of the states a target can be
        // in — nothing there, an older release's content, and current.
        let t = temp();
        let targets = one_of_each_form(t.path());

        for target in &targets {
            assert_eq!(
                inspect(target),
                Presence::Absent,
                "{}: nothing of ours is installed yet",
                target.agent
            );
        }

        for target in &targets {
            let change = apply(target).unwrap().change;
            assert_ne!(change, Change::Unchanged, "{}: first write", target.agent);
            assert_eq!(
                inspect(target),
                Presence::Current,
                "{}: current immediately after apply",
                target.agent
            );
            // The equivalence, stated directly.
            assert_eq!(
                apply(target).unwrap().change,
                Change::Unchanged,
                "{}: apply agrees it is current",
                target.agent
            );
        }
    }

    #[test]
    fn an_older_releases_content_inspects_as_stale_for_every_form() {
        let t = temp();
        let targets = one_of_each_form(t.path());
        for target in &targets {
            apply(target).unwrap();
        }

        for target in &targets {
            match target.form {
                Form::Skill => {
                    std::fs::write(target.path.join("SKILL.md"), b"from 0.9").unwrap();
                }
                Form::OwnFile { .. } => {
                    std::fs::write(&target.path, b"from 0.9").unwrap();
                }
                Form::Region => {
                    let stale = format!("# Ours\n\n{BEGIN}\nfrom 0.9\n{END}\n");
                    std::fs::write(&target.path, stale).unwrap();
                }
            }
            assert_eq!(
                inspect(target),
                Presence::Stale,
                "{}: an older release's content",
                target.agent
            );
            // And `apply` calls the same situation a change, not a no-op.
            assert_eq!(
                apply(target).unwrap().change,
                Change::Updated,
                "{}: apply rewrites it",
                target.agent
            );
        }
    }

    #[test]
    fn a_stray_file_makes_the_skill_stale_but_an_empty_directory_does_not() {
        // `remove_strays` prunes an emptied directory WITHOUT counting it as a
        // change, so `has_strays` must ignore one too — otherwise `status`
        // advertises work that `setup` then reports as `unchanged`.
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        let target = project_targets(t.path()).remove(0);
        apply(&target).unwrap();
        assert_eq!(inspect(&target), Presence::Current);

        std::fs::create_dir_all(target.path.join("leftover")).unwrap();
        assert_eq!(
            inspect(&target),
            Presence::Current,
            "an empty leftover directory is not a change apply would report"
        );
        assert_eq!(apply(&target).unwrap().change, Change::Unchanged);

        std::fs::write(target.path.join("from_0_9.md"), b"x").unwrap();
        assert_eq!(inspect(&target), Presence::Stale);
        assert_eq!(apply(&target).unwrap().change, Change::Updated);
    }

    #[test]
    fn a_shared_file_without_our_markers_is_absent_not_stale() {
        // AGENTS.md usually exists before this tool ever runs. Calling that
        // "an outdated teksilo install" would be a claim with no evidence.
        let t = temp();
        std::fs::write(t.path().join("AGENTS.md"), "# Someone else's\n").unwrap();
        let target = project_targets(t.path())
            .into_iter()
            .find(|t| t.form == Form::Region)
            .unwrap();
        assert_eq!(inspect(&target), Presence::Absent);
    }

    #[test]
    fn a_foreign_directory_at_the_skill_path_is_absent_not_stale() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude/skills/teksilo")).unwrap();
        std::fs::write(
            t.path().join(".claude/skills/teksilo/unrelated.md"),
            b"not ours",
        )
        .unwrap();
        let target = project_targets(t.path()).remove(0);
        assert_eq!(inspect(&target), Presence::Absent);
    }

    #[test]
    fn inspect_writes_nothing() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".cursor")).unwrap();
        let target = project_targets(t.path()).remove(0);
        assert_eq!(inspect(&target), Presence::Absent);
        assert!(
            !t.path().join(".cursor/rules").exists(),
            "inspecting must not create the directory apply would"
        );
    }

    #[test]
    fn the_user_scope_note_lists_every_not_applicable_agent() {
        // The note is rendered from the table `status` renders its n/a rows
        // from, so the two can never list different agents.
        let note = user_scope_note();
        for (agent, why) in USER_NOT_APPLICABLE {
            assert!(note.contains(agent), "note omits {agent}");
            assert!(note.contains(why), "note omits why for {agent}");
        }
        assert!(
            note.contains(&format!("those {}", USER_NOT_APPLICABLE.len())),
            "the count must be derived, not typed: {note}"
        );
    }

    // --- writing -----------------------------------------------------------

    #[test]
    fn installing_writes_the_whole_skill_tree() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        let targets = project_targets(t.path());
        let done = apply(&targets[0]).unwrap();

        let root = t.path().join(".claude/skills/teksilo");
        assert!(root.join("SKILL.md").is_file());
        assert!(root.join("reference/teksu.md").is_file());
        assert!(root.join("reference/automation.md").is_file());
        assert!(root.join("reference/teksilo_app_guide.md").is_file());
        assert_eq!(done.change, Change::Created);
        assert!(done.files >= 4);
    }

    #[test]
    fn reinstalling_removes_a_file_the_previous_version_shipped() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        let targets = project_targets(t.path());
        apply(&targets[0]).unwrap();

        let stale = t.path().join(".claude/skills/teksilo/reference/gone.md");
        std::fs::write(&stale, b"from an older release").unwrap();
        let again = apply(&targets[0]).unwrap();
        assert!(
            !stale.exists(),
            "a stale file must not shadow the new skill"
        );
        assert_eq!(again.change, Change::Updated);
    }

    #[test]
    fn an_unchanged_reinstall_reports_unchanged() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".claude")).unwrap();
        std::fs::create_dir_all(t.path().join(".cursor")).unwrap();
        std::fs::write(t.path().join("AGENTS.md"), "# Agents\n").unwrap();
        let targets = project_targets(t.path());
        for target in &targets {
            apply(target).unwrap();
        }
        for target in &targets {
            assert_eq!(
                apply(target).unwrap().change,
                Change::Unchanged,
                "{} re-wrote itself",
                target.agent
            );
        }
    }

    #[test]
    fn a_rules_file_carries_its_vendors_frontmatter_and_the_brief() {
        let t = temp();
        std::fs::create_dir_all(t.path().join(".cursor")).unwrap();
        std::fs::create_dir_all(t.path().join(".windsurf")).unwrap();
        for target in project_targets(t.path()) {
            apply(&target).unwrap();
        }

        let cursor = std::fs::read_to_string(t.path().join(".cursor/rules/teksilo.mdc")).unwrap();
        assert!(cursor.starts_with("---\ndescription:"));
        assert!(cursor.contains("alwaysApply: false"));
        assert!(cursor.contains("cargo teksilo show"));

        let windsurf =
            std::fs::read_to_string(t.path().join(".windsurf/rules/teksilo.md")).unwrap();
        assert!(windsurf.starts_with("---\ntrigger: glob"));
        assert!(windsurf.contains("cargo teksilo show"));
    }

    #[test]
    fn the_brief_stands_alone() {
        // It is the only teksilo instruction a non-Claude agent ever sees, so
        // it must not point at a skill that may not be installed.
        assert!(!BRIEF.contains("SKILL.md"));
        assert!(!BRIEF.contains("reference/"));
        assert!(BRIEF.contains("cargo teksilo symbol"));
        assert!(BRIEF.contains("cargo teksilo search"));
        assert!(BRIEF.contains("cargo teksilo show"));
        assert!(BRIEF.contains("cargo teksilo probe install"));
        assert!(BRIEF.contains("cargo teksilo init"));
        assert!(
            BRIEF.contains("blob/main"),
            "the GitHub warning is the point"
        );
    }

    #[test]
    fn the_embedded_skill_is_the_real_one() {
        let skill = SKILL
            .get_file("SKILL.md")
            .expect("SKILL.md must be embedded");
        let text = std::str::from_utf8(skill.contents()).unwrap();
        assert!(text.contains("name: teksilo"));
        assert!(text.starts_with("---\nname: teksilo\n"));
        assert!(text.len() > 5_000, "suspiciously small skill");
    }
}

/// Stable CLI identifiers, independent of display labels and detection markers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum Agent {
    Claude,
    Cursor,
    Windsurf,
    Cline,
    Copilot,
    Codex,
    Vibe,
    Opencode,
}
impl Agent {
    pub fn label(self) -> &'static str {
        match self {
            Self::Claude => "Claude Code",
            Self::Cursor => "Cursor",
            Self::Windsurf => "Windsurf",
            Self::Cline => "Cline",
            Self::Copilot => "GitHub Copilot",
            Self::Codex => "Codex / AGENTS.md",
            Self::Vibe => "Mistral Vibe",
            Self::Opencode => "opencode",
        }
    }
    pub fn id(self) -> &'static str {
        match self {
            Self::Claude => "claude",
            Self::Cursor => "cursor",
            Self::Windsurf => "windsurf",
            Self::Cline => "cline",
            Self::Copilot => "copilot",
            Self::Codex => "codex",
            Self::Vibe => "vibe",
            Self::Opencode => "opencode",
        }
    }
}
pub const AGENTS: &[Agent] = &[
    Agent::Claude,
    Agent::Cursor,
    Agent::Windsurf,
    Agent::Cline,
    Agent::Copilot,
    Agent::Codex,
    Agent::Vibe,
    Agent::Opencode,
];

pub fn selected_targets(
    root: &Path,
    selected: &[Agent],
    user: bool,
) -> Result<Vec<Target>, String> {
    if selected.is_empty() {
        return Ok(if user {
            user_targets(root)
        } else {
            project_targets(root)
        });
    }
    let candidates: Vec<Target> = if user {
        user_candidates(root, &vibe_home(root), &opencode_config(root))
            .into_iter()
            .map(|c| c.target)
            .collect()
    } else {
        project_candidates(root)
            .into_iter()
            .map(|c| c.target)
            .collect()
    };
    let mut targets = Vec::new();
    for agent in selected {
        let label = if !user && matches!(agent, Agent::Vibe | Agent::Opencode) {
            Agent::Codex.label()
        } else {
            agent.label()
        };
        let target = candidates
            .iter()
            .find(|t| t.agent == label)
            .ok_or_else(|| {
                format!(
                    "{} does not support user installation\nhelp: install without --user",
                    agent.id()
                )
            })?;
        if !targets.iter().any(|t: &Target| t.path == target.path) {
            targets.push(target.clone());
        }
    }
    Ok(targets)
}

/// Shared instruction regions preserve surrounding text. Whole files and skills
/// need explicit permission before replacing unknown or changed content.
pub fn check_conflict(target: &Target, force: bool) -> Result<(), String> {
    let state = inspect(target);
    if let Presence::Blocked(reason) = state {
        return Err(format!("{}: {reason}", target.path.display()));
    }
    let differs = state == Presence::Stale
        || (target.form != Form::Region && target.path.exists() && state == Presence::Absent);
    if !force && differs {
        return Err(format!(
            "{} contains different instructions\nhelp: use --force to replace them",
            target.path.display()
        ));
    }
    Ok(())
}