heddle-cli 0.4.0

An AI-native version control system
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
// SPDX-License-Identifier: Apache-2.0
//! Harness integration install and relay commands.

use std::{
    collections::BTreeSet,
    env, fs,
    io::{self, Read},
    path::{Path, PathBuf},
};

use anyhow::{Context, Result, anyhow};
use objects::fs_atomic::write_file_atomic;
use repo::Repository;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::advice::RecoveryAdvice;
use crate::{
    cli::{
        Cli, IntegrationCommands, IntegrationInstallArgs, IntegrationRelayArgs,
        IntegrationTargetArgs, should_output_json,
    },
    harness,
};

const MANIFEST_FILE: &str = "integrations.toml";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
enum IntegrationScope {
    Repo,
    User,
}

impl IntegrationScope {
    fn parse(value: &str) -> Result<Self> {
        match value {
            "repo" => Ok(Self::Repo),
            "user" => Ok(Self::User),
            other => Err(anyhow!(RecoveryAdvice::invalid_usage(
                "integration_scope_invalid",
                format!("invalid integration scope: {other}"),
                "Use `--scope repo` or `--scope user`.",
                "heddle integration install --scope repo",
            ))),
        }
    }
}

/// Whether installed hook commands invoke `heddle` via PATH (relative) or via
/// the absolute path of the heddle binary that performed the install.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
enum PathMode {
    #[default]
    Relative,
    Absolute,
}

/// Resolved heddle invocation token to splice into the generated hook command.
/// Either the literal string `heddle` (PATH-relative) or a shell-escaped absolute path.
struct HeddleInvocation(String);

impl HeddleInvocation {
    fn resolve(mode: PathMode) -> Result<Self> {
        Ok(match mode {
            PathMode::Relative => HeddleInvocation("heddle".to_string()),
            PathMode::Absolute => {
                let exe = std::env::current_exe()
                    .context("resolving current executable for integration install")?;
                HeddleInvocation(shell_escape(&exe))
            }
        })
    }

    /// Raw form (unescaped) for embedding in non-shell contexts (e.g. JS strings).
    fn raw(mode: PathMode) -> Result<String> {
        Ok(match mode {
            PathMode::Relative => "heddle".to_string(),
            PathMode::Absolute => std::env::current_exe()
                .context("resolving current executable for integration install")?
                .display()
                .to_string(),
        })
    }
}

impl std::fmt::Display for HeddleInvocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct InstalledIntegration {
    harness: String,
    scope: IntegrationScope,
    method: String,
    paths: Vec<String>,
    status: String,
    heddle_version: String,
    /// Whether `paths` reference a PATH-relative `heddle` invocation or an
    /// absolute path baked in at install time. Defaults to `relative` on read
    /// for backward compat with manifests written before this field existed.
    #[serde(default)]
    path_mode: PathMode,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct IntegrationManifest {
    #[serde(default)]
    integrations: Vec<InstalledIntegration>,
}

#[derive(Debug, Serialize)]
struct IntegrationStatus {
    harness: String,
    scope: String,
    method: String,
    status: String,
    healthy: bool,
    paths: Vec<String>,
    capabilities: Vec<String>,
    capability_paths: Vec<String>,
    path_mode: String,
}

pub fn cmd_integration(cli: &Cli, command: IntegrationCommands) -> Result<()> {
    let repo = cli.open_repo()?;
    match command {
        IntegrationCommands::List => list_integrations(cli, &repo),
        IntegrationCommands::Install(args) => install_integrations(cli, &repo, args),
        IntegrationCommands::Doctor => doctor_integrations(cli, &repo),
        IntegrationCommands::Uninstall(args) => uninstall_integrations(cli, &repo, args),
        IntegrationCommands::Upgrade(args) => upgrade_integrations(cli, &repo, args),
        IntegrationCommands::Relay(args) => relay_integration(&repo, args),
    }
}

pub fn maybe_prompt_init_install(
    cli: &Cli,
    repo: &Repository,
    args: &crate::cli::InitArgs,
) -> Result<()> {
    let json = should_output_json(cli, Some(repo.config()));
    let harnesses = prompt_init_install_decision(cli, repo.root(), args, json)?;
    perform_init_install(cli, repo, args, &harnesses)
}

/// Pre-write phase of init harness selection: resolve any explicit
/// `--install-harnesses` request WITHOUT writing anything. Returns the
/// harnesses to install once writes are safe.
///
/// `--quickstart` calls this before any filesystem mutation so scope
/// errors fail before writes. The install itself is deferred to
/// [`perform_init_install`] after the writes land. Only the directory
/// `root` is needed, so it works before the repository exists on disk.
pub fn prompt_init_install_decision(
    _cli: &Cli,
    root: &Path,
    args: &crate::cli::InitArgs,
    _json: bool,
) -> Result<Vec<String>> {
    // For now init never asks to install detected harnesses. Only an
    // explicit `--install-harnesses` selection installs anything;
    // detection is still available through `--install-harnesses auto`.
    let harnesses = if args.no_harness_install {
        Vec::new()
    } else {
        match &args.install_harnesses {
            Some(selection) => resolve_selection_for_root(root, selection)?,
            None => Vec::new(),
        }
    };

    // Validate the install plan with the SAME predicates the install path
    // uses, in this pre-write decision phase, so an invalid
    // `--harness-install-scope` OR a harness that rejects the chosen scope
    // (e.g. `codex` requires `--scope user`) fails before any repo is created
    // instead of after — keeping the quickstart fail-before-writes contract.
    // Only matters when something will actually be installed.
    if !harnesses.is_empty() {
        validate_install_plan(&harnesses, &args.harness_install_scope)?;
    }
    Ok(harnesses)
}

/// Post-write phase: install the harnesses chosen by
/// [`prompt_init_install_decision`]. No prompting happens here, so it is
/// safe to run after the repository has been created.
pub fn perform_init_install(
    cli: &Cli,
    repo: &Repository,
    args: &crate::cli::InitArgs,
    harnesses: &[String],
) -> Result<()> {
    if harnesses.is_empty() {
        return Ok(());
    }
    install_selected(
        cli,
        repo,
        harnesses,
        IntegrationScope::parse(&args.harness_install_scope)?,
        args.harness_install_force,
        PathMode::Relative,
    )
}

fn list_integrations(cli: &Cli, repo: &Repository) -> Result<()> {
    let manifest = load_manifest(repo)?;
    let statuses = manifest
        .integrations
        .into_iter()
        .map(|entry| integration_status(repo, &entry))
        .collect::<Result<Vec<_>>>()?;
    if should_output_json(cli, Some(repo.config())) {
        println!("{}", serde_json::to_string(&statuses)?);
    } else if statuses.is_empty() {
        println!("No Heddle-managed harness integrations.");
    } else {
        for status in statuses {
            println!(
                "{} [{}] {} ({})",
                status.harness, status.scope, status.status, status.method
            );
            if !status.capabilities.is_empty() {
                println!("  capabilities: {}", status.capabilities.join(", "));
            }
            for path in status.paths {
                println!("  {}", path);
            }
        }
    }
    Ok(())
}

fn install_integrations(cli: &Cli, repo: &Repository, args: IntegrationInstallArgs) -> Result<()> {
    let harnesses = if args.harnesses.is_empty() {
        detect_harnesses(repo)?
    } else {
        normalize_harnesses(args.harnesses)?
    };
    let path_mode = if args.absolute_path {
        PathMode::Absolute
    } else {
        PathMode::Relative
    };
    install_selected(
        cli,
        repo,
        &harnesses,
        IntegrationScope::parse(&args.scope)?,
        args.force,
        path_mode,
    )
}

fn install_selected(
    cli: &Cli,
    repo: &Repository,
    harnesses: &[String],
    scope: IntegrationScope,
    force: bool,
    path_mode: PathMode,
) -> Result<()> {
    let mut manifest = load_manifest(repo)?;
    for harness in harnesses {
        match harness.as_str() {
            "codex" => install_codex(repo, &mut manifest, &scope, force, path_mode)?,
            "claude-code" => install_claude(repo, &mut manifest, &scope, force, path_mode)?,
            "opencode" => install_opencode(repo, &mut manifest, &scope, force, path_mode)?,
            other => return Err(anyhow!(unsupported_harness_advice(other))),
        }
    }
    save_manifest(repo, &manifest)?;
    if !should_output_json(cli, Some(repo.config())) {
        println!(
            "Installed Heddle harness integrations for: {}",
            harnesses.join(", ")
        );
    }
    Ok(())
}

fn doctor_integrations(cli: &Cli, repo: &Repository) -> Result<()> {
    let manifest = load_manifest(repo)?;
    let statuses = manifest
        .integrations
        .iter()
        .map(|entry| integration_status(repo, entry))
        .collect::<Result<Vec<_>>>()?;
    if should_output_json(cli, Some(repo.config())) {
        println!("{}", serde_json::to_string(&statuses)?);
    } else if statuses.is_empty() {
        println!("No Heddle-managed harness integrations.");
    } else {
        for status in statuses {
            println!(
                "{} [{}] (path: {}): {}",
                status.harness,
                status.scope,
                status.path_mode,
                if status.healthy {
                    "healthy"
                } else {
                    &status.status
                }
            );
        }
    }
    Ok(())
}

fn uninstall_integrations(cli: &Cli, repo: &Repository, args: IntegrationTargetArgs) -> Result<()> {
    let mut manifest = load_manifest(repo)?;
    let targets = target_harnesses(&manifest, args.harnesses)?;
    for harness in &targets {
        uninstall_one(repo, &mut manifest, harness)?;
    }
    save_manifest(repo, &manifest)?;
    if !should_output_json(cli, Some(repo.config())) {
        println!(
            "Uninstalled Heddle harness integrations for: {}",
            targets.join(", ")
        );
    }
    Ok(())
}

fn upgrade_integrations(cli: &Cli, repo: &Repository, args: IntegrationTargetArgs) -> Result<()> {
    let mut manifest = load_manifest(repo)?;
    let targets = target_harnesses(&manifest, args.harnesses)?;
    for harness in &targets {
        let existing = manifest
            .integrations
            .iter()
            .find(|entry| &entry.harness == harness)
            .cloned();
        let scope = existing
            .as_ref()
            .map(|entry| entry.scope.clone())
            .unwrap_or(IntegrationScope::Repo);
        // Preserve the existing path mode across upgrades — do not silently flip
        // an absolute-path install back to relative just because the user ran
        // `integration upgrade`. New installs go through `install` and pick up
        // the relative default there.
        //
        // Manifests written before PathMode existed deserialize to the field's
        // Default (Relative). But every pre-PathMode install actually wrote
        // *absolute* paths — that's the codex-flagged regression. So when the
        // serde default fired (i.e. the on-disk manifest had no `path_mode`
        // field), use the actual installed config, not the default. We
        // re-read the harness's installed settings file and probe the first
        // emitted command for a leading `heddle` literal vs an absolute path.
        let path_mode = match existing.as_ref() {
            Some(entry) => detect_path_mode(harness.as_str(), entry).unwrap_or(entry.path_mode),
            None => PathMode::default(),
        };
        match harness.as_str() {
            "codex" => install_codex(repo, &mut manifest, &scope, true, path_mode)?,
            "claude-code" => install_claude(repo, &mut manifest, &scope, true, path_mode)?,
            "opencode" => install_opencode(repo, &mut manifest, &scope, true, path_mode)?,
            other => return Err(anyhow!(unsupported_harness_advice(other))),
        }
    }
    save_manifest(repo, &manifest)?;
    if !should_output_json(cli, Some(repo.config())) {
        println!(
            "Upgraded Heddle harness integrations for: {}",
            targets.join(", ")
        );
    }
    Ok(())
}

/// Inspect the harness's installed config and decide whether the recorded
/// invocation is `heddle` (PATH-relative) or an absolute path. Returns `None`
/// when the file is unreadable, missing, or doesn't carry a recognisable
/// command — the caller falls back to the manifest's stored value (or the
/// default). Pre-PathMode manifests deserialize the field to its `Default`
/// (Relative) but every pre-PathMode install actually wrote absolute paths;
/// this probe lets the upgrade flow recover the real on-disk shape.
fn detect_path_mode(harness: &str, entry: &InstalledIntegration) -> Option<PathMode> {
    let path = PathBuf::from(entry.paths.first()?);
    let contents = fs::read_to_string(&path).ok()?;
    match harness {
        "claude-code" => {
            // Hooks are JSON: walk to the first relay command we emitted.
            let root: Value = serde_json::from_str(&contents).ok()?;
            let cmd = root
                .get("hooks")
                .and_then(Value::as_object)?
                .values()
                .find_map(|groups| {
                    groups.as_array()?.iter().find_map(|group| {
                        group
                            .get("hooks")?
                            .as_array()?
                            .iter()
                            .find_map(|h| h.get("command")?.as_str().map(str::to_string))
                    })
                })
                .or_else(|| {
                    // Fallback: statusLine command, which is also rewritten on install.
                    root.get("statusLine")?
                        .get("command")?
                        .as_str()
                        .map(str::to_string)
                })?;
            Some(classify_command_path_mode(&cmd))
        }
        "codex" => {
            // notify is `["/bin/sh", "-lc", "<cmd>"]` — read the third arg.
            let value: toml::Value = toml::from_str(&contents).ok()?;
            let arr = value.get("notify")?.as_array()?;
            let cmd = arr.get(2)?.as_str()?;
            Some(classify_command_path_mode(cmd))
        }
        "opencode" => {
            // Plugin script: the spawn invocation is the first quoted token in
            // `Bun.spawnSync([...])`. We look for either `"heddle"` (relative) or
            // a quoted absolute path. Probe the literal we emit at install time.
            if contents.contains("Bun.spawnSync([\"heddle\"")
                || contents.contains("Bun.spawnSync(['heddle'")
            {
                Some(PathMode::Relative)
            } else if contents.contains("Bun.spawnSync([\"/")
                || contents.contains("Bun.spawnSync(['/")
            {
                Some(PathMode::Absolute)
            } else {
                None
            }
        }
        _ => None,
    }
}

/// A command line is "PATH-relative" iff its first whitespace-delimited
/// token is exactly `heddle`. Anything else (an absolute path, a
/// shell-escaped absolute path) classifies as Absolute.
fn classify_command_path_mode(cmd: &str) -> PathMode {
    let first = cmd
        .split_whitespace()
        .next()
        .unwrap_or("")
        .trim_matches('\'');
    if first == "heddle" {
        PathMode::Relative
    } else {
        PathMode::Absolute
    }
}

fn relay_integration(repo: &Repository, args: IntegrationRelayArgs) -> Result<()> {
    let mut payload = String::new();
    io::stdin().read_to_string(&mut payload)?;
    harness::relay_harness_event(repo, &args.harness, &args.event, &payload)
}

fn manifest_path(repo: &Repository) -> PathBuf {
    repo.root().join(".heddle/state").join(MANIFEST_FILE)
}

fn load_manifest(repo: &Repository) -> Result<IntegrationManifest> {
    let path = manifest_path(repo);
    if !path.exists() {
        return Ok(IntegrationManifest::default());
    }
    let contents = fs::read_to_string(path)?;
    Ok(toml::from_str(&contents)?)
}

fn save_manifest(repo: &Repository, manifest: &IntegrationManifest) -> Result<()> {
    let path = manifest_path(repo);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let contents = toml::to_string_pretty(manifest)?;
    write_file_atomic(&path, contents.as_bytes())?;
    Ok(())
}

fn integration_status(
    _repo: &Repository,
    entry: &InstalledIntegration,
) -> Result<IntegrationStatus> {
    let mut healthy = true;
    let mut status = "healthy".to_string();
    for path in &entry.paths {
        if !Path::new(path).exists() {
            healthy = false;
            status = "missing".to_string();
        }
    }
    if healthy && entry.harness == "claude-code" {
        let settings = entry.paths.first().map(PathBuf::from);
        if let Some(path) = settings
            && fs::read_to_string(&path)
                .map(|contents| !contents.contains("heddle integration relay claude-code"))
                .unwrap_or(true)
        {
            healthy = false;
            status = "drifted".to_string();
        }
    }
    if healthy && entry.harness == "codex" {
        let path = entry.paths.first().map(PathBuf::from);
        if let Some(path) = path
            && fs::read_to_string(&path)
                .map(|contents| !contents.contains("integration relay codex notify"))
                .unwrap_or(true)
        {
            healthy = false;
            status = "drifted".to_string();
        }
    }
    Ok(IntegrationStatus {
        harness: entry.harness.clone(),
        scope: match entry.scope {
            IntegrationScope::Repo => "repo".to_string(),
            IntegrationScope::User => "user".to_string(),
        },
        method: entry.method.clone(),
        status,
        healthy,
        paths: entry.paths.clone(),
        path_mode: match entry.path_mode {
            PathMode::Relative => "relative".to_string(),
            PathMode::Absolute => "absolute".to_string(),
        },
        capabilities: integration_capabilities(entry),
        capability_paths: integration_capability_paths(entry),
    })
}

fn integration_capabilities(entry: &InstalledIntegration) -> Vec<String> {
    if entry.harness == "opencode" && !integration_capability_paths(entry).is_empty() {
        vec!["timeline".to_string()]
    } else {
        Vec::new()
    }
}

fn integration_capability_paths(entry: &InstalledIntegration) -> Vec<String> {
    entry
        .paths
        .iter()
        .filter(|path| path.ends_with("heddle.timeline.json"))
        .cloned()
        .collect()
}

fn detect_harnesses(repo: &Repository) -> Result<Vec<String>> {
    Ok(detect_harnesses_for_root(repo.root()))
}

/// Path-based harness detection: PATH lookups for the harness binaries
/// plus `.claude`/`.opencode` directory probes under `root`. Works
/// before the repository exists, which explicit pre-write
/// `--install-harnesses auto` resolution relies on.
fn detect_harnesses_for_root(root: &Path) -> Vec<String> {
    let mut found = BTreeSet::new();
    for harness in ["codex", "claude", "opencode"] {
        if command_on_path(harness) {
            let normalized = match harness {
                "claude" => "claude-code",
                other => other,
            };
            found.insert(normalized.to_string());
        }
    }
    if root.join(".claude").exists() {
        found.insert("claude-code".to_string());
    }
    if root.join(".opencode").exists() {
        found.insert("opencode".to_string());
    }
    found.into_iter().collect()
}

fn command_on_path(bin: &str) -> bool {
    env::var_os("PATH")
        .map(|paths| env::split_paths(&paths).collect::<Vec<_>>())
        .into_iter()
        .flatten()
        .any(|dir| dir.join(bin).exists())
}

fn resolve_selection_for_root(root: &Path, selection: &str) -> Result<Vec<String>> {
    match selection {
        "none" => Ok(Vec::new()),
        "auto" => Ok(detect_harnesses_for_root(root)),
        value => normalize_harnesses(value.split(',').map(|item| item.to_string()).collect()),
    }
}

fn normalize_harnesses(harnesses: Vec<String>) -> Result<Vec<String>> {
    let mut seen = BTreeSet::new();
    for harness in harnesses {
        let normalized = match harness.trim() {
            "" => continue,
            "claude" => "claude-code",
            "codex" => "codex",
            "claude-code" => "claude-code",
            "opencode" => "opencode",
            other => return Err(anyhow!(unsupported_harness_advice(other))),
        };
        seen.insert(normalized.to_string());
    }
    Ok(seen.into_iter().collect())
}

fn unsupported_harness_advice(harness: &str) -> RecoveryAdvice {
    RecoveryAdvice::invalid_usage(
        "integration_harness_unsupported",
        format!("unsupported harness: {harness}"),
        "Use one of: codex, claude-code, opencode.",
        "heddle integration install codex",
    )
}

fn target_harnesses(manifest: &IntegrationManifest, requested: Vec<String>) -> Result<Vec<String>> {
    if requested.is_empty() {
        return Ok(manifest
            .integrations
            .iter()
            .map(|entry| entry.harness.clone())
            .collect());
    }
    normalize_harnesses(requested)
}

/// Single source of truth for which install scopes a harness accepts. Both the
/// pre-write preflight ([`validate_install_plan`], so a scope a harness will
/// reject fails BEFORE any repository is created) and the actual install path
/// ([`install_codex`] et al.) call this, so the two can never disagree — a
/// future scope-restricted harness adds its rule here and is automatically
/// enforced in the preflight. This closes the class behind cid 3329409818: a
/// `--quickstart --install-harnesses codex` with the default `--scope repo`
/// must fail in the preflight, not after `.heddle/`/capture/checkpoint exist.
fn validate_harness_scope(harness: &str, scope: &IntegrationScope) -> Result<()> {
    match harness {
        "codex" if *scope != IntegrationScope::User => Err(anyhow!(RecoveryAdvice::invalid_usage(
            "integration_codex_scope_invalid",
            "codex integration currently requires --scope user",
            "Rerun the install with `--scope user`.",
            "heddle integration install codex --scope user",
        ))),
        _ => Ok(()),
    }
}

/// Pre-write validation of a harness-install plan: the scope string parses AND
/// every selected harness accepts that scope. The quickstart preflight runs
/// this before any filesystem write so a harness/scope combination that the
/// install would reject (e.g. `codex` + `repo`) fails before a repo is created,
/// not midway through `install_selected` after `.heddle/` already exists.
fn validate_install_plan(harnesses: &[String], scope_value: &str) -> Result<()> {
    let scope = IntegrationScope::parse(scope_value)?;
    for harness in harnesses {
        validate_harness_scope(harness, &scope)?;
    }
    Ok(())
}

fn install_codex(
    repo: &Repository,
    manifest: &mut IntegrationManifest,
    scope: &IntegrationScope,
    force: bool,
    path_mode: PathMode,
) -> Result<()> {
    validate_harness_scope("codex", scope)?;
    let home = env::var("HOME").context("HOME is required for codex integration install")?;
    let config_path = PathBuf::from(home).join(".codex").join("config.toml");
    let existing = if config_path.exists() {
        fs::read_to_string(&config_path)?
    } else {
        String::new()
    };
    if existing.contains("notify =")
        && !existing.contains("integration relay codex notify")
        && !force
    {
        return Err(anyhow!(
            "codex config already defines a non-Heddle notify command; rerun with --force after manual review"
        ));
    }
    let mut value = if existing.trim().is_empty() {
        toml::Value::Table(toml::map::Map::new())
    } else {
        existing.parse::<toml::Value>()?
    };
    let heddle = HeddleInvocation::resolve(path_mode)?;
    let command = format!(
        "{} --repo {} integration relay codex notify",
        heddle,
        shell_escape(repo.root())
    );
    let table = value
        .as_table_mut()
        .ok_or_else(|| anyhow!("codex config root must be a TOML table"))?;
    table.insert(
        "notify".to_string(),
        toml::Value::Array(vec![
            toml::Value::String("/bin/sh".to_string()),
            toml::Value::String("-lc".to_string()),
            toml::Value::String(command),
        ]),
    );
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)?;
    }
    write_file_atomic(&config_path, toml::to_string_pretty(&value)?.as_bytes())?;
    upsert_manifest(
        manifest,
        InstalledIntegration {
            harness: "codex".to_string(),
            scope: scope.clone(),
            method: "notify".to_string(),
            paths: vec![config_path.display().to_string()],
            status: "installed".to_string(),
            heddle_version: env!("CARGO_PKG_VERSION").to_string(),
            path_mode,
        },
    );
    Ok(())
}

fn install_claude(
    repo: &Repository,
    manifest: &mut IntegrationManifest,
    scope: &IntegrationScope,
    _force: bool,
    path_mode: PathMode,
) -> Result<()> {
    let settings_path = match scope {
        IntegrationScope::Repo => repo.root().join(".claude").join("settings.json"),
        IntegrationScope::User => PathBuf::from(env::var("HOME")?)
            .join(".claude")
            .join("settings.json"),
    };
    let mut root: Value = if settings_path.exists() {
        serde_json::from_str(&fs::read_to_string(&settings_path)?)?
    } else {
        serde_json::json!({})
    };
    let hooks = root
        .as_object_mut()
        .ok_or_else(|| anyhow!("claude settings root must be a JSON object"))?
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let hooks_obj = hooks
        .as_object_mut()
        .ok_or_else(|| anyhow!("claude settings hooks must be an object"))?;

    let heddle = HeddleInvocation::resolve(path_mode)?;
    for event in [
        "SessionStart",
        "UserPromptSubmit",
        "PreToolUse",
        "PostToolUse",
        "SubagentStart",
        "SubagentStop",
        "Stop",
        "SessionEnd",
    ] {
        let command = format!(
            "{} --repo {} integration relay claude-code {}",
            heddle,
            shell_escape(repo.root()),
            event
        );
        let group = serde_json::json!({
            "matcher": "*",
            "hooks": [{
                "type": "command",
                "command": command
            }]
        });
        let entry = hooks_obj
            .entry(event.to_string())
            .or_insert_with(|| Value::Array(Vec::new()));
        let groups = entry
            .as_array_mut()
            .ok_or_else(|| anyhow!("claude hook event entries must be arrays"))?;
        let exists = groups
            .iter()
            .any(|group| group.to_string().contains("integration relay claude-code"));
        if !exists {
            groups.push(group);
        }
    }
    let root_obj = root
        .as_object_mut()
        .ok_or_else(|| anyhow!("claude settings root must be a JSON object"))?;
    let install_status_line = match root_obj.get("statusLine") {
        None => true,
        Some(value) => value
            .as_object()
            .and_then(|obj| obj.get("command"))
            .and_then(Value::as_str)
            .is_some_and(|command| command.contains("integration relay claude-code StatusLine")),
    };
    if install_status_line {
        root_obj.insert(
            "statusLine".to_string(),
            serde_json::json!({
                "type": "command",
                "command": format!(
                    "{} --repo {} integration relay claude-code StatusLine",
                    heddle,
                    shell_escape(repo.root())
                )
            }),
        );
    }
    if let Some(parent) = settings_path.parent() {
        fs::create_dir_all(parent)?;
    }
    write_file_atomic(
        &settings_path,
        serde_json::to_string_pretty(&root)?.as_bytes(),
    )?;
    upsert_manifest(
        manifest,
        InstalledIntegration {
            harness: "claude-code".to_string(),
            scope: scope.clone(),
            method: "hooks+statusline".to_string(),
            paths: vec![settings_path.display().to_string()],
            status: "installed".to_string(),
            heddle_version: env!("CARGO_PKG_VERSION").to_string(),
            path_mode,
        },
    );
    Ok(())
}

fn install_opencode(
    repo: &Repository,
    manifest: &mut IntegrationManifest,
    scope: &IntegrationScope,
    _force: bool,
    path_mode: PathMode,
) -> Result<()> {
    let plugin_path = match scope {
        IntegrationScope::Repo => repo
            .root()
            .join(".opencode")
            .join("plugins")
            .join("heddle.js"),
        IntegrationScope::User => PathBuf::from(env::var("HOME")?)
            .join(".config")
            .join("opencode")
            .join("plugins")
            .join("heddle.js"),
    };
    if let Some(parent) = plugin_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let timeline_manifest_path = plugin_path.with_file_name("heddle.timeline.json");
    let heddle_raw = HeddleInvocation::raw(path_mode)?;
    let script = format!(
        "const relay = async (event, payload) => {{
  const proc = Bun.spawnSync([{exe:?}, '--repo', {repo:?}, 'integration', 'relay', 'opencode', event], {{
    stdin: JSON.stringify(payload),
  }});
  if (proc.exitCode !== 0) console.error(new TextDecoder().decode(proc.stderr));
}};

export default async function(ctx) {{
  return {{
    event: async (input) => {{
      const event = input?.event?.name || input?.name || 'event';
      const allowed = new Set(['session.created','session.updated','session.diff','file.edited','tool.execute.before','tool.execute.after','permission.asked','permission.replied']);
      if (allowed.has(event)) {{
        await relay(event, input);
      }}
    }},
  }};
}}",
        exe = heddle_raw,
        repo = repo.root().display().to_string(),
    );
    write_file_atomic(&plugin_path, script.as_bytes())?;
    let capabilities = opencode_timeline_capabilities(repo, &heddle_raw);
    write_file_atomic(
        &timeline_manifest_path,
        serde_json::to_string_pretty(&capabilities)?.as_bytes(),
    )?;
    upsert_manifest(
        manifest,
        InstalledIntegration {
            harness: "opencode".to_string(),
            scope: scope.clone(),
            method: "plugin".to_string(),
            paths: vec![
                plugin_path.display().to_string(),
                timeline_manifest_path.display().to_string(),
            ],
            status: "installed".to_string(),
            heddle_version: env!("CARGO_PKG_VERSION").to_string(),
            path_mode,
        },
    );
    Ok(())
}

fn opencode_timeline_capabilities(repo: &Repository, heddle_raw: &str) -> Value {
    let repo_path = repo.root().display().to_string();
    serde_json::json!({
        "schema_version": 1,
        "producer": "heddle",
        "harness": "opencode",
        "repo": repo_path,
        "binary": heddle_raw,
        "privacy": {
            "native_payloads": "summaries-and-hashes",
            "raw_payloads_synced_by_default": false
        },
        "timeline": {
            "schema_version": 1,
            "default_thread": "main",
            "default_harness": "opencode",
            "output_kinds": ["timeline_log", "timeline_action"],
            "selectors": {
                "step": ["--step", "<timeline_step_id>"],
                "tool_call": [
                    "--tool-call",
                    "<opencode_tool_call_id>",
                    "--harness",
                    "opencode",
                    "--session",
                    "<opencode_session_id>"
                ],
                "undo": ["--undo"],
                "redo": ["--redo"],
                "current": ["--current"]
            },
            "verbs": [
                {
                    "name": "timeline_log",
                    "verb": "log --timeline",
                    "intent": "Inspect the current timeline cursor, branches, and recent steps.",
                    "argv": ["--repo", repo_path, "log", "--timeline", "--thread", "<thread>", "--output", "json"],
                    "mutates_checkout": false
                },
                {
                    "name": "timeline_fork_from_tool_call",
                    "verb": "timeline fork",
                    "intent": "Create a branch from an OpenCode tool call or timeline step before experimenting.",
                    "argv": ["--repo", repo_path, "timeline", "fork", "--tool-call", "<opencode_tool_call_id>", "--harness", "opencode", "--session", "<opencode_session_id>", "--reason", "fan-out", "--output", "json"],
                    "mutates_checkout": false
                },
                {
                    "name": "timeline_reset_to_tool_call",
                    "verb": "timeline reset",
                    "intent": "Move the timeline cursor to an OpenCode tool call and optionally materialize checkout files.",
                    "argv": ["--repo", repo_path, "timeline", "reset", "--tool-call", "<opencode_tool_call_id>", "--harness", "opencode", "--session", "<opencode_session_id>", "--materialize", "--mode", "fail-if-dirty", "--output", "json"],
                    "mutates_checkout": true
                },
                {
                    "name": "timeline_undo",
                    "verb": "timeline reset",
                    "intent": "Move one reversible timeline step backward.",
                    "argv": ["--repo", repo_path, "timeline", "reset", "--undo", "--materialize", "--mode", "fail-if-dirty", "--output", "json"],
                    "mutates_checkout": true
                },
                {
                    "name": "timeline_redo",
                    "verb": "timeline reset",
                    "intent": "Move one reversible timeline step forward.",
                    "argv": ["--repo", repo_path, "timeline", "reset", "--redo", "--materialize", "--mode", "fail-if-dirty", "--output", "json"],
                    "mutates_checkout": true
                },
                {
                    "name": "timeline_recover",
                    "verb": "timeline recover",
                    "intent": "Inspect or complete recovery after an interrupted timeline materialization.",
                    "argv": ["--repo", repo_path, "timeline", "recover", "--thread", "<thread>", "--output", "json"],
                    "mutates_checkout": false
                }
            ]
        }
    })
}

fn uninstall_one(
    repo: &Repository,
    manifest: &mut IntegrationManifest,
    harness: &str,
) -> Result<()> {
    let Some(existing) = manifest
        .integrations
        .iter()
        .find(|entry| entry.harness == harness)
        .cloned()
    else {
        return Ok(());
    };
    match harness {
        "codex" => {
            if let Some(path) = existing.paths.first() {
                let config_path = PathBuf::from(path);
                if config_path.exists() {
                    let mut value = fs::read_to_string(&config_path)?.parse::<toml::Value>()?;
                    if let Some(table) = value.as_table_mut()
                        && table.get("notify").is_some_and(|notify| {
                            notify
                                .to_string()
                                .contains("integration relay codex notify")
                        })
                    {
                        table.remove("notify");
                        write_file_atomic(
                            &config_path,
                            toml::to_string_pretty(&value)?.as_bytes(),
                        )?;
                    }
                }
            }
        }
        "claude-code" => {
            if let Some(path) = existing.paths.first() {
                let settings_path = PathBuf::from(path);
                if settings_path.exists() {
                    let mut root: Value =
                        serde_json::from_str(&fs::read_to_string(&settings_path)?)?;
                    if let Some(hooks) = root.get_mut("hooks").and_then(Value::as_object_mut) {
                        for groups in hooks.values_mut() {
                            if let Some(array) = groups.as_array_mut() {
                                array.retain(|group| {
                                    !group.to_string().contains("integration relay claude-code")
                                });
                            }
                        }
                    }
                    if let Some(command) = root
                        .get("statusLine")
                        .and_then(Value::as_object)
                        .and_then(|obj| obj.get("command"))
                        .and_then(Value::as_str)
                        && command.contains("integration relay claude-code StatusLine")
                    {
                        root.as_object_mut().map(|obj| obj.remove("statusLine"));
                    }
                    write_file_atomic(
                        &settings_path,
                        serde_json::to_string_pretty(&root)?.as_bytes(),
                    )?;
                }
            }
        }
        "opencode" => {
            for path in &existing.paths {
                let path = PathBuf::from(path);
                if path.exists() {
                    fs::remove_file(path)?;
                }
            }
        }
        _ => {}
    }
    manifest
        .integrations
        .retain(|entry| entry.harness != harness);
    let _ = repo;
    Ok(())
}

fn upsert_manifest(manifest: &mut IntegrationManifest, entry: InstalledIntegration) {
    manifest
        .integrations
        .retain(|existing| existing.harness != entry.harness);
    manifest.integrations.push(entry);
    manifest
        .integrations
        .sort_by(|a, b| a.harness.cmp(&b.harness));
}

fn shell_escape(path: &Path) -> String {
    format!("'{}'", path.display().to_string().replace('\'', "'\"'\"'"))
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;
    use crate::cli::Commands;

    struct HomeEnvGuard(Option<std::ffi::OsString>);

    impl HomeEnvGuard {
        fn set(path: &Path) -> Self {
            let original = std::env::var_os("HOME");
            unsafe {
                std::env::set_var("HOME", path);
            }
            Self(original)
        }
    }

    impl Drop for HomeEnvGuard {
        fn drop(&mut self) {
            match self.0.take() {
                Some(value) => unsafe { std::env::set_var("HOME", value) },
                None => unsafe { std::env::remove_var("HOME") },
            }
        }
    }

    fn init_repo() -> (tempfile::TempDir, Repository) {
        let temp = tempfile::TempDir::new().unwrap();
        let repo = Repository::init_default(temp.path()).unwrap();
        (temp, repo)
    }

    #[test]
    fn init_harness_selection_does_not_auto_connect_detected_harnesses() {
        let temp = tempfile::TempDir::new().unwrap();
        fs::create_dir(temp.path().join(".claude")).unwrap();
        let cli = Cli::parse_from(["heddle", "init"]);
        let Commands::Init(args) = &cli.command else {
            panic!("expected parsed init command");
        };

        let harnesses = prompt_init_install_decision(&cli, temp.path(), args, false).unwrap();

        assert!(
            harnesses.is_empty(),
            "init must not auto-select detected harnesses without --install-harnesses"
        );
    }

    #[test]
    fn claude_repo_install_writes_project_hooks_and_manifest() {
        let (_temp, repo) = init_repo();
        let mut manifest = IntegrationManifest::default();

        install_claude(
            &repo,
            &mut manifest,
            &IntegrationScope::Repo,
            false,
            PathMode::Relative,
        )
        .unwrap();

        let settings_path = repo.root().join(".claude").join("settings.json");
        let contents = fs::read_to_string(&settings_path).unwrap();
        assert!(contents.contains("integration relay claude-code SessionStart"));
        assert!(contents.contains("integration relay claude-code UserPromptSubmit"));
        assert!(contents.contains("integration relay claude-code PreToolUse"));
        assert!(contents.contains("integration relay claude-code PostToolUse"));
        assert!(contents.contains("integration relay claude-code SubagentStop"));
        assert!(contents.contains("integration relay claude-code Stop"));
        assert!(contents.contains("integration relay claude-code StatusLine"));

        // Default install must use the PATH-relative literal `heddle` and must
        // NOT bake in an absolute path. We assert the exact command shape so a
        // future regression that resurrects current_exe() trips this test.
        let parsed: Value = serde_json::from_str(&contents).unwrap();
        let session_start_cmd = parsed["hooks"]["SessionStart"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap();
        assert!(
            session_start_cmd.starts_with("heddle --repo "),
            "expected PATH-relative `heddle` invocation, got: {session_start_cmd}"
        );
        assert!(
            !session_start_cmd.starts_with('/'),
            "expected no absolute path leading the command, got: {session_start_cmd}"
        );
        let status_line_cmd = parsed["statusLine"]["command"].as_str().unwrap();
        assert!(
            status_line_cmd.starts_with("heddle --repo "),
            "expected PATH-relative `heddle` invocation in statusLine, got: {status_line_cmd}"
        );

        assert_eq!(manifest.integrations.len(), 1);
        assert_eq!(manifest.integrations[0].harness, "claude-code");
        assert_eq!(manifest.integrations[0].path_mode, PathMode::Relative);
    }

    #[test]
    fn claude_repo_install_with_absolute_path_bakes_current_exe() {
        let (_temp, repo) = init_repo();
        let mut manifest = IntegrationManifest::default();

        install_claude(
            &repo,
            &mut manifest,
            &IntegrationScope::Repo,
            false,
            PathMode::Absolute,
        )
        .unwrap();

        let settings_path = repo.root().join(".claude").join("settings.json");
        let contents = fs::read_to_string(&settings_path).unwrap();
        let parsed: Value = serde_json::from_str(&contents).unwrap();

        let exe = std::env::current_exe().unwrap();
        let escaped_exe = shell_escape(&exe);

        let session_start_cmd = parsed["hooks"]["SessionStart"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap();
        assert!(
            session_start_cmd.starts_with(&escaped_exe),
            "expected absolute heddle path {escaped_exe} prefix, got: {session_start_cmd}"
        );
        assert!(
            !session_start_cmd.starts_with("heddle "),
            "absolute mode must not emit bare `heddle`, got: {session_start_cmd}"
        );

        let status_line_cmd = parsed["statusLine"]["command"].as_str().unwrap();
        assert!(
            status_line_cmd.starts_with(&escaped_exe),
            "expected absolute heddle path {escaped_exe} prefix in statusLine, got: {status_line_cmd}"
        );

        assert_eq!(manifest.integrations[0].path_mode, PathMode::Absolute);
    }

    #[test]
    fn opencode_repo_install_and_uninstall_manage_plugin_file() {
        let (_temp, repo) = init_repo();
        let mut manifest = IntegrationManifest::default();

        install_opencode(
            &repo,
            &mut manifest,
            &IntegrationScope::Repo,
            false,
            PathMode::Relative,
        )
        .unwrap();
        let plugin_path = repo
            .root()
            .join(".opencode")
            .join("plugins")
            .join("heddle.js");
        assert!(plugin_path.exists());
        let plugin_contents = fs::read_to_string(&plugin_path).unwrap();
        assert!(
            plugin_contents.contains("\"heddle\""),
            "opencode plugin should reference PATH-relative `heddle`, got: {plugin_contents}"
        );
        let timeline_manifest_path = repo
            .root()
            .join(".opencode")
            .join("plugins")
            .join("heddle.timeline.json");
        assert!(timeline_manifest_path.exists());
        let timeline_manifest: Value =
            serde_json::from_str(&fs::read_to_string(&timeline_manifest_path).unwrap()).unwrap();
        assert_eq!(timeline_manifest["schema_version"], 1);
        assert_eq!(timeline_manifest["harness"], "opencode");
        assert_eq!(timeline_manifest["timeline"]["schema_version"], 1);
        assert_eq!(timeline_manifest["timeline"]["default_harness"], "opencode");
        assert!(
            timeline_manifest["timeline"]["verbs"]
                .as_array()
                .unwrap()
                .iter()
                .any(|verb| verb["name"] == "timeline_reset_to_tool_call")
        );
        assert!(
            timeline_manifest["timeline"]["verbs"]
                .as_array()
                .unwrap()
                .iter()
                .any(|verb| verb["name"] == "timeline_undo")
        );
        let status = integration_status(&repo, &manifest.integrations[0]).unwrap();
        assert_eq!(status.capabilities, vec!["timeline"]);
        assert_eq!(
            status.capability_paths,
            vec![timeline_manifest_path.display().to_string()]
        );

        uninstall_one(&repo, &mut manifest, "opencode").unwrap();
        assert!(!plugin_path.exists());
        assert!(!timeline_manifest_path.exists());
        assert!(manifest.integrations.is_empty());
    }

    #[test]
    #[serial_test::serial]
    fn codex_user_install_writes_notify_command() {
        // Serialize env-var access across tests. The credential store
        // (in heddle-client when the client feature is enabled) has its own mutex; this is
        // a local fallback for cli-only builds.
        static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _env_lock = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let (_temp, repo) = init_repo();
        let home = tempfile::TempDir::new().unwrap();
        let _home_guard = HomeEnvGuard::set(home.path());
        let mut manifest = IntegrationManifest::default();

        install_codex(
            &repo,
            &mut manifest,
            &IntegrationScope::User,
            false,
            PathMode::Relative,
        )
        .unwrap();

        let config_path = home.path().join(".codex").join("config.toml");
        let contents = fs::read_to_string(&config_path).unwrap();
        assert!(contents.contains("integration relay codex notify"));
        // The default codex install must invoke PATH-relative `heddle`, not the
        // absolute path of the current binary.
        assert!(
            contents.contains("\"heddle --repo "),
            "expected PATH-relative `heddle` in codex notify command, got: {contents}"
        );
        assert_eq!(manifest.integrations[0].harness, "codex");
        assert_eq!(manifest.integrations[0].path_mode, PathMode::Relative);
    }

    #[test]
    fn upgrade_preserves_path_mode_when_absolute() {
        let (_temp, repo) = init_repo();
        let mut manifest = IntegrationManifest::default();

        // First install with --absolute-path semantics.
        install_claude(
            &repo,
            &mut manifest,
            &IntegrationScope::Repo,
            false,
            PathMode::Absolute,
        )
        .unwrap();
        assert_eq!(manifest.integrations[0].path_mode, PathMode::Absolute);

        // Save and reload the manifest the way upgrade_integrations would, so we
        // exercise the same lookup path (find existing entry, read its path_mode).
        save_manifest(&repo, &manifest).unwrap();
        let mut reloaded = load_manifest(&repo).unwrap();

        // Simulate the upgrade body: look up existing entry, preserve mode, reinstall.
        let existing = reloaded
            .integrations
            .iter()
            .find(|entry| entry.harness == "claude-code")
            .cloned()
            .unwrap();
        install_claude(
            &repo,
            &mut reloaded,
            &existing.scope,
            true,
            existing.path_mode,
        )
        .unwrap();

        assert_eq!(reloaded.integrations[0].path_mode, PathMode::Absolute);

        let settings_path = repo.root().join(".claude").join("settings.json");
        let contents = fs::read_to_string(&settings_path).unwrap();
        let parsed: Value = serde_json::from_str(&contents).unwrap();
        let cmd = parsed["hooks"]["SessionStart"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap();
        assert!(
            !cmd.starts_with("heddle "),
            "upgrade must not silently flip an absolute install to relative, got: {cmd}"
        );
    }

    /// Regression for codex feedback on PR #56: pre-PathMode manifests
    /// deserialize the missing `path_mode` field to its `Default`
    /// (Relative). But every pre-PathMode install actually wrote
    /// *absolute* paths. So `integration upgrade` on a legacy manifest
    /// silently flipped the install to PATH-relative — breaking
    /// machines where `heddle` isn't on PATH.
    ///
    /// Fix: when probing the existing install, read the actual settings
    /// file and prefer the on-disk command shape over the manifest's
    /// (defaulted) `path_mode`. Setup: install once with absolute mode,
    /// then drop the `path_mode` field from the manifest TOML to
    /// emulate a pre-PathMode install. The upgrade path must detect the
    /// absolute heddle prefix in `.claude/settings.json` and preserve
    /// absolute mode.
    #[test]
    fn upgrade_preserves_path_mode_for_legacy_manifest_with_absolute_install() {
        let (_temp, repo) = init_repo();
        let mut manifest = IntegrationManifest::default();

        install_claude(
            &repo,
            &mut manifest,
            &IntegrationScope::Repo,
            false,
            PathMode::Absolute,
        )
        .unwrap();

        // Confirm we actually wrote an absolute heddle prefix.
        let settings_path = repo.root().join(".claude").join("settings.json");
        let settings_contents = fs::read_to_string(&settings_path).unwrap();
        assert!(
            !settings_contents.contains("\"heddle --repo "),
            "absolute install must NOT have bare `heddle` prefix"
        );

        // Strip `path_mode` from the manifest entry to emulate a
        // pre-PathMode manifest. Round-tripping it through TOML drops
        // the field and the reload deserializes to the default (Relative)
        // — exactly the legacy shape we want to recover from.
        manifest.integrations[0].path_mode = PathMode::Absolute; // ensure it's there pre-strip
        save_manifest(&repo, &manifest).unwrap();
        let manifest_path = repo.root().join(".heddle/state").join(MANIFEST_FILE);
        let raw = fs::read_to_string(&manifest_path).unwrap();
        // Drop any line containing `path_mode` to simulate the legacy on-disk shape.
        let stripped: String = raw
            .lines()
            .filter(|l| !l.trim_start().starts_with("path_mode"))
            .collect::<Vec<_>>()
            .join("\n");
        fs::write(&manifest_path, stripped).unwrap();

        // Reload — `path_mode` is missing, serde defaults it to Relative.
        let reloaded = load_manifest(&repo).unwrap();
        assert_eq!(
            reloaded.integrations[0].path_mode,
            PathMode::Relative,
            "sanity: legacy manifest must deserialize to the field default"
        );

        // The fix: detect_path_mode reads the actual settings.json and
        // reports Absolute, overriding the (defaulted) manifest field.
        let detected =
            detect_path_mode("claude-code", &reloaded.integrations[0]).expect("detection succeeds");
        assert_eq!(
            detected,
            PathMode::Absolute,
            "detect_path_mode must read the on-disk settings and recognise an absolute install"
        );

        // Drive the same code path as `upgrade_integrations`: pick the
        // detected mode, then re-install. The resulting settings file
        // must still have an absolute prefix — no silent flip.
        let mut working = reloaded;
        let resolved_mode =
            detect_path_mode("claude-code", &working.integrations[0]).unwrap_or(PathMode::Relative);
        let scope = working.integrations[0].scope.clone();
        install_claude(&repo, &mut working, &scope, true, resolved_mode).unwrap();

        let settings_after = fs::read_to_string(&settings_path).unwrap();
        let parsed: Value = serde_json::from_str(&settings_after).unwrap();
        let cmd = parsed["hooks"]["SessionStart"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap();
        assert!(
            !cmd.starts_with("heddle "),
            "upgrade of a legacy absolute install must NOT silently flip to PATH-relative, got: {cmd}"
        );
    }

    #[test]
    fn classify_command_path_mode_recognises_relative_and_absolute() {
        // Bare `heddle` literal at the start = relative.
        assert_eq!(
            classify_command_path_mode(
                "heddle --repo /some/path integration relay claude-code Stop"
            ),
            PathMode::Relative,
        );
        // Absolute path = absolute, with or without the shell-escape quotes.
        assert_eq!(
            classify_command_path_mode(
                "/Users/dev/.cargo/bin/heddle --repo /repo integration relay claude-code Stop"
            ),
            PathMode::Absolute,
        );
        assert_eq!(
            classify_command_path_mode(
                "'/Users/dev/.cargo/bin/heddle' --repo /repo integration relay claude-code Stop"
            ),
            PathMode::Absolute,
        );
    }

    #[test]
    fn upgrade_preserves_path_mode_when_relative() {
        let (_temp, repo) = init_repo();
        let mut manifest = IntegrationManifest::default();

        install_claude(
            &repo,
            &mut manifest,
            &IntegrationScope::Repo,
            false,
            PathMode::Relative,
        )
        .unwrap();
        save_manifest(&repo, &manifest).unwrap();

        let mut reloaded = load_manifest(&repo).unwrap();
        let existing = reloaded
            .integrations
            .iter()
            .find(|entry| entry.harness == "claude-code")
            .cloned()
            .unwrap();
        install_claude(
            &repo,
            &mut reloaded,
            &existing.scope,
            true,
            existing.path_mode,
        )
        .unwrap();

        assert_eq!(reloaded.integrations[0].path_mode, PathMode::Relative);
    }
}