ccsm 0.18.0

Context-managed session orchestration for AI coding agents — track, resume, and manage work across sessions
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
use anyhow::{Context, Result};
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};


// ── Workspace Identity ────────────────────────────────────────────

/// Workspace identity loaded from the `.ccsm` TOML file at project root.
///
/// `version` is the ccsm version that created this identity (from Cargo.toml).
/// On upgrade, migration code checks this field to run version-specific migrations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceIdentity {
    pub version: String,
    pub id: String,
}

/// Resolved workspace context for the current invocation.
pub struct WorkspaceContext {
    pub id: String,
    pub root: PathBuf,
    pub slug: String,
}

/// Home directory used for `~/.ccsm/` resolution. Override via `HOME` env var.
pub fn home_dir() -> PathBuf {
    std::env::var("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("/tmp"))
}

/// Global data directory for a workspace.
/// Default: `$HOME/.ccsm/<id>/`.
/// Override: `CCSM_DATA_DIR` env var sets a custom base (path is `<CCSM_DATA_DIR>/<id>/`).
pub fn global_data_dir(id: &str) -> PathBuf {
    let base = std::env::var("CCSM_DATA_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|_| home_dir().join(".ccsm"));
    base.join(id)
}

/// Path to the session registry: `~/.ccsm/<id>/sessions.json`
pub fn global_registry_path(id: &str) -> PathBuf {
    global_data_dir(id).join("sessions.json")
}

/// Path to the lock file: `~/.ccsm/<id>/sessions.json.lock`
pub fn global_lock_path(id: &str) -> PathBuf {
    global_data_dir(id).join("sessions.json.lock")
}

/// Path to a session detail file: `~/.ccsm/<id>/sessions/<name>.md`
pub fn global_detail_path(id: &str, name: &str) -> PathBuf {
    global_data_dir(id).join("sessions").join(format!("{name}.md"))
}

/// Path to the session detail template: `~/.ccsm/<id>/session-detail-template.md`
pub fn global_template_path(id: &str) -> PathBuf {
    global_data_dir(id).join("session-detail-template.md")
}

/// Path to a group detail file: `~/.ccsm/<id>/session-group/<name>.md`
pub fn global_group_path(id: &str, name: &str) -> PathBuf {
    global_data_dir(id).join("session-group").join(format!("{name}.md"))
}

/// Path to a worktree: `~/.ccsm/<id>/worktrees/<name>/`
pub fn global_worktree_path(id: &str, name: &str) -> PathBuf {
    global_data_dir(id).join("worktrees").join(name)
}

/// Path to the project config: `~/.ccsm/<id>/config.toml`
pub fn global_config_path(id: &str) -> PathBuf {
    global_data_dir(id).join("config.toml")
}

/// Walk up from `start` looking for a `.ccsm` identity file.
/// Returns the directory containing the file and its parsed contents.
pub fn find_project_root(start: &Path) -> Result<Option<(PathBuf, WorkspaceIdentity)>> {
    let mut current = Some(start);
    while let Some(dir) = current {
        let ccsm_file = dir.join(".ccsm");
        if ccsm_file.is_file() {
            let content = std::fs::read_to_string(&ccsm_file)
                .with_context(|| format!("reading {}", ccsm_file.display()))?;
            let identity: WorkspaceIdentity = toml::from_str(&content)
                .with_context(|| format!("parsing {} — expected `version` and `id` fields", ccsm_file.display()))?;
            return Ok(Some((dir.to_path_buf(), identity)));
        }
        current = dir.parent();
    }
    Ok(None)
}

/// Walk up from CWD to find the project root and workspace identity.
/// Errors if no `.ccsm` file exists — use `init_identity()` to create one.
/// On existing identity with stale version, runs version-gated migrations.
/// Also handles legacy `.ccsm/sessions.json/` → identity file migration.
pub fn resolve_identity() -> Result<WorkspaceContext> {
    let cwd = std::env::current_dir()?;

    if let Some((root, identity)) = find_project_root(&cwd)? {
        run_identity_migrations(&identity, &root)?;
        let slug = project_slug(&identity.id);
        return Ok(WorkspaceContext {
            id: identity.id,
            root,
            slug,
        });
    }

    // Check for legacy `.ccsm/sessions.json` to auto-migrate
    let mut current = Some(cwd.as_path());
    while let Some(dir) = current {
        if dir.join(".ccsm").join("sessions.json").exists() {
            let root = dir.to_path_buf();
            let id = uuid_v4();
            eprintln!("ccsm: migrating from {}/.ccsm/ to ~/.ccsm/{id}/", root.display());
            let ccsm_path = root.join(".ccsm");
            migrate_legacy_data(&root, &id)?;
            if ccsm_path.is_dir() {
                std::fs::remove_dir_all(&ccsm_path)?;
            }
            let content = format!("version = \"{}\"\nid = \"{id}\"\n", env!("CARGO_PKG_VERSION"));
            std::fs::write(&ccsm_path, &content)
                .context("writing .ccsm identity file")?;
            let slug = project_slug(&id);
            return Ok(WorkspaceContext { id, root, slug });
        }
        current = dir.parent();
    }

    anyhow::bail!(
        "no .ccsm identity file found in this project.\n\
         Run `ccsm init` to set up session tracking in the current directory."
    );
}

/// Create a `.ccsm` identity file at the nearest git root (or CWD).
/// Idempotent — won't overwrite an existing identity.
/// Also ensures the global data directory exists.
pub fn init_identity() -> Result<WorkspaceContext> {
    let cwd = std::env::current_dir()?;

    if let Some((root, identity)) = find_project_root(&cwd)? {
        eprintln!("ccsm: .ccsm identity already exists at {}", root.display());
        let slug = project_slug(&identity.id);
        return Ok(WorkspaceContext { id: identity.id, root, slug });
    }

    let root = find_nearest_git_root(&cwd).unwrap_or(cwd);
    let id = uuid_v4();
    let ccsm_path = root.join(".ccsm");
    if ccsm_path.is_dir() {
        std::fs::remove_dir_all(&ccsm_path)?;
    }
    if !ccsm_path.exists() {
        let content = format!("version = \"{}\"\nid = \"{id}\"\n", env!("CARGO_PKG_VERSION"));
        std::fs::write(&ccsm_path, &content)
            .context("writing .ccsm identity file")?;
    }
    let slug = project_slug(&id);
    ensure_data_dir(&id)?;
    eprintln!("ccsm: initialised workspace {id} at {}", root.display());
    Ok(WorkspaceContext { id, root, slug })
}

static MIGRATIONS_RAN: AtomicBool = AtomicBool::new(false);

/// Run version-gated migrations when the `.ccsm` identity file is from an older version.
/// Add new migration arms here as ccsm evolves.
/// Guarded by MIGRATIONS_RAN to avoid re-prompting when multiple code paths
/// call resolve_identity() in a single process.
fn run_identity_migrations(identity: &WorkspaceIdentity, root: &Path) -> Result<()> {
    if MIGRATIONS_RAN.swap(true, Ordering::Relaxed) {
        return Ok(());
    }

    let current = env!("CARGO_PKG_VERSION");
    if identity.version == current {
        return Ok(());
    }
    match identity.version.as_str() {
        "1" => {
            // Old hardcoded version from pre-0.15.0 dev — update to semver
            let content = format!("version = \"{current}\"\nid = \"{}\"\n", identity.id);
            std::fs::write(root.join(".ccsm"), &content)
                .context("rewriting .ccsm identity with current version")?;
            eprintln!("ccsm: migrated .ccsm identity from v{} to v{}", identity.version, current);
        }
        "0.15.0" => {
            // Strip stale worktree field from registry (field removed in 0.16.0)
            if let Err(e) = strip_stale_worktree(identity) {
                eprintln!("ccsm: warning: failed to strip worktree fields from registry: {e}");
            }
            let content = format!("version = \"{current}\"\nid = \"{}\"\n", identity.id);
            std::fs::write(root.join(".ccsm"), &content)
                .context("rewriting .ccsm identity with current version")?;
            eprintln!("ccsm: migrated .ccsm identity from v{} to v{} (stale worktree fields stripped)", identity.version, current);
        }
        _ => {
            // Unknown version — warn, don't block. The hard safety guard
            // (binary < project) is handled by check_version() in main.rs.
            // Binary > project is safe — the chain runner handles upgrades.
            eprintln!(
                "ccsm: .ccsm identity version \"{}\" doesn't match (expected {}). Run `ccsm migrate` to update.",
                identity.version, current,
            );
        }
    }
    Ok(())
}

/// Migrate legacy `<project>/.ccsm/` data to `~/.ccsm/<id>/`.
pub fn migrate_legacy_data(root: &Path, id: &str) -> Result<()> {
    ensure_data_dir(id)?;
    let src = root.join(".ccsm");

    // sessions.json
    let src_json = src.join("sessions.json");
    let dst_json = global_registry_path(id);
    if src_json.exists() {
        std::fs::copy(&src_json, &dst_json)
            .context("copying legacy sessions.json")?;
    }

    // sessions/ detail files
    let src_sessions = src.join("sessions");
    let dst_sessions = global_data_dir(id).join("sessions");
    if src_sessions.is_dir() {
        std::fs::create_dir_all(&dst_sessions)
            .context("creating global sessions dir")?;
        if let Ok(entries) = std::fs::read_dir(&src_sessions) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().is_some_and(|e| e == "md") {
                    let name = path.file_stem().and_then(|n| n.to_str()).unwrap_or("");
                    let dst = global_detail_path(id, name);
                    std::fs::copy(&path, &dst)
                        .with_context(|| format!("copying detail file {}", path.display()))?;
                }
            }
        }
    }

    // session-group/
    let src_group = src.join("session-group");
    let dst_group = global_data_dir(id).join("session-group");
    if src_group.is_dir() {
        std::fs::create_dir_all(&dst_group)
            .context("creating global session-group dir")?;
        if let Ok(entries) = std::fs::read_dir(&src_group) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().is_some_and(|e| e == "md") {
                    let name = path.file_stem().and_then(|n| n.to_str()).unwrap_or("");
                    let dst = global_group_path(id, name);
                    std::fs::copy(&path, &dst)
                        .with_context(|| format!("copying group file {}", path.display()))?;
                }
            }
        }
    }

    // session-detail-template.md
    let src_tpl = src.join("session-detail-template.md");
    if src_tpl.exists() {
        std::fs::copy(&src_tpl, global_template_path(id))
            .context("copying template file")?;
    }

    // config.toml
    let src_config = src.join("config.toml");
    if src_config.exists() {
        std::fs::copy(&src_config, global_config_path(id))
            .context("copying config.toml")?;
    }

    // Delete old .ccsm/ directory (non-critical cleanup)
    let _ = std::fs::remove_dir_all(&src);

    Ok(())
}

/// Strip stale `worktree` field from sessions.json by re-reading and re-saving.
/// In 0.16.0 the `worktree` field was removed from WorkspaceSession — serde
/// ignores it on deserialize and omits it on serialize, so a re-save is enough.
pub(crate) fn strip_stale_worktree(identity: &WorkspaceIdentity) -> Result<()> {
    let reg_path = global_registry_path(&identity.id);
    if !reg_path.exists() {
        return Ok(());
    }
    let contents = std::fs::read_to_string(&reg_path)?;
    let mut reg: WorkspaceRegistry = serde_json::from_str(&contents)
        .context("parsing sessions.json to strip stale worktree fields")?;
    reg.updated = now_iso();

    // Re-save — serde automatically omits the removed `worktree` field
    let new_contents = serde_json::to_string_pretty(&reg)?;
    std::fs::write(&reg_path, new_contents)
        .context("writing cleaned sessions.json")?;
    Ok(())
}

/// Ensure the global data directory structure exists for a workspace.
pub fn ensure_data_dir(id: &str) -> Result<()> {
    let dir = global_data_dir(id);
    std::fs::create_dir_all(dir.join("sessions"))
        .context("creating global sessions dir")?;
    std::fs::create_dir_all(dir.join("session-group"))
        .context("creating global session-group dir")?;
    std::fs::create_dir_all(dir.join("worktrees"))
        .context("creating global worktrees dir")?;
    Ok(())
}

/// Generate a random UUID v4 (no external crate dependency).
pub fn uuid_v4() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let pid = std::process::id() as u128;
    let r1 = ts.wrapping_mul(pid).wrapping_add(0xdeadbeef);
    let r2 = ts.wrapping_add(pid).wrapping_mul(0xcafebabe);
    let r3 = r1.wrapping_mul(r2).wrapping_add(0xdecafbad);
    let r4 = r2.wrapping_mul(0x9e3779b9).wrapping_add(ts);
    format!(
        "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
        (r1 & 0xffffffff) as u32,
        ((r2 >> 16) & 0xffff) as u16,
        ((r3 >> 48) & 0x0fff) as u16,
        (0x8000 | ((r4 >> 32) & 0x3fff)) as u16,
        (r3.wrapping_mul(r4) & 0xffffffffffff) as u64,
    )
}

/// Find the nearest git repository root from a starting path.
pub fn find_nearest_git_root(start: &Path) -> Option<PathBuf> {
    let mut current = Some(start);
    while let Some(dir) = current {
        if dir.join(".git").exists() || dir.join(".git").is_file() {
            return Some(dir.to_path_buf());
        }
        current = dir.parent();
    }
    None
}

// ── Group ─────────────────────────────────────────────────────────────

/// Ordering within a session group.
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(untagged)]
pub enum GroupRank {
    /// No ordering — tie-break alphabetically.
    #[default]
    Free,
    /// Numeric rank — lower = higher priority.
    Number(u32),
}

impl std::fmt::Display for GroupRank {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Free => write!(f, "free"),
            Self::Number(n) => write!(f, "{}", n),
        }
    }
}

/// A named group a session belongs to.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Group {
    pub name: String,
    #[serde(default)]
    pub rank: GroupRank,
}

// ── Workspace Detail ────────────────────────────────────────────────

/// Per-workspace session registry at `~/.ccsm/<id>/sessions.json`.
/// Rich detail with human/agent-curated goal, scope, status, and tags.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceRegistry {
    pub updated: String,
    pub sessions: Vec<WorkspaceSession>,
}

/// A retired Claude session — kept for history when `ccsm refresh` swaps
/// out a stale session for a fresh one within the same ccsm session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetiredSession {
    pub id: String,
    pub retired_at: String,
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceSession {
    pub session_id: String,
    pub name: String,
    pub goal: String,
    pub scope: String,
    #[serde(default = "default_status")]
    pub status: SessionStatus,
    #[serde(default)]
    pub pids: Vec<u32>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub started: String,
    #[serde(default)]
    pub completed: String,
    /// Which agent owns this session: "claude" or "pi".
    /// Used for cross-agent resume warnings.
    #[serde(default)]
    pub consumer: String,
    /// Group this session belongs to (optional).
    #[serde(default)]
    pub group: Option<Group>,
    /// Session names this session depends on (must complete first).
    #[serde(default)]
    pub depends_on: Vec<String>,
    /// Target git branch for this session (optional).
    /// Set with `ccsm new -b <branch>`; checked at resume via inject-scope.
    /// ccsm tracks this as metadata — it does not create or switch branches.
    #[serde(default)]
    pub branch: String,
    /// Whether this session should use a git worktree.
    /// Set with `ccsm new --worktree`; governed by config.worktrees policy.
    #[serde(default)]
    pub use_worktree: bool,
    /// Retired Claude session_ids — one ccsm session may chain through
    /// multiple Claude sessions as the context window fills up.
    #[serde(default)]
    pub retired_session_ids: Vec<RetiredSession>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum SessionStatus {
    Pending,
    InProgress,
    Completed,
    Blocked,
    Abandoned,
    /// Soft-deleted: hidden from normal view, recoverable.
    Trashed,
}

fn default_status() -> SessionStatus {
    SessionStatus::Pending
}

impl std::fmt::Display for SessionStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pending => write!(f, "pending"),
            Self::InProgress => write!(f, "in_progress"),
            Self::Completed => write!(f, "completed"),
            Self::Blocked => write!(f, "blocked"),
            Self::Abandoned => write!(f, "abandoned"),
            Self::Trashed => write!(f, "trashed"),
        }
    }
}

/// Allowed status transitions:
///
/// | from → to           | command        |
/// |---------------------|----------------|
/// | pending → in_progress | start       |
/// | in_progress → completed | complete  |
/// | in_progress → blocked  | block     |
/// | in_progress → abandoned | abandon  |
/// | blocked → abandoned    | abandon   |
/// | trashed → in_progress  | recover   |
/// | * → pending         | pending (reset) |
/// | * → trashed         | trash           |
/// | from == to          | (no-op)         |
///
/// All other transitions return `false`.
impl SessionStatus {
    pub fn transition_allowed(from: Self, to: Self) -> bool {
        if from == to {
            return true;
        }
        matches!(
            (from, to),
            (Self::Pending, Self::InProgress)
                | (Self::InProgress, Self::Completed)
                | (Self::InProgress, Self::Blocked)
                | (Self::InProgress, Self::Abandoned)
                | (Self::Blocked, Self::Abandoned)
                | (Self::Trashed, Self::InProgress)
                | (_, Self::Pending)
                | (_, Self::Trashed)
        )
    }
}

impl WorkspaceRegistry {
    /// Load from `~/.ccsm/<id>/sessions.json` where `<id>` is resolved from
    /// the `.ccsm` identity file in the project root (found by walking up from CWD).
    /// Returns an empty registry if no file exists yet (fresh project).
    pub fn load() -> Result<Self> {
        let data_dir = resolve_data_dir()?;
        Self::load_from(&data_dir)
    }

    /// Load from a specific data directory (used for migration and tests).
    pub fn load_from(data_dir: &Path) -> Result<Self> {
        let path = data_dir.join("sessions.json");
        if path.exists() {
            let contents = std::fs::read_to_string(&path)
                .with_context(|| format!("reading {}", path.display()))?;
            let mut reg: WorkspaceRegistry =
                serde_json::from_str(&contents)
                    .with_context(|| format!(
                        "parsing {} — JSON is malformed\n  → check for trailing/missing commas, unclosed brackets, or stray characters\n  → backup or delete the file to start fresh",
                        path.display(),
                    ))?;
            reg.updated = now_iso();
            return Ok(reg);
        }
        Ok(Self {
            updated: now_iso(),
            sessions: Vec::new(),
        })
    }

    /// Load with an exclusive lock held for the lifetime of the returned `LockFile`.
    /// Use this for every read-modify-write cycle to prevent races between
    /// chained `ccsm` mutation commands.
    pub fn load_locked() -> Result<(Self, LockFile)> {
        let data_dir = resolve_data_dir()?;
        let lock = LockFile::acquire_for_data_dir(&data_dir)?;
        let reg = Self::load_from(&data_dir)?;
        Ok((reg, lock))
    }

    /// Load from a specific data directory with an exclusive lock (for tests).
    pub fn load_locked_from(data_dir: &Path) -> Result<(Self, LockFile)> {
        let lock = LockFile::acquire_for_data_dir(data_dir)?;
        let reg = Self::load_from(data_dir)?;
        Ok((reg, lock))
    }

    /// Save to `~/.ccsm/<id>/sessions.json`.
    pub fn save(&self) -> Result<()> {
        let data_dir = resolve_data_dir()?;
        self.save_to(&data_dir)
    }

    /// Save to a specific data directory (used for migration and tests).
    pub fn save_to(&self, data_dir: &Path) -> Result<()> {
        let path = data_dir.join("sessions.json");
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).ok();
        }
        let json = serde_json::to_string_pretty(self)?;
        std::fs::write(&path, json).context("writing workspace registry")?;
        Ok(())
    }

    /// Soft-delete: mark a session as Trashed.  No files are touched.
    /// Matches by session_id; falls back to name for seed entries with empty id.
    pub fn trash(&mut self, session_id: &str, name: &str) -> bool {
        if let Some(entry) = self
            .sessions
            .iter_mut()
            .find(|e| e.session_id == session_id || (session_id.is_empty() && e.name == name))
        {
            entry.status = SessionStatus::Trashed;
            self.updated = now_iso();
            true
        } else {
            false
        }
    }

    /// Un-trash: move a trashed session back to InProgress.
    pub fn recover(&mut self, session_id: &str, name: &str) -> bool {
        if let Some(entry) = self
            .sessions
            .iter_mut()
            .find(|e| e.session_id == session_id || (session_id.is_empty() && e.name == name))
        {
            entry.status = SessionStatus::InProgress;
            self.updated = now_iso();
            true
        } else {
            false
        }
    }

    /// Permanently delete a single session: transcript JSONL, any lingering
    /// session files, and the registry entry.
    /// Matches by session_id; falls back to name for seed entries.
    pub fn clean(
        &mut self,
        session_id: &str,
        name: &str,
        home: &std::path::Path,
        workspace: &std::path::Path,
        consumer: crate::consumer::Consumer,
    ) {
        // Only delete files if we have a real session_id
        if !session_id.is_empty() {
            if !consumer.is_opencode() {
                let proj_dir = consumer.projects_dir_for(home, workspace);
                let slug = consumer.project_slug(workspace);
                let transcript = if consumer.is_pi() {
                    consumer.find_session_file(home, &slug, session_id)
                        .unwrap_or_else(|| proj_dir.join(format!("_{session_id}.jsonl")))
                } else {
                    proj_dir.join(format!("{session_id}.jsonl"))
                };
                let _ = std::fs::remove_file(&transcript);
            }

            // Remove any live session files with this session_id
            if let Ok(entries) = std::fs::read_dir(consumer.sessions_dir(home)) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.extension().is_none_or(|e| e != "json") {
                        continue;
                    }
                    if let Ok(contents) = std::fs::read_to_string(&path)
                        && contents.contains(session_id) {
                            let _ = std::fs::remove_file(&path);
                        }
                }
            }
        }

        // Delete the detail file from global data dir
        if let Ok(ctx) = resolve_identity() {
            let detail = global_detail_path(&ctx.id, name);
            let _ = std::fs::remove_file(&detail);
        }

        self.sessions.retain(|e| {
            !(e.session_id == session_id
                || (session_id.is_empty() && e.name == name && e.session_id.is_empty()))
        });
        self.updated = now_iso();
    }

    /// Archive: delete transcript + session files but KEEP the registry entry.
    /// Clears `session_id` so the entry remains as a permanent work log.
    /// Returns total bytes freed.
    pub fn archive(
        &mut self,
        session_id: &str,
        name: &str,
        home: &std::path::Path,
        workspace: &std::path::Path,
        consumer: crate::consumer::Consumer,
    ) -> u64 {
        let mut freed: u64 = 0;
        if !session_id.is_empty() {
            if !consumer.is_opencode() {
                let slug = consumer.project_slug(workspace);
                let transcript = consumer.find_session_file(home, &slug, session_id)
                    .unwrap_or_else(|| {
                        consumer.projects_dir(home, &slug).join(format!("{session_id}.jsonl"))
                    });
                if transcript.exists() {
                    if let Ok(meta) = std::fs::metadata(&transcript) {
                        freed += meta.len();
                    }
                    let _ = std::fs::remove_file(&transcript);
                }
            }

            // Remove any live session files with this session_id
            if let Ok(entries) = std::fs::read_dir(consumer.sessions_dir(home)) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.extension().is_none_or(|e| e != "json") {
                        continue;
                    }
                    if let Ok(contents) = std::fs::read_to_string(&path)
                        && contents.contains(session_id) {
                            if let Ok(meta) = std::fs::metadata(&path) {
                                freed += meta.len();
                            }
                            let _ = std::fs::remove_file(&path);
                        }
                }
            }
        }

        // Clear session_id — keep the entry as a work log
        if let Some(entry) = self
            .sessions
            .iter_mut()
            .find(|e| e.session_id == session_id || (session_id.is_empty() && e.name == name))
        {
            entry.session_id.clear();
            entry.pids.clear();
        }
        self.updated = now_iso();
        freed
    }

    /// Permanently clean every trashed session at once.
    pub fn clean_all_trashed(&mut self, home: &std::path::Path, workspace: &std::path::Path, consumer: crate::consumer::Consumer) {
        let trashed: Vec<(String, String)> = self
            .sessions
            .iter()
            .filter(|e| e.status == SessionStatus::Trashed)
            .map(|e| (e.session_id.clone(), e.name.clone()))
            .collect();
        for (sid, name) in &trashed {
            self.clean(sid, name, home, workspace, consumer);
        }
        self.updated = now_iso();
    }

    /// Seed with initial entries if empty. Safe to call on every startup.
    pub fn seed(&mut self, entries: Vec<WorkspaceSession>) {
        if self.sessions.is_empty() {
            self.sessions = entries;
        }
    }

    /// Default seed entries for ccsm's own workspace.
    /// Each project should define its own seed based on its build plan.
    pub fn default_seed() -> Vec<WorkspaceSession> {
        vec![
            WorkspaceSession {
                session_id: String::new(),
                name: "phase-1-pty-embedding".into(),
                goal: "Embed cds in a PTY with fixed-grid ANSI rendering".into(),
                scope: "Phase 1: spawn cds via portable-pty, render ANSI output as styled ratatui Text using tmux-style fixed-grid approach. Input passthrough (typing, arrows, Ctrl+C, Tab, F-keys). Quit on Ctrl+Q.".into(),
                status: SessionStatus::Completed,
                pids: vec![],
                tags: vec!["pty".into(), "ratatui".into(), "vt100".into(), "phase-1".into()],
                started: String::new(),
                completed: String::new(),
                group: None,
                depends_on: vec![],
                branch: String::new(),
                use_worktree: false,
                retired_session_ids: vec![],
                consumer: String::new(),
            },
            WorkspaceSession {
                session_id: String::new(),
                name: "phase-2-sidebar".into(),
                goal: "Add sidebar with session list and focus switching".into(),
                scope: "Phase 2: read ~/.claude/sessions/*.json, render session list with status indicators, 30/70 layout split, Tab focus switching, arrow/vim key navigation, workspace-aware filtering, session detail overlay.".into(),
                status: SessionStatus::Completed,
                pids: vec![],
                tags: vec!["sidebar".into(), "ratatui".into(), "sessions".into(), "phase-2".into()],
                started: String::new(),
                completed: String::new(),
                group: None,
                depends_on: vec![],
                branch: String::new(),
                use_worktree: false,
                retired_session_ids: vec![],
                consumer: String::new(),
            },
            WorkspaceSession {
                session_id: String::new(),
                name: "phase-3-session-replay".into(),
                goal: "View historical session transcripts in the PTY panel".into(),
                scope: "Enter on session loads JSONL transcript, renders user/assistant messages and tool calls with scroll support (↑↓/PgUp/PgDn/Home), Esc/Tab returns to live cds. ViewMode enum switches between Live and Transcript.".into(),
                status: SessionStatus::Completed,
                pids: vec![],
                tags: vec!["transcript".into(), "replay".into(), "phase-3".into()],
                started: String::new(),
                completed: String::new(),
                group: None,
                depends_on: vec![],
                branch: String::new(),
                use_worktree: false,
                retired_session_ids: vec![],
                consumer: String::new(),
            },
            WorkspaceSession {
                session_id: String::new(),
                name: "session-registry".into(),
                goal: "Global session registry at ~/.ccsm/ with per-project isolation".into(),
                scope: "Global data at ~/.ccsm/<id>/ with sessions.json, detail files, groups, worktrees, and config. Per-project .ccsm identity file for UUID-based workspace resolution. Survives ephemeral agent cleanup.".into(),
                status: SessionStatus::InProgress,
                pids: vec![],
                tags: vec!["registry".into(), "sessions".into(), "team".into()],
                started: String::new(),
                completed: String::new(),
                group: None,
                depends_on: vec![],
                branch: String::new(),
                use_worktree: false,
                retired_session_ids: vec![],
                consumer: String::new(),
            },
        ]
    }

    /// Create an empty registry.
    pub fn empty() -> Self {
        Self {
            updated: String::new(),
            sessions: Vec::new(),
        }
    }
}

// ── File Locking ─────────────────────────────────────────────────────

/// Advisory exclusive lock on `~/.ccsm/<id>/sessions.json.lock`.
///
/// Acquired before reading the registry and held until dropped —
/// this prevents the read-modify-write race when multiple `ccsm`
/// mutation commands are chained with `&&` in a single shell call.
///
/// The OS releases the lock automatically if the process exits,
/// so a crash won't leave the registry permanently locked.
pub struct LockFile {
    _file: std::fs::File,
}

impl LockFile {
    /// Acquire a lock within a specific data directory (tests/migration).
    pub fn acquire_for_data_dir(data_dir: &Path) -> Result<Self> {
        let lock_path = data_dir.join("sessions.json.lock");
        if let Some(parent) = lock_path.parent() {
            std::fs::create_dir_all(parent).ok();
        }
        let file = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
            .context("opening lock file")?;
        file.lock_exclusive()
            .context("acquiring exclusive lock on sessions.json")?;
        Ok(Self { _file: file })
    }
}

// ── Helpers ─────────────────────────────────────────────────────────

pub fn now_iso() -> String {
    // Simple ISO-like timestamp without chrono dependency
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let secs = ts % 86400;
    let days = ts / 86400;
    let h = secs / 3600;
    let m = (secs % 3600) / 60;
    let s = secs % 60;
    format!("day{days}T{h:02}:{m:02}:{s:02}Z")
}

pub(crate) fn format_ts(ms: u64) -> String {
    let secs = ms / 1000;
    let day_secs = secs % 86400;
    let days = secs / 86400;
    let h = day_secs / 3600;
    let m = (day_secs % 3600) / 60;
    format!("day{days}T{h:02}:{m:02}Z")
}

/// Parse a `day{days}T{time}Z` timestamp and return the age in days
/// (0 if unparseable or empty).
pub fn session_age_days(ts: &str) -> u64 {
    if ts.is_empty() {
        return 0;
    }
    let now_days = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
        / 86400;

    // Parse "day<number>..."
    let stripped = ts.strip_prefix("day").and_then(|s| {
        s.split('T').next().and_then(|n| n.parse::<u64>().ok())
    });

    match stripped {
        Some(days) => now_days.saturating_sub(days),
        None => 0,
    }
}

/// Derive a project slug from a workspace identity UUID.
/// Using UUID guarantees the same slug on every machine, unlike
/// the previous path-based derivation which tied slug to filesystem layout.
pub(crate) fn project_slug(id: &str) -> String {
    format!("ccsm-{id}")
}

/// Simple Levenshtein distance — used to suggest corrections for typos.
pub(crate) fn edit_distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut prev = (0..=b.len()).collect::<Vec<_>>();
    let mut curr = vec![0; b.len() + 1];
    for i in 1..=a.len() {
        curr[0] = i;
        for j in 1..=b.len() {
            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
            curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
        }
        std::mem::swap(&mut prev, &mut curr);
    }
    prev[b.len()]
}

pub(crate) fn note_timestamp() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let secs_per_day: u64 = 86400;
    let days = secs / secs_per_day;
    let day_secs = secs % secs_per_day;
    let hours = day_secs / 3600;
    let mins = (day_secs % 3600) / 60;

    let (y, m, d) = days_to_date(days);
    format!("{:04}-{:02}-{:02} {:02}:{:02}Z", y, m, d, hours, mins)
}

/// Convert days since 1970-01-01 to (year, month, day).
fn days_to_date(mut days: u64) -> (u32, u32, u32) {
    let mut year: u32 = 1970;
    loop {
        let diy: u64 = if is_leap(year) { 366 } else { 365 };
        if days < diy { break; }
        days -= diy;
        year += 1;
    }
    let mdays: [u64; 12] = if is_leap(year) {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };
    let mut month: u32 = 1;
    for &md in &mdays {
        if days < md { break; }
        days -= md;
        month += 1;
    }
    (year, month, (days + 1) as u32)
}

fn is_leap(y: u32) -> bool {
    y.is_multiple_of(4) && !y.is_multiple_of(100) || y.is_multiple_of(400)
}

/// Insert `new_entry` into the Progress Log section of `contents`.
/// Prepends (newest at top) — inserts right after the `## Progress Log`
/// header, past any blank lines or HTML comments.
pub(crate) fn insert_note(contents: &str, new_entry: &str) -> String {
    let lines: Vec<&str> = contents.lines().collect();

    if let Some(hdr) = lines.iter().position(|l| l.trim() == "## Progress Log") {
        let mut ins = hdr + 1;
        let mut comment = false;
        while ins < lines.len() {
            let t = lines[ins].trim();
            if t.is_empty() {
                ins += 1;
            } else if t.starts_with("<!--") {
                comment = true;
                ins += 1;
            } else if comment && (t == "-->" || t.ends_with("-->")) {
                comment = false;
                ins += 1;
            } else if comment {
                ins += 1;
            } else {
                break;
            }
        }

        let mut out = String::with_capacity(contents.len() + new_entry.len() + 2);
        for line in &lines[..ins] {
            out.push_str(line);
            out.push('\n');
        }
        out.push_str(new_entry);
        if ins < lines.len() { out.push('\n'); }
        for line in &lines[ins..] {
            out.push_str(line);
            out.push('\n');
        }
        out
    } else {
        let mut out = contents.to_string();
        if !out.ends_with('\n') { out.push('\n'); }
        out.push('\n');
        out.push_str("## Progress Log\n\n");
        out.push_str(new_entry);
        out.push('\n');
        out
    }
}

/// Replace the body of a `## SectionName` in a markdown string.
pub(crate) fn replace_detail_section(md: &str, header: &str, new_body: &str) -> String {
    let lines: Vec<&str> = md.lines().collect();

    let hdr_idx = lines.iter().position(|l| {
        let t = l.trim();
        t == header || t.starts_with(&format!("{} ", header))
    });

    match hdr_idx {
        Some(hdr) => {
            let end = lines[hdr + 1..]
                .iter()
                .position(|l| l.starts_with("## "))
                .map(|p| hdr + 1 + p)
                .unwrap_or(lines.len());

            let mut out = String::new();
            for line in &lines[..=hdr] {
                out.push_str(line);
                out.push('\n');
            }
            out.push('\n');
            out.push_str(new_body);
            if end < lines.len() {
                out.push('\n');
            }
            for line in &lines[end..] {
                out.push_str(line);
                out.push('\n');
            }
            out
        }
        None => {
            let mut out = md.to_string();
            if !out.ends_with('\n') {
                out.push('\n');
            }
            out.push_str(&format!("\n{}\n\n{}\n", header, new_body));
            out
        }
    }
}

/// Resolve the global data directory path from the current environment.
/// Convenience: resolves identity via `resolve_identity()`.
pub fn resolve_data_dir() -> Result<PathBuf> {
    let ctx = resolve_identity()?;
    Ok(global_data_dir(&ctx.id))
}

/// Sync the `> **status** | started ... | completed ...` line in the detail file
/// for a session to match the registry state. No-op if detail file doesn't exist.
/// The detail file lives in `~/.ccsm/<id>/sessions/<name>.md`.
pub fn sync_status_line(name: &str) {
    let detail_path = match resolve_data_dir() {
        Ok(dir) => dir.join("sessions").join(format!("{name}.md")),
        Err(_) => return,
    };

    if !detail_path.exists() {
        return;
    }

    let reg = match WorkspaceRegistry::load() {
        Ok(r) => r,
        Err(_) => return,
    };
    let Some(session) = reg.sessions.iter().find(|s| s.name == name) else {
        return;
    };

    let started = if session.started.is_empty() { "" } else { &session.started };
    let completed = if session.completed.is_empty() { "" } else { &session.completed };
    let new_line = format!(
        "> **{}** | started {} | completed {}",
        session.status, started, completed,
    );

    let Ok(contents) = std::fs::read_to_string(&detail_path) else { return };
    let mut updated = String::new();
    let mut found = false;
    for line in contents.lines() {
        if line.trim_start().starts_with("> **") && line.contains("| started") {
            updated.push_str(&new_line);
            updated.push('\n');
            found = true;
        } else {
            updated.push_str(line);
            updated.push('\n');
        }
    }

    if found {
        let _ = std::fs::write(&detail_path, updated);
    }
}

pub(crate) fn is_kebab_case(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

pub(crate) fn harvest_from_pid(home: &std::path::Path, pid: u32) -> anyhow::Result<String> {
    let session_file = home.join(".claude").join("sessions").join(format!("{pid}.json"));
    if !session_file.exists() {
        anyhow::bail!(
            "no session file at {}\n  Is PID {} running?",
            session_file.display(), pid
        );
    }
    let contents = std::fs::read_to_string(&session_file)
        .context("reading session file")?;
    let s: crate::session::Session = serde_json::from_str(&contents)
        .context("parsing session file")?;
    if s.session_id.is_empty() {
        anyhow::bail!("session file for PID {} has no sessionId yet", pid);
    }
    Ok(s.session_id)
}

pub(crate) fn validate_session_id(sid: &str) -> anyhow::Result<()> {
    // Accept OpenCode ses_* format (e.g. ses_abc123...)
    if sid.starts_with("ses_") && sid.len() > 4
        && sid[4..].chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Ok(());
    }
    // Accept standard 8-4-4-4-12 UUID
    let parts: Vec<&str> = sid.split('-').collect();
    if parts.len() == 5
        && parts[0].len() == 8
        && parts[1].len() == 4
        && parts[2].len() == 4
        && parts[3].len() == 4
        && parts[4].len() == 12
        && sid.chars().all(|c| c.is_ascii_hexdigit() || c == '-')
    {
        Ok(())
    } else {
        anyhow::bail!(
            "'{}' does not look like a session UUID (e.g. f493397b-...-4d5f15da0311).\n\
             If you renamed the session in the TUI, the name changed but the UUID didn't.\n\
             Use --pid <pid> instead: ccsm attach {} --pid <pid>",
            sid, sid
        );
    }
}

pub(crate) fn parse_sections(md: &str) -> Vec<(String, String)> {
    let mut sections: Vec<(String, String)> = Vec::new();
    let mut current_header: Option<String> = None;
    let mut current_body = String::new();

    for line in md.lines() {
        if line.starts_with("## ") {
            if let Some(h) = current_header.take() {
                sections.push((h, std::mem::take(&mut current_body)));
            }
            current_header = Some(line.strip_prefix("## ").unwrap().trim().to_string());
        } else if current_header.is_some() {
            if !current_body.is_empty() {
                current_body.push('\n');
            }
            current_body.push_str(line);
        }
    }
    if let Some(h) = current_header
        && (!current_body.trim().is_empty() || sections.iter().any(|(_, b)| !b.trim().is_empty())) {
            sections.push((h, current_body));
        }
    sections
}

// ── Tests ───────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
        use std::path::PathBuf;
        use std::sync::Arc;

    /// Create a temp workspace with `.claude/sessions.json` pre-populated.
    /// Create a temp directory with a data directory structure for testing.
    /// Returns `(tempdir, data_dir)` where `data_dir` is `tempdir/data/`.
    fn temp_workspace() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let data_dir = dir.path().join("data");
        std::fs::create_dir_all(&data_dir).unwrap();
        // Start with an empty but valid registry
        let reg = WorkspaceRegistry {
            updated: "test".into(),
            sessions: vec![],
        };
        let reg_path = data_dir.join("sessions.json");
        std::fs::write(&reg_path, serde_json::to_string_pretty(&reg).unwrap()).unwrap();
        (dir, data_dir)
    }

    // ── LockFile tests ─────────────────────────────────────────────

    #[test]
    fn lock_acquire_creates_lockfile() {
        let (_dir, data_dir) = temp_workspace();
        let lock_path = data_dir.join("sessions.json.lock");
        assert!(!lock_path.exists());

        let _lock = LockFile::acquire_for_data_dir(&data_dir).unwrap();
        assert!(lock_path.exists());
    }

    #[test]
    fn lock_drop_releases() {
        let (_dir, data_dir) = temp_workspace();

        // Acquire and drop
        let lock = LockFile::acquire_for_data_dir(&data_dir).unwrap();
        drop(lock);

        // Should be able to acquire again immediately (lock released)
        let _lock2 = LockFile::acquire_for_data_dir(&data_dir).unwrap();
    }

    #[test]
    fn lock_exclusive_blocks_same_process() {
        let (_dir, data_dir) = temp_workspace();

        // Acquire exclusive lock on one fd
        let _lock1 = LockFile::acquire_for_data_dir(&data_dir).unwrap();

        // Try to acquire on a different fd — should fail with try_lock
        let lock_path = data_dir.join("sessions.json.lock");
        let file2 = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
            .unwrap();

        // try_lock_exclusive should fail because lock1 still holds it
        assert!(fs2::FileExt::try_lock_exclusive(&file2).is_err());
    }

    #[test]
    fn lock_released_after_drop_allows_new_lock() {
        let (_dir, data_dir) = temp_workspace();

        let lock = LockFile::acquire_for_data_dir(&data_dir).unwrap();
        drop(lock);

        // Now try_lock should succeed
        let lock_path = data_dir.join("sessions.json.lock");
        let file = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
            .unwrap();
        assert!(fs2::FileExt::try_lock_exclusive(&file).is_ok());
    }

    // ── load_locked tests ──────────────────────────────────────────

    #[test]
    fn load_locked_loads_registry() {
        let (_dir, data_dir) = temp_workspace();
        // Write a known entry
        let reg = WorkspaceRegistry {
            updated: "day0T00:00:00Z".into(),
            sessions: vec![WorkspaceSession {
                session_id: "abc-123".into(),
                name: "test-session".into(),
                goal: "test goal".into(),
                scope: String::new(),
                status: SessionStatus::InProgress,
                pids: vec![42],
                tags: vec!["test".into()],
                started: "day0T00:00:00Z".into(),
                completed: String::new(),
                group: None,
                depends_on: vec![],
                branch: String::new(),
                use_worktree: false,
                retired_session_ids: vec![],
                consumer: String::new(),
            }],
        };
        std::fs::write(&data_dir.join("sessions.json"), serde_json::to_string_pretty(&reg).unwrap()).unwrap();

        let (loaded, _lock) = WorkspaceRegistry::load_locked_from(&data_dir).unwrap();
        assert_eq!(loaded.sessions.len(), 1);
        assert_eq!(loaded.sessions[0].name, "test-session");
        assert_eq!(loaded.sessions[0].goal, "test goal");
        assert_eq!(loaded.sessions[0].session_id, "abc-123");
    }

    #[test]
    fn load_locked_holds_lock_during_mutation() {
        let (_dir, data_dir) = temp_workspace();

        let (mut reg, _lock) = WorkspaceRegistry::load_locked_from(&data_dir).unwrap();

        // While lock is held, try_lock should fail on another fd
        let lock_path = data_dir.join("sessions.json.lock");
        let other_file = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
            .unwrap();
        assert!(fs2::FileExt::try_lock_exclusive(&other_file).is_err());

        // Mutate and save while holding the lock
        reg.sessions.push(WorkspaceSession {
            session_id: String::new(),
            name: "locked-mutation".into(),
            goal: "created under lock".into(),
            scope: String::new(),
            status: SessionStatus::Pending,
            pids: vec![],
            tags: vec![],
            started: String::new(),
            completed: String::new(),
            group: None,
            depends_on: vec![],
            branch: String::new(),
            use_worktree: false,
            retired_session_ids: vec![],
            consumer: String::new(),
        });
        reg.save_to(&data_dir).unwrap();

        // Drop the lock
        drop(_lock);
        drop(reg);

        // Now another lock can be acquired
        let (_reg2, _lock2) = WorkspaceRegistry::load_locked_from(&data_dir).unwrap();
        assert_eq!(_reg2.sessions.len(), 1);
        assert_eq!(_reg2.sessions[0].name, "locked-mutation");
    }

    // ── Concurrent mutation tests ──────────────────────────────────

    #[test]
    fn concurrent_mutations_preserve_all_entries() {
        let (_dir, data_dir) = temp_workspace();
        let num_threads = 8;
        let data_dir = Arc::new(data_dir);

        let mut handles = vec![];
        for i in 0..num_threads {
            let d = Arc::clone(&data_dir);
            handles.push(std::thread::spawn(move || {
                let name = format!("thread-{}", i);
                let (mut reg, _lock) = WorkspaceRegistry::load_locked_from(&d).unwrap();
                reg.sessions.push(WorkspaceSession {
                    session_id: String::new(),
                    name,
                    goal: format!("entry from thread {}", i),
                    scope: String::new(),
                    status: SessionStatus::Pending,
                    pids: vec![],
                    tags: vec![format!("t{}", i)],
                    started: String::new(),
                    completed: String::new(),
                    group: None,
                    depends_on: vec![],
                    branch: String::new(),
                    use_worktree: false,
                    retired_session_ids: vec![],
                    consumer: String::new(),
                });
                reg.save_to(&d).unwrap();
                // _lock dropped here
            }));
        }

        for h in handles {
            h.join().unwrap();
        }

        // All entries should be present — none lost to race
        let reg = WorkspaceRegistry::load_from(&data_dir).unwrap();
        assert_eq!(reg.sessions.len(), num_threads,
            "expected {} entries, got {} — mutations were lost to a race",
            num_threads, reg.sessions.len());

        let mut names: Vec<_> = reg.sessions.iter().map(|s| s.name.clone()).collect();
        names.sort();
        for i in 0..num_threads {
            assert_eq!(names[i], format!("thread-{}", i));
        }
    }

    #[test]
    fn concurrent_mutations_without_lock_can_lose_state() {
        // This test demonstrates WHY the lock is necessary.
        // Without locks, concurrent read-modify-write can corrupt the file
        // (empty reads, parse failures) or silently lose entries.
        let (_dir, data_dir) = temp_workspace();
        let num_threads = 8;
        let data_dir = Arc::new(data_dir);

        let mut handles = vec![];
        for i in 0..num_threads {
            let d = Arc::clone(&data_dir);
            handles.push(std::thread::spawn(move || {
                let name = format!("unlocked-{}", i);
                let mut reg = WorkspaceRegistry::load_from(&d)
                    .unwrap_or_else(|_| WorkspaceRegistry::empty());
                reg.sessions.push(WorkspaceSession {
                    session_id: String::new(),
                    name,
                    goal: "unlocked entry".into(),
                    scope: String::new(),
                    status: SessionStatus::Pending,
                    pids: vec![],
                    tags: vec![],
                    started: String::new(),
                    completed: String::new(),
                    group: None,
                    depends_on: vec![],
                    branch: String::new(),
                    use_worktree: false,
                    retired_session_ids: vec![],
                    consumer: String::new(),
                });
                let _ = reg.save_to(&d);
            }));
        }

        for h in handles {
            h.join().unwrap();
        }

        // Without locks, the file is often corrupted or entries are lost.
        // We just verify the locked version works correctly — this test
        // exists to document the race condition that load_locked prevents.
        let reg = WorkspaceRegistry::load_from(&data_dir).unwrap_or_else(|_| {
            // File was corrupted by concurrent writes — exactly what the lock prevents
            WorkspaceRegistry::empty()
        });
        eprintln!(
            "unlocked concurrent test: {}/{} entries survived ({} = expected with locking)",
            reg.sessions.len(),
            num_threads,
            num_threads
        );
        // No assertion on count — the file may be corrupt, partially written,
        // or missing entries. This is expected without locking.
    }

    // ── Portability tests ──────────────────────────────────────────────

    #[test]
    fn project_slug_uses_uuid() {
        let slug = project_slug("abc-123-def");
        assert_eq!(slug, "ccsm-abc-123-def");
    }

    #[test]
    fn project_slug_is_stable() {
        let id = "some-uuid-that-never-changes";
        assert_eq!(project_slug(id), project_slug(id));
    }

    #[test]
    fn global_data_dir_defaults_to_home_ccsm() {
        let prev = std::env::var("CCSM_DATA_DIR").ok();
        unsafe { std::env::remove_var("CCSM_DATA_DIR"); }
        let dir = global_data_dir("test-id");
        assert!(dir.to_string_lossy().contains("/.ccsm/test-id"));
        if let Some(v) = prev { unsafe { std::env::set_var("CCSM_DATA_DIR", v); } }
    }

    #[test]
    fn global_data_dir_respects_env_override() {
        let prev = std::env::var("CCSM_DATA_DIR").ok();
        unsafe { std::env::set_var("CCSM_DATA_DIR", "/tmp/ccsm-data"); }
        let dir = global_data_dir("test-id");
        assert_eq!(dir, std::path::PathBuf::from("/tmp/ccsm-data/test-id"));
        if let Some(v) = prev { unsafe { std::env::set_var("CCSM_DATA_DIR", v); } }
            else { unsafe { std::env::remove_var("CCSM_DATA_DIR"); } }
    }

    #[test]
    fn strip_stale_worktree_removes_field() {
        let dir = tempfile::tempdir().unwrap();
        let data_dir = dir.path().join("data");
        std::fs::create_dir_all(&data_dir).unwrap();

        // Write a sessions.json WITH a worktree field (simulating 0.15.0 format)
        let old_json = serde_json::json!({
            "updated": "test",
            "sessions": [{
                "session_id": "",
                "name": "old-session",
                "goal": "test",
                "scope": "",
                "status": "in_progress",
                "pids": [],
                "tags": [],
                "started": "",
                "completed": "",
                "group": null,
                "depends_on": [],
                "branch": "",
                "use_worktree": true,
                "worktree": "/home/user/proj/.claude/worktrees/old-session",
                "retired_session_ids": [],
                "consumer": ""
            }]
        });
        // Set up CCSM_DATA_DIR so global_registry_path resolves to our temp dir
        let prev = std::env::var("CCSM_DATA_DIR").ok();
        unsafe { std::env::set_var("CCSM_DATA_DIR", data_dir.to_string_lossy().as_ref()); }

        let identity = WorkspaceIdentity {
            version: "0.16.0".into(),
            id: "test-id".into(),
        };

        // Write registry with worktree field
        let reg_path = global_registry_path(&identity.id);
        if let Some(parent) = reg_path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(&reg_path, serde_json::to_string_pretty(&old_json).unwrap()).unwrap();

        // Verify worktree FIELD exists before stripping
        let raw = std::fs::read_to_string(&reg_path).unwrap();
        assert!(raw.contains(r#""worktree":"#), "worktree field should exist before");

        strip_stale_worktree(&identity).unwrap();

        // Verify worktree FIELD is gone after stripping (use_worktree still exists)
        let cleaned = std::fs::read_to_string(&reg_path).unwrap();
        assert!(!cleaned.contains(r#""worktree":"#), "worktree field should be stripped");

        if let Some(v) = prev { unsafe { std::env::set_var("CCSM_DATA_DIR", v); } }
            else { unsafe { std::env::remove_var("CCSM_DATA_DIR"); } }
    }

    #[test]
    fn worktree_path_for_is_deterministic() {
        let ws = std::path::Path::new("/home/user/project");
        let name = "my-session";
        let p = crate::commands::worktree::worktree_path_for(ws, name);
        assert_eq!(
            p,
            std::path::PathBuf::from("/home/user/project/.claude/worktrees/my-session")
        );
    }
}