lifeloop-cli 0.1.0

Provider-neutral lifecycle abstraction and normalizer for AI harnesses
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
//! Host integration asset rendering and merge behavior.
//!
//! Lifeloop owns the file shape, merge safety, and status reporting for
//! lifecycle integration assets installed into harness host directories
//! (`.claude/`, `.codex/`, `.hermes/`, `.openclaw/`). The `host apply`
//! and `host inspect` compatibility commands route here.
//!
//! # Boundary (issue #4)
//!
//! This module owns:
//! * rendering source/applied asset content as in-memory data,
//! * additive-merge logic that preserves user-owned entries,
//! * asset status reporting (`Present`/`Missing`/`Drifted`/`InvalidMode`/
//!   `NotApplicable`),
//! * supported-mode rules for each adapter.
//!
//! This module does **not** own:
//! * the hook protocol command strings themselves (those are issue #3 —
//!   the strings appear here only as opaque compatibility labels that the
//!   merge logic must recognize so it can scrub stale entries);
//! * the full adapter manifest registry (issue #6);
//! * lifecycle routing (issue #7);
//! * telemetry parsing (issue #5);
//! * filesystem IO. Callers handle reads, writes, mode bits, and atomic
//!   replace. This module is pure: it operates on `serde_json::Value`,
//!   strings, and byte slices.
//!
//! # CCD compatibility
//!
//! The command-prefix constants and legacy recognizer patterns
//! (`CCD_COMPAT_*`) are CCD compatibility labels — Lifeloop's first
//! client wires its own binary into harness hooks via these prefixes.
//! They are *not* core Lifeloop semantics: a future non-CCD client
//! gets its own profile in the same shape. Keeping them in one place
//! makes the compat surface auditable.
//!
//! # Lifecycle integration profiles (issue #26)
//!
//! [`LifecycleProfile`] generalizes the CCD-shaped command-prefix /
//! managed-event surface into a per-client-profile struct. The free
//! functions exported from this module keep their CCD-compat default
//! behavior (they delegate to [`CCD_COMPAT_PROFILE`]); paired
//! `*_with_profile` variants accept any profile so a non-CCD client
//! (e.g. [`LIFELOOP_DIRECT_PROFILE`], the post-slimdown shape where
//! the harness invokes the `lifeloop` CLI directly without CCD as
//! broker) can render and merge its own lifecycle hook assets without
//! editing core merge logic. This is the bridge contemplated by
//! `docs/release-gates.md` for the CCD slimdown
//! (dusk-network/ccd#723) — the slimdown lands by switching active
//! installs from `CCD_COMPAT_PROFILE` to a non-CCD profile, not by
//! rewriting the renderer.

use serde_json::{Value, json};

// ============================================================================
// Adapters and modes
// ============================================================================

/// Host adapters Lifeloop ships asset rendering and merge support for.
///
/// The on-the-wire identifier (`as_str()`) is the same string an
/// `AdapterManifest::adapter_id` would carry for the same harness; issue
/// #6 lands the full manifest registry that consumes these ids.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum HostAdapter {
    Claude,
    Codex,
    Hermes,
    OpenClaw,
}

impl HostAdapter {
    pub const ALL: &'static [Self] = &[Self::Claude, Self::Codex, Self::Hermes, Self::OpenClaw];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Claude => "claude",
            Self::Codex => "codex",
            Self::Hermes => "hermes",
            Self::OpenClaw => "openclaw",
        }
    }

    /// Recognizes both canonical ids and the historical CCD aliases (e.g.
    /// `claude-code`). Returns `None` for unknown names.
    pub fn from_id(name: &str) -> Option<Self> {
        match name {
            "claude" | "claude-code" => Some(Self::Claude),
            "codex" => Some(Self::Codex),
            "hermes" => Some(Self::Hermes),
            "openclaw" => Some(Self::OpenClaw),
            _ => None,
        }
    }

    /// Default integration mode when the host has no explicit declaration.
    pub fn default_mode(self) -> IntegrationMode {
        match self {
            Self::Claude => IntegrationMode::NativeHook,
            Self::Codex => IntegrationMode::ManualSkill,
            Self::Hermes | Self::OpenClaw => IntegrationMode::ReferenceAdapter,
        }
    }
}

/// Integration modes supported by host asset rendering.
///
/// Mirrors the subset of [`crate::IntegrationMode`] that maps to actual
/// installable assets. `TelemetryOnly` does not produce assets and is
/// therefore not represented here; callers that have a full
/// `IntegrationMode` can convert with [`Self::from_lifecycle_mode`].
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum IntegrationMode {
    ManualSkill,
    LauncherWrapper,
    NativeHook,
    ReferenceAdapter,
}

impl IntegrationMode {
    pub const ALL: &'static [Self] = &[
        Self::ManualSkill,
        Self::LauncherWrapper,
        Self::NativeHook,
        Self::ReferenceAdapter,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::ManualSkill => "manual_skill",
            Self::LauncherWrapper => "launcher_wrapper",
            Self::NativeHook => "native_hook",
            Self::ReferenceAdapter => "reference_adapter",
        }
    }

    pub fn from_id(value: &str) -> Option<Self> {
        match value {
            "manual_skill" => Some(Self::ManualSkill),
            "launcher_wrapper" => Some(Self::LauncherWrapper),
            "native_hook" => Some(Self::NativeHook),
            "reference_adapter" => Some(Self::ReferenceAdapter),
            _ => None,
        }
    }

    /// Convert from the broader [`crate::IntegrationMode`]. Returns `None`
    /// for `TelemetryOnly`, which has no asset surface.
    pub fn from_lifecycle_mode(mode: crate::IntegrationMode) -> Option<Self> {
        match mode {
            crate::IntegrationMode::ManualSkill => Some(Self::ManualSkill),
            crate::IntegrationMode::LauncherWrapper => Some(Self::LauncherWrapper),
            crate::IntegrationMode::NativeHook => Some(Self::NativeHook),
            crate::IntegrationMode::ReferenceAdapter => Some(Self::ReferenceAdapter),
            crate::IntegrationMode::TelemetryOnly => None,
        }
    }
}

/// Whether `host` supports the requested install mode. Gates `apply` so a
/// caller can refuse before mutating files.
pub fn supports_mode(host: HostAdapter, mode: IntegrationMode) -> bool {
    match host {
        HostAdapter::Claude => mode == IntegrationMode::NativeHook,
        HostAdapter::Codex => matches!(
            mode,
            IntegrationMode::ManualSkill
                | IntegrationMode::LauncherWrapper
                | IntegrationMode::NativeHook
        ),
        HostAdapter::Hermes | HostAdapter::OpenClaw => mode == IntegrationMode::ReferenceAdapter,
    }
}

/// Modes the adapter accepts, in declaration order, for diagnostic
/// messaging. Order is informational.
pub fn supported_modes(host: HostAdapter) -> &'static [IntegrationMode] {
    match host {
        HostAdapter::Claude => &[IntegrationMode::NativeHook],
        HostAdapter::Codex => &[
            IntegrationMode::ManualSkill,
            IntegrationMode::LauncherWrapper,
            IntegrationMode::NativeHook,
        ],
        HostAdapter::Hermes | HostAdapter::OpenClaw => &[IntegrationMode::ReferenceAdapter],
    }
}

// ============================================================================
// Asset descriptor and status
// ============================================================================

/// One file Lifeloop renders for a host adapter. `relative_path` is
/// relative to the repository root the caller is rendering into. `mode`
/// is a Unix permission bitmask when present; callers on non-Unix
/// targets may ignore it, but cross-checking is still meaningful for
/// status reporting.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RenderedAsset {
    pub relative_path: &'static str,
    pub contents: String,
    pub mode: Option<u32>,
}

/// Status of an installed asset relative to the rendered template.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AssetStatus {
    /// The on-disk asset matches the rendered shape.
    Present,
    /// The asset path does not exist.
    Missing,
    /// The asset exists but its content (or permission mode) differs from
    /// what Lifeloop would render. For merge-aware assets this means the
    /// merge result no longer matches the file.
    Drifted,
    /// The (host, mode) pair is not a supported install combination.
    InvalidMode,
    /// No asset is expected for this (host, mode) pair.
    NotApplicable,
}

/// Action taken for one asset during apply.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileAction {
    /// The asset was created.
    Installed,
    /// The asset existed and was rewritten with new content.
    Updated,
    /// The asset matched the rendered template; no write was needed.
    AlreadyPresent,
}

/// Combine `current` with `next` so a multi-file apply reports the
/// strongest action seen. `Updated` dominates `Installed` dominates
/// `AlreadyPresent`.
pub fn combine_actions(current: FileAction, next: FileAction) -> FileAction {
    match (current, next) {
        (FileAction::Updated, _) | (_, FileAction::Updated) => FileAction::Updated,
        (FileAction::Installed, _) | (_, FileAction::Installed) => FileAction::Installed,
        _ => FileAction::AlreadyPresent,
    }
}

/// Outcome of merging managed entries into an existing settings/hooks
/// file. `existing` is the prior file content (`None` if the file did
/// not exist); `rendered` is the merged content the caller should
/// write.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MergedFile {
    pub existing: Option<String>,
    pub rendered: String,
}

/// Errors returned by merge or render entry points. Callers convert as
/// needed; the variants are pinned so downstream tests can match.
#[derive(Debug)]
pub enum HostAssetError {
    /// The (host, mode) pair is not a supported install combination.
    UnsupportedMode {
        host: HostAdapter,
        mode: IntegrationMode,
    },
    /// The existing file's top-level shape conflicts with the merge
    /// invariants (e.g. `hooks` is an array instead of an object).
    Malformed { reason: String },
    /// The existing file is invalid JSON or TOML.
    Parse { reason: String },
    /// Re-serialization failed (should be unreachable for well-formed
    /// inputs; surfaced rather than panicked).
    Serialize { reason: String },
}

impl std::fmt::Display for HostAssetError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnsupportedMode { host, mode } => write!(
                f,
                "unsupported mode `{}` for {} (supported: {})",
                mode.as_str(),
                host.as_str(),
                supported_modes(*host)
                    .iter()
                    .map(|m| m.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::Malformed { reason } => write!(f, "malformed managed file: {reason}"),
            Self::Parse { reason } => write!(f, "parse error: {reason}"),
            Self::Serialize { reason } => write!(f, "serialize error: {reason}"),
        }
    }
}

impl std::error::Error for HostAssetError {}

// ============================================================================
// Path constants
// ============================================================================

pub const CLAUDE_SOURCE_SETTINGS: &str = ".ccd-hosts/claude/settings.json";
pub const CLAUDE_TARGET_SETTINGS: &str = ".claude/settings.json";

pub const CODEX_SOURCE_README: &str = ".ccd-hosts/codex/README.md";
pub const CODEX_SOURCE_LAUNCHER: &str = ".ccd-hosts/codex/launcher.sh";
pub const CODEX_SOURCE_CONFIG: &str = ".ccd-hosts/codex/config.toml";
pub const CODEX_SOURCE_HOOKS: &str = ".ccd-hosts/codex/hooks.json";
pub const CODEX_TARGET_LAUNCHER: &str = ".codex/ccd-launch.sh";
pub const CODEX_TARGET_CONFIG: &str = ".codex/config.toml";
pub const CODEX_TARGET_HOOKS: &str = ".codex/hooks.json";

pub const OPENCLAW_SOURCE_ADAPTER: &str = ".ccd-hosts/openclaw/adapter.json";
pub const OPENCLAW_TARGET_ADAPTER: &str = ".openclaw/ccd.json";

pub const HERMES_SOURCE_ADAPTER: &str = ".ccd-hosts/hermes/adapter.json";
pub const HERMES_TARGET_ADAPTER: &str = ".hermes/ccd.json";

// ============================================================================
// Lifecycle integration profiles
// ============================================================================
//
// A `LifecycleProfile` captures the per-client-profile facts that vary
// between integration profiles: per-host command prefixes, the legacy
// substrings the merge logic should scrub for that profile, and the
// managed event tables Lifeloop installs into each host's hook config
// for that profile. The renderers and merge logic consult a profile
// rather than hardcoding any one client's binary or command prefix,
// so adding a new profile does not require editing core merge logic.
// See the module rustdoc for the slimdown narrative this enables.

/// Per-client-profile data driving lifecycle integration asset
/// rendering and merge.
///
/// This struct expresses the client-shape of a host integration
/// profile (e.g. CCD compatibility, lifeloop-direct callback) without
/// pulling client semantics into core types. It is a pure data
/// surface: every field is `'static` and the methods are pure
/// functions of those fields.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct LifecycleProfile {
    /// Stable profile identifier (e.g. `"ccd-compat"`,
    /// `"lifeloop-direct"`). Used in diagnostics; not part of the
    /// rendered asset content.
    pub id: &'static str,
    /// Command prefix Lifeloop renders into `.claude/settings.json`
    /// for managed hook entries. The merge logic uses it as a
    /// managed-entry marker (it scrubs entries whose `command`
    /// starts with this prefix and rewrites them).
    pub claude_command_prefix: &'static str,
    /// Substrings inside `.claude/settings.json` `command` strings
    /// that the merge logic also treats as managed (legacy/pre-v1
    /// forms whose shape changed across releases). Always merged
    /// WITH the prefix scrub, never replacing it. Empty when the
    /// profile has no legacy shape to scrub.
    pub claude_legacy_substrings: &'static [&'static str],
    /// `(claude_event, hook_arg, matcher_pattern)` tuples this
    /// profile installs into Claude's hook config.
    pub claude_managed_events: &'static [(&'static str, &'static str, &'static str)],
    /// Command prefix Lifeloop renders into `.codex/hooks.json` for
    /// managed hook entries. Merge logic scrubs entries whose
    /// `command` starts with it.
    pub codex_command_prefix: &'static str,
    /// `(codex_event, hook_arg, matcher_pattern, status_message)`
    /// tuples this profile installs into Codex's hook config.
    pub codex_managed_events: &'static [(&'static str, &'static str, &'static str, &'static str)],
}

impl LifecycleProfile {
    /// Render this profile's `.claude/settings.json` hook command for
    /// `hook_arg`.
    pub fn claude_command(&self, hook_arg: &str) -> String {
        format!("{}{}", self.claude_command_prefix, hook_arg)
    }

    /// Render this profile's `.codex/hooks.json` hook command for
    /// `hook_arg`.
    pub fn codex_command(&self, hook_arg: &str) -> String {
        format!("{}{}", self.codex_command_prefix, hook_arg)
    }

    /// True when `entry` is recognized as a managed `.claude/settings.json`
    /// hook for this profile — either the modern command prefix or any
    /// of `claude_legacy_substrings`. Used by the merge logic to scrub
    /// stale managed entries before rewriting them.
    fn claude_entry_is_managed_or_legacy(&self, entry: &Value) -> bool {
        let cmd = entry.get("command").and_then(Value::as_str).unwrap_or("");
        cmd.starts_with(self.claude_command_prefix)
            || self
                .claude_legacy_substrings
                .iter()
                .any(|legacy| cmd.contains(legacy))
    }

    /// True when `entry` is recognized as a managed `.codex/hooks.json`
    /// hook for this profile.
    fn codex_entry_is_managed(&self, entry: &Value) -> bool {
        entry
            .get("command")
            .and_then(Value::as_str)
            .map(|cmd| cmd.starts_with(self.codex_command_prefix))
            .unwrap_or(false)
    }
}

// ----------------------------------------------------------------------------
// Shared event tables
// ----------------------------------------------------------------------------
//
// These tables describe the lifecycle events Lifeloop installs into a
// host's hook config. They are shared across profiles because the
// lifecycle event vocabulary is harness-defined, not client-defined —
// what varies across profiles is the *command prefix* that wraps each
// event's hook arg, not the (event, hook arg, matcher) triple. A
// future profile that needs to skip an event or use a different hook
// arg can simply ship its own table.

/// (claude_event, hook_arg, matcher_pattern). `TaskCompleted` is
/// intentionally excluded — only `Stop` fires reliably at end-of-turn
/// in Claude's hook protocol.
const STANDARD_CLAUDE_MANAGED_EVENTS: &[(&str, &str, &str)] = &[
    (
        "SessionStart",
        "on-session-start",
        "startup|resume|clear|compact",
    ),
    ("UserPromptSubmit", "before-prompt-build", "*"),
    ("PreCompact", "on-compaction-notice", "*"),
    ("Stop", "on-agent-end", "*"),
    ("SessionEnd", "on-session-end", "*"),
];

/// (codex_event, hook_arg, matcher_pattern, status_message). Codex's
/// hook surface does not expose `PreCompact` or `SessionEnd`, so the
/// table is shorter than the Claude one.
const STANDARD_CODEX_MANAGED_EVENTS: &[(&str, &str, &str, &str)] = &[
    (
        "SessionStart",
        "on-session-start",
        "startup|resume|clear",
        "Loading CCD session context",
    ),
    (
        "UserPromptSubmit",
        "before-prompt-build",
        "*",
        "Refreshing CCD prompt context",
    ),
    (
        "PreCompact",
        "on-compaction-notice",
        "*",
        "Recording CCD compaction boundary",
    ),
    (
        "PostCompact",
        "on-compaction-notice",
        "*",
        "Recording CCD compacted context boundary",
    ),
    (
        "Stop",
        "on-agent-end",
        "*",
        "Checking CCD continuation boundary",
    ),
];

/// (codex_event, hook_arg, matcher_pattern, status_message) for the
/// post-slimdown lifeloop-direct profile. Status text reads
/// "Lifeloop ..." rather than "CCD ..." so the operator-facing
/// messaging matches the binary actually invoked.
const LIFELOOP_DIRECT_CODEX_MANAGED_EVENTS: &[(&str, &str, &str, &str)] = &[
    (
        "SessionStart",
        "on-session-start",
        "startup|resume|clear",
        "Loading Lifeloop session context",
    ),
    (
        "UserPromptSubmit",
        "before-prompt-build",
        "*",
        "Refreshing Lifeloop prompt context",
    ),
    (
        "Stop",
        "on-agent-end",
        "*",
        "Checking Lifeloop continuation boundary",
    ),
];

// ----------------------------------------------------------------------------
// Built-in profiles
// ----------------------------------------------------------------------------

/// CCD compatibility profile: the harness invokes `${CCD_BIN:-ccd}
/// host-hook ...` and CCD acts as the broker that calls back into
/// Lifeloop. This is Lifeloop's first client and its current
/// production install shape.
pub const CCD_COMPAT_PROFILE: LifecycleProfile = LifecycleProfile {
    id: "ccd-compat",
    claude_command_prefix: "\"${CCD_BIN:-ccd}\" --output hook-protocol host-hook --path \"$CLAUDE_PROJECT_DIR\" --host claude --hook ",
    claude_legacy_substrings: &["ccd-hook.py"],
    claude_managed_events: STANDARD_CLAUDE_MANAGED_EVENTS,
    codex_command_prefix: "\"${CCD_BIN:-ccd}\" --output hook-protocol host-hook --path \"$(git rev-parse --show-toplevel)\" --host codex --hook ",
    codex_managed_events: STANDARD_CODEX_MANAGED_EVENTS,
};

/// Lifeloop-direct callback profile: the harness invokes
/// `${LIFELOOP_BIN:-lifeloop} host-hook ...` directly, with no CCD
/// in the loop. This is the post-slimdown shape contemplated by
/// dusk-network/ccd#723 — landing it as a built-in profile lets a
/// non-CCD pilot exercise the full host-asset rendering path before
/// the slimdown work commits to it.
pub const LIFELOOP_DIRECT_PROFILE: LifecycleProfile = LifecycleProfile {
    id: "lifeloop-direct",
    claude_command_prefix: "\"${LIFELOOP_BIN:-lifeloop}\" --output hook-protocol host-hook --path \"$CLAUDE_PROJECT_DIR\" --host claude --hook ",
    // The lifeloop-direct profile is the documented successor to the
    // CCD-compat profile (see `docs/decisions/lifecycle-profiles.md`
    // and `docs/release-gates.md` on dusk-network/ccd#723). Treating
    // CCD-compat entries as legacy ensures that an operator who runs
    // a lifeloop-direct merge over an existing CCD-compat
    // settings.json gets a single set of managed hooks in the new
    // shape — not two coexisting sets — which is what "switch
    // profiles" means at the install layer. The pre-v1 Python-bridge
    // substring is also recognized for the same reason. The reverse
    // direction (CCD-compat merge over lifeloop-direct) is
    // intentionally additive, since CCD has no claim to a successor
    // profile's shape; that asymmetry is pinned by tests in
    // `tests/host_assets_profiles.rs`.
    claude_legacy_substrings: &[CCD_COMPAT_PROFILE.claude_command_prefix, "ccd-hook.py"],
    claude_managed_events: STANDARD_CLAUDE_MANAGED_EVENTS,
    codex_command_prefix: "\"${LIFELOOP_BIN:-lifeloop}\" --output hook-protocol host-hook --path \"$(git rev-parse --show-toplevel)\" --host codex --hook ",
    codex_managed_events: LIFELOOP_DIRECT_CODEX_MANAGED_EVENTS,
};

// ----------------------------------------------------------------------------
// CCD-compat back-compat aliases
// ----------------------------------------------------------------------------
//
// The constants and helpers below preserve the pre-#26 public API
// while delegating to `CCD_COMPAT_PROFILE`. Keeping them in place
// avoids a churn ripple across in-tree callers and downstream
// consumers (CCD itself imports `CCD_COMPAT_CLAUDE_COMMAND_PREFIX` to
// produce matching strings during host-hook receipts).

/// Command prefix Lifeloop renders into `.claude/settings.json` for
/// CCD-managed hook entries. Equal to
/// [`CCD_COMPAT_PROFILE`]`.claude_command_prefix`.
pub const CCD_COMPAT_CLAUDE_COMMAND_PREFIX: &str = CCD_COMPAT_PROFILE.claude_command_prefix;

/// Command prefix Lifeloop renders into `.codex/hooks.json` for
/// CCD-managed hook entries. Equal to
/// [`CCD_COMPAT_PROFILE`]`.codex_command_prefix`.
pub const CCD_COMPAT_CODEX_COMMAND_PREFIX: &str = CCD_COMPAT_PROFILE.codex_command_prefix;

/// Substring that identifies the pre-v1 Python bridge entries in
/// `.claude/settings.json`. Merge logic scrubs these even when the
/// modern command prefix has changed.
pub const CCD_COMPAT_CLAUDE_LEGACY_PYTHON_HOOK: &str = "ccd-hook.py";

/// Render a CCD-compat `.claude/settings.json` hook command for `hook_arg`.
pub fn ccd_compat_claude_command(hook_arg: &str) -> String {
    CCD_COMPAT_PROFILE.claude_command(hook_arg)
}

/// Render a CCD-compat `.codex/hooks.json` hook command for `hook_arg`.
pub fn ccd_compat_codex_command(hook_arg: &str) -> String {
    CCD_COMPAT_PROFILE.codex_command(hook_arg)
}

// ============================================================================
// Asset rendering
// ============================================================================

/// Full set of source-tree assets for a host using the default
/// [`CCD_COMPAT_PROFILE`]. These are the templates that land under
/// `.ccd-hosts/<host>/`.
pub fn render_source_assets(host: HostAdapter) -> Vec<RenderedAsset> {
    render_source_assets_with_profile(host, &CCD_COMPAT_PROFILE)
}

/// Full set of source-tree assets for a host rendered with
/// `profile`'s command prefixes and managed event tables. See
/// [`render_applied_assets_with_profile`] for the per-profile vs.
/// per-host scope split.
pub fn render_source_assets_with_profile(
    host: HostAdapter,
    profile: &LifecycleProfile,
) -> Vec<RenderedAsset> {
    match host {
        HostAdapter::Claude => vec![RenderedAsset {
            relative_path: CLAUDE_SOURCE_SETTINGS,
            contents: claude_settings_json_for(profile),
            mode: None,
        }],
        HostAdapter::Codex => vec![
            RenderedAsset {
                relative_path: CODEX_SOURCE_README,
                contents: codex_guidance_readme(),
                mode: None,
            },
            RenderedAsset {
                relative_path: CODEX_SOURCE_CONFIG,
                contents: codex_config_toml(),
                mode: None,
            },
            RenderedAsset {
                relative_path: CODEX_SOURCE_HOOKS,
                contents: codex_hooks_json_for(profile),
                mode: None,
            },
            RenderedAsset {
                relative_path: CODEX_SOURCE_LAUNCHER,
                contents: codex_launcher_script(),
                mode: Some(0o755),
            },
        ],
        HostAdapter::Hermes => vec![RenderedAsset {
            relative_path: HERMES_SOURCE_ADAPTER,
            contents: hermes_adapter_json(),
            mode: None,
        }],
        HostAdapter::OpenClaw => vec![RenderedAsset {
            relative_path: OPENCLAW_SOURCE_ADAPTER,
            contents: openclaw_adapter_json(),
            mode: None,
        }],
    }
}

/// Subset of [`render_source_assets`] required for the given mode.
/// Modes that pin only a few of a host's source files (Codex
/// manual-skill, launcher-wrapper) trim the list so absent files don't
/// trigger spurious "missing scaffold" errors.
pub fn render_required_source_assets(
    host: HostAdapter,
    mode: IntegrationMode,
) -> Vec<RenderedAsset> {
    let assets = render_source_assets(host);
    let required_paths: &[&str] = match (host, mode) {
        (HostAdapter::Codex, IntegrationMode::ManualSkill) => &[CODEX_SOURCE_README],
        (HostAdapter::Codex, IntegrationMode::LauncherWrapper) => {
            &[CODEX_SOURCE_README, CODEX_SOURCE_LAUNCHER]
        }
        (HostAdapter::Codex, IntegrationMode::NativeHook) => {
            &[CODEX_SOURCE_README, CODEX_SOURCE_CONFIG, CODEX_SOURCE_HOOKS]
        }
        _ => return assets,
    };
    assets
        .into_iter()
        .filter(|asset| required_paths.contains(&asset.relative_path))
        .collect()
}

/// Assets to apply into the host's runtime directories (`.claude/`,
/// `.codex/`, `.hermes/`, `.openclaw/`) using the default
/// [`CCD_COMPAT_PROFILE`]. Empty when the (host, mode) pair has no
/// installable files (e.g. Codex manual-skill mode is scaffold-only).
///
/// This is a thin wrapper over [`render_applied_assets_with_profile`];
/// callers that want non-CCD command prefixes pass an explicit
/// profile.
pub fn render_applied_assets(host: HostAdapter, mode: IntegrationMode) -> Vec<RenderedAsset> {
    render_applied_assets_with_profile(host, mode, &CCD_COMPAT_PROFILE)
}

/// Assets to apply into the host's runtime directories rendered with
/// `profile`'s command prefixes and managed event tables.
///
/// Hermes and OpenClaw reference adapters currently render with a
/// CCD-flavored adapter JSON regardless of `profile`: those files are
/// per-host illustrative documentation, not active command surfaces,
/// and graduating them to per-profile rendering is a follow-up scoped
/// outside #26.
pub fn render_applied_assets_with_profile(
    host: HostAdapter,
    mode: IntegrationMode,
    profile: &LifecycleProfile,
) -> Vec<RenderedAsset> {
    match (host, mode) {
        (HostAdapter::Claude, IntegrationMode::NativeHook) => vec![RenderedAsset {
            relative_path: CLAUDE_TARGET_SETTINGS,
            contents: claude_settings_json_for(profile),
            mode: None,
        }],
        (HostAdapter::Codex, IntegrationMode::LauncherWrapper) => vec![RenderedAsset {
            relative_path: CODEX_TARGET_LAUNCHER,
            contents: codex_launcher_script(),
            mode: Some(0o755),
        }],
        (HostAdapter::Codex, IntegrationMode::NativeHook) => vec![
            RenderedAsset {
                relative_path: CODEX_TARGET_CONFIG,
                contents: codex_config_toml(),
                mode: None,
            },
            RenderedAsset {
                relative_path: CODEX_TARGET_HOOKS,
                contents: codex_hooks_json_for(profile),
                mode: None,
            },
        ],
        (HostAdapter::Codex, IntegrationMode::ManualSkill) => Vec::new(),
        (HostAdapter::Hermes, IntegrationMode::ReferenceAdapter) => vec![RenderedAsset {
            relative_path: HERMES_TARGET_ADAPTER,
            contents: hermes_adapter_json(),
            mode: None,
        }],
        (HostAdapter::OpenClaw, IntegrationMode::ReferenceAdapter) => vec![RenderedAsset {
            relative_path: OPENCLAW_TARGET_ADAPTER,
            contents: openclaw_adapter_json(),
            mode: None,
        }],
        _ => Vec::new(),
    }
}

// ============================================================================
// Asset content (private renderers)
// ============================================================================

fn claude_settings_json_for(profile: &LifecycleProfile) -> String {
    let mut hooks = serde_json::Map::new();
    for (event, hook_arg, matcher) in profile.claude_managed_events {
        hooks.insert(
            (*event).to_string(),
            json!([{
                "matcher": matcher,
                "hooks": [{
                    "type": "command",
                    "command": profile.claude_command(hook_arg),
                }]
            }]),
        );
    }
    let value = json!({ "hooks": Value::Object(hooks) });
    serde_json::to_string_pretty(&value).expect("claude settings json")
}

fn codex_guidance_readme() -> String {
    format!(
        r#"<!-- CCD-MANAGED -->
# Codex Host Guidance

Codex supports native repo-local hooks when `hooks` is enabled in
`.codex/config.toml` and `.codex/hooks.json` maps lifecycle events into CCD.

CCD installs a minimal native mapping:

- `SessionStart` -> `ccd host-hook --hook on-session-start`
- `UserPromptSubmit` -> `ccd host-hook --hook before-prompt-build`
- `PreCompact` -> `ccd host-hook --hook on-compaction-notice`
- `PostCompact` -> `ccd host-hook --hook on-compaction-notice`
- `Stop` -> `ccd host-hook --hook on-agent-end`

Human-driven Codex can still fall back to the manual CCD startup path:

- `/ccd-start`
- `ccd start --activate --path .`

That fallback is tracked as `manual_skill`, not as a product failure.

If you want the optional zero-ritual launcher/eval harness instead, run:

```bash
ccd host apply --host codex --with-launcher --path .
```

That applies the launcher wrapper at `./{CODEX_TARGET_LAUNCHER}`.
"#
    )
}

fn codex_config_toml() -> String {
    "[features]\nhooks = true\n".to_owned()
}

fn codex_hooks_json_for(profile: &LifecycleProfile) -> String {
    let merged = merge_codex_hooks_with_profile(json!({}), profile)
        .expect("empty object is a valid Codex hooks base for managed events");
    serde_json::to_string_pretty(&merged).expect("codex hooks json")
}

fn codex_launcher_script() -> String {
    r#"#!/bin/sh
# CCD-MANAGED
# Optional Codex launcher/eval harness.

set -e

if [ -n "$CCD_BIN" ] && [ -x "$CCD_BIN" ]; then
    CCD="$CCD_BIN"
elif command -v ccd >/dev/null 2>&1; then
    CCD=ccd
elif [ -x "$HOME/.ccd/bin/ccd" ]; then
    CCD="$HOME/.ccd/bin/ccd"
elif [ -x "$HOME/.cargo/bin/ccd" ]; then
    CCD="$HOME/.cargo/bin/ccd"
else
    CCD=""
fi

if [ -n "$CCD" ]; then
    "$CCD" host-hook --output json --path . --host codex --hook on-session-start >/dev/null 2>&1 || true
fi

exec codex "$@"
"#
    .to_owned()
}

fn openclaw_adapter_json() -> String {
    serde_json::to_string_pretty(&json!({
        "host": "openclaw",
        "integration_mode": "reference_adapter",
        "commands": {
            "session_start": "ccd --output json host-hook --path . --host openclaw --hook on-session-start --mode implement --lifecycle autonomous --owner-kind runtime-worker --actor-id runtime/openclaw-agent-1 --lease-seconds 900 --host-session-id acp-session-42 --host-run-id acp-run-42 --host-task-id req-openclaw-42",
            "before_prompt_build": "ccd host-hook --path . --host openclaw --hook before-prompt-build",
            "on_compaction_notice": "ccd host-hook --path . --host openclaw --hook on-compaction-notice",
            "on_agent_end": "ccd host-hook --path . --host openclaw --hook on-agent-end",
            "on_session_end": "ccd host-hook --path . --host openclaw --hook on-session-end"
        },
        "notes": [
            "Inject only the top-level context payload into prompt-build.",
            "Keep runtime transcript history outside CCD durable state.",
            "Use separate worktrees for parallel writers."
        ]
    }))
    .expect("openclaw adapter json")
}

fn hermes_adapter_json() -> String {
    serde_json::to_string_pretty(&json!({
        "host": "hermes",
        "integration_mode": "reference_adapter",
        "commands": {
            "session_start": "ccd host-hook --output json --path . --host hermes --hook on-session-start --mode implement --lifecycle autonomous --actor-id runtime/hermes-worker-1 --supervisor-id runtime/hermes-supervisor-1 --lease-seconds 900 --host-session-id hermes-channel-42 --host-run-id hermes-run-42 --host-task-id hermes-task-42",
            "before_prompt_build": "ccd host-hook --path . --host hermes --hook before-prompt-build",
            "on_compaction_notice": "ccd host-hook --path . --host hermes --hook on-compaction-notice",
            "on_agent_end": "ccd host-hook --path . --host hermes --hook on-agent-end",
            "on_session_end": "ccd host-hook --path . --host hermes --hook on-session-end",
            "supervisor_tick": "ccd host-hook --path . --host hermes --hook supervisor-tick"
        },
        "notes": [
            "Honor the top-level session_boundary before unattended continuation.",
            "Use supervisor_tick when the runtime can refresh lease ownership.",
            "Treat CCD outputs as control-plane truth rather than prompt folklore."
        ]
    }))
    .expect("hermes adapter json")
}

// ============================================================================
// Merge: .claude/settings.json
// ============================================================================

/// Additive merge of CCD-managed lifecycle hooks into a Claude
/// `settings.json` value, using the default [`CCD_COMPAT_PROFILE`].
///
/// See [`merge_claude_settings_with_profile`] for the algorithm. This
/// is the back-compat entry point preserved for callers that pre-date
/// the profile abstraction.
pub fn merge_claude_settings(settings: Value) -> Option<Value> {
    merge_claude_settings_with_profile(settings, &CCD_COMPAT_PROFILE)
}

/// Additive merge of `profile`'s managed lifecycle hooks into a Claude
/// `settings.json` value.
///
/// Algorithm:
/// 1. Ensure a top-level `hooks` object. Preserve every other top-level
///    key.
/// 2. For each managed event in `profile.claude_managed_events`,
///    ensure a matcher entry exists. Within its `hooks` array, drop
///    any entry whose `command` is recognized as a stale managed
///    entry for `profile` (current prefix or any of
///    `profile.claude_legacy_substrings`), then append the current
///    managed entry rendered through `profile.claude_command`.
/// 3. Non-managed entries within the same matcher are preserved in
///    original order.
/// 4. The retired `TaskCompleted` event is removed when its only
///    entries are managed by `profile`; user-owned `TaskCompleted`
///    hooks are preserved.
///
/// Returns `None` when the existing `hooks` shape is incompatible:
/// `hooks` is not an object, or a managed event's value is not an array,
/// or a matcher's inner `hooks` is not an array. Callers treat `None` as
/// malformed input.
pub fn merge_claude_settings_with_profile(
    mut settings: Value,
    profile: &LifecycleProfile,
) -> Option<Value> {
    let root_obj = settings.as_object_mut()?;
    let hooks_entry = root_obj
        .entry("hooks")
        .or_insert_with(|| Value::Object(Default::default()));
    let hooks_obj = hooks_entry.as_object_mut()?;
    scrub_retired_task_completed_event(hooks_obj, profile);

    for (event, hook_arg, matcher) in profile.claude_managed_events {
        let event_entry = hooks_obj
            .entry(*event)
            .or_insert_with(|| Value::Array(Vec::new()));
        let event_array = event_entry.as_array_mut()?;

        let matcher_idx = event_array.iter().position(|entry| {
            entry
                .get("matcher")
                .and_then(Value::as_str)
                .map(|s| s == *matcher)
                .unwrap_or(false)
        });
        let matcher_entry = match matcher_idx {
            Some(idx) => &mut event_array[idx],
            None => {
                event_array.push(json!({ "matcher": matcher, "hooks": [] }));
                event_array.last_mut().unwrap()
            }
        };

        let hooks_inside = matcher_entry
            .get_mut("hooks")
            .and_then(Value::as_array_mut)?;
        hooks_inside.retain(|entry| !profile.claude_entry_is_managed_or_legacy(entry));
        hooks_inside.push(json!({
            "type": "command",
            "command": profile.claude_command(hook_arg),
        }));
    }

    Some(settings)
}

fn scrub_retired_task_completed_event(
    hooks_obj: &mut serde_json::Map<String, Value>,
    profile: &LifecycleProfile,
) {
    let Some(task_completed) = hooks_obj.get_mut("TaskCompleted") else {
        return;
    };
    let Some(event_array) = task_completed.as_array_mut() else {
        return;
    };

    event_array.retain_mut(|entry| {
        let Some(hooks_inside) = entry.get_mut("hooks").and_then(Value::as_array_mut) else {
            return true;
        };
        hooks_inside.retain(|hook| !profile.claude_entry_is_managed_or_legacy(hook));
        !hooks_inside.is_empty()
    });

    if event_array.is_empty() {
        hooks_obj.remove("TaskCompleted");
    }
}

/// Merge an existing serialized `.claude/settings.json` body into the
/// CCD-managed shape (default [`CCD_COMPAT_PROFILE`]). See
/// [`merge_claude_settings_text_with_profile`] for the contract.
pub fn merge_claude_settings_text(
    existing: Option<&str>,
    force: bool,
) -> Result<Option<MergedFile>, HostAssetError> {
    merge_claude_settings_text_with_profile(existing, force, &CCD_COMPAT_PROFILE)
}

/// Merge an existing serialized `.claude/settings.json` body into
/// `profile`'s managed shape. Returns:
/// * `Ok(Some(merged))` on success;
/// * `Ok(None)` when the existing body is malformed and `force` was
///   not requested (caller should warn and skip);
/// * `Err(_)` for parse errors that `force` cannot recover from
///   without reset.
///
/// When `force` is true, parse errors and shape mismatches fall back
/// to a fresh merge against an empty object.
pub fn merge_claude_settings_text_with_profile(
    existing: Option<&str>,
    force: bool,
    profile: &LifecycleProfile,
) -> Result<Option<MergedFile>, HostAssetError> {
    let parsed = match existing {
        None => Value::Object(Default::default()),
        Some(body) => match serde_json::from_str::<Value>(body) {
            Ok(v) => v,
            Err(_) if force => Value::Object(Default::default()),
            Err(_) => return Ok(None),
        },
    };

    let root = if parsed.is_object() {
        parsed
    } else if force {
        Value::Object(Default::default())
    } else {
        return Ok(None);
    };

    let merged = match merge_claude_settings_with_profile(root, profile) {
        Some(v) => v,
        None if force => {
            merge_claude_settings_with_profile(Value::Object(Default::default()), profile)
                .expect("empty object is always a valid base")
        }
        None => return Ok(None),
    };
    let rendered =
        serde_json::to_string_pretty(&merged).map_err(|err| HostAssetError::Serialize {
            reason: err.to_string(),
        })?;
    Ok(Some(MergedFile {
        existing: existing.map(str::to_owned),
        rendered,
    }))
}

// ============================================================================
// Merge: .codex/hooks.json
// ============================================================================

/// Additive merge of CCD-managed lifecycle hooks into a Codex
/// `hooks.json` value (default [`CCD_COMPAT_PROFILE`]). See
/// [`merge_codex_hooks_with_profile`] for the algorithm.
pub fn merge_codex_hooks(hooks_doc: Value) -> Option<Value> {
    merge_codex_hooks_with_profile(hooks_doc, &CCD_COMPAT_PROFILE)
}

/// Additive merge of `profile`'s managed lifecycle hooks into a Codex
/// `hooks.json` value. See [`merge_claude_settings_with_profile`] for
/// the algorithm; the only differences are the managed event table
/// and the per-entry `timeout`/`statusMessage` fields Codex carries.
pub fn merge_codex_hooks_with_profile(
    mut hooks_doc: Value,
    profile: &LifecycleProfile,
) -> Option<Value> {
    let hooks_entry = hooks_doc
        .as_object_mut()?
        .entry("hooks")
        .or_insert_with(|| Value::Object(Default::default()));
    let hooks_obj = hooks_entry.as_object_mut()?;

    for (event, hook_arg, matcher, status_message) in profile.codex_managed_events {
        let event_entry = hooks_obj
            .entry(*event)
            .or_insert_with(|| Value::Array(Vec::new()));
        let event_array = event_entry.as_array_mut()?;

        let matcher_idx = event_array.iter().position(|entry| {
            entry
                .get("matcher")
                .and_then(Value::as_str)
                .map(|value| value == *matcher)
                .unwrap_or(false)
        });
        let matcher_entry = match matcher_idx {
            Some(idx) => &mut event_array[idx],
            None => {
                event_array.push(json!({ "matcher": matcher, "hooks": [] }));
                event_array.last_mut().unwrap()
            }
        };

        let hooks_inside = matcher_entry
            .get_mut("hooks")
            .and_then(Value::as_array_mut)?;
        hooks_inside.retain(|entry| !profile.codex_entry_is_managed(entry));
        hooks_inside.push(json!({
            "type": "command",
            "command": profile.codex_command(hook_arg),
            "timeout": 30,
            "statusMessage": status_message,
        }));
    }

    Some(hooks_doc)
}

/// True when `hooks_doc` already contains the full CCD-managed Codex
/// lifecycle hook set (default [`CCD_COMPAT_PROFILE`]). Used by status
/// reporting to detect "Codex hooks installed externally" vs.
/// "needs apply".
pub fn codex_hooks_contain_managed_lifecycle(hooks_doc: &Value) -> bool {
    codex_hooks_contain_managed_lifecycle_with_profile(hooks_doc, &CCD_COMPAT_PROFILE)
}

/// True when `hooks_doc` already contains the full set of `profile`'s
/// managed Codex lifecycle hooks.
pub fn codex_hooks_contain_managed_lifecycle_with_profile(
    hooks_doc: &Value,
    profile: &LifecycleProfile,
) -> bool {
    profile
        .codex_managed_events
        .iter()
        .all(|(event, hook_arg, _, _)| {
            codex_event_contains_managed_hook(hooks_doc, event, hook_arg, profile)
        })
}

fn codex_event_contains_managed_hook(
    hooks_doc: &Value,
    event: &str,
    hook_arg: &str,
    profile: &LifecycleProfile,
) -> bool {
    let expected = profile.codex_command(hook_arg);
    hooks_doc
        .get("hooks")
        .and_then(|hooks| hooks.get(event))
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|matcher| matcher.get("hooks").and_then(Value::as_array))
        .flatten()
        .any(|hook| {
            hook.get("command")
                .and_then(Value::as_str)
                .map(|command| {
                    command == expected
                        || (command.starts_with(profile.codex_command_prefix)
                            && command.contains(hook_arg))
                })
                .unwrap_or(false)
        })
}

/// Merge an existing serialized `.codex/hooks.json` body using the
/// default [`CCD_COMPAT_PROFILE`]. See
/// [`merge_codex_hooks_text_with_profile`] for the contract.
pub fn merge_codex_hooks_text(
    existing: Option<&str>,
    force: bool,
) -> Result<Option<MergedFile>, HostAssetError> {
    merge_codex_hooks_text_with_profile(existing, force, &CCD_COMPAT_PROFILE)
}

/// Merge an existing serialized `.codex/hooks.json` body using
/// `profile`. Returns `Ok(None)` when the existing body is invalid
/// JSON or has an incompatible top-level shape; `_force` is reserved
/// for symmetry with [`merge_claude_settings_text_with_profile`] and
/// currently behaves the same regardless of value (the previous CCD
/// implementation never branched on it).
pub fn merge_codex_hooks_text_with_profile(
    existing: Option<&str>,
    _force: bool,
    profile: &LifecycleProfile,
) -> Result<Option<MergedFile>, HostAssetError> {
    let parsed = match existing {
        None => Value::Object(Default::default()),
        Some(body) => match serde_json::from_str::<Value>(body) {
            Ok(value) => value,
            Err(_) => return Ok(None),
        },
    };

    let root = if parsed.is_object() {
        parsed
    } else {
        return Ok(None);
    };

    let merged = match merge_codex_hooks_with_profile(root, profile) {
        Some(value) => value,
        None => return Ok(None),
    };
    let rendered =
        serde_json::to_string_pretty(&merged).map_err(|err| HostAssetError::Serialize {
            reason: err.to_string(),
        })?;
    Ok(Some(MergedFile {
        existing: existing.map(str::to_owned),
        rendered,
    }))
}

// ============================================================================
// Merge: .codex/config.toml
// ============================================================================

/// Merge `[features].hooks = true` into an existing Codex
/// `config.toml`, preserving every other key.
pub fn merge_codex_config_text(existing: Option<&str>) -> Result<MergedFile, HostAssetError> {
    let mut root = match existing {
        None => toml::Table::new(),
        Some(raw) if raw.trim().is_empty() => toml::Table::new(),
        Some(raw) => match raw.parse::<toml::Value>() {
            Ok(value) => value
                .as_table()
                .cloned()
                .ok_or_else(|| HostAssetError::Malformed {
                    reason: "codex config.toml must be a TOML table".into(),
                })?,
            Err(err) => {
                return Err(HostAssetError::Parse {
                    reason: err.to_string(),
                });
            }
        },
    };

    let features_entry = root
        .entry("features".to_owned())
        .or_insert_with(|| toml::Value::Table(toml::Table::new()));
    let features = features_entry
        .as_table_mut()
        .ok_or_else(|| HostAssetError::Malformed {
            reason: "[features] must be a TOML table".into(),
        })?;
    features.insert("hooks".to_owned(), toml::Value::Boolean(true));

    let rendered = toml::to_string_pretty(&root).map_err(|err| HostAssetError::Serialize {
        reason: err.to_string(),
    })?;
    Ok(MergedFile {
        existing: existing.map(str::to_owned),
        rendered,
    })
}

/// True when the parsed TOML enables `[features].hooks`.
pub fn codex_hooks_feature_is_enabled(config: &toml::Value) -> bool {
    config
        .get("features")
        .and_then(|features| features.get("hooks"))
        .and_then(toml::Value::as_bool)
        == Some(true)
}

// ============================================================================
// Asset status
// ============================================================================

/// Status of an installed asset that uses byte-equal comparison (every
/// asset *except* the merge-aware Claude settings, Codex hooks, and
/// Codex config files).
///
/// `existing_content` and `existing_mode` describe the on-disk state:
/// `None` means the file does not exist. The caller is responsible for
/// reading them.
pub fn byte_equal_asset_status(
    asset: &RenderedAsset,
    existing_content: Option<&str>,
    existing_mode: Option<u32>,
) -> AssetStatus {
    let Some(content) = existing_content else {
        return AssetStatus::Missing;
    };
    if content != asset.contents {
        return AssetStatus::Drifted;
    }
    if let Some(expected) = asset.mode {
        match existing_mode {
            Some(actual) if actual == expected => {}
            _ => return AssetStatus::Drifted,
        }
    }
    AssetStatus::Present
}

/// Status of `.claude/settings.json` against the rendered template
/// for the default [`CCD_COMPAT_PROFILE`]. `existing` is the file
/// body (`None` means missing). The merge is re-run and compared
/// byte-for-byte to detect drift.
pub fn claude_settings_status(existing: Option<&str>) -> AssetStatus {
    claude_settings_status_with_profile(existing, &CCD_COMPAT_PROFILE)
}

/// Status of `.claude/settings.json` against the rendered template
/// for `profile`.
pub fn claude_settings_status_with_profile(
    existing: Option<&str>,
    profile: &LifecycleProfile,
) -> AssetStatus {
    let Some(content) = existing else {
        return AssetStatus::Missing;
    };
    match merge_claude_settings_text_with_profile(Some(content), false, profile) {
        Ok(Some(merged)) if merged.rendered == content => AssetStatus::Present,
        Ok(_) | Err(_) => AssetStatus::Drifted,
    }
}

/// Status of `.codex/hooks.json` against the rendered template for
/// the default [`CCD_COMPAT_PROFILE`].
pub fn codex_hooks_status(existing: Option<&str>) -> AssetStatus {
    codex_hooks_status_with_profile(existing, &CCD_COMPAT_PROFILE)
}

/// Status of `.codex/hooks.json` against the rendered template for
/// `profile`.
pub fn codex_hooks_status_with_profile(
    existing: Option<&str>,
    profile: &LifecycleProfile,
) -> AssetStatus {
    let Some(content) = existing else {
        return AssetStatus::Missing;
    };
    match merge_codex_hooks_text_with_profile(Some(content), false, profile) {
        Ok(Some(merged)) if merged.rendered == content => AssetStatus::Present,
        Ok(_) | Err(_) => AssetStatus::Drifted,
    }
}

/// Status of `.codex/config.toml`. Returns `Present` only when the
/// `[features].hooks = true` flag is set; the rest of the file
/// is ignored because users are free to add their own config.
pub fn codex_config_status(existing: Option<&str>) -> AssetStatus {
    let Some(content) = existing else {
        return AssetStatus::Missing;
    };
    match content.parse::<toml::Value>() {
        Ok(parsed) if codex_hooks_feature_is_enabled(&parsed) => AssetStatus::Present,
        Ok(_) | Err(_) => AssetStatus::Drifted,
    }
}

/// Compute status for one rendered asset by dispatching to the
/// appropriate per-path comparison. Falls back to byte-equal
/// comparison for any path that doesn't match a merge-aware target.
pub fn asset_status(
    asset: &RenderedAsset,
    existing_content: Option<&str>,
    existing_mode: Option<u32>,
) -> AssetStatus {
    match asset.relative_path {
        CLAUDE_TARGET_SETTINGS => claude_settings_status(existing_content),
        CODEX_TARGET_CONFIG => codex_config_status(existing_content),
        CODEX_TARGET_HOOKS => codex_hooks_status(existing_content),
        _ => byte_equal_asset_status(asset, existing_content, existing_mode),
    }
}

/// Combine per-asset statuses into a single bundle status. `Drifted`
/// dominates `Missing` dominates `Present`; an empty input is
/// `NotApplicable`.
pub fn aggregate_status<I: IntoIterator<Item = AssetStatus>>(statuses: I) -> AssetStatus {
    let mut saw_missing = false;
    let mut saw_drift = false;
    let mut saw_any = false;
    for s in statuses {
        saw_any = true;
        match s {
            AssetStatus::Drifted => saw_drift = true,
            AssetStatus::Missing => saw_missing = true,
            AssetStatus::InvalidMode => return AssetStatus::InvalidMode,
            AssetStatus::Present | AssetStatus::NotApplicable => {}
        }
    }
    if !saw_any {
        return AssetStatus::NotApplicable;
    }
    if saw_drift {
        AssetStatus::Drifted
    } else if saw_missing {
        AssetStatus::Missing
    } else {
        AssetStatus::Present
    }
}