synaps 0.11.0

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

use clap::{Parser, Subcommand};

use synaps_cli::tui;
mod cmd;
#[cfg(unix)]
mod watcher;

// ── Allocator ────────────────────────────────────────────────────────────────
// Long-lived sessions serialize the ENTIRE conversation to a JSON body every
// turn (prompt caching requires sending the full prefix — see
// runtime/api.rs `serde_json::to_vec(&body)`). That transient buffer scales
// with history length; on glibc the freed arena pages are never returned to the
// OS, so RSS ratchets up to ~history size and never shrinks (the classic
// transient-heavy-long-lived-process hysteresis).
//
// jemalloc's background thread purges cold dirty pages back to the OS, which
// reclaims exactly that dead-but-retained arena — with zero impact on caching
// or retained history. Gated to non-musl: musl's allocator already returns
// memory readily, and the Pria agentic-VM runtime is a musl build we don't want
// to perturb.
#[cfg(all(unix, not(target_env = "musl")))]
#[global_allocator]
static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

// Configure jemalloc at load time (no env var needed). Three settings:
//   - background_thread:true  → background thread purges cold dirty pages to OS
//   - narenas:4               → cap arenas (default is 4×ncpu = 48 on a 12-core
//                               box). 26 runtime threads sprawling across 48
//                               arenas reserve ~70 MB of 4 MB chunks at baseline
//                               for no benefit; 4 arenas is ample for our
//                               allocation concurrency and slashes idle RSS.
//   - dirty_decay_ms:1000     → return idle dirty pages ~1s after they go cold
//   - muzzy_decay_ms:0        → purge muzzy pages immediately
//
// CRITICAL: tikv-jemalloc-sys is built with the `_rjem_` symbol prefix, so
// jemalloc reads the config from `_rjem_malloc_conf` — NOT `malloc_conf`. An
// earlier revision exported the unmangled name, which jemalloc silently ignored
// (verified: opt.dirty_decay_ms sat at the 10000ms default). Keep this mangled.
#[cfg(all(unix, not(target_env = "musl")))]
#[allow(non_upper_case_globals)]
#[export_name = "_rjem_malloc_conf"]
pub static MALLOC_CONF: &[u8] =
    b"background_thread:true,narenas:4,dirty_decay_ms:1000,muzzy_decay_ms:0\0";

#[derive(Parser)]
#[command(
    name = "synaps",
    about = "SynapsCLI — terminal-native AI agent runtime (TUI, headless, server, RPC)",
    long_about = "SynapsCLI — terminal-native AI agent runtime.\n\nRun with no arguments for the interactive TUI. Subcommands provide headless chat,\na WebSocket server, autonomous agents, and event injection into running sessions.",
    version
)]
struct Cli {
    /// Configuration profile (loads ~/.synaps-cli/<PROFILE>/config)
    #[arg(long, global = true)]
    profile: Option<String>,

    /// Continue a previous session (TUI only). Optionally provide a session ID.
    #[arg(long = "continue", value_name = "NAME_OR_ID")]
    continue_session: Option<Option<String>>,

    /// System prompt: a string or path to a file (TUI only).
    #[arg(long = "system", short = 's', value_name = "PROMPT_OR_FILE")]
    system: Option<String>,

    /// Typed modular prompt manifest (validated offline before session start).
    #[arg(long = "prompt-manifest", value_name = "PATH")]
    prompt_manifest: Option<std::path::PathBuf>,

    /// Disable all extensions for this session.
    #[arg(long)]
    no_extensions: bool,

    /// Run the TUI attached to a daemon session instead of in-process
    /// (the daemon is started on first use). Optionally a session ID
    /// (prefix ok); with no live session a new one is created (`--continue`
    /// continues); --new (alias --create) forces a fresh session even if
    /// one is live. Modifiers: --observe (read-only), --takeover (steal input),
    /// --keep-warm (never parked), --new (fresh session); default mode is
    /// SYNAPS_ATTACH_MODE or mirror (input only if nobody owns it).
    #[arg(long = "attach", value_name = "ID", global = true, num_args = 0..=1)]
    attach: Option<Option<String>>,

    /// With --attach: mirror without input (read-only).
    #[arg(long, global = true, conflicts_with = "takeover")]
    observe: bool,

    /// With --attach: steal input ownership from the current owner (the
    /// previous owner is told; without it a second client is read-only
    /// while the owner is attached).
    #[arg(long, global = true)]
    takeover: bool,

    /// With --attach: what this client is called in the session (`/clients`,
    /// `synaps daemon sessions`, "input moved to …"). 1–32 letters, digits,
    /// `-` or `_`. Default: SYNAPS_CLIENT_NAME, else `tui` (`tui-2`, … when
    /// taken).
    #[arg(long = "as", value_name = "NAME", global = true)]
    client_name: Option<String>,

    /// With --attach: pin the session live (never parked).
    #[arg(long = "keep-warm", global = true)]
    keep_warm: bool,

    /// With --attach: never answer confirm prompts (tool-call and
    /// tool-activation approvals) from this TUI, whatever keys reach it;
    /// they are listed as waiting for another client to answer. Secret
    /// prompts are still typed here. For a TUI embedded where keystrokes may
    /// come from somewhere other than the person approving.
    #[arg(long = "no-confirm-answers", requires = "attach")]
    no_confirm_answers: bool,

    /// With --attach: always create a fresh session even if one is live
    /// (cannot be combined with an explicit session ID). Not global: the
    /// `attach` subcommand has its own `--create`/`--new`.
    #[arg(long = "new", alias = "create", requires = "attach")]
    new_session: bool,

    /// With --attach --new / --continue: name the created session so
    /// `synaps send --session <NAME>` resolves it immediately.
    #[arg(long = "name", value_name = "NAME", requires = "attach")]
    session_name: Option<String>,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Headless chat with full engine (MCP, extensions, skills, sessions)
    Chat {
        /// Continue a previous session (optional session ID, name, or chain)
        #[arg(long, short = 'c')]
        continue_session: Option<String>,
        /// System prompt (path or inline)
        #[arg(long, short = 's')]
        system: Option<String>,
        /// Agent name (loads agent prompt from ~/.synaps-cli/agents/)
        #[arg(long, short = 'a')]
        agent: Option<String>,
        /// Profile name
        #[arg(long)]
        profile: Option<String>,
        /// Disable extensions
        #[arg(long)]
        no_extensions: bool,
    },
    /// WebSocket API server
    Server {
        #[arg(long, short, default_value = "3145")]
        port: u16,
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
        #[arg(long = "system", short = 's')]
        system: Option<String>,
        #[arg(long = "continue", value_name = "NAME_OR_ID")]
        continue_session: Option<Option<String>>,
        /// Auth token (overrides config). Empty string disables auth.
        #[arg(long)]
        token: Option<String>,
        /// Auto-approve extension confirm hooks without prompting.
        #[arg(long)]
        auto_approve_confirms: bool,
        /// Comma-separated allowed origins (overrides config).
        #[arg(long)]
        allowed_origins: Option<String>,
    },
    /// Headless autonomous agent
    Agent {
        #[arg(long)]
        config: String,
        #[arg(long, default_value = "manual start")]
        trigger_context: String,
    },
    /// Agent supervisor and watcher
    Watcher {
        #[arg(default_value = "help")]
        subcommand: String,
        /// Additional arguments
        args: Vec<String>,
    },
    /// OAuth login
    Login {
        /// Non-interactive: log in directly with a named provider (skips the picker). e.g. openai-codex, claude
        #[arg(long)]
        provider: Option<String>,
        /// Store the OAuth credential in a named account slot (`<provider>@<label>`)
        /// instead of the default slot. Label: a-z, 0-9, '.', '_', '-' (max 32).
        /// Requires --provider. The default slot is never touched.
        #[arg(long, requires = "provider", value_name = "LABEL")]
        account: Option<String>,
    },
    /// Authentication management
    Auth {
        #[command(subcommand)]
        action: AuthAction,
    },
    /// Show account usage and reset times
    Status {
        /// Show memory (RSS/PSS/USS/RssAnon) per live session process tree
        /// instead of account usage. Linux only.
        #[arg(long)]
        memory: bool,
        /// Emit JSON instead of a table (usage or --memory mode).
        #[arg(long)]
        json: bool,
        /// With --memory: walk this pid's tree instead of the live sessions.
        #[arg(long, requires = "memory")]
        pid: Option<u32>,
        /// Show full usage windows, model availability, credits and diagnostics.
        #[arg(long, conflicts_with_all = ["memory", "json"])]
        verbose: bool,
        /// Usage for one OAuth provider (e.g. openai-codex, claude, kimi-code, xai-auth).
        #[arg(long, conflicts_with = "memory")]
        provider: Option<String>,
        /// Usage for one stored account of --provider (label or `default`); never falls back.
        #[arg(long, requires = "provider", conflicts_with = "memory", value_name = "LABEL")]
        account: Option<String>,
        /// Usage for every stored account of every usage-capable provider (or of --provider).
        #[arg(long, conflicts_with_all = ["memory", "account"])]
        all: bool,
    },
    /// Quota keeper: poll per-account usage (read-only by default) and, only for
    /// explicitly opted-in Codex accounts, run one minimal activation per reset.
    QuotaKeeper(cmd::quota_keeper::QuotaKeeperArgs),
    /// Credential broker — serve short-lived access tokens to client machines
    /// over HTTP/HTTPS so they can share one OAuth credential without storing it.
    ///
    /// For non-loopback binds, pass --tls-cert + --tls-key to enable HTTPS (recommended),
    /// or --insecure-http to acknowledge you are running behind WireGuard / a private network.
    AuthBroker {
        /// Address to bind, e.g. `0.0.0.0:8181` or `127.0.0.1:8181`.
        #[arg(long, default_value = "127.0.0.1:8181")]
        bind: String,
        /// REJECTED — a token in argv leaks via `ps aux` and
        /// /proc/<pid>/cmdline. Use `--machine-token-file` or
        /// `SYNAPS_BROKER_TOKEN`. Still parsed so we can emit a migration error.
        #[arg(long)]
        machine_token: Option<String>,
        /// Read the machine token from a file (avoids exposing it in argv/`ps`).
        #[arg(long)]
        machine_token_file: Option<std::path::PathBuf>,
        /// Allow starting with auth OFF on a non-loopback bind (serves
        /// credentials unauthenticated to the network — NOT recommended).
        #[arg(long)]
        insecure_no_auth: bool,
        /// PEM file containing the TLS certificate chain. Must be paired with --tls-key.
        /// When both are set, the broker listens on HTTPS.
        #[arg(long, value_name = "PATH")]
        tls_cert: Option<std::path::PathBuf>,
        /// PEM file containing the TLS private key. Must be paired with --tls-cert.
        #[arg(long, value_name = "PATH")]
        tls_key: Option<std::path::PathBuf>,
        /// Allow plain HTTP on a non-loopback bind without TLS.
        /// Only use this when the broker is behind WireGuard or another encrypted
        /// private network — the traffic will be unencrypted in-process.
        #[arg(long)]
        insecure_http: bool,
    },
    /// Session daemon — status/stop/sessions/reload (auto-started by --attach)
    Daemon(cmd::daemon::DaemonArgs),
    /// Thin line client attached to a daemon session (starts the daemon if needed)
    Attach(cmd::attach::AttachArgs),
    /// Headless line-JSON RPC server on stdin/stdout (synaps-bridge IPC)
    Rpc {
        /// Resume an existing session by ID, name, or prefix.
        #[arg(long = "continue", value_name = "SESSION_ID")]
        continue_id: Option<String>,
        /// System prompt: a string or path to a file.
        #[arg(long = "system", short = 's', value_name = "PROMPT_OR_FILE")]
        system: Option<String>,
        /// Override the active model for this session.
        #[arg(long = "model", short = 'm', value_name = "MODEL_ID")]
        model: Option<String>,
        /// Configuration profile to load.
        #[arg(long = "profile", value_name = "PROFILE")]
        profile: Option<String>,
    },
    /// Send an event to a running session (its socket), or to the shared inbox
    Send {
        /// Message text
        message: String,
        #[arg(long, default_value = "cli")]
        source: String,
        #[arg(long, default_value = "medium")]
        severity: String,
        #[arg(long)]
        channel: Option<String>,
        #[arg(long = "content-type", default_value = "message")]
        content_type: String,
        /// Target a specific session by ID, name, or prefix. A miss, or a
        /// socket that still refuses after 3 tries, is an error (exit 1,
        /// nothing delivered) unless --inbox is given
        #[arg(long, value_name = "SESSION")]
        session: Option<String>,
        /// Send to all active sessions
        #[arg(long)]
        broadcast: bool,
        /// With --session: when nothing matches or the socket refuses, leave
        /// the event in the shared inbox instead of failing. Only a session with an attached input
        /// owner takes inbox files, exactly once
        #[arg(long)]
        inbox: bool,
    },
    /// Generate shell completions (bash, zsh, fish, elvish, powershell)
    Completions {
        /// Target shell
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
    /// Offline modular prompt validation and inspection.
    Prompt {
        #[command(subcommand)]
        action: cmd::prompt::PromptAction,
    },
    /// Tool-surface utilities (schema export, etc.)
    Tools {
        #[command(subcommand)]
        action: cmd::tools::ToolsAction,
    },
    /// Request-trace export utilities (metadata-only by default).
    Trace {
        #[command(subcommand)]
        action: cmd::trace::TraceAction,
    },
    /// Unified retention: inspect/sweep/export/forget across sessions,
    /// memory, indexes, traces, and logs (chain-integrity-safe).
    Retention {
        #[command(subcommand)]
        action: cmd::retention::RetentionAction,
    },
}

#[derive(Subcommand)]
enum AuthAction {
    /// OAuth / API-key login (non-interactive with --provider, interactive without)
    Login {
        /// Non-interactive: log in directly with a named provider (skips the picker). e.g. openai-codex, claude
        #[arg(long)]
        provider: Option<String>,
        /// Store the OAuth credential in a named account slot (`<provider>@<label>`).
        /// Requires --provider. The default slot is never touched.
        #[arg(long, requires = "provider", value_name = "LABEL")]
        account: Option<String>,
    },
    /// List stored OAuth accounts (labels and non-secret metadata only)
    List {
        /// Restrict to one OAuth provider (e.g. openai-codex, claude, kimi-code)
        #[arg(long)]
        provider: Option<String>,
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// Preview automatic subscription ranking without making an inference request
    Plan {
        #[arg(long)]
        provider: Option<String>,
        /// Filter capacity by the model you intend to use
        #[arg(long)]
        model: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// Select which stored account a provider uses (writes auth.account.<provider>)
    Use {
        /// OAuth provider (e.g. openai-codex, claude)
        #[arg(long)]
        provider: String,
        /// Account label, `default`, or `auto` (opt-in capacity-based selection)
        #[arg(long, value_name = "LABEL|default|auto")]
        account: String,
    },
    /// Remove one stored account slot (never touches other slots)
    Remove {
        /// OAuth provider (e.g. openai-codex, claude)
        #[arg(long)]
        provider: String,
        /// Account label or `default`
        #[arg(long, value_name = "LABEL|default")]
        account: String,
        /// Skip confirmation (required for the default slot and non-interactive use)
        #[arg(long, short = 'y')]
        yes: bool,
    },
    /// Verify which provider account each stored slot holds and flag slots that
    /// share one seat (backfills identity for logins that predate this check).
    /// Local store only. Exits non-zero when duplicates exist.
    Identify {
        /// Restrict to one OAuth provider (e.g. openai-codex, claude)
        #[arg(long)]
        provider: Option<String>,
        /// Restrict to one account label (or `default`)
        #[arg(long, value_name = "LABEL|default")]
        account: Option<String>,
        /// Resolve and report only; write nothing
        #[arg(long)]
        dry_run: bool,
        /// Re-verify slots that already carry an account id
        #[arg(long)]
        force: bool,
        /// Machine-readable JSON
        #[arg(long)]
        json: bool,
    },
    /// What the running daemon's broker remembers about each account: its
    /// cooldown, last usage read, last token refresh and the last automatic
    /// selection. Memory only: no usage request, no refresh. Without a
    /// running daemon, lists the accounts with nothing recorded.
    State {
        /// Restrict to one OAuth provider (e.g. claude, openai-codex)
        #[arg(long)]
        provider: Option<String>,
        /// Restrict to one account label (or `default`): its state, and only
        /// the selections that chose it or list it as failed
        #[arg(long, value_name = "LABEL|default")]
        account: Option<String>,
        /// Machine-readable JSON (the report only; notices go to stderr)
        #[arg(long)]
        json: bool,
        /// Drop the matched accounts' in-memory cooldowns, usage readings and
        /// stickiness in the running daemon first. Never touches credentials.
        /// With --account, the selection history stays; only a clear without
        /// --account also drops it.
        #[arg(long)]
        clear: bool,
    },
}

/// Tokio worker-thread count (§3.6 process diet). `SYNAPS_WORKER_THREADS`:
/// `n > 0` → exactly `n`; `0` → tokio's default (one per core, the old
/// behaviour — the kill-switch); unset/invalid → `min(4, available_parallelism)`.
/// Only the async worker pool is capped; `spawn_blocking` is untouched.
fn worker_threads() -> Option<usize> {
    let ncpu = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4);
    worker_threads_from(std::env::var("SYNAPS_WORKER_THREADS").ok().as_deref(), ncpu)
}

fn worker_threads_from(raw: Option<&str>, ncpu: usize) -> Option<usize> {
    match raw.and_then(|v| v.trim().parse::<usize>().ok()) {
        Some(0) => None,
        Some(n) => Some(n),
        None => Some(ncpu.clamp(1, 4)),
    }
}

/// Which thin client argv asks for (`SYNAPS_DAEMON` not `0`): the TUI
/// (`--attach`/`--attach=` anywhere) or the line client (`attach` as the
/// first positional). `None` = the ordinary in-process boot, which must run
/// exactly like `synaps` does — no re-exec, no allocator diet, multi-thread
/// runtime (review H2).
#[derive(Debug, Clone, PartialEq, Eq)]
enum ThinClient {
    Tui { profile: Option<String> },
    Line { profile: Option<String> },
    /// Plain `synaps [--system ..] [--continue ..]` with **no** `--attach`:
    /// adopt the daemon (fresh session, exactly `--attach --new` semantics),
    /// **spawning it first if none is running** — the jcode model, same as
    /// `--attach`. A failed spawn falls back to the ordinary in-process boot
    /// with a notice. `SYNAPS_DAEMON_ADOPT=0` turns this off (always
    /// in-process); `--no-extensions` skips it (daemon extensions are
    /// shared, so the flag cannot be honoured over the socket).
    Adopt { profile: Option<String> },
}

impl ThinClient {
    fn profile_mut(&mut self) -> &mut Option<String> {
        match self {
            ThinClient::Tui { profile } | ThinClient::Line { profile } | ThinClient::Adopt { profile } => profile,
        }
    }
}

/// Pin the process profile before ANY config read. `config::get_profile()`
/// latches on first use (falling back to `SYNAPS_PROFILE`) and
/// `set_profile` is first-write-wins, so a single `load_config()` before
/// the pin — `ensure_daemon`'s idle-exit lookup and scope probe did that in
/// 0.10.1 — silently drops `--profile` for the rest of the process: the
/// TUI fell back to the default profile's config, sessions and `/model`
/// writes. Returns the profile actually in effect (flag, else env), which
/// is the one the daemon socket must be chosen by.
fn pin_profile(flag: Option<String>) -> Option<String> {
    if flag.is_some() {
        synaps_cli::config::set_profile(flag);
    }
    synaps_cli::config::get_profile()
}

/// `--profile X` must be the profile in effect; if something latched
/// another one first, refuse instead of running (and writing config,
/// sessions) under the wrong profile.
fn check_profile_applied(requested: Option<&str>, active: Option<&str>) -> anyhow::Result<()> {
    match requested {
        Some(want) if active != Some(want) => anyhow::bail!(
            "--profile {want} could not be applied (profile `{}` was already in effect); refusing to run under the wrong profile",
            active.unwrap_or("default")
        ),
        _ => Ok(()),
    }
}

/// `SYNAPS_DAEMON_ADOPT`: ON unless `0`/`false`/`off`/`no`. Off means a
/// plain `synaps` never looks for a running daemon (always in-process).
fn adopt_enabled() -> bool {
    !matches!(
        std::env::var("SYNAPS_DAEMON_ADOPT").ok().map(|s| s.trim().to_ascii_lowercase()).as_deref(),
        Some("0" | "false" | "off" | "no")
    )
}

fn thin_client() -> Option<ThinClient> {
    thin_client_from(std::env::args().skip(1), agent_engine::daemon::enabled(), adopt_enabled())
}

/// Top-level `Cli` options that always take a value (`--system FILE`,
/// `-s FILE`, `--name NAME`, `--prompt-manifest PATH`). Their value must
/// not be mistaken for a subcommand positional, or `synaps --attach --new
/// --system x.md` silently boots as a fat in-process-shaped client on the
/// socket (no auto-spawn, no allocator diet, multi-thread runtime).
const VALUE_OPTS: &[&str] = &["--system", "-s", "--name", "--prompt-manifest"];
/// Top-level options with an optional value (`num_args = 0..=1`): the next
/// token is their value iff it does not start with `-`, exactly as clap
/// parses `synaps --attach abc` / `synaps --continue foo`.
const OPT_VALUE_OPTS: &[&str] = &["--attach", "--continue"];

fn thin_client_from<I: IntoIterator<Item = String>>(
    args: I,
    daemon_enabled: bool,
    adopt: bool,
) -> Option<ThinClient> {
    if !daemon_enabled {
        return None;
    }
    let mut want_profile = false;
    let mut want_value = false;
    let mut maybe_value = false;
    let mut profile: Option<String> = None;
    let mut first_positional: Option<String> = None;
    let mut attach_flag = false;
    // Any flag outside the plain-TUI set (`--system/-s`, `--continue`,
    // `--prompt-manifest`, `--profile`): `--help`, `--version`,
    // `--no-extensions`, attach modifiers, typos — never adopt, let clap
    // decide exactly as before.
    let mut other_flag = false;
    for a in args {
        if want_profile {
            want_profile = false;
            profile = Some(a);
            continue;
        }
        if want_value {
            want_value = false;
            continue;
        }
        if maybe_value {
            maybe_value = false;
            if !a.starts_with('-') {
                continue;
            }
        }
        if a == "--attach" || a.starts_with("--attach=") {
            attach_flag = true;
            maybe_value = a == "--attach";
        } else if a == "--profile" {
            want_profile = true;
        } else if let Some(p) = a.strip_prefix("--profile=") {
            profile = Some(p.to_string());
        } else if VALUE_OPTS.contains(&a.as_str()) {
            want_value = true;
            // `--name` requires `--attach` (clap): not part of the plain-TUI set.
            other_flag |= a == "--name";
        } else if OPT_VALUE_OPTS.contains(&a.as_str()) {
            maybe_value = true;
        } else if !a.starts_with('-') {
            if first_positional.is_none() {
                first_positional = Some(a);
            }
        } else {
            other_flag = true;
        }
    }
    if first_positional.as_deref() == Some("attach") {
        Some(ThinClient::Line { profile })
    } else if attach_flag && first_positional.is_none() {
        Some(ThinClient::Tui { profile })
    } else if adopt && first_positional.is_none() && !other_flag {
        Some(ThinClient::Adopt { profile })
    } else {
        None
    }
}

/// Set by `main` when a plain `synaps` found a running daemon: the clap
/// branch runs the socket client with `--attach --new` semantics.
static ADOPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Auto-spawn (jcode model) before the runtime exists: a live daemon or a
/// freshly spawned one. Runs BEFORE the thin re-exec/diet so a failed spawn
/// can fall back to the untouched in-process boot. Returns the reason the
/// TUI should fall back in-process; the line client exits 3 instead.
fn ensure_daemon(kind: &ThinClient) -> Option<String> {
    use agent_engine::daemon::{self, EnsureError, Ensured, EXIT_REFUSED};
    let (profile, line) = match kind {
        ThinClient::Tui { profile } | ThinClient::Adopt { profile } => (profile.clone(), false),
        ThinClient::Line { profile } => (profile.clone(), true),
    };
    let opts = daemon::DaemonOpts { profile, ..Default::default() };
    match daemon::ensure_running(&opts) {
        Ok(Ensured::Running) => None,
        Ok(Ensured::Spawned(pid)) => {
            eprintln!("starting daemon (pid {pid}) — synaps daemon stop to end it");
            None
        }
        Err(EnsureError::AutospawnDisabled) => {
            // Plain `synaps` with autospawn off is simply the in-process
            // boot, quietly. An explicit `--attach` asked for a daemon and
            // must say why there is none.
            if matches!(kind, ThinClient::Adopt { .. }) {
                return Some("SYNAPS_DAEMON_AUTOSPAWN=0".into());
            }
            let msg = cmd::attach::no_daemon_message(opts.profile.as_deref());
            eprintln!("{msg}");
            std::process::exit(EXIT_REFUSED);
        }
        Err(EnsureError::Spawn(reason)) => {
            if line {
                eprintln!("synaps attach: daemon unavailable: {reason}");
                std::process::exit(EXIT_REFUSED);
            }
            Some(reason)
        }
    }
}

/// Our jemalloc boot conf for the re-exec'd thin client (`SYNAPS_CLIENT_MALLOC_CONF`
/// overrides). `narenas` is boot-only — the one knob a mallctl cannot set.
const THIN_MALLOC_CONF: &str = "narenas:1,background_thread:false,dirty_decay_ms:0,muzzy_decay_ms:0";

/// Set by `main` when the daemon could not be started: `--attach` runs the
/// ordinary TUI with a notice instead of the socket client.
const ATTACH_FALLBACK: &str = "SYNAPS_ATTACH_FALLBACK";

/// Env markers carried across the re-exec: the loop guard and the user's own
/// `_RJEM_MALLOC_CONF` (restored in the child so what we spawn sees it, M2).
const REEXECED: &str = "SYNAPS_CLIENT_REEXECED";
const USER_MALLOC_CONF: &str = "SYNAPS_CLIENT_USER_MALLOC_CONF";

/// Thin-client re-exec (PLAN-phase4 §4.5, extended): `PR_SET_THP_DISABLE`
/// is inherited across `execve`, so re-exec'ing ourselves once means the
/// **whole** image — `.bss`, the main stack, jemalloc's first chunks — is
/// mapped at 4 KiB granularity instead of the three 2 MiB huge pages the A1
/// ladder found already resident at `main` (6 of the 7.4 MB). The same exec
/// carries `_RJEM_MALLOC_CONF` so jemalloc boots with one arena and no
/// background thread. `SYNAPS_CLIENT_REEXEC=0` disables; cost ≈ 3–5 ms
/// (the `reexec` ladder stage is the pre-exec process' last line).
///
/// Only worth it when the kernel's THP mode is `[always]` (M1): under
/// `[madvise]`/`[never]` nothing is huge-mapped before `main`, and the only
/// thing the exec would buy is `narenas:1` — `tune_allocator` sets the rest
/// in-process via mallctl. `SYNAPS_CLIENT_THP=1` (keep huge pages) skips too.
#[cfg(target_os = "linux")]
fn thin_client_reexec() {
    use agent_core::core::memstat;
    if std::env::var("SYNAPS_CLIENT_REEXEC").is_ok_and(|v| v == "0")
        || std::env::var_os(REEXECED).is_some()
        || std::env::var("SYNAPS_CLIENT_THP").is_ok_and(|v| v == "1")
        || tui::client_diet::allocator_tuning_disabled()
        || memstat::thp_disabled() == Some(true)
    {
        return;
    }
    if memstat::thp_sysfs_always() != Some(true) {
        memstat::ladder("reexec", &"skipped=thp-not-always");
        return;
    }
    let Ok(exe) = std::env::current_exe() else { return };
    if memstat::disable_thp().is_err() {
        return;
    }
    memstat::ladder("reexec", &"");
    use std::os::unix::process::CommandExt;
    let ours = std::env::var("SYNAPS_CLIENT_MALLOC_CONF").unwrap_or_else(|_| THIN_MALLOC_CONF.into());
    let user = std::env::var("_RJEM_MALLOC_CONF").ok().filter(|v| !v.is_empty());
    // Later keys win in jemalloc's conf parser: the user's value stays visible, ours applies.
    let conf = match &user {
        Some(u) => format!("{u},{ours}"),
        None => ours,
    };
    let mut cmd = std::process::Command::new(exe);
    cmd.args(std::env::args_os().skip(1)).env(REEXECED, "1").env("_RJEM_MALLOC_CONF", conf);
    if let Some(u) = user {
        cmd.env(USER_MALLOC_CONF, u);
    }
    let err = cmd.exec();
    // exec only returns on failure: carry on in this image.
    let _ = err;
    std::env::remove_var(REEXECED);
}

#[cfg(not(target_os = "linux"))]
fn thin_client_reexec() {}

/// After the (possible) re-exec: jemalloc has read `_RJEM_MALLOC_CONF` at
/// load, so put the environment back the way the user had it — only what
/// the exec added is removed; a conf the user exported themselves is left
/// (or restored) for every child the client spawns (M2).
fn scrub_reexec_env() {
    if std::env::var_os(REEXECED).is_none() {
        return;
    }
    std::env::remove_var(REEXECED);
    match std::env::var(USER_MALLOC_CONF) {
        Ok(user) => std::env::set_var("_RJEM_MALLOC_CONF", user),
        Err(_) => std::env::remove_var("_RJEM_MALLOC_CONF"),
    }
    std::env::remove_var(USER_MALLOC_CONF);
}

fn main() -> anyhow::Result<()> {
    // Before anything can report it (daemon `Welcome`, the client's skew check).
    agent_engine::session::wire::set_build_id(env!("SYNAPS_BUILD_ID"));
    let mut thin = false;
    if let Some(mut kind) = thin_client() {
        // Before `ensure_daemon`: it reads config (idle-exit, process scopes).
        let profile = pin_profile(kind.profile_mut().take());
        *kind.profile_mut() = profile;
        // Adopt and --attach share one path: a running daemon or a freshly
        // spawned one; a failed spawn falls back to the in-process boot.
        match ensure_daemon(&kind) {
            None => {
                if matches!(kind, ThinClient::Adopt { .. }) {
                    ADOPTED.store(true, std::sync::atomic::Ordering::SeqCst);
                }
                thin = true;
            }
            Some(reason) => {
                eprintln!("daemon unavailable: {reason} — running in-process");
                tui::push_boot_notice(format!("daemon unavailable: {reason} — running in-process"));
                std::env::set_var(ATTACH_FALLBACK, "1");
            }
        }
    }
    if thin {
        thin_client_reexec();
        scrub_reexec_env();
        // Ladder START pins on the first call — `main` must be first (§7.1).
        agent_core::core::memstat::ladder("main", &"");
        tui::client_diet::tune_allocator();
    }
    let rt = if thin {
        tokio::runtime::Builder::new_current_thread().enable_all().thread_name("synaps-rt").build()?
    } else {
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        if let Some(n) = worker_threads() {
            builder.worker_threads(n);
        }
        builder.enable_all().thread_name("synaps-rt").build()?
    };
    if thin {
        agent_core::core::memstat::ladder("runtime", &"");
    }
    // The log-appender guard lives on the process `EngineHost` (a static —
    // never dropped by Rust). Flush it on every exit path so the teardown
    // burst (session save, hooks, extension shutdown) reaches disk.
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        default_hook(info);
        synaps_cli::EngineHost::flush_installed_logs();
    }));
    let result = rt.block_on(async_main());
    synaps_cli::EngineHost::flush_installed_logs();
    result
}

async fn async_main() -> anyhow::Result<()> {
    let mut cli = Cli::parse();
    if ADOPTED.load(std::sync::atomic::Ordering::SeqCst) && cli.command.is_none() && cli.attach.is_none() {
        cli.attach = Some(None);
        cli.new_session = true;
    }
    if matches!(cli.command, Some(Command::Prompt { .. })) {
        if let Some(Command::Prompt { action }) = cli.command {
            return cmd::prompt::run(action);
        }
        unreachable!();
    }
    if let Some(ref prof) = cli.profile {
        synaps_cli::config::set_profile(Some(prof.clone()));
    }
    // Flag, else `SYNAPS_PROFILE`: daemon sockets are chosen by this, so an
    // env-profiled client never lands on the default profile's daemon.
    let active_profile = synaps_cli::config::get_profile();
    check_profile_applied(cli.profile.as_deref(), active_profile.as_deref())?;

    match cli.command {
        None if cli.attach.is_some() => {
            let fallback = std::env::var_os(ATTACH_FALLBACK).is_some();
            std::env::remove_var(ATTACH_FALLBACK);
            if !agent_engine::daemon::enabled() || fallback {
                if !fallback {
                    eprintln!("--attach ignored: {}", agent_engine::daemon::DISABLED_NOTICE);
                }
                tui::run(
                    cli.continue_session,
                    cli.system,
                    cli.prompt_manifest,
                    cli.profile,
                    cli.no_extensions,
                )
                .await?;
            } else {
                let id = cli.attach.flatten();
                tui::attach::run_attached(tui::attach::AttachOpts {
                    profile: active_profile,
                    id,
                    continue_session: cli.continue_session,
                    system: cli.system,
                    prompt_manifest: cli.prompt_manifest,
                    mode: tui::attach::attach_mode(cli.observe, cli.takeover),
                    no_confirm_answers: cli.no_confirm_answers,
                    keep_warm: cli.keep_warm,
                    new_session: cli.new_session,
                    name: cli.session_name,
                    client_name: cli.client_name,
                    adopted: ADOPTED.load(std::sync::atomic::Ordering::SeqCst),
                })
                .await?;
            }
        }
        None => {
            tui::run(
                cli.continue_session,
                cli.system,
                cli.prompt_manifest,
                cli.profile,
                cli.no_extensions,
            )
            .await?;
        }
        Some(Command::Chat {
            continue_session,
            system,
            agent,
            profile,
            no_extensions,
        }) => {
            cmd::chat::run(continue_session, system, agent, profile, no_extensions).await?;
        }
        Some(Command::Server {
            port,
            host,
            system,
            continue_session,
            token,
            auto_approve_confirms,
            allowed_origins,
        }) => {
            cmd::server::run(
                port,
                host,
                system,
                continue_session,
                cli.profile,
                token,
                auto_approve_confirms,
                allowed_origins,
            )
            .await?;
        }
        Some(Command::Agent {
            config,
            trigger_context,
        }) => {
            cmd::agent::run(config, trigger_context).await;
        }
        Some(Command::Watcher { subcommand, args }) => {
            cmd::watcher::run(subcommand, args).await;
        }
        Some(Command::Login { provider, account }) => {
            cmd::login::run(cli.profile, provider, account)
                .await
                .map_err(anyhow::Error::msg)?;
        }
        Some(Command::Auth { action }) => match action {
            AuthAction::Login { provider, account } => {
                cmd::login::run(cli.profile, provider, account)
                    .await
                    .map_err(anyhow::Error::msg)?
            }
            AuthAction::List { provider, json } => {
                cmd::auth_accounts::list(cmd::auth_accounts::ListOptions { provider, json })
                    .await
                    .map_err(anyhow::Error::msg)?
            }
            AuthAction::Plan {
                provider,
                model,
                json,
            } => cmd::auth_accounts::plan(provider, model, json)
                .await
                .map_err(anyhow::Error::msg)?,
            AuthAction::Use { provider, account } => {
                cmd::auth_accounts::use_account(provider, account)
                    .await
                    .map_err(anyhow::Error::msg)?
            }
            AuthAction::Remove {
                provider,
                account,
                yes,
            } => cmd::auth_accounts::remove(provider, account, yes).map_err(anyhow::Error::msg)?,
            AuthAction::Identify {
                provider,
                account,
                dry_run,
                force,
                json,
            } => cmd::auth_accounts::identify(cmd::auth_accounts::IdentifyOptions {
                provider,
                account,
                dry_run,
                force,
                json,
            })
            .await
            .map_err(anyhow::Error::msg)?,
            AuthAction::State {
                provider,
                account,
                json,
                clear,
            } => cmd::auth_accounts::state(
                cli.profile,
                cmd::auth_accounts::StateOptions {
                    provider,
                    account,
                    json,
                    clear,
                },
            )
            .await
            .map_err(anyhow::Error::msg)?,
        },
        Some(Command::Status {
            memory,
            json,
            pid,
            verbose,
            provider,
            account,
            all,
        }) => {
            if memory {
                cmd::status::run_memory(json, pid).map_err(|e| anyhow::anyhow!(e.to_string()))?;
            } else {
                // No flags == legacy `synaps status` (StatusOptions::default()).
                cmd::status::run_usage(cmd::status::StatusOptions {
                    provider,
                    account,
                    all,
                    json,
                    verbose,
                })
                .await
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
            }
        }
        Some(Command::QuotaKeeper(args)) => {
            cmd::quota_keeper::run(args)
                .await
                .map_err(|e| anyhow::anyhow!(e.to_string()))?;
        }
        Some(Command::AuthBroker {
            bind,
            machine_token,
            machine_token_file,
            insecure_no_auth,
            tls_cert,
            tls_key,
            insecure_http,
        }) => {
            cmd::auth_broker::run(
                bind,
                machine_token,
                machine_token_file,
                insecure_no_auth,
                tls_cert,
                tls_key,
                insecure_http,
            )
            .await?;
        }
        Some(Command::Completions { shell }) => {
            use clap::CommandFactory;
            let mut cmd = Cli::command();
            let name = cmd.get_name().to_string();
            clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
        }
        Some(Command::Prompt { .. }) => {
            unreachable!("prompt dispatched before profile initialization")
        }
        Some(Command::Tools { action }) => {
            cmd::tools::run(action).await?;
        }
        Some(Command::Trace { action }) => {
            cmd::trace::run(action)?;
        }
        Some(Command::Retention { action }) => {
            cmd::retention::run(action)?;
        }
        Some(Command::Daemon(args)) => {
            cmd::daemon::run(active_profile, args).await?;
        }
        Some(Command::Attach(args)) => {
            cmd::attach::run(active_profile, args, cli.client_name).await?;
        }
        Some(Command::Rpc {
            continue_id,
            system,
            model,
            profile,
        }) => {
            cmd::rpc::run(continue_id, system, model, profile).await?;
        }
        Some(Command::Send {
            message,
            source,
            severity,
            channel,
            content_type,
            session,
            broadcast,
            inbox,
        }) => {
            cmd::send::run(
                message,
                source,
                severity,
                channel,
                content_type,
                session,
                broadcast,
                inbox,
            )
            .await?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod worker_threads_tests {
    use super::{thin_client_from, worker_threads_from};

    fn v(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn thin_client_requires_daemon_flag() {
        use super::ThinClient::{Line, Tui};
        assert_eq!(thin_client_from(v(&["--attach"]), false, false), None);
        assert_eq!(thin_client_from(v(&["attach"]), false, false), None);
        assert_eq!(thin_client_from(v(&["--attach"]), true, false), Some(Tui { profile: None }));
        assert_eq!(thin_client_from(v(&["--attach=abc"]), true, false), Some(Tui { profile: None }));
        assert_eq!(thin_client_from(v(&["attach"]), true, false), Some(Line { profile: None }));
        assert_eq!(thin_client_from(v(&["--profile", "x", "attach"]), true, false), Some(Line { profile: Some("x".into()) }));
        assert_eq!(thin_client_from(v(&["--profile=x", "--attach", "--new"]), true, false), Some(Tui { profile: Some("x".into()) }));
        // bare `attach` is only the subcommand position, not a value elsewhere
        assert_eq!(thin_client_from(v(&["send", "attach"]), true, false), None);
        assert_eq!(thin_client_from(v(&["--profile", "attach"]), true, false), None);
        // `--attach` next to a subcommand is not the TUI attach path
        assert_eq!(thin_client_from(v(&["daemon", "status", "--attach"]), true, false), None);
        assert_eq!(thin_client_from(v(&[]), true, false), None);
    }

    #[test]
    fn thin_client_sniff_skips_option_values() {
        use super::ThinClient::{Line, Tui};
        let t = Some(Tui { profile: None });
        // value-taking options: their value is not a subcommand positional
        assert_eq!(thin_client_from(v(&["--attach", "--new", "--system", "/tmp/id.md"]), true, false), t);
        assert_eq!(thin_client_from(v(&["--attach", "--new", "-s", "you are x"]), true, false), t);
        assert_eq!(thin_client_from(v(&["--attach", "--new", "--name", "ambient"]), true, false), t);
        assert_eq!(thin_client_from(v(&["--attach", "--prompt-manifest", "m.toml"]), true, false), t);
        assert_eq!(thin_client_from(v(&["--system", "/tmp/id.md", "--attach", "--new"]), true, false), t);
        // optional-value options: next non-dash token is the value (clap num_args 0..=1)
        assert_eq!(thin_client_from(v(&["--attach", "abc"]), true, false), t);
        assert_eq!(thin_client_from(v(&["--attach", "--continue", "foo"]), true, false), t);
        assert_eq!(thin_client_from(v(&["--continue", "--attach"]), true, false), t);
        // a real positional after the option values still means "not the TUI attach path"
        assert_eq!(thin_client_from(v(&["--attach", "abc", "status"]), true, false), None);
        assert_eq!(thin_client_from(v(&["--system", "x", "daemon", "status"]), true, false), None);
        assert_eq!(thin_client_from(v(&["--system", "x", "attach"]), true, false), Some(Line { profile: None }));
        // the value itself may be a subcommand name — still a value
        assert_eq!(thin_client_from(v(&["--attach", "--name", "attach"]), true, false), t);
        assert_eq!(thin_client_from(v(&["--system", "attach"]), true, false), None);
    }

    #[test]
    fn thin_client_adopt_only_for_plain_tui_argv() {
        use super::ThinClient::{Adopt, Line, Tui};
        let a = Some(Adopt { profile: None });
        // plain TUI invocations adopt a running daemon
        assert_eq!(thin_client_from(v(&[]), true, true), a);
        assert_eq!(thin_client_from(v(&["--system", "/tmp/id.md"]), true, true), a);
        assert_eq!(thin_client_from(v(&["-s", "you are x"]), true, true), a);
        assert_eq!(thin_client_from(v(&["--continue"]), true, true), a);
        assert_eq!(thin_client_from(v(&["--continue", "foo", "--system", "x"]), true, true), a);
        assert_eq!(thin_client_from(v(&["--prompt-manifest", "m.toml"]), true, true), a);
        assert_eq!(
            thin_client_from(v(&["--profile", "x", "--system", "y"]), true, true),
            Some(Adopt { profile: Some("x".into()) })
        );
        // adopt off (SYNAPS_DAEMON_ADOPT=0) or daemon off → ordinary boot
        assert_eq!(thin_client_from(v(&[]), true, false), None);
        assert_eq!(thin_client_from(v(&[]), false, true), None);
        // explicit attach paths are unchanged by the adopt flag
        assert_eq!(thin_client_from(v(&["--attach", "--new"]), true, true), Some(Tui { profile: None }));
        assert_eq!(thin_client_from(v(&["attach"]), true, true), Some(Line { profile: None }));
        // any subcommand, or any flag outside the plain-TUI set, never adopts
        for argv in [
            &["daemon", "status"][..],
            &["chat", "-s", "x"],
            &["run"],
            &["--version"],
            &["-V"],
            &["--help"],
            &["--no-extensions"],
            &["--system", "x", "--no-extensions"],
            &["--observe"],
            &["--keep-warm"],
            &["--no-confirm-answers"],
            &["--new"],
            &["--name", "n"],
            &["--bogus"],
        ] {
            assert_eq!(thin_client_from(v(argv), true, true), None, "{argv:?}");
        }
    }

    #[test]
    fn attach_new_flag_combos() {
        use clap::Parser;
        let ok = super::Cli::try_parse_from(["synaps", "--attach", "--new"]).unwrap();
        assert!(ok.new_session && ok.attach.is_some());
        let alias = super::Cli::try_parse_from(["synaps", "--attach", "--create"]).unwrap();
        assert!(alias.new_session);
        // `--attach ID --new` parses; the attach path rejects the combination
        // (`choose_attach`: "cannot combine") so the message names both flags.
        let both = super::Cli::try_parse_from(["synaps", "--attach", "abc", "--new"]).unwrap();
        assert_eq!(both.attach.flatten().as_deref(), Some("abc"));
        assert!(both.new_session);
        // The line client's own --create/--new must not collide with the
        // top-level alias (clap's debug assert panics on duplicate longs).
        let line = super::Cli::try_parse_from(["synaps", "attach", "--create"]).unwrap();
        assert!(matches!(line.command, Some(super::Command::Attach(ref a)) if a.create));
        let line = super::Cli::try_parse_from(["synaps", "attach", "--new"]).unwrap();
        assert!(matches!(line.command, Some(super::Command::Attach(ref a)) if a.create));
        // --new without --attach is a clap error
        assert!(super::Cli::try_parse_from(["synaps", "--new"]).is_err());
        // --name rides on --attach (create or continue)
        let named = super::Cli::try_parse_from(["synaps", "--attach", "--new", "--name", "ambient"]).unwrap();
        assert_eq!(named.session_name.as_deref(), Some("ambient"));
        assert!(super::Cli::try_parse_from(["synaps", "--name", "ambient"]).is_err());
    }

    /// `--no-confirm-answers` rides on `--attach` (any mode) and is a
    /// clap error without it, so a binary that lacks it fails loudly.
    #[test]
    fn no_confirm_answers_flag_requires_attach() {
        use clap::Parser;
        let ok = super::Cli::try_parse_from([
            "synaps",
            "--attach",
            "abc",
            "--observe",
            "--no-confirm-answers",
        ])
        .unwrap();
        assert!(ok.no_confirm_answers && ok.observe);
        let take = super::Cli::try_parse_from([
            "synaps",
            "--no-confirm-answers",
            "--attach",
            "abc",
            "--takeover",
        ])
        .unwrap();
        assert!(take.no_confirm_answers && take.takeover);
        let plain = super::Cli::try_parse_from(["synaps", "--attach", "abc"]).unwrap();
        assert!(!plain.no_confirm_answers, "off by default");
        assert!(super::Cli::try_parse_from(["synaps", "--no-confirm-answers"]).is_err());
        assert_eq!(
            super::thin_client_from(v(&["--attach", "abc", "--no-confirm-answers"]), true, true),
            Some(super::ThinClient::Tui { profile: None })
        );
    }

    #[test]
    fn profile_must_be_the_one_in_effect() {
        use super::check_profile_applied as check;
        assert!(check(None, None).is_ok());
        // no flag: whatever SYNAPS_PROFILE latched is legitimate
        assert!(check(None, Some("work")).is_ok());
        assert!(check(Some("axon"), Some("axon")).is_ok());
        // the 0.10.1 incident: `--profile axon` but the default had latched
        let e = check(Some("axon"), None).unwrap_err().to_string();
        assert!(e.contains("--profile axon") && e.contains("`default`"), "{e}");
        assert!(check(Some("axon"), Some("work")).is_err());
    }

    #[test]
    fn thin_client_profile_is_rewritable_for_every_kind() {
        use super::ThinClient;
        for argv in [&["--profile", "axon"][..], &["--profile=axon", "--attach"], &["--profile", "axon", "attach"]] {
            let mut kind = thin_client_from(v(argv), true, true).expect("thin");
            assert_eq!(kind.profile_mut().as_deref(), Some("axon"), "{argv:?}");
            *kind.profile_mut() = Some("pinned".into());
            let profile = match kind {
                ThinClient::Tui { profile } | ThinClient::Line { profile } | ThinClient::Adopt { profile } => profile,
            };
            assert_eq!(profile.as_deref(), Some("pinned"));
        }
    }

    #[test]
    fn worker_threads_env_matrix() {
        assert_eq!(worker_threads_from(None, 24), Some(4));
        assert_eq!(worker_threads_from(None, 2), Some(2));
        assert_eq!(worker_threads_from(None, 0), Some(1));
        assert_eq!(worker_threads_from(Some("0"), 24), None);
        assert_eq!(worker_threads_from(Some("8"), 24), Some(8));
        assert_eq!(worker_threads_from(Some(" 3 "), 24), Some(3));
        assert_eq!(worker_threads_from(Some("bogus"), 24), Some(4));
    }
}