cflx 0.6.327

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

mod acceptance;
mod agent;
mod ai_command_runner;
mod analyzer;
mod archive_layout;
mod bounded_git;
mod embedded_skills;
mod install_skills;

mod cli;
mod client;
mod command_queue;
mod completion;
mod config;
mod dependency_targets;
mod error;
mod error_history;
mod events;
mod execution;
mod history;
mod hooks;
mod ids;
mod judge_command;
#[allow(dead_code, unused_imports)]
mod judge_evaluation;
mod lifecycle_integration;
mod log_viewer;
mod openspec;
mod openspec_cmd;
mod orchestration;
mod orchestrator;
mod parallel;
mod parallel_run_service;
mod permission;
mod process_manager;
#[allow(dead_code)]
mod repo_lock;
#[allow(dead_code, unused_imports)]
mod runtime;
mod shell_command;
mod spec_delta;
#[cfg(test)]
mod spec_test_annotations;
mod stall;
#[allow(dead_code)]
mod startup_preflight;
mod stream_json_textifier;
mod task_file;
mod task_parser;
mod templates;
mod tui;
#[allow(dead_code, unused_imports)]
mod upstream;
mod vcs;
#[cfg(feature = "web-monitoring")]
mod web;
mod worktree_ops;

#[cfg(test)]
mod test_support;

use clap::{CommandFactory, Parser};
use cli::{
    install_skills_legacy_error, Cli, Commands, InstallSkillsTarget, InternalCompleteCommands,
    LogsArgs, TuiArgs, VERSION_WITH_BUILD,
};
use config::OrchestratorConfig;
use error::Result;
use install_skills::{run_install_skills, InstallSkillsOptions};
use lifecycle_integration::{
    LifecycleContext, LifecycleEvent, LifecycleExecutionMode, LifecycleIntegration, LifecycleState,
};
use orchestrator::Orchestrator;
use parallel::PostArchiveAction;
use std::path::Path;
#[cfg(feature = "web-monitoring")]
use std::path::PathBuf;
use tracing::{error, info, Level};
use tracing_subscriber::{filter::LevelFilter, prelude::*};

fn tui_post_archive_action(args: &TuiArgs) -> PostArchiveAction {
    args.push
        .clone()
        .map(|remote| PostArchiveAction::PushToRemote { remote })
        .unwrap_or_default()
}

/// Privacy-safe lifecycle context identifying this cflx process.
///
/// Only the workspace root is reported; no environment, configuration, or
/// command content is ever included.
fn lifecycle_process_context() -> LifecycleContext {
    match std::env::current_dir() {
        Ok(dir) => LifecycleContext::workspace(dir.display().to_string()),
        Err(_) => LifecycleContext::default(),
    }
}

/// Validate and construct the local TUI's upstream runtime before any TUI or
/// orchestration state exists.
///
/// This is deliberately the same contract as `cflx run`: it resolves the option
/// through the shared frontend normalizer, then runs the same static and
/// initial-fetch validation.
///
/// The default-off path additionally refuses to start while repository evidence
/// proves an unpublished opted-in integration, which is the option-less restart
/// refusal. That scan is offline, so a disabled TUI gains no network access.
///
/// Failures are returned rather than exited on, because by the time this runs
/// the local API listeners are already bound: the caller has to give the socket
/// back before it terminates.
async fn resolve_tui_upstream_runtime(
    args: &TuiArgs,
) -> std::result::Result<Option<upstream::UpstreamRuntime>, String> {
    let upstream_config = args.upstream_integration().map_err(|err| err.to_string())?;

    // Git preflight already ran, so the workspace is a usable repository here.
    let git_dir_exists = true;

    let repo_root = match std::env::current_dir() {
        Ok(root) => root,
        Err(err) => {
            if upstream_config.is_some() {
                return Err(format!(
                    "upstream integration requires a readable workspace: {err}"
                ));
            }
            return Ok(None);
        }
    };

    match upstream_config {
        Some(upstream_config) => upstream::prepare_upstream_integration(
            upstream_config,
            &repo_root,
            args.push.clone(),
            git_dir_exists,
            false,
        )
        .await
        .map(Some)
        .map_err(|err| err.to_string()),
        None => {
            {
                if let Err(err) = upstream::ensure_no_unpushed_upstream_recovery(&repo_root).await {
                    if matches!(err, upstream::UpstreamStartupError::Invalid(_)) {
                        return Err(err.to_string());
                    }
                    tracing::debug!("Upstream recovery scan unavailable, continuing: {}", err);
                }
            }
            Ok(None)
        }
    }
}

async fn launch_tui(args: TuiArgs) -> Result<()> {
    let post_archive_action = tui_post_archive_action(&args);

    // Configuration decides where persistent logs live, so it is loaded and its
    // storage root proven usable before logging initialization. A configuration
    // or path failure is therefore a stderr diagnostic rather than a line in a
    // log file this process may not be allowed to open — and it happens before
    // any listener, lifecycle adapter, or AI child process exists.
    let config = OrchestratorConfig::load(args.config.as_deref())?;
    ensure_state_root_ready(&config);

    init_logging(false, config.get_state_base_dir())?;
    log_startup("tui");

    tui::log_deduplicator::configure_logging(config.get_logging());

    // Listing changes is a local read of the workspace; it starts nothing and
    // reaches no network, so it may precede the listeners it feeds.
    let changes = openspec::list_changes_native()?;

    // The local API is a startup contract, so every requested listener binds
    // before upstream validation, the lifecycle adapter, any AI subprocess, or
    // the TUI itself. A process that cannot serve its API must fail here, while
    // it still has nothing to clean up — in particular before the initial
    // upstream fetch, which is the first startup step that touches a remote and
    // updates local refs.
    #[cfg(feature = "web-monitoring")]
    let started = start_local_api(LocalApiOptions::from(&args), &changes).await;

    // Repository usability and main-worktree eligibility were both settled by
    // the shared owner preflight, before the lock, this process's logging, and
    // the listeners above. What remains here is the upstream contract.
    let startup: std::result::Result<Option<upstream::UpstreamRuntime>, String> =
        resolve_tui_upstream_runtime(&args).await;

    // Startup validation runs before the terminal is taken over, so a rejected
    // invocation reports plainly and leaves no orchestration state behind. The
    // listeners are already bound here, so a refusal gives the socket back on
    // its way out instead of leaving a stale entry.
    let upstream_runtime = match startup {
        Ok(runtime) => runtime,
        Err(err) => {
            eprintln!("Error: {err}");
            #[cfg(feature = "web-monitoring")]
            if let Some((handle, _)) = started {
                handle.shutdown().await;
            }
            std::process::exit(1);
        }
    };

    #[cfg(feature = "web-monitoring")]
    let (web_url, web_state_opt) = match &started {
        Some((handle, state)) => (handle.tcp_url().map(str::to_string), Some(state.clone())),
        None => (None, None),
    };

    // Startup has now resolved both publication options, so the contract a
    // client verifies completion against is a fact rather than a guess.
    #[cfg(feature = "web-monitoring")]
    if let Some(state) = &web_state_opt {
        publish_execution_contract(
            state,
            args.push.as_deref(),
            upstream_runtime
                .as_ref()
                .map(|runtime| runtime.config.remote.as_str()),
        )
        .await;
    }

    #[cfg(not(feature = "web-monitoring"))]
    let web_url: Option<String> = {
        if args.web {
            eprintln!(
                "Warning: Web monitoring is not enabled. Compile with --features web-monitoring"
            );
        }
        None
    };

    // Start the optional external lifecycle adapter before the interactive TUI
    // is presented. Failures here are observability-only and never block startup.
    let lifecycle = LifecycleIntegration::start(
        config.get_lifecycle_integration(),
        LifecycleExecutionMode::Tui,
    );
    lifecycle.handle().publish(LifecycleEvent::ProcessStarted {
        context: lifecycle_process_context(),
    });

    let result = tui::run_tui(
        changes,
        config,
        web_url,
        #[cfg(feature = "web-monitoring")]
        web_state_opt,
        post_archive_action,
        upstream_runtime,
        lifecycle.handle(),
    )
    .await;

    lifecycle.shutdown().await;

    // Graceful termination stops the listeners and gives the socket path back
    // without waiting for another signal.
    #[cfg(feature = "web-monitoring")]
    if let Some((handle, _)) = started {
        handle.shutdown().await;
    }

    result
}

/// Publish the minimal execution contract a client needs to verify completion.
///
/// This is what turns `cflx client wait` from a guess into a proof: it names the
/// base branch this owner integrates into and *how* a change reaches its
/// terminal success, so a waiter knows which repository evidence would count.
/// It is observational only — nothing in this process reads it back to decide a
/// workflow action, and it holds no per-change or durable state.
///
/// Published after option validation and before orchestration, so a client that
/// connects during startup sees either no contract or the real one, never a
/// guessed base branch.
#[cfg(feature = "web-monitoring")]
async fn publish_execution_contract(
    state: &web::WebState,
    push_remote: Option<&str>,
    upstream_remote: Option<&str>,
) {
    let Ok(repo_root) = std::env::current_dir() else {
        return;
    };
    // A detached HEAD has no base-branch identity to publish, and inventing one
    // would let a client verify completion against a branch this owner never
    // integrates into. Publishing nothing makes `wait` say so.
    let Ok(Some(base_branch)) = vcs::git::commands::get_current_branch(&repo_root).await else {
        return;
    };
    state.set_execution_contract(
        web::remote_control_api::dto::OwnerExecutionContract::resolve(
            base_branch,
            push_remote,
            upstream_remote,
        ),
    );
}

/// Resolve which listeners this local orchestration invocation must start.
///
/// Repository identity comes from the same canonical Git common directory the
/// repository lock uses, so linked worktrees agree on one socket and no new
/// out-of-worktree routing state is introduced.
#[cfg(feature = "web-monitoring")]
fn resolve_listener_plan(
    tcp: bool,
    unix_socket: Option<&Path>,
    no_unix_socket: bool,
) -> std::result::Result<web::ListenerPlan, String> {
    #[cfg(unix)]
    {
        let workspace = std::env::current_dir()
            .map_err(|e| format!("failed to resolve the current directory: {e}"))?;
        let common_dir = repo_lock::discover_common_dir(&workspace);
        let selection = web::unix_socket::resolve_unix_socket(
            unix_socket,
            no_unix_socket,
            common_dir.as_deref(),
        )?;
        Ok(web::ListenerPlan {
            unix_socket: selection.path().map(Path::to_path_buf),
            tcp,
        })
    }
    // Unix-domain sockets are the only default local API surface, so a
    // non-Unix build keeps exactly the retained `--web` behavior.
    #[cfg(not(unix))]
    {
        let _ = (unix_socket, no_unix_socket);
        Ok(web::ListenerPlan { tcp })
    }
}

/// The listener-selecting options every local orchestration entrypoint carries.
///
/// `cflx`, `cflx tui`, and `cflx run` parse their own copies of these flags, so
/// collecting them here is what keeps the three entrypoints one contract rather
/// than three that happen to agree today.
#[cfg(feature = "web-monitoring")]
struct LocalApiOptions {
    tcp: bool,
    port: u16,
    bind: String,
    auth_token: Option<String>,
    auth_token_env: Option<String>,
    allowed_origins: Vec<String>,
    unix_socket: Option<PathBuf>,
    no_unix_socket: bool,
}

#[cfg(feature = "web-monitoring")]
impl From<&TuiArgs> for LocalApiOptions {
    fn from(args: &TuiArgs) -> Self {
        Self {
            tcp: args.web,
            port: args.web_port,
            bind: args.web_bind.clone(),
            auth_token: args.web_auth_token.clone(),
            auth_token_env: args.web_auth_token_env.clone(),
            allowed_origins: args.web_allowed_origins.clone(),
            unix_socket: args.web_unix_socket.clone(),
            no_unix_socket: args.no_web_unix_socket,
        }
    }
}

#[cfg(feature = "web-monitoring")]
impl From<&cli::RunArgs> for LocalApiOptions {
    fn from(args: &cli::RunArgs) -> Self {
        Self {
            tcp: args.web,
            port: args.web_port,
            bind: args.web_bind.clone(),
            auth_token: args.web_auth_token.clone(),
            auth_token_env: args.web_auth_token_env.clone(),
            allowed_origins: args.web_allowed_origins.clone(),
            unix_socket: args.web_unix_socket.clone(),
            no_unix_socket: args.no_web_unix_socket,
        }
    }
}

/// Bind every requested listener, or exit non-zero without side effects.
///
/// Returns `None` only when the operator opted out of every listener. Any other
/// failure — an unsafe TCP configuration, a non-Git default path, an occupied
/// socket path, a bind or permission error — is a hard startup error, because a
/// process that advertised an endpoint it never bound is worse than one that
/// refused to start.
#[cfg(feature = "web-monitoring")]
async fn start_local_api(
    options: LocalApiOptions,
    changes: &[openspec::Change],
) -> Option<(web::ServerHandle, std::sync::Arc<web::WebState>)> {
    let plan = match resolve_listener_plan(
        options.tcp,
        options.unix_socket.as_deref(),
        options.no_unix_socket,
    ) {
        Ok(plan) => plan,
        Err(error) => {
            eprintln!("Error: {error}");
            std::process::exit(1);
        }
    };
    if plan.is_empty() {
        return None;
    }

    let config = web::WebConfig::enabled(options.port, options.bind)
        .with_tcp_enabled(options.tcp)
        .with_auth(
            options.auth_token,
            options.auth_token_env,
            options.allowed_origins,
        );
    let state = std::sync::Arc::new(web::WebState::new(changes));

    match web::start_listeners(config, plan, state.clone()).await {
        Ok(handle) => {
            // Only bound endpoints reach this list, so what an operator reads
            // here is always something a client can actually connect to.
            for endpoint in handle.endpoints() {
                info!("Local API available at: {}", endpoint);
            }
            Some((handle, state))
        }
        Err(error) => {
            eprintln!("Error: {error}");
            std::process::exit(1);
        }
    }
}

/// Prove a configured Conflux state root is usable before anything writes to it.
///
/// Runs before logging initialization, listeners, lifecycle adapters, and AI
/// child processes, so a relative, unavailable, uncreatable, or unwritable root
/// stops startup with an actionable diagnostic instead of silently falling back
/// to the internal disk.
fn ensure_state_root_ready(config: &OrchestratorConfig) {
    if let Err(err) = config::defaults::ensure_state_root_usable(config.get_state_base_dir()) {
        eprintln!("Error: {err}");
        std::process::exit(1);
    }
}

/// Initialize logging.
///
/// - Always enables file logging with automatic log rotation and cleanup.
/// - Optionally enables stdout logging (for non-TUI modes).
///
/// Logs are written to `<state root>/logs/<project_slug>/<YYYY-MM-DD>.log`, where
/// the state root is `state_base_dir` when configured, else `XDG_STATE_HOME`,
/// else the platform default. Old logs are automatically cleaned up (7-day
/// retention) from that same resolved root.
fn init_logging(enable_stdout: bool, state_base_dir: Option<&str>) -> Result<()> {
    use config::defaults::{cleanup_old_logs, get_log_file_path};
    use std::fs::{create_dir_all, File};
    use tracing_subscriber::fmt::writer::MakeWriterExt;

    // Get current directory as repo root
    let repo_root = std::env::current_dir().ok();

    // Get log file path
    let log_path = get_log_file_path(state_base_dir, repo_root.as_deref())
        .map_err(|e| error::OrchestratorError::Io(std::io::Error::other(e.to_string())))?;

    // Create parent directory if it doesn't exist
    if let Some(parent) = log_path.parent() {
        create_dir_all(parent).map_err(|e| {
            error::OrchestratorError::Io(std::io::Error::other(format!(
                "Failed to create log directory '{}': {}",
                parent.display(),
                e
            )))
        })?;
    }

    // Clean up old logs (7-day retention)
    if let Err(e) = cleanup_old_logs(state_base_dir, repo_root.as_deref(), 7) {
        tracing::warn!("Failed to clean up old logs: {}", e);
    }

    // Create or append to log file
    let file = File::options()
        .create(true)
        .append(true)
        .open(&log_path)
        .map_err(|e| {
            error::OrchestratorError::Io(std::io::Error::other(format!(
                "Failed to open log file '{}': {}",
                log_path.display(),
                e
            )))
        })?;

    let file_layer = tracing_subscriber::fmt::layer()
        .with_writer(file.with_max_level(Level::DEBUG))
        .with_ansi(false)
        .with_target(true)
        .with_thread_ids(false)
        .with_file(true)
        .with_line_number(true);

    let registry = tracing_subscriber::registry().with(file_layer);

    if enable_stdout {
        let stdout_layer = tracing_subscriber::fmt::layer()
            .with_writer(std::io::stdout)
            .with_ansi(true)
            .with_target(false)
            .with_thread_ids(false)
            .with_file(false)
            .with_line_number(false)
            .with_filter(LevelFilter::INFO);

        registry.with(stdout_layer).init();
    } else {
        registry.init();
    }

    Ok(())
}

fn log_startup(mode: &str) {
    info!("Starting cflx {} mode={}.", VERSION_WITH_BUILD, mode);
}

/// Classify the parsed CLI invocation for repository-lock purposes.
fn repository_lock_invocation(cli: &Cli) -> repo_lock::InvocationKind {
    match &cli.command {
        None => repo_lock::InvocationKind::DefaultTui,
        Some(Commands::Tui(_)) => repo_lock::InvocationKind::Tui,
        Some(Commands::Run(_)) => repo_lock::InvocationKind::Run,
        _ => repo_lock::InvocationKind::Other,
    }
}

/// Refuse an orchestration-owning invocation whose workspace cannot own
/// orchestration, before any observable side effect.
///
/// This is the whole startup boundary for owner entrypoints: a usable Git
/// repository, the `git` command, and the repository's *main* worktree. It runs
/// before the repository lock — so a linked worktree is answered with its own
/// diagnostic rather than being reported as a lock conflict with whichever owner
/// happens to be running — and therefore before logging initialization, listener
/// binding, lifecycle adapters, AI subprocesses, hooks, and workspace mutation.
/// Non-owner commands, `cflx client` included, bypass it entirely.
fn enforce_owner_startup_preflight(cli: &Cli) {
    let kind = repository_lock_invocation(cli);
    if let Some(message) = startup_preflight::owner_startup_error(kind) {
        eprintln!("Error: {message}");
        std::process::exit(1);
    }
}

/// Take the repository orchestration lock before any startup side effect.
///
/// Runs before logging adapters, listeners, AI subprocesses, and orchestration
/// so a rejected invocation leaves the repository and the existing owner
/// completely untouched. The acquired lock is retained for the process
/// lifetime; the OS releases it when the process exits, normally or not.
fn acquire_repository_lock(cli: &Cli) {
    let kind = repository_lock_invocation(cli);
    let mode = match repo_lock::classify_invocation(kind) {
        repo_lock::LockDecision::Bypass => return,
        repo_lock::LockDecision::Acquire(mode) => mode,
    };

    let Ok(workspace) = std::env::current_dir() else {
        return;
    };

    match repo_lock::acquire(&workspace, mode) {
        // No Git repository here, so there is no repository identity to guard.
        Ok(None) => {}
        Ok(Some(lock)) => repo_lock::install(lock),
        Err(err @ repo_lock::LockError::Conflict(_)) => {
            eprintln!("{err}");
            std::process::exit(1);
        }
        // An unusable lock file proves no conflict, so refusing to start would
        // be a worse failure than continuing without exclusion.
        Err(err) => {
            eprintln!("Warning: repository lock unavailable, continuing: {err}");
        }
    }
}

fn run_completion_subcommand(args: cli::CompletionArgs) {
    let shell = clap_complete::Shell::from(args.shell);
    let mut command = Cli::command();
    let mut stdout = std::io::stdout();
    clap_complete::generate(shell, &mut command, "cflx", &mut stdout);
    print_dynamic_completion_hooks(args.shell);
}

fn print_dynamic_completion_hooks(shell: cli::CompletionShell) {
    match shell {
        cli::CompletionShell::Bash => print!("{}", BASH_DYNAMIC_COMPLETION_HOOK),
        cli::CompletionShell::Zsh => print!("{}", ZSH_DYNAMIC_COMPLETION_HOOK),
        cli::CompletionShell::Fish => print!("{}", FISH_DYNAMIC_COMPLETION_HOOK),
        cli::CompletionShell::PowerShell => print!("{}", POWERSHELL_DYNAMIC_COMPLETION_HOOK),
    }
}

fn run_internal_complete_subcommand(args: cli::InternalCompleteArgs) {
    match args.command {
        InternalCompleteCommands::ChangeIds(change_args) => {
            let scope = completion::ChangeIdCandidateScope::from_flags(
                change_args.active,
                change_args.archived,
            );
            let cwd = match std::env::current_dir() {
                Ok(cwd) => cwd,
                Err(_) => return,
            };
            for candidate in completion::discover_change_id_candidates(
                &cwd,
                scope,
                change_args.prefix.as_deref(),
            ) {
                println!("{candidate}");
            }
        }
    }
}

const BASH_DYNAMIC_COMPLETION_HOOK: &str = r#"

# cflx dynamic OpenSpec change-id completion hook
_cflx_static_completion() {
    _cflx "$@"
}
_cflx_dynamic_change_ids() {
    local scope="$1"
    local prefix="$2"
    local -a cmd=(cflx __complete change-ids --prefix "$prefix")
    case "$scope" in
        active) cmd+=(--active) ;;
        all) cmd+=(--active --archived) ;;
    esac
    mapfile -t COMPREPLY < <("${cmd[@]}" 2>/dev/null)
}
_cflx_dynamic_run_change_ids() {
    local current="${COMP_WORDS[COMP_CWORD]}"
    local prefix="${current##*,}"
    local before="${current%,*}"
    _cflx_dynamic_change_ids active "$prefix"
    if [[ "$before" != "$current" ]]; then
        local i
        for i in "${!COMPREPLY[@]}"; do COMPREPLY[$i]="$before,${COMPREPLY[$i]}"; done
    fi
}
_cflx_dynamic_completion() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local prev="${COMP_WORDS[COMP_CWORD-1]}"
    if [[ "$prev" == "--change" ]]; then
        _cflx_dynamic_run_change_ids
        return
    fi
    if [[ ${COMP_CWORD} -ge 3 && "${COMP_WORDS[1]}" == "openspec" ]]; then
        case "${COMP_WORDS[2]}" in
            show)
                if [[ "$cur" != -* ]]; then
                    _cflx_dynamic_change_ids all "$cur"
                    return
                fi
                ;;
            validate|archive)
                if [[ "$cur" != -* ]]; then
                    _cflx_dynamic_change_ids active "$cur"
                    return
                fi
                ;;
        esac
    fi
    _cflx_static_completion "$@"
}
complete -F _cflx_dynamic_completion -o bashdefault -o default cflx
# Surfaces: cflx run --change -> _cflx_dynamic_run_change_ids; cflx openspec show -> active+archived;
# cflx openspec validate/archive -> active. Candidate command: cflx __complete change-ids
"#;

const ZSH_DYNAMIC_COMPLETION_HOOK: &str = r#"

# cflx dynamic OpenSpec change-id completion hook
_cflx_static_completion() {
    _cflx "$@"
}
_cflx_dynamic_change_ids() {
    local scope="$1"
    local prefix="$2"
    local -a cmd=(cflx __complete change-ids --prefix "$prefix")
    case "$scope" in
        active) cmd+=(--active) ;;
        all) cmd+=(--active --archived) ;;
    esac
    compadd -- "${(@f)$(${cmd[@]} 2>/dev/null)}"
}
_cflx_dynamic_run_change_ids() {
    local current="${words[CURRENT]}"
    local prefix="${current##*,}"
    local before="${current%,*}"
    local -a candidates
    candidates=("${(@f)$(cflx __complete change-ids --active --prefix "$prefix" 2>/dev/null)}")
    if [[ "$before" != "$current" ]]; then
        candidates=("${(@)^candidates/#/$before,}")
    fi
    compadd -- "${candidates[@]}"
}
_cflx_dynamic_completion() {
    if [[ "${words[CURRENT-1]}" == "--change" ]]; then
        _cflx_dynamic_run_change_ids
        return
    fi
    if [[ ${CURRENT} -ge 4 && "${words[2]}" == "openspec" ]]; then
        case "${words[3]}" in
            show)
                [[ "${words[CURRENT]}" == -* ]] || { _cflx_dynamic_change_ids all "${words[CURRENT]}"; return; }
                ;;
            validate|archive)
                [[ "${words[CURRENT]}" == -* ]] || { _cflx_dynamic_change_ids active "${words[CURRENT]}"; return; }
                ;;
        esac
    fi
    _cflx_static_completion "$@"
}
compdef _cflx_dynamic_completion cflx
# Surfaces: cflx run --change -> _cflx_dynamic_run_change_ids; cflx openspec show -> active+archived;
# cflx openspec validate/archive -> active. Candidate command: cflx __complete change-ids
"#;

const FISH_DYNAMIC_COMPLETION_HOOK: &str = r#"

# cflx dynamic OpenSpec change-id completion hook
function __cflx_dynamic_change_ids
    set -l scope $argv[1]
    set -l prefix $argv[2]
    set -l cmd cflx __complete change-ids --prefix "$prefix"
    switch $scope
        case active
            set cmd $cmd --active
        case all
            set cmd $cmd --active --archived
    end
    $cmd 2>/dev/null
end
complete -c cflx -n '__fish_seen_subcommand_from run; and __fish_seen_argument --change' -a '(__cflx_dynamic_change_ids active (string split -r -m1 , (commandline -ct))[-1])'
complete -c cflx -n '__fish_seen_subcommand_from openspec; and __fish_seen_subcommand_from show' -a '(__cflx_dynamic_change_ids all (commandline -ct))'
complete -c cflx -n '__fish_seen_subcommand_from openspec; and __fish_seen_subcommand_from validate archive' -a '(__cflx_dynamic_change_ids active (commandline -ct))'
"#;

const POWERSHELL_DYNAMIC_COMPLETION_HOOK: &str = r#"

# cflx dynamic OpenSpec change-id completion hook
function __CflxDynamicChangeIds($Scope, $Prefix) {
    $args = @('__complete', 'change-ids', '--prefix', $Prefix)
    if ($Scope -eq 'active') { $args += '--active' }
    if ($Scope -eq 'all') { $args += @('--active', '--archived') }
    & cflx @args 2>$null
}
function __CflxDynamicRunChangeIds($WordToComplete) {
    $prefix = $WordToComplete -replace '^.*,', ''
    $before = $WordToComplete -replace ',?[^,]*$', ''
    foreach ($candidate in (__CflxDynamicChangeIds active $prefix)) {
        if ($before) { "$before,$candidate" } else { $candidate }
    }
}
Register-ArgumentCompleter -Native -CommandName 'cflx' -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)
    $elements = @($commandAst.CommandElements | ForEach-Object { $_.Extent.Text })
    $commandText = $elements -join ' '
    if ($commandText -match '^cflx\s+run\b' -and ($elements -contains '--change')) {
        __CflxDynamicRunChangeIds $wordToComplete | ForEach-Object {
            [CompletionResult]::new($_, $_, [CompletionResultType]::ParameterValue, 'OpenSpec active change ID')
        }
        return
    }
    if ($commandText -match '^cflx\s+openspec\s+show\b' -and $wordToComplete -notlike '-*') {
        __CflxDynamicChangeIds all $wordToComplete | ForEach-Object {
            [CompletionResult]::new($_, $_, [CompletionResultType]::ParameterValue, 'OpenSpec change ID')
        }
        return
    }
    if ($commandText -match '^cflx\s+openspec\s+(validate|archive)\b' -and $wordToComplete -notlike '-*') {
        __CflxDynamicChangeIds active $wordToComplete | ForEach-Object {
            [CompletionResult]::new($_, $_, [CompletionResultType]::ParameterValue, 'OpenSpec active change ID')
        }
        return
    }
}
# Surfaces: cflx run --change -> active comma-token candidates; cflx openspec show -> active+archived;
# cflx openspec validate/archive -> active. Candidate command: cflx __complete change-ids
"#;

/// Write the generated `/api/v2` OpenAPI document to stdout and nothing else.
///
/// The bytes come from the same function that serves `GET /api/v2/openapi.yaml`,
/// so `cflx openapi > openapi.yaml` and the live endpoint cannot disagree. A
/// build without the feature that declares the contract has no complete document
/// to emit, so it refuses instead of writing a partial one: a truncated schema
/// would be believed by a generated client.
fn run_openapi_subcommand() {
    #[cfg(feature = "web-monitoring")]
    {
        use std::io::Write;

        let document = web::openapi::document_yaml();
        let mut stdout = std::io::stdout();
        // A closed or full stdout must fail loudly rather than silently emit a
        // truncated document that still looks like a schema.
        if let Err(e) = stdout
            .write_all(document.as_bytes())
            .and_then(|()| stdout.flush())
        {
            eprintln!("Error: failed to write the OpenAPI document to stdout: {e}");
            std::process::exit(1);
        }
    }

    #[cfg(not(feature = "web-monitoring"))]
    {
        eprintln!(
            "Error: OpenAPI support is unavailable in this build. \
             Rebuild with `--features web-monitoring` to export the /api/v2 schema."
        );
        std::process::exit(1);
    }
}

fn run_logs_subcommand(args: LogsArgs, custom_config_path: Option<&Path>) {
    // Viewing logs starts nothing, so configuration is read only for the storage
    // root and required commands are deliberately not validated here. Resolving
    // the same root the writers use is what keeps `cflx logs` pointed at the
    // directory this installation actually writes to — which means the viewer has
    // to merge the *same* sources the writers merged, custom `--config` file
    // included. Dropping it here would silently point the reader at a root the
    // writers abandoned.
    let state_base_dir = match OrchestratorConfig::load_storage_settings(custom_config_path) {
        Ok(config) => config.get_state_base_dir().map(str::to_string),
        Err(e) => {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    };

    let options = log_viewer::LogViewerOptions {
        print_path: args.path,
        last: args.last,
        follow: args.follow,
        today: args.today,
        project: args.project,
        repo_root: std::env::current_dir().ok(),
        state_base_dir,
    };

    if let Err(e) = log_viewer::run_logs_command(&options, &mut std::io::stdout()) {
        eprintln!("Error: {e}");
        std::process::exit(1);
    }
}

/// Run `cflx judge-eval`, which reads the dedicated evaluation store and
/// nothing else.
///
/// Like `cflx logs`, only *storage* settings are loaded: required agent
/// commands are not validated, because summarizing records starts no agent. The
/// same `--config` the writers merged has to be merged here too — otherwise the
/// reader would point at a state root this installation abandoned.
fn run_judge_eval_subcommand(args: cli::JudgeEvalArgs, custom_config_path: Option<&Path>) {
    use cli::JudgeEvalCommands;

    let config = match OrchestratorConfig::load_storage_settings(custom_config_path) {
        Ok(config) => config,
        Err(e) => {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    };

    match args.command {
        JudgeEvalCommands::Summary(summary_args) => {
            // `--purpose` is a closed enum whose only member is the purpose
            // this store records, so parsing already settled which root to
            // read; it is carried into output rather than re-decided here.
            let command = match judge_evaluation::SummaryCommand::resolve(
                &config,
                summary_args.purpose.as_str(),
                summary_args.since_days,
                summary_args.project,
                summary_args.json,
            ) {
                Ok(command) => command,
                Err(e) => {
                    eprintln!("Error: {e}");
                    std::process::exit(1);
                }
            };

            let code = command.run(&mut std::io::stdout());
            if code != 0 {
                std::process::exit(code);
            }
        }
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    // `try_parse` rather than `parse`, so a rejected invocation is answered here
    // instead of inside Clap's own exit. `cflx client ... --json` promises one
    // versioned envelope on stdout for *every* outcome, and a parse failure is
    // an outcome; every other invocation keeps Clap's human diagnostics.
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(error) => client::exit_on_parse_error(error),
    };

    // Top-level upstream options only reach the bare local TUI. An explicit
    // subcommand parses its own copies, so accepting them here would silently
    // drop an opt-in whose publication is part of the success contract. This is
    // a pure usage check, so rejecting here still leaves the repository and any
    // existing lock owner untouched.
    if let Err(error) = cli.validate_upstream_option_placement() {
        eprintln!("Error: {error}");
        std::process::exit(2);
    }

    // Workspace eligibility is decided first: a repository that cannot be
    // orchestrated, or a linked worktree that may not own orchestration, is
    // refused before this process contends for the repository lock.
    enforce_owner_startup_preflight(&cli);

    // Repository exclusion is decided before anything observable happens.
    acquire_repository_lock(&cli);

    match cli.command {
        // Completion commands intentionally run before logging/config/orchestration paths.
        Some(Commands::Completion(args)) => {
            run_completion_subcommand(args);
        }

        // Hidden candidate command intentionally runs before logging/config/orchestration paths.
        Some(Commands::Complete(args)) => {
            run_internal_complete_subcommand(args);
        }

        // Schema export is a pure read of a compiled-in document, so it runs
        // before logging/config/orchestration and never needs a repository.
        Some(Commands::Openapi) => {
            run_openapi_subcommand();
        }

        // A client of an existing owner, so it runs before logging, config
        // loading, lifecycle adapters, and orchestration — none of which a
        // client is allowed to start. The repository lock was already bypassed
        // for this invocation kind, so nothing here can contend with the owner
        // it is about to talk to.
        Some(Commands::Client(args)) => {
            std::process::exit(client::run(args).await);
        }

        // No subcommand: launch TUI (default behavior)
        None => {
            launch_tui(TuiArgs {
                config: cli.config,
                web: cli.web,
                web_port: cli.web_port,
                web_bind: cli.web_bind,
                web_auth_token: cli.web_auth_token,
                web_auth_token_env: cli.web_auth_token_env,
                web_allowed_origins: cli.web_allowed_origins,
                web_unix_socket: cli.web_unix_socket,
                no_web_unix_socket: cli.no_web_unix_socket,
                push: cli.push,
                // Bare local TUI carries the same upstream contract as `cflx tui`.
                integrate_upstream: cli.integrate_upstream,
                integrate_upstream_default_remote: cli.integrate_upstream_default_remote,
                upstream_verify_command: cli.upstream_verify_command,
            })
            .await?;
        }

        // TUI subcommand: launch interactive TUI dashboard
        Some(Commands::Tui(tui_args)) => launch_tui(tui_args).await?,

        // Run subcommand: non-interactive orchestration
        Some(Commands::Run(args)) => {
            // Configuration selects the persistent state root, so it is loaded
            // and validated before logging initialization — and therefore before
            // the local API listener, the lifecycle adapter, and every AI child
            // process. A configuration-load failure stays a stderr diagnostic.
            let config = OrchestratorConfig::load(args.config.as_deref())?;
            ensure_state_root_ready(&config);

            // Initialize logging: include stdout for run mode
            init_logging(true, config.get_state_base_dir())?;
            log_startup("run");

            // The local API binds before the lifecycle adapter, any AI
            // subprocess, and orchestration, so a run that cannot serve its
            // required endpoint exits without having started any work.
            #[cfg(feature = "web-monitoring")]
            let started_api = {
                let initial_changes = openspec::list_changes_native()?;
                start_local_api(LocalApiOptions::from(&args), &initial_changes).await
            };
            #[cfg(feature = "web-monitoring")]
            let web_state_arc = started_api.as_ref().map(|(_, state)| state.clone());

            // Run mode owns no `EventDispatcher`: the orchestrator forwards its
            // typed events straight into `WebState::apply_execution_event`.
            // Binding the one process-local facts store here is what makes that
            // forwarder feed `/api/v2/execution-status`, which serves on the
            // default Unix socket in this mode too. Without it the resource
            // would answer "nothing is running" with full authority while
            // lifecycle work is in flight — the exact misreading an agent is
            // told to trust this resource to prevent.
            //
            // One store for the whole process, created before orchestration and
            // outside the restart loop, so a restarted run keeps reading the
            // same observability output the socket already advertises. It stays
            // observability-only: nothing here decides a workflow action.
            #[cfg(feature = "web-monitoring")]
            if let Some(web_state) = web_state_arc.as_ref() {
                web_state
                    .set_execution_facts(std::sync::Arc::new(
                        orchestration::execution_facts::ExecutionFactsStore::new(),
                    ))
                    .await;
                // A run binds no command executor, so a client can only observe
                // it — but observing truthfully still needs to know which
                // repository evidence would prove a change finished.
                publish_execution_contract(
                    web_state,
                    args.push.as_deref(),
                    args.upstream_integration()
                        .ok()
                        .flatten()
                        .as_ref()
                        .map(|config| config.remote.as_str()),
                )
                .await;
            }

            #[cfg(not(feature = "web-monitoring"))]
            if args.web {
                eprintln!(
                    "Warning: Web monitoring is not enabled. Compile with --features web-monitoring"
                );
            }

            // Parse VCS backend from CLI option
            let vcs_override = match args.vcs.parse::<vcs::VcsBackend>() {
                Ok(backend) => Some(backend),
                Err(err) => {
                    eprintln!("Error: {}", err);
                    std::process::exit(1);
                }
            };

            // Worktree orchestration is the only execution model, and a linked
            // worktree may not own it. Both facts were settled by the shared
            // owner preflight before the repository lock, this process's
            // logging, and the listeners above, so nothing here re-checks them.

            // Opt-in upstream integration. When the option is absent no upstream
            // object is constructed, so the existing execution path performs no
            // additional fetch, merge, verification, event, or push.
            let upstream_integration = match args.upstream_integration() {
                Ok(config) => config,
                Err(err) => {
                    eprintln!("Error: {}", err);
                    std::process::exit(1);
                }
            };

            let upstream_runtime = match upstream_integration {
                Some(config) => {
                    let repo_root = std::env::current_dir()?;
                    match upstream::prepare_upstream_integration(
                        config,
                        &repo_root,
                        args.push.clone(),
                        true,
                        args.dry_run,
                    )
                    .await
                    {
                        Ok(runtime) => Some(runtime),
                        Err(err) => {
                            eprintln!("Error: {}", err);
                            std::process::exit(1);
                        }
                    }
                }
                None => {
                    // Default-off path: refuse to continue only when repository
                    // evidence proves an unpushed upstream merge is reachable.
                    // The scan is offline, so nothing new is fetched here.
                    if !args.dry_run {
                        let repo_root = std::env::current_dir()?;
                        if let Err(err) =
                            upstream::ensure_no_unpushed_upstream_recovery(&repo_root).await
                        {
                            if matches!(err, upstream::UpstreamStartupError::Invalid(_)) {
                                eprintln!("Error: {}", err);
                                std::process::exit(1);
                            }
                            tracing::debug!(
                                "Upstream recovery scan unavailable, continuing: {}",
                                err
                            );
                        }
                    }
                    None
                }
            };

            // Non-interactive run reports process and orchestration lifecycle
            // through the same observability-only contract as the TUI. Started
            // after startup validation so a rejected invocation never leaves an
            // adapter process behind.
            let lifecycle = LifecycleIntegration::start(
                config.get_lifecycle_integration(),
                LifecycleExecutionMode::Run,
            );
            let lifecycle_handle = lifecycle.handle();
            let workspace_context = lifecycle_process_context().workspace;
            lifecycle_handle.publish(LifecycleEvent::ProcessStarted {
                context: lifecycle_process_context(),
            });

            // Run mode control state for web control integration
            // Run mode now supports retry and resume via outer loop.
            use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
            use std::sync::Arc;

            // Control state: 0 = Stopped, 1 = Running, 2 = Stopping
            let run_state = Arc::new(AtomicU8::new(1)); // Start in Running state
            let graceful_stop_flag = Arc::new(AtomicBool::new(false));
            let force_stop_flag = Arc::new(AtomicBool::new(false));
            let restart_requested = Arc::new(AtomicBool::new(false));

            // `cflx run --web` has no control bridge: `/api/v2` executes every
            // lifecycle command through the shared run-control service instead of
            // enqueueing it onto a process-local channel, so there is nothing left
            // for a bridge task to receive.

            // Signal handler flags (shared across all iterations)
            let signal_stop = Arc::new(AtomicBool::new(false));

            // Spawn signal handler tasks
            #[cfg(unix)]
            {
                let signal_stop_sigterm = signal_stop.clone();
                tokio::spawn(async move {
                    let mut sigterm =
                        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                            .expect("Failed to install SIGTERM handler");
                    sigterm.recv().await;
                    info!("Received SIGTERM, shutting down gracefully...");
                    signal_stop_sigterm.store(true, Ordering::SeqCst);
                });
            }

            {
                let signal_stop_sigint = signal_stop.clone();
                tokio::spawn(async move {
                    let _ = tokio::signal::ctrl_c().await;
                    info!("Received SIGINT (Ctrl+C), shutting down gracefully...");
                    signal_stop_sigint.store(true, Ordering::SeqCst);
                });
            }

            // Clone normalized targets for use in restart loop: None means explicit --all.
            let change_ids = args.normalized_target_changes();
            let config_path = args.config.clone();
            let max_iterations = args.max_iterations;
            let max_concurrent = args.max_concurrent;
            let dry_run = args.dry_run;
            let no_resume = args.no_resume;
            let post_archive_action = args
                .push
                .clone()
                .map(|remote| parallel::PostArchiveAction::PushToRemote { remote })
                .unwrap_or_default();

            // Outer loop for retry/restart support in Run mode
            loop {
                // Check for signal stop before starting new iteration
                if signal_stop.load(Ordering::SeqCst) {
                    info!("Signal stop detected, exiting");
                    break;
                }

                info!("Starting orchestrator");
                lifecycle_handle
                    .publish_state(LifecycleState::Working, lifecycle_process_context());
                let mut orchestrator = Orchestrator::new(
                    change_ids.clone(),
                    config_path.clone(),
                    max_iterations,
                    max_concurrent,
                    dry_run,
                    vcs_override,
                    no_resume,
                    post_archive_action.clone(),
                )?;

                orchestrator
                    .set_lifecycle_handle(lifecycle_handle.clone(), workspace_context.clone());

                // Invocation-scoped; reinstalled on every restart-loop iteration so
                // an enabled run keeps its selected remote, base branch, and
                // verification command across orchestrator reconstruction.
                if let Some(runtime) = upstream_runtime.clone() {
                    orchestrator.set_upstream_integration(runtime);
                }

                #[cfg(feature = "web-monitoring")]
                if let Some(ref web_state) = web_state_arc {
                    orchestrator.set_web_state(web_state.clone()).await;
                }

                // Create a fresh cancel token for this run iteration
                let cancel_token = tokio_util::sync::CancellationToken::new();

                // Monitor stop flags and trigger cancellation for this iteration
                // Note: graceful_stop is NOT monitored here - it's checked directly in orchestrator loop
                // This allows CancelStop to clear the flag before orchestrator sees it
                let monitor_token = cancel_token.clone();
                let monitor_force = force_stop_flag.clone();
                let monitor_signal = signal_stop.clone();
                let monitor_handle = tokio::spawn(async move {
                    loop {
                        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                        if monitor_signal.load(Ordering::SeqCst)
                            || monitor_force.load(Ordering::SeqCst)
                        {
                            if monitor_force.load(Ordering::SeqCst) {
                                info!("Force stop detected, cancelling orchestrator");
                            } else {
                                info!("Signal received, cancelling orchestrator");
                            }
                            monitor_token.cancel();
                            break;
                        }
                    }
                });

                let result = orchestrator
                    .run(cancel_token, Some(graceful_stop_flag.clone()))
                    .await;

                // Cancel monitor task
                monitor_handle.abort();

                // After orchestrator completes, update state
                run_state.store(0, Ordering::SeqCst); // Stopped

                // Handle result - wait for restart requests in both error and stopped states
                match result {
                    Err(e) => {
                        error!("Orchestrator error: {}", e);
                        // An error state waits for an operator retry decision.
                        lifecycle_handle
                            .publish_state(LifecycleState::Blocked, lifecycle_process_context());

                        // Wait for retry request in error state
                        // Keep checking restart_requested flag until user requests retry or signals stop
                        loop {
                            // Check if restart was requested
                            if restart_requested.load(Ordering::SeqCst) {
                                info!("Retry requested after error, will restart orchestrator");
                                break;
                            }

                            // Check if force stop or signal was received (exit on those)
                            if force_stop_flag.load(Ordering::SeqCst)
                                || signal_stop.load(Ordering::SeqCst)
                            {
                                info!("Stop requested in error state, exiting");
                                lifecycle.shutdown().await;
                                return Err(e);
                            }

                            // Wait a bit before checking again (100ms polling interval)
                            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                        }

                        info!("Continuing after error due to retry request");
                    }
                    Ok(()) => {
                        // Successful completion — exit run mode immediately
                        info!("Orchestrator completed successfully");
                    }
                }

                // Check if restart was requested (Start/Retry from web UI or post-error/stop retry)
                if restart_requested.swap(false, Ordering::SeqCst) {
                    info!("Restarting orchestrator due to web control request");
                    run_state.store(1, Ordering::SeqCst); // Back to Running
                                                          // Reset stop flags for new run
                    graceful_stop_flag.store(false, Ordering::SeqCst);
                    force_stop_flag.store(false, Ordering::SeqCst);
                    continue; // Restart loop
                }

                // No restart requested, exit loop
                break;
            }

            lifecycle.shutdown().await;

            // Terminal completion stops the listeners and refresh task and
            // removes the socket this run created, so a finite run needs no
            // external signal to give its endpoint back. Error exits rely on the
            // socket guard's drop for the same cleanup.
            #[cfg(feature = "web-monitoring")]
            if let Some((handle, _)) = started_api {
                handle.shutdown().await;
            }
        }

        // Logs subcommand: read-only persistent log viewer. Intentionally runs before
        // init_logging() so viewing logs never creates, appends, or cleans log files.
        Some(Commands::Logs(args)) => {
            run_logs_subcommand(args, cli.config.as_deref());
        }

        // judge-eval subcommand: read-only evaluation-record reader. Placed
        // beside `logs` and before init_logging() for the same reason — reading
        // the store must not create a log file, an evaluation directory, an
        // installation salt, or trigger retention.
        Some(Commands::JudgeEval(args)) => {
            run_judge_eval_subcommand(args, cli.config.as_deref());
        }

        // Init subcommand: generate only required commands missing globally.
        Some(Commands::Init(args)) => {
            let config_path = Path::new(".cflx.jsonc");

            if config_path.exists() && !args.force {
                eprintln!(
                    "Error: Configuration file '{}' already exists.",
                    config_path.display()
                );
                eprintln!("Use --force to overwrite the existing file.");
                std::process::exit(1);
            }

            let global = OrchestratorConfig::load_global_settings()?;
            let Some(content) = templates::get_missing_required_template(args.template, &global)?
            else {
                println!("Global configuration already defines all required commands; no project configuration was created.");
                return Ok(());
            };
            std::fs::write(config_path, content)?;

            println!(
                "Created configuration file '{}' with required {:?} commands missing from global configuration.",
                config_path.display(),
                args.template
            );
        }

        // install-skills subcommand: install agent skills
        Some(Commands::InstallSkills(args)) => {
            if let Some(src) = &args.legacy_source {
                eprintln!("{}", install_skills_legacy_error(src));
                std::process::exit(1);
            }
            let target = match args.target() {
                InstallSkillsTarget::Agents => install_skills::InstallTarget::Agents,
                InstallSkillsTarget::Claude => install_skills::InstallTarget::Claude,
            };
            let opts = InstallSkillsOptions {
                global: args.global,
                target,
                project_root: None, // use CWD at runtime
            };
            if let Err(e) = run_install_skills(opts) {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }

        // Openspec subcommand: native OpenSpec utility operations
        Some(Commands::Openspec(args)) => {
            use cli::{EvidenceMode, OpenspecCommands};

            match args.command {
                OpenspecCommands::List(list_args) => {
                    if let Err(e) = crate::openspec_cmd::cmd_list(list_args.specs) {
                        eprintln!("Error: {}", e);
                        std::process::exit(1);
                    }
                }
                OpenspecCommands::Show(show_args) => {
                    if let Err(e) = crate::openspec_cmd::cmd_show(
                        &show_args.change_id,
                        show_args.json,
                        show_args.deltas_only,
                    ) {
                        eprintln!("Error: {}", e);
                        std::process::exit(1);
                    }
                }
                OpenspecCommands::Validate(val_args) => {
                    let strict = val_args.strict || val_args.archive_gate;
                    let evidence = if val_args.archive_gate {
                        "error"
                    } else {
                        match val_args.evidence {
                            EvidenceMode::Off => "off",
                            EvidenceMode::Warn => "warn",
                            EvidenceMode::Error => "error",
                        }
                    };
                    let (is_valid, exit_code) = crate::openspec_cmd::cmd_validate(
                        val_args.change_id.as_deref(),
                        strict,
                        evidence,
                    );
                    if !is_valid {
                        std::process::exit(exit_code);
                    }
                }
                OpenspecCommands::Archive(arc_args) => {
                    if !arc_args.yes {
                        eprintln!("Error: --yes flag is required (non-interactive only)");
                        std::process::exit(1);
                    }
                    if let Err(e) =
                        crate::openspec_cmd::cmd_archive(&arc_args.change_id, arc_args.skip_specs)
                    {
                        eprintln!("Error: {}", e);
                        std::process::exit(1);
                    }
                }
                OpenspecCommands::Verify(verify_args) => {
                    match crate::openspec_cmd::cmd_verify(
                        &verify_args.change_id,
                        verify_args.verification_id.as_deref(),
                        verify_args.plan,
                        verify_args.json,
                    )
                    .await
                    {
                        Ok(0) => {}
                        Ok(code) => std::process::exit(code),
                        Err(e) => {
                            eprintln!("Error: {}", e);
                            std::process::exit(1);
                        }
                    }
                }
            }
        }

        // CheckConflicts subcommand: detect conflicts between spec delta files
        Some(Commands::CheckConflicts(args)) => {
            // Get list of all non-archived changes
            let changes = openspec::list_changes_native()?;

            // Collect all deltas from all changes
            let mut all_deltas = Vec::new();
            for change in &changes {
                match spec_delta::parse_change_deltas(&change.id) {
                    Ok(deltas) => all_deltas.extend(deltas),
                    Err(e) => {
                        eprintln!("Error parsing deltas for change '{}': {}", change.id, e);
                        std::process::exit(1);
                    }
                }
            }

            // Detect conflicts
            let conflicts = spec_delta::detect_conflicts(&all_deltas);

            // Output results
            if args.json {
                match spec_delta::format_conflicts_json(&conflicts) {
                    Ok(json) => {
                        println!("{}", json);
                    }
                    Err(e) => {
                        eprintln!("Error formatting JSON output: {}", e);
                        std::process::exit(1);
                    }
                }
            } else {
                let output = spec_delta::format_conflicts_human(&conflicts);
                println!("{}", output);
            }

            // Exit with non-zero status if conflicts found
            if !conflicts.is_empty() {
                std::process::exit(2);
            }
        }
    }

    Ok(())
}