codex-cli-captain 0.0.9

Codex-Cli-Captain runtime, installer, and MCP server for Codex CLI.
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
use crate::install_check::create_server_identity_payload;
use crate::request_routing::{
    create_companion_tool_route_payload, infer_mutation_intent, infer_request_shape,
    infer_task_shape,
};
use crate::review_policy::{
    collect_os_review_pressure_snapshot, create_review_policy_payload, read_u64_field,
    runtime_review_pressure_snapshot_from_value, RuntimeReviewPressureSnapshot,
};
use crate::run_bootstrap::create_ccc_start_payload;
use crate::run_locator::{resolve_run_locator_arguments, resolve_workspace_path};
use crate::specialist_roles::load_role_config_snapshot;
use crate::token_usage::create_token_usage_payload;
use crate::{
    create_ccc_status_payload, create_worker_visibility_payload, load_runtime_config,
    read_json_document, read_optional_shared_config_document, SessionContext,
};
use serde_json::{json, Value};
use std::io;
use std::path::Path;

pub(crate) fn normalize_entry_policy_mode_value(value: &str) -> Option<&'static str> {
    match value {
        "explicit_only" => Some("explicit_only"),
        "guided_explicit" => Some("guided_explicit"),
        "ccc_first_bounded" => Some("ccc_first_bounded"),
        "codex_cli_ccc_first" | "codex_cli_foreman_first" => Some("codex_cli_ccc_first"),
        _ => None,
    }
}

fn normalize_entry_policy_mode(value: Option<&str>) -> String {
    value
        .and_then(normalize_entry_policy_mode_value)
        .unwrap_or("guided_explicit")
        .to_string()
}

fn load_entry_policy_mode() -> String {
    read_optional_shared_config_document()
        .ok()
        .flatten()
        .map(|(_, config)| config)
        .and_then(|config| config.get("entry_policy").cloned())
        .and_then(|entry_policy| entry_policy.get("mode").cloned())
        .and_then(|mode| {
            mode.as_str()
                .map(|value| normalize_entry_policy_mode(Some(value)))
        })
        .unwrap_or_else(|| "guided_explicit".to_string())
}

fn bool_config_value(config: &Value, pointers: &[&str]) -> Option<(bool, String)> {
    pointers.iter().find_map(|pointer| {
        config
            .pointer(pointer)
            .and_then(Value::as_bool)
            .map(|value| (value, (*pointer).trim_start_matches('/').replace('/', ".")))
    })
}

fn parsed_auto_entry_opt_in(parsed: &Value) -> Option<(bool, String)> {
    bool_config_value(
        parsed,
        &[
            "/entry_policy/auto_entry/enabled",
            "/entry_policy/auto_entry_enabled",
            "/auto_entry/opt_in",
            "/auto_entry_enabled",
        ],
    )
}

fn runtime_auto_entry_opt_in(runtime_config: &Value) -> (bool, String) {
    bool_config_value(
        runtime_config,
        &[
            "/entry_policy/auto_entry/enabled",
            "/entry_policy/auto_entry_enabled",
            "/auto_entry/opt_in",
        ],
    )
    .unwrap_or((false, "default_false".to_string()))
}

fn load_auto_entry_opt_in() -> (bool, String) {
    read_optional_shared_config_document()
        .ok()
        .flatten()
        .map(|(_, config)| runtime_auto_entry_opt_in(&config))
        .unwrap_or((false, "default_false".to_string()))
}

fn create_entry_policy_summary(policy_mode: &str) -> &'static str {
    match policy_mode {
        "codex_cli_ccc_first" => {
            "Entry policy prefers CCC-first for fresh MCP requests through the bounded auto-entry surface."
        }
        "ccc_first_bounded" => {
            "Entry policy is opt-in CCC-first on the explicit auto-entry surface."
        }
        _ => "Entry policy remains explicit and expects recommend-entry plus explicit start/run surfaces.",
    }
}

fn request_is_cap_entry(request: &NormalizedEntryRequest<'_>) -> bool {
    request
        .raw
        .split_whitespace()
        .next()
        .map(|token| token == "$cap")
        .unwrap_or(false)
        || request.compact_lowercase.starts_with("$cap ")
}

fn request_is_trivial_or_chat(request: &NormalizedEntryRequest<'_>) -> bool {
    let text = request.compact_lowercase.trim();
    let token_count = text.split_whitespace().count();
    if text.is_empty() {
        return true;
    }
    if matches!(
        text,
        "hi" | "hello"
            | "hey"
            | "thanks"
            | "thank you"
            | "ok"
            | "okay"
            | "yes"
            | "no"
            | "status"
            | "ccc status"
            | "show status"
            | "what is status"
            | "what's the status"
            | "current status"
            | "continue"
            | "go on"
    ) {
        return true;
    }
    token_count <= 2
        && [
            "status", "hello", "hi", "thanks", "ok", "okay", "continue", "ping",
        ]
        .iter()
        .any(|signal| text.contains(signal))
        || request_is_status_or_explanation_only(request)
}

fn request_is_status_or_explanation_only(request: &NormalizedEntryRequest<'_>) -> bool {
    let text = request.compact_lowercase.trim();
    let has_actionable_mutation = [
        "implement",
        "fix",
        "repair",
        "patch",
        "refactor",
        "change",
        "add",
        "remove",
        "wire",
        "create",
        "delete",
        "write",
        "edit",
        "run",
        "test",
        "verify",
        "review",
    ]
    .iter()
    .any(|signal| text.contains(signal));
    if has_actionable_mutation {
        return false;
    }

    let status_query = text == "status"
        || text.starts_with("status ")
        || text.starts_with("show status")
        || text.starts_with("show me status")
        || text.starts_with("what is the status")
        || text.starts_with("what's the status")
        || text.starts_with("current status")
        || text.starts_with("give me status")
        || text.starts_with("summarize status")
        || text.starts_with("summarise status");
    let explanation_query = text.starts_with("explain ")
        || text.starts_with("can you explain")
        || text.starts_with("could you explain")
        || text.starts_with("what is ")
        || text.starts_with("what's ")
        || text.starts_with("tell me about ")
        || text.starts_with("how does ")
        || text.starts_with("how do ");

    status_query || explanation_query
}

fn request_has_docs_entry_signal(request: &NormalizedEntryRequest<'_>) -> bool {
    [
        "docs/",
        "/docs/",
        "readme",
        "changelog",
        "release note",
        "release notes",
        "document",
        "documentation",
        ".md",
        "문서",
        "릴리즈",
    ]
    .iter()
    .any(|signal| request.lowercase.contains(signal) || request.raw.contains(signal))
}

fn request_has_implementation_entry_signal(request: &NormalizedEntryRequest<'_>) -> bool {
    [
        "implement",
        "fix",
        "repair",
        "patch",
        "refactor",
        "update",
        "change",
        "add",
        "remove",
        "wire",
        "구현",
        "수정",
        "変更",
        "実装",
        "修改",
        "实现",
    ]
    .iter()
    .any(|signal| request.lowercase.contains(signal) || request.raw.contains(signal))
}

fn request_has_review_entry_signal(request: &NormalizedEntryRequest<'_>) -> bool {
    [
        "review",
        "verify",
        "validation",
        "regression",
        "test",
        "검토",
        "確認",
        "検証",
        "验证",
    ]
    .iter()
    .any(|signal| request.lowercase.contains(signal) || request.raw.contains(signal))
}

fn classify_non_cap_entry_probe(request: &str, runtime_config: &Value) -> Value {
    let normalized_request = NormalizedEntryRequest::new(request);
    let (auto_entry_opt_in, auto_entry_opt_in_source) = runtime_auto_entry_opt_in(runtime_config);
    let policy_mode = runtime_config
        .pointer("/entry_policy/mode")
        .and_then(Value::as_str)
        .map(|value| normalize_entry_policy_mode(Some(value)))
        .unwrap_or_else(|| "guided_explicit".to_string());
    let policy_mode_allows_auto_entry = matches!(
        policy_mode.as_str(),
        "ccc_first_bounded" | "codex_cli_ccc_first"
    );
    let request_shape = infer_request_shape(request);
    let task_shape = infer_task_shape(request, request_shape);
    let has_docs_signal = request_has_docs_entry_signal(&normalized_request);
    let has_implementation_signal = request_has_implementation_entry_signal(&normalized_request);
    let has_review_signal = request_has_review_entry_signal(&normalized_request);
    let has_documented_completion_signal =
        request_mentions_documented_completion(&normalized_request);
    let has_way_signal = request_has_ambiguous_entry_signal(&normalized_request)
        || request_has_broad_way_confirmation_signal(&normalized_request)
        || [
            "way",
            "plan",
            "planning",
            "longway",
            "phase",
            "step",
            "roadmap",
            "strategy",
            "investigate",
            "analyze",
            "what remains",
        ]
        .iter()
        .any(|signal| normalized_request.compact_lowercase.contains(signal));
    let is_cap_entry = request_is_cap_entry(&normalized_request);
    let trivial_or_chat = request_is_trivial_or_chat(&normalized_request);

    let (candidate, reason, confidence, candidate_kind) = if is_cap_entry {
        (false, "cap_entry_preserved", "high", "explicit_cap_entry")
    } else if trivial_or_chat {
        (false, "trivial_status_or_chat_prompt", "high", "ignored")
    } else if has_docs_signal && has_documented_completion_signal {
        (true, "documented_docs_completion_request", "high", "docs")
    } else if request_shape == "diagnostic" || request_shape == "lookup" {
        (
            false,
            "bounded_read_only_or_status_prompt",
            "medium",
            "ignored",
        )
    } else if request_shape == "mutation" && (has_implementation_signal || has_docs_signal) {
        (
            true,
            "implementation_or_docs_request",
            "high",
            "implementation",
        )
    } else if request_shape == "review" && has_review_signal {
        (true, "review_or_validation_request", "high", "review")
    } else if request_shape == "way" && (has_way_signal || has_docs_signal) {
        (true, "explore_way_or_docs_request", "medium", "way")
    } else {
        (
            false,
            "insufficient_conservative_entry_signal",
            "low",
            "ignored",
        )
    };
    let would_invoke_auto_entry =
        candidate && auto_entry_opt_in && policy_mode_allows_auto_entry && !is_cap_entry;

    json!({
        "candidate": candidate,
        "ignored": !candidate,
        "reason": reason,
        "confidence": confidence,
        "candidate_kind": candidate_kind,
        "request_shape": request_shape,
        "task_shape": task_shape,
        "opt_in": {
            "enabled": auto_entry_opt_in,
            "source": auto_entry_opt_in_source,
            "policy_mode": policy_mode,
            "policy_mode_allows_auto_entry": policy_mode_allows_auto_entry,
        },
        "would_invoke_ccc_auto_entry": would_invoke_auto_entry,
        "preserves_cap_skill_path": true,
        "public_entry_label": "$cap",
    })
}

pub(crate) fn create_entry_probe_dry_run_payload(
    request: Option<&str>,
    runtime_config: &Value,
    activation_path: &str,
) -> Value {
    let Some(request) = request.map(str::trim).filter(|value| !value.is_empty()) else {
        let (auto_entry_opt_in, auto_entry_opt_in_source) =
            runtime_auto_entry_opt_in(runtime_config);
        let policy_mode = runtime_config
            .pointer("/entry_policy/mode")
            .and_then(Value::as_str)
            .map(|value| normalize_entry_policy_mode(Some(value)))
            .unwrap_or_else(|| "guided_explicit".to_string());
        let policy_mode_allows_auto_entry = matches!(
            policy_mode.as_str(),
            "ccc_first_bounded" | "codex_cli_ccc_first"
        );
        return json!({
            "schema": "ccc.entry_probe_dry_run.v1",
            "status": "ignored",
            "activation_path": activation_path,
            "candidate": false,
            "ignored": true,
            "reason": "no_prompt",
            "confidence": "high",
            "opt_in": {
                "enabled": auto_entry_opt_in,
                "source": auto_entry_opt_in_source,
                "policy_mode": policy_mode,
                "policy_mode_allows_auto_entry": policy_mode_allows_auto_entry,
            },
            "would_invoke_ccc_auto_entry": false,
            "entry_command": "ccc auto-entry --quiet --json '{...}'",
            "mutates_on_probe": false,
            "mutates_on_hook": false,
            "preserves_cap_skill_path": true,
            "public_entry_label": "$cap",
            "summary": "Entry probe did not inspect a prompt; auto-entry remains opt-in and non-mutating on dry-run."
        });
    };
    let classification = classify_non_cap_entry_probe(request, runtime_config);
    let candidate = classification
        .get("candidate")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let would_invoke = classification
        .get("would_invoke_ccc_auto_entry")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    json!({
        "schema": "ccc.entry_probe_dry_run.v1",
        "status": if candidate { "candidate" } else { "ignored" },
        "activation_path": activation_path,
        "candidate": candidate,
        "ignored": !candidate,
        "reason": classification.get("reason").cloned().unwrap_or(Value::String("unknown".to_string())),
        "confidence": classification.get("confidence").cloned().unwrap_or(Value::String("low".to_string())),
        "candidate_kind": classification.get("candidate_kind").cloned().unwrap_or(Value::String("ignored".to_string())),
        "request_shape": classification.get("request_shape").cloned().unwrap_or(Value::Null),
        "task_shape": classification.get("task_shape").cloned().unwrap_or(Value::Null),
        "opt_in": classification.get("opt_in").cloned().unwrap_or(Value::Null),
        "would_invoke_ccc_auto_entry": would_invoke,
        "entry_command": "ccc auto-entry --quiet --json '{...}'",
        "mutates_on_probe": false,
        "mutates_on_hook": false,
        "preserves_cap_skill_path": true,
        "public_entry_label": "$cap",
        "summary": if would_invoke {
            "Entry probe dry-run classifies this prompt as an opt-in CCC auto-entry candidate; the probe itself remains non-mutating."
        } else if candidate {
            "Entry probe dry-run classifies this prompt as a CCC candidate, but opt-in policy prevents automatic run creation."
        } else {
            "Entry probe dry-run ignored this prompt under the conservative non-$cap policy."
        }
    })
}

fn create_entry_boundary_payload(policy_mode: &str) -> Value {
    match policy_mode {
        "codex_cli_ccc_first" => json!({
            "entry_boundary": "session_instruction_plus_wrapper",
            "entry_boundary_summary": "The supported CCC-first boundary is bounded MCP session guidance plus the explicit wrapper surface."
        }),
        "ccc_first_bounded" => json!({
            "entry_boundary": "explicit_auto_entry",
            "entry_boundary_summary": "The supported CCC-first boundary is the explicit auto-entry surface only."
        }),
        _ => json!({
            "entry_boundary": "explicit_cli_or_mcp",
            "entry_boundary_summary": "The supported CCC entry boundary stays fully explicit."
        }),
    }
}

fn create_entry_guard_reason(
    request_shape: &str,
    task_shape: &str,
    documented_completion_requested: bool,
    direct_allowed: bool,
    companion_tool_routed: bool,
    tool_operation: &str,
) -> String {
    if direct_allowed {
        "The request is a bounded read-only lookup and can proceed directly without mutating CCC state."
            .to_string()
    } else if tool_operation == "mutation" {
        "The request routes to a companion-owned mutation tool; captain-local tool execution is hard-blocked and must reroute through CCC control-plane ownership."
            .to_string()
    } else if companion_tool_routed {
        "The request routes to companion-owned tool work; captain-local tool execution is hard-blocked and must reroute to the owning companion role."
            .to_string()
    } else if documented_completion_requested {
        "The request asks for documented completion, so captain should stay inside CCC state until the criteria are met or explicitly blocked."
            .to_string()
    } else if request_shape == "mutation" {
        "The request contains mutation signals and should not bypass CCC control-plane state."
            .to_string()
    } else if request_shape == "review" {
        "The request is a review pass and should stay inside CCC control-plane truth before any follow-up."
            .to_string()
    } else if task_shape == "multi_step_or_unclear" {
        "The request is multi-step or unclear and should stay inside CCC control-plane state before execution."
            .to_string()
    } else {
        "The request should stay inside CCC control-plane state before execution.".to_string()
    }
}

fn create_entry_guard_active_run_summary() -> &'static str {
    "ccc_recommend_entry does not scan active runs; use ccc_status for run-scoped truth."
}

fn infer_recommended_entrypoint(request_shape: &str) -> &'static str {
    match request_shape {
        "lookup" | "diagnostic" | "review" => "start",
        _ => "way",
    }
}

fn infer_recommended_task_kind(request_shape: &str) -> &'static str {
    match request_shape {
        "review" => "review",
        "lookup" | "diagnostic" => "explore",
        _ => "way",
    }
}

pub(crate) fn runtime_review_pressure_snapshot_from_run_directory(
    run_directory: &Path,
) -> io::Result<Option<RuntimeReviewPressureSnapshot>> {
    let runtime_config = load_runtime_config()?;
    let run_record = read_json_document(&run_directory.join("run.json"))?;
    let active_task_card_id = run_record
        .get("active_task_card_id")
        .and_then(Value::as_str);
    let worker_visibility =
        create_worker_visibility_payload(run_directory, active_task_card_id, &runtime_config)?;
    let token_usage = create_token_usage_payload(run_directory)?;
    let snapshot = RuntimeReviewPressureSnapshot {
        source: "run_status_surfaces".to_string(),
        stale_worker_count: read_u64_field(&worker_visibility, "stale_worker_count"),
        timed_out_worker_count: read_u64_field(&worker_visibility, "timed_out_worker_count"),
        reclaim_needed_worker_count: read_u64_field(
            &worker_visibility,
            "reclaim_needed_worker_count",
        ),
        active_run_count: 0,
        token_total: read_u64_field(&token_usage, "total_tokens"),
        token_soft_limit: runtime_config
            .get("review_token_soft_limit")
            .and_then(Value::as_u64)
            .filter(|limit| *limit > 0),
        cpu_available_parallelism: None,
        memory_total_kib: None,
        memory_available_kib: None,
        memory_available_percent: None,
        pressure_reason: None,
    };
    if let Some(os_snapshot) = collect_os_review_pressure_snapshot() {
        let snapshot = RuntimeReviewPressureSnapshot {
            source: "combined_run_and_os_snapshot".to_string(),
            cpu_available_parallelism: os_snapshot.cpu_available_parallelism,
            memory_total_kib: os_snapshot.memory_total_kib,
            memory_available_kib: os_snapshot.memory_available_kib,
            memory_available_percent: os_snapshot.memory_available_percent,
            ..snapshot
        };
        return Ok(snapshot.has_observed_pressure().then_some(snapshot));
    }
    Ok(snapshot.has_observed_pressure().then_some(snapshot))
}

fn create_recommendation_title(request: &str) -> String {
    let single_line = request.split_whitespace().collect::<Vec<_>>().join(" ");
    let trimmed = single_line.trim();
    if trimmed.chars().count() <= 88 {
        trimmed.to_string()
    } else {
        format!("{}...", trimmed.chars().take(85).collect::<String>())
    }
}

struct NormalizedEntryRequest<'a> {
    raw: &'a str,
    lowercase: String,
    compact_lowercase: String,
}

impl<'a> NormalizedEntryRequest<'a> {
    fn new(raw: &'a str) -> Self {
        let lowercase = raw.to_ascii_lowercase();
        let compact_lowercase = lowercase.split_whitespace().collect::<Vec<_>>().join(" ");
        Self {
            raw,
            lowercase,
            compact_lowercase,
        }
    }
}

fn request_mentions_documented_completion(request: &NormalizedEntryRequest<'_>) -> bool {
    request.lowercase.contains("finish")
        || request.lowercase.contains("complete")
        || request.lowercase.contains("end to end")
        || request.lowercase.contains("until done")
        || request.lowercase.contains("release note")
        || request.lowercase.contains("docs/")
        || request.lowercase.contains(".md")
        || request.raw.contains("끝까지")
        || request.raw.contains("완료")
        || request.raw.contains("마무리")
        || request.raw.contains("문서")
        || request.raw.contains("릴리즈")
}

fn request_has_ambiguous_entry_signal(request: &NormalizedEntryRequest<'_>) -> bool {
    let file_path_mentions = request.raw.matches('.').count();
    file_path_mentions >= 3
        || [
            "ambiguous",
            "unclear",
            "not sure",
            "investigate",
            "analyze",
            "diagnose",
            "multi-step",
            "runtime mutation",
            "what remains",
            "plan the next",
            "next bounded step",
            "next step",
        ]
        .iter()
        .any(|signal| request.compact_lowercase.contains(signal))
}

fn request_has_broad_way_confirmation_signal(request: &NormalizedEntryRequest<'_>) -> bool {
    [
        "across",
        "across modules",
        "cross-module",
        "cross module",
        "repository-wide",
        "repo-wide",
        "strategy",
        "strategic",
        "multiple tasks",
        "multiple workstreams",
        "multi-part",
        "multi part",
        "several tasks",
        "전체",
        "다방면",
        "여러 작업",
        "복수 작업",
    ]
    .iter()
    .any(|signal| request.compact_lowercase.contains(signal))
}

fn request_mentions_release_install_mutation(
    request: &NormalizedEntryRequest<'_>,
    request_shape: &str,
) -> bool {
    if request_shape != "mutation" {
        return false;
    }
    let release_or_install = [
        "release",
        "install",
        "installer",
        "install.sh",
        "install.ps1",
        "release asset",
        "scripts/release",
    ]
    .iter()
    .any(|signal| request.lowercase.contains(signal));
    let mutation_signal = [
        "fix",
        "repair",
        "implement",
        "change",
        "update",
        "patch",
        "upload",
        "edit",
        "create",
        "delete",
    ]
    .iter()
    .any(|signal| request.lowercase.contains(signal));
    release_or_install && mutation_signal
}

fn create_completion_discipline_payload(
    request: &NormalizedEntryRequest<'_>,
    task_shape: &str,
) -> Value {
    let documented_completion = request_mentions_documented_completion(request);
    json!({
        "state": if documented_completion { "required" } else { "bounded" },
        "completion_mode": if documented_completion { "documented_completion_criteria" } else { "single_bounded_checkpoint" },
        "documented_completion_requested": documented_completion,
        "task_shape": task_shape,
        "summary": if documented_completion {
            "Captain must continue through the referenced document or checklist until acceptance is met, explicitly out of scope, or blocked on an operator decision; stopping after a partial slice is not complete."
        } else {
            "Captain may keep the first run to one bounded checkpoint, then continue only when the persisted next action requires it."
        },
        "captain_obligations": if documented_completion {
            json!([
                "derive concrete remaining items from the referenced document or checklist",
                "persist progress and next action after each slice",
                "continue slices until every in-scope item is completed, explicitly deferred, or blocked",
                "record validation or the exact blocker before answering"
            ])
        } else {
            json!([
                "persist one bounded run and visible next captain action",
                "avoid hidden local fallback when CCC owns the entry"
            ])
        },
    })
}

fn intent_confirmation_reason_codes(
    request: &NormalizedEntryRequest<'_>,
    request_shape: &str,
    task_shape: &str,
    risk: &str,
    tool_operation: &str,
) -> Vec<&'static str> {
    let mut reasons = Vec::new();
    if request_mentions_release_install_mutation(request, request_shape) {
        reasons.push("release_install_mutation");
    }
    if request_shape == "mutation" && task_shape == "multi_step_or_unclear" {
        reasons.push("multi_step_runtime_mutation");
    }
    if request_shape == "way"
        && task_shape == "multi_step_or_unclear"
        && request_has_broad_way_confirmation_signal(request)
    {
        reasons.push("broad_way_request");
    }
    if request_shape == "way" && request_has_ambiguous_entry_signal(request) {
        reasons.push("ambiguous_way_request");
    }
    if risk == "high" {
        reasons.push("high_risk_request");
    }
    if tool_operation == "mutation" {
        reasons.push("companion_tool_mutation");
    }
    reasons
}

fn create_intent_confirmation_payload(
    request: &NormalizedEntryRequest<'_>,
    request_shape: &str,
    task_shape: &str,
    mutation_intent: &str,
    recommended_entrypoint: &str,
    recommended_task_kind: &str,
    risk: &str,
    direct_allowed: bool,
    tool_route: &Value,
) -> Value {
    let tool_operation = tool_route
        .get("operation")
        .and_then(Value::as_str)
        .unwrap_or("none");
    let reason_codes =
        intent_confirmation_reason_codes(request, request_shape, task_shape, risk, tool_operation);
    let required = !direct_allowed && !reason_codes.is_empty();
    let next_action = if required {
        "await_operator"
    } else {
        "proceed"
    };
    let interpretation = json!({
        "request_title": create_recommendation_title(request.raw),
        "request_shape": request_shape,
        "task_shape": task_shape,
        "mutation_intent": mutation_intent,
        "recommended_entrypoint": recommended_entrypoint,
        "recommended_task_kind": recommended_task_kind,
        "risk": risk,
        "companion_tool_operation": tool_operation,
        "companion_tool_route_class": tool_route.get("route_class").cloned().unwrap_or(Value::String("none".to_string())),
    });
    let prompt = if required {
        Value::String(
            "Confirm this interpretation before CCC creates a Way/run, or rephrase the request with the intended scope."
                .to_string(),
        )
    } else {
        Value::Null
    };

    json!({
        "state": if required { "required" } else { "not_required" },
        "required": required,
        "next_action": next_action,
        "confirmation_kind": if required { "intent_interpretation" } else { "none" },
        "awaiting": if required { "operator_confirmation" } else { "none" },
        "reason_codes": reason_codes,
        "interpretation": interpretation,
        "clarification_policy": {
            "question_count": if required { "1-3" } else { "0" },
            "required_for": [
                "broad work",
                "risky work",
                "ambiguous scope",
                "irreversible actions"
            ],
            "narrow_work_default": "proceed_with_explicit_assumptions"
        },
        "prompt": prompt,
        "summary": if required {
            "CCC must await operator confirmation of the interpreted intent before Way planning or normal entry."
        } else if direct_allowed {
            "No intent confirmation is required for this bounded read-only request."
        } else {
            "No blocking intent confirmation is required by the current bounded policy."
        },
    })
}

fn create_captain_local_tool_guard_payload(
    request_shape: &str,
    direct_allowed: bool,
    companion_tool_routed: bool,
    tool_route: &Value,
) -> Value {
    let tool_operation = tool_route
        .get("operation")
        .and_then(Value::as_str)
        .unwrap_or("none");
    let owner_role = tool_route.get("owner_role").cloned().unwrap_or(Value::Null);
    let route_class = tool_route
        .get("route_class")
        .cloned()
        .unwrap_or(Value::String("none".to_string()));
    let hard_block =
        companion_tool_routed || request_shape == "mutation" || tool_operation == "mutation";
    let next_action = if companion_tool_routed {
        "reroute_to_companion_tool_owner"
    } else if request_shape == "mutation" {
        "enter_ccc_control_plane"
    } else if direct_allowed {
        "proceed_direct_read_only"
    } else {
        "enter_ccc_control_plane"
    };
    let required_action = if companion_tool_routed {
        "Do not perform captain-local tool work; route through the companion tool owner recorded in this recommendation."
    } else if request_shape == "mutation" {
        "Do not perform unrecorded captain-local mutation; enter CCC control-plane state first."
    } else if direct_allowed {
        "Proceed only with bounded read-only local answering."
    } else {
        "Enter CCC control-plane state before execution."
    };

    json!({
        "state": if hard_block { "hard_block_reroute" } else if direct_allowed { "direct_read_only_allowed" } else { "control_plane_required" },
        "hard_block": hard_block,
        "captain_local_tool_work_allowed": direct_allowed && !companion_tool_routed,
        "reroute_required": companion_tool_routed,
        "next_action": next_action,
        "required_action": required_action,
        "companion_tool_operation": tool_operation,
        "companion_tool_route_class": route_class,
        "companion_tool_owner_role": owner_role,
        "summary": if companion_tool_routed {
            "Captain local tool work is blocked because this request has an explicit companion-owned tool route."
        } else if request_shape == "mutation" {
            "Captain local mutation is blocked until CCC state records the bounded work."
        } else if direct_allowed {
            "Captain may answer directly only because no companion-owned tool route or mutation intent was detected."
        } else {
            "Captain should enter CCC state before execution."
        }
    })
}

pub(crate) fn create_ccc_recommend_entry_payload_for_policy(
    parsed: &Value,
    policy_mode_override: Option<&str>,
) -> Value {
    let request = parsed
        .get("request")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let normalized_request = NormalizedEntryRequest::new(request);
    let cwd = parsed.get("cwd").cloned().unwrap_or(Value::Null);
    let policy_mode = policy_mode_override
        .map(|value| normalize_entry_policy_mode(Some(value)))
        .unwrap_or_else(load_entry_policy_mode);
    let request_shape = infer_request_shape(request);
    let mutation_intent = infer_mutation_intent(request_shape);
    let task_shape = infer_task_shape(request, request_shape);
    let completion_discipline =
        create_completion_discipline_payload(&normalized_request, task_shape);
    let payload_runtime_pressure = runtime_review_pressure_snapshot_from_value(
        parsed.get("runtime_pressure"),
        "request_payload",
    );
    let review_policy = create_review_policy_payload(
        request,
        request_shape,
        task_shape,
        None,
        payload_runtime_pressure.as_ref(),
    );
    let recommended_entrypoint = infer_recommended_entrypoint(request_shape);
    let recommended_task_kind = infer_recommended_task_kind(request_shape);
    let tool_route = create_companion_tool_route_payload(request, mutation_intent);
    let tool_operation = tool_route
        .get("operation")
        .and_then(Value::as_str)
        .unwrap_or("none");
    let companion_tool_routed = tool_route.get("execution_state").and_then(Value::as_str)
        == Some("route_backed_specialist_owned")
        || tool_route
            .get("owner_role")
            .and_then(Value::as_str)
            .map(|value| !value.trim().is_empty())
            .unwrap_or(false)
        || !matches!(tool_operation, "none" | "");
    let documented_completion_requested = completion_discipline
        .get("documented_completion_requested")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let direct_allowed = matches!(request_shape, "lookup" | "diagnostic")
        && task_shape == "single_scoped_task"
        && !documented_completion_requested
        && !companion_tool_routed;
    let requires_user_confirmation = !direct_allowed;
    let recommended_action = if direct_allowed {
        "direct_read_only"
    } else if companion_tool_routed {
        "reroute_companion_tool"
    } else {
        "enter_ccc_control_plane"
    };
    let entry_guard_reason = create_entry_guard_reason(
        request_shape,
        task_shape,
        documented_completion_requested,
        direct_allowed,
        companion_tool_routed,
        tool_operation,
    );
    let confidence = if task_shape == "multi_step_or_unclear" {
        "high"
    } else {
        "medium"
    };
    let policy_mode_supports_auto_entry = matches!(
        policy_mode.as_str(),
        "ccc_first_bounded" | "codex_cli_ccc_first"
    );
    let (auto_entry_opt_in, auto_entry_opt_in_source) = parsed_auto_entry_opt_in(parsed)
        .unwrap_or_else(|| {
            if policy_mode_override.is_some() {
                (false, "default_false".to_string())
            } else {
                load_auto_entry_opt_in()
            }
        });
    let automatic_entry_supported = policy_mode_supports_auto_entry && auto_entry_opt_in;
    let entry_boundary = create_entry_boundary_payload(&policy_mode);
    let orchestrator_role_config = load_role_config_snapshot("orchestrator");
    let risk = review_policy
        .get("risk")
        .and_then(Value::as_str)
        .unwrap_or("unknown");
    let intent_confirmation = create_intent_confirmation_payload(
        &normalized_request,
        request_shape,
        task_shape,
        mutation_intent,
        recommended_entrypoint,
        recommended_task_kind,
        risk,
        direct_allowed,
        &tool_route,
    );
    let intent_confirmation_required = intent_confirmation
        .get("required")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let captain_local_tool_guard = create_captain_local_tool_guard_payload(
        request_shape,
        direct_allowed,
        companion_tool_routed,
        &tool_route,
    );
    let guarded_next_action = if intent_confirmation_required {
        intent_confirmation
            .get("next_action")
            .cloned()
            .unwrap_or(Value::String("await_operator".to_string()))
    } else {
        captain_local_tool_guard
            .get("next_action")
            .cloned()
            .unwrap_or(Value::String("proceed".to_string()))
    };
    let rationale = match request_shape {
        "mutation" => vec![
            "The request contains explicit mutation signals.".to_string(),
            "Captain should still enter through a bounded LongWay contract before specialist execution.".to_string(),
        ],
        "way" => vec![
            "The request contains Way or multi-step investigation signals.".to_string(),
            "Captain should keep the first move on a bounded Way route.".to_string(),
        ],
        "review" => vec![
            "The request reads like a review or verification pass.".to_string(),
            "A bounded read-only or review-scoped run is safer than direct execution.".to_string(),
        ],
        _ => vec![
            "The request is lightweight and can stay on a bounded read-only start path.".to_string(),
        ],
    };
    let summary = if recommended_entrypoint == "way" {
        "Recommend `Way` because captain should generate a bounded LongWay before specialist execution."
    } else {
        "Recommend `start` because the request can stay on a single bounded read-only or review-scoped run."
    };

    json!({
        "cwd": cwd,
        "request": request,
        "policy_mode": policy_mode,
        "policy_summary": create_entry_policy_summary(&policy_mode),
        "auto_entry_opt_in": auto_entry_opt_in,
        "auto_entry_opt_in_source": auto_entry_opt_in_source,
        "policy_mode_supports_auto_entry": policy_mode_supports_auto_entry,
        "automatic_entry_supported": automatic_entry_supported,
        "would_invoke_ccc_auto_entry": automatic_entry_supported && !direct_allowed && !intent_confirmation_required,
        "entry_boundary": entry_boundary.get("entry_boundary").cloned().unwrap_or(Value::Null),
        "entry_boundary_summary": entry_boundary.get("entry_boundary_summary").cloned().unwrap_or(Value::Null),
        "upstream_codex_binary_intercept_supported": false,
        "upstream_codex_binary_intercept_summary": "Hidden upstream Codex CLI binary interception is not a supported CCC entry boundary.",
        "orchestrator_scope": "bounded_synthesis_decision_and_state_supervision",
        "orchestrator_scope_summary": "Captain stays responsible for Way and LongWay supervision, bounded routing, persisted state supervision, and operator-facing visibility.",
        "orchestrator_agent": {
            "role": "orchestrator",
            "roster_name": "captain",
            "profile": orchestrator_role_config.get("profile").cloned().unwrap_or(Value::Null),
            "model": orchestrator_role_config.get("model").cloned().unwrap_or(Value::Null),
            "variant": orchestrator_role_config.get("variant").cloned().unwrap_or(Value::Null),
            "config_entries": orchestrator_role_config.get("config_entries").cloned().unwrap_or_else(|| Value::Array(Vec::new())),
        },
        "orchestrator_request_settings_preview": {
            "source": "shared_role_config",
            "profile": orchestrator_role_config.get("profile").cloned().unwrap_or(Value::Null),
            "model": orchestrator_role_config.get("model").cloned().unwrap_or(Value::Null),
            "variant": orchestrator_role_config.get("variant").cloned().unwrap_or(Value::Null),
            "config_entries": orchestrator_role_config.get("config_entries").cloned().unwrap_or_else(|| Value::Array(Vec::new())),
        },
        "recommended_entrypoint": recommended_entrypoint,
        "task_shape": task_shape,
        "request_shape": request_shape,
        "mutation_intent": mutation_intent,
        "recommended_task_kind": recommended_task_kind,
        "recommended_action": recommended_action,
        "direct_allowed": direct_allowed,
        "requires_user_confirmation": requires_user_confirmation,
        "active_run_summary": create_entry_guard_active_run_summary(),
        "risk": review_policy.get("risk").cloned().unwrap_or(Value::Null),
        "reason": entry_guard_reason,
        "next_action": guarded_next_action,
        "operator_confirmation_required": intent_confirmation_required,
        "confirmation_prompt": intent_confirmation.get("prompt").cloned().unwrap_or(Value::Null),
        "intent_confirmation": intent_confirmation,
        "captain_local_tool_guard": captain_local_tool_guard,
        "completion_discipline": completion_discipline,
        "review_policy": review_policy,
        "confidence": confidence,
        "summary": summary,
        "rationale": rationale,
        "suggested_cli_command": "ccc start",
        "suggested_mcp_tool": if recommended_entrypoint == "way" { "ccc_start" } else { "ccc_start" },
        "workflow_variant_selection": Value::Null,
        "companion_tool_route_class": tool_route.get("route_class").cloned().unwrap_or(Value::String("none".to_string())),
        "companion_tool_names": tool_route.get("tool_names").cloned().unwrap_or_else(|| Value::Array(Vec::new())),
        "companion_tool_operation": tool_route.get("operation").cloned().unwrap_or(Value::String("none".to_string())),
        "companion_tool_owner_role": tool_route.get("owner_role").cloned().unwrap_or(Value::Null),
        "companion_tool_model": tool_route.get("model").cloned().unwrap_or(Value::Null),
        "companion_tool_variant": tool_route.get("variant").cloned().unwrap_or(Value::Null),
        "companion_tool_fallback_mode": tool_route.get("fallback_mode").cloned().unwrap_or(Value::String("visible_degraded_host_fallback".to_string())),
        "companion_tool_execution_state": tool_route.get("execution_state").cloned().unwrap_or(Value::String("not_applicable".to_string())),
    })
}

pub(crate) fn create_ccc_recommend_entry_payload(parsed: &Value) -> Value {
    create_ccc_recommend_entry_payload_for_policy(parsed, None)
}

pub(crate) fn create_ccc_recommend_entry_text(payload: &Value) -> String {
    let mut text = format!(
        "CCC entry recommendation: action={} direct_allowed={} next_action={} risk={} confidence={}",
        payload
            .get("recommended_action")
            .and_then(Value::as_str)
            .unwrap_or("enter_ccc_control_plane"),
        payload
            .get("direct_allowed")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        payload
            .get("next_action")
            .and_then(Value::as_str)
            .unwrap_or("proceed"),
        payload
            .get("risk")
            .and_then(Value::as_str)
            .unwrap_or("unknown"),
        payload
            .get("confidence")
            .and_then(Value::as_str)
            .unwrap_or("medium"),
    );
    if payload
        .get("operator_confirmation_required")
        .and_then(Value::as_bool)
        .unwrap_or(false)
    {
        if let Some(prompt) = payload.get("confirmation_prompt").and_then(Value::as_str) {
            text.push_str(" prompt=\"");
            text.push_str(prompt);
            text.push('"');
        }
    }
    text
}

fn create_auto_entry_start_request(parsed: &Value, recommendation: &Value) -> Value {
    let request = parsed
        .get("request")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let request_shape = recommendation
        .get("request_shape")
        .and_then(Value::as_str)
        .unwrap_or("way");
    let recommended_task_kind = recommendation
        .get("recommended_task_kind")
        .and_then(Value::as_str)
        .unwrap_or("way");
    let recommended_entrypoint = recommendation
        .get("recommended_entrypoint")
        .and_then(Value::as_str)
        .unwrap_or("way");
    let completion_discipline = recommendation
        .get("completion_discipline")
        .cloned()
        .unwrap_or(Value::Null);
    let documented_completion = completion_discipline
        .get("documented_completion_requested")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let title = create_recommendation_title(request);
    let intent = match request_shape {
        "mutation" => "Create a bounded captain-first Way before mutation execution.",
        "review" => "Create a bounded review-scoped run before verification.",
        "lookup" => "Create a bounded read-only run for the operator request.",
        _ => "Create a bounded captain-first Way run for the operator request.",
    };
    let scope = if documented_completion {
        "Continue through the referenced document or checklist in bounded slices until every in-scope completion criterion is met, explicitly deferred, or blocked on an operator decision."
    } else {
        match request_shape {
            "mutation" => "Keep the first run limited to one Way checkpoint and the smallest next implementation slice.",
            "review" => "Keep the run limited to one review or verification checkpoint.",
            "lookup" => "Keep the run read-only and bounded to one visible checkpoint.",
            _ => "Keep the run bounded to one Way checkpoint and the smallest next specialist handoff.",
        }
    };
    let acceptance = if documented_completion {
        "Done only when all referenced document/checklist items are completed with validation recorded, explicitly out of scope, or blocked with the exact operator decision needed; do not report success after a partial slice."
    } else {
        "Persist an honest bounded run with one active task-card, a visible next captain action, and no hidden reuse or hydration wait."
    };
    let assigned_role = recommendation
        .get("companion_tool_owner_role")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .filter(|_| recommended_entrypoint == "start");

    json!({
        "cwd": parsed.get("cwd").cloned().unwrap_or(Value::Null),
        "goal": request,
        "title": title,
        "intent": intent,
        "scope": scope,
        "acceptance": acceptance,
        "prompt": request,
        "task_kind": recommended_task_kind,
        "assigned_role": assigned_role,
        "codex_bin": parsed.get("codex_bin").cloned().unwrap_or(Value::Null),
        "review_policy": recommendation.get("review_policy").cloned().unwrap_or(Value::Null),
        "completion_discipline": completion_discipline,
    })
}

pub(crate) fn create_ccc_auto_entry_payload_for_policy(
    session_context: &SessionContext,
    parsed: &Value,
    policy_mode_override: Option<&str>,
) -> io::Result<Value> {
    let parsed_policy_mode = parsed
        .pointer("/entry_policy/mode")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty());
    let recommendation = create_ccc_recommend_entry_payload_for_policy(
        parsed,
        policy_mode_override.or(parsed_policy_mode),
    );
    let automatic_entry_supported = recommendation
        .get("automatic_entry_supported")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let cwd = resolve_workspace_path(parsed.get("cwd").and_then(Value::as_str))?;
    let entry_probe_runtime_config = json!({
        "entry_policy": {
            "mode": recommendation.get("policy_mode").cloned().unwrap_or(Value::String("guided_explicit".to_string())),
            "auto_entry": {
                "enabled": recommendation.get("auto_entry_opt_in").cloned().unwrap_or(Value::Bool(false))
            }
        }
    });
    let entry_probe = create_entry_probe_dry_run_payload(
        parsed.get("request").and_then(Value::as_str),
        &entry_probe_runtime_config,
        "ccc_auto_entry_preflight",
    );
    if entry_probe
        .get("candidate")
        .and_then(Value::as_bool)
        .unwrap_or(false)
        == false
    {
        return Ok(json!({
            "cwd": cwd.to_string_lossy(),
            "request": parsed.get("request").cloned().unwrap_or(Value::Null),
            "policy_mode": recommendation.get("policy_mode").cloned().unwrap_or(Value::Null),
            "auto_entry_opt_in": recommendation.get("auto_entry_opt_in").cloned().unwrap_or(Value::Bool(false)),
            "auto_entry_opt_in_source": recommendation.get("auto_entry_opt_in_source").cloned().unwrap_or(Value::String("default_false".to_string())),
            "policy_mode_supports_auto_entry": recommendation.get("policy_mode_supports_auto_entry").cloned().unwrap_or(Value::Bool(false)),
            "automatic_entry_supported": automatic_entry_supported,
            "entry_boundary": recommendation.get("entry_boundary").cloned().unwrap_or(Value::Null),
            "entry_boundary_summary": recommendation.get("entry_boundary_summary").cloned().unwrap_or(Value::Null),
            "upstream_codex_binary_intercept_supported": false,
            "created": false,
            "run_selection": "entry_probe_ignored",
            "active_run_scan_state": "skipped_entry_probe_ignored",
            "active_run_scan_summary": "Rust auto-entry did not scan or create a run because the conservative entry_probe policy ignored this prompt.",
            "inspected_active_run_count": 0,
            "fresh_active_run_count": 0,
            "stale_active_run_count": 0,
            "entrypoint_used": Value::Null,
            "scoping_source": "entry_probe_dry_run",
            "run_decision_reason": entry_probe.get("reason").cloned().unwrap_or(Value::String("entry_probe_ignored".to_string())),
            "summary": "Rust auto-entry did not create a run because the prompt was not a conservative non-$cap CCC candidate.",
            "entry_probe": entry_probe,
            "review_policy": recommendation.get("review_policy").cloned().unwrap_or(Value::Null),
            "completion_discipline": recommendation.get("completion_discipline").cloned().unwrap_or(Value::Null),
            "answer_trace": {
                "request_shape": recommendation.get("request_shape").cloned().unwrap_or(Value::Null),
                "mutation_intent": recommendation.get("mutation_intent").cloned().unwrap_or(Value::Null),
                "selected_role": "captain",
                "execution_path": "entry_probe_ignored",
                "budget_class": "none",
                "review_requirement": recommendation.pointer("/review_policy/decision").cloned().unwrap_or(Value::String("not_applicable".to_string())),
                "completion_mode": recommendation.pointer("/completion_discipline/completion_mode").cloned().unwrap_or(Value::Null),
            },
            "recommendation": recommendation,
            "server_identity": create_server_identity_payload(session_context),
        }));
    }

    if !automatic_entry_supported {
        return Ok(json!({
            "cwd": cwd.to_string_lossy(),
            "request": parsed.get("request").cloned().unwrap_or(Value::Null),
            "policy_mode": recommendation.get("policy_mode").cloned().unwrap_or(Value::Null),
            "auto_entry_opt_in": recommendation.get("auto_entry_opt_in").cloned().unwrap_or(Value::Bool(false)),
            "auto_entry_opt_in_source": recommendation.get("auto_entry_opt_in_source").cloned().unwrap_or(Value::String("default_false".to_string())),
            "policy_mode_supports_auto_entry": recommendation.get("policy_mode_supports_auto_entry").cloned().unwrap_or(Value::Bool(false)),
            "automatic_entry_supported": false,
            "entry_boundary": recommendation.get("entry_boundary").cloned().unwrap_or(Value::Null),
            "entry_boundary_summary": recommendation.get("entry_boundary_summary").cloned().unwrap_or(Value::Null),
            "upstream_codex_binary_intercept_supported": false,
            "created": false,
            "run_selection": "explicit_entry_required",
            "active_run_scan_state": "skipped_for_rust_deterministic_path",
            "active_run_scan_summary": "Rust auto-entry intentionally skipped active-run reuse and requires explicit entry under the current policy.",
            "inspected_active_run_count": 0,
            "fresh_active_run_count": 0,
            "stale_active_run_count": 0,
            "entrypoint_used": Value::Null,
            "scoping_source": "recommendation_only",
            "run_decision_reason": "policy_requires_explicit_entry",
            "summary": "Rust auto-entry returned a deterministic recommendation only because the current policy does not allow automatic run creation.",
            "entry_probe": entry_probe,
            "review_policy": recommendation.get("review_policy").cloned().unwrap_or(Value::Null),
            "completion_discipline": recommendation.get("completion_discipline").cloned().unwrap_or(Value::Null),
            "answer_trace": {
                "request_shape": recommendation.get("request_shape").cloned().unwrap_or(Value::Null),
                "mutation_intent": recommendation.get("mutation_intent").cloned().unwrap_or(Value::Null),
                "selected_role": "captain",
                "execution_path": "recommendation_only",
                "budget_class": "way_budget",
                "review_requirement": recommendation.pointer("/review_policy/decision").cloned().unwrap_or(Value::String("not_applicable".to_string())),
                "completion_mode": recommendation.pointer("/completion_discipline/completion_mode").cloned().unwrap_or(Value::Null),
            },
            "recommendation": recommendation,
            "server_identity": create_server_identity_payload(session_context),
        }));
    }

    if recommendation
        .get("operator_confirmation_required")
        .and_then(Value::as_bool)
        .unwrap_or(false)
    {
        return Ok(json!({
            "cwd": cwd.to_string_lossy(),
            "request": parsed.get("request").cloned().unwrap_or(Value::Null),
            "policy_mode": recommendation.get("policy_mode").cloned().unwrap_or(Value::Null),
            "auto_entry_opt_in": recommendation.get("auto_entry_opt_in").cloned().unwrap_or(Value::Bool(false)),
            "auto_entry_opt_in_source": recommendation.get("auto_entry_opt_in_source").cloned().unwrap_or(Value::String("default_false".to_string())),
            "policy_mode_supports_auto_entry": recommendation.get("policy_mode_supports_auto_entry").cloned().unwrap_or(Value::Bool(false)),
            "automatic_entry_supported": true,
            "entry_boundary": recommendation.get("entry_boundary").cloned().unwrap_or(Value::Null),
            "entry_boundary_summary": recommendation.get("entry_boundary_summary").cloned().unwrap_or(Value::Null),
            "upstream_codex_binary_intercept_supported": false,
            "created": false,
            "run_selection": "operator_confirmation_required",
            "active_run_scan_state": "skipped_pending_operator_confirmation",
            "active_run_scan_summary": "Rust auto-entry did not scan or create a run because intent confirmation is required before Way planning or normal entry.",
            "inspected_active_run_count": 0,
            "fresh_active_run_count": 0,
            "stale_active_run_count": 0,
            "entrypoint_used": Value::Null,
            "scoping_source": "recommendation_only",
            "run_decision_reason": "operator_confirmation_required",
            "next_action": recommendation.get("next_action").cloned().unwrap_or(Value::String("await_operator".to_string())),
            "operator_confirmation_required": true,
            "intent_confirmation": recommendation.get("intent_confirmation").cloned().unwrap_or(Value::Null),
            "summary": "Rust auto-entry returned a confirmation requirement without creating a run.",
            "entry_probe": entry_probe,
            "review_policy": recommendation.get("review_policy").cloned().unwrap_or(Value::Null),
            "completion_discipline": recommendation.get("completion_discipline").cloned().unwrap_or(Value::Null),
            "answer_trace": {
                "request_shape": recommendation.get("request_shape").cloned().unwrap_or(Value::Null),
                "mutation_intent": recommendation.get("mutation_intent").cloned().unwrap_or(Value::Null),
                "selected_role": "captain",
                "execution_path": "await_operator_confirmation",
                "budget_class": "confirmation_gate",
                "review_requirement": recommendation.pointer("/review_policy/decision").cloned().unwrap_or(Value::String("not_applicable".to_string())),
                "completion_mode": recommendation.pointer("/completion_discipline/completion_mode").cloned().unwrap_or(Value::Null),
            },
            "recommendation": recommendation,
            "server_identity": create_server_identity_payload(session_context),
        }));
    }

    let start_request = create_auto_entry_start_request(parsed, &recommendation);
    let start_payload = create_ccc_start_payload(&start_request)?;
    let locator = resolve_run_locator_arguments(
        &json!({
            "run_id": start_payload.get("run_id").cloned().unwrap_or(Value::Null),
            "cwd": start_payload.get("cwd").cloned().unwrap_or(Value::Null),
        }),
        "ccc_status",
    )?;
    let status_payload = create_ccc_status_payload(session_context, &locator)?;
    let request_shape = recommendation
        .get("request_shape")
        .and_then(Value::as_str)
        .unwrap_or("way");

    Ok(json!({
        "cwd": cwd.to_string_lossy(),
        "request": parsed.get("request").cloned().unwrap_or(Value::Null),
        "policy_mode": recommendation.get("policy_mode").cloned().unwrap_or(Value::Null),
        "auto_entry_opt_in": recommendation.get("auto_entry_opt_in").cloned().unwrap_or(Value::Bool(false)),
        "auto_entry_opt_in_source": recommendation.get("auto_entry_opt_in_source").cloned().unwrap_or(Value::String("default_false".to_string())),
        "policy_mode_supports_auto_entry": recommendation.get("policy_mode_supports_auto_entry").cloned().unwrap_or(Value::Bool(false)),
        "automatic_entry_supported": true,
        "entry_boundary": recommendation.get("entry_boundary").cloned().unwrap_or(Value::Null),
        "entry_boundary_summary": recommendation.get("entry_boundary_summary").cloned().unwrap_or(Value::Null),
        "upstream_codex_binary_intercept_supported": false,
        "created": true,
        "run_selection": start_payload.get("run_selection").cloned().unwrap_or(Value::String("new_run_created".to_string())),
        "active_run_scan_state": start_payload.pointer("/active_run_scan/active_run_scan_state").cloned().unwrap_or(Value::Null),
        "active_run_scan_summary": start_payload.pointer("/active_run_scan/active_run_scan_summary").cloned().unwrap_or(Value::Null),
        "inspected_active_run_count": start_payload.pointer("/active_run_scan/inspected_active_run_count").cloned().unwrap_or(Value::Number(0.into())),
        "fresh_active_run_count": start_payload.pointer("/active_run_scan/fresh_active_run_count").cloned().unwrap_or(Value::Number(0.into())),
        "stale_active_run_count": start_payload.pointer("/active_run_scan/stale_active_run_count").cloned().unwrap_or(Value::Number(0.into())),
        "active_run_scan": start_payload.get("active_run_scan").cloned().unwrap_or(Value::Null),
        "entrypoint_used": recommendation.get("recommended_entrypoint").cloned().unwrap_or(Value::String("way".to_string())),
        "scoping_source": "rust_deterministic_auto_entry",
        "run_id": start_payload.get("run_id").cloned().unwrap_or(Value::Null),
        "task_card_id": start_payload.get("task_card_id").cloned().unwrap_or(Value::Null),
        "run_directory": start_payload.get("run_directory").cloned().unwrap_or(Value::Null),
        "run_ref": start_payload.get("run_ref").cloned().unwrap_or(Value::Null),
        "status": status_payload.get("status").cloned().unwrap_or(Value::Null),
        "stage": status_payload.get("stage").cloned().unwrap_or(Value::Null),
        "next_step": start_payload.get("next_step").cloned().unwrap_or(Value::Null),
        "can_advance": start_payload.get("can_advance").cloned().unwrap_or(Value::Null),
        "allowed_next_commands": start_payload.get("allowed_next_commands").cloned().unwrap_or(Value::Null),
        "run_decision_reason": if start_payload.pointer("/active_run_scan/fresh_active_run_count").and_then(Value::as_u64).unwrap_or(0) > 0 { "fresh_run_created_with_active_prior_run_visibility" } else { "fresh_deterministic_rust_entry" },
        "summary": if start_payload.pointer("/active_run_scan/fresh_active_run_count").and_then(Value::as_u64).unwrap_or(0) > 0 { "Rust auto-entry created a fresh bounded run while surfacing active prior-run continuity guidance for captain merge/replan/reclaim handling." } else { "Rust auto-entry created a fresh bounded run on a deterministic captain-first path." },
        "entry_probe": entry_probe,
        "review_policy": status_payload.get("review_policy").cloned().unwrap_or_else(|| recommendation.get("review_policy").cloned().unwrap_or(Value::Null)),
        "completion_discipline": status_payload
            .get("current_task_card")
            .and_then(|value| value.get("completion_discipline"))
            .cloned()
            .unwrap_or_else(|| recommendation.get("completion_discipline").cloned().unwrap_or(Value::Null)),
        "answer_trace": {
            "request_shape": request_shape,
            "mutation_intent": recommendation.get("mutation_intent").cloned().unwrap_or(Value::Null),
            "selected_role": status_payload
                .get("current_task_card")
                .and_then(|value| value.get("assigned_agent_id"))
                .cloned()
                .or_else(|| status_payload.get("active_agent_id").cloned())
                .unwrap_or(Value::Null),
            "execution_path": "new_run",
            "budget_class": if request_shape == "mutation" { Value::String("implementation_budget".to_string()) } else { Value::String("way_budget".to_string()) },
            "review_requirement": recommendation.pointer("/review_policy/decision").cloned().unwrap_or_else(|| if request_shape == "review" { Value::String("required".to_string()) } else { Value::String("optional".to_string()) }),
            "completion_mode": recommendation.pointer("/completion_discipline/completion_mode").cloned().unwrap_or(Value::Null),
            "why_selected": "Rust auto-entry keeps the first move bounded and persisted instead of answering through captain-local fallback.",
            "why_not_local": "This request was routed into a persisted run instead of a no-run local answer.",
            "why_not_heavier_role": "Heavier reviewed paths wait until a bounded specialist result exists.",
        },
        "recommendation": recommendation,
        "current_task_card": status_payload.get("current_task_card").cloned().unwrap_or(Value::Null),
        "run_state": status_payload.get("run_state").cloned().unwrap_or(Value::Null),
        "server_identity": create_server_identity_payload(session_context),
    }))
}

pub(crate) fn create_ccc_auto_entry_payload(
    session_context: &SessionContext,
    parsed: &Value,
) -> io::Result<Value> {
    create_ccc_auto_entry_payload_for_policy(session_context, parsed, None)
}

pub(crate) fn create_ccc_auto_entry_text(payload: &Value) -> String {
    if payload.get("created").and_then(Value::as_bool) == Some(true) {
        format!(
            "Rust CCC auto-entry created run {} through {}",
            payload
                .get("run_id")
                .and_then(Value::as_str)
                .unwrap_or("unknown-run"),
            payload
                .get("entrypoint_used")
                .and_then(Value::as_str)
                .unwrap_or("way"),
        )
    } else {
        "Rust CCC auto-entry returned a recommendation without creating a run.".to_string()
    }
}