tapes-harnesses 0.1.0

Shared, open-source client-side harness knowledge for Tapes capture: the harness registry, launch recipes, config patch grammars, plugin artifacts, per-harness session attribution, and transcript discovery.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
//! Codex's own plugin manager: the source layout it consumes and the `codex`
//! subcommands that register and install from it.
//!
//! [`super`] renders the two manifests a hook plugin *is*. Neither is
//! installable on its own: Codex installs a plugin from a **marketplace**, a
//! directory whose `.agents/plugins/marketplace.json` offers one or more
//! plugins as local sources, and it installs *by running its own CLI*. So a
//! consumer that only had the templates could write a tree and then had to
//! tell the user to finish the job by hand.
//!
//! Everything needed to finish it lives here, and it is all Codex knowledge
//! rather than any consumer's:
//!
//! * **The wrapper.** [`MARKETPLACE_MANIFEST_TEMPLATE`] and the paths under
//!   [`plugin_source_dir`] are the layout `codex plugin marketplace add`
//!   walks. A consumer supplies two names and gets the tree Codex reads.
//! * **The invocation.** [`PluginManager::register`] runs the two commands in
//!   order and interprets the answers.
//! * **The quirks.** Codex reports "this is already done" as a *failure* with
//!   a distinguishing phrase on stderr, and it refuses a same-named
//!   marketplace pointing at a different directory. Recognising those answers
//!   is the difference between an install that completes and one that reports
//!   a spurious error, and it is the bulk of what this module knows.
//!
//! # Observed behaviour, and why it is guarded
//!
//! The collision and refresh semantics below were verified against
//! codex-cli 0.146.0. They are matched on stderr *phrases* because the CLI
//! offers nothing better — no machine-readable status, no distinct exit code.
//! Every phrase check therefore only ever reinterprets a **failure**, and only
//! against the specific phrasings observed, so a CLI whose wording moves
//! degrades to an honest failure plus [`PluginManager::manual_commands`]
//! rather than to a silent wrong answer.
//!
//! # What stays with the consumer
//!
//! Bytes on disk and words on a terminal. This module never writes a file,
//! never reads one, and never prints: it takes a marketplace root that already
//! exists and hands back outcomes. Whether a consumer extracts an embedded
//! bundle or renders one, how it records what it has delivered, and how it
//! narrates any of that are its own.

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

use super::{render_slots, shell_quote};

/// Slot in [`MARKETPLACE_MANIFEST_TEMPLATE`] for the marketplace name — the
/// name `codex plugin marketplace remove` takes and the right-hand side of a
/// `<plugin>@<marketplace>` spec.
pub const MARKETPLACE_NAME_SLOT: &str = "__TAPES_MARKETPLACE_NAME__";

/// Slot for the marketplace's display name, shown when the app lists sources.
pub const MARKETPLACE_DISPLAY_NAME_SLOT: &str = "__TAPES_MARKETPLACE_DISPLAY_NAME__";

/// Slot for the offered plugin's name. The same spelling
/// [`super::PLUGIN_MANIFEST_TEMPLATE`] uses, because it must hold the same
/// value: Codex resolves the offer against the plugin manifest's `name`.
pub const MARKETPLACE_PLUGIN_NAME_SLOT: &str = "__TAPES_PLUGIN_NAME__";

/// Slot for the offered plugin's source path, relative to the marketplace
/// root. Its own slot rather than text spliced around
/// [`MARKETPLACE_PLUGIN_NAME_SLOT`] so substitution stays whole-value and
/// JSON-escaped, exactly as every other slot in this crate is.
pub const MARKETPLACE_PLUGIN_SOURCE_PATH_SLOT: &str = "__TAPES_PLUGIN_SOURCE_PATH__";

/// The marketplace manifest template — [`MARKETPLACE_MANIFEST_PATH`] in the
/// packaged tree.
///
/// One local-source plugin, installable on request and authenticated when it
/// is installed. A marketplace may offer several plugins; this template offers
/// exactly one, which is the shape a capture client needs and the only shape
/// the path helpers here describe.
pub const MARKETPLACE_MANIFEST_TEMPLATE: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/codex-app/marketplace.json"
));

/// Where [`MARKETPLACE_MANIFEST_TEMPLATE`] is written, relative to the
/// marketplace root a consumer hands `codex plugin marketplace add`.
pub const MARKETPLACE_MANIFEST_PATH: &str = ".agents/plugins/marketplace.json";

/// The two names a marketplace manifest carries, plus the display string the
/// app shows for the source.
///
/// `#[non_exhaustive]` for the reason [`super::HookPluginIdentity`] is; build
/// one with [`MarketplaceIdentity::new`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct MarketplaceIdentity<'a> {
    /// The marketplace name. Codex keys a registered source on it, so two
    /// consumers choosing the same name collide on one machine — see
    /// [`MarketplaceOutcome::Replaced`].
    pub name: &'a str,
    /// The offered plugin's name, which must equal the `name` in the plugin
    /// manifest rendered by [`super::render_plugin_manifest`].
    pub plugin_name: &'a str,
    /// Display name for the source in the app's marketplace list.
    pub display_name: &'a str,
}

impl<'a> MarketplaceIdentity<'a> {
    /// A marketplace offering exactly `plugin_name`, displayed under `name`
    /// until [`Self::with_display_name`] says otherwise.
    #[must_use]
    pub const fn new(name: &'a str, plugin_name: &'a str) -> Self {
        Self {
            name,
            plugin_name,
            display_name: name,
        }
    }

    /// Set the display name shown for the source.
    #[must_use]
    pub const fn with_display_name(mut self, display_name: &'a str) -> Self {
        self.display_name = display_name;
        self
    }
}

/// The plugin's source directory, relative to the marketplace root.
#[must_use]
pub fn plugin_source_dir(plugin_name: &str) -> PathBuf {
    Path::new("plugins").join(plugin_name)
}

/// Where [`super::render_plugin_manifest`]'s output is written, relative to
/// the marketplace root.
#[must_use]
pub fn plugin_manifest_path(plugin_name: &str) -> PathBuf {
    plugin_source_dir(plugin_name)
        .join(".codex-plugin")
        .join("plugin.json")
}

/// Where [`super::render_hooks_manifest`]'s output is written, relative to the
/// marketplace root. This is Codex's *default* hooks location, which is why a
/// rendered plugin manifest declares no `hooks` override.
#[must_use]
pub fn hooks_manifest_path(plugin_name: &str) -> PathBuf {
    plugin_source_dir(plugin_name)
        .join("hooks")
        .join("hooks.json")
}

/// The `<plugin>@<marketplace>` spec `codex plugin add` and
/// `codex plugin remove` take, and the key Codex records enablement under in
/// its `config.toml`.
#[must_use]
pub fn plugin_spec(plugin_name: &str, marketplace_name: &str) -> String {
    format!("{plugin_name}@{marketplace_name}")
}

/// Render the marketplace manifest around a consumer's names.
///
/// The source path is derived from the plugin name rather than accepted as a
/// parameter: it must agree with [`plugin_source_dir`], and a manifest whose
/// path points anywhere else installs nothing.
#[must_use]
pub fn render_marketplace_manifest(identity: &MarketplaceIdentity) -> String {
    let source_path = format!("./{}", plugin_source_dir(identity.plugin_name).display());
    render_slots(
        MARKETPLACE_MANIFEST_TEMPLATE,
        &[
            (MARKETPLACE_NAME_SLOT, identity.name),
            (MARKETPLACE_DISPLAY_NAME_SLOT, identity.display_name),
            (MARKETPLACE_PLUGIN_NAME_SLOT, identity.plugin_name),
            (MARKETPLACE_PLUGIN_SOURCE_PATH_SLOT, &source_path),
        ],
    )
}

/// Whether Codex's `config.toml` marks `plugin_spec` explicitly disabled.
///
/// Deliberately forgiving: unparseable text, an absent table, or an absent key
/// all read as "not disabled", because the question this answers is only
/// "would installing override a choice the user made in the app", and the
/// cost of guessing wrong toward `false` is an install the user asked for.
///
/// Text in, no filesystem — resolving `$CODEX_HOME` and reading the file stay
/// with the consumer, as they do for [`crate::config::codex`].
#[must_use]
pub fn plugin_disabled_in_config(config_text: &str, plugin_spec: &str) -> bool {
    use toml_edit::{Document, Item};

    let Ok(document) = config_text.parse::<Document>() else {
        return false;
    };
    document
        .get("plugins")
        .and_then(Item::as_table_like)
        .and_then(|plugins| plugins.get(plugin_spec))
        .and_then(Item::as_table_like)
        .and_then(|plugin| plugin.get("enabled"))
        .and_then(Item::as_bool)
        == Some(false)
}

/// What a registration run must accomplish on Codex's side.
///
/// The distinction exists because an "already installed" answer is only
/// trustworthy when the caller knows the *current* bytes are what Codex
/// cached. Which of these applies is the consumer's bookkeeping; what each
/// one makes the CLI do is this module's.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InstallGoal {
    /// Nothing is known to have been delivered. An existing install is of
    /// unknown provenance — a copy from someone's source checkout, or an
    /// older release — so "already installed" cannot be believed and the
    /// cached copy is forced fresh.
    Install,
    /// A *different* set of bytes was delivered before. Codex's cached copy
    /// is known stale and must be re-copied.
    Refresh,
    /// These exact bytes were delivered and confirmed. "Already installed" is
    /// trustworthy and nothing is forced.
    Verify,
}

/// Outcome of registering the marketplace source.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarketplaceOutcome {
    /// `codex plugin marketplace add` exited 0.
    Added,
    /// It failed, saying this source is already registered.
    AlreadyAdded,
    /// A marketplace of the same name pointed at a **different** directory
    /// (the state of any machine that registered the plugin from a source
    /// checkout). It was removed and re-added from the caller's root.
    ///
    /// Replacing is safe in Codex's model: removing a marketplace does not
    /// uninstall the plugins installed from it, so the install survives and
    /// the following `plugin add` re-copies it from the new root.
    Replaced {
        /// The name whose previous registration was replaced.
        marketplace_name: String,
    },
    /// The step failed for a real reason.
    Failed {
        /// The CLI's own words, flattened and bounded.
        detail: String,
    },
}

impl MarketplaceOutcome {
    /// One line naming what happened, for a consumer's summary.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            Self::Added => "added".to_owned(),
            Self::AlreadyAdded => "already added".to_owned(),
            Self::Replaced { marketplace_name } => format!(
                "replaced an existing '{marketplace_name}' marketplace that pointed at a \
                 different source"
            ),
            Self::Failed { detail } => format!("failed: {detail}"),
        }
    }

    /// Whether the plugin step must be skipped: there is no source to install
    /// from.
    #[must_use]
    pub fn failed(&self) -> bool {
        matches!(self, Self::Failed { .. })
    }
}

/// Outcome of installing or refreshing the plugin.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum InstallOutcome {
    /// `codex plugin add` succeeded with nothing known to be stale.
    Installed,
    /// The caller knew the current bytes were delivered and the CLI agrees an
    /// install exists.
    AlreadyInstalled,
    /// Codex's cached copy was re-copied from the marketplace root.
    Refreshed,
    /// The step failed; whatever was installed before is still installed.
    Failed {
        /// The CLI's own words, flattened and bounded.
        detail: String,
    },
    /// The forced refresh removed the untrusted install and then failed to
    /// re-add it: the plugin is currently **not** installed, which is the one
    /// outcome a consumer must say out loud.
    RemovedNotReinstalled {
        /// The CLI's own words, flattened and bounded.
        detail: String,
    },
    /// The step never ran because the marketplace step failed.
    Skipped,
}

impl InstallOutcome {
    /// One line naming what happened, for a consumer's summary.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            Self::Installed => "installed".to_owned(),
            Self::AlreadyInstalled => "already installed".to_owned(),
            Self::Refreshed => "refreshed to the new bundled version".to_owned(),
            Self::Failed { detail } | Self::RemovedNotReinstalled { detail } => {
                format!("failed: {detail}")
            }
            Self::Skipped => "skipped (marketplace registration failed)".to_owned(),
        }
    }

    /// Whether the consumer's summary should print
    /// [`PluginManager::manual_commands`].
    #[must_use]
    pub fn needs_manual_retry(&self) -> bool {
        matches!(
            self,
            Self::Failed { .. } | Self::RemovedNotReinstalled { .. } | Self::Skipped
        )
    }

    /// Whether this run **confirmed** that Codex's cache now holds the bytes
    /// under the marketplace root — the only outcomes a consumer may record as
    /// delivered.
    #[must_use]
    pub fn confirmed_delivery(&self) -> bool {
        matches!(self, Self::Installed | Self::Refreshed)
    }
}

/// What one [`PluginManager::register`] run found, distinguishing "there is no
/// CLI here at all" from per-step outcomes so a summary never fakes success.
///
/// Deliberately *not* `#[non_exhaustive]`, unlike the outcome enums it holds:
/// the variants here are the closed set of reasons a run ends, and every
/// consumer must branch on all of them. Forcing a wildcard arm would only
/// invite one that silently swallowed a case with real consequences — adding
/// [`Self::SkippedDisabled`] here deliberately broke both consumers rather
/// than letting them keep reporting an install that no longer happens. The
/// outcomes inside [`Self::Steps`] stay open, because Codex can always give a
/// new answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ManagerRun {
    /// The `codex` program does not exist. Nothing ran and nothing is known;
    /// a consumer prints [`PluginManager::manual_commands`] and leaves its
    /// own delivery bookkeeping untouched.
    CliAbsent,
    /// The caller reported the plugin disabled in Codex's config, so nothing
    /// ran at all — see [`SKIPPED_DISABLED_REASON`].
    ///
    /// A sibling of [`Self::CliAbsent`] rather than an install outcome,
    /// because "disabled" is not a fact about the install step. Registering
    /// the marketplace can *replace* a same-named source belonging to someone
    /// else, and doing that to serve an install that is then not performed is
    /// a destructive act taken behind the back of a user who already said no.
    /// Nothing runs, so nothing — not even the existence of the CLI — is
    /// learned.
    SkippedDisabled,
    /// The CLI ran. Each step reports its own outcome.
    Steps {
        /// Registering the marketplace source.
        marketplace: MarketplaceOutcome,
        /// Installing or refreshing the plugin.
        install: InstallOutcome,
    },
}

/// Why [`ManagerRun::SkippedDisabled`] happened, in words a consumer can print.
///
/// Shared so both clients say the same thing about the same Codex behaviour:
/// `codex plugin add` sets `enabled = true`, so installing over a disabled
/// plugin would silently reverse a choice the user made in the app.
pub const SKIPPED_DISABLED_REASON: &str = "the plugin is disabled in Codex config; enable it in the app, then install again \
     (installing now would force-re-enable it)";

/// One packaged plugin, and the `codex` binary that manages it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginManager {
    codex_program: PathBuf,
    marketplace_root: PathBuf,
    marketplace_name: String,
    plugin_name: String,
}

impl PluginManager {
    /// Manage `plugin_name`, offered by the marketplace at `marketplace_root`
    /// under `marketplace_name`, through the `codex` binary at
    /// `codex_program`.
    ///
    /// `codex_program` is a parameter rather than the literal `codex` so a
    /// test can inject a shim; production callers pass the bare name and let
    /// `PATH` resolve it. Child processes inherit the caller's environment, so
    /// `$CODEX_HOME` resolves the same for the CLI as for the caller — pinning
    /// it here would only risk desynchronising from a future CLI change.
    #[must_use]
    pub fn new(
        codex_program: impl Into<PathBuf>,
        marketplace_root: impl Into<PathBuf>,
        marketplace_name: impl Into<String>,
        plugin_name: impl Into<String>,
    ) -> Self {
        Self {
            codex_program: codex_program.into(),
            marketplace_root: marketplace_root.into(),
            marketplace_name: marketplace_name.into(),
            plugin_name: plugin_name.into(),
        }
    }

    /// The directory `codex plugin marketplace add` is pointed at.
    #[must_use]
    pub fn marketplace_root(&self) -> &Path {
        &self.marketplace_root
    }

    /// The `<plugin>@<marketplace>` spec this manager installs.
    #[must_use]
    pub fn plugin_spec(&self) -> String {
        plugin_spec(&self.plugin_name, &self.marketplace_name)
    }

    /// The two commands, in order, that [`Self::register`] runs — the exact
    /// text to print when there is no CLI to run them with, or when a step
    /// failed and the user must retry by hand.
    /// Every argument is shell-quoted, because this text exists to be pasted
    /// into a shell: a marketplace root under a home directory with a space in
    /// it would otherwise register a different — probably nonexistent —
    /// directory, without saying so.
    #[must_use]
    pub fn manual_commands(&self) -> [String; 2] {
        [
            format!(
                "codex plugin marketplace add {}",
                shell_quote(&self.marketplace_root.to_string_lossy())
            ),
            self.install_command(),
        ]
    }

    /// Just the install command — what a consumer prints to recover from
    /// [`InstallOutcome::RemovedNotReinstalled`]. Shell-quoted for the reason
    /// [`Self::manual_commands`] gives.
    #[must_use]
    pub fn install_command(&self) -> String {
        format!("codex plugin add {}", shell_quote(&self.plugin_spec()))
    }

    /// Register the marketplace and install (or refresh) the plugin.
    ///
    /// `plugin_disabled` is the caller's answer from
    /// [`plugin_disabled_in_config`], passed in rather than read here because
    /// locating `config.toml` is deployment. It gates the **whole** run: a
    /// disabled plugin means no `codex` command is issued, not merely that the
    /// install step is skipped. Registering the marketplace is not a read —
    /// against a same-named source pointing elsewhere it removes that
    /// registration and redirects the name here, which is not something to do
    /// on behalf of an install that will not happen.
    #[must_use]
    pub fn register(&self, goal: InstallGoal, plugin_disabled: bool) -> ManagerRun {
        if plugin_disabled {
            return ManagerRun::SkippedDisabled;
        }
        let Some(marketplace) = self.register_marketplace() else {
            return ManagerRun::CliAbsent;
        };
        let install = if marketplace.failed() {
            InstallOutcome::Skipped
        } else {
            self.install(goal)
        };
        ManagerRun::Steps {
            marketplace,
            install,
        }
    }

    /// Register the marketplace, replacing a same-named one that points
    /// elsewhere. `None` means the `codex` program does not exist.
    ///
    /// The collision check runs before the generic "already" check because the
    /// collision error *also* contains "already added": ordering them the
    /// other way would report a stale registration as a success and install
    /// from the wrong directory.
    fn register_marketplace(&self) -> Option<MarketplaceOutcome> {
        match self.run_marketplace_add() {
            Invocation::Missing => None,
            Invocation::Ran { success: true, .. } => Some(MarketplaceOutcome::Added),
            Invocation::Ran { detail, .. } => {
                let lowered = detail.to_ascii_lowercase();
                if lowered.contains("different source") {
                    Some(self.replace_marketplace())
                } else if says_already(&lowered) {
                    Some(MarketplaceOutcome::AlreadyAdded)
                } else {
                    Some(MarketplaceOutcome::Failed { detail })
                }
            }
        }
    }

    fn replace_marketplace(&self) -> MarketplaceOutcome {
        let name = &self.marketplace_name;
        match self.run(&["plugin", "marketplace", "remove", name]) {
            Invocation::Missing => {
                return MarketplaceOutcome::Failed {
                    detail: CLI_VANISHED.to_owned(),
                };
            }
            Invocation::Ran {
                success: false,
                detail,
            } => {
                return MarketplaceOutcome::Failed {
                    detail: format!(
                        "an existing '{name}' marketplace points at a different source and \
                         `codex plugin marketplace remove {name}` failed: {detail}"
                    ),
                };
            }
            Invocation::Ran { success: true, .. } => {}
        }
        match self.run_marketplace_add() {
            Invocation::Ran { success: true, .. } => MarketplaceOutcome::Replaced {
                marketplace_name: name.clone(),
            },
            Invocation::Ran { detail, .. } => MarketplaceOutcome::Failed {
                detail: format!(
                    "removed the previous '{name}' marketplace but re-adding the managed one \
                     failed: {detail}"
                ),
            },
            Invocation::Missing => MarketplaceOutcome::Failed {
                detail: CLI_VANISHED.to_owned(),
            },
        }
    }

    /// Install the plugin, forcing a cache refresh whenever the goal says the
    /// cached copy cannot be trusted.
    ///
    /// codex-cli 0.146.0 has no `plugin update` subcommand, and
    /// `plugin marketplace upgrade` only refreshes Git-sourced snapshots — but
    /// `plugin add` against a *local* marketplace exits 0 and re-copies the
    /// cached plugin on every run, so a plain re-`add` is the native refresh.
    /// The remove-then-re-add fallback below exists for CLI versions that
    /// instead report the existing install without re-copying.
    fn install(&self, goal: InstallGoal) -> InstallOutcome {
        match self.run_plugin_add() {
            Invocation::Missing => InstallOutcome::Failed {
                detail: CLI_VANISHED.to_owned(),
            },
            Invocation::Ran { success: true, .. } => {
                if goal == InstallGoal::Refresh {
                    InstallOutcome::Refreshed
                } else {
                    InstallOutcome::Installed
                }
            }
            Invocation::Ran { detail, .. } => {
                if says_already(&detail.to_ascii_lowercase()) {
                    match goal {
                        InstallGoal::Verify => InstallOutcome::AlreadyInstalled,
                        InstallGoal::Install | InstallGoal::Refresh => self.force_refresh(),
                    }
                } else {
                    InstallOutcome::Failed { detail }
                }
            }
        }
    }

    /// Remove the untrusted install, then re-add it from the marketplace root.
    ///
    /// Failure ordering carries the whole meaning: a failed *remove* leaves
    /// the stale plugin installed and is a plain failure, while a successful
    /// remove followed by a failed *re-add* leaves the plugin uninstalled —
    /// strictly worse than doing nothing, and the only case a consumer must
    /// hand the user a recovery command for.
    fn force_refresh(&self) -> InstallOutcome {
        let spec = self.plugin_spec();
        match self.run(&["plugin", "remove", &spec]) {
            Invocation::Missing => {
                return InstallOutcome::Failed {
                    detail: CLI_VANISHED.to_owned(),
                };
            }
            Invocation::Ran {
                success: false,
                detail,
            } => {
                // Nothing to remove is a fine starting point for the re-add.
                if !says_nothing_to_remove(&detail.to_ascii_lowercase()) {
                    return InstallOutcome::Failed {
                        detail: format!(
                            "the installed plugin is stale and `codex plugin remove` failed: \
                             {detail}"
                        ),
                    };
                }
            }
            Invocation::Ran { success: true, .. } => {}
        }
        match self.run_plugin_add() {
            Invocation::Ran { success: true, .. } => InstallOutcome::Refreshed,
            Invocation::Ran { detail, .. } => {
                if says_already(&detail.to_ascii_lowercase()) {
                    InstallOutcome::Failed {
                        detail: "codex plugin add still reports an existing install after \
                                 remove; refresh manually"
                            .to_owned(),
                    }
                } else {
                    InstallOutcome::RemovedNotReinstalled { detail }
                }
            }
            Invocation::Missing => InstallOutcome::RemovedNotReinstalled {
                detail: CLI_VANISHED.to_owned(),
            },
        }
    }

    fn run_marketplace_add(&self) -> Invocation {
        let root = self.marketplace_root.clone();
        let mut command = std::process::Command::new(&self.codex_program);
        command.args(["plugin", "marketplace", "add"]).arg(root);
        run_invocation(command)
    }

    fn run_plugin_add(&self) -> Invocation {
        self.run(&["plugin", "add", &self.plugin_spec()])
    }

    fn run(&self, args: &[&str]) -> Invocation {
        let mut command = std::process::Command::new(&self.codex_program);
        command.args(args);
        run_invocation(command)
    }
}

/// Detail for the narrow window where the `codex` binary existed for one
/// command and not the next.
const CLI_VANISHED: &str = "codex CLI disappeared between commands";

/// One `codex` invocation, uninterpreted.
enum Invocation {
    /// The `codex` program does not exist.
    Missing,
    /// It ran; exit status plus flattened output.
    Ran { success: bool, detail: String },
}

/// Whether a **failed** invocation's lowercased output says the work was
/// already done.
///
/// Matches the specific phrasings the CLI uses rather than a bare "already",
/// so unrelated errors that happen to contain the word (a file "already in
/// use") stay failures.
fn says_already(lowered_detail: &str) -> bool {
    ["already added", "already installed", "already exists"]
        .iter()
        .any(|phrase| lowered_detail.contains(phrase))
}

/// Whether a **failed** remove's lowercased output says there was nothing to
/// remove.
fn says_nothing_to_remove(lowered_detail: &str) -> bool {
    ["not installed", "not configured", "already removed"]
        .iter()
        .any(|phrase| lowered_detail.contains(phrase))
}

/// Run one invocation with stdin closed and output captured.
///
/// Stdin is closed because a plugin manager that decides to prompt would
/// otherwise hang a non-interactive install forever. Only
/// [`std::io::ErrorKind::NotFound`] is [`Invocation::Missing`]; any other
/// spawn failure is a failed run carrying the OS error, so a permission
/// problem reads as a failure rather than as an absent CLI.
fn run_invocation(mut command: std::process::Command) -> Invocation {
    let output = match command.stdin(std::process::Stdio::null()).output() {
        Ok(output) => output,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Invocation::Missing;
        }
        Err(error) => {
            return Invocation::Ran {
                success: false,
                detail: error.to_string(),
            };
        }
    };
    if output.status.success() {
        return Invocation::Ran {
            success: true,
            detail: String::new(),
        };
    }
    Invocation::Ran {
        success: false,
        detail: summarize_output(&output),
    }
}

/// Flatten a failed invocation's stderr and stdout into one bounded line.
///
/// Bounded because the result is both matched on and printed: an unbounded
/// CLI dump would push a consumer's own summary off the screen.
fn summarize_output(output: &std::process::Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut detail = stderr
        .lines()
        .chain(stdout.lines())
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join("; ");
    if detail.chars().count() > MAX_DETAIL_CHARS {
        detail = detail.chars().take(MAX_DETAIL_CHARS).collect::<String>() + "";
    }
    if detail.is_empty() {
        detail = format!("exited with {}", output.status);
    }
    detail
}

/// Cap on a flattened CLI detail, in characters.
const MAX_DETAIL_CHARS: usize = 200;

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::plugin::codex_app::{HookPluginIdentity, render_plugin_manifest};

    fn identity() -> MarketplaceIdentity<'static> {
        MarketplaceIdentity::new("acme", "acme-codex").with_display_name("Acme")
    }

    fn manager(codex_program: PathBuf, root: &Path) -> PluginManager {
        PluginManager::new(
            codex_program,
            root.join("marketplace"),
            "acme",
            "acme-codex",
        )
    }

    fn missing_codex(root: &Path) -> PathBuf {
        root.join("codex-not-installed")
    }

    /// A `codex` shim that appends its arguments to `invocations.log` and
    /// scripts per-subcommand behaviour, so a test asserts exact invocations
    /// without touching `PATH`.
    ///
    /// The shim is executed once before it is returned, retrying `ETXTBSY`,
    /// because a freshly written executable is momentarily unrunnable in a
    /// multithreaded test binary. While `fs::write` holds the file open for
    /// writing, any other test thread that spawns ITS shim forks this
    /// process, and the child inherits a duplicate of the open descriptor
    /// until its own exec closes it (`O_CLOEXEC` closes at exec, not at
    /// fork). Linux refuses to exec a file any process holds open for
    /// writing, so a spawn that lands in that window fails with
    /// `Text file busy`. Closing our handle before returning — which
    /// `fs::write` already does — cannot retract the duplicates, and neither
    /// can a write-then-rename, since the duplicates name the inode rather
    /// than the path. The duplicates are only ever created during the write,
    /// though, and each dies at its holder's exec — so once one exec of the
    /// shim succeeds, none remain and every later spawn is safe. That first
    /// exec happens here, with no arguments — no shim body changes any state
    /// on an argument list that names no subcommand — and the log line it
    /// appends is deleted so each test still observes exactly its own
    /// invocations.
    #[cfg(unix)]
    fn write_codex_shim(root: &Path, body: &str) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;

        let log = root.join("invocations.log");
        let path = root.join("codex");
        std::fs::write(
            &path,
            format!("#!/bin/sh\necho \"$@\" >> \"{}\"\n{body}\n", log.display()),
        )
        .unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();

        for attempt in 1.. {
            match std::process::Command::new(&path).output() {
                Ok(_) => break,
                Err(err)
                    if err.kind() == std::io::ErrorKind::ExecutableFileBusy && attempt < 100 =>
                {
                    std::thread::sleep(std::time::Duration::from_millis(5));
                }
                Err(err) => panic!("warm-up exec of {} failed: {err}", path.display()),
            }
        }
        let _ = std::fs::remove_file(&log);
        path
    }

    #[cfg(unix)]
    fn shim_log(root: &Path) -> Vec<String> {
        std::fs::read_to_string(root.join("invocations.log"))
            .unwrap_or_default()
            .lines()
            .map(str::to_owned)
            .collect()
    }

    #[cfg(unix)]
    fn add_marketplace(root: &Path) -> String {
        format!(
            "plugin marketplace add {}",
            root.join("marketplace").display()
        )
    }

    #[test]
    fn the_rendered_marketplace_offers_the_plugin_at_the_path_the_helpers_name() {
        let rendered = render_marketplace_manifest(&identity());
        let parsed: serde_json::Value = serde_json::from_str(&rendered).unwrap();

        assert!(!rendered.contains("__TAPES_"), "{rendered}");
        assert_eq!(parsed["name"], "acme");
        assert_eq!(parsed["interface"]["displayName"], "Acme");
        let plugins = parsed["plugins"].as_array().unwrap();
        assert_eq!(plugins.len(), 1);
        assert_eq!(plugins[0]["name"], "acme-codex");
        assert_eq!(plugins[0]["source"]["source"], "local");

        // The offered path must cover the files the path helpers place, or the
        // marketplace advertises a plugin Codex cannot find.
        let offered = plugins[0]["source"]["path"].as_str().unwrap();
        let offered = Path::new(offered.trim_start_matches("./"));
        assert_eq!(offered, plugin_source_dir("acme-codex"));
        for path in [
            plugin_manifest_path("acme-codex"),
            hooks_manifest_path("acme-codex"),
        ] {
            assert!(
                path.starts_with(offered),
                "{} escapes {offered:?}",
                path.display()
            );
        }
    }

    /// The marketplace's plugin name and the plugin manifest's `name` are how
    /// Codex resolves an offer to a directory; a drift between them installs
    /// nothing. The spec a consumer hands `plugin add` is built from the same
    /// pair.
    #[test]
    fn the_offered_name_the_manifest_name_and_the_spec_agree() {
        let marketplace: serde_json::Value =
            serde_json::from_str(&render_marketplace_manifest(&identity())).unwrap();
        let manifest: serde_json::Value = serde_json::from_str(&render_plugin_manifest(
            &HookPluginIdentity::new("acme-codex", "1.0.0"),
        ))
        .unwrap();

        assert_eq!(marketplace["plugins"][0]["name"], manifest["name"]);
        assert_eq!(
            plugin_spec("acme-codex", "acme"),
            format!(
                "{}@{}",
                marketplace["plugins"][0]["name"].as_str().unwrap(),
                marketplace["name"].as_str().unwrap()
            )
        );
    }

    /// A minimal identity leaves no slot behind, and the display name falls
    /// back to the marketplace name rather than to an empty string.
    #[test]
    fn a_minimal_marketplace_identity_fills_every_slot() {
        let rendered = render_marketplace_manifest(&MarketplaceIdentity::new("bare", "bare-codex"));
        let parsed: serde_json::Value = serde_json::from_str(&rendered).unwrap();

        assert!(!rendered.contains("__TAPES_"), "{rendered}");
        assert_eq!(parsed["interface"]["displayName"], "bare");
    }

    /// The de-branding bar every crate-owned asset meets.
    #[test]
    fn the_marketplace_template_carries_no_vendor_branding() {
        let lowered = MARKETPLACE_MANIFEST_TEMPLATE.to_ascii_lowercase();
        for token in ["paper", "papercompute", "tapesctl"] {
            assert!(!lowered.contains(token), "the template mentions {token:?}");
        }
    }

    #[test]
    fn every_marketplace_slot_is_filled_and_none_is_unknown() {
        for slot in [
            MARKETPLACE_NAME_SLOT,
            MARKETPLACE_DISPLAY_NAME_SLOT,
            MARKETPLACE_PLUGIN_NAME_SLOT,
            MARKETPLACE_PLUGIN_SOURCE_PATH_SLOT,
        ] {
            assert!(
                MARKETPLACE_MANIFEST_TEMPLATE.contains(&format!("\"{slot}\"")),
                "template is missing slot {slot}"
            );
        }
        assert_eq!(MARKETPLACE_MANIFEST_TEMPLATE.matches("__TAPES_").count(), 4);
    }

    #[test]
    fn an_absent_cli_is_reported_rather_than_failed() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(missing_codex(root.path()), root.path());

        for goal in [
            InstallGoal::Install,
            InstallGoal::Refresh,
            InstallGoal::Verify,
        ] {
            assert_eq!(manager.register(goal, false), ManagerRun::CliAbsent);
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_clean_run_adds_the_marketplace_then_the_plugin() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(write_codex_shim(root.path(), "exit 0"), root.path());

        let run = manager.register(InstallGoal::Install, false);

        assert_eq!(
            run,
            ManagerRun::Steps {
                marketplace: MarketplaceOutcome::Added,
                install: InstallOutcome::Installed,
            }
        );
        assert_eq!(
            shim_log(root.path()),
            vec![
                add_marketplace(root.path()),
                "plugin add acme-codex@acme".to_owned(),
            ]
        );
    }

    #[cfg(unix)]
    #[test]
    fn already_wording_is_trusted_only_when_the_caller_confirmed_delivery() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                "echo 'error: marketplace already exists' >&2\nexit 1",
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Verify, false);

        assert_eq!(
            run,
            ManagerRun::Steps {
                marketplace: MarketplaceOutcome::AlreadyAdded,
                install: InstallOutcome::AlreadyInstalled,
            }
        );
    }

    /// Unrecognised failure wording must stay a failure: reinterpreting it
    /// would report an install that never happened.
    #[cfg(unix)]
    #[test]
    fn unrecognised_failure_wording_skips_the_install() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(root.path(), "echo 'boom: no permission' >&2\nexit 2"),
            root.path(),
        );

        let run = manager.register(InstallGoal::Install, false);

        assert_eq!(
            run,
            ManagerRun::Steps {
                marketplace: MarketplaceOutcome::Failed {
                    detail: "boom: no permission".to_owned()
                },
                install: InstallOutcome::Skipped,
            }
        );
        assert_eq!(
            shim_log(root.path()).len(),
            1,
            "the plugin add must not run"
        );
    }

    /// codex-cli 0.146.0's own refresh path: `plugin add` exits 0 and
    /// re-copies, so the fallback must not fire.
    #[cfg(unix)]
    #[test]
    fn a_cooperative_add_refreshes_without_the_remove_fallback() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(write_codex_shim(root.path(), "exit 0"), root.path());

        let run = manager.register(InstallGoal::Refresh, false);

        assert_eq!(
            run,
            ManagerRun::Steps {
                marketplace: MarketplaceOutcome::Added,
                install: InstallOutcome::Refreshed,
            }
        );
        assert_eq!(
            shim_log(root.path()),
            vec![
                add_marketplace(root.path()),
                "plugin add acme-codex@acme".to_owned(),
            ]
        );
    }

    #[cfg(unix)]
    fn add_is_sticky_until_removed(root: &Path) -> PathBuf {
        write_codex_shim(
            root,
            &format!(
                "case \"$*\" in\n  \
                 *'plugin remove'*) touch \"{removed}\"; exit 0 ;;\n  \
                 *'plugin add'*) if [ -f \"{removed}\" ]; then exit 0; \
                 else echo 'plugin is already installed' >&2; exit 1; fi ;;\n  \
                 *) exit 0 ;;\nesac",
                removed = root.join("removed.sentinel").display()
            ),
        )
    }

    #[cfg(unix)]
    #[test]
    fn an_uncooperative_add_falls_back_to_remove_then_re_add() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(add_is_sticky_until_removed(root.path()), root.path());

        let run = manager.register(InstallGoal::Refresh, false);

        assert_eq!(
            run,
            ManagerRun::Steps {
                marketplace: MarketplaceOutcome::Added,
                install: InstallOutcome::Refreshed,
            }
        );
        assert_eq!(
            shim_log(root.path()),
            vec![
                add_marketplace(root.path()),
                "plugin add acme-codex@acme".to_owned(),
                "plugin remove acme-codex@acme".to_owned(),
                "plugin add acme-codex@acme".to_owned(),
            ],
            "fallback order must be add, remove, re-add"
        );
    }

    /// An install of unknown provenance is forced fresh even though nothing is
    /// known to be stale: the cached copy could be anyone's.
    #[cfg(unix)]
    #[test]
    fn an_unconfirmed_existing_install_is_forced_fresh() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(add_is_sticky_until_removed(root.path()), root.path());

        let run = manager.register(InstallGoal::Install, false);

        assert!(
            matches!(
                run,
                ManagerRun::Steps {
                    install: InstallOutcome::Refreshed,
                    ..
                }
            ),
            "{run:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_failed_remove_keeps_the_stale_install_in_place() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                "case \"$*\" in\n  \
                 *'plugin remove'*) echo 'remove blew up' >&2; exit 2 ;;\n  \
                 *'plugin add'*) echo 'plugin is already installed' >&2; exit 1 ;;\n  \
                 *) exit 0 ;;\nesac",
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Refresh, false);

        let ManagerRun::Steps { install, .. } = run else {
            panic!("expected steps");
        };
        let InstallOutcome::Failed { detail } = install else {
            panic!("expected a plain failure, got {install:?}");
        };
        assert!(detail.contains("codex plugin remove"), "{detail}");
        assert!(detail.contains("remove blew up"), "{detail}");
        assert_eq!(
            shim_log(root.path())
                .iter()
                .filter(|line| line.starts_with("plugin add"))
                .count(),
            1,
            "no re-add may follow a failed remove"
        );
    }

    /// Nothing-to-remove wording is not a failure: it is the state the re-add
    /// wants anyway.
    #[cfg(unix)]
    #[test]
    fn a_remove_that_had_nothing_to_remove_proceeds_to_the_re_add() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                &format!(
                    "case \"$*\" in\n  \
                     *'plugin remove'*) touch \"{done}\"; echo 'plugin is not installed' >&2; \
                     exit 1 ;;\n  \
                     *'plugin add'*) if [ -f \"{done}\" ]; then exit 0; \
                     else echo 'plugin is already installed' >&2; exit 1; fi ;;\n  \
                     *) exit 0 ;;\nesac",
                    done = root.path().join("removed.sentinel").display()
                ),
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Refresh, false);

        assert!(
            matches!(
                run,
                ManagerRun::Steps {
                    install: InstallOutcome::Refreshed,
                    ..
                }
            ),
            "{run:?}"
        );
    }

    /// The one outcome that leaves the machine worse off than doing nothing.
    #[cfg(unix)]
    #[test]
    fn a_failed_re_add_after_a_successful_remove_says_so() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                &format!(
                    "case \"$*\" in\n  \
                     *'plugin remove'*) touch \"{removed}\"; exit 0 ;;\n  \
                     *'plugin add'*) if [ -f \"{removed}\" ]; then echo 'network exploded' >&2; \
                     exit 2; else echo 'plugin is already installed' >&2; exit 1; fi ;;\n  \
                     *) exit 0 ;;\nesac",
                    removed = root.path().join("removed.sentinel").display()
                ),
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Refresh, false);

        let ManagerRun::Steps { install, .. } = run else {
            panic!("expected steps");
        };
        assert_eq!(
            install,
            InstallOutcome::RemovedNotReinstalled {
                detail: "network exploded".to_owned()
            }
        );
        assert!(install.needs_manual_retry());
        assert!(!install.confirmed_delivery());
    }

    /// Collision wording verified live against codex-cli 0.146.0. The
    /// collision error also contains "already added", so the ordering inside
    /// [`PluginManager::register_marketplace`] is what this pins.
    #[cfg(unix)]
    #[test]
    fn a_same_named_marketplace_at_another_source_is_replaced() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                &format!(
                    "case \"$*\" in\n  \
                     *'plugin marketplace remove'*) touch \"{removed}\"; exit 0 ;;\n  \
                     *'plugin marketplace add'*) if [ -f \"{removed}\" ]; then exit 0; \
                     else echo \"Error: marketplace 'acme' is already added from a different \
                     source; remove it before adding this source\" >&2; exit 1; fi ;;\n  \
                     *) exit 0 ;;\nesac",
                    removed = root.path().join("mkt-removed.sentinel").display()
                ),
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Install, false);

        assert_eq!(
            run,
            ManagerRun::Steps {
                marketplace: MarketplaceOutcome::Replaced {
                    marketplace_name: "acme".to_owned()
                },
                install: InstallOutcome::Installed,
            }
        );
        assert_eq!(
            shim_log(root.path()),
            vec![
                add_marketplace(root.path()),
                "plugin marketplace remove acme".to_owned(),
                add_marketplace(root.path()),
                "plugin add acme-codex@acme".to_owned(),
            ],
            "collision order must be add, remove, re-add, plugin add"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_collision_whose_removal_fails_is_reported_with_both_reasons() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                "case \"$*\" in\n  \
                 *'plugin marketplace remove'*) echo 'permission denied' >&2; exit 2 ;;\n  \
                 *'plugin marketplace add'*) echo \"Error: marketplace 'acme' is already added \
                 from a different source; remove it before adding this source\" >&2; exit 1 ;;\n  \
                 *) exit 0 ;;\nesac",
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Install, false);

        let ManagerRun::Steps {
            marketplace,
            install,
        } = run
        else {
            panic!("expected steps");
        };
        let MarketplaceOutcome::Failed { detail } = marketplace else {
            panic!("expected a failure, got {marketplace:?}");
        };
        assert!(detail.contains("different source"), "{detail}");
        assert!(detail.contains("permission denied"), "{detail}");
        assert_eq!(install, InstallOutcome::Skipped);
    }

    /// A disabled plugin must leave the machine exactly as it found it — and
    /// the sharpest case is a same-named marketplace registered from someone
    /// else's source. Replacing that is destructive, it is done to serve an
    /// install that is then not performed, and it happens behind the back of a
    /// user who already said no.
    ///
    /// Asserting the invocation log is EMPTY rather than "no plugin add" is
    /// the point: the earlier spelling of this test watched only the install
    /// step and so could not see the marketplace being rewritten underneath.
    #[cfg(unix)]
    #[test]
    fn a_disabled_plugin_leaves_someone_elses_marketplace_alone() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                &format!(
                    "case \"$*\" in\n  \
                     *'plugin marketplace remove'*) touch \"{removed}\"; exit 0 ;;\n  \
                     *'plugin marketplace add'*) if [ -f \"{removed}\" ]; then exit 0; \
                     else echo \"Error: marketplace 'acme' is already added from a different \
                     source; remove it before adding this source\" >&2; exit 1; fi ;;\n  \
                     *) exit 0 ;;\nesac",
                    removed = root.path().join("mkt-removed.sentinel").display()
                ),
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Install, true);

        assert_eq!(run, ManagerRun::SkippedDisabled);
        assert!(
            shim_log(root.path()).is_empty(),
            "a disabled plugin must run no codex command at all, got {:?}",
            shim_log(root.path())
        );
    }

    /// Every printed command is copy-paste text, so each of its arguments must
    /// survive `/bin/sh` word splitting as exactly one word. A marketplace root
    /// under a home directory with a space in it is ordinary, not exotic.
    ///
    /// The round trip is real: the command is handed to `sh` via `set --`,
    /// which performs the same splitting a user's paste would, and each
    /// resulting word is printed on its own line.
    #[cfg(unix)]
    #[test]
    fn a_printed_command_survives_shell_word_splitting() {
        let awkward = std::path::PathBuf::from("/tmp/two words/it's here/$HOME`x`;rm -rf/plugin");
        let manager = PluginManager::new("codex", &awkward, "acme", "acme-codex");

        let words = shell_words(&manager.manual_commands()[0]);

        assert_eq!(
            words,
            vec![
                "codex".to_owned(),
                "plugin".to_owned(),
                "marketplace".to_owned(),
                "add".to_owned(),
                awkward.display().to_string(),
            ],
            "the marketplace path did not survive as one word"
        );
    }

    /// Split a command string the way a shell would, by letting a shell do it.
    #[cfg(unix)]
    fn shell_words(command: &str) -> Vec<String> {
        let output = std::process::Command::new("/bin/sh")
            .arg("-c")
            .arg(format!("set -- {command}\nprintf '%s\\n' \"$@\""))
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "the printed command is not even parseable by /bin/sh: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8(output.stdout)
            .unwrap()
            .lines()
            .map(str::to_owned)
            .collect()
    }

    /// A CLI that fails with no output at all still produces a detail a user
    /// can act on, rather than an empty "failed: ".
    #[cfg(unix)]
    #[test]
    fn a_silent_failure_still_carries_a_detail() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(write_codex_shim(root.path(), "exit 3"), root.path());

        let run = manager.register(InstallGoal::Install, false);

        let ManagerRun::Steps { marketplace, .. } = run else {
            panic!("expected steps");
        };
        let MarketplaceOutcome::Failed { detail } = marketplace else {
            panic!("expected a failure, got {marketplace:?}");
        };
        assert!(detail.contains("exited with"), "{detail}");
    }

    #[cfg(unix)]
    #[test]
    fn a_long_failure_detail_is_bounded() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(
            write_codex_shim(
                root.path(),
                "yes x | head -c 5000 | tr -d '\\n' >&2; exit 1",
            ),
            root.path(),
        );

        let run = manager.register(InstallGoal::Install, false);

        let ManagerRun::Steps { marketplace, .. } = run else {
            panic!("expected steps");
        };
        let MarketplaceOutcome::Failed { detail } = marketplace else {
            panic!("expected a failure, got {marketplace:?}");
        };
        assert_eq!(detail.chars().count(), MAX_DETAIL_CHARS + 1, "{detail}");
        assert!(detail.ends_with(''), "{detail}");
    }

    #[test]
    fn the_manual_commands_are_the_commands_a_run_would_have_issued() {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(missing_codex(root.path()), root.path());

        // An ordinary path and an ordinary spec print bare: quoting is applied
        // where it is needed, not everywhere, so the common case stays
        // readable.
        assert_eq!(
            manager.manual_commands(),
            [
                format!(
                    "codex plugin marketplace add {}",
                    manager.marketplace_root().display()
                ),
                "codex plugin add acme-codex@acme".to_owned(),
            ]
        );
        assert_eq!(manager.install_command(), manager.manual_commands()[1]);
    }

    #[test]
    fn only_an_explicit_false_reads_as_disabled() {
        let spec = plugin_spec("acme-codex", "acme");

        assert!(plugin_disabled_in_config(
            &format!("[plugins.\"{spec}\"]\nenabled = false\n"),
            &spec
        ));
        assert!(!plugin_disabled_in_config(
            &format!("[plugins.\"{spec}\"]\nenabled = true\n"),
            &spec
        ));
        // Absent table, absent key, another plugin's entry, and unparseable
        // text all mean "the user has not said no".
        assert!(!plugin_disabled_in_config("", &spec));
        assert!(!plugin_disabled_in_config(
            &format!("[plugins.\"{spec}\"]\n"),
            &spec
        ));
        assert!(!plugin_disabled_in_config(
            "[plugins.\"other@acme\"]\nenabled = false\n",
            &spec
        ));
        assert!(!plugin_disabled_in_config("not = [valid\n", &spec));
    }

    #[test]
    fn describes_cover_every_outcome_without_leaking_a_debug_shape() {
        for outcome in [
            MarketplaceOutcome::Added,
            MarketplaceOutcome::AlreadyAdded,
            MarketplaceOutcome::Replaced {
                marketplace_name: "acme".to_owned(),
            },
            MarketplaceOutcome::Failed {
                detail: "boom".to_owned(),
            },
        ] {
            let described = outcome.describe();
            assert!(!described.is_empty());
            assert!(!described.contains('{'), "{described}");
        }
        for outcome in [
            InstallOutcome::Installed,
            InstallOutcome::AlreadyInstalled,
            InstallOutcome::Refreshed,
            InstallOutcome::Failed {
                detail: "boom".to_owned(),
            },
            InstallOutcome::RemovedNotReinstalled {
                detail: "boom".to_owned(),
            },
            InstallOutcome::Skipped,
        ] {
            let described = outcome.describe();
            assert!(!described.is_empty());
            assert!(!described.contains('{'), "{described}");
        }
    }

    /// Only the two outcomes that prove Codex re-copied the bytes may advance
    /// a consumer's delivered record; everything else must leave delivery
    /// pending so a later run retries.
    #[test]
    fn only_a_proven_copy_counts_as_delivered() {
        assert!(InstallOutcome::Installed.confirmed_delivery());
        assert!(InstallOutcome::Refreshed.confirmed_delivery());
        for outcome in [
            InstallOutcome::AlreadyInstalled,
            InstallOutcome::Failed {
                detail: String::new(),
            },
            InstallOutcome::RemovedNotReinstalled {
                detail: String::new(),
            },
            InstallOutcome::Skipped,
        ] {
            assert!(!outcome.confirmed_delivery(), "{outcome:?}");
        }
    }
}