agent-chorus 0.14.1

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


use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use serde_json::json;

#[derive(Parser)]
#[command(name = "chorus")]
#[command(about = "Agent Chorus CLI", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Read a session from an agent
    Read {
        /// Agent to read from
        #[arg(long, value_enum)]
        agent: AgentType,

        /// Session ID or UUID (substring match supported)
        #[arg(long)]
        id: Option<String>,

        /// Working directory to scope search (defaults to current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Explicit path to chats directory (Gemini only)
        #[arg(long)]
        chats_dir: Option<String>,

        /// Number of last assistant messages to return
        #[arg(long, default_value = "1")]
        last: usize,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,

        /// Return session metadata only (no content)
        #[arg(long)]
        metadata_only: bool,

        /// Include redaction audit trail in output
        #[arg(long)]
        audit_redactions: bool,

        /// Interleave each user prompt with the assistant turn that followed it
        #[arg(long)]
        include_user: bool,

        /// Render tool-call blocks with their input arguments
        #[arg(long = "tool-calls")]
        tool_calls: bool,

        /// Output format: json | md | markdown (default: text)
        #[arg(long)]
        format: Option<String>,
    },

    /// Compare sources and return an analyze-mode report
    Compare {
        /// Source spec: <agent> or <agent>:<session-substring>
        #[arg(long = "source", required = true)]
        sources: Vec<String>,

        /// Working directory to scope current-session lookups
        #[arg(long)]
        cwd: Option<String>,

        /// Emit structured JSON instead of markdown
        #[arg(long)]
        json: bool,

        /// Number of last messages to read from each source
        #[arg(long, default_value = "10")]
        last: usize,
    },

    /// Build a report from a handoff packet JSON file
    Report {
        /// Path to handoff JSON file
        #[arg(long)]
        handoff: String,

        /// Working directory fallback for source lookups
        #[arg(long)]
        cwd: Option<String>,

        /// Emit structured JSON instead of markdown
        #[arg(long)]
        json: bool,
    },

    /// List sessions for an agent
    List {
        /// Agent to list sessions for
        #[arg(long, value_enum)]
        agent: AgentType,

        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,

        /// Maximum number of sessions to return
        #[arg(long, default_value = "10")]
        limit: usize,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Search sessions for a keyword
    Search {
        /// Keyword to search for
        #[arg(index = 1)]
        query: String,

        /// Agent to search
        #[arg(long, value_enum)]
        agent: AgentType,

        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,

        /// Maximum number of sessions to return
        #[arg(long, default_value = "10")]
        limit: usize,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Roast agents based on their session content (easter egg)
    #[command(name = "trash-talk")]
    TrashTalk {
        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,
    },

    /// Initialize agent-chorus in the current directory (provider blocks, scaffolding, optional context-pack)
    Setup {
        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Preview changes without executing
        #[arg(long)]
        dry_run: bool,

        /// Overwrite existing scaffolding files
        #[arg(long)]
        force: bool,

        /// Also initialize and seal an agent-context pack
        #[arg(long)]
        context_pack: bool,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Reverse setup: remove managed blocks, scaffolding, and hooks
    Teardown {
        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Preview changes without executing
        #[arg(long)]
        dry_run: bool,

        /// Also remove global cache (~/.cache/agent-chorus/)
        #[arg(long)]
        global: bool,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Build/sync/install agent-context automation
    #[command(name = "agent-context")]
    AgentContext {
        #[command(subcommand)]
        command: ContextPackCommand,
    },

    /// Deprecated alias for agent-context
    #[command(name = "context-pack", hide = true)]
    ContextPack {
        #[command(subcommand)]
        command: ContextPackCommand,
    },

    /// Compare two sessions from the same agent
    Diff {
        /// Agent to diff sessions for
        #[arg(long, value_enum)]
        agent: AgentType,

        /// First session ID (substring match)
        #[arg(long)]
        from: String,

        /// Second session ID (substring match)
        #[arg(long)]
        to: String,

        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,

        /// Number of last assistant messages per session
        #[arg(long, default_value = "1")]
        last: usize,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Inspect relevance patterns for context-pack filtering
    Relevance {
        /// List current include/exclude patterns
        #[arg(long)]
        list: bool,

        /// Test whether a specific file path is relevant
        #[arg(long)]
        test: Option<String>,

        /// Suggest patterns based on detected project conventions
        #[arg(long)]
        suggest: bool,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Send a message from one agent to another
    Send {
        /// Sending agent
        #[arg(long)]
        from: String,

        /// Target agent
        #[arg(long)]
        to: String,

        /// Message content
        #[arg(long)]
        message: String,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Read messages for an agent
    Messages {
        /// Agent whose messages to read
        #[arg(long)]
        agent: String,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Clear messages after reading
        #[arg(long)]
        clear: bool,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Broadcast current git state to every other agent's inbox
    Checkpoint {
        /// Sending agent (one of: codex, gemini, claude, cursor)
        #[arg(long)]
        from: String,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Override the auto-composed state message
        #[arg(long)]
        message: Option<String>,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Session digest: files, tools, duration, user requests
    Summary {
        /// Agent to summarize
        #[arg(long, value_enum)]
        agent: AgentType,

        /// Session ID or UUID (substring match)
        #[arg(long)]
        id: Option<String>,

        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,

        /// Explicit path to chats directory (Gemini only)
        #[arg(long)]
        chats_dir: Option<String>,

        /// Output format: json | md | markdown (default: text)
        #[arg(long)]
        format: Option<String>,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Diagnostic checks across the agent-chorus install
    Doctor {
        /// Working directory to scope checks
        #[arg(long)]
        cwd: Option<String>,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    /// Cross-agent chronological view of recent sessions
    Timeline {
        /// Agent to include (repeatable; default: all)
        #[arg(long)]
        agent: Vec<String>,

        /// Working directory to scope search
        #[arg(long)]
        cwd: Option<String>,

        /// Maximum sessions per agent
        #[arg(long, default_value = "5")]
        limit: usize,

        /// Output format: json | md | markdown (default: text)
        #[arg(long)]
        format: Option<String>,

        /// Emit structured JSON instead of text
        #[arg(long)]
        json: bool,
    },

    #[cfg(feature = "update-check")]
    #[command(hide = true)]
    UpdateWorker,
}

#[derive(Subcommand)]
enum ContextPackCommand {
    /// Build or refresh context pack files
    Build {
        /// Build reason (metadata only)
        #[arg(long)]
        reason: Option<String>,

        /// Base SHA for changed-file computation
        #[arg(long)]
        base: Option<String>,

        /// Head SHA for changed-file computation
        #[arg(long)]
        head: Option<String>,

        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// Explicit changed file (repeatable)
        #[arg(long = "changed-file")]
        changed_files: Vec<String>,

        /// Force creating a new snapshot even when unchanged
        #[arg(long)]
        force_snapshot: bool,
    },

    /// Sync context pack during a main-branch push event
    #[command(name = "sync-main")]
    SyncMain {
        #[arg(long)]
        local_ref: String,

        #[arg(long)]
        local_sha: String,

        #[arg(long)]
        remote_ref: String,

        #[arg(long)]
        remote_sha: String,
    },

    /// Install/refresh pre-push hook wiring
    #[command(name = "install-hooks")]
    InstallHooks {
        /// Target directory inside repo (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Preview changes without writing
        #[arg(long)]
        dry_run: bool,

        /// P1 — also install a post-commit hook that runs
        /// `chorus agent-context post-commit-reconcile` when the commit
        /// touched `.agent-context/**`. Opt-in — off by default so existing
        /// installs are not disturbed.
        #[arg(long = "enable-post-commit-reconcile")]
        enable_post_commit_reconcile: bool,

        /// P4 — also merge the shipped `cli/templates/settings.agent-context.json`
        /// PreToolUse hook entries into `.claude/settings.json`. Existing keys
        /// are preserved; idempotent when run twice.
        #[arg(long = "install-settings-template")]
        install_settings_template: bool,
    },

    /// P1 — reconcile the manifest's `post_commit_sha` with the current
    /// git HEAD. Intended to be invoked from a post-commit hook after a
    /// commit that touched `.agent-context/**`.
    #[command(name = "post-commit-reconcile")]
    PostCommitReconcile {
        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,
    },

    /// Restore context pack from snapshot
    Rollback {
        /// Snapshot ID (default: latest)
        #[arg(long)]
        snapshot: Option<String>,

        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// P13/F58: roll back to the snapshot matching the manifest's
        /// `last_known_good_sha` field. The pointer is promoted on
        /// `verify --ci` success, so this gives teams a simple "undo to last
        /// green" without knowing the snapshot ID. Conflicts with `--snapshot`.
        #[arg(long = "latest-good")]
        latest_good: bool,
    },

    /// Verify context pack integrity (checksums)
    Verify {
        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// CI mode: output JSON with integrity + freshness results, exit 1 on failure
        #[arg(long)]
        ci: bool,

        /// Base ref for freshness check (default: origin/main)
        #[arg(long)]
        base: Option<String>,

        /// Recover from a corrupt manifest by restoring the most recent intact
        /// snapshot. Prompts for confirmation unless --yes is given.
        #[arg(long)]
        repair: bool,

        /// Skip the interactive confirmation prompt when running --repair.
        #[arg(long = "yes")]
        repair_yes: bool,

        /// P3: emit a JSON payload with changed_files, pack_sections_to_update,
        /// a capped diff excerpt, and a reserved baseline_drift array. Used by
        /// agents to target which pack sections to patch.
        #[arg(long = "suggest-patches")]
        suggest_patches: bool,

        /// P6: opt-in CI gate that fails when any commit in the PR range
        /// mixes `.agent-context/**` with non-pack paths. Off by default; only
        /// active under `--ci`.
        #[arg(long = "enforce-separate-commits")]
        enforce_separate_commits: bool,
    },

    /// Warn when context-relevant files changed without pack update
    #[command(name = "check-freshness")]
    CheckFreshness {
        /// Base ref for diff (default: origin/main)
        #[arg(long)]
        base: Option<String>,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,
    },

    /// Initialize context pack templates
    Init {
        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Overwrite existing template files
        #[arg(long)]
        force: bool,

        /// Dereference symlinks whose targets resolve outside the repo root.
        /// Off by default so a rogue symlink cannot exfiltrate content into
        /// the pack. Opt in only for repos that rely on out-of-tree sources.
        #[arg(long)]
        follow_symlinks: bool,

        /// P13/F46: adoption tier for the scaffolded pack. Tier 1 ships just
        /// `20_CODE_MAP.md` + `routes.json`. Tier 2 adds
        /// `30_BEHAVIORAL_INVARIANTS.md` + `completeness_contract.json`. Tier
        /// 3 (the default) scaffolds the full pack — existing behavior.
        #[arg(long, value_parser = clap::value_parser!(u8).range(1..=3), default_value_t = 3)]
        tier: u8,
    },

    /// P7 — zone-grouped diff from the seal-time baseline to current HEAD.
    ///
    /// Intended for the orchestrator of a parallel-subagent session: after
    /// subagents modify code, run this to learn which pack sections are
    /// impacted, then dispatch a single reconciler subagent to patch and
    /// re-seal. Requires a sealed pack (`manifest.json` with
    /// `head_sha_at_seal` or `post_commit_sha`).
    Diff {
        /// Emit diff since the seal-time baseline recorded in
        /// `manifest.json`. This flag is the only mode currently supported;
        /// reserved in the spec so future diff modes can slot in cleanly.
        #[arg(long = "since-seal")]
        since_seal: bool,

        /// Output format: `json` (default, machine-readable) or `text`
        /// (human-readable summary of zones + actions).
        #[arg(long, default_value = "json")]
        format: DiffFormat,

        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,
    },

    /// Validate and seal an agent-authored context pack
    Seal {
        /// Seal reason (metadata only)
        #[arg(long)]
        reason: Option<String>,

        /// Base SHA for changed-file computation
        #[arg(long)]
        base: Option<String>,

        /// Head SHA for changed-file computation
        #[arg(long)]
        head: Option<String>,

        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,

        /// Seal even if template markers remain
        #[arg(long)]
        force: bool,

        /// Force creating a new snapshot even when unchanged
        #[arg(long)]
        force_snapshot: bool,

        /// Dereference symlinks whose targets resolve outside the repo root.
        /// Off by default; turn on only when an out-of-tree source must be
        /// read into the pack. Seal will still warn on skipped files.
        #[arg(long)]
        follow_symlinks: bool,
    },

    /// P11-drift / F38 — verify that shipped helper scripts under
    /// `.agent-context/current/tools/` still match the SHA256 values recorded
    /// on `manifest.json` at seal time. Exits non-zero on any mismatch so CI
    /// can use it as a standalone tampering gate alongside `verify --ci`.
    #[command(name = "check-tool-integrity")]
    CheckToolIntegrity {
        /// Override pack directory (default: .agent-context or CHORUS_CONTEXT_PACK_DIR)
        #[arg(long)]
        pack_dir: Option<String>,

        /// Working directory (default: current directory)
        #[arg(long)]
        cwd: Option<String>,
    },
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
enum AgentType {
    Codex,
    Gemini,
    Claude,
    Cursor,
}

impl AgentType {
    fn as_str(&self) -> &'static str {
        match self {
            AgentType::Codex => "codex",
            AgentType::Gemini => "gemini",
            AgentType::Claude => "claude",
            AgentType::Cursor => "cursor",
        }
    }
}

/// P7 — output format for `agent-context diff --since-seal`. JSON is the
/// machine-readable contract; text is a compact human-facing summary so an
/// operator can eyeball the zones without piping through `jq`.
#[derive(Copy, Clone, PartialEq, Eq, ValueEnum, Debug)]
enum DiffFormat {
    Json,
    Text,
}

fn main() {
    let cli = match Cli::try_parse() {
        Ok(c) => c,
        Err(e) => {
            // If --json was passed on the command line, emit structured error
            let raw_args: Vec<String> = std::env::args().collect();
            let has_json = raw_args.iter().any(|a| a == "--json");
            if has_json {
                let msg = e.to_string();
                // Detect unsupported agent from clap's error message
                let code = if msg.contains("invalid value") && msg.contains("--agent") {
                    agents::ChorusErrorCode::UnsupportedAgent
                } else {
                    agents::classify_error(&msg)
                };
                let error_json = serde_json::json!({
                    "error_code": code.as_str(),
                    "message": msg.to_string().lines().next().unwrap_or(""),
                });
                println!("{}", serde_json::to_string_pretty(&error_json).unwrap_or_default());
                std::process::exit(1);
            } else {
                e.exit();
            }
        }
    };
    let json_mode = is_json_mode(&cli.command);

    if let Err(err) = run(cli) {
        if json_mode {
            let msg = format!("{:#}", err);
            let code = agents::classify_error(&msg);
            let error_json = serde_json::json!({
                "error_code": code.as_str(),
                "message": msg,
            });
            println!("{}", serde_json::to_string_pretty(&error_json).unwrap_or_default());
        } else {
            eprintln!("{:#}", err);
        }
        std::process::exit(1);
    }
}

fn is_json_mode(command: &Commands) -> bool {
    match command {
        Commands::Read { json, format, .. } => *json || is_json_format(format.as_deref()),
        Commands::Compare { json, .. } => *json,
        Commands::Report { json, .. } => *json,
        Commands::List { json, .. } => *json,
        Commands::Search { json, .. } => *json,
        Commands::TrashTalk { .. } => false,
        Commands::Diff { json, .. } => *json,
        Commands::Relevance { json, .. } => *json,
        Commands::Send { json, .. } => *json,
        Commands::Messages { json, .. } => *json,
        Commands::Checkpoint { json, .. } => *json,
        Commands::Setup { json, .. } => *json,
        Commands::Teardown { json, .. } => *json,
        Commands::Summary { json, .. } => *json,
        Commands::Timeline { json, .. } => *json,
        Commands::Doctor { json, .. } => *json,
        Commands::AgentContext { .. } | Commands::ContextPack { .. } => false,
        #[cfg(feature = "update-check")]
        Commands::UpdateWorker => false,
    }
}

fn run(cli: Cli) -> Result<()> {
    match cli.command {
        Commands::Read {
            agent,
            id,
            cwd,
            chats_dir,
            last,
            json,
            metadata_only,
            audit_redactions,
            include_user,
            tool_calls,
            format,
        } => {
            let effective_cwd = effective_cwd(cwd);
            let last_n = last.max(1);
            let adapter = adapters::get_adapter(agent.as_str())
                .with_context(|| format!("Unsupported agent: {}", agent.as_str()))?;
            let opts = adapters::ReadOptions {
                include_user,
                include_tool_calls: tool_calls,
            };
            let session = adapter.read_session_with_options(
                id.as_deref(),
                &effective_cwd,
                chats_dir.as_deref(),
                last_n,
                opts,
            )?;

            // If audit mode requested, re-run redaction with audit on the raw content
            let redaction_audit = if audit_redactions {
                let (_, audit) = agents::redact_sensitive_text_with_audit(&session.content);
                Some(audit)
            } else {
                None
            };

            let included_roles: Vec<&'static str> = if include_user {
                vec!["user", "assistant"]
            } else {
                vec!["assistant"]
            };

            // Format resolution: --json wins when set. Otherwise --format md/markdown → markdown.
            // --format json is also honored as an explicit alias for --json (Node's CLI
            // ignores format=json and falls through to text; we match the documented
            // semantics instead — see report).
            let format_str = format.as_deref();
            let want_json = json || is_json_format(format_str);
            let want_markdown = !want_json && is_markdown_format(format_str);

            if want_json {
                let content_value = if metadata_only {
                    serde_json::Value::Null
                } else {
                    serde_json::Value::String(session.content.clone())
                };
                let mut report = json!({
                    "chorus_output_version": 1,
                    "agent": session.agent,
                    "source": session.source,
                    "content": content_value,
                    "warnings": session.warnings,
                    "session_id": session.session_id,
                    "cwd": session.cwd,
                    "timestamp": session.timestamp,
                    "message_count": session.message_count,
                    "messages_returned": session.messages_returned,
                    "included_roles": included_roles,
                });
                if tool_calls {
                    report.as_object_mut().unwrap().insert(
                        "included_tool_calls".to_string(),
                        serde_json::Value::Bool(true),
                    );
                }
                if let Some(ref audit) = redaction_audit {
                    report.as_object_mut().unwrap().insert(
                        "redactions".to_string(),
                        serde_json::to_value(audit)?,
                    );
                }
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else if want_markdown {
                println!("{}", utils::sanitize_for_terminal(&render_read_as_markdown(&session)));
            } else {
                for warning in &session.warnings {
                    eprintln!("{}", utils::sanitize_for_terminal(warning));
                }
                println!("--- BEGIN CHORUS OUTPUT ---");
                println!("SOURCE: {} Session ({})", format_agent_name(session.agent), utils::sanitize_for_terminal(&session.source));
                if !metadata_only {
                    println!("---");
                    println!("{}", utils::sanitize_for_terminal(&session.content));
                }
                if let Some(ref audit) = redaction_audit {
                    if !audit.is_empty() {
                        println!("---");
                        println!("Redaction audit:");
                        for entry in audit {
                            println!("  {}{} occurrence(s)", entry.pattern, entry.count);
                        }
                    }
                }
                println!("--- END CHORUS OUTPUT ---");
            }
        }
        Commands::Compare { sources, cwd, json, last } => {
            let effective_cwd = effective_cwd(cwd);
            let mut source_specs = sources
                .iter()
                .map(|raw| report::parse_source_arg(raw))
                .collect::<Result<Vec<report::SourceSpec>>>()?;

            for spec in &mut source_specs {
                spec.last_n = Some(last.max(1));
            }

            let request = report::ReportRequest {
                mode: "analyze".to_string(),
                task: "Compare agent outputs".to_string(),
                success_criteria: vec![
                    "Identify agreements and contradictions".to_string(),
                    "Highlight unavailable sources".to_string(),
                ],
                sources: source_specs,
                constraints: Vec::new(),
            };

            let result = report::build_report(&request, &effective_cwd);
            emit_report_output(&result, json)?;
        }
        Commands::Report { handoff, cwd, json } => {
            let effective_cwd = effective_cwd(cwd);
            let request = report::load_handoff(&handoff)
                .with_context(|| format!("Failed to load handoff packet from {}", handoff))?;
            let result = report::build_report(&request, &effective_cwd);
            emit_report_output(&result, json)?;
        }
        Commands::List { agent, cwd, limit, json } => {
            let normalized_cwd = cwd.map(|value| {
                utils::normalize_path(&value)
                    .map(|path| path.to_string_lossy().to_string())
                    .unwrap_or(value)
            });
            let adapter = adapters::get_adapter(agent.as_str())
                .with_context(|| format!("Unsupported agent: {}", agent.as_str()))?;
            let entries = adapter.list_sessions(normalized_cwd.as_deref(), limit)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&entries)?);
            } else if entries.is_empty() {
                println!("No sessions found.");
            } else {
                println!("  {:<8} {:<12}  {:<24} CWD", "AGENT", "SESSION", "TIMESTAMP");
                println!("  {:<8} {:<12}  {:<24} {}", "".repeat(8), "".repeat(12), "".repeat(24), "".repeat(20));
                for entry in &entries {
                    let agent_name = entry.get("agent").and_then(|v| v.as_str()).unwrap_or("");
                    let sid = entry.get("session_id").and_then(|v| v.as_str()).unwrap_or("");
                    let sid_short = if sid.len() > 12 { &sid[..12] } else { sid };
                    let ts_raw = entry.get("modified_at").and_then(|v| v.as_str()).unwrap_or("unknown");
                    let ts = format_timestamp(ts_raw);
                    let cwd_val = entry.get("cwd").and_then(|v| v.as_str()).unwrap_or("");
                    let cwd_display = if cwd_val.is_empty() { String::new() } else { truncate_cwd(cwd_val) };
                    println!("  {:<8} {:<12}  {:<24} {}", agent_name, sid_short, ts, cwd_display);
                }
                println!("\n  {} session{} found.", entries.len(), if entries.len() == 1 { "" } else { "s" });
            }
        }
        Commands::Search { query, agent, cwd, limit, json } => {
            let normalized_cwd = cwd.map(|value| {
                utils::normalize_path(&value)
                    .map(|path| path.to_string_lossy().to_string())
                    .unwrap_or(value)
            });
            let adapter = adapters::get_adapter(agent.as_str())
                .with_context(|| format!("Unsupported agent: {}", agent.as_str()))?;
            let entries = adapter.search_sessions(&query, normalized_cwd.as_deref(), limit)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&entries)?);
            } else if entries.is_empty() {
                println!("Search for \"{}\": no matching sessions found.", query);
            } else {
                println!("Search for \"{}\": {} result{}\n",
                    query, entries.len(), if entries.len() == 1 { "" } else { "s" });
                for entry in &entries {
                    let agent_name = entry.get("agent").and_then(|v| v.as_str()).unwrap_or("");
                    let sid = entry.get("session_id").and_then(|v| v.as_str()).unwrap_or("");
                    let sid_short = if sid.len() > 12 { &sid[..12] } else { sid };
                    let ts_raw = entry.get("modified_at").and_then(|v| v.as_str()).unwrap_or("unknown");
                    let ts = format_timestamp(ts_raw);
                    let snippet = entry.get("match_snippet")
                        .and_then(|v| v.as_str())
                        .filter(|s| !s.is_empty())
                        .map(|s| format!("\n    \"{}\"", s.trim()))
                        .unwrap_or_default();
                    println!("  {:<8} {:<12}  {}{}", agent_name, sid_short, ts, snippet);
                }
            }
        }
        Commands::TrashTalk { cwd } => {
            let effective = effective_cwd(cwd);
            agents::trash_talk(&effective);
        }
        Commands::Diff { agent, from, to, cwd, last, json } => {
            let effective_cwd = effective_cwd(cwd);
            let last_n = last.max(1);
            let result = diff::diff_sessions(agent.as_str(), &from, &to, &effective_cwd, last_n)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&result)?);
            } else {
                println!("Diff: {} session {} vs {}", result.agent, result.session_a, result.session_b);
                println!("  +{} added, -{} removed, {} unchanged\n", result.added_lines, result.removed_lines, result.equal_lines);

                // Collapse consecutive equal runs > 5 lines
                const CONTEXT_LINES: usize = 2;
                let mut equal_run: Vec<&str> = Vec::new();

                let flush_equal_run = |run: &[&str]| {
                    if run.len() <= 5 {
                        for line in run {
                            println!("  {}", line);
                        }
                    } else {
                        for line in &run[..CONTEXT_LINES] {
                            println!("  {}", line);
                        }
                        println!("  ... ({} unchanged lines)", run.len() - 2 * CONTEXT_LINES);
                        for line in &run[run.len() - CONTEXT_LINES..] {
                            println!("  {}", line);
                        }
                    }
                };

                for hunk in &result.hunks {
                    match hunk.tag.as_str() {
                        "equal" => {
                            equal_run.push(&hunk.content);
                        }
                        _ => {
                            if !equal_run.is_empty() {
                                flush_equal_run(&equal_run);
                                equal_run.clear();
                            }
                            match hunk.tag.as_str() {
                                "add" => println!("+ {}", hunk.content),
                                "remove" => println!("- {}", hunk.content),
                                _ => println!("  {}", hunk.content),
                            }
                        }
                    }
                }
                // Flush remaining equal lines
                if !equal_run.is_empty() {
                    flush_equal_run(&equal_run);
                }
            }
        }
        Commands::Relevance { list, test, suggest, cwd, json } => {
            let effective = std::path::PathBuf::from(effective_cwd(cwd));

            if let Some(file_path) = test {
                let result = relevance::test_file(&effective, &file_path);
                if json {
                    println!("{}", serde_json::to_string_pretty(&result)?);
                } else {
                    let status = if result.relevant { "RELEVANT" } else { "NOT RELEVANT" };
                    println!("{}: {}", result.path, status);
                    if let Some(ref matched) = result.matched_by {
                        println!("  matched by: {}", matched);
                    }
                }
            } else if suggest {
                let suggestions = relevance::suggest_patterns(&effective);
                if json {
                    println!("{}", serde_json::to_string_pretty(&suggestions)?);
                } else if suggestions.is_empty() {
                    println!("No additional pattern suggestions for this project.");
                } else {
                    for s in &suggestions {
                        println!("[{}] {}{}", s.suggestion_type, s.pattern, s.reason);
                    }
                }
            } else if list {
                let info = relevance::list_patterns(&effective);
                if json {
                    println!("{}", serde_json::to_string_pretty(&info)?);
                } else {
                    println!("Source: {}", info.source);
                    println!("\nInclude:");
                    for p in &info.include {
                        println!("  {}", p);
                    }
                    println!("\nExclude:");
                    for p in &info.exclude {
                        println!("  {}", p);
                    }
                }
            } else {
                println!("Usage: chorus relevance --list | --test <path> | --suggest");
                println!("  Add --json for structured output");
                println!("  Add --cwd <dir> to specify working directory");
            }
        }
        Commands::Send { from, to, message, cwd, json } => {
            let effective = effective_cwd(cwd);
            let msg = messaging::send_message(&from, &to, &message, &effective)?;
            if json {
                println!("{}", serde_json::to_string_pretty(&msg)?);
            } else {
                println!("Message sent from {} to {} at {}", msg.from, msg.to, msg.timestamp);
            }
        }
        Commands::Messages { agent, cwd, clear, json } => {
            let effective = effective_cwd(cwd);
            let messages = messaging::read_messages(&agent, &effective)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&messages)?);
            } else if messages.is_empty() {
                println!("No messages for {}.", agent);
            } else {
                for msg in &messages {
                    println!("[{}] from={} → to={}: {}", msg.timestamp, msg.from, msg.to, msg.content);
                }
            }

            if clear {
                let count = messaging::clear_messages(&agent, &effective)?;
                if !json {
                    println!("Cleared {} message(s).", count);
                }
            }
        }
        Commands::Checkpoint { from, cwd, message, json } => {
            let effective = effective_cwd(cwd);
            let outcome = checkpoint::run(&from, &effective, message.as_deref())?;
            match outcome {
                None => {
                    if json {
                        println!("{}", serde_json::to_string_pretty(&json!({
                            "ok": true,
                            "from": from,
                            "recipients": Vec::<String>::new(),
                            "message": null,
                            "note": "No .agent-chorus/ present — checkpoint was a no-op.",
                        }))?);
                    } else {
                        println!(
                            "No .agent-chorus/ directory in {} — checkpoint skipped.",
                            effective
                        );
                    }
                }
                Some(result) => {
                    if json {
                        println!("{}", serde_json::to_string_pretty(&result)?);
                    } else {
                        println!(
                            "Checkpoint from {} to {} recipient(s): {}",
                            result.from,
                            result.recipients.len(),
                            result.recipients.join(", ")
                        );
                        println!("  {}", result.message);
                    }
                }
            }
        }
        Commands::Setup { cwd, dry_run, force, context_pack, json } => {
            let effective_cwd = effective_cwd(cwd);
            let result = setup::run_setup(&effective_cwd, dry_run, force, context_pack)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&result.to_json())?);
            } else {
                setup::print_text(&result);
            }
        }
        Commands::Teardown { cwd, dry_run, json, global } => {
            let effective_cwd = effective_cwd(cwd);
            let result = teardown::run_teardown(&effective_cwd, dry_run, global)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&json!({
                    "cwd": result.cwd,
                    "dry_run": result.dry_run,
                    "global": result.global,
                    "operations": result.operations,
                    "warnings": result.warnings,
                    "changed": result.changed,
                }))?);
            } else {
                let mode = if result.dry_run { "(dry run) " } else { "" };
                println!("Agent Chorus teardown {}complete for {}", mode, result.cwd);
                for warning in &result.warnings {
                    println!("- [warn] {}", warning);
                }
                for op in &result.operations {
                    let status = op.get("status").and_then(|s| s.as_str()).unwrap_or("unknown");
                    let path = op.get("path").and_then(|s| s.as_str()).unwrap_or("");
                    let note = op.get("note").and_then(|s| s.as_str()).unwrap_or("");
                    println!("- [{}] {} ({})", status, path, note);
                }
            }
        }
        Commands::ContextPack { command } => {
            eprintln!("Warning: 'context-pack' is deprecated, use 'agent-context' instead.");
            handle_context_pack(command)?;
        }
        Commands::AgentContext { command } => {
            handle_context_pack(command)?;
        }
        Commands::Summary { agent, id, cwd, chats_dir, format, json } => {
            let effective_cwd = effective_cwd(cwd);
            let result = summary::build_summary(
                agent.as_str(),
                id.as_deref(),
                &effective_cwd,
                chats_dir.as_deref(),
            )?;

            if json {
                println!("{}", serde_json::to_string_pretty(&result.to_json())?);
            } else if is_markdown_format(format.as_deref()) {
                println!("{}", utils::sanitize_for_terminal(&result.to_markdown()));
            } else {
                print!("{}", utils::sanitize_for_terminal(&result.to_text()));
            }
        }
        Commands::Timeline { agent, cwd, limit, format, json } => {
            let effective_cwd = effective_cwd(cwd);
            let result = timeline::build_timeline(&agent, &effective_cwd, limit)?;

            if json {
                println!("{}", serde_json::to_string_pretty(&result.to_json())?);
            } else if is_markdown_format(format.as_deref()) {
                println!("{}", utils::sanitize_for_terminal(&result.to_markdown()));
            } else {
                print!("{}", utils::sanitize_for_terminal(&result.to_text()));
            }
        }
        Commands::Doctor { cwd, json } => {
            let effective_cwd = effective_cwd(cwd);
            let result = doctor::run_doctor(&effective_cwd)?;
            if json {
                println!("{}", serde_json::to_string_pretty(&result.to_json())?);
            } else {
                doctor::print_text(&result);
            }
        }
        #[cfg(feature = "update-check")]
        Commands::UpdateWorker => {
            update_check::run_worker();
        }
    }

    #[cfg(feature = "update-check")]
    update_check::maybe_notify(&cli.command);

    Ok(())
}

fn handle_context_pack(command: ContextPackCommand) -> Result<()> {
    match command {
        ContextPackCommand::Build {
            reason,
            base,
            head,
            pack_dir,
            changed_files,
            force_snapshot,
        } => {
            agent_context::build(agent_context::BuildOptions {
                reason,
                base,
                head,
                pack_dir,
                changed_files,
                force_snapshot,
            })?;
        }
        ContextPackCommand::SyncMain {
            local_ref,
            local_sha,
            remote_ref,
            remote_sha,
        } => {
            agent_context::sync_main(
                &local_ref,
                &local_sha,
                &remote_ref,
                &remote_sha,
            )?;
        }
        ContextPackCommand::InstallHooks {
            cwd,
            dry_run,
            enable_post_commit_reconcile,
            install_settings_template,
        } => {
            let target_cwd = effective_cwd(cwd);
            agent_context::install_hooks_with_options(
                &target_cwd,
                dry_run,
                enable_post_commit_reconcile,
            )?;
            if install_settings_template {
                agent_context::install_settings_template(&target_cwd, dry_run)?;
            }
        }
        ContextPackCommand::PostCommitReconcile { cwd, pack_dir } => {
            agent_context::post_commit_reconcile(cwd.as_deref(), pack_dir.as_deref())?;
        }
        ContextPackCommand::Rollback { snapshot, pack_dir, latest_good } => {
            // P13/F58: --latest-good conflicts with an explicit --snapshot
            // value. Fail loudly rather than silently picking one.
            if latest_good && snapshot.is_some() {
                return Err(anyhow::anyhow!(
                    "[agent-context] rollback: --latest-good and --snapshot are mutually exclusive"
                ));
            }
            agent_context::rollback_with_options(agent_context::RollbackOptions {
                snapshot,
                pack_dir,
                latest_good,
            })?;
        }
        ContextPackCommand::Verify {
            pack_dir,
            cwd,
            ci,
            base,
            repair,
            repair_yes,
            suggest_patches,
            enforce_separate_commits,
        } => {
            let target_cwd = effective_cwd(cwd);
            agent_context::verify(agent_context::VerifyOptions {
                pack_dir,
                cwd: target_cwd,
                ci,
                base,
                repair,
                repair_yes,
                suggest_patches,
                enforce_separate_commits,
            })?;
        }
        ContextPackCommand::CheckFreshness { base, cwd } => {
            let target_cwd = effective_cwd(cwd);
            agent_context::check_freshness(
                base.as_deref().unwrap_or("origin/main"),
                &target_cwd,
            )?;
        }
        ContextPackCommand::Init {
            pack_dir,
            cwd,
            force,
            follow_symlinks,
            tier,
        } => {
            // P13/F46: map the numeric CLI flag to the internal tier enum.
            // clap's range parser guarantees 1..=3 reaches us here.
            let init_tier = match tier {
                1 => agent_context::InitTier::One,
                2 => agent_context::InitTier::Two,
                _ => agent_context::InitTier::Three,
            };
            agent_context::init(agent_context::InitOptions {
                pack_dir,
                cwd,
                force,
                follow_symlinks,
                tier: init_tier,
            })?;
        }
        ContextPackCommand::Seal {
            reason,
            base,
            head,
            pack_dir,
            cwd,
            force,
            force_snapshot,
            follow_symlinks,
        } => {
            agent_context::seal(agent_context::SealOptions {
                reason,
                base,
                head,
                pack_dir,
                cwd,
                force,
                force_snapshot,
                follow_symlinks,
            })?;
        }
        ContextPackCommand::Diff {
            since_seal,
            format,
            pack_dir,
            cwd,
        } => {
            // --since-seal is currently the only supported diff mode. We
            // accept it as an explicit flag so future modes (e.g. --since-tag)
            // slot in cleanly without breaking the CLI contract.
            if !since_seal {
                return Err(anyhow::anyhow!(
                    "[agent-context] diff requires --since-seal; no other mode is implemented yet"
                ));
            }
            let target_cwd = effective_cwd(cwd);
            let result = agent_context::diff_since_seal(
                std::path::Path::new(&target_cwd),
                pack_dir.as_deref(),
            )?;
            match format {
                DiffFormat::Json => {
                    println!("{}", serde_json::to_string_pretty(&result.value)?);
                }
                DiffFormat::Text => {
                    agent_context::render_diff_since_seal_text(&result.value);
                }
            }
        }
        ContextPackCommand::CheckToolIntegrity { pack_dir, cwd } => {
            let target_cwd = effective_cwd(cwd);
            agent_context::check_tool_integrity(&target_cwd, pack_dir.as_deref())?;
        }
    }
    Ok(())
}

fn emit_report_output(report_value: &serde_json::Value, json_output: bool) -> Result<()> {
    if json_output {
        println!("{}", serde_json::to_string_pretty(report_value)?);
    } else {
        println!("{}", utils::sanitize_for_terminal(&report::report_to_markdown(report_value)));
    }
    Ok(())
}

fn effective_cwd(cwd: Option<String>) -> String {
    cwd.unwrap_or_else(|| {
        std::env::current_dir()
            .map(|path| path.to_string_lossy().to_string())
            .unwrap_or_else(|_| ".".to_string())
    })
}

fn is_markdown_format(fmt: Option<&str>) -> bool {
    matches!(fmt, Some("markdown" | "md"))
}

fn is_json_format(fmt: Option<&str>) -> bool {
    matches!(fmt, Some("json"))
}

/// Render the session as markdown, mirroring Node's `renderReadAsMarkdown`.
fn render_read_as_markdown(session: &agents::Session) -> String {
    let label = format_agent_name(session.agent);
    let source_basename = std::path::Path::new(&session.source)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(session.source.as_str())
        .to_string();
    let session_id = session.session_id.as_deref().unwrap_or("(unknown)");
    let cwd = session.cwd.as_deref().unwrap_or("(unknown)");
    let mut lines = vec![
        format!("## {} Session: {}", label, session_id),
        String::new(),
        "| Field | Value |".to_string(),
        "|---|---|".to_string(),
        format!("| Source | `{}` |", source_basename),
        format!("| CWD | `{}` |", cwd),
        format!("| Messages | {} of {} |", session.messages_returned, session.message_count),
    ];
    if let Some(ts) = &session.timestamp {
        lines.push(format!("| Timestamp | {} |", ts));
    }
    lines.push(String::new());
    lines.push("---".to_string());
    lines.push(String::new());
    if session.content.is_empty() {
        lines.push("(no content)".to_string());
    } else {
        lines.push(session.content.clone());
    }
    lines.join("\n")
}

fn format_agent_name(agent: &str) -> &'static str {
    match agent {
        "codex" => "Codex",
        "gemini" => "Gemini",
        "claude" => "Claude",
        "cursor" => "Cursor",
        _ => "Unknown",
    }
}

/// Format an ISO 8601 timestamp as a locale-like string (e.g., "3/17/2026, 4:54:38 PM").
fn format_timestamp(iso: &str) -> String {
    // Parse "YYYY-MM-DDThh:mm:ss" prefix
    let parts: Vec<&str> = iso.splitn(2, 'T').collect();
    if parts.len() < 2 {
        return iso.to_string();
    }
    let date_parts: Vec<&str> = parts[0].split('-').collect();
    let time_str = parts[1].trim_end_matches('Z').split('.').next().unwrap_or("");
    let time_parts: Vec<&str> = time_str.split(':').collect();
    if date_parts.len() < 3 || time_parts.len() < 3 {
        return iso.to_string();
    }
    let year: u32 = date_parts[0].parse().unwrap_or(0);
    let month: u32 = date_parts[1].parse().unwrap_or(0);
    let day: u32 = date_parts[2].parse().unwrap_or(0);
    let hour: u32 = time_parts[0].parse().unwrap_or(0);
    let minute: u32 = time_parts[1].parse().unwrap_or(0);
    let second: u32 = time_parts[2].parse().unwrap_or(0);

    let (h12, ampm) = if hour == 0 {
        (12, "AM")
    } else if hour < 12 {
        (hour, "AM")
    } else if hour == 12 {
        (12, "PM")
    } else {
        (hour - 12, "PM")
    };

    format!("{}/{}/{}, {}:{:02}:{:02} {}", month, day, year, h12, minute, second, ampm)
}

/// Truncate a CWD path: if >3 segments, show …/last/two.
fn truncate_cwd(path: &str) -> String {
    let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    if parts.len() <= 3 {
        return path.to_string();
    }
    format!("…/{}", parts[parts.len() - 2..].join("/"))
}