tambo 0.10.0

Install and prove the whole AI knowledge-tool kit
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
use std::path::PathBuf;

use anyhow::Result;
#[cfg(unix)]
use caboodle::harness_hooks;
use caboodle::{
    crew::CrewEvidence,
    doctor,
    embedding::EmbeddingModel,
    emission, engine, interview,
    model::{CrewMode, InstallIntent, Plan, Profile, QuipuFlavor, State},
    observability, projection,
};
use clap::{Parser, Subcommand, ValueEnum};

/// `0.2.2 (1a2b3c4d5e6f)`: the release version and the commit it was built from.
const VERSION: &str = concat!(
    env!("CARGO_PKG_VERSION"),
    " (",
    env!("CABOODLE_GIT_SHA"),
    ")"
);

#[derive(Parser)]
#[command(name = env!("CARGO_BIN_NAME"), version = VERSION, about)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Render or separately install the exact per-slot helper permission fragment
    #[cfg(unix)]
    JobPolicy {
        #[arg(long)]
        directory: PathBuf,
        #[arg(long)]
        apply: bool,
    },
    /// Prepare public own-job metadata only, from the protected host inventory
    #[cfg(unix)]
    JobMetadata {
        #[arg(long)]
        directory: PathBuf,
        #[arg(long)]
        apply: bool,
    },
    /// Inspect or separately apply one pinned immutable job runtime artifact
    #[cfg(unix)]
    JobRuntime {
        #[arg(long)]
        directory: PathBuf,
        #[arg(long)]
        manifest_sha256: String,
        #[arg(long)]
        apply: bool,
    },
    /// Review protected per-job accounts; apply only a separately admitted macOS host inventory
    #[cfg(unix)]
    JobSlots {
        #[arg(long)]
        directory: PathBuf,
        /// Create only the exact reviewed accounts; requires native macOS and root-owned input
        #[arg(long)]
        apply: bool,
    },
    /// Review memory setup or inspect actual firing evidence (never disables auto-memory)
    #[cfg(unix)]
    Memory {
        #[command(subcommand)]
        command: MemoryCommand,
    },
    /// Print the agent primer and each installed stack tool's `prime --brief`
    Prime {
        /// At most 10 lines: version, stack tools found, which have prime
        #[arg(long)]
        brief: bool,
        /// One object in the stack prime contract's common shape
        #[arg(long)]
        json: bool,
        /// Skip the live part; print only the static primer
        #[arg(long = "static")]
        offline: bool,
        /// Print one primer section, by case-insensitive heading prefix
        #[arg(long)]
        section: Option<String>,
        /// Per-tool timeout for `<tool> prime --brief`, in milliseconds
        #[arg(long, default_value_t = 1000, hide = true)]
        timeout_ms: u64,
        /// Rikuy static-site URL; otherwise RIKUY_URL. Reads only source.json.
        #[arg(long)]
        rikuy_url: Option<String>,
    },
    /// Install the local single-user stack with no interview, server, or token
    Quickstart {
        #[arg(long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
        /// Use tools already installed by an external package manager
        #[arg(long)]
        skip_install: bool,
        /// Do not add the query-first hooks to Claude Code and Codex
        #[arg(long)]
        no_agent_hooks: bool,
    },
    /// Install an administrator-issued Quipu token after proving acceptance; never rotate
    ProvisionQuipuToken {
        #[arg(long = "from")]
        source: PathBuf,
        #[arg(long)]
        server: String,
    },
    /// Install, verify or remove the query-first hooks for Claude Code and Codex
    #[cfg(unix)]
    Hooks {
        #[command(subcommand)]
        command: HooksCommand,
    },
    /// Internal harness hook entry points
    #[cfg(unix)]
    #[command(hide = true)]
    Hook {
        #[command(subcommand)]
        command: HookCommand,
    },
    /// Report, without changing anything, what would stop an install on this host
    Doctor {
        /// Plan to check; without one, every tool in the everything profile is checked
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        /// Install state; when it records every planned tool verified, doctor says so
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
    },
    /// Run the resumable guided interview and write a reviewable plan
    Init {
        /// Use the guided question flow
        #[arg(long)]
        guided: bool,
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        output: PathBuf,
        #[arg(long, default_value = ".caboodle/interview.toml")]
        session: PathBuf,
        /// Opt in to repository pendant sync hooks; retains existing hooks
        #[arg(long, conflicts_with = "guided")]
        pack_hooks: bool,
        /// Select project shares by their native path scope in installed hooks
        #[arg(long, requires = "pack_hooks")]
        monorepo: bool,
        #[arg(long, default_value = ".")]
        repo: PathBuf,
        /// Operator-controlled shape-authority pendant for local composition
        #[arg(long, requires = "pack_hooks")]
        shapes_from: Option<PathBuf>,
        #[arg(long, requires = "pack_hooks")]
        db: Option<PathBuf>,
        #[arg(long, requires = "pack_hooks")]
        trust_file: Option<PathBuf>,
    },
    /// Write a reviewable install plan without changing the machine
    Plan {
        #[arg(long, value_enum, default_value_t = ProfileArg::Retrieval)]
        profile: ProfileArg,
        /// Crew runtime when --profile crew is selected
        #[arg(long, value_enum, default_value_t = CrewModeArg::Standalone)]
        crew: CrewModeArg,
        /// Reviewable intended-use, crew-theme, and ontology-question contract
        #[arg(long, default_value = "caboodle-intent.toml")]
        intent: PathBuf,
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        output: PathBuf,
        /// Canonical Quipu share directories to stage during apply
        #[arg(long = "share")]
        shares: Vec<PathBuf>,
        /// Explicit Quipu database that receives staged shares
        #[arg(long, requires = "shares")]
        quipu_db: Option<PathBuf>,
        /// Quipu install flavor; lancedb builds the same reviewed revision
        /// with the lancedb cargo feature compiled in
        #[arg(long, value_enum, default_value_t = QuipuFlavorArg::Release)]
        quipu_flavor: QuipuFlavorArg,
        /// Checksum-pinned embedding-model artifact spec copied into the plan
        #[arg(long)]
        embedding_model: Option<PathBuf>,
        /// Register this Quipu server's MCP endpoint with Claude Code through a
        /// headersHelper that reads the token at connect time (no secret in config)
        #[arg(long)]
        quipu_mcp_url: Option<String>,
        /// This host's Quipu token FILE, baked into the helper as its default
        /// (a path, never the token). Defaults to $QUIPU_AUTH_TOKEN_FILE when set.
        #[arg(long, requires = "quipu_mcp_url")]
        quipu_mcp_token_file: Option<String>,
    },
    /// Converge installed tools and prove each binary by version read-back
    Apply {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
        /// Refuse to install missing tools; useful for managed or offline machines
        #[arg(long)]
        skip_install: bool,
        /// Apply this plan host profile (e.g. exclude crew a different lane owns)
        #[arg(long)]
        host_profile: Option<String>,
    },
    /// Run isolated functional round trips for every selected tool
    Verify {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
        /// Creel browser doctor JSON produced by its capability preflight
        #[arg(long)]
        creel_doctor: Option<PathBuf>,
        /// Creel admission JSON produced by its provider-window governor
        #[arg(long)]
        creel_admission: Option<PathBuf>,
        /// Apply this plan host profile (e.g. exclude crew a different lane owns)
        #[arg(long)]
        host_profile: Option<String>,
    },
    /// Verify one embedded release member in temporary roots without installing it
    VerifyMember { member: String },
    /// Apply and verify a previously reviewed plan
    Install {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
        #[arg(long)]
        skip_install: bool,
        #[arg(long)]
        creel_doctor: Option<PathBuf>,
        #[arg(long)]
        creel_admission: Option<PathBuf>,
        /// Apply this plan host profile (e.g. exclude crew a different lane owns)
        #[arg(long)]
        host_profile: Option<String>,
        /// Do not add the query-first hooks to Claude Code and Codex
        #[arg(long)]
        no_agent_hooks: bool,
    },
    /// Report drift from the releases reviewed by this Tambo build
    CheckUpdates {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        /// Apply this plan host profile (e.g. exclude crew a different lane owns)
        #[arg(long)]
        host_profile: Option<String>,
    },
    /// Converge drifted tools to reviewed releases and verify each change
    Update {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
        #[arg(long)]
        creel_doctor: Option<PathBuf>,
        #[arg(long)]
        creel_admission: Option<PathBuf>,
        /// Apply this plan host profile (e.g. exclude crew a different lane owns)
        #[arg(long)]
        host_profile: Option<String>,
    },
    /// Update this installer from a published checksummed release
    #[cfg(unix)]
    UpdateSelf {
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
        #[arg(long)]
        check: bool,
        /// Select this exact published stable installer tag instead of latest.
        #[arg(long)]
        tag: Option<String>,
        /// Bind the downloaded archive to pre-install release evidence.
        #[arg(long, requires_all = ["tag", "binary_sha256"])]
        archive_sha256: Option<String>,
        /// Bind candidate bytes before executing or replacing the installer.
        #[arg(long, requires_all = ["tag", "archive_sha256"])]
        binary_sha256: Option<String>,
    },
    /// Internal: update-self runs this on the NEWLY installed binary so its
    /// own repairs apply on the first natural update (aegis-61f).
    #[cfg(unix)]
    #[command(hide = true)]
    PostInstallRepair,
    /// Maintainers: re-pin a stack member manifest to its published release,
    /// recording the digests the release publishes after hashing each asset
    /// (review and merge the result; installs never read the release's sums)
    #[cfg(unix)]
    BumpMember {
        /// The manifest to rewrite, e.g. members/seeds.toml
        manifest: PathBuf,
        /// Release tag to pin instead of the latest stable release
        #[arg(long)]
        tag: Option<String>,
        /// Run every execution of the new, unreviewed release as
        /// `<wrapper> <program> <args...>`, e.g. a sandbox (aegis-uy26l7)
        #[arg(long)]
        probe_wrapper: Option<PathBuf>,
    },
    /// Track a published binary release for one tool in an existing reviewed plan
    #[cfg(unix)]
    UpdateRelease {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        #[arg(long, default_value = ".caboodle/state.json")]
        state: PathBuf,
        /// bobbin, yupana or desire-path track the newest published release;
        /// quipu and stack members track reviewed pins. Camayoc/Shantytown
        /// refuse until checksummed publications exist
        #[arg(long, value_parser = update_release_tool)]
        tool: String,
        /// Inspect release/version metadata without downloading or replacing binaries
        #[arg(long)]
        check: bool,
    },
    /// Restore Seeds from the receipt of its last successful release update
    #[cfg(unix)]
    RollbackSeeds {
        #[arg(long)]
        plan: PathBuf,
        #[arg(long)]
        state: PathBuf,
        #[arg(long)]
        current_sha256: String,
        #[arg(long)]
        prior_sha256: String,
    },
    /// Register the rig crew through shantytown and its Quipu tooling manifest
    ProjectSettings {
        /// Shantytown store root (otherwise st uses its normal discovery)
        #[arg(long)]
        root: Option<PathBuf>,
        /// Equip only this local crew card (default: every local card)
        #[arg(long)]
        agent: Option<String>,
        #[arg(long, value_parser = ["files", "quipu", "toml"], default_value = "files")]
        registry: String,
        /// Only export the legacy plan policy summaries; does not register MCP
        #[arg(long, conflicts_with_all = ["root", "agent"])]
        policy_only: bool,
        #[arg(
            short,
            long,
            default_value = "caboodle-plan.toml",
            requires = "policy_only"
        )]
        plan: PathBuf,
        #[arg(
            short,
            long,
            default_value = "caboodle-settings",
            requires = "policy_only"
        )]
        output: PathBuf,
    },
    /// Execute every anticipated ontology question against the installed Quipu
    VerifyQuestions {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        /// Optional isolated Quipu database used by the question probes
        #[arg(long)]
        db: Option<PathBuf>,
    },
    /// Render reviewable Prometheus, alert, dashboard, and contract artifacts
    RenderObservability {
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
        #[arg(long, default_value = "caboodle-observability.toml")]
        targets: PathBuf,
        #[arg(short, long, default_value = "caboodle-observability")]
        output: PathBuf,
    },
    /// Validate generated observability artifacts against their contracts
    ValidateObservability {
        #[arg(short, long, default_value = "caboodle-observability")]
        output: PathBuf,
    },
    /// Queue created/commented/closed lifecycle episodes from a br JSONL snapshot
    QueueBr {
        input: PathBuf,
        #[arg(short, long, default_value = ".caboodle/episodes")]
        queue: PathBuf,
    },
    /// Deliver identical queued episodes after a Quipu readiness control passes
    FlushEpisodes {
        #[arg(short, long, default_value = ".caboodle/episodes")]
        queue: PathBuf,
        #[arg(long)]
        endpoint: String,
    },
    /// Pendant packs a repository ships under .quipu/packs/
    Packs {
        #[command(subcommand)]
        command: PacksCommand,
    },
}

#[derive(Subcommand)]
enum PacksCommand {
    /// Print the native CONSTRUCT path scope used for one derived project share
    ProjectScope {
        /// Read CODEOWNERS from this checkout and attach ownership in the scope
        #[arg(long, requires_all = ["ownership_predicate", "db"])]
        repo: Option<PathBuf>,
        /// Existing producer store; owner resources must already be registered
        #[arg(long, requires = "repo")]
        db: Option<PathBuf>,
        /// Existing RDF ownership predicate, supplied by the producer's schema
        #[arg(long, requires = "repo")]
        ownership_predicate: Option<String>,
        #[arg(long)]
        graph: String,
        #[arg(long)]
        path_predicate: String,
        #[arg(long)]
        prefix: String,
    },
    /// Discover trusted .quipu/packs/*.pendant.tar.gz and update local CURRENT
    Sync {
        /// Exclude the parent and load only derived projects present in the checkout
        #[arg(long)]
        monorepo: bool,
        #[arg(long, default_value = ".")]
        repo: PathBuf,
        #[arg(long)]
        db: Option<PathBuf>,
        /// Trusted local authority pendant, never chosen from repository data
        #[arg(long)]
        shapes_from: Option<PathBuf>,
        #[arg(long)]
        trust_file: Option<PathBuf>,
    },
    /// Which packs and pointer endpoints may load (~/.config/caboodle/pack-trust.toml)
    Trust {
        /// Trust file to read and write instead of the default
        #[arg(long, global = true)]
        file: Option<PathBuf>,
        #[command(subcommand)]
        command: TrustCommand,
    },
}

#[derive(Subcommand)]
enum TrustCommand {
    /// Autoload every repository of this owner (host/owner, e.g. github.com/scbrown)
    Own { owner: String },
    /// Admit exactly one foreign pack archive: repository plus its sha256
    Allow {
        repo: String,
        sha256: String,
        #[arg(long)]
        note: Option<String>,
    },
    /// Admit exactly one pointer endpoint declared by a foreign repository's pack
    AllowEndpoint {
        repo: String,
        endpoint: String,
        #[arg(long)]
        note: Option<String>,
    },
    /// Decide one pointer endpoint: exit 0 to federate, 3 refused
    CheckEndpoint {
        /// The declaring repository's git remote URL
        remote: String,
        /// The exact endpoint URL
        endpoint: String,
    },
    /// Print the trust file
    List,
    /// Decide one pack: exit 0 to load, 3 refused (message names the pack)
    Check {
        /// The repository's git remote URL
        remote: String,
        sha256: String,
        /// The pack's path, named in a refusal
        #[arg(long, default_value = "pack")]
        pack: String,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum ProfileArg {
    Kg,
    Retrieval,
    CodeIntel,
    Crew,
    Everything,
}

#[derive(Clone, Copy, ValueEnum)]
enum QuipuFlavorArg {
    Release,
    Lancedb,
}

impl From<QuipuFlavorArg> for QuipuFlavor {
    fn from(value: QuipuFlavorArg) -> Self {
        match value {
            QuipuFlavorArg::Release => Self::Release,
            QuipuFlavorArg::Lancedb => Self::Lancedb,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
enum CrewModeArg {
    Shantytown,
    Creel,
    Both,
    Standalone,
}

impl From<CrewModeArg> for CrewMode {
    fn from(value: CrewModeArg) -> Self {
        match value {
            CrewModeArg::Shantytown => Self::Shantytown,
            CrewModeArg::Creel => Self::Creel,
            CrewModeArg::Both => Self::Both,
            CrewModeArg::Standalone => Self::Standalone,
        }
    }
}

impl From<ProfileArg> for Profile {
    fn from(value: ProfileArg) -> Self {
        match value {
            ProfileArg::Kg => Self::Kg,
            ProfileArg::Retrieval => Self::Retrieval,
            ProfileArg::CodeIntel => Self::CodeIntel,
            ProfileArg::Crew => Self::Crew,
            ProfileArg::Everything => Self::Everything,
        }
    }
}

/// `update-release --tool`: the release-tracked built-ins, or any embedded member.
#[cfg(unix)]
fn update_release_tool(value: &str) -> Result<String, String> {
    if [
        "bobbin",
        "yupana",
        "desire-path",
        "quipu",
        "camayoc",
        "shantytown",
    ]
    .contains(&value)
        || caboodle::members::get(value).is_some()
    {
        Ok(value.to_owned())
    } else {
        let members: Vec<&str> = caboodle::members::all()
            .iter()
            .map(|m| m.name.as_str())
            .collect();
        Err(format!(
            "possible values: bobbin, yupana, desire-path, quipu, camayoc, shantytown, or a stack member ({})",
            members.join(", ")
        ))
    }
}

#[cfg(unix)]
#[derive(Subcommand)]
enum HooksCommand {
    /// Add the query-first hooks to ~/.claude/settings.json and ~/.codex/config.toml
    Install {
        /// Plan whose local Quipu store the directive names
        #[arg(short, long, default_value = "caboodle-plan.toml")]
        plan: PathBuf,
    },
    /// Report whether each harness has working query-first hooks
    Verify,
    /// Remove the hooks; restore the exact prior file when nothing else changed
    Uninstall,
}

#[cfg(unix)]
#[derive(Subcommand)]
enum HookCommand {
    /// Print the query-first directive and count the firing (always exits 0)
    QueryFirst {
        #[arg(long, value_parser = ["claude", "codex"])]
        harness: String,
        #[arg(long, value_parser = ["SessionStart", "UserPromptSubmit"])]
        event: String,
    },
}

#[cfg(unix)]
#[derive(Subcommand)]
enum MemoryCommand {
    /// Prepare private reviewed edits and producer-generated skills; no live writes
    Plan {
        #[arg(long)]
        root: PathBuf,
        #[arg(long)]
        bobbin_config: PathBuf,
        #[arg(long)]
        person: String,
        #[arg(long)]
        issuer_name: Option<String>,
        /// Preserve file writes by default; blocking requires an explicit choice
        #[arg(long, value_enum, default_value_t = caboodle::agent_memory::RedirectMode::Copy)]
        redirect_mode: caboodle::agent_memory::RedirectMode,
        #[arg(long)]
        camayoc_source: PathBuf,
        #[arg(long)]
        claude_home: Option<PathBuf>,
        #[arg(long)]
        codex_home: Option<PathBuf>,
        #[arg(long)]
        output: PathBuf,
    },
    /// Install a reviewed memory setup through the existing settings owner
    Apply {
        #[arg(long)]
        plan: PathBuf,
    },
    /// Restore only unchanged files and bundles owned by this plan
    Restore {
        #[arg(long)]
        plan: PathBuf,
    },
    /// Check current configuration, generated tools and actual hook firing
    Verify {
        #[arg(long)]
        plan: PathBuf,
    },
    /// Refuse disabling auto-memory until all rollout acceptance gates are proven
    DisableAutoMemory {
        #[arg(long)]
        plan: PathBuf,
    },
    /// Internal harness hook: delegate to Camayoc and record metadata-only evidence
    #[command(hide = true)]
    Hook {
        #[arg(long)]
        plan: PathBuf,
        #[arg(long, value_parser=["claude","codex"])]
        harness: String,
        #[arg(long)]
        event: String,
    },
    /// Read a matching successful firing receipt (one Unix timestamp)
    #[command(hide = true)]
    Evidence {
        #[arg(long)]
        plan: PathBuf,
        #[arg(long, value_parser=["claude","codex"])]
        harness: String,
        #[arg(long)]
        event: String,
    },
}

fn main() -> Result<()> {
    match Cli::parse().command {
        #[cfg(unix)]
        Commands::JobPolicy { directory, apply } => {
            if apply {
                println!(
                    "{}",
                    serde_json::json!({"changed":caboodle::job_slots::apply_policy(&directory)?})
                );
            } else {
                print!("{}", caboodle::job_slots::sudoers(&directory)?);
            }
        }
        #[cfg(unix)]
        Commands::JobMetadata { directory, apply } => {
            if apply {
                println!(
                    "{}",
                    serde_json::json!({"changed":caboodle::job_slots::prepare_metadata(&directory)?})
                );
            } else {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&caboodle::job_slots::load(&directory)?)?
                );
            }
        }
        #[cfg(unix)]
        Commands::JobRuntime {
            directory,
            manifest_sha256,
            apply,
        } => {
            let plan = if apply {
                caboodle::job_runtime::apply(&directory, &manifest_sha256)?
            } else {
                caboodle::job_runtime::preview(&directory, &manifest_sha256)?
            };
            println!("{}", serde_json::to_string_pretty(&plan)?);
        }
        #[cfg(unix)]
        Commands::JobSlots { directory, apply } => {
            let plan = if apply {
                caboodle::job_slots::apply(&directory)?
            } else {
                caboodle::job_slots::load(&directory)?
            };
            println!("{}", serde_json::to_string_pretty(&plan)?);
        }
        #[cfg(unix)]
        Commands::Memory { command } => {
            use caboodle::agent_memory::{self, hooks, lifecycle};
            let mut runner = lifecycle::System;
            match command {
                MemoryCommand::Plan {
                    root,
                    bobbin_config,
                    person,
                    issuer_name,
                    redirect_mode,
                    camayoc_source,
                    claude_home,
                    codex_home,
                    output,
                } => {
                    let home = std::env::var_os("HOME").map(PathBuf::from);
                    let claude = claude_home
                        .or_else(|| home.as_ref().map(|p| p.join(".claude")))
                        .ok_or_else(|| anyhow::anyhow!("HOME or --claude-home required"))?;
                    let codex = codex_home
                        .or_else(|| std::env::var_os("CODEX_HOME").map(PathBuf::from))
                        .or_else(|| home.as_ref().map(|p| p.join(".codex")))
                        .ok_or_else(|| anyhow::anyhow!("HOME or --codex-home required"))?;
                    lifecycle::create(
                        lifecycle::Create {
                            root: &root,
                            bobbin: &bobbin_config,
                            person: &person,
                            output: &output,
                            source: &camayoc_source,
                            claude_home: &claude,
                            codex_home: &codex,
                            issuer_name: issuer_name.as_deref(),
                            redirect_mode,
                        },
                        &mut runner,
                    )?;
                    println!(
                        "memory plan: {} (private; review plan.json before applying)",
                        output.display()
                    );
                }
                MemoryCommand::Apply { plan } => {
                    lifecycle::apply(&plan, &mut runner)?;
                    println!("memory setup applied; restart sessions and run memory verify; auto-memory unchanged");
                }
                MemoryCommand::Restore { plan } => {
                    lifecycle::restore(&plan, &mut runner)?;
                    println!("memory setup restored; restart sessions to load restored settings");
                }
                MemoryCommand::Verify { plan } => {
                    let report = agent_memory::verify(&plan, &mut runner)?;
                    println!("{}", serde_json::to_string_pretty(&report)?);
                    if report["hook_setup_status"] != "verified" {
                        anyhow::bail!("memory setup firing/configuration is not verified");
                    }
                }
                MemoryCommand::DisableAutoMemory { plan } => {
                    agent_memory::disable_auto_memory(&plan, &mut runner)?
                }
                MemoryCommand::Hook {
                    plan,
                    harness,
                    event,
                } => std::process::exit(hooks::run(&plan, &harness, &event)),
                MemoryCommand::Evidence {
                    plan,
                    harness,
                    event,
                } => println!("{}", hooks::evidence(&plan, &harness, &event)?),
            }
        }
        Commands::Prime {
            brief,
            json,
            offline,
            section,
            timeout_ms,
            rikuy_url,
        } => {
            let opts = caboodle::prime::Options {
                brief,
                json,
                offline,
                section: section.as_deref(),
                timeout: std::time::Duration::from_millis(timeout_ms),
                rikuy_url: rikuy_url.as_deref(),
            };
            match caboodle::prime::run(&opts) {
                Ok(text) => print!("{text}"),
                Err(e) => {
                    eprintln!("{e}");
                    std::process::exit(2);
                }
            }
        }
        Commands::Quickstart {
            plan,
            state,
            skip_install,
            no_agent_hooks,
        } => {
            let selected = if plan.exists() {
                Plan::read(&plan)?
            } else {
                let mut selected = Plan::for_profile(Profile::Retrieval);
                selected.quipu_db = Some(PathBuf::from(".caboodle/quipu.db"));
                selected.write(&plan)?;
                selected
            };
            println!("plan: {}", plan.display());
            engine::apply(&selected, &state, skip_install)?;
            engine::verify(&selected, &state, &CrewEvidence::default())?;
            #[cfg(unix)]
            if !no_agent_hooks {
                install_agent_hooks(Some(&selected), false)?;
            }
        }

        Commands::ProvisionQuipuToken { source, server } => {
            engine::provision_quipu_credential(&source, &server)?;
        }
        #[cfg(unix)]
        Commands::Hooks { command } => match command {
            HooksCommand::Install { plan } => {
                let read = if plan.exists() {
                    Some(Plan::read(&plan)?)
                } else {
                    None
                };
                install_agent_hooks(read.as_ref(), true)?;
            }
            HooksCommand::Verify => {
                let paths = harness_hooks::Paths::from_env()?;
                let findings = harness_hooks::verify(&paths);
                for f in &findings {
                    let label = match f.level {
                        doctor::Level::Ok => "ok  ",
                        doctor::Level::Warn => "warn",
                        doctor::Level::Fail => "FAIL",
                    };
                    println!("{label} {}: {}", f.subject, f.detail);
                }
                if findings.iter().any(|f| f.level != doctor::Level::Ok) {
                    std::process::exit(1);
                }
            }
            HooksCommand::Uninstall => {
                let paths = harness_hooks::Paths::from_env()?;
                for (harness, outcome) in harness_hooks::uninstall(&paths)? {
                    println!("{}: {}", harness.name(), outcome.describe());
                }
            }
        },
        #[cfg(unix)]
        Commands::Hook {
            command: HookCommand::QueryFirst { harness, event },
        } => {
            let harness = harness_hooks::Harness::parse(&harness)?;
            // A hook must never block or fail a session.
            let _ = harness_hooks::run_hook(harness, &event);
        }
        Commands::Doctor { plan, state } => {
            let mut installed = false;
            let scope = if plan.exists() {
                println!("doctor: checking {}", plan.display());
                let read = Plan::read(&plan)?;
                installed = doctor::installed(&read, &State::read(&state)?);
                let mut scope = doctor::Scope::from_plan(&read);
                scope.work_dir = doctor::is_work_dir(&plan);
                scope
            } else {
                println!(
                    "doctor: no plan at {}; checking every tool in the everything profile",
                    plan.display()
                );
                doctor::Scope::everything()
            };
            #[allow(unused_mut)]
            let mut findings = doctor::diagnose(&scope);
            #[cfg(unix)]
            findings.extend(harness_hooks::verify(&harness_hooks::Paths::from_env()?));
            let stdout = std::io::stdout();
            if !doctor::report(&findings, installed, &mut stdout.lock())? {
                std::process::exit(1);
            }
        }
        Commands::Init {
            guided,
            output,
            session,
            pack_hooks,
            monorepo,
            repo,
            shapes_from,
            db,
            trust_file,
        } => {
            if pack_hooks {
                let options = caboodle::pendant_sync::Options {
                    repo: &repo,
                    db: db.as_deref(),
                    shapes_from: shapes_from.as_deref(),
                    trust_file: trust_file.as_deref(),
                    monorepo,
                };
                for path in caboodle::pendant_hooks::install(&options)? {
                    println!("pendant hook: {}", path.display());
                }
                return Ok(());
            }
            if !guided {
                anyhow::bail!("caboodle init currently requires --guided");
            }
            let stdin = std::io::stdin();
            let mut input = stdin.lock();
            let stdout = std::io::stdout();
            let mut output_stream = stdout.lock();
            interview::guided(&mut input, &mut output_stream, &session, &output)?;
        }
        Commands::Plan {
            profile,
            crew,
            intent,
            output,
            shares,
            quipu_db,
            quipu_flavor,
            embedding_model,
            quipu_mcp_url,
            quipu_mcp_token_file,
        } => {
            let profile = Profile::from(profile);
            let crew: CrewMode = crew.into();
            let mut plan = if profile == Profile::Crew {
                Plan::for_crew(crew)
            } else {
                let mut plan = Plan::for_profile(profile);
                if profile == Profile::Everything && crew != CrewMode::Standalone {
                    plan.crew = Some(caboodle::model::CrewSelection::for_mode(crew));
                }
                plan
            };
            plan.shares = shares;
            plan.quipu_db = quipu_db;
            plan.quipu_flavor = quipu_flavor.into();
            if let Some(spec) = embedding_model {
                plan.embedding_model = Some(EmbeddingModel::read(&spec)?);
            }
            plan.quipu_mcp = quipu_mcp_url.map(|url| caboodle::model::QuipuMcp {
                url,
                token_file: quipu_mcp_token_file.or_else(|| {
                    std::env::var("QUIPU_AUTH_TOKEN_FILE")
                        .ok()
                        .filter(|path| !path.is_empty())
                }),
            });
            plan.intent = Some(InstallIntent::read(&intent)?);
            plan.write(&output)?;
            println!("plan: {}", output.display());
        }
        Commands::Apply {
            plan,
            state,
            skip_install,
            host_profile,
        } => {
            engine::apply(
                &read_plan(&plan, host_profile.as_deref())?,
                &state,
                skip_install,
            )?;
        }
        Commands::Verify {
            plan,
            state,
            creel_doctor,
            creel_admission,
            host_profile,
        } => {
            engine::verify(
                &read_plan(&plan, host_profile.as_deref())?,
                &state,
                &CrewEvidence {
                    creel_doctor,
                    creel_admission,
                },
            )?;
        }
        Commands::VerifyMember { member } => {
            caboodle::adapter::verify_member(&member)?;
            println!("{member}: reviewed release functional verification passed");
        }
        Commands::Install {
            plan,
            state,
            skip_install,
            creel_doctor,
            creel_admission,
            host_profile,
            no_agent_hooks,
        } => {
            let plan = read_plan(&plan, host_profile.as_deref())?;
            engine::apply(&plan, &state, skip_install)?;
            engine::verify(
                &plan,
                &state,
                &CrewEvidence {
                    creel_doctor,
                    creel_admission,
                },
            )?;
            #[cfg(unix)]
            if !no_agent_hooks {
                install_agent_hooks(Some(&plan), false)?;
            }
        }
        Commands::CheckUpdates { plan, host_profile } => {
            let plan = read_plan(&plan, host_profile.as_deref())?;
            if !engine::check_updates(&plan)? {
                anyhow::bail!("selected stack has pending reviewed updates");
            }
        }
        Commands::Update {
            plan,
            state,
            creel_doctor,
            creel_admission,
            host_profile,
        } => {
            engine::update(
                &read_plan(&plan, host_profile.as_deref())?,
                &state,
                &CrewEvidence {
                    creel_doctor,
                    creel_admission,
                },
            )?;
        }
        #[cfg(unix)]
        Commands::UpdateSelf {
            state,
            check,
            tag,
            archive_sha256,
            binary_sha256,
        } => match (tag, archive_sha256, binary_sha256) {
            (Some(tag), Some(archive), Some(binary)) => {
                caboodle::release_update::update_self_pinned(
                    &state, check, &tag, &archive, &binary,
                )?
            }
            (Some(tag), None, None) => {
                caboodle::release_update::update_self_at(&state, check, &tag)?
            }
            (None, None, None) => caboodle::release_update::update_self(&state, check)?,
            _ => anyhow::bail!("installer artifact binding requires tag and both SHA256 values"),
        },
        #[cfg(unix)]
        Commands::PostInstallRepair => {
            println!(
                "post-install repair: {}",
                caboodle::adapter::repair_owned_quipu_alias()?
            );
        }
        #[cfg(unix)]
        Commands::BumpMember {
            manifest,
            tag,
            probe_wrapper,
        } => {
            match caboodle::member_bump::bump(&manifest, tag.as_deref(), probe_wrapper.as_deref())?
            {
                caboodle::member_bump::Outcome::Current { version } => {
                    println!(
                        "{}: already pins {version}; nothing written",
                        manifest.display()
                    );
                }
                caboodle::member_bump::Outcome::Bumped { from, to, digests } => {
                    println!("{}: {from} -> {to}", manifest.display());
                    for (target, digest) in digests {
                        println!("  {target} {digest}");
                    }
                    println!(
                        "review the diff and open a PR; it ships in the next caboodle release"
                    );
                }
            }
        }
        #[cfg(unix)]
        Commands::UpdateRelease {
            plan,
            state,
            tool,
            check,
        } => {
            if tool == "shantytown" {
                anyhow::bail!(
                    "shantytown publishes a wheel without a checksum asset; release update refused"
                );
            }
            let tool = serde_json::from_value(serde_json::Value::String(tool))?;
            caboodle::release_update::update(&Plan::read(&plan)?, tool, &state, check)?;
        }
        #[cfg(unix)]
        Commands::RollbackSeeds {
            plan,
            state,
            current_sha256,
            prior_sha256,
        } => {
            caboodle::release_update::rollback_seeds(
                &Plan::read(&plan)?,
                &state,
                &current_sha256,
                &prior_sha256,
            )?;
        }
        Commands::ProjectSettings {
            plan,
            output,
            root,
            agent,
            registry,
            policy_only,
        } => {
            if policy_only {
                for name in projection::write(&Plan::read(&plan)?, &output)? {
                    println!(
                        "policy summary (not MCP registration): {}",
                        output.join(name).display()
                    );
                }
            } else {
                projection::register(root.as_deref(), agent.as_deref(), &registry)?;
            }
        }
        Commands::VerifyQuestions { plan, db } => {
            engine::verify_questions(&Plan::read(&plan)?, db.as_deref())?;
        }
        Commands::RenderObservability {
            plan,
            targets,
            output,
        } => {
            observability::render(&Plan::read(&plan)?, &targets, &output)?;
            println!("observability: {}", output.display());
        }
        Commands::ValidateObservability { output } => {
            observability::validate(&output)?;
            println!("observability contracts: verified");
        }
        Commands::QueueBr { input, queue } => {
            let count = emission::queue_br_jsonl(&input, &queue)?;
            println!("queued lifecycle projections: {count}");
        }
        Commands::FlushEpisodes { queue, endpoint } => {
            let count = emission::flush(&queue, &endpoint)?;
            println!("delivered queued episodes: {count}");
        }
        Commands::Packs {
            command:
                PacksCommand::Sync {
                    monorepo,
                    repo,
                    db,
                    shapes_from,
                    trust_file,
                },
        } => {
            let result = caboodle::pendant_sync::sync(&caboodle::pendant_sync::Options {
                repo: &repo,
                db: db.as_deref(),
                shapes_from: shapes_from.as_deref(),
                trust_file: trust_file.as_deref(),
                monorepo,
            })?;
            println!("{}", serde_json::to_string_pretty(&result)?);
        }
        Commands::Packs {
            command:
                PacksCommand::ProjectScope {
                    graph,
                    path_predicate,
                    prefix,
                    repo,
                    ownership_predicate,
                    db,
                },
        } => {
            let owners = if let (Some(repo), Some(predicate)) = (repo, ownership_predicate) {
                caboodle::pendant_ownership::resolve(&repo, &prefix, &predicate)?
            } else {
                Vec::new()
            };
            let query = caboodle::pendant_projects::enriched_query(
                &graph,
                &path_predicate,
                &prefix,
                &owners,
            )?;
            if let Some(db) = db {
                caboodle::pendant_ownership::verify_owners(&graph, &db, &owners)?;
            }
            println!("{query}");
        }
        Commands::Packs {
            command: PacksCommand::Trust { file, command },
        } => run_pack_trust(file, command)?,
    }
    Ok(())
}

fn run_pack_trust(file: Option<PathBuf>, command: TrustCommand) -> Result<()> {
    use caboodle::pack_trust::{default_path, Decision, TrustConfig};
    let path = match file {
        Some(path) => path,
        None => default_path()?,
    };
    let mut trust = TrustConfig::load(&path)?;
    let changed = match command {
        TrustCommand::Own { owner } => trust.add_owner(&owner)?,
        TrustCommand::Allow { repo, sha256, note } => {
            trust.add_pack(&repo, &sha256, note.as_deref())?
        }
        TrustCommand::AllowEndpoint {
            repo,
            endpoint,
            note,
        } => trust.add_endpoint(&repo, &endpoint, note.as_deref())?,
        TrustCommand::CheckEndpoint { remote, endpoint } => {
            match trust.decide_endpoint(&remote, &endpoint) {
                Decision::Allow { basis } => println!("federate: {basis}"),
                Decision::Refuse { .. } => {
                    // Policy errors can embed the raw URL, including userinfo.
                    // Keep this read-only command's diagnostics free of input.
                    eprintln!("refused: endpoint trust policy did not admit this request; check the repository and endpoint, then review packs trust --help");
                    std::process::exit(3);
                }
            }
            return Ok(());
        }
        TrustCommand::List => {
            print!("{}", toml::to_string_pretty(&trust)?);
            return Ok(());
        }
        TrustCommand::Check {
            remote,
            sha256,
            pack,
        } => {
            match trust.decide_pack(&remote, &pack, &sha256) {
                Decision::Allow { basis } => println!("load: {basis}"),
                Decision::Refuse { message } => {
                    eprintln!("refused: {message}");
                    std::process::exit(3);
                }
            }
            return Ok(());
        }
    };
    if changed {
        trust.save(&path)?;
        println!("recorded in {}", path.display());
    } else {
        println!("already recorded in {}", path.display());
    }
    Ok(())
}

/// Read a plan and apply `--host-profile`, printing each exclusion so an
/// excluded runtime is visible and never mistaken for a verified one.
fn read_plan(path: &std::path::Path, host_profile: Option<&str>) -> anyhow::Result<Plan> {
    let (plan, excluded) = Plan::read(path)?.for_host(host_profile)?;
    for line in excluded {
        println!("{line}");
    }
    Ok(plan)
}

#[cfg(all(test, unix))]
mod memory_cli_tests {
    use super::*;

    #[test]
    fn redirect_mode_defaults_to_copy_and_requires_a_known_choice() {
        let required = [
            "tambo",
            "memory",
            "plan",
            "--root",
            "/tmp/crew",
            "--bobbin-config",
            "/tmp/bobbin.toml",
            "--person",
            "person-fixture",
            "--camayoc-source",
            "/tmp/source",
            "--output",
            "/tmp/private-plan",
        ];
        for choice in [None, Some("copy"), Some("block"), Some("off")] {
            let mut args = required.to_vec();
            if let Some(mode) = choice {
                args.extend(["--redirect-mode", mode]);
            }
            let cli = Cli::try_parse_from(args).unwrap();
            let Commands::Memory {
                command: MemoryCommand::Plan { redirect_mode, .. },
            } = cli.command
            else {
                panic!("expected memory plan");
            };
            assert_eq!(redirect_mode.as_str(), choice.unwrap_or("copy"));
        }
        let mut bad = required.to_vec();
        bad.extend(["--redirect-mode", "surprise"]);
        assert!(Cli::try_parse_from(bad).is_err());
    }
}

/// Add the query-first hooks, naming the plan's local store when it has one.
#[cfg(unix)]
fn install_agent_hooks(plan: Option<&Plan>, explicit: bool) -> Result<()> {
    use harness_hooks::{install, Paths, Target};
    let plan_crew = plan
        .and_then(|p| p.crew.as_ref())
        .is_some_and(|c| matches!(c.mode, CrewMode::Shantytown | CrewMode::Both));
    if let Some(reason) =
        harness_hooks::crew_host_reason(std::env::var_os("SHANTY_ROOT").as_deref(), plan_crew)
    {
        if explicit {
            anyhow::bail!(
                "this is a shantytown crew host ({reason}): st already gives crew sessions the \
                 query-first directive, and user-level hooks would add a second copy; nothing was written"
            );
        }
        println!("agent hooks: skipped on this shantytown crew host ({reason}); st provides the query-first directive");
        return Ok(());
    }
    let db = match plan.and_then(|p| p.quipu_db.as_deref()) {
        Some(db) if db.is_absolute() => Some(db.to_path_buf()),
        Some(db) => Some(std::env::current_dir()?.join(db)),
        None => None,
    };
    let tambo = std::env::current_exe()?;
    for (harness, outcome) in install(&Paths::from_env()?, &tambo, &Target { db })? {
        println!("{} hooks: {}", harness.name(), outcome.describe());
        if harness == harness_hooks::Harness::Codex && outcome == harness_hooks::Outcome::Written {
            println!("codex hooks: the next `codex` start asks you to review them; Codex runs them only after you trust them");
        }
    }
    Ok(())
}