treeboot-spec 0.16.0

Executable language-agnostic conformance specification for Treeboot.
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
# treeboot Specification v2.6.0

A portable worktree lifecycle helper that lets every coding agent, editor, and
orchestration tool run the same repo-local bootstrap and teardown commands.

**Tags:** compatibility contract, command-line executable, TOML config,
idempotent default, configured commands, teardown commands, agent-tool aliases

| Term            | Description                                                |
| --------------- | ---------------------------------------------------------- |
| Default command | `treeboot` == `treeboot run`                               |
| Root path       | Source checkout for copy, symlink, and sync operations     |
| Worktree path   | Current worktree root where operations execute             |
| Conflict policy | Skip existing by default, strict validates, force replaces |
| Primary file    | `.treeboot.toml`                                           |
| Teardown        | Explicit commands run before an external worktree removal  |

treeboot requires Git 2.36 or newer.

## Intent: One setup contract for many tools

Agentic coding tools already create isolated Git worktrees. The repeated pain is
everything Git intentionally leaves behind: ignored files, local credentials,
dependency caches, and per-worktree setup commands.

### Goals

- Provide one repo-local worktree bootstrap command.
- Avoid duplicate setup files across agent tools.
- Make common copy, symlink, and sync operations declarative.
- Allow custom setup through configured commands.
- Allow explicit cleanup before another tool removes a linked worktree.
- Be safe and idempotent by default.
- Ship as a small, portable executable.

### Non-goals

- Create Git worktrees.
- Remove Git worktrees or branches.
- Install or enforce hooks around `git worktree remove`.
- Manage long-running dev servers.
- Allocate per-worktree ports.
- Replace tool-specific setup systems entirely.
- Manage secrets beyond user-configured file operations.

### Design rule

treeboot should be boring to run repeatedly. File operations are idempotent by
default. Bootstrap and teardown commands always run when their phase is
executed, so users must make configured commands safe to rerun when that
matters.

### Conformance scope

A compatible implementation is any executable that provides the observable CLI
behavior defined by this specification. The executable's implementation
language, internal APIs, parser library, and release process are outside this
contract.

Contractual behavior appears as declarative behavior descriptions, required text
or data shapes, durable output, and explicit mandatory requirements, which
typically use `must`. `should` marks non-binding design or adoption guidance.
Examples and rationale do not add requirements. Placeholder and example values
are illustrative unless the surrounding text identifies an exact value. A
conformance result applies to the specification version, host platform, and
capabilities exercised by that run. A result on one host does not establish
support for other platforms.

## CLI surface: Subcommands and one default path

The common integration point is intentionally short: `treeboot`. Tool-specific
setup hooks only need to invoke the declarative treeboot config.

`TB-CLI-HELP`: The top-level command, every subcommand, and every nested
subcommand must accept `--help`, exit `0`, and write human-readable help to
stdout. Help must identify the invoked command and its supported arguments,
options, and immediate subcommands. Exact layout, capitalization, wrapping, and
parser-generated prose are not contractual.

`TB-CLI-USAGE`: Invalid command syntax must exit `2`, write a non-empty
diagnostic to stderr, and not execute treeboot behavior. This includes unknown
options or commands, missing required arguments, conflicting options, and
unsupported enumerated values. Exact parser wording, suggestions, quoting,
color, and usage layout are not contractual unless another section requires
specific text.

### `treeboot run`

Runs worktree bootstrap. This is also the implicit command when no subcommand is
provided.

```sh
treeboot
treeboot run
treeboot run --dry-run
treeboot run --verbose
treeboot run --strict
treeboot run --force
treeboot run --root /path/to/root-checkout
treeboot run --config .treeboot.toml
treeboot run --skip-commands
treeboot run --dry-run --json
treeboot run --skip-commands --json
```

Text is the default output. Structured JSON/YAML output is accepted only when
`--dry-run` prevents all effects or `--skip-commands` prevents configured
commands from writing to stdout. See
[Structured output formats](#structured-output-formats).

### `treeboot plan`

Plans the bootstrap work that `treeboot run` would perform from the current
filesystem state. Planning never writes files or spawns configured commands.

```sh
treeboot plan
treeboot plan --root /path/to/root-checkout
treeboot plan --config .treeboot.toml
treeboot plan --strict
treeboot plan --force
treeboot plan --skip-commands
treeboot plan --verbose
treeboot plan --json
treeboot plan --yaml
```

Plan uses the same discovery, runtime policy, validation, concrete file
decisions, root-checkout behavior, and missing-config behavior as run. It does
not accept `--dry-run` because it is always side-effect-free. By default it
reports configured bootstrap commands as planned work. `--skip-commands` omits
them without weakening config parsing or bootstrap validation. Text output uses
the same file-decision and `treeboot: would run <label>` lines as run dry-run,
and also prints each non-fatal validation warning as
`treeboot: warning: <message>`.

### `treeboot teardown`

Runs configured teardown commands for a linked worktree without removing the
worktree itself.

```sh
treeboot teardown
treeboot teardown --dry-run
treeboot teardown --yes
treeboot teardown --worktree ../feature-branch
treeboot teardown --worktree ../feature-branch --yes
treeboot teardown --root /path/to/root-checkout
treeboot teardown --config .treeboot.toml
```

The target defaults to the process working directory. `--worktree <path>` may
point anywhere inside another linked worktree and resolves to that worktree's
Git top level. Teardown rejects Git's main/root checkout before prompting.

`--yes` is long-only and grants non-interactive approval. Without `--yes`,
teardown prompts only when stdin is a terminal. `--dry-run` validates and
reports every teardown command without prompting, requiring `--yes`, or spawning
a process.

Teardown is command-only. It never applies configured file operations, runs
bootstrap `commands`, removes a worktree, or deletes a branch.

Teardown does not accept `--force` or `--strict`. `--force` remains the
file-replacement option, and teardown has no file conflict policy. Use
`--config` when teardown must require a specific config.

### `treeboot status`

Prints the detected worktree, root checkout, default branch, and config file
without parsing config or running configured commands. `treeboot info` is an
alias.

```sh
treeboot status
treeboot status --root /path/to/root-checkout
treeboot status --config .treeboot.toml
treeboot status --format json
treeboot status --format yaml
treeboot status --json
treeboot status --yaml
treeboot info
```

JSON and YAML output are defined in
[Structured output formats](#structured-output-formats).

### `treeboot version`

Prints version metadata and exits without discovering Git context or config.
`treeboot --version` and `treeboot -V` are global version flags. Nested command
parsers also accept both flags.

```sh
treeboot version
treeboot version --format json
treeboot version --format yaml
treeboot version --json
treeboot version --yaml
treeboot --version
treeboot -V
```

Human-readable output is a compact, flag-like summary:

```text
treeboot <PACKAGE_VERSION> (spec <SPEC_VERSION>)
```

`TB-CLI-VERSION`: Every version flag must report the implementation's package
version and implemented specification version and exit `0` without Git or config
discovery. A nested version flag may identify the invoked command in its leading
label; that label and the parser's exact formatting are not contractual.
`treeboot version` text output retains the exact compact summary shape shown
above, substituting the implementation's actual package version for
`<PACKAGE_VERSION>` and its implemented specification version for
`<SPEC_VERSION>`.

JSON and YAML output are defined in
[Structured output formats](#structured-output-formats).

### `treeboot config`

Parses the selected TOML config and prints the normalized file, bootstrap
command, and teardown command operations without executing them.

```sh
treeboot config
treeboot config --config .treeboot.toml
treeboot config --format json
treeboot config --format yaml
treeboot config --json
treeboot config --yaml
```

This command is view-only. It is intended for validating and inspecting config
parsing behavior; editing config values is out of scope.

Human-readable text output lists normalized source and target values plus
behavior-affecting normalized fields such as `required`, `compare`, `delete`,
`symlinks`, `include`, `ignore`, `allow_failure`, `cwd`, and command `env`
values when present. Before those collections it prints the effective worktree
ID and slug with their normalized `length`, `max_length`, and `separator`
settings. It labels bootstrap and teardown command collections separately and
prints `(none)` for an empty collection. JSON and YAML output emit the effective
values as the top-level `worktree_id` and `worktree_slug` strings and the full
normalized config structure, including its fully defaulted settings objects.

### `treeboot check`

Validates the complete selected config contract without applying file operations
or running bootstrap or teardown commands.

```sh
treeboot check
treeboot check --root /path/to/root-checkout
treeboot check --config .treeboot.toml
treeboot check --strict
treeboot check --format json
treeboot check --format yaml
treeboot check --json
treeboot check --yaml
```

`check` resolves the same worktree context and config selection rules as `run`,
parses and normalizes declarative config, resolves bootstrap runtime policy, and
independently validates the bootstrap and teardown plans.

When declarative config is selected, config parse and normalization errors are
fatal to the whole contract. After normalization, bootstrap and teardown
semantic validation are independent. `check` evaluates both, preserves both
failures when both phases are invalid, reports them in bootstrap-then-teardown
order, and exits non-zero when either phase fails.

On success, human-readable output prints:

```text
treeboot: check ok
```

Run validation can produce non-fatal warnings, such as an include list that
matches no source paths. `check` prints each warning as a
`treeboot: warning: ...` line before the final `treeboot: check ok` line and
still exits zero.

JSON and YAML output are defined in
[Structured output formats](#structured-output-formats). Fatal errors still use
treeboot's normal error reporting and non-zero exit behavior.

### `treeboot init`

Creates a starter config.

```sh
treeboot init
treeboot init --config
treeboot init --path .treeboot.toml
```

The default path is `.treeboot.toml`. Existing init targets, including symlinks,
are never replaced.

### `treeboot schema`

Prints the bundled JSON Schema for treeboot config to stdout and exits without
discovering Git context or config.

```sh
treeboot schema
treeboot schema --output config.schema.json
treeboot schema -o config.schema.json
treeboot schema > config.schema.json
```

The emitted schema is the canonical config schema at
`crates/treeboot-spec/assets/treeboot.schema.json`. Stdout and `--output` must
contain that document's exact UTF-8 bytes without added framing or byte changes.
When `--output` is provided, treeboot writes the schema to that path instead of
stdout. Parent directories must already exist. Existing regular files are
replaced.

`schema` does not support `--format`, `--json`, or `--yaml`; the schema payload
is already JSON.

### `treeboot copy`

Runs one or more copy operations without running declarative config file
operations or configured commands.

```sh
treeboot copy .env.local
treeboot copy .env.local mise.local.toml --target local
treeboot copy templates/editorconfig --target .editorconfig
treeboot copy shared/config --symlinks preserve
treeboot copy shared/config --verbose
```

### `treeboot symlink`

Runs one or more symlink operations from the root path into the current
worktree.

```sh
treeboot symlink .tool-versions
treeboot symlink bin scripts --target .local
treeboot symlink shared/bin --target bin
```

### `treeboot sync`

Runs one or more sync operations without running declarative config file
operations or configured commands.

```sh
treeboot sync shared/config
treeboot sync shared/config shared/editor --target .config
treeboot sync shared/config --delete
treeboot sync shared/config --compare checksum
treeboot sync shared/config --verbose
```

### `treeboot completions`

Prints shell completion scripts for supported shells so package managers and
users can install them.

```sh
treeboot completions bash
treeboot completions zsh
treeboot completions fish
treeboot completions powershell
treeboot completions elvish
```

`TB-COMPLETION-SCRIPTS`: Each supported shell invocation must emit a usable
registration script for the named shell without Git or config discovery. The
installed script must complete the commands, options, option values, and nested
commands documented by this specification. The emitted script bytes, helper
process protocol, and environment variables used to obtain candidates are not
contractual.

### `treeboot doctor`

Prints diagnostics for the current treeboot environment without applying file
operations or running configured commands.

```sh
treeboot doctor
treeboot doctor --root /path/to/root-checkout
treeboot doctor --config .treeboot.toml
treeboot doctor --strict
treeboot doctor --format json
treeboot doctor --format yaml
treeboot doctor --json
treeboot doctor --yaml
```

`doctor` checks Git availability, worktree discovery, root path discovery,
default branch discovery, child environment construction, config discovery, and
both bootstrap and teardown validation when config is selected. It reports
separate phase diagnostics from the same complete-config validation result used
by `check`. It is intended for human troubleshooting. Warnings do not fail the
command, but fatal discovery or config errors exit non-zero.

`--strict` makes doctor report missing config, root-checkout execution context,
and strict file-operation validation failures as fatal diagnostics while still
printing the diagnostics report when possible. `TREEBOOT_STRICT=true` applies
the same strict pre-config diagnostics and config validation. Config-level
`strict = true` applies to config validation only, because config-level options
are not loaded before root-checkout or missing-config checks.

JSON and YAML output are defined in
[Structured output formats](#structured-output-formats).

### `treeboot env`

Prints the environment variables treeboot passes to configured commands.

```sh
treeboot env
treeboot env --config .treeboot.toml
treeboot env --root /path/to/root-checkout
treeboot env --format json
treeboot env --format yaml
treeboot env --json
treeboot env --yaml
```

The text format is one `KEY=value` pair per line, sorted by variable name.
Values are resolved for the current worktree context and selected config. `env`
discovers and parses config to resolve the effective worktree ID and slug, but
does not apply file operations or run commands. Missing discovered config uses
default identity settings. A missing explicit config or any invalid selected
config is an error.

JSON and YAML output are defined in
[Structured output formats](#structured-output-formats).

`env` prints only the treeboot-owned child environment variables described in
[Environment variables](#compatibility-environment-variables). It does not print
the full process environment, per-command `env` overlays, or the config option
override variables that treeboot reads from its parent environment.

### `treeboot worktree`

Derives a stable Treeboot ID and readable slug for one target, or inventories
the registered worktrees in the current Git repository.

```sh
treeboot worktree id
treeboot worktree id ../prospective-worktree
treeboot worktree slug
treeboot worktree slug ../prospective-worktree
treeboot worktree path k7m2qx
treeboot worktree list
treeboot worktree id --json
treeboot worktree slug --yaml
treeboot worktree path k7m2qx --yaml
treeboot worktree list --format json
```

Without `PATH`, `worktree id` and `worktree slug` discover and fully parse the
current worktree's config using the same rules as `treeboot env`. Text output is
the requested effective value followed by a newline.

With `PATH`, both commands derive identity for the exact target rather than
replacing it with an enclosing Git worktree root. A relative input resolves
against the process current directory. The result is normalized to an absolute
path by canonicalizing the longest existing ancestor and lexically normalizing
any missing suffix. An explicitly supplied empty argument is a usage error.
Windows drive-relative paths such as `C:target` and root-relative paths without
a drive or share such as `\target` are unsupported path errors; they are not
joined to the current directory. Existing non-directory targets are errors,
including regular files, symlinks to files, and dangling symlinks. Ordinary
directories, symlinks to directories, and nonexistent targets work outside Git.

An existing target directory uses config discovered directly within that
directory and fully parses the selected file. A nonexistent target uses default
identity settings. Invalid discovered config is fatal before output even when
the invalid declaration is unrelated to identity. Explicit mode ignores ambient
root and default-branch compatibility overrides. Git discovery is optional and
starts from the exact target when it exists or its nearest existing directory
ancestor otherwise. It may supply only the main-worktree basename used by the
slug's readable fallback and never replaces the exact hash target.

Equivalent relative, absolute, symlink, `.`, and `..` spellings normalize to one
identity. A nonexistent target retains that identity after creation as an
ordinary directory while the normalized target remains the same. For an actual
Git worktree, explicit and implicit invocations produce the same values.

`worktree path <ID>` enumerates all of the current repository's registered,
non-bare worktrees whose paths still exist. Every candidate path is
canonicalized, then that candidate's discovered config is fully parsed. The
complete effective ID is compared exactly and case-sensitively. The main
worktree participates. Text output is the matching canonical absolute path
followed by a newline.

No match exits non-zero. Multiple matches are a distinct error that reports
every matching canonical path. Lookup always scans every candidate before
succeeding so a later collision cannot be missed.

`worktree list` uses the same candidate discovery and identity generation. Text
output is an `ID`, `SLUG`, and `PATH` table. The main worktree is first and
remaining entries are sorted by canonical path. Duplicate IDs and slugs remain
visible and do not make listing fail. Only ID collisions affect lookup. On Unix,
`worktree path` and `worktree list` text output preserve native path bytes
exactly.

Missing registered paths are stale and skipped without changing Git metadata.
Bare records are excluded from inventory and reverse lookup, but a bare primary
repository remains the Git main-worktree identity used to resolve linked
worktree context. An existing candidate that cannot be canonicalized,
discovered, or fully parsed makes the complete operation fail. A candidate that
disappears during inspection is skipped only when the failure is a not-found I/O
error; other failures are fatal and attributed to the candidate path. Reports
are collected before rendering, so a candidate failure does not leave partial
standard output.

Ambient recognized Treeboot environment inputs remain honored by implicit
single-target and repository-wide inspection. Explicit `id PATH` and `slug PATH`
ignore them. These commands do not accept `--root` or `--config`.

### Manual file operation commands

`copy`, `symlink`, and `sync` expose the same file operation engine used by
declarative config. Each command requires at least one source argument. Multiple
source arguments create multiple independent file operations. These commands
still discover the root path and worktree path, but they do not run configured
commands.

After worktree/root context checks, manual file operation commands discover and
parse config when one is present only to load top-level runtime policy. They
ignore the config's file operations, bootstrap commands, and teardown commands.
If config parsing is reached and the config is invalid, the manual command fails
before applying file operations.

With one source, `--target` is the exact target path. With multiple sources,
`--target` is a directory or path prefix joined with each source value. For
example, `treeboot copy .env.local mise.local.toml --target local` copies
`.env.local` to `local/.env.local` and `mise.local.toml` to
`local/mise.local.toml`.

Manual commands apply the same output contract as declarative file operations.
Multiple source arguments create multiple top-level file operations for output
and progress as well as execution. A command such as
`treeboot copy a b --target local` reports separate decisions for `a -> local/a`
and `b -> local/b`; it does not collapse them into one command-wide summary.

Operation-specific flags are valid only on the commands listed in the option
table. For example, using `--compare` on `copy` or `--symlinks` on `symlink` is
a CLI usage error and exits with code `2`.

| Option                                                     | Scope                                                              | Behavior                                                                                                                                                                                                                                                                    |
| ---------------------------------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-r`, `--root <path>`                                      | run/plan/teardown/status/config/check/copy/symlink/sync/doctor/env | Overrides the root checkout used for discovery and file-operation context.                                                                                                                                                                                                  |
| `-c`, `--config <path>`                                    | run/plan/teardown/status/config/check/doctor/env                   | Uses one specific config file and skips config discovery. For teardown and env, relative paths resolve from the selected worktree.                                                                                                                                          |
| `--worktree <path>`                                        | teardown                                                           | Selects the linked worktree to tear down. Defaults to the process working directory; a path inside a worktree resolves to its Git top level.                                                                                                                                |
| `-o`, `--format <text\|json\|yaml>`                        | run/plan/status/version/config/check/doctor/env/worktree leaves    | Selects human-readable, JSON, or YAML output. Defaults to `text`. Structured run requires `--dry-run` or `--skip-commands`.                                                                                                                                                 |
| `-J`, `--json`                                             | run/plan/status/version/config/check/doctor/env/worktree leaves    | Shortcut for `--format json`. Conflicts with `--format` and `--yaml`.                                                                                                                                                                                                       |
| `-Y`, `--yaml`                                             | run/plan/status/version/config/check/doctor/env/worktree leaves    | Shortcut for `--format yaml`. Conflicts with `--format` and `--json`.                                                                                                                                                                                                       |
| `-V`, `--version`                                          | global and nested command parsers                                  | Prints package and spec version details and exits before command validation.                                                                                                                                                                                                |
| `-o`, `--output <path>`                                    | schema                                                             | Writes the bundled config schema to a file instead of stdout.                                                                                                                                                                                                               |
| `-S`, `--strict`                                           | run/plan/check/copy/symlink/sync/doctor                            | Fails if a copy/symlink target exists; rejects sync operations; exits non-zero when run from the root checkout. Declarative config can also enable strict mode with top-level `strict = true`. For doctor, strict failures are reported as fatal diagnostics when possible. |
| `-f`, `--force`                                            | run/plan/copy/symlink/sync                                         | Replaces existing file-operation targets where supported.                                                                                                                                                                                                                   |
| `-n`, `--dry-run`                                          | run/teardown/copy/symlink/sync                                     | Prints planned work without writing files or running commands. Teardown does not prompt or require `--yes`.                                                                                                                                                                 |
| `-v`, `--verbose`                                          | run/plan/copy/symlink/sync                                         | Prints detailed file-operation actions instead of compact summaries. Interactive progress is disabled in verbose mode. JSON/YAML run and plan reject it.                                                                                                                    |
| `--skip-commands`                                          | run/plan                                                           | Omits configured bootstrap commands. Run applies or previews files only; plan omits commands from the report.                                                                                                                                                               |
| `--yes`                                                    | teardown                                                           | Long-only explicit approval that suppresses the terminal confirmation prompt. It does not bypass discovery, parsing, or validation.                                                                                                                                         |
| `-t`, `--target <path>`                                    | copy/symlink/sync                                                  | Overrides the target. With multiple sources, acts as the target path prefix for each source.                                                                                                                                                                                |
| `--required`                                               | copy/symlink/sync                                                  | Fails when any requested source does not exist.                                                                                                                                                                                                                             |
| `--symlinks <preserve>`                                    | copy/sync                                                          | Selects how source symlinks are handled. The initial supported value is `preserve`.                                                                                                                                                                                         |
| `--include <pattern>`                                      | copy/sync                                                          | Repeats to narrow directory operations to source paths matching operation-local include patterns. Patterns use gitignore-style syntax without `!` negation and are not read from `.gitignore` files. Conflicts with `--delete` / `-D`.                                      |
| `--ignore <pattern>`                                       | copy/sync                                                          | Repeats to skip source paths matching operation-local ignore patterns. Patterns use gitignore-style syntax and are not read from `.gitignore` files.                                                                                                                        |
| `--ignore-metadata <permissions\|owner\|group\|ownership>` | copy/sync                                                          | Repeats to opt out of metadata comparison and preservation. `ownership` means owner and group.                                                                                                                                                                              |
| `--compare <metadata\|checksum>`                           | sync                                                               | Selects sync comparison behavior.                                                                                                                                                                                                                                           |
| `-D`, `--delete` / `--no-delete`                           | sync                                                               | Controls whether sync deletes target-only files. Defaults to `--no-delete`.                                                                                                                                                                                                 |
| `--config`                                                 | init                                                               | Creates a starter TOML config. This intentionally has no short alias so `-c` can consistently mean config path for run/teardown/config.                                                                                                                                     |
| `-p`, `--path <path>`                                      | init                                                               | Writes the generated init output to a custom path.                                                                                                                                                                                                                          |

## Structured output formats

Commands that accept `--format json`, `--json`, `--format yaml`, or `--yaml`
must emit the structures in this section. JSON output is pretty-printed and YAML
output uses the same field names, values, and nesting as JSON. Path values are
strings. Optional values are `null` when absent. Tagged enum values are
lowercase `snake_case` strings. JSON object member order is not part of the
contract.

Structured path values require valid UTF-8. If any path cannot be represented by
the JSON/YAML string schema, serialization fails before stdout is written. Use
text output when native non-UTF-8 Unix path bytes must be preserved.

The shared worktree context object has this shape:

```json
{
  "root_path": "/repo",
  "worktree_path": "/repo-worktree",
  "default_branch": "main"
}
```

### `treeboot status` JSON

`treeboot status`, and its `treeboot info` alias, emit a discovery report:

```json
{
  "context": {
    "root_path": "/repo",
    "worktree_path": "/repo-worktree",
    "default_branch": "main"
  },
  "config": "/repo-worktree/.treeboot.toml"
}
```

`config` is a path string or `null`.

### `treeboot version` JSON

`treeboot version` emits package and implemented-spec metadata:

```json
{
  "package": "treeboot",
  "version": "<PACKAGE_VERSION>",
  "spec_version": "<SPEC_VERSION>"
}
```

`package` is the CLI package name. `version` is the package version.
`spec_version` is the TreeBoot spec version implemented by the build. The
angle-bracketed values above are placeholders, not literals.

### `treeboot config` JSON

`treeboot config` emits the selected config path and normalized config:

```json
{
  "path": "/repo-worktree/.treeboot.toml",
  "worktree_id": "a1b2c3",
  "worktree_slug": "repo-worktree-a1b2c3",
  "config": {
    "strict": false,
    "default_ignore": [],
    "dangerously_allow_sources_outside_root": false,
    "dangerously_allow_targets_outside_worktree": false,
    "worktree_id": {
      "length": 6
    },
    "worktree_slug": {
      "max_length": 48,
      "separator": "-"
    },
    "files": [
      {
        "operation": "copy",
        "source": ".env",
        "target": ".env",
        "source_path": "/repo/.env",
        "target_path": "/repo-worktree/.env",
        "required": false,
        "compare": null,
        "delete": null,
        "symlinks": "preserve",
        "include": [],
        "ignore": [],
        "ignore_metadata": [],
        "declaration": {
          "start": 0,
          "end": 15,
          "line": 1,
          "column": 1
        }
      }
    ],
    "commands": [
      {
        "name": "Install packages",
        "command": {
          "kind": "shell",
          "run": "mise install"
        },
        "cwd": null,
        "cwd_path": null,
        "env": {},
        "allow_failure": false,
        "declaration": {
          "start": 17,
          "end": 50,
          "line": 3,
          "column": 1
        }
      }
    ],
    "teardown_commands": [
      {
        "name": "Drop database",
        "command": {
          "kind": "shell",
          "run": "mise run db:drop"
        },
        "cwd": null,
        "cwd_path": null,
        "env": {},
        "allow_failure": false,
        "declaration": {
          "start": 52,
          "end": 98,
          "line": 5,
          "column": 1
        }
      }
    ]
  }
}
```

The top-level `worktree_id` and `worktree_slug` strings are the effective
identity values for the selected worktree. `config.worktree_id` and
`config.worktree_slug` contain their normalized settings.

`files`, `commands`, and `teardown_commands` are ordered arrays. Omitted
collections normalize to empty arrays. File `operation` is `copy`, `symlink`, or
`sync`. `compare` is `metadata`, `checksum`, or `null`. `delete` is a boolean or
`null`. `symlinks` is `preserve` or `null`. `include` is an ordered array of
operation-local path include patterns. `ignore` is an ordered array of
operation-local path ignore patterns. `ignore_metadata` is an ordered array of
canonical ignored metadata fields: `permissions`, `owner`, and `group`. Config
input can use `ownership` as a shorthand, but normalized inspection output
expands it to `owner` and `group`.

Command `name`, `cwd`, and `cwd_path` are strings or `null`. `env` is an object
whose keys and values are strings. `command` is one of:

```json
{
  "kind": "shell",
  "run": "mise install"
}
```

```json
{
  "kind": "direct",
  "program": "npm",
  "args": [
    "install"
  ]
}
```

Each `declaration` object describes the byte and one-based line/column location
of the source TOML declaration:

```json
{
  "start": 0,
  "end": 15,
  "line": 1,
  "column": 1
}
```

### `treeboot check` JSON

`treeboot check` emits the resolved context, the selected bootstrap action, and
non-fatal run-validation warnings:

```json
{
  "context": {
    "root_path": "/repo",
    "worktree_path": "/repo-worktree",
    "default_branch": "main"
  },
  "action": {
    "kind": "config",
    "path": "/repo-worktree/.treeboot.toml"
  },
  "warnings": []
}
```

`warnings` is an ordered array of human-readable warning strings produced by run
validation, such as an include list that matches no source paths. It is empty
when validation produces no warnings.

`action` is one of:

```json
{ "kind": "missing_config" }
```

```json
{ "kind": "root_worktree_skipped" }
```

```json
{
  "kind": "config",
  "path": "/repo-worktree/.treeboot.toml"
}
```

### `treeboot plan` and structured `treeboot run`

Plan and the safe structured run modes emit one complete bootstrap report:

```json
{
  "mode": "plan",
  "context": {
    "root_path": "/repo",
    "worktree_path": "/repo-worktree",
    "default_branch": "main"
  },
  "action": {
    "kind": "config",
    "path": "/repo-worktree/.treeboot.toml"
  },
  "has_file_changes": true,
  "file_summary": {
    "changed": 4,
    "skipped": 2,
    "deleted": 1,
    "metadata_changed": 1,
    "file_warnings": 1
  },
  "files": [
    {
      "operation": "sync",
      "source": "shared",
      "target": "shared",
      "summary": {
        "changed": 4,
        "skipped": 2,
        "deleted": 1,
        "metadata_changed": 1,
        "file_warnings": 1,
        "expanded": true,
        "skip_reason": null
      }
    }
  ],
  "commands_skipped": false,
  "commands": [
    {
      "label": "Install packages: mise run setup",
      "allow_failure": false
    }
  ],
  "validation_warnings": [],
  "file_warnings": [
    {
      "path": "shared/current",
      "reason": "symlink target does not exist"
    }
  ],
  "execution_warnings": []
}
```

`mode` is `plan` for `treeboot plan`, `dry_run` for structured run with
`--dry-run`, and `execute` for structured run with `--skip-commands` but no
`--dry-run`.

The `action` variants match check: `missing_config`, `root_worktree_skipped`, or
`config` with its path. Missing discovered config and non-strict root-worktree
invocations are successful empty reports. An explicitly requested missing config
remains an error, as do strict missing-config and root-worktree cases.

`files` preserves config declaration order and contains one entry for every
normalized top-level file operation, including operations with zero decisions.
Each operation `summary` uses the current concrete filesystem decisions.
`changed` counts creates, updates, replacements, and metadata repairs. `deleted`
counts sync deletions. A metadata repair increments both `changed` and
`metadata_changed`. `file_warnings` counts concrete planning warnings. Aggregate
counts equal the sums of the operation counts. An expanded operation always has
`skip_reason: null`; one unexpanded skip includes its reason.

`has_file_changes` is true exactly when `file_summary.changed > 0` or
`file_summary.deleted > 0`. Skips and warnings do not make it true.

`commands` preserves config declaration order and uses the labels from text
dry-run output. `commands_skipped` is true, and `commands` is empty, when
`--skip-commands` is selected. Structured execute mode therefore always omits
commands. A consumer interested in all planned bootstrap work checks
`has_file_changes || !commands.is_empty()`.

`validation_warnings` contains ordered human-readable `ActionPlan` warnings.
`file_warnings` contains ordered path/reason pairs from concrete planning, and
its length equals the aggregate warning count. `execution_warnings` contains
ordered path/reason pairs produced while files are applied, currently ownership
preservation warnings. It is empty in plan and dry-run modes. Execution warnings
do not change the precomputed file counts.

JSON/YAML run output is valid only with `--dry-run` or `--skip-commands`.
`treeboot run --json`, `treeboot run --yaml`, and equivalent non-text format
uses without either option are usage errors. Structured run and plan also reject
`--verbose`. These checks happen before Git or config discovery. Any implicit
run option placed before an explicit subcommand is a usage error. Implicit run
options are accepted before command selection only when no subcommand follows.

Structured output never contains configured command stdout. Dry-run never spawns
commands, while `--skip-commands` omits them. Implementations must buffer the
complete document before writing stdout. A structured executing run must
preflight every prepared action path before mutation. A later execution failure
may retain the same partial file effects as text execution, but stdout remains
empty. Successful reports exit `0` whether or not changes exist.

### `treeboot doctor` JSON

`treeboot doctor` emits an ordered diagnostics report:

```json
{
  "fatal": false,
  "context": {
    "root_path": "/repo",
    "worktree_path": "/repo-worktree",
    "default_branch": "main"
  },
  "diagnostics": [
    {
      "name": "worktree",
      "status": "ok",
      "message": "worktree context resolved"
    },
    {
      "name": "config",
      "status": "ok",
      "message": "config is valid: /repo-worktree/.treeboot.toml"
    },
    {
      "name": "teardown_validation",
      "status": "ok",
      "message": "teardown config is valid"
    }
  ]
}
```

`fatal` is `true` when any diagnostic is fatal. `context` is the shared context
object or `null` when context discovery fails. Each diagnostic has a stable
`name`, a `status` of `ok`, `warning`, or `error`, and a human-readable
`message`.

The diagnostic names defined by this spec are `environment_options`, `worktree`,
`root`, `root_worktree`, `default_branch`, `environment`, `config`,
`config_validation`, and `teardown_validation`. Bootstrap validation preserves
the spec-2.0 behavior: success uses `config` with `config is valid: <path>`,
while failure uses `config_validation`. Teardown validation is reported
separately as `teardown_validation`.

The `default_branch` diagnostic is `ok` when a non-empty default branch was
resolved and `warning` when default branch discovery falls back to the
best-effort empty string. An unknown default branch is not fatal; treeboot still
sets `TREEBOOT_DEFAULT_BRANCH` and `CONDUCTOR_DEFAULT_BRANCH` to an empty
string.

### `treeboot env` JSON

`treeboot env` emits an object containing only treeboot-owned child environment
variables:

```json
{
  "CODEX_SOURCE_TREE_PATH": "/repo",
  "CODEX_WORKTREE_PATH": "/repo-worktree",
  "CONDUCTOR_DEFAULT_BRANCH": "main",
  "CONDUCTOR_ROOT_PATH": "/repo",
  "CONDUCTOR_WORKSPACE_PATH": "/repo-worktree",
  "GIT_SOURCE_TREE_PATH": "/repo",
  "GIT_WORKTREE_PATH": "/repo-worktree",
  "SUPERSET_ROOT_PATH": "/repo",
  "TREEBOOT_DEFAULT_BRANCH": "main",
  "TREEBOOT_ROOT_PATH": "/repo",
  "TREEBOOT_WORKTREE_ID": "nw67nj",
  "TREEBOOT_WORKTREE_PATH": "/repo-worktree",
  "TREEBOOT_WORKTREE_SLUG": "repo-worktree-nw67nj"
}
```

Keys are variable names and values are strings. The object excludes the parent
process environment, per-command config overlays, and config option override
variables that treeboot reads from the parent environment.

### `treeboot worktree` JSON

`treeboot worktree id` emits:

```json
{
  "id": "nw67nj"
}
```

`treeboot worktree slug` emits:

```json
{
  "slug": "repo-worktree-nw67nj"
}
```

`treeboot worktree path <ID>` emits:

```json
{
  "id": "nw67nj",
  "path": "/repo-worktree"
}
```

`treeboot worktree list` emits:

```json
{
  "worktrees": [
    {
      "id": "a1b2c3",
      "slug": "repo-a1b2c3",
      "path": "/repo"
    },
    {
      "id": "nw67nj",
      "slug": "repo-worktree-nw67nj",
      "path": "/repo-worktree"
    }
  ]
}
```

The YAML forms have the same fields and nesting.

### `treeboot schema` JSON

`treeboot schema` emits the bundled config JSON Schema document directly. It is
not wrapped in a treeboot report object and it does not support the structured
output flags. The schema payload is defined by
`crates/treeboot-spec/assets/treeboot.schema.json`.

### Commands without structured output

`treeboot teardown`, `treeboot init`, `treeboot copy`, `treeboot symlink`,
`treeboot sync`, and `treeboot completions` do not support `--format`, `--json`,
or `--yaml`. Their output is text-only and follows the command sections plus
[Operator experience](#operator-experience-output-and-exit-codes).

## Path model: Root path feeds the worktree path

User-facing docs use "root path" instead of "main worktree" to avoid confusion
with main branches. The spec still explains that Git's main worktree is the
default source when no override exists.

### Root path

Source checkout treeboot reads from. Defaults to Git's main worktree, but can be
overridden.

### Worktree path

Current worktree root. File targets and command execution are anchored here.

The current worktree path resolved from `git rev-parse --show-toplevel`
preserves platform-native filesystem path data. On Unix, this includes non-UTF-8
bytes and boundary whitespace. Only Git's single trailing LF delimiter is
removed.

### Root Path Discovery

The root path is the checkout used as the source for copy, symlink, and sync
operations.

1. Use `--root`, if provided.
2. Use `TREEBOOT_ROOT_PATH`, if set.
3. Use `CODEX_SOURCE_TREE_PATH`, if set.
4. Use `CONDUCTOR_ROOT_PATH`, if set.
5. Use `SUPERSET_ROOT_PATH`, if set.
6. Use Git's main worktree from `git worktree list --porcelain -z`.

Git-discovered worktree and root paths preserve platform-native filesystem path
data. On Unix, this includes non-UTF-8 bytes and boundary whitespace. Git's
NUL-delimited worktree output is parsed as bytes so path quoting and embedded
newlines cannot change the discovered root path.

Treeboot always retains Git's discovered main-worktree path as a separate
identity used for root-target checks. `--root` and environment aliases override
the file-operation source root only; they cannot make the actual main worktree
look like a linked worktree.

If no root path can be determined, `treeboot run` fails with a clear error.

### Root Checkout No-op

If Git's actual main-worktree identity and the current worktree path are the
same, `treeboot run` is running from the root checkout rather than a separate
worktree. This classification is unchanged by source-root overrides.

In the default mode, treeboot prints `This is not a work tree` and exits
successfully before discovering config. In strict mode enabled by `--strict` or
`TREEBOOT_STRICT`, treeboot prints the same info message and exits non-zero.
Config-level `strict` is not loaded before this check.

The same root-checkout behavior applies to manual `copy`, `symlink`, and `sync`
commands. In default mode they exit successfully without applying file
operations. In strict mode they exit non-zero before applying file operations.
`treeboot doctor` reports root-checkout strictness as a fatal `root_worktree`
diagnostic instead of exiting before printing the diagnostics report.

`treeboot teardown` has no root-checkout no-op. It rejects the main/root
checkout with exit code `1` before loading config or reading confirmation input.
Teardown is only valid for a linked worktree. Bootstrap strictness does not
change this rule.

### Default Branch Discovery

`TREEBOOT_DEFAULT_BRANCH` is best effort. treeboot uses an existing
`CONDUCTOR_DEFAULT_BRANCH` value if present, otherwise resolves `origin/HEAD`,
otherwise sets an empty string. When resolved from Git, the value is the short
branch name, such as `main`, not `origin/main` or a full ref path.

## Compatibility: Environment variables

Configured commands adapted from Codex, Conductor, or Superset setup scripts
should usually work with minimal changes. treeboot sets canonical variables plus
aliases for common setup-script ecosystems.

### Scope

treeboot builds one environment variable set for the resolved worktree and
applies it when executing bootstrap or teardown commands from declarative
config.

### Config option environment overrides

Bootstrap and manual file-operation flows read environment variables for
config-level boolean options. Values `1`, `true`, `yes`, and `on` enable an
option; `0`, `false`, `no`, and `off` disable it. Invalid values are errors
before bootstrap file operations or commands run.

```text
TREEBOOT_STRICT
TREEBOOT_DANGEROUSLY_ALLOW_SOURCES_OUTSIDE_ROOT
TREEBOOT_DANGEROUSLY_ALLOW_TARGETS_OUTSIDE_WORKTREE
```

These variables affect bootstrap file planning and manual file operations.
Command-only teardown does not parse or resolve bootstrap runtime policy, so
even invalid values do not fail teardown. They do not make a missing discovered
teardown config fatal, permit teardown of the root checkout, or change teardown
command planning.

### Canonical

```text
TREEBOOT_ROOT_PATH
TREEBOOT_WORKTREE_PATH
TREEBOOT_WORKTREE_ID
TREEBOOT_WORKTREE_SLUG
TREEBOOT_DEFAULT_BRANCH
```

### Worktree ID and slug

`TREEBOOT_WORKTREE_ID` is a stable compact ID shared by bootstrap and teardown
commands. It contains only a configured prefix of the path digest.
`TREEBOOT_WORKTREE_SLUG` is the readable companion containing a sanitized name,
one configured separator, and the complete ID:

```text
TREEBOOT_WORKTREE_ID=k7m2qx
TREEBOOT_WORKTREE_SLUG=feature-login-k7m2qx
```

Two optional top-level inline objects control the values:

```toml
worktree_id = { length = 6 }
worktree_slug = { max_length = 48, separator = "-" }
```

All fields independently default. `worktree_id.length` must be in `1..=52`.
`worktree_slug.separator` must be exactly `-` or `_`. `worktree_slug.max_length`
must be at least `worktree_id.length + 2` so the slug can hold one readable
character, one separator, and the complete ID. Validation happens after omitted
fields default, so `worktree_id = { length = 50 }` is invalid against the
default slug maximum of 48. Normalized config output always includes both
settings objects and all of their fields. The unreleased composite `worktree_id`
fields `max_length`, `hash_length`, and `separator` are unknown fields; there
are no compatibility aliases for that shape. There is no environment or CLI
override for these settings.

The identity digest is SHA-256 over a platform-native, domain-separated byte
sequence:

```text
<ASCII "treeboot-worktree-id-v1"><NUL><ASCII platform><NUL><canonical path bytes>
```

On Unix, `platform` is `unix` and the final bytes are the canonical worktree
path's raw `OsStr` bytes. On Windows, `platform` is `windows` and the final
bytes are the canonical worktree path's UTF-16 code units serialized
little-endian. The canonical `Worktree.worktree_path` is the only identity
input: root-source overrides, current directory, branch, config path, and
manager state do not affect it. No additional case folding occurs.

Treat the 256-bit digest as a big-endian bitstream and encode it without padding
using the lowercase Crockford alphabet:

```text
0123456789abcdefghjkmnpqrstvwxyz
```

Consume five bits per character from most to least significant. Left-align the
final remaining high bit and fill its low four bits with zero, producing 52
characters for the complete digest. Retain the first `worktree_id.length`
characters as the complete ID. Readable naming and slug settings never affect
the ID.

Choose the readable source using the first matching complete trailing component
pattern:

| Manager       | Trailing path pattern                                          | Readable source              |
| ------------- | -------------------------------------------------------------- | ---------------------------- |
| Codex/ChatGPT | `.../.codex/worktrees/<opaque>/<project>`                      | `<project>`                  |
| Claude Code   | `.../<project>/.claude/worktrees/<name>`                       | `<name>`                     |
| T3 Code       | `.../.t3/worktrees/<project>/t3code-<opaque>`                  | `<project>`                  |
| Conductor     | `.../conductor/workspaces/<project>/<city>`                    | `<project>` plus `<city>`    |
| Superset      | `.../.superset/worktrees/<project>/<workspace>/<workspace...>` | Components after `<project>` |
| Generic       | no recognized pattern                                          | Worktree basename            |

Here `...` consumes any leading components and Superset requires one or more
components after the project. Matches are component-wise and use the literal
marker spelling; Treeboot does not read `HOME`, `CODEX_HOME`, or other vendor
environment variables.

A selected single component is considered mechanical when it is a canonical
hexadecimal UUID in `8-4-4-4-12` form, a hexadecimal token of at least eight
characters, or `t3code-` followed by a non-empty ASCII alphanumeric, `_`, or `-`
token. When Git supplies a main-worktree fallback, mechanical names use that
fallback. Without one, including non-Git explicit targets, the target basename
is retained as the deterministic readable source.

Sanitize the selected native components lossily for the slug while retaining
exact native bytes for hashing: lowercase ASCII letters, retain ASCII letters
and digits, replace each maximal run of all other characters (including
component boundaries) with one configured separator, and trim boundary
separators. If nothing remains, sanitize the main-worktree basename when
available, then the target basename, then use `worktree` as the defensive
fallback.

The readable budget is `worktree_slug.max_length - 1 - worktree_id.length`.
Truncate from the right to that budget and trim a separator exposed at the new
end, then append exactly one configured separator and the complete ID. The
default slug is at most 48 ASCII characters and is a DNS-compatible label. `_`
intentionally favors unquoted SQL/programming identifiers over DNS-label
compatibility.

Both identity variables are Treeboot-owned. A bootstrap or teardown command that
declares either one in its `env` table fails planning before file operations or
commands run. Changing the hash input, encoding, recognizer precedence,
sanitization, or truncation behavior is a compatibility change.

Existing configs that omit either settings object use defaults. Older Treeboot
versions reject the new `worktree_slug` key under the normal unknown-field
forward-version rule. Structured `env` and `config` consumers receive additive
slug keys. Scripts that previously ran `treeboot env` successfully beside an
invalid discovered config now fail until that config is fixed or an explicit
valid config is selected, because environment inspection must match configured
command behavior.

### Aliases

```text
GIT_SOURCE_TREE_PATH
GIT_WORKTREE_PATH

CODEX_SOURCE_TREE_PATH
CODEX_WORKTREE_PATH

CONDUCTOR_ROOT_PATH
CONDUCTOR_WORKSPACE_PATH
CONDUCTOR_DEFAULT_BRANCH

SUPERSET_ROOT_PATH
```

| Variable                   | Value                     | Reason                                  |
| -------------------------- | ------------------------- | --------------------------------------- |
| `CODEX_SOURCE_TREE_PATH`   | `TREEBOOT_ROOT_PATH`      | Matches Codex setup-script terminology. |
| `CODEX_WORKTREE_PATH`      | `TREEBOOT_WORKTREE_PATH`  | Matches Codex setup-script terminology. |
| `GIT_SOURCE_TREE_PATH`     | `TREEBOOT_ROOT_PATH`      | Generic compatibility alias.            |
| `GIT_WORKTREE_PATH`        | `TREEBOOT_WORKTREE_PATH`  | Generic compatibility alias.            |
| `CONDUCTOR_ROOT_PATH`      | `TREEBOOT_ROOT_PATH`      | Supports Conductor-style setup scripts. |
| `CONDUCTOR_WORKSPACE_PATH` | `TREEBOOT_WORKTREE_PATH`  | Supports Conductor-style setup scripts. |
| `CONDUCTOR_DEFAULT_BRANCH` | `TREEBOOT_DEFAULT_BRANCH` | Supports Conductor-style setup scripts. |
| `SUPERSET_ROOT_PATH`       | `TREEBOOT_ROOT_PATH`      | Supports Superset-style setup scripts.  |

### Tool-mode variables are intentionally absent

treeboot does not set `CONDUCTOR_IS_LOCAL`, `CONDUCTOR_PORT`, or
`SUPERSET_PORT_BASE`. Those variables are owned by the tools that define them
and must not be fabricated.

## Execution: Plan and run flow

Declarative config is the only bootstrap mode.

1. **Confirm Git context**: Fail early if not inside a Git working tree.
2. **Discover paths**: Resolve worktree path, root path, and default branch.
3. **Skip root checkout**: If Git's actual main-worktree identity and the
   current worktree path match, print `This is not a work tree` and exit before
   config; strict mode from CLI or environment exits non-zero.
4. **Build environment**: Set treeboot canonical variables and compatibility
   aliases, including a default `TREEBOOT_WORKTREE_ID`.
5. **Load config**: Discover TOML config unless a specific path is provided. If
   no config is found, print an info message and exit.
6. **Resolve config options**: Refine `TREEBOOT_WORKTREE_ID` from normalized
   config, then merge runtime options with environment overrides and CLI flags.
7. **Validate config**: Normalize entries and detect duplicate operation
   targets.
8. **Prepare file groups**: Plan every concrete file-operation group and
   cross-operation warning before the first possible mutation.
9. **Preview or apply**: Plan and dry-run report the prepared groups without
   mutation. Run applies those exact groups, then runs commands unless
   `--skip-commands` was selected.

## Execution: Teardown flow

Teardown is an explicitly approved, command-only phase for a linked worktree.

1. **Select target**: Resolve `--worktree`, or the process working directory,
   through Git worktree discovery to a canonical worktree top level.
2. **Discover paths**: Resolve the root checkout, default branch, and
   treeboot-owned environment for that target.
3. **Reject root checkout**: Fail before config loading or confirmation when
   Git's actual main-worktree identity and target worktree path are equal.
   Explicit and environment source-root overrides do not change this identity.
4. **Load config**: Discover TOML config in the target worktree, or use only the
   explicitly requested config path. Report `treeboot: config detected <path>`
   after selecting the path and before reading or parsing it.
5. **Normalize the whole document**: Parse all declarations and construct one
   normalized config. Any TOML syntax, type, unknown-field, declaration-shape,
   or declaration-normalization error anywhere in the document is fatal.
6. **Plan teardown**: Refine `TREEBOOT_WORKTREE_ID` from normalized config and
   validate only the teardown command collection. Bootstrap file and command
   semantic planning failures do not prevent a valid teardown.
7. **Approve**: Skip approval for no-op and dry-run outcomes. Otherwise require
   `--yes` or affirmative terminal confirmation.
8. **Execute the prepared plan**: Run the exact validated command set that was
   approved. Do not reload or reparse config after confirmation.

The preparation result distinguishes missing discovered config, a valid config
with no teardown commands, and a ready teardown plan. Missing discovered config
prints `treeboot: no config detected` and exits successfully. An explicitly
requested missing config is an error. An empty teardown plan prints
`treeboot: no teardown commands configured` and exits successfully. Neither
no-op prompts.

### Teardown confirmation

Confirmation occurs only after discovery, parsing, normalization, and teardown
planning succeed. The prompt is written to stderr and flushed before reading
stdin:

```text
Run 2 teardown commands for /repo/worktrees/feature?
These commands may delete resources outside the worktree. [y/N]
```

Only `y` and `yes`, case-insensitively after trimming whitespace, approve. Every
other response, an empty line, and EOF decline. A decline runs nothing and exits
with code `1`.

The prompt uses `1 teardown command` for one command and
`<count> teardown commands` for every other count.

When stdin is not a terminal, teardown without `--yes` runs nothing, exits with
code `1`, and tells the caller to rerun with `--yes`. Prompt read or write
failures also run nothing and exit with code `1`. `--yes` suppresses the prompt
but does not bypass discovery, parsing, normalization, or validation.
`--dry-run` never prompts and never requires `--yes`.

The unsuccessful decline contract makes this composition safe:

```sh
treeboot teardown --worktree "$path" &&
  git worktree remove "$path"
```

Treeboot itself never performs the removal.

## Migration from legacy init scripts

treeboot does not discover or execute `.treeboot.sh`, `.treebootrc`, or
`.config/treeboot/init`. These names have no special meaning and are treated as
ordinary repository files, regardless of executable permissions.
`--no-init-script`, `init --script`, and `init -s` are not accepted options;
using them is a CLI usage error with exit code `2`.

Move custom setup into a declarative command. For example:

```toml
commands = [
  { run = "./scripts/bootstrap-worktree.sh" },
]
```

Configured commands inherit the complete `TREEBOOT_*` environment and
compatibility aliases and run from the worktree root by default. Unlike the old
init-script invocation, treeboot does not automatically pass the root checkout
as positional argument `$1`; scripts should read `TREEBOOT_ROOT_PATH`, or the
config should pass it explicitly. Configured commands run after configured file
operations. `--skip-commands` omits them, and `--dry-run` reports them without
executing them.

## Declarative mode: Config files

TOML is the intended config format. Simple lists cover the common case;
top-level options and object entries cover stricter runtime, file, and command
behavior.

### Discovery

```text
.treeboot.toml
treeboot.toml
.config/treeboot/config.toml
```

The first existing config file wins. If `--config` is provided, only that file
is used. Relative config paths resolve from `TREEBOOT_WORKTREE_PATH`.

### Init Defaults

`treeboot init` creates `.treeboot.toml` by default. `treeboot init --config` is
an explicit spelling of the same config output. The command never prompts
interactively and fails if the output path already exists, including when that
path is a symlink. The starter config includes an empty `teardown_commands = []`
declaration.

```toml
teardown_commands = [
]
```

### Missing config

If no config file is detected, treeboot prints an info message such as
`treeboot: no config detected`. Without `--strict` or `TREEBOOT_STRICT` it exits
successfully. With either one, it exits non-zero. Config-level `strict` cannot
affect missing-config behavior because no config has been loaded.

For `treeboot teardown`, missing discovered config is always a successful no-op.
Teardown does not resolve bootstrap strictness. An explicitly selected missing
config remains an error.

### Config inspection

`treeboot config` uses the same config discovery rules as run mode, parses the
selected TOML file, normalizes file, bootstrap command, and teardown command
declarations, and exits successfully when parsing and normalization succeed. It
does not apply file operations or execute configured commands. Invalid TOML,
unknown fields, invalid enum values, missing required fields, and mutually
exclusive command fields are config errors.

After normalization, config inspection independently validates bootstrap and
teardown semantics. It prints phase-labelled `treeboot: warning: ...` lines for
each invalid phase without changing the successful parse-only exit status.
Non-fatal bootstrap validation warnings, such as an include list that matches no
source paths, are printed the same way. Warnings go to stderr in every output
format, so JSON and YAML stdout output stays parseable and the structured config
shape is unchanged.

### JSON Schema

`TB-CONFIG-SCHEMA`: The JSON Schema at
`crates/treeboot-spec/assets/treeboot.schema.json` is the normative
machine-readable definition of the config document's structure. It must describe
the accepted document shapes, rejected fields, and constraints that the schema
expresses. Passing schema validation does not guarantee runtime acceptance:
semantic rules that depend on normalized values, path or pattern syntax,
filesystem state, repository context, or runtime policy remain defined by the
prose contract and conformance requirements. Runtime defaults also remain
defined by the prose contract. `treeboot schema` stdout and `--output` must emit
the canonical document's exact UTF-8 bytes as described in
[`treeboot schema`](#treeboot-schema).

```toml
#:schema https://github.com/jimeh/treeboot/releases/latest/download/config.schema.json

strict = false
default_ignore = [".DS_Store", "Thumbs.db"]
worktree_id = { length = 6 }
worktree_slug = { max_length = 48, separator = "-" }
dangerously_allow_sources_outside_root = false
dangerously_allow_targets_outside_worktree = false

copy = [
  ".env.local",
  ".env.development.local",
  ".env.test.local",
  "mise.local.toml",
]

symlink = [
  ".tool-versions",
  { source = "shared/.agents", target = ".agents" },
]

sync = [
  "shared/config",
  { source = "tooling/config", target = ".config/tooling" },
]

commands = [
  "mise install",
  { name = "Install dependencies", run = "mise run setup" },
]

teardown_commands = [
  { name = "Stop services", run = "docker compose down" },
  { name = "Drop database", run = "mise run db:drop" },
]

files = [
  { operation = "copy", source = ".npmrc", target = ".npmrc" },
  { operation = "symlink", source = "shared/bin", target = "bin" },
  { operation = "sync", source = "shared/editor", target = ".editor" },
]
```

### Top-level options

Top-level options are project defaults for declarative bootstrap execution.
Environment variables override matching config values. CLI flags override both
where an equivalent flag exists. The normalized config still carries these
values during teardown, but command-only teardown does not resolve or apply
them.

| Option                                       | Environment                                           | Meaning                                                                                                                                                 |
| -------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `strict`                                     | `TREEBOOT_STRICT`                                     | Defaults to `false`. Enables stricter declarative validation and conflict handling. CLI or environment strictness also applies before config discovery. |
| `dangerously_allow_sources_outside_root`     | `TREEBOOT_DANGEROUSLY_ALLOW_SOURCES_OUTSIDE_ROOT`     | Defaults to `false`. Allows declarative file operation sources outside `TREEBOOT_ROOT_PATH`.                                                            |
| `dangerously_allow_targets_outside_worktree` | `TREEBOOT_DANGEROUSLY_ALLOW_TARGETS_OUTSIDE_WORKTREE` | Defaults to `false`. Allows declarative file operation targets outside `TREEBOOT_WORKTREE_PATH`.                                                        |
| `default_ignore`                             | none                                                  | Defaults to `[]`. Ordered path ignore patterns prepended to every `copy` and `sync` operation's effective ignore list.                                  |
| `worktree_id`                                | none                                                  | Defaults to `{ length = 6 }`. Controls the compact path-digest prefix used as the worktree ID.                                                          |
| `worktree_slug`                              | none                                                  | Defaults to `{ max_length = 48, separator = "-" }`. Controls readable worktree slug presentation.                                                       |

### File objects

`copy`, `symlink`, and `sync` accept strings and objects. Strings mean source
and target are the same path. For `sync`, string entries also use
`compare = "metadata"` and `delete = false`. The `files` list accepts objects
with an `operation` field for mixed copy, symlink, and sync entries. Missing
sources are skipped by default; object entries can set `required = true` to make
a missing source fail. When an object has `source` but no `target`, its target
defaults to the same path as `source`.

```toml
copy = [
  ".env.local",
  { source = ".env.development.local" },
  ".env.test.local",
  "mise.local.toml",
  { source = ".env.required.local", required = true },
]

symlink = [
  ".tool-versions",
  { source = "shared/.agents", target = ".agents" },
]

sync = [
  "shared/config",
  { source = "tooling/config", target = ".config/tooling", delete = true },
  { source = "shared/tool.lock", target = ".tool.lock", compare = "checksum" },
  { source = "shared/cache", target = ".cache/shared", ignore_metadata = ["ownership"] },
  { source = "shared/vendor", ignore = ["**/tmp/**", "!**/tmp/keep/**"] },
]

files = [
  { operation = "copy", source = ".npmrc", target = ".npmrc" },
  { operation = "copy", source = ".env.local", ignore_metadata = ["permissions"] },
  { operation = "symlink", source = "shared/bin", target = "bin" },
  { operation = "sync", source = "shared/editor", target = ".editor" },
]

[[file]]
operation = "copy"
source = "templates/editorconfig"
target = ".editorconfig"
```

The verbose table-array name is singular `[[file]]` so it can coexist with the
plural `files = [...]` list in the same TOML file.

| File field        | Applies to          | Meaning                                                                                                                                                                      |
| ----------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `operation`       | `files`, `[[file]]` | Required for object entries; one of copy, symlink, or sync.                                                                                                                  |
| `source`          | all file operations | Required for object entries. Relative paths resolve from root path.                                                                                                          |
| `required`        | all file operations | Defaults to `false`. When true, a missing source is a failure instead of a skipped operation.                                                                                |
| `target`          | all file operations | Optional; defaults to source. Relative paths resolve from worktree path.                                                                                                     |
| `compare`         | `sync`              | `metadata` by default; `checksum` for content checks.                                                                                                                        |
| `delete`          | `sync` directories  | Defaults to `false`; when true, deletes target-only files and directories.                                                                                                   |
| `symlinks`        | `copy`, `sync`      | Defaults to `preserve`; safe source symlinks are recreated as symlinks and unsafe symlinks are validation errors.                                                            |
| `include`         | `copy`, `sync`      | Optional list of operation-local path include patterns that narrow directory operations to matching source paths. A non-empty list cannot combine with sync `delete = true`. |
| `ignore`          | `copy`, `sync`      | Optional list of operation-local path ignore patterns appended after top-level `default_ignore`.                                                                             |
| `ignore_metadata` | `copy`, `sync`      | Optional list of metadata fields to ignore. Supported values are `permissions`, `owner`, `group`, and `ownership`. `ownership` is shorthand for owner and group.             |

### Command objects

`commands` accepts string entries and compact object entries. Strings are
shorthand for objects with a `run` field. For longer command definitions, use
verbose `[[command]]` entries.

`teardown_commands` and verbose `[[teardown_command]]` entries accept the same
fields and defaults. Compact teardown entries run before verbose teardown
entries, matching the bootstrap `commands` then `[[command]]` ordering.
Bootstrap and teardown normalize into separate ordered collections. An omitted
teardown declaration normalizes to an empty collection, so existing config files
remain valid. Older treeboot versions reject configs using the new keys because
unknown config fields are deliberately denied.

```toml
commands = [
  "mise install",
  { run = "mise run setup", env = { NODE_ENV = "development" } },
]

teardown_commands = [
  { name = "Stop services", run = "docker compose down" },
]

[[command]]
name = "Install dependencies"
run = "npm install"
cwd = "."
allow_failure = false
[command.env]
NODE_ENV = "development"

[[command]]
name = "Install dependencies without a shell"
program = "npm"
args = ["install"]

[[teardown_command]]
name = "Drop database"
program = "mise"
args = ["run", "db:drop"]
allow_failure = false
```

| Command field      | Meaning                                                                                                                     |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------- |
| `run`              | Shell command to execute. Mutually exclusive with `program`.                                                                |
| `program` / `args` | Direct process execution without shell parsing.                                                                             |
| `cwd`              | Command working directory, relative to the worktree by default. Normalized paths must stay inside `TREEBOOT_WORKTREE_PATH`. |
| `env`              | Extra environment variables merged into the treeboot env set. Treeboot-owned variables and aliases cannot be overridden.    |
| `allow_failure`    | Defaults to `false`. When true, non-zero exit is not fatal.                                                                 |

Exactly one of `run` or `program` is required. `args` is valid only with
`program`. The parser rejects unknown fields in both bootstrap and teardown
command declarations.

## Before execution: Operation validation

treeboot validates self-conflicting file operations before it starts changing
the worktree.

### Whole-document and phase boundary

Config loading parses and normalizes the whole TOML document before any
bootstrap or teardown semantic plan is built. A syntax, type, unknown-field,
declaration-shape, mutually exclusive field, or path-normalization error in any
declaration makes config loading fail for every command.

After a normalized config exists, bootstrap and teardown semantic planning are
independent:

- `treeboot run` validates and builds only the bootstrap plan.
- `treeboot teardown` validates and builds only the teardown plan.
- a missing required bootstrap source, strict sync conflict, bootstrap command
  cwd escape, or bootstrap owned-environment override does not block valid
  teardown planning
- an invalid teardown cwd or owned-environment override does not block bootstrap
  planning
- `treeboot check`, `treeboot doctor`, and `treeboot config` independently
  evaluate both phase outcomes from one complete-config validation pass

Complete-config validation orders bootstrap before teardown deterministically
and preserves both errors when both phases fail. `check` returns one fatal
aggregate error containing every failed phase. `doctor` reports separate phase
diagnostics. `config` reports phase-labelled warnings while preserving its
successful parse-only status.

### Normalize first

Config parsing normalizes `copy`, `symlink`, `sync`, `files`, and `[[file]]`
into one ordered list of file operations with resolved source and target paths.
It normalizes bootstrap and teardown declarations into separate ordered command
collections. Manual `copy`, `symlink`, and `sync` commands must produce the same
normalized operation shape.

Relative file-operation source paths resolve from `TREEBOOT_ROOT_PATH`. Relative
file-operation target paths and command `cwd` paths resolve from
`TREEBOOT_WORKTREE_PATH`. Absolute paths are preserved and then normalized
against the filesystem where possible. Missing final path components are
normalized by canonicalizing the nearest existing ancestor and applying lexical
`.` / `..` cleanup to the missing tail.

On Windows, normalized paths must be emitted in ordinary tool-friendly form when
the platform returns an extended-length path during canonicalization. Fully
qualified drive paths such as `C:\repo\file`, UNC paths such as
`\\server\share\repo\file`, and relative paths without a drive or root prefix
are supported. Drive-relative paths such as `C:repo\file` and root-relative
paths without a drive or share such as `\repo\file` are rejected for declarative
file-operation paths, manual file-operation paths, and command `cwd` values
because they depend on process-local current-drive state.

### Conflicting targets

If multiple file operations target the same normalized absolute path, or one
target is inside another target, treeboot must report every conflicting entry
with its operation, source, target, and declaration location when available.

### Target boundary

Every file operation target must resolve inside `TREEBOOT_WORKTREE_PATH`.
Targets outside the current worktree are validation errors by default. For
symlink operations, the target is the path of the symlink created in the
worktree; the symlink destination is the source and may point back into
`TREEBOOT_ROOT_PATH`.

Existing target parent components under `TREEBOOT_WORKTREE_PATH` must be real
directories. If a target parent component is a symlink or another non-directory
file type, validation fails before any file operation or command runs. Missing
parent components are allowed and created as directories when the operation is
applied. The final target path itself is not treated as a parent component:
force and sync may still replace the final target path when the conflict matrix
allows replacing an existing file or symlink.

Immediately before a file operation mutates a target, treeboot must re-check the
live target ancestor chain. If a target ancestor became a symlink or
non-directory after validation, that operation fails before mutating the target.

### Source boundary

Every file operation source must resolve inside `TREEBOOT_ROOT_PATH`. Sources
outside the root path are validation errors by default.

### Command boundary

Bootstrap and teardown command `cwd` values are normalized relative to
`TREEBOOT_WORKTREE_PATH`. Paths may contain `..`, but the final resolved path
must stay inside the worktree. Planning resolves each cwd before any side effect
and retains that canonical worktree boundary. Immediately before spawning each
command, treeboot re-resolves the cwd and live worktree root. The live root must
still equal the planning-time boundary, and the freshly resolved cwd must remain
inside it. For bootstrap this happens after file operations; teardown has no
file phase. A changed root or escaped cwd prevents the spawn and follows the
normal command-start `allow_failure` policy.

| Rule                                                        | Behavior                                                        |
| ----------------------------------------------------------- | --------------------------------------------------------------- |
| Any duplicate operation target                              | Fail before any file operation or command runs.                 |
| Target resolves outside the worktree                        | Fail before any file operation or command runs.                 |
| Target parent is a symlink or non-directory at validation   | Fail before any file operation or command runs.                 |
| Target ancestor becomes a symlink or non-directory at apply | Fail that operation before mutating the target.                 |
| Source resolves outside the root path                       | Fail before any file operation or command runs.                 |
| Required file operation source does not exist               | Fail before any file operation or command runs.                 |
| Optional file operation source does not exist               | Skip that operation, make no target changes, and continue.      |
| Command `cwd` resolves outside the worktree during planning | Fail before any file operation or command runs.                 |
| Live worktree root differs from its planned boundary        | Do not spawn it; fail or warn and continue per `allow_failure`. |
| Command `cwd` resolves outside the worktree before spawn    | Do not spawn it; fail or warn and continue per `allow_failure`. |
| Command `env` overrides treeboot-owned variables            | Fail before any file operation or command runs.                 |
| Copy or sync encounters an unsafe source symlink            | Fail before any file operation or command runs.                 |
| Preserved copy or sync source symlink changes before apply  | Fail that operation before mutating the target.                 |
| Strict mode with any sync operation                         | Fail before any file operation or command runs.                 |
| `--dry-run`                                                 | Print the validation error, change no files, and exit non-zero. |

### Conflicting targets are invalid config

A config that copies a file and later symlinks to the same target is ambiguous
at best and destructive under force mode. treeboot must reject duplicate
configured targets in every mode. It must also reject ancestor/descendant target
pairs because a sync operation with `delete = true` can remove target-only
children produced by another operation in the same plan. Manual commands must
reject duplicate and overlapping targets derived from their source arguments and
`--target` before any file changes are made.

### Outside-worktree targets need an explicit escape hatch

The top-level option `dangerously_allow_targets_outside_worktree = true`
disables the target-boundary check. `dangerously_allow_sources_outside_root`
separately disables the source-boundary check. These checks affect declarative
file operations and manual file operation commands. Configured commands remain
unrestricted because treeboot cannot safely validate arbitrary command behavior.

### Strict mode is incompatible with sync

Sync expects existing targets and can be configured to delete target-only files,
so strict mode rejects sync operations before execution. Strict mode can be
enabled with `--strict`, top-level `strict = true`, or `TREEBOOT_STRICT=true`.

## Files first: File operations

Sources resolve against the root path. Targets resolve against the worktree
path. Parent target directories are created as needed.

| Config                                               | Source                                         | Target                                                     |
| ---------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------- |
| `copy = [".env.local"]`                              | `TREEBOOT_ROOT_PATH/.env.local`                | `TREEBOOT_WORKTREE_PATH/.env.local`                        |
| `symlink = [".tool-versions"]`                       | `TREEBOOT_ROOT_PATH/.tool-versions`            | `TREEBOOT_WORKTREE_PATH/.tool-versions`                    |
| `sync = ["shared/config"]`                           | `TREEBOOT_ROOT_PATH/shared/config`             | `TREEBOOT_WORKTREE_PATH/shared/config`                     |
| `{ source = "a", target = "b" }`                     | `TREEBOOT_ROOT_PATH/a`                         | `TREEBOOT_WORKTREE_PATH/b`                                 |
| `{ operation = "sync", source = "a", target = "b" }` | `TREEBOOT_ROOT_PATH/a`                         | `TREEBOOT_WORKTREE_PATH/b`                                 |
| `treeboot copy a --target b`                         | `TREEBOOT_ROOT_PATH/a`                         | `TREEBOOT_WORKTREE_PATH/b`                                 |
| `treeboot copy a c --target b`                       | `TREEBOOT_ROOT_PATH/a`, `TREEBOOT_ROOT_PATH/c` | `TREEBOOT_WORKTREE_PATH/b/a`, `TREEBOOT_WORKTREE_PATH/b/c` |

### Manual operation source completion

`TB-COMPLETION-SOURCES`: Installed shell completions for the source arguments of
`treeboot copy`, `treeboot symlink`, and `treeboot sync` must list files and
directories from the resolved root path, not from the current worktree.

Completion candidates must be relative to the root path so completed values can
be reused as default targets.

Root-relative source completion applies to every shell supported by
`treeboot completions`: Bash, Zsh, Fish, PowerShell, and Elvish.

Completion candidate generation uses root/worktree discovery only. It must not
parse config files, run configured commands, or fail because config is missing
or invalid.

### Manual operation normalization

Manual file operation commands normalize to the same internal file operation
shape as config entries. The subcommand supplies `operation`, each positional
source supplies `source`, `--required` supplies `required = true`, and
operation-specific flags supply `symlinks`, `compare`, `delete`, `include`,
`ignore`, or `ignore_metadata`.

Manual normalization happens under the same resolved runtime policy as
declarative file operations: defaults, then config top-level policy when a
config is present, then environment overrides, then CLI strictness. For manual
`copy` and `sync`, effective ignore rules are the loaded config's
`default_ignore` patterns followed by repeated `--ignore` flags. Effective
include rules are the repeated `--include` flags alone; no config default is
merged.

If `--target` is omitted, each target defaults to its source value. If one
source is passed, `--target` is that operation's target. If more than one source
is passed, `--target` is joined with each source value to produce each
operation's target.

### Missing sources

Missing sources are optional by default for copy, symlink, and sync. When a
source does not exist and the entry does not set `required = true`, treeboot
skips that operation and leaves the target unchanged. This lets one config list
several local-only files, such as `.env.local` and `.env.development.local`,
while only applying the files that exist in the root checkout.

### Copy

Copies files and directories. Directory copies recursively copy the source
directory into the configured target path. This is a copy operation, not a sync
operation: treeboot never deletes target files merely because they are absent
from the source. Source symlinks are preserved by default when they are safe. By
default, copy preserves the metadata described in
[File metadata preservation](#file-metadata-preservation). Configure `ignore`,
or use `--ignore`, to skip selected source paths during directory copies.
Configure `include`, or use `--include`, to narrow directory copies to selected
source paths. Configure `ignore_metadata`, or use `--ignore-metadata`, to opt
out of selected metadata fields.

`treeboot copy` exposes `--target`, `--required`, `--symlinks`, `--include`,
`--ignore`, `--ignore-metadata`, `--dry-run`, `--verbose`, `--strict`, and
`--force`.

### Symlink

Creates relative symlinks whenever treeboot can compute the path from the target
parent to the source. If it cannot, it falls back to an absolute symlink.

`treeboot symlink` exposes `--target`, `--required`, `--dry-run`, `--verbose`,
`--strict`, and `--force`.

### Sync

Reconciles target content to match source content. Files are compared by size
and modified time by default, or by content when `compare = "checksum"` is set.
Checksum comparison must detect content changes even when size and modified time
do not change. Sync also compares and repairs the metadata fields described in
[File metadata preservation](#file-metadata-preservation), unless those fields
are listed in `ignore_metadata`. Configure `ignore`, or use `--ignore`, to skip
selected source and target paths during directory sync. Configure `include`, or
use `--include`, to narrow directory sync to selected source paths; a non-empty
`include` list cannot be combined with `delete = true`. Source symlinks are
preserved by default when they are safe.

`treeboot sync` exposes `--target`, `--required`, `--compare`, `--delete`,
`--no-delete`, `--symlinks`, `--include`, `--ignore`, `--ignore-metadata`,
`--dry-run`, `--verbose`, `--strict`, and `--force`.

### Path ignore rules

`default_ignore` is an ordered top-level list of path patterns prepended to
every `copy` and `sync` operation's effective ignore list. `ignore` is an
ordered list of operation-local path patterns appended after `default_ignore`.
Patterns use gitignore-style syntax, including `*`, `?`, `**`, character
classes, trailing slash directory matches, comments, escaped metacharacters, and
`!` negation. Later matching patterns override earlier matching patterns. A path
matched by a non-negated pattern is ignored. A path matched by a later negated
pattern is re-included. Because operation-local `ignore` patterns come after
`default_ignore`, an operation-local `!` pattern can re-include a path ignored
by the top-level defaults.

A pattern that cannot be parsed as a glob is a file operation validation error,
reported before any side effects. Unlike Git, treeboot does not silently skip
malformed patterns.

Normalized file operations expose the effective merged ignore list in their
`ignore` field. Normalized config output also preserves `default_ignore` as a
top-level policy field.

treeboot never loads `.gitignore`, `.ignore`, `.rgignore`, `.git/info/exclude`,
or global Git ignore files for file operations. Ignore rules come only from
top-level `default_ignore`, the operation's `ignore` field, or repeated manual
`--ignore` flags.

Patterns match source-relative paths for the operation. For example, with
`source = "shared"` and `ignore = ["**/vendor/**"]`, the pattern is evaluated
against paths below `TREEBOOT_ROOT_PATH/shared`, not against paths below the
repository root unless the operation source is the root itself. Matching uses
directory knowledge, so directory-only patterns match only directories.

Ignore rules affect directory sources only. When a `copy` or `sync` source is a
single file or a source symlink, treeboot validates the patterns but does not
apply them to skip the top-level source. Use a directory source when selective
path filtering is required.

Ignored source paths are skipped before copy/sync action planning and before
unsafe source-symlink validation. Ignored unsafe symlinks are therefore not
validation errors. Re-included paths are planned and validated normally.

When negated patterns are present, treeboot must still be able to discover
re-included descendants under ignored directories. Implementations may traverse
ignored directories conservatively to find re-included descendants. Ignored
directories that exist only as ancestors of re-included descendants may be
created as target parent directories, but treeboot must not report or repair the
ignored directory itself unless that directory is re-included.

For directory sync with `delete = true`, ignore rules also apply to target-only
paths by evaluating the same operation-relative path under the sync target.
Ignored target-only files and directories are preserved. Re-included target-only
paths remain eligible for deletion.

### Path include rules

`include` is an ordered list of operation-local path patterns that narrows a
`copy` or `sync` operation to matching source paths. When an operation's include
list is empty or absent, no include filtering applies. When it is non-empty, a
path below a directory source is in scope only when it matches at least one
include pattern and is not ignored.

Include and ignore are independent gates evaluated against the same
source-relative paths. Include selects paths as a plain union: a path is
included when any include pattern matches it, without last-match-wins ordering.
Ignore rules then remove paths from that selection. A negated `!` ignore pattern
only unwinds earlier ignore patterns; it cannot re-include a path that does not
match the include rules.

Include patterns use the same gitignore-style syntax as ignore patterns, except
that every include entry must be an effective positive pattern. Patterns
beginning with `!`, blank or whitespace-only patterns, and `#` comment lines are
validation errors in include lists; exclusion belongs to `ignore`. The `\!` and
`\#` escapes remain valid and match literal leading `!` or `#` characters in
file names. As with ignore patterns, an include pattern that cannot be parsed as
a glob is a file operation validation error. Because inert entries are rejected,
a non-empty include list always filters.

A directory that matches an include pattern includes its whole subtree, subject
to ignore rules. A directory that matches no include pattern is still traversed
when a descendant could match. Directories receive target actions only when the
directory itself is included or its subtree contains an in-scope path; a path
that matches include but is ignored is not in scope and does not materialize its
ancestors. Ancestor directories of in-scope paths that are not ignored are
created as target parent directories and keep their normal metadata comparison
and repair behavior, even when every in-scope descendant is unchanged. Ignored
ancestors traversed only to reach in-scope descendants follow
[Path ignore rules](#path-ignore-rules) and are not reported or repaired unless
re-included. Directories with no in-scope descendants that are not themselves
included produce no target actions.

Like ignore rules, include rules affect directory sources only. When a `copy` or
`sync` source is a single file or a source symlink, treeboot validates the
patterns but never filters the top-level source. Each operation's include list
applies only within that operation's source tree; selecting which sources an
invocation covers is done by listing them.

Non-included source paths are skipped before copy/sync action planning and
before unsafe source-symlink validation. Non-included unsafe symlinks are
therefore not validation errors.

`include` is rejected on `symlink` operations, like `ignore`. A `sync` operation
with a non-empty `include` list cannot combine it with `delete = true`: config
validation rejects the combination, and `--include` conflicts with `--delete` /
`-D` for manual `treeboot sync`. Absent `include` and `include = []` do not
conflict with deletion. To mirror a subtree with deletion, narrow the
operation's source instead of using include patterns.

There is no top-level `default_include`. Include rules come only from the
operation's `include` field or repeated manual `--include` flags. For manual
`copy` and `sync`, the effective include list is the repeated `--include` flags
alone; the config `default_ignore` merging behavior has no include counterpart.

An include list that matches no source paths is not an error. `run` performs the
operation with no in-scope paths and stays silent. `treeboot check` and
`treeboot config` surface one non-fatal warning, in operation order, for each
`copy` or `sync` operation whose effective include list is non-empty, whose
source exists and is a directory, and whose source tree contains no path
matching the include rules before ignore filtering. Operations whose source is
missing, a single file, or a source symlink do not produce zero-match include
warnings.

Implementations may prune directories that cannot contain included paths instead
of traversing them. Because of this latitude, an unreadable directory that is
outside include scope may or may not produce an error. Pruning must not
otherwise change observable results.

Normalized file operations expose the operation-local include list in their
`include` field.

### Symlinks inside copy and sync

Copy and sync use `symlinks = "preserve"` by default: safe source symlinks are
recreated as symlinks instead of copying their referents. A source symlink whose
target text is empty, whose target is dangling or otherwise cannot be resolved,
or whose resolved target is outside `TREEBOOT_ROOT_PATH` is a validation error.
Ignored paths and paths outside include scope may be skipped before this
validation under [Path ignore rules](#path-ignore-rules) and
[Path include rules](#path-include-rules). Preserved source symlinks are
rechecked immediately before target mutation; if the source stops being a
symlink, changes the planned target, cannot be resolved, or resolves outside
`TREEBOOT_ROOT_PATH`, treeboot fails the operation before creating or replacing
the worktree link. When source and target layouts differ, treeboot rewrites
copied symlinks to point at the analogous worktree destination when it can.
Root-local symlink targets are mapped by root-relative path into the worktree
before treeboot computes the destination symlink. When no rewrite is needed,
treeboot preserves the symlink target text. For a safe, resolvable root-local
source symlink, treeboot prints a warning if its final worktree referent does
not exist and will not be created by the current run. This warning does not
apply to a dangling source symlink, which fails validation. Projects that need
custom symlink handling should use a configured command.

### File metadata preservation

Copy and sync preserve regular file contents, permissions, owner, group, and
modified time where the platform supports them. For directories, copy and sync
preserve permissions, owner, and group where supported. Directory modified time
is not preserved or compared because directory modified times change as children
are created, removed, or updated.

`ignore_metadata` lets a copy or sync operation opt out of selected metadata
comparison and preservation. Supported values are:

| Value         | Meaning                                                        |
| ------------- | -------------------------------------------------------------- |
| `permissions` | Do not compare or apply file or directory permission metadata. |
| `owner`       | Do not compare or apply owner metadata.                        |
| `group`       | Do not compare or apply group metadata.                        |
| `ownership`   | Shorthand for `owner` and `group`.                             |

Ignored metadata fields do not trigger sync updates and are not applied after
copy or sync content updates. Non-ignored metadata fields are still compared and
applied. Modified time is not configurable in this version; regular-file
modified time remains part of the default sync idempotency contract because
`compare = "metadata"` compares size and modified time for content drift.

Permission preservation failures are operation failures. Owner and group
preservation is best-effort when the operating system denies ownership changes,
because unprivileged users often cannot set arbitrary owners or groups. In that
case treeboot reports a warning and continues. Other unexpected ownership errors
are operation failures.

This metadata contract is intentionally narrower than archive copying. treeboot
does not preserve ACLs, extended attributes, resource forks, file flags,
hard-link identity, sparse-file layout, or other platform-specific archive
metadata. Projects that need archive semantics should use project-local commands
such as `rsync`, `cp -a`, `ditto`, or another purpose-built tool.

### Sync preserves extras by default

When the source is a directory, sync recurses through source and target. It
copies new files and updates changed files. Target files or directories that do
not exist in the source are preserved by default. Configure `delete = true` on a
sync entry, or use `--delete` / `-D` for manual sync, to delete target-only
files and directories. Deletion cannot be combined with a non-empty `include`
list; see [Path include rules](#path-include-rules).

### Operation order

treeboot executes `copy` list entries first, `symlink` list entries second,
`sync` list entries third, `files` entries fourth, then `[[file]]` entries in
document order.

## Safety: Conflict modes

The default mode is optimized for repeated worktree setup. Strict mode is for
CI-like validation. Force mode is intentionally destructive and requires
explicit selection.

### Trusted setup inputs

`treeboot run` and `treeboot teardown` are intended for repositories whose setup
contract the user trusts. The trust boundary includes declarative config files
and configured commands, which can run arbitrary code and may modify or delete
resources outside the worktree. Use `treeboot config` to inspect TOML without
execution, `treeboot run --skip-commands` to apply only configured file
operations, and `treeboot teardown --dry-run` to inspect teardown command
execution.

Dry-run reports the same file-operation decision that treeboot would take
without mutating files. Default text output reports one compact line per
top-level file operation when that operation has a visible decision. A single
file create, update, symlink, delete, or skip uses the same direct line shape as
the concrete action. Directory copy and sync operations summarize expanded child
actions with counts. `--verbose` reports each concrete child action instead of
the compact top-level summary.

The table below is the compatibility contract for file-operation conflicts.

| Case                                  | Default                                                                                              | `--strict`                             | `--force`                                | `--dry-run`                                                                                       |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------- |
| Copy file to missing destination      | Create file and parents.                                                                             | Create file and parents.               | Create file and parents.                 | Report planned create.                                                                            |
| Copy file to existing file or symlink | Skip with info output.                                                                               | Fail before mutation.                  | Replace file or symlink.                 | Report skip, fail, or replace.                                                                    |
| Copy file to existing directory       | Fail operation.                                                                                      | Fail before mutation.                  | Fail; do not remove directory.           | Report failure.                                                                                   |
| Copy directory to missing destination | Recursively create directory tree. Summarize expanded child actions by default.                      | Recursively create directory tree.     | Recursively create directory tree.       | Report planned creates, summarized by default.                                                    |
| Copy directory to existing directory  | Recursively copy missing files and skip existing files. Summarize expanded child actions by default. | Fail before mutation.                  | Merge and overwrite matching files only. | Report planned creates, skips, fail, or merge, summarized by default.                             |
| Copy directory to file or symlink     | Fail operation.                                                                                      | Fail before mutation.                  | Fail; do not replace with directory.     | Report failure.                                                                                   |
| Symlink to missing destination        | Create parent directories and symlink.                                                               | Create parent directories and symlink. | Create parent directories and symlink.   | Report planned symlink.                                                                           |
| Symlink to existing file or symlink   | Skip with info output.                                                                               | Fail before mutation.                  | Replace file or symlink.                 | Report skip, fail, or replace.                                                                    |
| Symlink to existing directory         | Fail operation.                                                                                      | Fail before mutation.                  | Fail; do not remove directory.           | Report failure.                                                                                   |
| Sync file                             | Create or update when changed.                                                                       | Rejected by validation.                | Same as default.                         | Report create or update; stay silent when unchanged.                                              |
| Sync directory                        | Reconcile tree; preserve target-only files by default. Summarize expanded child actions by default.  | Rejected by validation.                | Same as default.                         | Report creates, updates, and explicit deletes, summarized by default; stay silent when unchanged. |
| Optional missing source               | Skip and leave target unchanged.                                                                     | Skip and leave target unchanged.       | Skip and leave target unchanged.         | Report planned skip.                                                                              |

### Directory copy under force

In force mode, copying a source directory over an existing target directory
traverses the source and overwrites matching target files. It does not remove
target files or directories that are not present in the source. Removing extras
would be sync behavior, not copy behavior.

### Force does not erase directories casually

Force mode may replace existing regular files and symlinks. It must not delete a
non-empty directory to satisfy a copy or symlink operation. Copying a file over
a directory, creating a symlink over a directory, or copying a directory over a
file are operation failures. Use sync when directory contents should be
reconciled.

### Sync is intentionally destructive

Sync is the operation that may delete target-only files when deletion is
explicitly enabled. Existing targets are expected for sync and are not treated
as conflicts in default or force mode. Strict mode rejects configs with sync
operations before runtime. Use `--dry-run` to preview sync creates, updates, and
explicit deletes.

## File operation output and progress

File-operation output is compact by default and preserves detailed diagnostics
when requested. Default text output is grouped by top-level file operation.
Top-level operations are declarative config entries or normalized manual source
arguments.

Single concrete actions omit parenthesized counts because the source and target
already describe the work:

```text
treeboot: copy .env -> .env
treeboot: sync .env -> .env
treeboot: would copy .env -> .env
treeboot: skip copy .env; target exists
treeboot: would skip copy .env; target exists
```

Expanded operations include counts after the source and target:

```text
treeboot: copy shared -> shared (12 changed)
treeboot: copy node_modules -> node_modules (1842 changed, 27 skipped)
treeboot: sync shared -> shared (4 changed, 1 deleted)
treeboot: would sync shared -> shared (4 changes, 1 delete)
```

Count words are singular when the count is one and plural otherwise. `changed`
counts created directories, copied files, created symlinks, and replaced files
or symlinks. `skipped` counts planned or actual skip decisions. `deleted` counts
sync target-only paths removed or planned for removal.

Manual multi-source commands report each normalized source operation
independently:

```text
treeboot copy a b --target local

treeboot: copy a -> local/a (12 changed)
treeboot: copy b -> local/b (4 changed, 2 skipped)
```

`--verbose` preserves the detailed action stream. In verbose mode, directory
copy and sync report concrete creates, updates, deletes, skips, and warnings
rather than only the grouped summary. Verbose mode disables interactive progress
rendering so detailed lines do not interleave with progress redraws.

When stdout and stderr are interactive terminals, non-verbose copy and sync
operations may render ephemeral progress on stderr: a spinner while planning a
top-level operation and a determinate progress bar while applying planned
actions. Progress rendering must not change the final stdout summary lines. When
output is redirected, captured by CI, or otherwise non-interactive, non-verbose
file operations must suppress spinner/progress control output and print only
normal summary, warning, command, and error lines.

File-operation warnings remain visible in compact mode. If a warning is emitted
while progress is active, progress must be cleared or suspended before printing
the warning so terminal output remains readable.

## Command phases: Shared runtime

Bootstrap and teardown commands are arbitrary project commands. treeboot plans
and runs both collections through the same command semantics while keeping the
phase plans separate.

### Execution rules

- Bootstrap commands run after file operations complete successfully and run
  even if every file operation was skipped.
- Teardown commands run without applying any file operation or bootstrap
  command.
- Commands run sequentially in declaration order.
- Re-resolve each command cwd and the live worktree root immediately before
  spawn, require the root to equal the planning-time boundary, and reject a live
  cwd escape.
- A command with `allow_failure = true` warns when it cannot be spawned or exits
  non-zero, then later commands continue.
- Run from `TREEBOOT_WORKTREE_PATH` unless a command sets `cwd`.
- Receive the full treeboot environment variable set described in
  [Environment variables]#compatibility-environment-variables.
- Per-command `env` values are merged into that environment for that command
  only.
- Bootstrap commands skip only when `treeboot run --skip-commands` is provided.
- In run `--dry-run`, report planned file operations and bootstrap commands
  without spawning any configured command process.
- In teardown `--dry-run`, report teardown commands without prompting or
  spawning any configured command process.

### Shells

```text
Unix:    sh -c <command>
Windows: cmd /C <command>

Direct:  program + args
```

String commands and objects with `run` use the shell. Objects with `program`
execute directly without shell parsing.

### Parallel setup work

treeboot does not parallelize configured commands. Projects that want parallel
setup work should delegate to one project-local task, such as `mise run setup`,
`make setup`, or another task runner command.

### Lifecycle output

For bootstrap, treeboot reports `treeboot: run <label>` before spawning each
command. In dry-run it reports `treeboot: would run <label>` instead.

For teardown, treeboot reports `treeboot: teardown run <label>` before spawning
each command. In dry-run it reports `treeboot: teardown would run <label>`
instead.

A successful command in either phase does not produce a separate success event.

### Command labels

Labels include both `name` and invocation when `name` is set, formatted as
`Name: invocation`. Without a name, shell commands use the shell string and
direct commands use `program arg...`.

### Child output

Commands inherit stdout and stderr directly.

### Failures

Fatal command failures exit non-zero immediately and later commands do not run.
In either phase, a command that cannot be spawned reports
`treeboot: failed to run command <label>: <io-error>` to stderr and exits
non-zero unless `allow_failure = true`.

Allowed failures always emit a phase-labelled warning and do not make the
command fail by themselves:

```text
treeboot: warning: command optional lint: npm run lint failed with exit status: 1
treeboot: warning: teardown command Stop services: docker compose down failed with exit status 1
```

Execution-time cwd resolution or boundary failures use the same phase-specific
command-start failure behavior and prevent that command from spawning. Under
`allow_failure = false` the failure is fatal; under `allow_failure = true` it
warns and later commands continue.

### Cross-platform contract

Windows support is part of the compatibility contract. Shell execution, path
handling, symlink creation, and canonical path presentation must follow the
platform-specific rules in this specification.

## Operator experience: Output and exit codes

Output should be concise enough for setup logs while still making skipped
targets and destructive choices obvious.

```text
treeboot: copy .env.local -> .env.local
treeboot: skip copy .env.local; target exists
treeboot: symlink .tool-versions -> ../repo/.tool-versions
treeboot: sync shared/config -> .config
treeboot: sync metadata shared/editor/settings.json -> .editor/settings.json
treeboot: sync shared -> shared (4 changed, 1 deleted)
treeboot: run Install packages: npm install
treeboot: teardown run Stop services: docker compose down
treeboot: warning: could not preserve ownership shared/cache: operation not permitted
treeboot: warning: command optional lint: npm run lint failed with exit status: 1
```

Unchanged sync files and directories produce no output. Sync reports creates,
content updates, metadata-only updates, and deletes directly for single concrete
actions and as grouped counts for expanded directory operations. Command child
output is inherited directly.

Metadata-only sync updates use the same source and target display style as
content updates:

```text
treeboot: sync metadata shared/config -> shared/config
treeboot: would sync metadata shared/config -> shared/config
treeboot: warning: could not preserve ownership shared/config: operation not permitted
```

Interactive progress is ephemeral terminal UI, not durable log output. It is
rendered to stderr only for non-verbose copy and sync operations on interactive
terminals. Final summaries, warnings, and command lifecycle lines remain normal
`treeboot:` lines.

Command start lines use `treeboot: run <label>`. Dry-run uses
`treeboot: would run <label>` and does not spawn commands. Fatal command
failures are reported as `treeboot: command <label> failed with <status>`. Fatal
spawn failures are reported as
`treeboot: failed to run command <label>: <io-error>`. Allowed spawn failures
are reported as
`treeboot: warning: command <label> failed to start: <io-error>`.

Teardown command start lines use `treeboot: teardown run <label>`. Teardown
dry-run uses `treeboot: teardown would run <label>`. Teardown allowed-failure
messages identify the teardown phase. Discovery output remains shared:

```text
treeboot: config detected /repo/worktrees/feature/.treeboot.toml
treeboot: teardown run Stop services: docker compose down
treeboot: teardown run Drop database: mise run db:drop
```

No-op output is durable:

```text
treeboot: no config detected
treeboot: no teardown commands configured
```

Command-wide manual argument or option validation errors must identify the CLI
operation and the offending option, value, or reason. An error while normalizing
a manual operation's declared source-to-target mapping must identify the CLI
operation and source. It must also identify the target once target derivation
has succeeded. After normalization, a file-operation planning or execution error
must identify the CLI operation, the path involved, and the reason. A recursive
source-tree inspection or resolution error must identify the CLI operation and a
source path associated with the failure. That path may be the operation's
declared top-level source, its normalized location, or a nested source path. It
should identify the most specific failing source path available. None of these
error categories reports synthetic config paths or TOML locations for
command-line arguments. Config parse or normalization errors found while loading
manual command policy still report the real config path and TOML location.

| Exit | Meaning                                                                                                             |
| ---- | ------------------------------------------------------------------------------------------------------------------- |
| `0`  | Success, including missing discovered config or no teardown commands.                                               |
| `1`  | Runtime failure, config error, operation or command failure, teardown decline, or missing non-interactive approval. |
| `2`  | CLI usage error.                                                                                                    |

This Markdown document is the project specification for treeboot.