workspace_tools 0.12.0

Reliable workspace-relative path resolution for Rust projects. Automatically finds your workspace root and provides consistent file path handling regardless of execution context. Features memory-safe secret management, configuration loading with validation, and resource discovery.
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
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
//! Universal workspace-relative path resolution for Rust projects
//!
//! This crate provides consistent, reliable path management regardless of execution context
//! or working directory. It solves common path resolution issues in software projects by
//! leveraging cargo's environment variable injection system.
//!
//! ## problem solved
//!
//! - **execution context dependency** : paths break when code runs from different directories
//! - **environment inconsistency** : different developers have different working directory habits
//! - **testing fragility** : tests fail when run from different locations
//! - **ci/cd brittleness** : automated systems may execute from unexpected directories
//!
//! ## quick start
//!
//! 1. Configure cargo in workspace root `.cargo/config.toml` :
//! ```toml
//! [env]
//! WORKSPACE_PATH = { value = ".", relative = true }
//! ```
//!
//! 2. Use in your code :
//! ```rust
//! use workspace_tools::{ workspace, WorkspaceError };
//!
//! # fn main() -> Result< (), WorkspaceError >
//! # {
//! // get workspace instance
//! let ws = workspace()?;
//!
//! // resolve workspace-relative paths
//! let config_path = ws.config_dir().join( "app.toml" );
//! let data_path = ws.data_dir().join( "cache.db" );
//! # Ok( () )
//! # }
//! ```
//!
//! ## workspace resolution strategies
//!
//! the crate supports multiple resolution strategies to work in both development and
//! installed contexts. the `workspace()` function tries strategies in priority order:
//!
//! 1. **cargo workspace** - detected via `Cargo.toml` metadata (development)
//! 2. **`WORKSPACE_PATH` env** - set by `.cargo/config.toml` (development)
//! 3. **git root** - searches for `.git` directory with `Cargo.toml` (development)
//! 4. **`$PRO` env** - user-configured project root (installed applications)
//! 5. **`$HOME` directory** - universal fallback (installed applications)
//! 6. **current directory** - last resort fallback
//!
//! ### for installed applications
//!
//! when your cli tool is installed via `cargo install`, workspace resolution automatically
//! falls back to user-configured locations:
//!
//! ```bash
//! # option 1: $PRO (recommended for multi-project users)
//! export PRO=~/pro
//! mkdir -p ~/pro/secret
//!
//! # option 2: $HOME (simple for casual users)
//! mkdir -p ~/secret
//! ```
//!
//! this enables installed binaries to load workspace-level secrets and configurations
//! without requiring `WORKSPACE_PATH` to be set globally.
//!
//! ## features
//!
//! - **`glob`** : enables pattern-based resource discovery
//! - **`secrets`** : provides secure configuration file handling utilities
//! - **`secure`** : enables memory-safe secret handling with the secrecy crate
//! - **`serde`** : provides configuration loading with serde support
//! - **`validation`** : enables configuration validation with JSON Schema
//!
//! ## security best practices
//!
//! when using the `secure` feature for secret management :
//!
//! - secrets are wrapped in `SecretString` types that prevent accidental exposure
//! - debug output automatically redacts secret values
//! - secrets require explicit `expose_secret()` calls for access
//! - use the `SecretInjectable` trait for automatic configuration injection
//! - validate secret strength with `validate_secret()` method
//! - secrets are zeroized from memory when dropped

#![ warn( missing_docs ) ]

use std ::
{
  env,
  path :: { Path, PathBuf },
};

use std ::collections ::HashMap;

#[ cfg( feature = "glob" ) ]
use glob ::glob;

#[ cfg( feature = "secrets" ) ]
use std ::fs;

#[ cfg( feature = "validation" ) ]
use jsonschema ::Validator;

#[ cfg( feature = "validation" ) ]
use schemars ::JsonSchema;

#[ cfg( feature = "secure" ) ]
use secrecy :: { SecretString, ExposeSecret };


/// workspace path resolution errors
#[ derive( Debug, Clone ) ]
#[ non_exhaustive ]
pub enum WorkspaceError
{
  /// configuration parsing error
  ConfigurationError( String ),
  /// environment variable not found
  EnvironmentVariableMissing( String ),
  /// glob pattern error
  #[ cfg( feature = "glob" ) ]
  GlobError( String ),
  /// io error during file operations
  IoError( String ),
  /// path does not exist
  PathNotFound( PathBuf ),
  /// path is outside workspace boundaries
  PathOutsideWorkspace( PathBuf ),
  /// cargo metadata error
  CargoError( String ),
  /// toml parsing error
  TomlError( String ),
  /// serde deserialization error
  #[ cfg( feature = "serde" ) ]
  SerdeError( String ),
  /// config validation error
  #[ cfg( feature = "validation" ) ]
  ValidationError( String ),
  /// secret validation error
  #[ cfg( feature = "secure" ) ]
  SecretValidationError( String ),
  /// secret injection error
  #[ cfg( feature = "secure" ) ]
  SecretInjectionError( String ),
}

impl core::fmt::Display for WorkspaceError
{
  #[ inline ]
  #[ allow( clippy::elidable_lifetime_names ) ]
  fn fmt< 'a >( &self, f: &mut core::fmt::Formatter< 'a > ) -> core::fmt::Result
  {
  match self
  {
   WorkspaceError::ConfigurationError( msg ) =>
  write!( f, "configuration error: {msg}" ),
   WorkspaceError::EnvironmentVariableMissing( var ) =>
  write!( f, "environment variable '{var}' not found. ensure .cargo/config.toml is properly configured with WORKSPACE_PATH" ),
   #[ cfg( feature = "glob" ) ]
   WorkspaceError::GlobError( msg ) =>
  write!( f, "glob pattern error: {msg}" ),
   WorkspaceError::IoError( msg ) =>
  write!( f, "io error: {msg}" ),
   WorkspaceError::PathNotFound( path ) =>
  write!( f, "path not found: {}. ensure the workspace structure is properly initialized", path.display() ),
   WorkspaceError::PathOutsideWorkspace( path ) =>
  write!( f, "path is outside workspace boundaries: {}", path.display() ),
  WorkspaceError::CargoError( msg ) =>
  write!( f, "cargo metadata error: {msg}" ),
  WorkspaceError::TomlError( msg ) =>
  write!( f, "toml parsing error: {msg}" ),
   #[ cfg( feature = "serde" ) ]
   WorkspaceError::SerdeError( msg ) =>
  write!( f, "serde error: {msg}" ),
   #[ cfg( feature = "validation" ) ]
   WorkspaceError::ValidationError( msg ) =>
  write!( f, "config validation error: {msg}" ),
   #[ cfg( feature = "secure" ) ]
   WorkspaceError::SecretValidationError( msg ) =>
  write!( f, "secret validation error: {msg}" ),
   #[ cfg( feature = "secure" ) ]
   WorkspaceError::SecretInjectionError( msg ) =>
  write!( f, "secret injection error: {msg}" ),
  }
  }
}

impl core ::error ::Error for WorkspaceError {}

/// result type for workspace operations
pub type Result< T > = core ::result ::Result< T, WorkspaceError >;

/// trait for types that support automatic secret injection
///
/// configuration types can implement this trait to enable automatic
/// secret injection from workspace secret files
#[ cfg( feature = "secure" ) ]
pub trait SecretInjectable
{
  /// inject a secret value for the given key
  ///
  /// # Errors
  ///
  /// returns error if the key is not recognized or injection fails
  fn inject_secret( &mut self, key: &str, value: String ) -> Result< () >;

  /// validate all injected secrets meet security requirements
  ///
  /// # Errors
  ///
  /// returns error if any secret fails validation
  fn validate_secrets( &self ) -> Result< () >;
}

/// workspace path resolver providing centralized access to workspace-relative paths
///
/// the workspace struct encapsulates workspace root detection and provides methods
/// for resolving standard directory paths and joining workspace-relative paths safely.
#[ derive( Debug, Clone ) ]
pub struct Workspace
{
  root: PathBuf,
}

impl Workspace
{
  /// create workspace from a given root path
  ///
  /// # Arguments
  ///
  /// * `root` - the root directory path for the workspace
  ///
  /// # Examples
  ///
  /// ```rust
  /// use workspace_tools ::Workspace;
  /// use std ::path ::PathBuf;
  ///
  /// let workspace = Workspace ::new( PathBuf ::from( "/path/to/workspace" ) );
  /// ```
  #[ must_use ]
  #[ inline ]
  pub fn new< P: Into< PathBuf > >( root: P ) -> Self
  {
  let root = root.into();
  let root = Self ::cleanup_path( root );
  Self { root }
  }

  /// resolve workspace from environment variables
  ///
  /// reads the `WORKSPACE_PATH` environment variable set by cargo configuration
  /// and validates that the workspace root exists.
  ///
  /// # errors
  ///
  /// returns error if :
  /// - `WORKSPACE_PATH` environment variable is not set
  /// - the path specified by `WORKSPACE_PATH` does not exist
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::Workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let workspace = Workspace ::resolve()?;
  /// println!( "workspace root: {}", workspace.root().display() );
  /// # Ok(())
  /// # }
  /// ```
  /// 
  /// # Errors
  /// 
  /// Returns an error if the workspace path environment variable is not set or the path doesn't exist.
  #[ inline ]
  pub fn resolve() -> Result< Self >
  {
  let root = Self ::get_env_path( "WORKSPACE_PATH" )?;

  if !root.exists()
  {
   return Err( WorkspaceError::PathNotFound( root ) );
  }

  Ok( Self { root } )
  }

  /// resolve workspace with extended fallback strategies
  ///
  /// tries multiple strategies to find workspace root, including user-configured
  /// locations for installed CLI applications:
  ///
  /// 1. cargo workspace detection (developer context)
  /// 2. `WORKSPACE_PATH` environment variable (cargo operations)
  /// 3. git repository root with Cargo.toml (developer context)
  /// 4. `$PRO` environment variable (user-configured project root)
  /// 5. `$HOME` directory (universal fallback)
  /// 6. current working directory (last resort)
  ///
  /// this method is designed for CLI applications that need to work both during
  /// development (via `cargo run`) and after installation (via `cargo install`).
  ///
  /// # examples
  ///
  /// ```rust
  /// use workspace_tools ::Workspace;
  ///
  /// // this will always succeed with some workspace root
  /// let workspace = Workspace ::resolve_with_extended_fallbacks();
  /// ```
  ///
  /// # resolution priority
  ///
  /// **developer contexts** (cargo operations):
  /// - `from_cargo_workspace()` → finds cargo workspace via metadata
  /// - `resolve()` → uses `WORKSPACE_PATH` from .cargo/config.toml
  /// - `from_git_root()` → searches upward for .git + Cargo.toml
  ///
  /// **user contexts** (installed binaries):
  /// - `from_pro_env()` → uses `$PRO` environment variable
  /// - `from_home_dir()` → uses `$HOME` or `%USERPROFILE%`
  ///
  /// **fallback**:
  /// - `from_cwd()` → current working directory
  #[ must_use ]
  #[ inline ]
  pub fn resolve_with_extended_fallbacks() -> Self
  {
  Self ::from_cargo_workspace()
   .or_else( |_| Self ::resolve() )
   .or_else( |_| Self ::from_git_root() )
   .or_else( |_| Self ::from_pro_env() )     // ← NEW: $PRO fallback
   .or_else( |_| Self ::from_home_dir() )    // ← NEW: $HOME fallback
   .unwrap_or_else( |_| Self ::from_cwd() )
  }

  /// resolve workspace with fallback strategies
  ///
  /// # deprecated
  ///
  /// use `resolve_with_extended_fallbacks()` instead. this method lacks
  /// support for installed CLI application contexts ($PRO and $HOME fallbacks).
  ///
  /// # migration
  ///
  /// ```rust
  /// // old:
  /// # use workspace_tools ::Workspace;
  /// let ws = Workspace ::resolve_or_fallback();
  ///
  /// // new:
  /// let ws = Workspace ::resolve_with_extended_fallbacks();
  /// ```
  ///
  /// # examples
  ///
  /// ```rust
  /// use workspace_tools ::Workspace;
  ///
  /// // this will always succeed with some workspace root
  /// let workspace = Workspace ::resolve_or_fallback();
  /// ```
  #[ deprecated(
  since = "0.8.0",
  note = "use `resolve_with_extended_fallbacks()` for installed CLI app support"
 ) ]
  #[ must_use ]
  #[ inline ]
  pub fn resolve_or_fallback() -> Self
  {
  {
   Self ::from_cargo_workspace()
  .or_else( |_| Self ::resolve() )
  .or_else( |_| Self ::from_current_dir() )
  .or_else( |_| Self ::from_git_root() )
  .unwrap_or_else( |_| Self ::from_cwd() )
  }
  }

  /// create workspace from current working directory
  ///
  /// # Errors
  ///
  /// returns error if current directory cannot be accessed
  #[ inline ]
  pub fn from_current_dir() -> Result< Self >
  {
  let root = env ::current_dir()
   .map_err( | e | WorkspaceError::IoError( e.to_string() ) )?;
  Ok( Self { root } )
  }

  /// create workspace from git repository root
  ///
  /// searches upward from current directory for .git directory
  ///
  /// # Errors
  ///
  /// returns error if current directory cannot be accessed or no .git directory found
  #[ inline ]
  pub fn from_git_root() -> Result< Self >
  {
  let mut current = env ::current_dir()
   .map_err( | e | WorkspaceError::IoError( e.to_string() ) )?;

  loop
  {
   if current.join( ".git" ).exists()
   {
  return Ok( Self { root: current } );
  }

   match current.parent()
   {
  Some( parent ) => current = parent.to_path_buf(),
  None => return Err( WorkspaceError::PathNotFound( current ) ),
  }
  }
  }

  /// create workspace from current working directory (infallible)
  ///
  /// this method will not fail - it uses current directory or root as fallback
  #[ must_use ]
  #[ inline ]
  pub fn from_cwd() -> Self
  {
  let root = env ::current_dir().unwrap_or_else( |_| PathBuf ::from( "/" ) );
  Self { root }
  }

  /// create workspace from $PRO environment variable
  ///
  /// intended for users who organize projects under a common root directory.
  /// the $PRO environment variable should point to the projects root.
  ///
  /// # setup
  ///
  /// ```bash
  /// # linux/mac
  /// export PRO=~/pro
  /// echo 'export PRO=~/pro' >> ~/.bashrc
  ///
  /// # windows
  /// set PRO=%USERPROFILE%\pro
  /// setx PRO "%USERPROFILE%\pro"
  /// ```
  ///
  /// # examples
  ///
  /// ```rust
  /// use workspace_tools ::Workspace;
  ///
  /// // user has: export PRO=~/pro
  /// # std ::env ::set_var( "PRO", std ::env ::current_dir().unwrap() );
  /// let workspace = Workspace ::from_pro_env().unwrap();
  /// // workspace.root() → /home/user/pro
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if:
  /// - $PRO environment variable is not set
  /// - path specified by $PRO does not exist
  ///
  /// # use cases
  ///
  /// - installed CLI tools needing workspace-level secrets
  /// - multi-project users with organized directory structure
  /// - CI/CD environments with standardized project layouts
  #[ inline ]
  pub fn from_pro_env() -> Result< Self >
  {
  let pro_path = env ::var( "PRO" )
   .map_err( |_| WorkspaceError::EnvironmentVariableMissing( "PRO".to_string() ) )?;

  let root = PathBuf ::from( pro_path );

  if !root.exists()
  {
   return Err( WorkspaceError::PathNotFound( root ) );
  }

  let root = Self ::cleanup_path( root );
  Ok( Self { root } )
  }

  /// create workspace from user home directory
  ///
  /// universal fallback using the standard home directory location.
  /// works cross-platform by checking both unix ($HOME) and windows (%USERPROFILE%).
  ///
  /// # examples
  ///
  /// ```rust
  /// use workspace_tools ::Workspace;
  ///
  /// let workspace = Workspace ::from_home_dir().unwrap();
  /// // linux/mac: workspace.root() → /home/user
  /// // windows:   workspace.root() → C:\Users\user
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if:
  /// - neither $HOME nor %USERPROFILE% environment variables are set
  /// - resolved path does not exist
  ///
  /// # use cases
  ///
  /// - simple secret storage in ~/secret/ directory
  /// - casual users without complex project organization
  /// - minimal configuration requirement for CLI tools
  #[ inline ]
  pub fn from_home_dir() -> Result< Self >
  {
  let home_path = env ::var( "HOME" )
   .or_else( |_| env ::var( "USERPROFILE" ) )  // windows compatibility
   .map_err( |_| WorkspaceError::EnvironmentVariableMissing(
  "HOME or USERPROFILE".to_string()
 ) )?;

  let root = PathBuf ::from( home_path );

  if !root.exists()
  {
   return Err( WorkspaceError::PathNotFound( root ) );
  }

  let root = Self ::cleanup_path( root );
  Ok( Self { root } )
  }

  /// get workspace root directory
  ///
  /// # Path Normalization Guarantees
  ///
  /// the returned path is guaranteed to be:
  /// - absolute (not relative)
  /// - normalized (no `/./ ` or trailing `/.`)
  /// - preserves symlinks (does not resolve to canonical path)
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  /// let root = ws.root();
  ///
  /// // always absolute
  /// assert!( root.is_absolute() );
  ///
  /// // never contains "/./"
  /// assert!( !root.to_string_lossy().contains( "/./" ) );
  ///
  /// // never ends with "/."
  /// assert!( !root.to_string_lossy().ends_with( "/." ) );
  ///
  /// // clean path joining
  /// let secret_dir = root.join( "secret" );
  /// // produces: "/path/to/workspace/secret" not "/path/to/workspace/./secret"
  /// # Ok(())
  /// # }
  /// ```
  #[ must_use ]
  #[ inline ]
  pub fn root( &self ) -> &Path
  {
  &self.root
  }

  /// join path components relative to workspace root
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  /// let config_file = ws.join( "config/app.toml" );
  /// # Ok(())
  /// # }
  /// ```
  #[ inline ]
  pub fn join< P: AsRef< Path > >( &self, path: P ) -> PathBuf
  {
  self.root.join( path )
  }

  /// get standard configuration directory
  ///
  /// returns `workspace_root/config`
  #[ must_use ]
  #[ inline ]
  pub fn config_dir( &self ) -> PathBuf
  {
  self.root.join( "config" )
  }

  /// get standard data directory
  ///
  /// returns `workspace_root/data`
  #[ must_use ]
  #[ inline ]
  pub fn data_dir( &self ) -> PathBuf
  {
  self.root.join( "data" )
  }

  /// get standard logs directory
  ///
  /// returns `workspace_root/logs`
  #[ must_use ]
  #[ inline ]
  pub fn logs_dir( &self ) -> PathBuf
  {
  self.root.join( "logs" )
  }

  /// get standard documentation directory
  ///
  /// returns `workspace_root/docs`
  #[ must_use ]
  #[ inline ]
  pub fn docs_dir( &self ) -> PathBuf
  {
  self.root.join( "docs" )
  }

  /// get standard tests directory
  ///
  /// returns `workspace_root/tests`
  #[ must_use ]
  #[ inline ]
  pub fn tests_dir( &self ) -> PathBuf
  {
  self.root.join( "tests" )
  }

  /// get workspace metadata directory
  ///
  /// returns `workspace_root/.workspace`
  #[ must_use ]
  #[ inline ]
  pub fn workspace_dir( &self ) -> PathBuf
  {
  self.root.join( ".workspace" )
  }

  /// get path to workspace cargo.toml
  ///
  /// returns `workspace_root/Cargo.toml`
  #[ must_use ]
  #[ inline ]
  pub fn cargo_toml( &self ) -> PathBuf
  {
  self.root.join( "Cargo.toml" )
  }

  /// get path to workspace readme
  ///
  /// returns `workspace_root/readme.md`
  #[ must_use ]
  #[ inline ]
  pub fn readme( &self ) -> PathBuf
  {
  self.root.join( "readme.md" )
  }

  /// validate workspace structure
  ///
  /// checks that workspace root exists and is accessible
  ///
  /// # Errors
  ///
  /// returns error if workspace root is not accessible or is not a directory
  #[ inline ]
  pub fn validate( &self ) -> Result< () >
  {
  if !self.root.exists()
  {
   return Err( WorkspaceError::PathNotFound( self.root.clone() ) );
  }

  if !self.root.is_dir()
  {
   return Err( WorkspaceError::ConfigurationError(
  format!( "workspace root is not a directory: {}", self.root.display() )
 ) );
  }

  Ok( () )
  }

  /// check if a path is within workspace boundaries
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  /// let config_path = ws.join( "config/app.toml" );
  ///
  /// assert!( ws.is_workspace_file( &config_path ) );
  /// assert!( !ws.is_workspace_file( "/etc/passwd" ) );
  /// # Ok(())
  /// # }
  /// ```
  #[ inline ]
  pub fn is_workspace_file< P: AsRef< Path > >( &self, path: P ) -> bool
  {
  path.as_ref().starts_with( &self.root )
  }

  /// normalize path for cross-platform compatibility
  ///
  /// resolves symbolic links and canonicalizes the path
  ///
  /// # Errors
  ///
  /// returns error if path cannot be canonicalized or does not exist
  #[ inline ]
  pub fn normalize_path< P: AsRef< Path > >( &self, path: P ) -> Result< PathBuf >
  {
  let path = self.join( path );
  path.canonicalize()
   .map_err( | e | WorkspaceError::IoError( format!( "failed to normalize path {} : {}", path.display(), e ) ) )
  }

  /// get environment variable as path
  fn get_env_path( key: &str ) -> Result< PathBuf >
  {
  let value = env ::var( key )
   .map_err( |_| WorkspaceError::EnvironmentVariableMissing( key.to_string() ) )?;

  // reject empty paths
  if value.is_empty()
  {
   return Err( WorkspaceError::PathNotFound( PathBuf ::from( "" ) ) );
  }

  let path = PathBuf ::from( value );

  // if relative path, resolve against current directory
  let absolute = if path.is_relative()
  {
   env ::current_dir()
    .map_err( | e | WorkspaceError::IoError( e.to_string() ) )?
    .join( path )
  }
  else
  {
   path
  };

  // normalize to remove trailing "." and other redundancies
  Ok( Self ::cleanup_path( absolute ) )
  }

  /// cleanup path by removing redundant components
  ///
  /// removes trailing `/.` and `/./` components without resolving symlinks
  fn cleanup_path< P: AsRef< Path > >( path: P ) -> PathBuf
  {
  // manual normalization without canonicalization (preserves symlinks)
  let mut normalized = PathBuf::new();
  let mut components = path.as_ref().components().peekable();

  while let Some( component ) = components.next()
  {
   use std ::path ::Component;
   match component
   {
    Component ::CurDir =>
    {
     // skip "." unless it's the only component
     if normalized.as_os_str().is_empty() && components.peek().is_none()
     {
      normalized.push( "." );
     }
    }
    Component ::ParentDir =>
    {
     // handle ".." by popping parent
     if !normalized.pop()
     {
      // if we cant pop (at root), keep the ParentDir
      normalized.push( component );
     }
    }
    _ => normalized.push( component ),
   }
  }

  normalized
  }

  /// find configuration file by name
  ///
  /// searches for configuration files in standard locations :
  /// - config/{name}.toml
  /// - config/{name}.yaml
  /// - config/{name}.json
  /// - .{name}.toml (dotfile in workspace root)
  ///
  /// # Errors
  ///
  /// returns error if no configuration file with the given name is found
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // looks for config/database.toml, config/database.yaml, etc.
  /// if let Ok( config_path ) = ws.find_config( "database" )
  /// {
  ///     println!( "found config at: {}", config_path.display() );
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn find_config( &self, name: &str ) -> Result< PathBuf >
  {
  let candidates = vec!
  [
   self.config_dir().join( format!( "{name}.toml" ) ),
   self.config_dir().join( format!( "{name}.yaml" ) ),
   self.config_dir().join( format!( "{name}.yml" ) ),
   self.config_dir().join( format!( "{name}.json" ) ),
   self.root.join( format!( ".{name}.toml" ) ),
   self.root.join( format!( ".{name}.yaml" ) ),
   self.root.join( format!( ".{name}.yml" ) ),
 ];

  for candidate in candidates
  {
   if candidate.exists()
   {
  return Ok( candidate );
  }
  }

  Err( WorkspaceError::PathNotFound(
   self.config_dir().join( format!( "{name}.toml" ) )
 ) )
  }
}

// cargo integration types and implementations
/// cargo metadata information for workspace
#[ derive( Debug, Clone ) ]
pub struct CargoMetadata
{
  /// root directory of the cargo workspace
  pub workspace_root: PathBuf,
  /// list of workspace member packages
  pub members: Vec< CargoPackage >,
  /// workspace-level dependencies
  pub workspace_dependencies: HashMap< String, String >,
}

/// information about a cargo package within a workspace
#[ derive( Debug, Clone ) ]
pub struct CargoPackage
{
  /// package name
  pub name: String,
  /// package version
  pub version: String,
  /// path to the package's Cargo.toml
  pub manifest_path: PathBuf,
  /// root directory of the package
  pub package_root: PathBuf,
}

// serde integration types
#[ cfg( feature = "serde" ) ]
/// trait for configuration types that can be merged
pub trait ConfigMerge: Sized
{
  /// merge this configuration with another, returning the merged result
  #[ must_use ]
  fn merge( self, other: Self ) -> Self;
}

#[ cfg( feature = "serde" ) ]
/// workspace-aware serde deserializer
#[ derive( Debug ) ]
pub struct WorkspaceDeserializer< 'ws >
{
  /// reference to workspace for path resolution
  pub workspace: &'ws Workspace,
}

#[ cfg( feature = "serde" ) ]
/// custom serde field for workspace-relative paths
#[ derive( Debug, Clone, PartialEq ) ]
pub struct WorkspacePath( pub PathBuf );

// conditional compilation for optional features

#[ cfg( feature = "glob" ) ]
impl Workspace
{
  /// find files matching a glob pattern within the workspace
  ///
  /// # Errors
  ///
  /// returns error if the glob pattern is invalid or if there are errors reading the filesystem
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // find all rust source files
  /// let rust_files = ws.find_resources( "src/**/*.rs" )?;
  ///
  /// // find all configuration files
  /// let configs = ws.find_resources( "config/**/*.toml" )?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn find_resources( &self, pattern: &str ) -> Result< Vec< PathBuf > >
  {
  let full_pattern = self.join( pattern );
  let pattern_str = full_pattern.to_string_lossy();

  let mut results = Vec ::new();

  for entry in glob( &pattern_str )
   .map_err( | e | WorkspaceError::GlobError( e.to_string() ) )?
  {
   match entry
   {
  Ok( path ) => results.push( path ),
  Err( e ) => return Err( WorkspaceError::GlobError( e.to_string() ) ),
  }
  }

  Ok( results )
  }

}

#[ cfg( feature = "secrets" ) ]
impl Workspace
{
  /// get secrets directory path
  ///
  /// returns `workspace_root/secret`
  #[ must_use ]
  pub fn secret_dir( &self ) -> PathBuf
  {
  self.root.join( "secret" )
  }

  /// get path to secret configuration file
  ///
  /// returns `workspace_root/secret/{name}`
  #[ must_use ]
  pub fn secret_file( &self, name: &str ) -> PathBuf
  {
  self.secret_dir().join( name )
  }

  /// load secrets from a file in the workspace secrets directory
  ///
  /// supports shell script format (KEY=value lines) and loads secrets from filenames
  /// within the workspace `secret/` directory
  ///
  /// # Path Resolution
  ///
  /// Files are resolved as: `workspace_root/secret/{filename}`
  ///
  /// **Important** : This method expects a filename, not a path. If you need to load
  /// from a path, use `load_secrets_from_path()` instead.
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // ✅ Correct usage - simple filenames only
  /// // let secrets = ws.load_secrets_from_file( "-secrets.sh" )?;      // -> secret/-secrets.sh
  /// // let dev = ws.load_secrets_from_file( "development.env" )?;      // -> secret/development.env
  ///
  /// // ❌ Common mistake - using paths (will emit warning)
  /// // let secrets = ws.load_secrets_from_file( "config/secrets.env" )?; // DON'T DO THIS
  ///
  /// // ✅ For paths, use the path-specific method instead
  /// // let path_secrets = ws.load_secrets_from_path( "config/secrets.env" )?; // -> workspace/config/secrets.env
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_from_file( &self, filename: &str ) -> Result< HashMap< String, String > >
  {
  Self::warn_if_path_like( filename );
  self.try_load_secrets_with_fallback( filename )
  }

  /// load a specific secret key with fallback to environment
  ///
  /// tries to load from secret file first, then falls back to environment variable
  /// this method uses filename-based resolution (looks in secret/ directory)
  ///
  /// # Path Resolution
  ///
  /// Files are resolved as: `workspace_root/secret/{filename}`
  ///
  /// # Fallback Strategy
  ///
  /// 1. First attempts to load from secrets file
  /// 2. If key not found in file or file doesn't exist, checks environment variables
  /// 3. If neither source contains the key, returns error
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // ✅ Correct usage - filename only
  /// match ws.load_secret_key( "API_KEY", "-secrets.sh" )  // -> secret/-secrets.sh
  /// {
  ///     Ok( key ) => println!( "loaded api key from file or environment" ),
  ///     Err( e ) => println!( "api key not found: {}", e ),
  /// }
  ///
  /// // ❌ Common mistake - using paths (will emit warning)
  /// // let key = ws.load_secret_key( "API_KEY", "config/secrets.env" )?; // DON'T DO THIS
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the key is not found in either the secret file or environment variables
  pub fn load_secret_key( &self, key_name: &str, filename: &str ) -> Result< String >
  {
  let secret_file_path = self.secret_file( filename );

  // try loading from secret file first
  if let Ok( secrets ) = self.load_secrets_from_file( filename )
  {
   if let Some( value ) = secrets.get( key_name )
   {
  return Ok( value.clone() );
  }
  }

  // fallback to environment variable
  env ::var( key_name )
   .map_err( |_| WorkspaceError::ConfigurationError(
  format!(
   "{} not found in secrets file '{}' (resolved to: {}) or environment variables",
   key_name,
   filename,
   secret_file_path.display()
 )
 ))
  }

  /// parse key-value file content
  ///
  /// supports multiple formats :
  /// - shell script format with comments and quotes
  /// - export statements: `export KEY=VALUE`
  /// - standard dotenv format: `KEY=VALUE`
  /// - mixed formats in same file
  fn parse_key_value_file( content: &str ) -> HashMap< String, String >
  {
  let mut secrets = HashMap ::new();

  for line in content.lines()
  {
   let line = line.trim();

   // skip empty lines and comments
   if line.is_empty() || line.starts_with( '#' )
   {
  continue;
  }

   // handle export statements by stripping 'export ' prefix
   let processed_line = if line.starts_with( "export " )
   {
  line.strip_prefix( "export " ).unwrap_or( line ).trim()
  }
   else
   {
  line
 };

   // parse KEY=VALUE format
   if let Some( ( key, value ) ) = processed_line.split_once( '=' )
   {
  let key = key.trim();
  let value = value.trim();

  // remove quotes if present
  let value = if ( value.starts_with( '"' ) && value.ends_with( '"' ) ) ||
   ( value.starts_with( '\'' ) && value.ends_with( '\'' ) )
  {
   &value[ 1..value.len() - 1 ]
  }
  else
  {
   value
 };

  secrets.insert( key.to_string(), value.to_string() );
  }
  }

  secrets
  }

  /// warn if filename contains path separators
  ///
  /// emits warning to stderr if filename looks like a path rather than a simple filename
  /// this helps users understand they should use path-specific methods for paths
  fn warn_if_path_like( filename: &str )
  {
  if filename.contains( '/' ) || filename.contains( '\\' )
  {
   eprintln!(
  "⚠️  Warning: '{filename}' contains path separators. Use load_secrets_from_path() for paths."
 );
  }
  }

  /// try loading secrets from fallback chain
  ///
  /// implements automatic fallback with proper corner case handling:
  /// 1. local workspace: `workspace_root/secret/{filename}`
  /// 2. `$PRO` workspace: `$PRO/secret/{filename}` (if `$PRO` set and valid)
  /// 3. `$HOME` directory: `$HOME/secret/{filename}` (if `$HOME`/`$USERPROFILE` set and valid)
  ///
  /// uses path canonicalization to avoid reading same file multiple times
  fn try_load_secrets_with_fallback( &self, filename: &str ) -> Result< HashMap< String, String > >
  {
  let mut tried_paths = Vec ::new();
  let mut canonical_paths = std ::collections ::HashSet ::new();

  // 1. try local workspace first
  let local_path = self.secret_file( filename );
  tried_paths.push( format!( "  - {} (local workspace)", local_path.display() ) );

  if let Some( canonical ) = Self::try_canonicalize( &local_path )
  {
   canonical_paths.insert( canonical );
   if local_path.exists()
   {
     match Self::read_secret_file_validated( &local_path )
     {
       Ok( content ) => return Ok( Self::parse_key_value_file( &content ) ),
       Err( e ) => return Err( e ),
     }
   }
  }

  // 2. try $PRO workspace if different
  if let Ok( pro_env ) = env::var( "PRO" )
  {
   if !pro_env.trim().is_empty()
   {
     if let Ok( pro_ws ) = Workspace::from_pro_env()
     {
       let pro_path = pro_ws.secret_file( filename );
       if let Some( canonical ) = Self::try_canonicalize( &pro_path )
       {
         if !canonical_paths.contains( &canonical )
         {
           canonical_paths.insert( canonical );
           tried_paths.push( format!( "  - {} ($PRO workspace)", pro_path.display() ) );
           if pro_path.exists()
           {
             match Self::read_secret_file_validated( &pro_path )
             {
               Ok( content ) => return Ok( Self::parse_key_value_file( &content ) ),
               Err( e ) => return Err( e ),
             }
           }
         }
       }
     }
   }
  }

  // 3. try $HOME workspace if different
  #[ cfg( not( target_os = "windows" ) ) ]
  let home_env_var = "HOME";
  #[ cfg( target_os = "windows" ) ]
  let home_env_var = "USERPROFILE";

  if let Ok( home_env ) = env::var( home_env_var )
  {
   if !home_env.trim().is_empty()
   {
     if let Ok( home_ws ) = Workspace::from_home_dir()
     {
       let home_path = home_ws.secret_file( filename );
       if let Some( canonical ) = Self::try_canonicalize( &home_path )
       {
         if !canonical_paths.contains( &canonical )
         {
           canonical_paths.insert( canonical );
           tried_paths.push( format!( "  - {} ($HOME directory)", home_path.display() ) );
           if home_path.exists()
           {
             match Self::read_secret_file_validated( &home_path )
             {
               Ok( content ) => return Ok( Self::parse_key_value_file( &content ) ),
               Err( e ) => return Err( e ),
             }
           }
         }
       }
     }
   }
  }

  // none found - return error with helpful message including available files
  let mut error_msg = format!(
   "Secrets file '{}' not found in any location.\n\nTried:\n{}",
   filename,
   tried_paths.join( "\n" )
  );

  if let Ok( available_files ) = self.list_secrets_files()
  {
   if !available_files.is_empty()
   {
     error_msg.push_str( "\n\nAvailable files: " );
     error_msg.push_str( &available_files.join( ", " ) );
   }
  }

  error_msg.push_str( "\n\nCreate secret file in one of the above locations." );
  Err( WorkspaceError::ConfigurationError( error_msg ) )
  }

  /// try to canonicalize path, return None if it fails
  ///
  /// used for path deduplication to handle symlinks and path normalization
  fn try_canonicalize( path: &Path ) -> Option< PathBuf >
  {
  path.canonicalize().ok()
  }

  /// read secret file with validation checks
  ///
  /// validates file type (must be regular file) and size (max 10MB)
  /// provides clear error messages for common issues
  fn read_secret_file_validated( path: &Path ) -> Result< String >
  {
  let metadata = fs::metadata( path )
   .map_err( | e | WorkspaceError::IoError( format!( "Failed to read secrets file\n  Absolute path: {}\n  Error: {}", path.display(), e ) ) )?;

  // validate file type - must be regular file
  if !metadata.is_file()
  {
   let file_type = if metadata.is_dir() { "directory" }
     else if metadata.file_type().is_symlink() { "symbolic link" }
     else { "special file (device, socket, or pipe)" };

   return Err( WorkspaceError::ConfigurationError( format!(
     "Secrets file is a {}, not a regular file\n  Path: {}",
     file_type, path.display()
   ) ) );
  }

  // validate file size - max 10MB to prevent OOM
  const MAX_SIZE: u64 = 10 * 1024 * 1024;
  if metadata.len() > MAX_SIZE
  {
   return Err( WorkspaceError::ConfigurationError( format!(
     "Secrets file too large ({} bytes, max {} bytes)\n  Path: {}\n  Hint: Secret files should be small key-value files",
     metadata.len(), MAX_SIZE, path.display()
   ) ) );
  }

  fs::read_to_string( path )
   .map_err( | e | WorkspaceError::IoError( format!( "Failed to read secrets file\n  Absolute path: {}\n  Error: {}", path.display(), e ) ) )
  }

  /// list available secrets files in the secrets directory
  ///
  /// returns vector of filenames (not full paths) found in secret/ directory
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  /// let files = ws.list_secrets_files()?;
  /// println!( "Available secret files: {:?}", files );
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the secrets directory cannot be read
  pub fn list_secrets_files( &self ) -> Result< Vec< String > >
  {
  let secret_dir = self.secret_dir();

  if !secret_dir.exists()
  {
   return Ok( Vec ::new() );
  }

  let entries = fs ::read_dir( &secret_dir )
   .map_err( | e | WorkspaceError::IoError( format!( "failed to read secrets directory {} : {}", secret_dir.display(), e ) ) )?;

  let mut files = Vec ::new();

  for entry in entries
  {
   let entry = entry
  .map_err( | e | WorkspaceError::IoError( format!( "failed to read directory entry: {e}" ) ) )?;

   let path = entry.path();

   if path.is_file()
   {
  if let Some( filename ) = path.file_name()
  {
   if let Some( filename_str ) = filename.to_str()
   {
  files.push( filename_str.to_string() );
  }
  }
  }
  }

  files.sort();
  Ok( files )
  }

  /// check if a secrets file exists
  ///
  /// returns true if the file exists in the secrets directory
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// if ws.secrets_file_exists( "-secrets.sh" )
  /// {
  ///     println!( "secrets file found" );
  /// }
  /// # Ok(())
  /// # }
  /// ```
  #[ must_use ]
  pub fn secrets_file_exists( &self, secret_file_name: &str ) -> bool
  {
  self.secret_file( secret_file_name ).exists()
  }

  /// get resolved path for secrets file (for debugging)
  ///
  /// returns the full path where the secrets file would be located
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  /// let path = ws.resolve_secrets_path( "-secrets.sh" );
  /// println!( "Secrets file would be at: {}", path.display() );
  /// # Ok(())
  /// # }
  /// ```
  #[ must_use ]
  pub fn resolve_secrets_path( &self, secret_file_name: &str ) -> PathBuf
  {
  self.secret_file( secret_file_name )
  }

  /// load secrets from workspace-relative path
  ///
  /// loads secrets from a file specified as a path relative to the workspace root
  /// use this method when you need to load secrets from custom locations
  ///
  /// # Path Resolution
  ///
  /// Files are resolved as: `workspace_root/{relative_path}`
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // load from config/secrets.env (workspace_root/config/secrets.env)
  /// // let secrets = ws.load_secrets_from_path( "config/secrets.env" )?;
  ///
  /// // load from nested directory
  /// // let nested = ws.load_secrets_from_path( "lib/project/secret/api.env" )?;
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_from_path( &self, relative_path: &str ) -> Result< HashMap< String, String > >
  {
  let secret_file = self.join( relative_path );
  let content = Self::read_secret_file_validated( &secret_file )?;
  Ok( Self::parse_key_value_file( &content ) )
  }

  /// load secrets from absolute path
  ///
  /// loads secrets from a file specified as an absolute filesystem path
  /// use this method when you need to load secrets from locations outside the workspace
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  /// use std ::path ::Path;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // load from absolute path
  /// let absolute_path = Path ::new( "/etc/secrets/production.env" );
  /// // let secrets = ws.load_secrets_from_absolute_path( absolute_path )?;
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_from_absolute_path( &self, absolute_path: &Path ) -> Result< HashMap< String, String > >
  {
  let content = Self::read_secret_file_validated( absolute_path )?;
  Ok( Self::parse_key_value_file( &content ) )
  }

  /// load secrets with verbose debug information
  ///
  /// provides detailed path resolution and validation information for debugging
  /// use this method when troubleshooting secret loading issues
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // load with debug output
  /// match ws.load_secrets_with_debug( "-secrets.sh" )
  /// {
  ///     Ok( secrets ) => println!( "Loaded {} secrets", secrets.len() ),
  ///     Err( e ) => println!( "Failed to load secrets: {}", e ),
  /// }
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_with_debug( &self, secret_file_name: &str ) -> Result< HashMap< String, String > >
  {
  println!( "🔍 Debug: Loading secrets with detailed information" );
  println!( "   Parameter: '{secret_file_name}'" );

  // check for path-like parameter
  if secret_file_name.contains( '/' ) || secret_file_name.contains( '\\' )
  {
   println!( "   ⚠️  Parameter contains path separators - consider using load_secrets_from_path()" );
  }

  let secret_file = self.secret_file( secret_file_name );
  println!( "   Resolved path: {}", secret_file.display() );
  println!( "   File exists: {}", secret_file.exists() );

  // show available files for context
  match self.list_secrets_files()
  {
   Ok( files ) =>
   {
  if files.is_empty()
  {
   println!( "   Available files: none (secrets directory: {})", self.secret_dir().display() );
  }
  else
  {
   println!( "   Available files: {}", files.join( ", " ) );
  }
  }
   Err( e ) => println!( "   Could not list available files: {e}" ),
  }

  // attempt to load normally
  match self.load_secrets_from_file( secret_file_name )
  {
   Ok( secrets ) =>
   {
  println!( "   ✅ Successfully loaded {} secrets", secrets.len() );
  for key in secrets.keys()
  {
   println!( "      - {key}" );
  }
  Ok( secrets )
  }
   Err( e ) =>
   {
  println!( "   ❌ Failed to load secrets: {e}" );
  Err( e )
  }
  }
  }
}

#[ cfg( feature = "secure" ) ]
/// trait for converting plain types to secure memory-protected types
///
/// this trait provides a generic way to convert regular strings and collections
/// into their secure counterparts that use memory protection and zeroization
trait AsSecure
{
  /// the secure version of this type
  type Secure;

  /// convert this value into its secure equivalent
  fn into_secure( self ) -> Self::Secure;
}

#[ cfg( feature = "secure" ) ]
impl AsSecure for String
{
  type Secure = SecretString;

  fn into_secure( self ) -> Self::Secure
  {
  SecretString::new( self )
  }
}

#[ cfg( feature = "secure" ) ]
impl AsSecure for HashMap< String, String >
{
  type Secure = HashMap< String, SecretString >;

  fn into_secure( self ) -> Self::Secure
  {
  self.into_iter()
   .map( | ( key, value ) | ( key, SecretString::new( value ) ) )
   .collect()
  }
}

#[ cfg( feature = "secure" ) ]
impl Workspace
{
  /// load secrets from a file in the workspace secrets directory with memory-safe handling
  ///
  /// returns secrets as `SecretString` types for enhanced security
  /// supports shell script format (KEY=value lines) and loads secrets from filenames
  /// within the workspace `secret/` directory
  ///
  /// # Path Resolution
  ///
  /// Files are resolved as: `workspace_root/secret/{filename}`
  ///
  /// **Important** : This method expects a filename, not a path. If you need to load
  /// from a path, use `load_secrets_from_path_secure()` instead.
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  /// use secrecy ::ExposeSecret;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // ✅ Correct usage - simple filenames only
  /// // let secrets = ws.load_secrets_secure( "-secrets.sh" )?;         // -> secret/-secrets.sh
  /// // let dev = ws.load_secrets_secure( "development.env" )?;         // -> secret/development.env
  ///
  /// // Access secret values (requires explicit expose_secret() call)
  /// // if let Some( api_key ) = secrets.get( "API_KEY" )
  /// // {
  /// //     println!( "loaded api key: {}", api_key.expose_secret() );
  /// // }
  ///
  /// // ❌ Common mistake - using paths (will emit warning)
  /// // let secrets = ws.load_secrets_secure( "config/secrets.env" )?; // DON'T DO THIS
  ///
  /// // ✅ For paths, use the path-specific method instead
  /// // let path_secrets = ws.load_secrets_from_path_secure( "config/secrets.env" )?;
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_secure( &self, filename: &str ) -> Result< HashMap< String, SecretString > >
  {
  self.load_secrets_from_file( filename ).map( AsSecure::into_secure )
  }

  /// load a specific secret key with memory-safe handling and fallback to environment
  ///
  /// tries to load from secret file first, then falls back to environment variable
  /// returns `SecretString` for enhanced security
  ///
  /// # Errors
  ///
  /// returns error if the key is not found in either the secret file or environment variables
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  /// use secrecy ::ExposeSecret;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // looks for API_KEY in secret/-secrets.sh, then in environment
  /// match ws.load_secret_key_secure( "API_KEY", "-secrets.sh" )
  /// {
  ///     Ok( key ) => println!( "loaded api key: {}", key.expose_secret() ),
  ///     Err( _ ) => println!( "api key not found" ),
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn load_secret_key_secure( &self, key_name: &str, filename: &str ) -> Result< SecretString >
  {
  self.load_secret_key( key_name, filename ).map( AsSecure::into_secure )
  }

  /// get environment variable as `SecretString` for memory-safe handling
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  /// use secrecy ::ExposeSecret;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// if let Some( token ) = ws.env_secret( "GITHUB_TOKEN" )
  /// {
  ///     println!( "using secure token: {}", token.expose_secret() );
  /// }
  /// # Ok(())
  /// # }
  /// ```
  #[ must_use ]
  pub fn env_secret( &self, key: &str ) -> Option< SecretString >
  {
  env ::var( key ).ok().map( SecretString ::new )
  }

  /// validate secret strength and security requirements
  ///
  /// checks for common security issues like weak passwords, common patterns, etc.
  ///
  /// # Errors
  ///
  /// returns error if the secret does not meet minimum security requirements
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // this will fail - too weak
  /// assert!( ws.validate_secret( "123" ).is_err() );
  ///
  /// // this will pass - strong secret
  /// assert!( ws.validate_secret( "super-strong-secret-2024!" ).is_ok() );
  /// # Ok(())
  /// # }
  /// ```
  pub fn validate_secret( &self, secret: &str ) -> Result< () >
  {
  if secret.len() < 8
  {
   return Err( WorkspaceError::SecretValidationError( 
  "secret must be at least 8 characters long".to_string() 
 ) );
  }

  if secret == "123" || secret == "password" || secret == "secret" || secret.to_lowercase() == "test"
  {
   return Err( WorkspaceError::SecretValidationError( 
  "secret is too weak or uses common patterns".to_string() 
 ) );
  }

  // check for reasonable complexity (at least some variety)
  let has_letter = secret.chars().any( char ::is_alphabetic );
  let has_number = secret.chars().any( char ::is_numeric );
  let has_special = secret.chars().any( | c | !c.is_alphanumeric() );

  if !( has_letter || has_number || has_special )
  {
   return Err( WorkspaceError::SecretValidationError( 
  "secret should contain letters, numbers, or special characters".to_string() 
 ) );
  }

  Ok( () )
  }

  /// load configuration with automatic secret injection
  ///
  /// replaces `${VAR_NAME}` placeholders in configuration with values from secret files
  ///
  /// # Errors
  ///
  /// returns error if configuration file cannot be read or secret injection fails
  ///
  /// # examples
  ///
  /// ```rust,no_run
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // loads config.toml and replaces ${SECRET} with values from secrets.sh
  /// let config = ws.load_config_with_secret_injection( "config.toml", "secrets.sh" )?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn load_config_with_secret_injection( &self, config_file: &str, secret_file: &str ) -> Result< String >
  {
  // load the configuration file
  let config_path = self.join( config_file );
  let config_content = Self::read_file_to_string( &config_path )?;

  // load secrets securely
  let secrets = self.load_secrets_secure( secret_file )?;

  // perform template substitution
  let mut result = config_content;
  for ( key, secret_value ) in secrets
  {
   let placeholder = format!( "${{{key}}}" );
   let replacement = secret_value.expose_secret();
   result = result.replace( &placeholder, replacement );
  }

  // check for unresolved placeholders
  if result.contains( "${" )
  {
   return Err( WorkspaceError::SecretInjectionError(
  "configuration contains unresolved placeholders - check secret file completeness".to_string()
 ) );
  }

  Ok( result )
  }

  /// load configuration with automatic secret injection using `SecretInjectable` trait
  ///
  /// loads secrets from file and injects them into the configuration type
  ///
  /// # Errors
  ///
  /// returns error if secret loading or injection fails
  ///
  /// # examples
  ///
  /// ```rust,no_run
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// # #[ cfg(feature = "secure") ] {
  /// use workspace_tools :: { workspace, SecretInjectable };
  ///
  /// #[ derive(Debug) ]
  /// struct AppConfig {
  ///     database_url: String,
  ///     api_key: String,
  /// }
  ///
  /// impl SecretInjectable for AppConfig
  /// {
  ///   fn inject_secret(&mut self, key: &str, value: String) -> workspace_tools ::Result< () >
  ///   {
  ///     match key
  ///     {
  ///             "DATABASE_URL" => self.database_url = value,
  ///             "API_KEY" => self.api_key = value,
  ///             _ => return Err(workspace_tools ::WorkspaceError::SecretInjectionError(
  ///                 format!("unknown secret key: {}", key)
  /// )),
  /// }
  ///         Ok(())
  /// }
  ///
  ///     fn validate_secrets( &self ) -> workspace_tools ::Result< () > {
  ///  if self.api_key.is_empty() {
  ///             return Err(workspace_tools ::WorkspaceError::SecretValidationError(
  ///                 "api_key cannot be empty".to_string()
  /// ));
  /// }
  ///         Ok(())
  /// }
  /// }
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  /// let mut config = AppConfig { database_url: String ::new(), api_key: String ::new() };
  ///
  /// // config gets secrets injected from secret/-config.sh
  /// config = ws.load_config_with_secrets( config, "-config.sh" )?;
  /// # }
  /// # Ok(())
  /// # }
  /// ```
  pub fn load_config_with_secrets< T: SecretInjectable >( &self, mut config: T, secret_file: &str ) -> Result< T >
  {
  // load secrets securely
  let secrets = self.load_secrets_secure( secret_file )?;

  // inject each secret into the configuration
  for ( key, secret_value ) in secrets
  {
   config.inject_secret( &key, secret_value.expose_secret().clone() )?;
  }

  // validate the final configuration
  config.validate_secrets()?;

  Ok( config )
  }

  /// load secrets from workspace-relative path with memory-safe handling
  ///
  /// loads secrets from a file specified as a path relative to the workspace root
  /// returns secrets as `SecretString` types for enhanced security
  ///
  /// # Path Resolution
  ///
  /// Files are resolved as: `workspace_root/{relative_path}`
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  /// use secrecy ::ExposeSecret;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // load from config/secrets.env (workspace_root/config/secrets.env)
  /// // let secrets = ws.load_secrets_from_path_secure( "config/secrets.env" )?;
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_from_path_secure( &self, relative_path: &str ) -> Result< HashMap< String, SecretString > >
  {
  self.load_secrets_from_path( relative_path ).map( AsSecure::into_secure )
  }

  /// load secrets from absolute path with memory-safe handling
  ///
  /// loads secrets from a file specified as an absolute filesystem path
  /// returns secrets as `SecretString` types for enhanced security
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  /// use secrecy ::ExposeSecret;
  /// use std ::path ::Path;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // load from absolute path
  /// // let absolute_path = Path ::new( "/etc/secrets/production.env" );
  /// // let secrets = ws.load_secrets_from_absolute_path_secure( absolute_path )?;
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_from_absolute_path_secure( &self, absolute_path: &Path ) -> Result< HashMap< String, SecretString > >
  {
  self.load_secrets_from_absolute_path( absolute_path ).map( AsSecure::into_secure )
  }

  /// load secrets with verbose debug information and memory-safe handling
  ///
  /// provides detailed path resolution and validation information for debugging
  /// returns secrets as `SecretString` types for enhanced security
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::workspace;
  /// use secrecy ::ExposeSecret;
  ///
  /// # std ::env ::set_var( "WORKSPACE_PATH", std ::env ::current_dir().unwrap() );
  /// let ws = workspace()?;
  ///
  /// // load with debug output
  /// match ws.load_secrets_with_debug_secure( "-secrets.sh" )
  /// {
  ///     Ok( secrets ) => println!( "Loaded {} secrets", secrets.len() ),
  ///     Err( e ) => println!( "Failed to load secrets: {}", e ),
  /// }
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Errors
  ///
  /// returns error if the file cannot be read, doesn't exist, or contains invalid format
  pub fn load_secrets_with_debug_secure( &self, secret_file_name: &str ) -> Result< HashMap< String, SecretString > >
  {
  self.load_secrets_with_debug( secret_file_name ).map( AsSecure::into_secure )
  }

}

impl Workspace
{
  /// create workspace from cargo workspace root (auto-detected)
  ///
  /// traverses up directory tree looking for `Cargo.toml` with `[workspace]` section
  /// or workspace member that references a workspace root
  ///
  /// # Errors
  ///
  /// returns error if no cargo workspace is found or if cargo.toml cannot be parsed
  ///
  /// # examples
  ///
  /// ```rust
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// use workspace_tools ::Workspace;
  ///
  /// let workspace = Workspace ::from_cargo_workspace()?;
  /// println!( "cargo workspace root: {}", workspace.root().display() );
  /// # Ok(())
  /// # }
  /// ```
  pub fn from_cargo_workspace() -> Result< Self >
  {
  let workspace_root = Self ::find_cargo_workspace()?;
  let workspace_root = Self ::cleanup_path( workspace_root );
  Ok( Self { root: workspace_root } )
  }

  /// create workspace from specific cargo.toml path
  ///
  /// # Errors
  ///
  /// returns error if the manifest path does not exist or cannot be parsed
  pub fn from_cargo_manifest< P: AsRef< Path > >( manifest_path: P ) -> Result< Self >
  {
  let manifest_path = manifest_path.as_ref();
  
  if !manifest_path.exists()
  {
   return Err( WorkspaceError::PathNotFound( manifest_path.to_path_buf() ) );
  }

  let workspace_root = if manifest_path.file_name() == Some( std ::ffi ::OsStr ::new( "Cargo.toml" ) )
  {
   manifest_path.parent()
  .ok_or_else( || WorkspaceError::ConfigurationError( "invalid manifest path".to_string() ) )?
  .to_path_buf()
  }
  else
  {
   manifest_path.to_path_buf()
 };

  // normalize the path before creating workspace
  let workspace_root = Self ::cleanup_path( workspace_root );

  Ok( Self { root: workspace_root } )
  }

  /// get cargo metadata for this workspace
  ///
  /// # Errors
  ///
  /// returns error if cargo metadata command fails or workspace is not a cargo workspace
  pub fn cargo_metadata( &self ) -> Result< CargoMetadata >
  {
  let cargo_toml = self.cargo_toml();
  
  if !cargo_toml.exists()
  {
   return Err( WorkspaceError::CargoError( "not a cargo workspace".to_string() ) );
  }

  // use cargo_metadata crate for robust metadata extraction
  let metadata = cargo_metadata ::MetadataCommand ::new()
   .manifest_path( &cargo_toml )
   .exec()
   .map_err( | e | WorkspaceError::CargoError( e.to_string() ) )?;

  let mut members = Vec ::new();
  let mut workspace_dependencies = HashMap ::new();

  // extract workspace member information
  for package in metadata.workspace_packages()
  {
   members.push( CargoPackage {
  name: package.name.clone(),
  version: package.version.to_string(),
  manifest_path: package.manifest_path.clone().into(),
  package_root: package.manifest_path
   .parent()
   .unwrap_or( &package.manifest_path )
   .into(),
 } );
  }

  // extract workspace dependencies if available
  if let Some( deps ) = metadata.workspace_metadata.get( "dependencies" )
  {
   if let Some( deps_map ) = deps.as_object()
   {
  for ( name, version ) in deps_map
  {
   if let Some( version_str ) = version.as_str()
   {
  workspace_dependencies.insert( name.clone(), version_str.to_string() );
  }
  }
  }
  }

  Ok( CargoMetadata {
   workspace_root: metadata.workspace_root.into(),
   members,
   workspace_dependencies,
 } )
  }

  /// check if this workspace is a cargo workspace
  #[ must_use ]
  pub fn is_cargo_workspace( &self ) -> bool
  {
  let cargo_toml = self.cargo_toml();
  
  if !cargo_toml.exists()
  {
   return false;
  }

  // check if Cargo.toml contains workspace section
  if let Ok( content ) = std ::fs ::read_to_string( &cargo_toml )
  {
   if let Ok( parsed ) = toml ::from_str :: < toml ::Value >( &content )
   {
  return parsed.get( "workspace" ).is_some();
  }
  }

  false
  }

  /// get workspace members (if cargo workspace)
  ///
  /// # Errors
  ///
  /// returns error if not a cargo workspace or cargo metadata fails
  pub fn workspace_members( &self ) -> Result< Vec< PathBuf > >
  {
  let metadata = self.cargo_metadata()?;
  Ok( metadata.members.into_iter().map( | pkg | pkg.package_root ).collect() )
  }

  /// find cargo workspace root by traversing up directory tree
  fn find_cargo_workspace() -> Result< PathBuf >
  {
  let mut current = std ::env ::current_dir()
   .map_err( | e | WorkspaceError::IoError( e.to_string() ) )?;

  loop
  {
   let manifest = current.join( "Cargo.toml" );
   if manifest.exists()
   {
  let content = std ::fs ::read_to_string( &manifest )
   .map_err( | e | WorkspaceError::IoError( e.to_string() ) )?;
  
  let parsed: toml ::Value = toml ::from_str( &content )
   .map_err( | e | WorkspaceError::TomlError( e.to_string() ) )?;

  // check if this is a workspace root
  if parsed.get( "workspace" ).is_some()
  {
   return Ok( current );
  }

  // check if this is a workspace member pointing to a parent workspace
  if let Some( package ) = parsed.get( "package" )
  {
   if package.get( "workspace" ).is_some()
   {
  // continue searching upward for the actual workspace root
  }
  }
  }

   match current.parent()
   {
  Some( parent ) => current = parent.to_path_buf(),
  None => return Err( WorkspaceError::PathNotFound( current ) ),
  }
  }
  }
}

#[ cfg( any( feature = "serde", feature = "validation", feature = "secure" ) ) ]
impl Workspace
{
  /// internal helper to read file with error wrapping
  ///
  /// provides consistent error messages across all file reading operations
  fn read_file_to_string< P: AsRef< Path > >( path: P ) -> Result< String >
  {
    let path = path.as_ref();
    std ::fs ::read_to_string( path )
      .map_err( | e | WorkspaceError::IoError(
        format!( "failed to read {}: {}", path.display(), e )
      ) )
  }

  /// internal helper to detect file format from extension
  ///
  /// returns format string (toml/json/yaml/yml) based on file extension
  fn detect_format< P: AsRef< Path > >( path: P ) -> String
  {
    path.as_ref()
      .extension()
      .and_then( | ext | ext.to_str() )
      .unwrap_or( "toml" )
      .to_string()
  }
}

#[ cfg( feature = "serde" ) ]
impl Workspace
{

  /// internal helper to parse config content based on format
  fn parse_content< T >( content: &str, format: &str ) -> Result< T >
  where
    T: serde ::de ::DeserializeOwned,
  {
    match format
    {
      "toml" => toml ::from_str( content )
        .map_err( | e | WorkspaceError::SerdeError( format!( "toml error: {e}" ) ) ),
      "json" => serde_json ::from_str( content )
        .map_err( | e | WorkspaceError::SerdeError( format!( "json error: {e}" ) ) ),
      "yaml" | "yml" => serde_yaml ::from_str( content )
        .map_err( | e | WorkspaceError::SerdeError( format!( "yaml error: {e}" ) ) ),
      _ => Err( WorkspaceError::ConfigurationError(
        format!( "unsupported format: {format}" )
      ) ),
    }
  }

  /// internal helper to serialize config content based on format
  fn serialize_content< T >( config: &T, format: &str ) -> Result< String >
  where
    T: serde ::Serialize,
  {
    match format
    {
      "toml" => toml ::to_string_pretty( config )
        .map_err( | e | WorkspaceError::SerdeError( format!( "toml error: {e}" ) ) ),
      "json" => serde_json ::to_string_pretty( config )
        .map_err( | e | WorkspaceError::SerdeError( format!( "json error: {e}" ) ) ),
      "yaml" | "yml" => serde_yaml ::to_string( config )
        .map_err( | e | WorkspaceError::SerdeError( format!( "yaml error: {e}" ) ) ),
      _ => Err( WorkspaceError::ConfigurationError(
        format!( "unsupported format: {format}" )
      ) ),
    }
  }

  /// load configuration with automatic format detection
  ///
  /// # Errors
  ///
  /// returns error if configuration file is not found or cannot be deserialized
  ///
  /// # examples
  ///
  /// ```rust,no_run
  /// use workspace_tools ::workspace;
  /// use serde ::Deserialize;
  ///
  /// #[ derive( Deserialize ) ]
  /// struct AppConfig
  /// {
  ///     name: String,
  ///     port: u16,
  /// }
  ///
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// let ws = workspace()?;
  /// // looks for config/app.toml, config/app.yaml, config/app.json
  /// let config: AppConfig = ws.load_config( "app" )?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn load_config< T >( &self, name: &str ) -> Result< T >
  where
  T: serde ::de ::DeserializeOwned,
  {
  let config_path = self.find_config( name )?;
  self.load_config_from( config_path )
  }

  /// load configuration from specific file
  ///
  /// # Errors
  ///
  /// returns error if file cannot be read or deserialized
  pub fn load_config_from< T, P >( &self, path: P ) -> Result< T >
  where
  T: serde ::de ::DeserializeOwned,
  P: AsRef< Path >,
  {
  let path = path.as_ref();
  let content = Self::read_file_to_string( path )?;
  let format = Self::detect_format( path );
  Self::parse_content( &content, &format )
  }

  /// save configuration with format matching the original
  ///
  /// # Errors
  ///
  /// returns error if configuration cannot be serialized or written to file
  pub fn save_config< T >( &self, name: &str, config: &T ) -> Result< () >
  where
  T: serde ::Serialize,
  {
  let config_path = self.find_config( name )
   .or_else( |_| Ok( self.config_dir().join( format!( "{name}.toml" ) ) ) )?;
  
  self.save_config_to( config_path, config )
  }

  /// save configuration to specific file with format detection
  ///
  /// # Errors
  ///
  /// returns error if configuration cannot be serialized or written to file
  pub fn save_config_to< T, P >( &self, path: P, config: &T ) -> Result< () >
  where
  T: serde ::Serialize,
  P: AsRef< Path >,
  {
  let path = path.as_ref();
  let format = Self::detect_format( path );
  let content = Self::serialize_content( config, &format )?;

  // ensure parent directory exists
  if let Some( parent ) = path.parent()
  {
   std ::fs ::create_dir_all( parent )
  .map_err( | e | WorkspaceError::IoError( format!( "failed to create directory {}: {}", parent.display(), e ) ) )?;
  }

  // atomic write using temporary file
  let temp_path = path.with_extension( format!( "{format}.tmp" ) );
  std ::fs ::write( &temp_path, content )
   .map_err( | e | WorkspaceError::IoError( format!( "failed to write temporary file {}: {}", temp_path.display(), e ) ) )?;

  std ::fs ::rename( &temp_path, path )
   .map_err( | e | WorkspaceError::IoError( format!( "failed to rename {} to {}: {}", temp_path.display(), path.display(), e ) ) )?;

  Ok( () )
  }

  /// load and merge multiple configuration layers
  ///
  /// # Errors
  ///
  /// returns error if any configuration file cannot be loaded or merged
  pub fn load_config_layered< T >( &self, names: &[ &str ] ) -> Result< T >
  where
  T: serde ::de ::DeserializeOwned + ConfigMerge,
  {
  let mut result: Option< T > = None;

  for name in names
  {
   if let Ok( config ) = self.load_config :: < T >( name )
   {
  result = Some( match result
  {
   Some( existing ) => existing.merge( config ),
   None => config,
 } );
  }
  }

  result.ok_or_else( || WorkspaceError::ConfigurationError( "no configuration files found".to_string() ) )
  }

  /// update configuration partially
  ///
  /// # Errors
  ///
  /// returns error if configuration cannot be loaded, updated, or saved
  pub fn update_config< T, U >( &self, name: &str, updates: U ) -> Result< T >
  where
  T: serde ::de ::DeserializeOwned + serde ::Serialize,
  U: serde ::Serialize,
  {
  // load existing configuration
  let existing: T = self.load_config( name )?;
  
  // serialize both to json for merging
  let existing_json = serde_json ::to_value( &existing )
   .map_err( | e | WorkspaceError::SerdeError( format!( "failed to serialize existing config: {e}" ) ) )?;
  
  let updates_json = serde_json ::to_value( updates )
   .map_err( | e | WorkspaceError::SerdeError( format!( "failed to serialize updates: {e}" ) ) )?;

  // merge json objects
  let merged = Self ::merge_json_objects( existing_json, updates_json )?;
  
  // deserialize back to target type
  let merged_config: T = serde_json ::from_value( merged )
   .map_err( | e | WorkspaceError::SerdeError( format!( "failed to deserialize merged config: {e}" ) ) )?;
  
  // save updated configuration
  self.save_config( name, &merged_config )?;
  
  Ok( merged_config )
  }

  /// merge two json objects recursively
  fn merge_json_objects( mut base: serde_json ::Value, updates: serde_json ::Value ) -> Result< serde_json ::Value >
  {
  match ( &mut base, updates )
  {
   ( serde_json ::Value ::Object( ref mut base_map ), serde_json ::Value ::Object( updates_map ) ) =>
   {
  for ( key, value ) in updates_map
  {
   match base_map.get_mut( &key )
   {
  Some( existing ) if existing.is_object() && value.is_object() =>
  {
   *existing = Self ::merge_json_objects( existing.clone(), value )?;
  }
  _ =>
  {
   base_map.insert( key, value );
  }
  }
  }
  }
   ( _, updates_value ) =>
   {
  base = updates_value;
  }
  }
  
  Ok( base )
  }
}

#[ cfg( feature = "serde" ) ]
impl serde ::Serialize for WorkspacePath
{
  fn serialize< S >( &self, serializer: S ) -> core ::result ::Result< S ::Ok, S ::Error >
  where
  S: serde ::Serializer,
  {
  self.0.serialize( serializer )
  }
}

#[ cfg( feature = "serde" ) ]
impl< 'de > serde ::Deserialize< 'de > for WorkspacePath
{
  fn deserialize< D >( deserializer: D ) -> core ::result ::Result< Self, D ::Error >
  where
  D: serde ::Deserializer< 'de >,
  {
  let path = PathBuf ::deserialize( deserializer )?;
  Ok( WorkspacePath( path ) )
  }
}

#[ cfg( feature = "validation" ) ]
impl Workspace
{
  /// internal helper to parse content to JSON value for validation
  fn parse_to_json( content: &str, format: &str ) -> Result< serde_json ::Value >
  {
    match format
    {
      "toml" =>
      {
        let toml_value: toml ::Value = toml ::from_str( content )
          .map_err( | e | WorkspaceError::SerdeError( format!( "toml parse: {e}" ) ) )?;
        serde_json ::to_value( toml_value )
          .map_err( | e | WorkspaceError::SerdeError( format!( "toml→json: {e}" ) ) )
      }
      "json" => serde_json ::from_str( content )
        .map_err( | e | WorkspaceError::SerdeError( format!( "json parse: {e}" ) ) ),
      "yaml" | "yml" =>
      {
        let yaml_value: serde_yaml ::Value = serde_yaml ::from_str( content )
          .map_err( | e | WorkspaceError::SerdeError( format!( "yaml parse: {e}" ) ) )?;
        serde_json ::to_value( yaml_value )
          .map_err( | e | WorkspaceError::SerdeError( format!( "yaml→json: {e}" ) ) )
      }
      _ => Err( WorkspaceError::ConfigurationError(
        format!( "unsupported format: {format}" )
      ) ),
    }
  }

  /// internal helper to validate JSON against schema
  fn validate_against_schema(
    json_value: &serde_json ::Value,
    schema: &Validator
  ) -> Result< () >
  {
    if let Err( validation_errors ) = schema.validate( json_value )
    {
      let errors: Vec< String > = validation_errors
        .map( | error | format!( "{}: {}", error.instance_path, error ) )
        .collect();
      return Err( WorkspaceError::ValidationError(
        format!( "validation failed: {}", errors.join( "; " ) )
      ) );
    }
    Ok( () )
  }

  /// load and validate configuration against a json schema
  ///
  /// # Errors
  ///
  /// returns error if configuration cannot be loaded, schema is invalid, or validation fails
  ///
  /// # examples
  ///
  /// ```rust,no_run
  /// use workspace_tools ::workspace;
  /// use serde :: { Deserialize };
  /// use schemars ::JsonSchema;
  ///
  /// #[ derive( Deserialize, JsonSchema ) ]
  /// struct AppConfig
  /// {
  ///     name: String,
  ///     port: u16,
  /// }
  ///
  /// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
  /// let ws = workspace()?;
  /// let config: AppConfig = ws.load_config_with_validation( "app" )?;
  /// # Ok(())
  /// # }
  /// ```
  pub fn load_config_with_validation< T >( &self, name: &str ) -> Result< T >
  where
  T: serde ::de ::DeserializeOwned + JsonSchema,
  {
  // generate schema from type
  let schema = schemars ::schema_for!( T );
  let schema_json = serde_json ::to_value( &schema )
   .map_err( | e | WorkspaceError::ValidationError( format!( "failed to serialize schema: {e}" ) ) )?;
  
  // compile schema for validation
  let compiled_schema = Validator ::new( &schema_json )
   .map_err( | e | WorkspaceError::ValidationError( format!( "failed to compile schema: {e}" ) ) )?;
  
  self.load_config_with_schema( name, &compiled_schema )
  }
  
  /// load and validate configuration against a provided json schema
  ///
  /// # Errors
  ///
  /// returns error if configuration cannot be loaded or validation fails
  pub fn load_config_with_schema< T >( &self, name: &str, schema: &Validator ) -> Result< T >
  where
  T: serde ::de ::DeserializeOwned,
  {
  let config_path = self.find_config( name )?;
  self.load_config_from_with_schema( config_path, schema )
  }
  
  /// load and validate configuration from specific file with schema
  ///
  /// # Errors
  ///
  /// returns error if file cannot be read, parsed, or validated
  pub fn load_config_from_with_schema< T, P >( &self, path: P, schema: &Validator ) -> Result< T >
  where
  T: serde ::de ::DeserializeOwned,
  P: AsRef< Path >,
  {
  let path = path.as_ref();
  let content = Self::read_file_to_string( path )?;
  let format = Self::detect_format( path );

  // parse to json value first for validation
  let json_value = Self::parse_to_json( &content, &format )?;

  // validate against schema
  Self::validate_against_schema( &json_value, schema )?;

  // if validation passes, deserialize to target type
  serde_json ::from_value( json_value )
    .map_err( | e | WorkspaceError::SerdeError( format!( "deserialization error: {e}" ) ) )
  }
  
  /// validate configuration content against schema without loading
  ///
  /// # Errors
  ///
  /// returns error if content cannot be parsed or validation fails
  pub fn validate_config_content( content: &str, schema: &Validator, format: &str ) -> Result< () >
  {
  // parse content to json value
  let json_value = Self::parse_to_json( content, format )?;

  // validate against schema
  Self::validate_against_schema( &json_value, schema )
  }
}

/// testing utilities for workspace functionality
#[ cfg( feature = "testing" ) ]
pub mod testing
{
  use super ::Workspace;
  use tempfile ::TempDir;

  /// create a temporary workspace for testing
  ///
  /// returns a tuple of (`temp_dir`, workspace) where `temp_dir` must be kept alive
  /// for the duration of the test to prevent the directory from being deleted
  ///
  /// # Panics
  ///
  /// panics if temporary directory creation fails or workspace resolution fails
  ///
  /// # examples
  ///
  /// ```rust
  /// #[ cfg( test ) ]
  /// mod tests
  /// {
  ///     use workspace_tools ::testing ::create_test_workspace;
  ///
  ///     #[ test ]
  ///     fn test_my_feature()
  ///     {
  ///         let ( _temp_dir, workspace ) = create_test_workspace();
  ///
  ///         // test with isolated workspace
  ///         let config = workspace.config_dir().join( "test.toml" );
  ///         assert!( config.starts_with( workspace.root() ) );
  /// }
  /// }
  /// ```
  #[ must_use ]
  #[ inline ]
  pub fn create_test_workspace() -> ( TempDir, Workspace )
  {
  let temp_dir = TempDir ::new().unwrap_or_else( | e | panic!( "failed to create temp directory: {e}" ) );
  std ::env ::set_var( "WORKSPACE_PATH", temp_dir.path() );
  let workspace = Workspace ::resolve().unwrap_or_else( | e | panic!( "failed to resolve test workspace: {e}" ) );
  ( temp_dir, workspace )
  }

  /// create test workspace with standard directory structure
  ///
  /// creates a temporary workspace with config/, data/, logs/, docs/, tests/ directories
  ///
  /// # Panics
  ///
  /// panics if temporary directory creation fails or if any standard directory creation fails
  #[ must_use ]
  #[ inline ]
  pub fn create_test_workspace_with_structure() -> ( TempDir, Workspace )
  {
  let ( temp_dir, workspace ) = create_test_workspace();

  // create standard directories
  let base_dirs = vec!
  [
   workspace.config_dir(),
   workspace.data_dir(),
   workspace.logs_dir(),
   workspace.docs_dir(),
   workspace.tests_dir(),
   workspace.workspace_dir(),
 ];

  #[ cfg( feature = "secrets" ) ]
  let all_dirs = {
   let mut dirs = base_dirs;
   dirs.push( workspace.secret_dir() );
   dirs
 };

  #[ cfg( not( feature = "secrets" ) ) ]
  let all_dirs = base_dirs;

  for dir in all_dirs
  {
   std ::fs ::create_dir_all( &dir )
  .unwrap_or_else( | e | panic!( "failed to create directory {} : {}", dir.display(), e ) );
  }

  ( temp_dir, workspace )
  }
}

/// convenience function to get workspace instance with extended fallbacks
///
/// uses `Workspace ::resolve_with_extended_fallbacks()` which tries multiple
/// strategies including $PRO and $HOME for installed CLI applications.
/// always succeeds by falling back through multiple strategies.
///
/// # note
///
/// this function always succeeds (never returns Err), but maintains `Result`
/// return type for backward compatibility. you can safely `.unwrap()` the result.
///
/// # Errors
///
/// this function never returns an error. it always succeeds by falling back
/// through multiple resolution strategies. the `Result` return type is maintained
/// for backward compatibility only.
///
/// # examples
///
/// ```rust
/// # fn main() -> Result< (), workspace_tools ::WorkspaceError > {
/// use workspace_tools ::workspace;
///
/// // works without WORKSPACE_PATH set (uses fallbacks)
/// let ws = workspace()?;
/// let config_dir = ws.config_dir();
/// # Ok(())
/// # }
/// ```
///
/// # resolution priority
///
/// 1. cargo workspace (development context)
/// 2. `WORKSPACE_PATH` environment variable
/// 3. git repository root
/// 4. `$PRO` environment variable (installed apps)
/// 5. `$HOME` directory (universal fallback)
/// 6. current working directory
#[ inline ]
pub fn workspace() -> Result< Workspace >
{
  Ok( Workspace ::resolve_with_extended_fallbacks() )
}