whetstone-cli 3.19.1

Installer and CLI for Claude Code token optimization (Headroom + RTK + Memory)
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
use std::env;
use std::process::Command;
use std::time::{Duration, Instant};

const DEFAULT_PROXY: &str = "http://127.0.0.1:8787";
const PROXY_READY_TIMEOUT: Duration = Duration::from_secs(15);
const PROXY_POLL_INTERVAL: Duration = Duration::from_millis(250);
const PROXY_PROBE_TIMEOUT: Duration = Duration::from_millis(800);

/// Seed a default `ANTHROPIC_BASE_URL` pointing at the anchor port, so a bare
/// `whetstone proxy` / `whetstone rtk` launch (which never calls
/// `select_proxy_port`) still has something sane to inherit. `wrap_claude`
/// overrides this per-session once it knows the actual port the registry
/// resolved to.
fn set_proxy_env() {
    if std::env::var("ANTHROPIC_BASE_URL").is_err() {
        std::env::set_var("ANTHROPIC_BASE_URL", DEFAULT_PROXY);
    }
}

// The env var headroom reads for a custom upstream Anthropic API URL (its
// `proxy --anthropic-api-url` flag mirrors this). Setting it here propagates to
// both the detached `headroom proxy` child and the exec'd `headroom wrap`.
const ANTHROPIC_TARGET_API_URL: &str = "ANTHROPIC_TARGET_API_URL";

/// Export a stored setting as `key` so a whetstone-spawned proxy *and* the
/// exec'd `headroom wrap claude` read the same value (for the savings profile
/// that agreement is what avoids wrap's "missing --savings-profile"
/// hot-restart). An externally-set env var wins over the stored setting.
fn apply_env_setting(key: &str, setting: Option<&str>) {
    if let Some(value) = resolve_env_setting(setting, env::var(key).ok()) {
        env::set_var(key, value);
    }
}

/// Pure resolution for [`apply_env_setting`]: an existing non-empty env
/// override takes precedence; otherwise a non-blank setting is used. `None`
/// means "leave the environment untouched".
fn resolve_env_setting(
    setting: Option<&str>,
    existing_env: Option<String>,
) -> Option<String> {
    if existing_env.is_some_and(|v| !v.trim().is_empty()) {
        return None;
    }
    setting
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

/// Export `ENABLE_TOOL_SEARCH=1` when the setting is on so Claude Code (launched
/// by the exec'd `headroom wrap claude`) turns on deferred-tool search. When
/// off, whetstone touches nothing, so any externally-set `ENABLE_TOOL_SEARCH`
/// passes through untouched. Not part of the proxy fingerprint — this is a
/// Claude Code concern, not a Headroom one.
fn apply_enable_tool_search(on: bool) {
    if on {
        env::set_var(ENABLE_TOOL_SEARCH_ENV, "1");
    }
}

pub fn wrap_claude(args: &[String], memory_flag: bool) -> ! {
    set_proxy_env();

    let (resolved, spec) = prepare_session(memory_flag);
    apply_enable_tool_search(resolved.enable_tool_search);

    // Drain any stray `.headroom` store this project accumulated before memory
    // was pinned to the global root. Idempotent no-op once clean. A remote
    // proxy keeps memory on its own host, so there is nothing local to drain.
    if spec.remote.is_none() {
        crate::memory_consolidate::auto_consolidate_cwd();
    }

    let want_memory = spec.memory;
    let selected = select_proxy_port(&spec);
    // An unreachable remote must not block a launch (think: laptop offline),
    // so it takes the same soft fallback as a failed local spawn.
    if selected.is_none() && spec.remote.is_some() {
        eprintln!(
            "[WARN] whetstone: using a local headroom proxy for this session"
        );
    }
    if let Some(port) = selected {
        env::set_var("ANTHROPIC_BASE_URL", format!("http://127.0.0.1:{port}"));
    }
    let proxy_ready = selected.is_some();
    let wrap_memory = if proxy_ready { false } else { want_memory };

    // An explicit `--model` suppresses the launch-time update prompt entirely;
    // otherwise offer any newer/new-family model and honor the user's choice.
    let user_set = user_set_model(args);
    let fallback = resolve_model(resolved.api_model.clone());
    let model_decision = if user_set {
        crate::model_update::ModelDecision::NoChange
    } else {
        crate::model_update::maybe_prompt(&resolved)
    };
    let model = choose_model(user_set, model_decision, &fallback);

    // Last word before exec: if the model we're about to launch is a pin the
    // models list has retired or superseded, say so. This is the path the
    // modal above can't cover — non-interactive launches, projects with no v3
    // manifest, dismissed ids, and pins whose family has gone entirely.
    crate::model_update::notify_pinned_model(
        &model,
        resolved.api_model.as_deref(),
        resolved.api_model_scope,
        user_set,
    );

    let cmd_args = build_claude_args(
        args,
        selected,
        wrap_memory,
        &model,
        resolved.permission_mode.as_deref(),
    );

    exec("headroom", &cmd_args);
}

/// Export the resolved launch environment (upstream URL, savings profile,
/// `HEADROOM_*` plan) and describe the proxy this session needs. Shared by
/// the launch path and by the commands that must find the same proxy
/// (`doctor`, `stats`).
fn prepare_session(
    memory_flag: bool,
) -> (
    crate::config::ResolvedSettings,
    crate::proxy_registry::ProxySpec,
) {
    let resolved = resolved_settings();
    apply_env_setting(
        ANTHROPIC_TARGET_API_URL,
        resolved.anthropic_api_url.as_deref(),
    );
    apply_env_setting(
        HEADROOM_SAVINGS_PROFILE_ENV,
        resolved.savings_profile.as_deref(),
    );

    let hr_plan = headroom_env_plan();
    warn_ignored_headroom_env(&hr_plan.ignored);
    for (key, value) in &hr_plan.apply {
        env::set_var(key, value);
    }

    let want_memory = memory_flag || resolved.headroom_memory;
    let spec = build_proxy_spec(&resolved, &hr_plan, want_memory);
    (resolved, spec)
}

/// The proxy spec a plain launch from this directory would use.
pub(crate) fn session_proxy_spec() -> crate::proxy_registry::ProxySpec {
    prepare_session(false).1
}

/// The local port of this directory's proxy, bringing it (or its tunnel) up
/// if needed.
pub(crate) fn session_proxy_port() -> Option<u16> {
    select_proxy_port(&session_proxy_spec())
}

/// Testable core: assemble a `ProxySpec` from resolved inputs + the apply set.
fn build_proxy_spec_from(
    savings_profile: String,
    telemetry: bool,
    memory: bool,
    anthropic_api_url: Option<String>,
    apply: &[(String, String)],
    remote: Option<String>,
) -> crate::proxy_registry::ProxySpec {
    let env = apply
        .iter()
        .filter(|(k, _)| k != "HEADROOM_MEMORY_DB_PATH")
        .cloned()
        .collect();
    crate::proxy_registry::ProxySpec {
        savings_profile,
        telemetry,
        memory,
        anthropic_api_url: anthropic_api_url.filter(|s| !s.trim().is_empty()),
        env,
        remote,
    }
}

/// Production wrapper: reads live settings, the applied env plan, and the
/// effective upstream URL.
fn build_proxy_spec(
    resolved: &crate::config::ResolvedSettings,
    hr_plan: &crate::headroom_env::HeadroomEnvPlan,
    memory: bool,
) -> crate::proxy_registry::ProxySpec {
    build_proxy_spec_from(
        required_savings_profile(),
        resolved.headroom_telemetry,
        memory,
        env::var(ANTHROPIC_TARGET_API_URL).ok(),
        &hr_plan.apply,
        resolved.headroom_remote.clone(),
    )
}

/// Lock the registry, reconcile it against the running proxies, and return the
/// port this session should use (spawning one if needed). Falls back to `None`
/// so the caller can let `headroom wrap` try its own proxy.
fn select_proxy_port(spec: &crate::proxy_registry::ProxySpec) -> Option<u16> {
    use crate::proxy_registry as reg;
    let path = reg::registry_path()?;
    let lock_path = path.with_extension("lock");
    // Lock window must outlast a full readiness wait.
    let _guard = reg::acquire_lock(&lock_path, Duration::from_secs(60)).ok()?;

    let mut registry = reg::Registry::load(&path);
    let probe = |p: u16| probe_port(p);
    let port_free = |p: u16| free_port_is_bindable(p);
    let free = || free_port();
    let spawn = |p: u16| match &spec.remote {
        Some(dest) => spawn_remote_tunnel(dest, spec, p),
        None => spawn_proxy_ready(p, spec.memory),
    };
    let deps = reg::ResolveDeps {
        probe: &probe,
        port_free: &port_free,
        free_port: &free,
        spawn: &spawn,
        alive: &pid_alive,
        reap: &reg::kill_entry,
        now: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs()),
        // `exec` keeps the pid, so this is the session's pid too.
        session: std::process::id(),
    };

    let outcome = reg::resolve(&mut registry, spec, &deps);
    if let Err(e) = registry.save(&path) {
        crate::ui::warn(&format!(
            "could not persist proxy registry ({e}); a spawned proxy may be untracked"
        ));
    }
    match outcome {
        reg::ProxyOutcome::Reused(p) | reg::ProxyOutcome::Spawned(p) => Some(p),
        reg::ProxyOutcome::Failed => None,
    }
}

/// Can we bind this specific port right now?
fn free_port_is_bindable(port: u16) -> bool {
    std::net::TcpListener::bind(("127.0.0.1", port)).is_ok()
}

pub(crate) fn resolved_settings() -> crate::config::ResolvedSettings {
    let global = crate::config::GlobalSettings::load().unwrap_or_default();
    let cwd = env::current_dir().ok();
    let project = cwd
        .map(|d| crate::config::WhetstoneManifest::path_for(&d))
        .and_then(|p| crate::config::WhetstoneManifest::load(&p).ok().flatten())
        .map(|m| m.settings)
        .unwrap_or_default();
    crate::config::ResolvedSettings::resolve(&global, &project)
}

/// The memory provider recorded in this project's manifest, or `Skip` when
/// there is no manifest — used to gate Headroom's built-in memory tools.
fn resolved_provider() -> crate::config::ProviderTag {
    let cwd = env::current_dir().ok();
    cwd.map(|d| crate::config::WhetstoneManifest::path_for(&d))
        .and_then(|p| crate::config::WhetstoneManifest::load(&p).ok().flatten())
        .map(|m| m.provider)
        .unwrap_or(crate::config::ProviderTag::Skip)
}

/// Testable core: build the launch-env plan from resolved settings +
/// provider + an env-presence probe.
fn headroom_env_plan_for(
    resolved: &crate::config::ResolvedSettings,
    provider: crate::config::ProviderTag,
    memory_db_path: Option<&str>,
    env_has: impl Fn(&str) -> bool,
) -> crate::headroom_env::HeadroomEnvPlan {
    crate::headroom_env::build_headroom_env(
        &resolved.headroom_env,
        provider,
        memory_db_path,
        env_has,
    )
}

/// Production wrapper: reads live settings + real process env.
fn headroom_env_plan() -> crate::headroom_env::HeadroomEnvPlan {
    let resolved = resolved_settings();
    let provider = resolved_provider();
    let db_path = crate::memory_consolidate::global_memory_db_path();
    let db_path = db_path.as_deref().map(|p| p.to_string_lossy().to_string());
    headroom_env_plan_for(&resolved, provider, db_path.as_deref(), |k| {
        env::var_os(k).is_some()
    })
}

/// Warn once per key in `headroom_env` that whetstone refuses to export.
fn warn_ignored_headroom_env(ignored: &[String]) {
    for key in ignored {
        eprintln!(
            "[WARN] whetstone: ignoring {key:?} in headroom_env \
             (only HEADROOM_* names are exported, and not HEADROOM_PORT)"
        );
    }
}

fn probe_port(port: u16) -> bool {
    let url = format!("http://127.0.0.1:{port}/health");
    ureq::get(&url)
        .config()
        .timeout_global(Some(PROXY_PROBE_TIMEOUT))
        .build()
        .call()
        .is_ok()
}

fn probe_proxy() -> bool {
    probe_port(crate::proxy_registry::ANCHOR_PORT)
}

/// Spawn a proxy on `port` and poll until it answers or times out. Returns the
/// child pid on success (read back from the port's own report is unnecessary —
/// we return the spawned pid), else `None`.
fn spawn_proxy_ready(port: u16, memory: bool) -> Option<u32> {
    let pid = spawn_proxy_detached_pid(&port.to_string(), memory)?;
    if wait_for_port(port) {
        return Some(pid);
    }
    eprintln!(
        "[WARN] whetstone: proxy on 127.0.0.1:{port} did not respond in time"
    );
    None
}

/// Is a process with this pid running? (Signal 0 only checks.)
fn pid_alive(pid: u32) -> bool {
    Command::new("kill")
        .args(["-0", &pid.to_string()])
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

fn wait_for_port(port: u16) -> bool {
    let deadline = Instant::now() + PROXY_READY_TIMEOUT;
    while Instant::now() < deadline {
        if probe_port(port) {
            return true;
        }
        std::thread::sleep(PROXY_POLL_INTERVAL);
    }
    false
}

/// Remote counterpart of [`spawn_proxy_ready`]: make sure the proxy for
/// `spec` runs on `dest`, then tunnel local `port` to it. Returns the ssh
/// tunnel's pid, or `None` (after saying why) when the host can't serve.
fn spawn_remote_tunnel(
    dest: &str,
    spec: &crate::proxy_registry::ProxySpec,
    port: u16,
) -> Option<u32> {
    let remote_port = match crate::remote::ensure_proxy(dest, spec) {
        Ok(remote_port) => remote_port,
        Err(e) => {
            eprintln!("[WARN] whetstone: remote headroom unavailable ({e:#})");
            return None;
        }
    };
    let pid = crate::remote::open_tunnel(dest, port, remote_port)?;
    if wait_for_port(port) {
        return Some(pid);
    }
    // Our own child, spawned a moment ago: this pid cannot have been reused.
    let _ = Command::new("kill").arg(pid.to_string()).status();
    eprintln!("[WARN] whetstone: ssh tunnel to {dest} did not come up");
    None
}

fn spawn_proxy_detached_pid(port: &str, memory: bool) -> Option<u32> {
    use std::process::Stdio;
    let telemetry_disabled = !headroom_telemetry_enabled();
    let args = build_proxy_args(
        port,
        headroom_proxy_flag_support(),
        telemetry_disabled,
        memory,
    );
    let mut cmd = Command::new("headroom");
    cmd.args(&args)
        .env("HEADROOM_SAVINGS_PROFILE", required_savings_profile())
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    if telemetry_disabled {
        cmd.env("HEADROOM_TELEMETRY", "off");
    }

    // NOTE: keys that `wrap_claude` already exported via `env::set_var`
    // (or that the user exported externally) are seen as present here and so
    // are omitted from `apply` — they reach the child through normal env
    // inheritance instead. This is what preserves the external-env-wins
    // precedence. Do NOT add `.env_clear()` to this Command: it would drop
    // those inherited overrides while leaving the exec sink intact.
    let hr_plan = headroom_env_plan();
    for (key, value) in &hr_plan.apply {
        cmd.env(key, value);
    }

    let child = cmd.spawn().ok()?;
    Some(child.id())
}

/// Verdict from [`check_proxy_starts`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ProxyStartCheck {
    /// A proxy is already answering on the whetstone port — the strongest
    /// possible evidence that headroom starts.
    AlreadyRunning,
    /// A throwaway proxy got past startup validation.
    Starts,
    /// The proxy exited during startup. `detail` is headroom's own complaint.
    Failed { detail: String },
}

/// How long a smoke-test proxy gets to prove it survives startup. Startup
/// *validation* failures (a rejected flag, a missing dependency, a bad config)
/// are immediate; a healthy proxy takes longer than this to serve traffic, so
/// "still running at the deadline" is the pass condition, not "/health said
/// yes".
const PROXY_SMOKE_TIMEOUT: Duration = Duration::from_secs(6);

/// Actually try to start headroom.
///
/// Installed, right version, right extras — and still dead on arrival, because
/// something in headroom's own `settings.json` asks for a flag the current
/// rollout channel rejects. Nothing whetstone inspected could see that; only
/// running the thing can. Uses the same args and env whetstone launches the
/// real proxy with, on a throwaway port so a live proxy is never disturbed.
pub(crate) fn check_proxy_starts() -> ProxyStartCheck {
    if probe_proxy() {
        return ProxyStartCheck::AlreadyRunning;
    }
    smoke_start_proxy("headroom", PROXY_SMOKE_TIMEOUT)
}

/// Spawn half of [`check_proxy_starts`], with the program and grace window
/// passed in so the observe logic can be tested against a stub instead of a
/// real headroom (and without depending on whether a proxy happens to be up).
fn smoke_start_proxy(program: &str, grace: Duration) -> ProxyStartCheck {
    use std::process::Stdio;

    let port = match free_port() {
        Some(port) => port.to_string(),
        None => {
            return ProxyStartCheck::Failed {
                detail: "could not reserve a local port for the smoke test"
                    .into(),
            }
        }
    };

    let telemetry_disabled = !headroom_telemetry_enabled();
    let args = build_proxy_args(
        &port,
        headroom_proxy_flag_support(),
        telemetry_disabled,
        false,
    );

    let mut cmd = Command::new(program);
    cmd.args(&args)
        .env("HEADROOM_SAVINGS_PROFILE", required_savings_profile())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    if telemetry_disabled {
        cmd.env("HEADROOM_TELEMETRY", "off");
    }
    for (key, value) in &headroom_env_plan().apply {
        cmd.env(key, value);
    }

    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            return ProxyStartCheck::Failed {
                detail: format!("could not spawn `headroom proxy`: {e}"),
            }
        }
    };

    let deadline = Instant::now() + grace;
    loop {
        match child.try_wait() {
            Ok(Some(_)) => {
                let output = child.wait_with_output().ok();
                let (stdout, stderr) = output
                    .map(|o| {
                        (
                            String::from_utf8_lossy(&o.stdout).to_string(),
                            String::from_utf8_lossy(&o.stderr).to_string(),
                        )
                    })
                    .unwrap_or_default();
                return ProxyStartCheck::Failed {
                    detail: summarize_startup_failure(&stdout, &stderr),
                };
            }
            Ok(None) if Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                return ProxyStartCheck::Starts;
            }
            Ok(None) => std::thread::sleep(PROXY_POLL_INTERVAL),
            Err(e) => {
                let _ = child.kill();
                return ProxyStartCheck::Failed {
                    detail: format!("could not wait on `headroom proxy`: {e}"),
                };
            }
        }
    }
}

/// Ask the OS for an unused local port, then let go of it. The window between
/// releasing and headroom binding is a theoretical race; losing it just makes
/// one doctor run report a bind failure.
fn free_port() -> Option<u16> {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").ok()?;
    let port = listener.local_addr().ok()?.port();
    drop(listener);
    Some(port)
}

/// Boil headroom's startup output down to the line that explains the failure.
/// Prefers an explicit error line; falls back to the last thing it said.
/// Library chatter on stderr (the transformers/PyTorch notice) is dropped —
/// it is present on healthy runs too and would bury the real message.
fn summarize_startup_failure(stdout: &str, stderr: &str) -> String {
    let lines: Vec<&str> = stderr
        .lines()
        .chain(stdout.lines())
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .filter(|line| !is_startup_noise(line))
        .collect();

    lines
        .iter()
        .find(|line| {
            let lower = line.to_lowercase();
            lower.starts_with("error") || lower.contains("error:")
        })
        .or_else(|| lines.last())
        .map(|line| line.to_string())
        .unwrap_or_else(|| "exited during startup with no output".into())
}

fn is_startup_noise(line: &str) -> bool {
    line.starts_with("[transformers]") || line.contains("PyTorch was not found")
}

fn build_proxy_args(
    port: &str,
    flags: ProxyFlagSupport,
    no_telemetry: bool,
    memory: bool,
) -> Vec<&str> {
    let mut args = vec!["proxy", "--port", port];
    if flags.savings_profile {
        args.push("--savings-profile");
    }
    if no_telemetry {
        args.push("--no-telemetry");
    }
    if memory {
        args.push("--memory");
    }
    // Headroom throttles requests through the proxy by default. A whetstone
    // proxy only ever serves local Claude Code sessions, which the upstream
    // API already rate-limits, so the extra limiter adds nothing but 429s.
    if flags.no_rate_limit {
        args.push("--no-rate-limit");
    }
    args
}

fn headroom_telemetry_enabled() -> bool {
    resolved_settings().headroom_telemetry
}

// The savings profile `headroom wrap claude` requires (headroom
// `cli/wrap.py` `_DEFAULT_AGENT_SAVINGS_PROFILE`). The proxy must report this
// profile via `/health`, or `headroom wrap claude` decides it is "missing:
// --savings-profile", hot-restarts it, and crashes binding the port before
// the old proxy releases it ([Errno 98]). The proxy reads the profile from
// the `HEADROOM_SAVINGS_PROFILE` env var, not a CLI flag, in current headroom.
const DEFAULT_SAVINGS_PROFILE: &str = "agent-90";

// The env var headroom reads for the savings profile. Whetstone owns this key
// (see `headroom_env::RESERVED_OWNED`): `apply_savings_profile` exports the
// configured setting here, and both the spawned proxy and exec'd wrap read it.
const HEADROOM_SAVINGS_PROFILE_ENV: &str = "HEADROOM_SAVINGS_PROFILE";

// The env var Claude Code reads to turn on deferred-tool search.
const ENABLE_TOOL_SEARCH_ENV: &str = "ENABLE_TOOL_SEARCH";

fn required_savings_profile() -> String {
    resolve_savings_profile(env::var(HEADROOM_SAVINGS_PROFILE_ENV).ok())
}

// Honor an existing override (matching what `headroom wrap claude` will read),
// falling back to headroom's default so a whetstone-spawned proxy always
// matches the profile wrap demands.
fn resolve_savings_profile(override_value: Option<String>) -> String {
    override_value
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| DEFAULT_SAVINGS_PROFILE.to_string())
}

/// Which optional `headroom proxy` flags the installed headroom accepts.
/// Passing a flag an older headroom rejects kills the proxy at startup, so
/// every optional flag is gated on this probe.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct ProxyFlagSupport {
    savings_profile: bool,
    no_rate_limit: bool,
}

/// Probe headroom once per launch and answer for every optional flag at
/// the same time — one `headroom proxy --help` subprocess, not one per flag.
fn headroom_proxy_flag_support() -> ProxyFlagSupport {
    let Some(output) = Command::new("headroom")
        .args(["proxy", "--help"])
        .output()
        .ok()
    else {
        return ProxyFlagSupport::default();
    };

    let help = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    proxy_flag_support_from_help(&help)
}

fn proxy_flag_support_from_help(help: &str) -> ProxyFlagSupport {
    ProxyFlagSupport {
        savings_profile: proxy_help_mentions_flag(help, "--savings-profile"),
        no_rate_limit: proxy_help_mentions_flag(help, "--no-rate-limit"),
    }
}

fn proxy_help_mentions_flag(help_text: &str, flag: &str) -> bool {
    help_text.contains(flag)
}

// Pinned fallback model — used only when the user hasn't selected one AND we
// can't reach the models API to detect a newer Opus (offline / no
// ANTHROPIC_API_KEY). If the user (or a wrapping CLI layer) already passes
// `--model`, we leave it alone. Keep this at the current flagship Opus: it is
// the model a credential-less launch boots with, so a stale value here is the
// one way whetstone can quietly start an old model.
pub(crate) const DEFAULT_MODEL: &str = "claude-opus-5-5";

// Resolve the model to launch with, in priority order:
//   1. an explicit selection stored in whetstone settings (`api_model`)
//   2. the newest available Opus, per the 12h-cached models API
//   3. the pinned `DEFAULT_MODEL` fallback
fn resolve_model(explicit: Option<String>) -> String {
    explicit
        .or_else(crate::settings::preferred_default_model)
        .unwrap_or_else(|| DEFAULT_MODEL.to_string())
}

// Fold the launch-time model-update decision into a concrete model id. An
// explicit `--model` on the command line always wins, so `user_set` short-
// circuits to the resolved fallback and the prompt's decision is ignored.
fn choose_model(
    user_set: bool,
    decision: crate::model_update::ModelDecision,
    fallback: &str,
) -> String {
    use crate::model_update::ModelDecision;
    if user_set {
        return fallback.to_string();
    }
    match decision {
        ModelDecision::UsePinned(m) | ModelDecision::UseSession(m) => m,
        ModelDecision::NoChange => fallback.to_string(),
    }
}

fn build_claude_args(
    args: &[String],
    proxy_port: Option<u16>,
    wrap_memory: bool,
    model: &str,
    permission_mode: Option<&str>,
) -> Vec<String> {
    let mut cmd_args = vec!["wrap".to_string(), "claude".to_string()];

    // When whetstone owns the proxy, tell wrap both to skip starting one
    // (`--no-proxy`) AND which port to point Claude at (`--port`). `wrap`
    // always re-derives `ANTHROPIC_BASE_URL` from `--port` (default 8787), so
    // without the port a per-config proxy on a fresh port is spawned but never
    // used — Claude keeps talking to 8787.
    if let Some(port) = proxy_port {
        cmd_args.push("--no-proxy".into());
        cmd_args.push("--port".into());
        cmd_args.push(port.to_string());
    }

    // Newer headroom spells this `--code-memory none`, but keeps `--no-serena`
    // as a hidden alias. The old spelling is the one both sides of our
    // supported version floor understand, so keep emitting it.
    cmd_args.push("--no-serena".into());

    // Only when whetstone is *not* managing the proxy itself — wrap brings up
    // its own session-bound proxy and needs `--memory` to enable it there.
    if wrap_memory {
        cmd_args.push("--memory".into());
    }

    if !user_set_model(args) {
        cmd_args.push("--model".into());
        cmd_args.push(model.into());
    }

    // Inject the configured Claude Code edit mode unless the user passed their
    // own `--permission-mode` (which always wins, like `--model`).
    if let Some(mode) = permission_mode {
        if !user_set_permission_mode(args) {
            cmd_args.push("--permission-mode".into());
            cmd_args.push(mode.into());
        }
    }

    // Claude Code ranks settings files above the process env, so a stale
    // `env.ANTHROPIC_BASE_URL` (e.g. left in `.claude/settings.local.json` by
    // `headroom init`) silently routes past the proxy whetstone picked — a
    // remote tunnel included. `--settings` outranks every file but managed
    // policy. A user's own `--settings` wins, like `--model`.
    if let Some(port) = proxy_port {
        if !user_set_settings(args) {
            cmd_args.push("--settings".into());
            cmd_args.push(format!(
                r#"{{"env":{{"ANTHROPIC_BASE_URL":"http://127.0.0.1:{port}"}}}}"#
            ));
        }
    }

    cmd_args.extend_from_slice(args);
    cmd_args
}

// Whether the user passed an explicit `--model` on the command line.
fn user_set_model(args: &[String]) -> bool {
    args.iter()
        .any(|a| a == "--model" || a.starts_with("--model="))
}

// Whether the user passed their own `--settings` on the command line.
fn user_set_settings(args: &[String]) -> bool {
    args.iter()
        .any(|a| a == "--settings" || a.starts_with("--settings="))
}

// Whether the user passed an explicit `--permission-mode` on the command line.
fn user_set_permission_mode(args: &[String]) -> bool {
    args.iter().any(|a| {
        a == "--permission-mode" || a.starts_with("--permission-mode=")
    })
}

pub fn wrap_proxy(args: &[String], memory: bool) -> ! {
    set_proxy_env();

    // An explicit `whetstone proxy` asks for a foreground proxy here; say so
    // when sessions in this project would use a different machine.
    if let Some(dest) = resolved_settings().headroom_remote {
        eprintln!(
            "[WARN] whetstone: this project uses a remote headroom ({dest}); \
             `whetstone proxy` still starts a local one"
        );
    }

    // A standalone `whetstone proxy` launches Headroom directly, so it gets
    // the same opinionated defaults + `headroom_env` overrides as the bare
    // `whetstone` / `whetstone claude` paths. exec inherits process env.
    let hr_plan = headroom_env_plan();
    warn_ignored_headroom_env(&hr_plan.ignored);
    for (key, value) in &hr_plan.apply {
        env::set_var(key, value);
    }

    let mut proxy_args = vec!["proxy".to_string()];
    if memory && !args.iter().any(|a| a == "--memory") {
        proxy_args.push("--memory".into());
    }
    // Same reasoning as `build_proxy_args`: no limiter in front of a local
    // proxy. Skipped when the caller already spelled it out themselves.
    if headroom_proxy_flag_support().no_rate_limit
        && !args.iter().any(|a| a == "--no-rate-limit")
    {
        proxy_args.push("--no-rate-limit".into());
    }
    proxy_args.extend_from_slice(args);
    exec("headroom", &proxy_args);
}

pub fn wrap_rtk(args: &[String]) -> ! {
    set_proxy_env();
    exec("rtk", args);
}

#[cfg(unix)]
fn exec(program: &str, args: &[String]) -> ! {
    use std::os::unix::process::CommandExt;
    crate::tools::ensure_available(program);
    let err = Command::new(program).args(args).exec();
    eprintln!("[FAIL] failed to exec {program}: {err}");
    std::process::exit(127);
}

#[cfg(not(unix))]
fn exec(program: &str, args: &[String]) -> ! {
    crate::tools::ensure_available(program);
    let status =
        Command::new(program)
            .args(args)
            .status()
            .unwrap_or_else(|e| {
                eprintln!("[FAIL] failed to run {program}: {e}");
                std::process::exit(127);
            });
    std::process::exit(status.code().unwrap_or(1));
}

#[cfg(test)]
mod tests {
    use super::*;

    fn strings(values: &[&str]) -> Vec<String> {
        values.iter().map(|value| (*value).to_string()).collect()
    }

    #[test]
    fn plan_from_settings_applies_code_aware() {
        let resolved = crate::config::ResolvedSettings {
            headroom_telemetry: false,
            headroom_memory: false,
            api_model: None,
            api_model_scope: None,
            anthropic_api_url: None,
            permission_mode: None,
            savings_profile: None,
            enable_tool_search: false,
            headroom_remote: None,
            headroom_env: std::collections::BTreeMap::new(),
        };
        let plan = headroom_env_plan_for(
            &resolved,
            crate::config::ProviderTag::Skip,
            None,
            |_| false,
        );
        assert!(plan
            .apply
            .contains(&("HEADROOM_CODE_AWARE_ENABLED".into(), "1".into())));
    }

    #[test]
    fn plan_pins_global_memory_db_path() {
        let resolved = crate::config::ResolvedSettings {
            headroom_telemetry: false,
            headroom_memory: false,
            api_model: None,
            api_model_scope: None,
            anthropic_api_url: None,
            permission_mode: None,
            savings_profile: None,
            enable_tool_search: false,
            headroom_remote: None,
            headroom_env: std::collections::BTreeMap::new(),
        };
        let plan = headroom_env_plan_for(
            &resolved,
            crate::config::ProviderTag::Skip,
            Some("/home/u/.headroom/memory.db"),
            |_| false,
        );
        assert!(plan.apply.contains(&(
            "HEADROOM_MEMORY_DB_PATH".into(),
            "/home/u/.headroom/memory.db".into()
        )));
    }

    #[test]
    fn build_proxy_spec_excludes_memory_db_path() {
        use std::collections::BTreeMap;
        let mut apply = vec![
            ("HEADROOM_CODE_AWARE_ENABLED".to_string(), "1".to_string()),
            (
                "HEADROOM_MEMORY_DB_PATH".to_string(),
                "/home/u/.headroom/memory.db".to_string(),
            ),
        ];
        // Sorted apply set is fine; the helper filters by key.
        apply.sort();
        let spec = build_proxy_spec_from(
            "agent-90".to_string(),
            true, // telemetry
            true, // memory
            Some("https://up.test".to_string()),
            &apply,
            Some("me@box".to_string()),
        );
        assert_eq!(spec.remote.as_deref(), Some("me@box"));
        assert_eq!(spec.savings_profile, "agent-90");
        assert!(spec.telemetry);
        assert!(spec.memory);
        assert_eq!(spec.anthropic_api_url.as_deref(), Some("https://up.test"));
        assert!(spec.env.contains_key("HEADROOM_CODE_AWARE_ENABLED"));
        assert!(!spec.env.contains_key("HEADROOM_MEMORY_DB_PATH"));
        let _ = BTreeMap::<String, String>::new();
    }

    #[test]
    fn resolve_env_setting_uses_setting_when_env_unset() {
        assert_eq!(
            resolve_env_setting(Some("https://proxy.example"), None),
            Some("https://proxy.example".to_string())
        );
    }

    #[test]
    fn resolve_env_setting_env_override_wins() {
        assert_eq!(
            resolve_env_setting(
                Some("https://setting.example"),
                Some("https://env.example".to_string())
            ),
            None
        );
    }

    #[test]
    fn resolve_env_setting_ignores_blank_setting() {
        assert_eq!(resolve_env_setting(Some("   "), None), None);
        assert_eq!(resolve_env_setting(None, None), None);
    }

    #[test]
    fn resolve_env_setting_ignores_blank_env_override() {
        assert_eq!(
            resolve_env_setting(
                Some("https://setting.example"),
                Some("  ".to_string())
            ),
            Some("https://setting.example".to_string())
        );
    }

    #[test]
    fn resolve_model_prefers_explicit_selection() {
        assert_eq!(
            resolve_model(Some("claude-sonnet-5".to_string())),
            "claude-sonnet-5"
        );
    }

    #[test]
    fn choose_model_uses_pinned_when_offered() {
        let decision = crate::model_update::ModelDecision::UsePinned(
            "claude-opus-5".into(),
        );
        assert_eq!(choose_model(false, decision, "fallback"), "claude-opus-5");
    }

    #[test]
    fn choose_model_uses_session_when_offered() {
        let decision = crate::model_update::ModelDecision::UseSession(
            "claude-opus-5".into(),
        );
        assert_eq!(choose_model(false, decision, "fallback"), "claude-opus-5");
    }

    #[test]
    fn choose_model_falls_back_on_no_change() {
        let decision = crate::model_update::ModelDecision::NoChange;
        assert_eq!(choose_model(false, decision, "fallback"), "fallback");
    }

    #[test]
    fn choose_model_ignores_decision_when_user_set() {
        let decision = crate::model_update::ModelDecision::UsePinned(
            "claude-opus-5".into(),
        );
        assert_eq!(choose_model(true, decision, "fallback"), "fallback");
    }

    #[test]
    fn build_claude_args_injects_default_model_when_absent() {
        let args = build_claude_args(&[], None, false, DEFAULT_MODEL, None);

        assert_eq!(
            args,
            strings(&[
                "wrap",
                "claude",
                "--no-serena",
                "--model",
                DEFAULT_MODEL,
            ])
        );
    }

    #[test]
    fn build_claude_args_preserves_explicit_model() {
        let args = build_claude_args(
            &["--model".into(), "claude-sonnet".into()],
            None,
            false,
            DEFAULT_MODEL,
            None,
        );

        assert_eq!(
            args,
            strings(&[
                "wrap",
                "claude",
                "--no-serena",
                "--model",
                "claude-sonnet"
            ])
        );
        assert_eq!(args.iter().filter(|a| a.as_str() == "--model").count(), 1);
    }

    #[test]
    fn build_claude_args_preserves_explicit_model_equals_form() {
        let args = build_claude_args(
            &["--model=claude-sonnet".into()],
            None,
            false,
            DEFAULT_MODEL,
            None,
        );

        assert_eq!(
            args,
            strings(&[
                "wrap",
                "claude",
                "--no-serena",
                "--model=claude-sonnet"
            ])
        );
    }

    #[test]
    fn build_claude_args_passes_through_arbitrary_args_unchanged() {
        let args = build_claude_args(
            &["--dangerously-skip-permissions".into(), "--print".into()],
            None,
            false,
            DEFAULT_MODEL,
            None,
        );

        assert_eq!(
            args,
            strings(&[
                "wrap",
                "claude",
                "--no-serena",
                "--model",
                DEFAULT_MODEL,
                "--dangerously-skip-permissions",
                "--print",
            ])
        );
    }

    #[test]
    fn build_claude_args_uses_configured_model() {
        let args =
            build_claude_args(&[], None, false, "claude-sonnet-4-6", None);

        assert_eq!(
            args,
            strings(&[
                "wrap",
                "claude",
                "--no-serena",
                "--model",
                "claude-sonnet-4-6"
            ])
        );
    }

    #[test]
    fn build_claude_args_injects_permission_mode_when_configured() {
        let args = build_claude_args(
            &[],
            None,
            false,
            DEFAULT_MODEL,
            Some("acceptEdits"),
        );
        assert_eq!(
            args,
            strings(&[
                "wrap",
                "claude",
                "--no-serena",
                "--model",
                DEFAULT_MODEL,
                "--permission-mode",
                "acceptEdits",
            ])
        );
    }

    #[test]
    fn build_claude_args_omits_permission_mode_when_none() {
        let args = build_claude_args(&[], None, false, DEFAULT_MODEL, None);
        assert!(!args.contains(&"--permission-mode".to_string()));
    }

    #[test]
    fn build_claude_args_preserves_explicit_permission_mode() {
        let args = build_claude_args(
            &["--permission-mode".into(), "plan".into()],
            None,
            false,
            DEFAULT_MODEL,
            Some("acceptEdits"),
        );
        assert_eq!(
            args.iter()
                .filter(|a| a.as_str() == "--permission-mode")
                .count(),
            1
        );
        assert!(args.contains(&"plan".to_string()));
        assert!(!args.contains(&"acceptEdits".to_string()));
    }

    #[test]
    fn build_claude_args_preserves_explicit_permission_mode_equals_form() {
        let args = build_claude_args(
            &["--permission-mode=plan".into()],
            None,
            false,
            DEFAULT_MODEL,
            Some("acceptEdits"),
        );
        assert!(args.contains(&"--permission-mode=plan".to_string()));
        assert!(!args.contains(&"acceptEdits".to_string()));
    }

    /// Write an executable stub that stands in for `headroom proxy`.
    #[cfg(unix)]
    fn stub_binary(dir: &std::path::Path, body: &str) -> std::path::PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let path = dir.join("fake-headroom");
        std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
            .unwrap();
        path
    }

    #[cfg(unix)]
    #[test]
    fn smoke_reports_failure_when_the_proxy_exits_during_startup() {
        // The read-maturation case: headroom rejects its own flag and dies
        // before serving anything.
        let dir = tempfile::tempdir().unwrap();
        let stub = stub_binary(
            dir.path(),
            "echo '[transformers] PyTorch was not found.' >&2\n             echo 'error: --read-maturation is not available in the current              rollout channel (stable).' >&2\n             exit 1",
        );

        let result =
            smoke_start_proxy(stub.to_str().unwrap(), Duration::from_secs(5));

        match result {
            ProxyStartCheck::Failed { detail } => {
                assert!(
                    detail.contains("--read-maturation"),
                    "expected headroom's own error, got: {detail}"
                );
                assert!(
                    !detail.contains("transformers"),
                    "library chatter should be filtered, got: {detail}"
                );
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn smoke_passes_when_the_proxy_survives_startup() {
        let dir = tempfile::tempdir().unwrap();
        let stub = stub_binary(dir.path(), "sleep 30");

        assert_eq!(
            smoke_start_proxy(
                stub.to_str().unwrap(),
                Duration::from_millis(600)
            ),
            ProxyStartCheck::Starts,
        );
    }

    #[test]
    fn smoke_reports_failure_when_the_binary_cannot_be_spawned() {
        let result = smoke_start_proxy(
            "/nonexistent/definitely-not-headroom",
            Duration::from_millis(200),
        );
        match result {
            ProxyStartCheck::Failed { detail } => {
                assert!(detail.contains("could not spawn"), "got: {detail}")
            }
            other => panic!("expected Failed, got {other:?}"),
        }
    }

    #[test]
    fn startup_failure_prefers_the_error_line() {
        let stderr = "[transformers] PyTorch was not found. Models won't be \
                      available.\nerror: --read-maturation is not available in \
                      the current rollout channel (stable).\n";
        assert_eq!(
            summarize_startup_failure("", stderr),
            "error: --read-maturation is not available in the current rollout \
             channel (stable).",
        );
    }

    #[test]
    fn startup_failure_ignores_library_chatter() {
        // The transformers notice appears on healthy runs too; reporting it as
        // the failure would send the user chasing the wrong thing.
        let stderr = "[transformers] PyTorch was not found.\n\
                      Error: Proxy dependencies not installed. Run: pip \
                      install headroom-ai[proxy]\n";
        assert_eq!(
            summarize_startup_failure("", stderr),
            "Error: Proxy dependencies not installed. Run: pip install \
             headroom-ai[proxy]",
        );
    }

    #[test]
    fn startup_failure_falls_back_to_the_last_line() {
        assert_eq!(
            summarize_startup_failure("starting up\nbind failed\n", ""),
            "bind failed",
        );
    }

    #[test]
    fn startup_failure_with_no_output_still_says_something() {
        assert_eq!(
            summarize_startup_failure(
                "",
                "[transformers] PyTorch was not found.\n"
            ),
            "exited during startup with no output",
        );
    }

    #[test]
    fn free_port_returns_a_usable_port() {
        let port = free_port().expect("OS should hand out an ephemeral port");
        assert!(port > 0);
    }

    // No optional flag survived the help probe.
    const NO_FLAGS: ProxyFlagSupport = ProxyFlagSupport {
        savings_profile: false,
        no_rate_limit: false,
    };

    // Only `--savings-profile` is supported, so the rate-limit assertions
    // below isolate one flag at a time.
    const SAVINGS_ONLY: ProxyFlagSupport = ProxyFlagSupport {
        savings_profile: true,
        no_rate_limit: false,
    };

    #[test]
    fn build_proxy_args_without_savings_profile() {
        let args = build_proxy_args("8787", NO_FLAGS, false, false);
        assert_eq!(args, vec!["proxy", "--port", "8787"]);
    }

    #[test]
    fn build_proxy_args_with_savings_profile() {
        let args = build_proxy_args("8787", SAVINGS_ONLY, false, false);
        assert_eq!(args, vec!["proxy", "--port", "8787", "--savings-profile"]);
    }

    #[test]
    fn build_proxy_args_with_no_telemetry() {
        let args = build_proxy_args("8787", NO_FLAGS, true, false);
        assert_eq!(args, vec!["proxy", "--port", "8787", "--no-telemetry"]);
    }

    #[test]
    fn build_proxy_args_with_memory() {
        let args = build_proxy_args("8787", NO_FLAGS, false, true);
        assert_eq!(args, vec!["proxy", "--port", "8787", "--memory"]);
    }

    #[test]
    fn build_proxy_args_with_savings_profile_and_memory() {
        let args = build_proxy_args("8787", SAVINGS_ONLY, false, true);
        assert_eq!(
            args,
            vec!["proxy", "--port", "8787", "--savings-profile", "--memory"]
        );
    }

    #[test]
    fn build_proxy_args_disables_rate_limiting_when_supported() {
        let flags = ProxyFlagSupport {
            savings_profile: false,
            no_rate_limit: true,
        };
        let args = build_proxy_args("8787", flags, false, false);
        assert_eq!(args, vec!["proxy", "--port", "8787", "--no-rate-limit"]);
    }

    #[test]
    fn build_proxy_args_omits_rate_limit_flag_when_unsupported() {
        let args = build_proxy_args("8787", SAVINGS_ONLY, true, true);
        assert!(!args.contains(&"--no-rate-limit"));
    }

    #[test]
    fn proxy_flag_support_reads_both_flags_from_help() {
        let help = "  --savings-profile  ...\n  --no-rate-limit  Disable rate limiting\n";
        assert_eq!(
            proxy_flag_support_from_help(help),
            ProxyFlagSupport {
                savings_profile: true,
                no_rate_limit: true,
            }
        );
    }

    #[test]
    fn proxy_flag_support_is_empty_for_an_older_headroom() {
        let help = "  --port INTEGER  Port bind\n  --no-cache  Disable semantic caching\n";
        assert_eq!(proxy_flag_support_from_help(help), NO_FLAGS);
    }

    #[test]
    fn build_claude_args_injects_memory_when_wrap_manages_proxy() {
        let args = build_claude_args(&[], None, true, DEFAULT_MODEL, None);
        assert!(args.contains(&"--memory".to_string()));
        // wrap owns the proxy here, so --no-proxy must NOT be present.
        assert!(!args.contains(&"--no-proxy".to_string()));
    }

    #[test]
    fn build_claude_args_omits_memory_by_default() {
        let args =
            build_claude_args(&[], Some(8787), false, DEFAULT_MODEL, None);
        assert!(!args.contains(&"--memory".to_string()));
    }

    #[test]
    fn build_proxy_args_with_savings_profile_and_no_telemetry() {
        let args = build_proxy_args("8787", SAVINGS_ONLY, true, false);
        assert_eq!(
            args,
            vec![
                "proxy",
                "--port",
                "8787",
                "--savings-profile",
                "--no-telemetry"
            ]
        );
    }

    #[test]
    fn resolve_savings_profile_defaults_when_unset() {
        assert_eq!(resolve_savings_profile(None), DEFAULT_SAVINGS_PROFILE);
    }

    #[test]
    fn resolve_savings_profile_defaults_when_empty() {
        assert_eq!(
            resolve_savings_profile(Some(String::new())),
            DEFAULT_SAVINGS_PROFILE
        );
    }

    #[test]
    fn resolve_savings_profile_honors_override() {
        assert_eq!(
            resolve_savings_profile(Some("agent-50".to_string())),
            "agent-50"
        );
    }

    #[test]
    fn proxy_help_mentions_flag_finds_present_flag() {
        let help = "  --port INTEGER  Port to listen on\n  --savings-profile  Enable savings\n";
        assert!(proxy_help_mentions_flag(help, "--savings-profile"));
    }

    #[test]
    fn proxy_help_mentions_flag_rejects_absent_flag() {
        let help = "  --port INTEGER  Port to listen on\n  --verbose  Verbose output\n";
        assert!(!proxy_help_mentions_flag(help, "--savings-profile"));
    }

    #[test]
    fn proxy_help_mentions_flag_empty_text() {
        assert!(!proxy_help_mentions_flag("", "--savings-profile"));
    }

    #[test]
    fn build_claude_args_adds_no_proxy_and_port_when_proxy_ready() {
        let args =
            build_claude_args(&[], Some(42111), false, DEFAULT_MODEL, None);
        assert!(args.contains(&"--no-proxy".to_string()));
        // wrap re-derives ANTHROPIC_BASE_URL from --port, so the managed
        // proxy's actual port must be passed through, not left to default 8787.
        let idx = args.iter().position(|a| a == "--port").expect("--port");
        assert_eq!(args[idx + 1], "42111");
        assert_eq!(&args[0..2], &["wrap".to_string(), "claude".to_string()]);
        // Settings files outrank env, so the port is pinned via --settings too.
        let idx = args
            .iter()
            .position(|a| a == "--settings")
            .expect("--settings");
        assert_eq!(
            args[idx + 1],
            r#"{"env":{"ANTHROPIC_BASE_URL":"http://127.0.0.1:42111"}}"#
        );
    }

    #[test]
    fn build_claude_args_keeps_users_own_settings() {
        let user = strings(&["--settings", "/tmp/mine.json"]);
        let args =
            build_claude_args(&user, Some(42111), false, DEFAULT_MODEL, None);
        assert_eq!(args.iter().filter(|a| *a == "--settings").count(), 1);
    }

    #[test]
    fn build_claude_args_omits_no_proxy_and_port_when_proxy_not_ready() {
        let args = build_claude_args(&[], None, false, DEFAULT_MODEL, None);
        assert!(!args.contains(&"--no-proxy".to_string()));
        assert!(!args.contains(&"--port".to_string()));
        assert!(!args.contains(&"--settings".to_string()));
    }

    // headroom 0.34.0 removed `--no-rtk`; emitting it aborts the launch with
    // "no such option". No flag combination may reintroduce it.
    #[test]
    fn build_claude_args_never_emits_no_rtk() {
        for proxy_port in [None, Some(8787u16)] {
            for wrap_memory in [false, true] {
                let args = build_claude_args(
                    &["--resume".into()],
                    proxy_port,
                    wrap_memory,
                    DEFAULT_MODEL,
                    None,
                );
                assert!(
                    !args.contains(&"--no-rtk".to_string()),
                    "--no-rtk leaked with proxy_port={proxy_port:?} \
                     wrap_memory={wrap_memory}"
                );
            }
        }
    }
}