cursor-setup-system 0.0.84

Install, update, back up, restore and remove complete Cursor CLI configurations. Built by NDDev.
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
//! The product's own lifecycle: planning what to fetch, and installing it.
//!
//! The argv and the plan shape here are not this program's invention. They were
//! proposed on `ai-engineers-guild/ai_stp#414`, agreed, and recorded in that
//! project's `docs/contracts/provider-protocol.md`. Where an earlier version of
//! this file guessed, it guessed differently -- one `--artifact`, a single
//! object, the program under the target -- and the agreement is what this now
//! follows:
//!
//! * `--target` is the configuration directory; `--prefix` is the program
//!   directory. Different paths with different lifetimes, both absolute.
//! * The plan carries an array. One element is one file, and `apply` receives
//!   one repeated `--software-artifact` per element **in that order**, so which
//!   file answers which entry is never inferred.
//! * `--software-version` omitted means the pinned version; given means exactly
//!   one of the versions this build names -- the pinned one, or the one pinned
//!   before it once the harness has been bumped. The plan records that version
//!   and the artifact digest; apply re-checks both and refuses a neighbour
//!   pin's bytes even when this build also publishes them.
//! * An unpinned platform refuses with `unsupported_platform`.
//! * `software_remove` plans and applies with no download and no artifact.
//!
//! It is deliberately not routed through [`crate::harness_runtime::wire::perform`], and the
//! reason is not convenience. That path exists to mutate the namespaces this
//! provider owns inside a *target*: it captures a backup slot, re-checks the
//! target's identity, and journals. A software install writes under `--prefix`
//! and touches no namespace, so running it through that path would spend one of
//! ten backup slots on a capture nobody can use. Installing ten times would
//! evict every configuration backup the target had.
//!
//! What it does keep is a lock, because two installs racing into one directory
//! is a real failure. It needs nothing more, because the layout makes the
//! operation atomic by construction: bytes land in a directory named for their
//! version, and the entry point is pointed at them only once every byte is
//! written. An interrupted install leaves a partial directory the next one
//! replaces, and an entry point still naming the version that worked.

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

use crate::provider_v3::plan::SoftwareArtifact;
use crate::provider_v3::{Error, Operation, Result, WireReason};
use crate::setup_core::platform_of_this_host;
use crate::setup_core::software::{self, Delivery, Software};

use crate::harness_runtime::facts::{Harness, LaunchBinding};

/// The software this harness installs, or the reason it installs none.
fn declared(harness: &Harness) -> Result<Software> {
    match harness.software {
        Some(
            found @ Software {
                delivery: Delivery::Artifacts(_),
                ..
            },
        ) => Ok(found),
        Some(Software {
            delivery: Delivery::Manager { tool, reason },
            command,
            ..
        }) => Err(Error::refuse(
            WireReason::UnsupportedOperation,
            format!(
                "{command} is installed by {tool}, which resolves a dependency closure: {reason}"
            ),
        )),
        None => Err(Error::refuse(
            WireReason::UnsupportedOperation,
            format!(
                "{} does not implement the software lifecycle",
                harness.provider_id
            ),
        )),
    }
}

/// The program directory a software operation was given.
fn program_directory(prefix: Option<&Path>, operation: Operation) -> Result<PathBuf> {
    prefix.map(Path::to_path_buf).ok_or_else(|| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{operation} installs a program, which lives under --prefix, not under --target; \
                 name an absolute --prefix"
            ),
        )
    })
}

/// This build as it describes the version an operation was asked for.
///
/// A build names its pinned version and, once it has been bumped, the one it
/// pinned before. Anything else refuses: installing a version it *does* name
/// instead would be answering a question nobody asked.
fn version_for(declared: &Software, asked: Option<&str>) -> Result<Software> {
    declared.at(asked).ok_or_else(|| {
        let wanted = asked.unwrap_or_default();
        Error::refuse(
            WireReason::UnsupportedOperation,
            format!(
                "this build names {} {}; it cannot install {wanted}, and installing one it does \
                 name instead would be answering a question nobody asked",
                declared.command,
                declared.versions().join(" and "),
            ),
        )
    })
}

/// Plan one software operation: name the exact bytes, with no network open.
///
/// # Errors
///
/// Refuses when this harness declares no software lifecycle, when no `--prefix`
/// was given, when a version other than the pinned one was asked for, or when
/// the vendor publishes no build for the running platform.
pub(crate) fn plan(
    harness: &Harness,
    prefix: Option<&Path>,
    operation: Operation,
    software_version: Option<&str>,
) -> Result<(Vec<SoftwareArtifact>, Vec<String>, &'static str)> {
    let declared = version_for(&declared(harness)?, software_version)?;
    let root = program_directory(prefix, operation)?;

    // Not always the command: pi's entry point is JavaScript, and Windows runs
    // a file by its extension rather than by a shebang, so what is exposed
    // there is `pi.cmd`. The plan states what a caller will actually be able to
    // run, which is the whole point of naming it -- and it is derived from
    // **this platform's** member, not the table's first row. The hint
    // derivation promised `bin/agent` on Windows while the apply wrote
    // `bin/agent.cmd`, because cursor's Windows member is a `.cmd` and its
    // Unix members are extensionless; the consumer's matrix caught the plan
    // lying on exactly the one platform where the two rows classify apart.
    let (os, arch) = platform_of_this_host();
    let member = declared.member_on(os, arch);
    let entry_point = format!(
        "bin/{}",
        crate::setup_core::software::exposed_name(declared.command, member)
    );
    let exposed = root.join(&entry_point);

    // Planning may read the local disk and may not reach the network, so what
    // is already under the prefix belongs in the plan. Without it an install
    // and an update produced byte-identical effects -- two names for one act,
    // and neither said what was about to be replaced.
    let present = software::Present::under_named(&root, declared.command, member);

    if operation == Operation::SoftwareRemove {
        let mut effects = vec![
            format!(
                "remove {}, the {} tree this provider installed",
                root.join(declared.version).display(),
                declared.version
            ),
            format!("remove {}", exposed.display()),
        ];
        // Other versions are left, and saying which is the difference between
        // leaving them and losing track of them. This build pins one version
        // and cannot know whether an older tree is still wanted.
        let kept: Vec<&str> = present
            .versions
            .iter()
            .map(String::as_str)
            .filter(|version| *version != declared.version)
            .collect();
        if !kept.is_empty() {
            effects.push(format!(
                "leave {} in place: this build pins {} and does not decide about versions it \
                 does not pin",
                kept.join(", "),
                declared.version
            ));
        }
        return Ok((Vec::new(), effects, declared.version));
    }

    // An update of nothing is a request that cannot be honoured as asked.
    // Installing instead would be doing something else and calling it done.
    if operation == Operation::SoftwareUpdate && present.versions.is_empty() {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "there is no {} under {} to update; software_install is the operation that \
                 puts one there",
                declared.command,
                root.display()
            ),
        ));
    }

    let artifact = declared.artifact_for(os, arch)?;
    let mut effects = Vec::new();
    if present.holds(declared.version) {
        effects.push(format!(
            "replace {}, which is already installed",
            declared.version
        ));
    } else if let Some(running) = present.exposed.as_deref() {
        effects.push(format!(
            "move {} from {running} to {}, keeping {running} where it is",
            declared.command, declared.version
        ));
    } else if !present.versions.is_empty() {
        effects.push(format!(
            "install {} beside {}, which no entry point names",
            declared.version,
            present.versions.join(", ")
        ));
    }
    effects.extend([
        format!(
            "download {} ({} bytes) in the operation's own download phase",
            artifact.url, artifact.bytes
        ),
        format!("check those bytes against {}", artifact.sha256),
        match artifact.shape {
            software::Shape::Raw => format!(
                "place them as {}",
                root.join(declared.version).join(declared.command).display()
            ),
            software::Shape::GzipTar | software::Shape::Zip => format!(
                "extract them into {}, whose {} is the program",
                root.join(declared.version).display(),
                artifact.member
            ),
        },
        format!("point {} at it", exposed.display()),
    ]);

    Ok((
        vec![SoftwareArtifact {
            platform: artifact.platform.to_owned(),
            url: artifact.url.to_owned(),
            sha256: artifact.sha256.to_owned(),
            byte_length: artifact.bytes,
            entry_point,
        }],
        effects,
        declared.version,
    ))
}

/// Apply one software operation under a lock, with no network open.
///
/// # Errors
///
/// Refuses a missing `--prefix`, a count of downloaded files that does not match
/// what the plan named, bytes that are not the ones it named, or an archive that
/// does not hold the member it named.
pub(crate) fn apply(
    harness: &Harness,
    prefix: Option<&Path>,
    operation: Operation,
    planned_version: &str,
    planned_artifacts: &[SoftwareArtifact],
    downloaded: &[PathBuf],
) -> Result<serde_json::Value> {
    let declared = version_for(&declared(harness)?, Some(planned_version))?;
    let root = program_directory(prefix, operation)?;

    // The lock lives in this provider's own dotted directory inside the prefix,
    // not at its root. `acquire` takes a control directory, and a `target.lock`
    // sitting beside `bin/` in a program directory would be both misnamed and
    // in the way of whoever looks in there for a program.
    let control = root.join(harness.control_directory);
    std::fs::create_dir_all(&control).map_err(|error| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!("--prefix {} cannot be created: {error}", root.display()),
        )
    })?;
    let mut guard = crate::setup_core::lock::TargetLock::acquire(&control)?;
    guard.annotate(&format!("{} {operation}", harness.provider_id))?;

    // **Under the lock, before anything reads the prefix.** An interrupted
    // install leaves a staged tree, or a tree that stepped aside for a promote
    // that did not land -- and the second reads as "nothing installed" to every
    // other function here. Until this call the leftovers were cleared by
    // whatever ran next, so the resolution was a side effect of the next
    // operation rather than a decision, and an install could be planned against
    // a prefix whose real state was a version in quarantine.
    //
    // Reported rather than done quietly: a person whose install was interrupted
    // should be told what was found, and the answer is empty on every ordinary
    // run.
    let recovered = crate::setup_core::software::recover(&root)?;

    if operation == Operation::SoftwareRemove {
        if !downloaded.is_empty() {
            return Err(Error::refuse(
                WireReason::UnsupportedOperation,
                "software_remove downloads nothing, so it takes no --software-artifact",
            ));
        }
        let removed = software::remove(&declared, &root)?;
        return Ok(serde_json::json!({
            "state": "verified",
            "recovered": recovered,
            "operation": operation.as_str(),
            "command": declared.command,
            "version": declared.version,
            "removed": removed,
        }));
    }

    // One file per entry the plan named. This build's table names one, so a
    // second file is a caller holding a plan from a different build -- which the
    // plan digest already refuses, but saying which mismatch it is costs a line.
    let [path] = downloaded else {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{operation} installs the 1 artifact the plan named, and {} were given; \
                 pass one --software-artifact per entry, in the plan's order",
                downloaded.len()
            ),
        ));
    };
    let [planned] = planned_artifacts else {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{operation} installs the 1 artifact the plan named, and the plan listed {}",
                planned_artifacts.len()
            ),
        ));
    };

    // Re-checked here, not trusted from the plan: applying happens later, and
    // the prefix could have been emptied in between. The plan's digest binds
    // what was decided, not what the disk still holds.
    if operation == Operation::SoftwareUpdate
        && software::Present::under_named(&root, declared.command, declared.member_here())
            .versions
            .is_empty()
    {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "there is no {} under {} to update any more; software_install is the operation \
                 that puts one there",
                declared.command,
                root.display()
            ),
        ));
    }

    // The plan named both the version and the artifact. Bytes that belong to
    // another pin this build publishes are still the wrong effect: they are
    // not the bytes this plan authorised. Digest-of-file remains the
    // observation; it no longer selects a neighbour release.
    let digest = crate::setup_core::digest::of_file(path)?;
    if digest != planned.sha256 {
        return Err(Error::refuse(
            WireReason::DigestMismatch,
            format!(
                "the artifact given hashes to {digest}; this plan named {} for {planned_version}",
                planned.sha256
            ),
        ));
    }
    let (os, arch) = platform_of_this_host();
    let artifact = declared.artifact_for(os, arch)?;
    if artifact.sha256 != planned.sha256 {
        return Err(Error::refuse(
            WireReason::DigestMismatch,
            format!(
                "this plan binds {planned_version} but names {}; {} publishes {}",
                planned.sha256, declared.command, artifact.sha256
            ),
        ));
    }
    let installed = software::install(&declared, artifact, path, &root)?;

    Ok(serde_json::json!({
        "state": "verified",
        "recovered": recovered,
        "operation": operation.as_str(),
        "command": declared.command,
        "version": installed.version,
        "entry_point": format!(
            "bin/{}",
            crate::setup_core::software::exposed_name(declared.command, artifact.member)
        ),
        "executable": installed.executable.to_string_lossy(),
        "files": installed.files,
    }))
}

/// Start the exact program a software install placed, replacing this process.
///
/// Not a name looked up on `PATH`: that starts whatever else shares the
/// spelling, which is the failure this command exists to avoid. The path comes
/// from the same table the plan was built from, and it must resolve to a
/// regular file this host can execute — an existing but non-executable file is
/// a refusal with a reason, not a process error surfacing from somewhere else.
///
/// On success this does not return. The caller's stdio and exit status become
/// the product's, which is what starting a program means; everything that could
/// refuse has already refused by then.
///
/// # Errors
///
/// Refuses when this build does not declare `launch`, when no `--prefix` was
/// given, when nothing is installed there, or when what is there cannot be run.
pub(crate) fn launch(
    harness: &Harness,
    target: &Path,
    prefix: Option<&Path>,
    arguments: &[String],
) -> Result<serde_json::Value> {
    if !harness.can_launch() {
        return Err(Error::refuse(
            WireReason::UnsupportedOperation,
            // The reason comes from the declaration rather than being guessed
            // from one field here. Guessing produced a refusal that told cursor
            // callers *"this build installs no software"* -- false, it installs
            // and removes it, and the actual reason is that the product follows
            // its variable for one of the seven surfaces this provider owns.
            format!(
                "{} does not declare launch: {}",
                harness.provider_id,
                harness.why_no_launch()
            ),
        ));
    }
    if harness.config_home_env.is_empty() {
        refuse_unless_documented_home(harness, target)?;
    }

    let declared = declared(harness)?;
    let root = program_directory(prefix, Operation::Launch)?;
    // The same name the plan stated and the apply wrote. Three readings of one
    // fact, and they have to be one expression or they will drift apart on the
    // one platform where they differ.
    let executable = root.join("bin").join(crate::setup_core::software::exposed_name(
        declared.command,
        declared.member_here(),
    ));

    let found = executable.metadata().map_err(|error| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} is not installed under {}: {error}; run software_install first",
                declared.command,
                root.display()
            ),
        )
    })?;
    if !found.is_file() {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!("{} is not a regular file", executable.display()),
        ));
    }
    if !is_executable(&found) {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} exists but this host cannot execute it",
                executable.display()
            ),
        ));
    }

    verify_installed(&root, declared.command, &executable)?;

    let overlay = prepare_launch_overlay(harness, target)?;

    // One of the two places in this program that may spawn, and the reason it
    // may: `launch` starts the product, which the contract declares
    // `runtime_external` rather than a local phase. The lint refuses the type
    // everywhere else so a `tar` shell-out cannot arrive quietly in an unpack.
    #[allow(
        clippy::disallowed_types,
        reason = "launch starts the product, and is declared as doing so"
    )]
    let mut command = std::process::Command::new(&executable);
    command.args(arguments);
    for (name, value) in launch_environment(harness, target, overlay.as_deref()) {
        command.env(name, value);
    }

    Err(replace_this_process(command, &executable))
}

/// Launch against a product that documents no home-override variable.
///
/// The product always reads [`Harness::documented_config_home`]. Honouring a
/// different `--target` would start it against that home while reporting that
/// the target had been used. Inventing an environment name does not change
/// what the product reads.
fn refuse_unless_documented_home(harness: &Harness, target: &Path) -> Result<()> {
    let expected = documented_home_path(harness)?;
    if same_directory(target, &expected) {
        return Ok(());
    }
    Err(Error::refuse(
        WireReason::UnsupportedOperation,
        format!(
            "{} documents no environment variable for its configuration home, so launch \
             is honest only when --target is {}; this target is not that home",
            harness.product, harness.documented_config_home
        ),
    ))
}

fn documented_home_path(harness: &Harness) -> Result<PathBuf> {
    let Some(leaf) = harness.documented_config_home.strip_prefix("~/") else {
        return Err(Error::refuse(
            WireReason::UnsupportedOperation,
            format!(
                "{} documented configuration home is not under ~/",
                harness.provider_id
            ),
        ));
    };
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .ok_or_else(|| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!(
                    "cannot resolve {} without HOME or USERPROFILE",
                    harness.documented_config_home
                ),
            )
        })?;
    Ok(PathBuf::from(home).join(leaf))
}

fn same_directory(left: &Path, right: &Path) -> bool {
    match (fs::canonicalize(left), fs::canonicalize(right)) {
        (Ok(a), Ok(b)) => a == b,
        _ => match (std::path::absolute(left), std::path::absolute(right)) {
            (Ok(a), Ok(b)) => a == b,
            _ => left == right,
        },
    }
}

/// The bytes under the exposed command are the bytes this provider installed.
///
/// `launch` checked that a file was there, that it was a regular file, and that
/// this host could execute it. None of those is a statement about *which* bytes.
/// So a product that replaced itself, a package manager that wrote over the
/// tree, or anything else with the prefix in reach was started and reported as
/// the pinned release -- and the plan that authorised the install, the digest
/// recorded beside it and the rollback to the version next door were all still
/// saying otherwise.
///
/// Read from the record `expose` writes, and the executable it names rather
/// than the exposed command: on Windows the exposure can be a `.cmd` launcher
/// holding a path rather than a copy of the program, so hashing the exposed
/// file would check the launcher.
///
/// **No record is a refusal, not a hole.** A prefix written by an earlier
/// release has none, and launching it would start a chain this build cannot
/// name. Re-run `software_install` to write a receipt, then launch.
fn verify_installed(root: &Path, command: &str, exposed: &Path) -> Result<()> {
    let manifest = match crate::setup_core::software::Manifest::inspect(root, command) {
        crate::setup_core::software::ManifestState::Missing => {
            return Err(Error::refuse(
                WireReason::ProviderUnavailable,
                format!(
                    "{} is missing; the installed chain is unresolved. \
                     Nothing has been started.",
                    crate::setup_core::software::Manifest::path(root, command).display()
                ),
            ));
        }
        crate::setup_core::software::ManifestState::Unreadable => {
            return Err(Error::refuse(
                WireReason::ProviderUnavailable,
                format!(
                    "{} exists and could not be read; the installed chain is unresolved. \
                     Nothing has been started.",
                    crate::setup_core::software::Manifest::path(root, command).display()
                ),
            ));
        }
        crate::setup_core::software::ManifestState::Malformed => {
            return Err(Error::refuse(
                WireReason::ProviderUnavailable,
                format!(
                    "{} is not a usable launch receipt; the installed chain is unresolved. \
                     Nothing has been started.",
                    crate::setup_core::software::Manifest::path(root, command).display()
                ),
            ));
        }
        crate::setup_core::software::ManifestState::Unsupported { schema_version } => {
            return Err(Error::refuse(
                WireReason::ProviderUnavailable,
                format!(
                    "{} names schema {schema_version}, which this build does not verify; \
                     the installed chain is unresolved. Nothing has been started.",
                    crate::setup_core::software::Manifest::path(root, command).display()
                ),
            ));
        }
        crate::setup_core::software::ManifestState::Present(found) => found,
    };
    let executable = root.join(&manifest.executable);
    let found = crate::setup_core::digest::of_file(&executable).map_err(|error| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} names {} and it could not be read: {error}",
                crate::setup_core::software::Manifest::path(root, command).display(),
                manifest.executable
            ),
        )
    })?;
    if found != manifest.executable_sha256 {
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} is not the {} this provider installed: recorded {}, found {}. \
                 Nothing has been started. Re-run software_install to put the pinned \
                 bytes back, or software_remove to take the prefix off.",
                manifest.executable, manifest.version, manifest.executable_sha256, found
            ),
        ));
    }
    verify_exposed_chain(exposed, &executable, &found)
}

/// The file `launch` will exec still names the payload the receipt hashed.
fn verify_exposed_chain(exposed: &Path, payload: &Path, payload_digest: &str) -> Result<()> {
    if let Ok(target) = fs::read_link(exposed) {
        let resolved = if target.is_absolute() {
            target
        } else {
            exposed.parent().unwrap_or(Path::new(".")).join(target)
        };
        let expected = payload.canonicalize().ok();
        let found = resolved.canonicalize().ok();
        if expected.is_some() && expected == found {
            return Ok(());
        }
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} no longer names {}; nothing has been started",
                exposed.display(),
                payload.display()
            ),
        ));
    }
    if exposed
        .extension()
        .is_some_and(|ext| ext == "cmd" || ext == "bat")
    {
        let wrapper = fs::read_to_string(exposed).map_err(|error| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!("{} could not be read: {error}", exposed.display()),
            )
        })?;
        let needle = payload.to_string_lossy();
        if wrapper.contains(needle.as_ref()) {
            return Ok(());
        }
        return Err(Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "{} is a launcher that does not name {}; nothing has been started",
                exposed.display(),
                payload.display()
            ),
        ));
    }
    let exposed_digest = crate::setup_core::digest::of_file(exposed).map_err(|error| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!("{} could not be read: {error}", exposed.display()),
        )
    })?;
    if exposed_digest == payload_digest {
        return Ok(());
    }
    Err(Error::refuse(
        WireReason::ProviderUnavailable,
        format!(
            "{} is not the payload recorded at {}; nothing has been started",
            exposed.display(),
            payload.display()
        ),
    ))
}

/// Everything this provider adds to the environment of the product it starts.
///
/// A function returning the pairs rather than four `command.env` calls, for the
/// reason `exposed_name_on` and `render_mode_for` are functions: a decision made
/// inline in a builder can only be *demonstrated*, and `launch` ends in an
/// `exec` that replaces this process, so a test can never look at what it set.
/// This one can be asserted.
///
/// Two entries at most:
///
/// * **the configuration home**, because every command here takes an explicit
///   `--target` and the product's own documented variable is how it is told;
/// * **the updater switch**, where the product has one.
///
/// Nothing else. Filtering another program's environment would be deciding what
/// it needs, and only its vendor knows that. The updater is the one exception
/// and it is not a decision about the product's needs: this provider pins a
/// version, records the digest of the artifact it came from, and offers a
/// rollback to the version beside it. A product that replaces those bytes while
/// running makes all three false, and this prefix is a distribution channel its
/// vendor did not build.
fn launch_environment(
    harness: &Harness,
    target: &Path,
    overlay: Option<&Path>,
) -> Vec<(&'static str, String)> {
    let mut pairs = Vec::new();
    if !harness.config_home_env.is_empty() {
        pairs.push((
            harness.config_home_env,
            target.to_string_lossy().into_owned(),
        ));
    }
    if !harness.updates_off_env.is_empty() {
        pairs.push((harness.updates_off_env, "1".to_owned()));
    }
    if let Some(home) = overlay {
        let home = home.to_string_lossy().into_owned();
        pairs.push(("HOME", home.clone()));
        if cfg!(windows) {
            pairs.push(("USERPROFILE", home));
        }
    }
    pairs
}

/// Materialise process-home surfaces from `--target` into a child-only home.
///
/// Cursor joins `rules`, `commands`, `hooks.json`, `mcp.json`, `plugins/local`
/// and `skills` to `homedir()/.cursor`, ignoring `CURSOR_CONFIG_DIR`. Copying
/// those files into `{target}/{control}/launch-home/.cursor` and pointing only
/// the child `HOME` there makes the selected setup what `homedir()` resolves,
/// without writing the caller's home.
pub(crate) fn prepare_launch_overlay(
    harness: &Harness,
    target: &Path,
) -> Result<Option<std::path::PathBuf>> {
    let LaunchBinding::Partial { home_rooted, .. } = harness.launch_binding else {
        return Ok(None);
    };
    if home_rooted.is_empty() {
        return Ok(None);
    }
    let Some(leaf) = harness.documented_config_home.strip_prefix("~/") else {
        return Err(Error::refuse(
            WireReason::UnsupportedOperation,
            format!(
                "{} names process-home surfaces but its documented config home is not under ~/",
                harness.provider_id
            ),
        ));
    };
    let overlay = target.join(harness.control_directory).join("launch-home");
    let rooted = overlay.join(leaf);
    if rooted.exists() {
        crate::setup_core::lock::remove_dir_all(&rooted).map_err(|error| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!("cannot reset {}: {error}", rooted.display()),
            )
        })?;
    }
    fs::create_dir_all(&rooted).map_err(|error| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!("cannot create {}: {error}", rooted.display()),
        )
    })?;
    for relative in home_rooted {
        let from = target.join(relative);
        if !from.exists() {
            continue;
        }
        let to = rooted.join(relative);
        copy_owned(&from, &to)?;
    }
    Ok(Some(overlay))
}

fn copy_owned(from: &Path, to: &Path) -> Result<()> {
    if from.is_dir() {
        fs::create_dir_all(to).map_err(|error| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!("cannot create {}: {error}", to.display()),
            )
        })?;
        let read = fs::read_dir(from).map_err(|error| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!("cannot list {}: {error}", from.display()),
            )
        })?;
        for entry in read.flatten() {
            copy_owned(&entry.path(), &to.join(entry.file_name()))?;
        }
        return Ok(());
    }
    if let Some(parent) = to.parent() {
        fs::create_dir_all(parent).map_err(|error| {
            Error::refuse(
                WireReason::ProviderUnavailable,
                format!("cannot create {}: {error}", parent.display()),
            )
        })?;
    }
    fs::copy(from, to).map_err(|error| {
        Error::refuse(
            WireReason::ProviderUnavailable,
            format!(
                "cannot copy {} to {}: {error}",
                from.display(),
                to.display()
            ),
        )
    })?;
    Ok(())
}

/// Whether the mode bits say this host can run it.
#[cfg(unix)]
fn is_executable(found: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::MetadataExt;
    found.mode() & 0o111 != 0
}

/// Windows decides by extension, not by a mode bit there is none of.
#[cfg(not(unix))]
fn is_executable(_found: &std::fs::Metadata) -> bool {
    true
}

/// Hand this process to the product, and only return if that failed.
#[cfg(unix)]
#[allow(
    clippy::disallowed_types,
    reason = "the command `launch` built, handed to exec"
)]
fn replace_this_process(mut command: std::process::Command, executable: &Path) -> Error {
    use std::os::unix::process::CommandExt;
    // `exec` returns only on failure. The product inherits this process, so its
    // stdio and its exit status are the ones the caller sees, with nothing of
    // this program's left in between.
    let failure = command.exec();
    Error::refuse(
        WireReason::ProviderUnavailable,
        format!("{} could not be started: {failure}", executable.display()),
    )
}

/// Windows has no `exec`, so the status is carried back by hand.
#[cfg(not(unix))]
fn replace_this_process(mut command: std::process::Command, executable: &Path) -> Error {
    match command.status() {
        Ok(status) => std::process::exit(status.code().unwrap_or(1)),
        Err(failure) => Error::refuse(
            WireReason::ProviderUnavailable,
            format!("{} could not be started: {failure}", executable.display()),
        ),
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::panic)]

    use std::fs;

    use super::*;

    /// A launch refuses bytes that are not the ones this provider installed.
    ///
    /// `launch` checked existence, file-ness and an executable bit, none of
    /// which says *which* bytes. `DISABLE_UPDATES` closed the product's own way
    /// of replacing them; nothing closed anybody else's.
    ///
    /// Four states, because collapsing any of them into "no receipt" would
    /// start a program whose chain this build cannot name:
    ///
    /// * the recorded bytes -- accepted;
    /// * one byte different -- refused, naming both digests;
    /// * no record at all -- refused as missing, distinct from corrupt;
    /// * a present record that cannot be read, parsed, or verified -- refused
    ///   under that state's own sentence.
    #[test]
    fn a_launch_refuses_an_executable_that_is_not_the_one_installed() {
        let root = std::env::temp_dir().join(format!(
            "harness-runtime-verify-{}-{}",
            std::process::id(),
            line!()
        ));
        let _ = fs::remove_dir_all(&root);
        let version = root.join("1.2.3");
        fs::create_dir_all(&version).unwrap();
        fs::create_dir_all(root.join("bin")).unwrap();
        let executable = version.join("program");
        fs::write(&executable, b"the installed bytes\n").unwrap();
        let exposed = root.join("bin").join("program");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&executable, &exposed).unwrap();
        #[cfg(not(unix))]
        fs::copy(&executable, &exposed).unwrap();

        let missing = verify_installed(&root, "program", &exposed).unwrap_err();
        assert!(
            missing.detail().contains("is missing"),
            "a prefix with no record must fail as missing, not as a silent skip: {}",
            missing.detail()
        );

        let manifest = crate::setup_core::software::Manifest {
            schema_version: 1,
            version: "1.2.3".to_owned(),
            executable: "1.2.3/program".to_owned(),
            executable_sha256: crate::setup_core::digest::of_file(&executable).unwrap(),
        };
        fs::write(
            crate::setup_core::software::Manifest::path(&root, "program"),
            serde_json::to_vec(&manifest).unwrap(),
        )
        .unwrap();
        assert!(
            verify_installed(&root, "program", &exposed).is_ok(),
            "the bytes named by the record were refused"
        );

        fs::write(&executable, b"the installed bytes?\n").unwrap();
        let refused = verify_installed(&root, "program", &exposed).unwrap_err();
        assert_eq!(refused.reason(), Some(WireReason::ProviderUnavailable));
        assert!(
            refused.detail().contains("recorded") && refused.detail().contains("found"),
            "the refusal does not say which digest was expected: {}",
            refused.detail()
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_corrupt_or_unsupported_manifest_is_not_a_verified_launch() {
        let root = std::env::temp_dir().join(format!(
            "harness-runtime-verify-corrupt-{}-{}",
            std::process::id(),
            line!()
        ));
        let _ = fs::remove_dir_all(&root);
        let version = root.join("1.2.3");
        fs::create_dir_all(&version).unwrap();
        fs::create_dir_all(root.join("bin")).unwrap();
        let executable = version.join("program");
        fs::write(&executable, b"the installed bytes\n").unwrap();
        let exposed = root.join("bin").join("program");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&executable, &exposed).unwrap();
        #[cfg(not(unix))]
        fs::copy(&executable, &exposed).unwrap();
        let path = crate::setup_core::software::Manifest::path(&root, "program");

        fs::write(&path, b"{not a manifest").unwrap();
        let malformed = verify_installed(&root, "program", &exposed).unwrap_err();
        assert!(
            malformed.detail().contains("not a usable launch receipt"),
            "{}",
            malformed.detail()
        );

        fs::write(
            &path,
            serde_json::to_vec(&crate::setup_core::software::Manifest {
                schema_version: 2,
                version: "1.2.3".to_owned(),
                executable: "1.2.3/program".to_owned(),
                executable_sha256: crate::setup_core::digest::of_file(&executable).unwrap(),
            })
            .unwrap(),
        )
        .unwrap();
        let unsupported = verify_installed(&root, "program", &exposed).unwrap_err();
        assert!(
            unsupported.detail().contains("schema 2"),
            "{}",
            unsupported.detail()
        );

        fs::write(
            &path,
            serde_json::to_vec(&crate::setup_core::software::Manifest {
                schema_version: 1,
                version: "1.2.3".to_owned(),
                executable: "1.2.3/program".to_owned(),
                executable_sha256: crate::setup_core::digest::of_file(&executable).unwrap(),
            })
            .unwrap(),
        )
        .unwrap();
        #[cfg(unix)]
        {
            let other = version.join("other");
            fs::write(&other, b"the installed bytes\n").unwrap();
            fs::remove_file(&exposed).unwrap();
            std::os::unix::fs::symlink(&other, &exposed).unwrap();
            let drifted = verify_installed(&root, "program", &exposed).unwrap_err();
            assert!(
                drifted.detail().contains("no longer names"),
                "{}",
                drifted.detail()
            );
        }

        let _ = fs::remove_dir_all(&root);
    }

    /// A launch adds the target and, where the product has one, the updater switch.
    ///
    /// The switch exists because this provider's three strongest statements
    /// about an installation -- the version it pins, the digest of the artifact
    /// it came from, and the rollback to the version beside it -- are all false
    /// the moment the product replaces those bytes itself. Anthropic documents
    /// the variable for exactly this case, a distribution channel somebody else
    /// controls, and the 2.1.251 artifact carries it nine times.
    ///
    /// Both directions, because only the pair says anything. A build that added
    /// the variable to every launch would pass the first assertion while setting
    /// a name nothing reads on six products, and a build that added it to none
    /// would pass the second.
    #[test]
    fn a_launch_sets_the_updater_switch_only_where_the_product_has_one() {
        let target = Path::new("/tmp/nddev-launch-environment");

        let with = Harness {
            config_home_env: "PRODUCT_CONFIG_DIR",
            updates_off_env: "DISABLE_UPDATES",
            ..crate::harness_runtime::wire::tests_support::TEST
        };
        assert_eq!(
            launch_environment(&with, target, None),
            vec![
                ("PRODUCT_CONFIG_DIR", target.display().to_string()),
                ("DISABLE_UPDATES", "1".to_owned()),
            ]
        );

        let without = Harness {
            config_home_env: "PRODUCT_CONFIG_DIR",
            updates_off_env: "",
            ..crate::harness_runtime::wire::tests_support::TEST
        };
        assert_eq!(
            launch_environment(&without, target, None),
            vec![("PRODUCT_CONFIG_DIR", target.display().to_string())],
            "a product with no such variable had its environment written to anyway"
        );

        let documented = Harness {
            config_home_env: "",
            updates_off_env: "",
            launch_binding: LaunchBinding::DocumentedHome { how: "measured" },
            ..crate::harness_runtime::wire::tests_support::TEST
        };
        assert_eq!(
            launch_environment(&documented, target, None),
            Vec::<(&str, String)>::new(),
            "an empty config-home variable must not be written into the child environment"
        );
    }

    #[test]
    fn documented_home_launch_refuses_an_alternate_root_by_name() {
        let harness = Harness {
            config_home_env: "",
            launch_binding: LaunchBinding::DocumentedHome {
                how: "the product always reads ~/.test",
            },
            documented_config_home: "~/.test",
            ..crate::harness_runtime::wire::tests_support::TEST
        };
        assert!(harness.can_launch());
        let elsewhere = std::env::temp_dir().join(format!(
            "harness-runtime-not-documented-home-{}",
            std::process::id()
        ));
        let _ = fs::create_dir_all(&elsewhere);
        let error = launch(&harness, &elsewhere, None, &[]).unwrap_err();
        let _ = fs::remove_dir_all(&elsewhere);
        assert_eq!(error.reason(), Some(WireReason::UnsupportedOperation));
        assert!(
            error.detail().contains("this target is not that home"),
            "{}",
            error.detail()
        );
        assert!(error.detail().contains("~/.test"), "{}", error.detail());
    }

    #[test]
    fn documented_home_launch_accepts_the_resolved_home() {
        let harness = Harness {
            config_home_env: "",
            launch_binding: LaunchBinding::DocumentedHome {
                how: "the product always reads ~/.test",
            },
            documented_config_home: "~/.test",
            ..crate::harness_runtime::wire::tests_support::TEST
        };
        let target = documented_home_path(&harness).unwrap();
        refuse_unless_documented_home(&harness, &target).unwrap();
    }

    fn planted_prefix(tag: &str) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
        let root = std::env::temp_dir().join(format!(
            "harness-runtime-launch-{tag}-{}",
            std::process::id(),
        ));
        let _ = fs::remove_dir_all(&root);
        let version = root.join("1.2.3");
        fs::create_dir_all(&version).unwrap();
        fs::create_dir_all(root.join("bin")).unwrap();
        let payload = version.join("test-harness");
        fs::write(&payload, crate::harness_runtime::wire::tests_support::TEST_PAYLOAD).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&payload, fs::Permissions::from_mode(0o755)).unwrap();
        }
        let exposed = root.join("bin").join("test-harness");
        #[cfg(unix)]
        std::os::unix::fs::symlink(&payload, &exposed).unwrap();
        #[cfg(not(unix))]
        fs::copy(&payload, &exposed).unwrap();
        (root, payload, exposed)
    }

    #[test]
    fn launch_refuses_missing_unreadable_malformed_and_unsupported_receipts_as_distinct_states() {
        let target = Path::new("/tmp/nddev-launch-verify-target");
        let (root, payload, exposed) = planted_prefix("receipts");
        let path = crate::setup_core::software::Manifest::path(&root, "test-harness");

        let missing =
            launch(&crate::harness_runtime::wire::tests_support::TEST, target, Some(&root), &[]).unwrap_err();
        assert!(
            missing.detail().contains("is missing"),
            "{}",
            missing.detail()
        );

        fs::write(&path, b"{not a manifest").unwrap();
        let malformed =
            launch(&crate::harness_runtime::wire::tests_support::TEST, target, Some(&root), &[]).unwrap_err();
        assert!(
            malformed.detail().contains("not a usable launch receipt"),
            "{}",
            malformed.detail()
        );

        fs::write(
            &path,
            serde_json::to_vec(&crate::setup_core::software::Manifest {
                schema_version: 2,
                version: "1.2.3".to_owned(),
                executable: "1.2.3/test-harness".to_owned(),
                executable_sha256: crate::setup_core::digest::of_file(&payload).unwrap(),
            })
            .unwrap(),
        )
        .unwrap();
        let unsupported =
            launch(&crate::harness_runtime::wire::tests_support::TEST, target, Some(&root), &[]).unwrap_err();
        assert!(
            unsupported.detail().contains("schema 2"),
            "{}",
            unsupported.detail()
        );

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::write(
                &path,
                serde_json::to_vec(&crate::setup_core::software::Manifest {
                    schema_version: 1,
                    version: "1.2.3".to_owned(),
                    executable: "1.2.3/test-harness".to_owned(),
                    executable_sha256: crate::setup_core::digest::of_file(&payload).unwrap(),
                })
                .unwrap(),
            )
            .unwrap();
            fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).unwrap();
            let unreadable =
                launch(&crate::harness_runtime::wire::tests_support::TEST, target, Some(&root), &[]).unwrap_err();
            fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
            assert!(
                unreadable.detail().contains("could not be read"),
                "{}",
                unreadable.detail()
            );
        }

        let _ = fs::remove_dir_all(&root);
        let _ = exposed;
    }

    #[test]
    fn launch_refuses_another_valid_pin_substituted_for_the_recorded_payload() {
        let target = Path::new("/tmp/nddev-launch-pin-swap-target");
        let (root, payload, exposed) = planted_prefix("pin-swap");
        let digest = crate::setup_core::digest::of_file(&payload).unwrap();
        fs::write(
            crate::setup_core::software::Manifest::path(&root, "test-harness"),
            serde_json::to_vec(&crate::setup_core::software::Manifest {
                schema_version: 1,
                version: "1.2.3".to_owned(),
                executable: "1.2.3/test-harness".to_owned(),
                executable_sha256: digest,
            })
            .unwrap(),
        )
        .unwrap();
        fs::write(&payload, crate::harness_runtime::wire::tests_support::TEST_EARLIER_PAYLOAD).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&payload, fs::Permissions::from_mode(0o755)).unwrap();
        }
        let swapped =
            launch(&crate::harness_runtime::wire::tests_support::TEST, target, Some(&root), &[]).unwrap_err();
        assert!(
            swapped.detail().contains("recorded") && swapped.detail().contains("found"),
            "{}",
            swapped.detail()
        );
        let _ = fs::remove_dir_all(&root);
        let _ = exposed;
    }

    #[test]
    fn launch_refuses_a_windows_wrapper_that_does_not_name_the_recorded_payload() {
        let root = std::env::temp_dir().join(format!(
            "harness-runtime-wrapper-{}-{}",
            std::process::id(),
            line!()
        ));
        let _ = fs::remove_dir_all(&root);
        let version = root.join("1.2.3");
        fs::create_dir_all(&version).unwrap();
        fs::create_dir_all(root.join("bin")).unwrap();
        let payload = version.join("test-harness.exe");
        fs::write(&payload, b"payload-bytes\n").unwrap();
        let wrapper = root.join("bin").join("test-harness.cmd");
        fs::write(&wrapper, "@call \"C:\\other\\test-harness.exe\" %*\r\n").unwrap();
        fs::write(
            crate::setup_core::software::Manifest::path(&root, "test-harness"),
            serde_json::to_vec(&crate::setup_core::software::Manifest {
                schema_version: 1,
                version: "1.2.3".to_owned(),
                executable: "1.2.3/test-harness.exe".to_owned(),
                executable_sha256: crate::setup_core::digest::of_file(&payload).unwrap(),
            })
            .unwrap(),
        )
        .unwrap();
        let refused = verify_installed(&root, "test-harness", &wrapper).unwrap_err();
        assert!(
            refused.detail().contains("does not name"),
            "{}",
            refused.detail()
        );
        let _ = fs::remove_dir_all(&root);
    }

    fn cursor_like() -> Harness {
        Harness {
            documented_config_home: "~/.cursor",
            config_home_env: "CURSOR_CONFIG_DIR",
            control_directory: ".cursor-setup-system",
            launch_binding: LaunchBinding::Partial {
                unbound: "rules, hooks.json",
                home_rooted: &["rules", "hooks.json", "skills"],
            },
            ..crate::harness_runtime::wire::tests_support::TEST
        }
    }

    /// Process-home surfaces come from `--target`, not from the caller's home.
    ///
    /// `cli-config.json` follows `CURSOR_CONFIG_DIR` and must stay at the
    /// target. Overlaying it under `.cursor/` would duplicate the bound file
    /// and still leave rules/hooks coming from the caller.
    #[test]
    fn launch_overlay_copies_home_rooted_surfaces_from_the_target_not_the_caller() {
        let root = std::env::temp_dir().join(format!(
            "harness-runtime-overlay-{}-{}",
            std::process::id(),
            line!()
        ));
        let _ = fs::remove_dir_all(&root);
        let target = root.join("target");
        let caller = root.join("caller-home");
        fs::create_dir_all(target.join("rules")).unwrap();
        fs::write(target.join("rules").join("a.mdc"), "from-target\n").unwrap();
        fs::write(target.join("hooks.json"), "{\"from\":\"target\"}\n").unwrap();
        fs::write(
            target.join("cli-config.json"),
            "{\"approvalMode\":\"unrestricted\"}\n",
        )
        .unwrap();
        fs::create_dir_all(caller.join(".cursor").join("rules")).unwrap();
        fs::write(
            caller.join(".cursor").join("rules").join("a.mdc"),
            "from-caller\n",
        )
        .unwrap();

        let harness = cursor_like();
        let overlay = prepare_launch_overlay(&harness, &target).unwrap().unwrap();
        assert_eq!(
            overlay,
            target.join(".cursor-setup-system").join("launch-home")
        );
        let cursor_leaf = overlay.join(".cursor");
        assert_eq!(
            fs::read_to_string(cursor_leaf.join("rules").join("a.mdc")).unwrap(),
            "from-target\n"
        );
        assert_eq!(
            fs::read_to_string(cursor_leaf.join("hooks.json")).unwrap(),
            "{\"from\":\"target\"}\n"
        );
        assert!(
            !cursor_leaf.join("cli-config.json").exists(),
            "bound cli-config.json was copied into the process-home leaf"
        );
        assert_eq!(
            fs::read_to_string(caller.join(".cursor").join("rules").join("a.mdc")).unwrap(),
            "from-caller\n",
            "the caller's home was written"
        );

        let env = launch_environment(&harness, &target, Some(&overlay));
        assert!(env.contains(&("CURSOR_CONFIG_DIR", target.display().to_string())));
        assert!(env.contains(&("HOME", overlay.display().to_string())));
        assert!(
            !env.iter()
                .any(|(name, value)| *name == "HOME" && Path::new(value) == caller)
        );

        let _ = fs::remove_dir_all(&root);
    }
}