harn-serve 0.10.133

Shared outbound workflow server core for Harn adapters
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
//! ACP session modes (<https://agentclientprotocol.com/protocol/session-modes>).
//!
//! A session mode is the ACP-facing name for Harn's runtime autonomy tier.
//! The catalog is fixed and is rendered both as legacy ACP `modes` and as
//! the newer `configOptions` mode selector.

use harn_vm::{orchestration::CapabilityPolicy, AutonomyTier};

use super::AcpSandboxConfig;

/// Default mode id assigned to newly created sessions. `ask` is the
/// conservative ACP default: the agent can inspect context, but side effects
/// are held behind the approval-oriented autonomy tier until a client or user
/// explicitly switches to `code`.
pub(super) const DEFAULT_MODE_ID: &str = "ask";

pub(super) struct ModeDefinition {
    pub(super) id: &'static str,
    pub(super) name: &'static str,
    pub(super) description: &'static str,
    autonomy_tier: AutonomyTier,
}

/// The static catalog of modes Harn advertises over ACP. Order is preserved on
/// the wire so clients render a stable selector.
pub(super) const MODE_CATALOG: &[ModeDefinition] = &[
    ModeDefinition {
        id: "ask",
        name: "Ask",
        description: "Request permission before making changes.",
        autonomy_tier: AutonomyTier::ActWithApproval,
    },
    ModeDefinition {
        id: "architect",
        name: "Architect",
        description: "Design and plan without modifying the workspace.",
        autonomy_tier: AutonomyTier::Suggest,
    },
    ModeDefinition {
        id: "code",
        name: "Code",
        description: "Read, write, execute processes, and call external services.",
        autonomy_tier: AutonomyTier::ActAuto,
    },
    ModeDefinition {
        id: "shadow",
        name: "Shadow",
        description: "Evaluate the request and emit proposals without side effects.",
        autonomy_tier: AutonomyTier::Shadow,
    },
];

pub(super) fn is_known(mode_id: &str) -> bool {
    definition(mode_id).is_some()
}

pub(super) fn known_mode_ids() -> Vec<&'static str> {
    MODE_CATALOG.iter().map(|m| m.id).collect()
}

fn definition(mode_id: &str) -> Option<&'static ModeDefinition> {
    MODE_CATALOG.iter().find(|m| m.id == mode_id)
}

/// Render the spec-shaped `SessionModeState`:
/// `{ currentModeId, availableModes: [{ id, name, description }] }`.
pub(super) fn session_mode_state(current_mode_id: &str) -> serde_json::Value {
    serde_json::json!({
        "currentModeId": current_mode_id,
        "availableModes": mode_entries("id"),
    })
}

/// Render the preferred ACP `configOptions` representation for the
/// per-session knobs Harn exposes today: session mode, pinned LLM
/// model, and a provider-aware thought level. Entries follow the `select` shape (the only `type` the
/// current spec defines, per
/// <https://agentclientprotocol.com/protocol/session-config-options>).
///
/// New knobs (temperature, permissions, …) plug in here by appending
/// another entry rather than introducing a new wire surface; ACP keeps
/// `configId` open-ended so clients can ignore unknown ids without
/// breaking.
pub(super) fn config_options_state(
    current_mode_id: &str,
    pinned_model: Option<&str>,
    pinned_reasoning_policy: Option<&str>,
    budget_value: Option<&str>,
) -> serde_json::Value {
    serde_json::json!([
        {
            "id": "mode",
            "name": "Session Mode",
            "description": "Controls Harn autonomy and side-effect policy.",
            "category": "mode",
            "type": "select",
            "currentValue": current_mode_id,
            "options": mode_entries("value"),
        },
        model_config_option(pinned_model),
        reasoning_policy_config_option(pinned_reasoning_policy),
        budget_config_option(budget_value),
    ])
}

fn mode_entries(id_key: &str) -> Vec<serde_json::Value> {
    MODE_CATALOG
        .iter()
        .map(|mode| {
            let mut entry = serde_json::Map::new();
            entry.insert(id_key.to_string(), serde_json::json!(mode.id));
            entry.insert("name".to_string(), serde_json::json!(mode.name));
            entry.insert(
                "description".to_string(),
                serde_json::json!(mode.description),
            );
            serde_json::Value::Object(entry)
        })
        .collect()
}

/// Sentinel option value rendered on the model selector when no
/// session-level pin is active. Picking it through
/// `session/set_config_option` clears any prior pin and reverts the
/// session to the ambient default (env / providers.toml).
///
/// Spec note: the ACP `ConfigOption.currentValue` field has
/// `minLength: 1`, so an empty string can't represent "unpinned".
/// `@inherit` is a stable sentinel that satisfies the schema and
/// clearly signals "fall through to the ambient default" instead of
/// being mistaken for a real model id.
pub(super) const MODEL_INHERIT_VALUE: &str = "@inherit";
pub(super) const BUDGET_INHERIT_VALUE: &str = "@inherit";
pub(super) const BUDGET_OFF_VALUE: &str = "off";

fn model_config_option(pinned_model: Option<&str>) -> serde_json::Value {
    serde_json::json!({
        "id": "model",
        "name": "LLM Model",
        "description": "Pinned model for subsequent prompts. llm_call invocations without an \
                        explicit `model:` option resolve to this selector. Aliases and \
                        `provider:model` selectors are both accepted; pick `@inherit` to clear \
                        the pin and revert to the ambient default.",
        "category": "model",
        "type": "select",
        "currentValue": pinned_model.unwrap_or(MODEL_INHERIT_VALUE),
        "options": model_select_options(pinned_model),
    })
}

/// Curated list of model values the spec-mandated `select` renders.
/// Anything that resolves through `harn_vm::llm_config::resolve_model_info`
/// to a registered provider is accepted by the handler — the dropdown is
/// a UI hint, not the enforcement boundary.
fn model_select_options(pinned_model: Option<&str>) -> Vec<serde_json::Value> {
    let mut entries: Vec<serde_json::Value> = Vec::new();
    entries.push(serde_json::json!({
        "value": MODEL_INHERIT_VALUE,
        "name": "Inherit ambient default",
        "description": "Clear any session-level pin and use HARN_LLM_MODEL / providers.toml.",
    }));
    let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for alias in harn_vm::llm_config::known_model_names() {
        let resolved = harn_vm::llm_config::resolve_model_info(&alias);
        let label = format!("{alias} ({}/{})", resolved.provider, resolved.id);
        if seen.insert(alias.clone()) {
            let description = if resolved.tier.is_empty() {
                resolved.provider.clone()
            } else {
                format!("tier: {}", resolved.tier)
            };
            entries.push(serde_json::json!({
                "value": alias,
                "name": label,
                "description": description,
            }));
        }
    }
    for (model_id, model) in harn_vm::llm_config::model_catalog_entries() {
        if seen.insert(model_id.clone()) {
            let description = model
                .tier
                .as_deref()
                .filter(|tier| !tier.is_empty())
                .map(|tier| format!("tier: {tier}"))
                .unwrap_or_else(|| model.provider.clone());
            entries.push(serde_json::json!({
                "value": model_id,
                "name": format!("{} ({})", model.name, model.provider),
                "description": description,
            }));
        }
    }
    // The currently pinned selector may be a free-form id outside the
    // alias catalog. Surface it so the dropdown reflects the real
    // state instead of showing a stale "(none)" entry.
    if let Some(pinned) = pinned_model.filter(|value| !value.is_empty()) {
        if seen.insert(pinned.to_string()) {
            entries.push(serde_json::json!({
                "value": pinned,
                "name": pinned,
                "description": "Currently pinned (not in alias catalog).",
            }));
        }
    }
    entries
}

fn reasoning_policy_config_option(pinned_policy: Option<&str>) -> serde_json::Value {
    serde_json::json!({
        "id": "thought_level",
        "name": "Thought Level",
        "description": "Provider-aware reasoning policy for subsequent prompts. Harn lowers this \
                        to the route's native thinking shape (`reasoning_effort`, thinking budgets, \
                        adaptive thinking, or Qwen `/no_think`). Per-call `thinking` and \
                        `reasoning_effort` options still win; pick `@inherit` to clear the pin.",
        "category": "model",
        "type": "select",
        "currentValue": pinned_policy.unwrap_or(harn_vm::llm::reasoning_policy::INHERIT_POLICY_VALUE),
        "options": reasoning_policy_select_options(),
    })
}

fn budget_config_option(budget_value: Option<&str>) -> serde_json::Value {
    let current_value = budget_value.unwrap_or(BUDGET_INHERIT_VALUE);
    serde_json::json!({
        "id": "budget",
        "name": "Call Budget",
        "description": "Per-prompt resource ceiling installed before Harn runs the next ACP turn. \
                        Values are compact JSON objects such as \
                        {\"llm_cost_usd\":0.05,\"llm_tokens\":200000}; pick `@inherit` to use \
                        the server default or `off` to disable the session override.",
        "category": "_harn_budget",
        "type": "select",
        "currentValue": current_value,
        "options": budget_select_options(current_value),
    })
}

fn budget_select_options(current_value: &str) -> Vec<serde_json::Value> {
    let mut entries = vec![
        serde_json::json!({
            "value": BUDGET_INHERIT_VALUE,
            "name": "Inherit server default",
            "description": "Use the budget configured by the ACP server embedder.",
        }),
        serde_json::json!({
            "value": BUDGET_OFF_VALUE,
            "name": "No session budget",
            "description": "Do not install an ACP session budget for subsequent prompt turns.",
        }),
        serde_json::json!({
            "value": "{\"llm_cost_usd\":0.01}",
            "name": "$0.01 per prompt",
            "description": "Stop the prompt after roughly one cent of model spend.",
        }),
        serde_json::json!({
            "value": "{\"llm_cost_usd\":0.05,\"llm_tokens\":200000}",
            "name": "$0.05 and 200k tokens",
            "description": "Cap both model spend and input+output tokens for the prompt.",
        }),
        serde_json::json!({
            "value": "{\"llm_tokens\":50000}",
            "name": "50k tokens",
            "description": "Token-only ceiling for local or unknown-price providers.",
        }),
    ];
    if !entries
        .iter()
        .any(|entry| entry["value"].as_str() == Some(current_value))
    {
        entries.push(serde_json::json!({
            "value": current_value,
            "name": "Current custom budget",
            "description": "Session budget supplied by the client.",
        }));
    }
    entries
}

fn reasoning_policy_select_options() -> Vec<serde_json::Value> {
    let mut entries = vec![serde_json::json!({
        "value": harn_vm::llm::reasoning_policy::INHERIT_POLICY_VALUE,
        "name": "Inherit script default",
        "description": "Clear the session-level thought policy pin.",
    })];
    entries.extend(
        [
            (
                "auto",
                "Auto",
                "Let Harn choose from task, scale, provider, and model capabilities.",
            ),
            (
                "off",
                "Off",
                "Disable model thinking when possible, including Qwen no-think directives.",
            ),
            (
                "minimal",
                "Minimal",
                "Use the lowest provider-supported reasoning floor.",
            ),
            (
                "low",
                "Low",
                "Light extra reasoning for verification or small tasks.",
            ),
            (
                "medium",
                "Medium",
                "Balanced reasoning for general agent work.",
            ),
            (
                "high",
                "High",
                "More reasoning for difficult planning or code changes.",
            ),
            (
                "xhigh",
                "Extra High",
                "Extended reasoning for routes that expose it.",
            ),
            (
                "max",
                "Maximum",
                "Maximum reasoning for routes that expose it.",
            ),
        ]
        .into_iter()
        .map(|(value, name, description)| {
            serde_json::json!({
                "value": value,
                "name": name,
                "description": description,
            })
        }),
    );
    entries
}

pub(super) fn validate_reasoning_policy_selector(raw: &str) -> Result<Option<String>, String> {
    harn_vm::llm::reasoning_policy::normalize_policy_selector(raw)
}

/// Validate a model selector for `session/set_config_option(configId="model")`.
/// Returns the normalized selector (trimmed; aliases are kept verbatim so
/// the session pin tracks the user's chosen handle) or a descriptive
/// error suitable for surfacing as `invalid_model`.
///
/// The wire surface is intentionally curated: scripts that need ad-hoc
/// selectors should pass `model:` directly to `llm_call`. Accepted forms:
///
/// - empty / whitespace → `Ok(None)` (clear pin sentinel)
/// - `provider:model` / `provider/model` where provider is in `providers.toml`
/// - an alias from `known_model_names()`
/// - a model id present in `model_catalog_entries()`
pub(super) fn validate_model_selector(raw: &str) -> Result<Option<String>, String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() || trimmed == MODEL_INHERIT_VALUE {
        return Ok(None);
    }
    if let Some((provider, _model)) = split_provider_prefix(trimmed)
        .filter(|(provider, model)| !provider.trim().is_empty() && !model.trim().is_empty())
    {
        if provider == "mock" || harn_vm::llm_config::provider_config(provider).is_some() {
            return Ok(Some(trimmed.to_string()));
        }
        return Err(format!(
            "invalid_model: provider '{provider}' is not registered. Available: {}",
            harn_vm::llm_config::provider_names().join(", ")
        ));
    }
    if harn_vm::llm_config::known_model_names()
        .iter()
        .any(|name| name == trimmed)
    {
        return Ok(Some(trimmed.to_string()));
    }
    if harn_vm::llm_config::model_catalog_entry(trimmed).is_some() {
        return Ok(Some(trimmed.to_string()));
    }
    Err(format!(
        "invalid_model: '{trimmed}' is not a known alias, catalog model id, or 'provider:model' form."
    ))
}

/// Split a selector on the first provider-form separator. Both `:` and
/// `/` are recognized because the two appear in the wild — Anthropic /
/// OpenAI route paths use `/` (e.g. `anthropic/claude-opus-4-7`), while
/// Ollama tag selectors use `:` (e.g. `ollama:llama3.2:latest`).
fn split_provider_prefix(value: &str) -> Option<(&str, &str)> {
    value.split_once([':', '/'])
}

/// Capability ceiling enforced while a prompt runs in this mode. Harn's
/// autonomy-tier policy remains authoritative; ACP modes only select the tier.
///
/// The ACP embedder contributes sandbox config for host-owned assets and
/// process-only filesystem presets. Read-only roots widen Harn file reads;
/// process roots/presets are carried only into OS child-process sandboxes.
pub(super) fn policy_for_mode(
    mode_id: &str,
    sandbox: &AcpSandboxConfig,
) -> Option<CapabilityPolicy> {
    let mode = definition(mode_id)?;
    if mode.autonomy_tier == AutonomyTier::ActAuto {
        // ActAuto is the "no human approval gate" tier — but that is an
        // *approval* decision, decoupled from *OS confinement*. When the
        // embedder said nothing about sandboxing, preserve the historical
        // behavior exactly: no per-turn policy, ambient host/runtime policy
        // remains the authority (installing a no-op ceiling would make legacy
        // bridge fallbacks look policy-governed and block them).
        if !sandbox.is_configured() {
            return None;
        }
        // Preserve every configured filesystem axis in code mode. Read-only
        // roots by themselves are a Harn file-read grant, not an instruction
        // to confine child processes. Only explicit process config selects the
        // Worktree OS sandbox and its network backstop.
        let mut policy = harn_vm::policy_for_autonomy_tier(AutonomyTier::ActAuto);
        if sandbox.has_process_confinement() {
            policy.sandbox_profile = harn_vm::orchestration::SandboxProfile::Worktree;
        }
        // An explicit request wins over the inference above. Inference can only
        // ever arm confinement, so without this an embedder that deliberately
        // wanted an unconfined run got a confined one and no error — the
        // request was simply dropped.
        if let Some(requested) = sandbox.requested_profile {
            policy.sandbox_profile = requested;
        }
        apply_sandbox_config(&mut policy, sandbox);
        return Some(policy);
    }
    let mut policy = harn_vm::policy_for_autonomy_tier(mode.autonomy_tier);
    if let Some(requested) = sandbox.requested_profile {
        policy.sandbox_profile = requested;
    }
    apply_sandbox_config(&mut policy, sandbox);
    Some(policy)
}

/// Add embedder sandbox config to the per-turn policy, skipping duplicate
/// Harn read roots and delegating process-only merging to the VM policy type.
fn apply_sandbox_config(policy: &mut CapabilityPolicy, sandbox: &AcpSandboxConfig) {
    for root in &sandbox.read_only_roots {
        if !policy
            .read_only_roots
            .iter()
            .any(|existing| existing == root)
        {
            policy.read_only_roots.push(root.clone());
        }
    }
    policy.process_sandbox.extend(&sandbox.process);
}

/// Task-scoped owner of one turn's mode capability policy and egress posture.
///
/// The adapter runs every session on one current-thread `LocalSet`, so two
/// prompts interleave at their `.await` points. A thread-local push/pop guard
/// held across those awaits is therefore a SHARED stack, not a per-turn one:
/// the second turn's push lands on top of the first's, the first turn resumes
/// reading the second turn's policy, and each drop pops the other's entry. A
/// session that asked for `unrestricted` could descend into its agent loop
/// under a concurrent session's confinement, and vice versa.
///
/// `run` hands both policies to the VM's ambient scope instead, which swaps
/// them in around every poll of the wrapped future. Only the currently polling
/// turn's policy is ever installed on the thread.
pub(super) struct ModePolicyScope {
    policy: Option<CapabilityPolicy>,
    require_ssrf_guard: bool,
}

impl ModePolicyScope {
    pub(super) fn new(mode_id: &str, sandbox: &AcpSandboxConfig) -> Self {
        // Install the SSRF guard only with explicit process confinement.
        // It blocks PRIVATE/loopback/link-local/metadata egress while leaving
        // public traffic (model APIs, web_search/web_fetch to public hosts)
        // ALLOWED. Local model servers on loopback are reached via the
        // documented `HARN_EGRESS_ALLOW_LOOPBACK=1` /
        // `harness.net.egress_policy({block_private:"off"})` hatch; the metadata endpoint
        // stays blocked regardless. With no sandbox config we install nothing,
        // so egress is byte-identical to today's default.
        //
        // `policy` and `require_ssrf_guard` cannot disagree: process
        // confinement makes `is_configured` true, so any sandbox that arms the
        // guard also yields a policy. That is why `run`'s `None` arm needs no
        // guard of its own.
        Self {
            policy: policy_for_mode(mode_id, sandbox),
            require_ssrf_guard: sandbox.has_process_confinement(),
        }
    }

    /// Run one asynchronous span of the turn with this turn's policy installed
    /// around every poll of `inner`, and nobody else's.
    ///
    /// Callable more than once per turn. Each call captures the ambient scope
    /// as it stands, so the synchronous code between two spans runs with the
    /// caller's own context, exactly as it did under the previous guard.
    pub(super) async fn run<F: std::future::Future>(&self, inner: F) -> F::Output {
        match self.policy.clone() {
            Some(policy) => {
                // The scope snapshot is taken eagerly by
                // `scope_execution_policy`, and it captures every other ambient
                // slot — the SSRF depth included, via `SubtaskAmbientState`. So
                // arm the guard first, let the snapshot copy that depth, then
                // drop the raw guard: the requirement now lives in the scope and
                // is installed only while `inner` is being polled.
                let ssrf_guard = self
                    .require_ssrf_guard
                    .then(harn_vm::egress::require_ssrf_guard_for_host);
                let scoped = harn_vm::orchestration::scope_execution_policy(policy, inner);
                drop(ssrf_guard);
                scoped.await
            }
            // A mode that installs no policy of its own still needs the span to
            // own its ambient context. The prompt body holds resource ceilings
            // across these awaits, and on an unscoped span those live on the
            // polling thread, where the other turn reads and restores them.
            None => harn_vm::orchestration::scope_ambient_context(inner).await,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapters::acp::AcpSandboxConfig;

    #[test]
    fn catalog_contains_expected_modes() {
        let ids = known_mode_ids();
        assert!(ids.contains(&"ask"));
        assert!(ids.contains(&"architect"));
        assert!(ids.contains(&"code"));
        assert!(ids.contains(&"shadow"));
    }

    #[test]
    fn default_mode_matches_first_catalog_entry() {
        assert_eq!(MODE_CATALOG.first().map(|m| m.id), Some(DEFAULT_MODE_ID));
    }

    #[test]
    fn session_mode_state_contains_current_and_available() {
        let state = session_mode_state("architect");
        assert_eq!(state["currentModeId"], "architect");
        let available = state["availableModes"].as_array().expect("array");
        assert_eq!(available.len(), MODE_CATALOG.len());
        assert!(available
            .iter()
            .any(|m| m["id"] == "architect" && m["name"] == "Architect"));
    }

    #[test]
    fn config_options_state_contains_mode_selector() {
        let state = config_options_state("code", None, None, None);
        let options = state.as_array().expect("config options array");
        assert_eq!(options.len(), 4);
        assert_eq!(options[0]["id"], "mode");
        assert_eq!(options[0]["currentValue"], "code");
        assert!(options[0]["options"]
            .as_array()
            .expect("mode options")
            .iter()
            .any(|m| m["value"] == "ask"));
    }

    #[test]
    fn config_options_state_includes_model_selector_with_pin_clear_sentinel() {
        let state = config_options_state("code", None, None, None);
        let options = state.as_array().expect("config options array");
        let model_option = options
            .iter()
            .find(|entry| entry["id"] == "model")
            .expect("model config option");
        assert_eq!(model_option["category"], "model");
        assert_eq!(model_option["type"], "select");
        assert_eq!(model_option["currentValue"], MODEL_INHERIT_VALUE);
        let values: Vec<&str> = model_option["options"]
            .as_array()
            .expect("model options")
            .iter()
            .map(|entry| entry["value"].as_str().expect("value string"))
            .collect();
        assert!(
            values.contains(&MODEL_INHERIT_VALUE),
            "options must include the inherit sentinel: {values:?}"
        );
    }

    #[test]
    fn config_options_state_surfaces_free_form_pinned_model() {
        let state = config_options_state("code", Some("custom-model-not-in-catalog"), None, None);
        let model_option = state
            .as_array()
            .expect("config options array")
            .iter()
            .find(|entry| entry["id"] == "model")
            .cloned()
            .expect("model config option");
        assert_eq!(model_option["currentValue"], "custom-model-not-in-catalog");
        let has_entry = model_option["options"]
            .as_array()
            .expect("model options")
            .iter()
            .any(|entry| entry["value"] == "custom-model-not-in-catalog");
        assert!(
            has_entry,
            "free-form pinned model must appear in select options"
        );
    }

    #[test]
    fn validate_model_selector_accepts_empty_as_clear_pin() {
        assert!(validate_model_selector("").unwrap().is_none());
        assert!(validate_model_selector("   ").unwrap().is_none());
        assert!(validate_model_selector("@inherit").unwrap().is_none());
    }

    #[test]
    fn config_options_state_includes_thought_level_selector() {
        let state = config_options_state("code", None, Some("high"), None);
        let thought_option = state
            .as_array()
            .expect("config options array")
            .iter()
            .find(|entry| entry["id"] == "thought_level")
            .cloned()
            .expect("thought level config option");
        assert_eq!(thought_option["category"], "model");
        assert_eq!(thought_option["type"], "select");
        assert_eq!(thought_option["currentValue"], "high");
        let values: Vec<&str> = thought_option["options"]
            .as_array()
            .expect("thought options")
            .iter()
            .map(|entry| entry["value"].as_str().expect("value string"))
            .collect();
        let expected: Vec<&str> =
            std::iter::once(harn_vm::llm::reasoning_policy::INHERIT_POLICY_VALUE)
                .chain(
                    harn_vm::llm::reasoning_policy::policy_values()
                        .iter()
                        .copied(),
                )
                .collect();
        assert_eq!(values, expected);
    }

    #[test]
    fn config_options_state_includes_budget_selector_with_custom_value() {
        let custom = "{\"llm_tokens\":123}";
        let state = config_options_state("code", None, None, Some(custom));
        let budget_option = state
            .as_array()
            .expect("config options array")
            .iter()
            .find(|entry| entry["id"] == "budget")
            .cloned()
            .expect("budget config option");
        assert_eq!(budget_option["category"], "_harn_budget");
        assert_eq!(budget_option["type"], "select");
        assert_eq!(budget_option["currentValue"], custom);
        assert!(budget_option["options"]
            .as_array()
            .expect("budget options")
            .iter()
            .any(|entry| entry["value"] == custom));
    }

    #[test]
    fn validate_reasoning_policy_selector_normalizes_aliases() {
        assert!(validate_reasoning_policy_selector("").unwrap().is_none());
        assert!(validate_reasoning_policy_selector("@inherit")
            .unwrap()
            .is_none());
        assert_eq!(
            validate_reasoning_policy_selector("NO_THINK")
                .unwrap()
                .as_deref(),
            Some("off"),
        );
        assert_eq!(
            validate_reasoning_policy_selector(" high ")
                .unwrap()
                .as_deref(),
            Some("high"),
        );
        assert!(validate_reasoning_policy_selector("slow").is_err());
    }

    #[test]
    fn validate_model_selector_accepts_known_alias() {
        // `claude-sonnet-4-6` is the catalog default; any registered
        // alias works for this check.
        let resolved = validate_model_selector("claude-sonnet-4-6")
            .expect("known alias should validate")
            .expect("known alias should produce a Some(...) selector");
        assert_eq!(resolved, "claude-sonnet-4-6");
    }

    #[test]
    fn validate_model_selector_rejects_unknown_provider_form() {
        let error = validate_model_selector("nosuchprovider:nosuchmodel")
            .expect_err("unknown provider must error");
        assert!(
            error.contains("invalid_model"),
            "error should be tagged invalid_model: {error}"
        );
    }

    #[test]
    fn policy_for_code_with_no_config_is_none() {
        // No-config default MUST be byte-identical to historical behavior:
        // ActAuto `code` mode installs no per-turn policy, leaving the ambient
        // (unrestricted) host/runtime policy as the authority.
        assert!(policy_for_mode("code", &AcpSandboxConfig::default()).is_none());
        // The default config is, by definition, not "configured".
        assert!(!AcpSandboxConfig::default().is_configured());
    }

    #[test]
    fn policy_for_code_with_only_read_only_roots_preserves_file_policy_without_process_confinement()
    {
        let roots = vec!["/work/project".to_string()];
        let sandbox = AcpSandboxConfig::with_read_only_roots(roots.clone());
        assert!(sandbox.is_configured());
        assert!(!sandbox.has_process_confinement());
        let policy = policy_for_mode("code", &sandbox)
            .expect("read-only roots must survive the code-mode policy boundary");
        assert_eq!(policy.read_only_roots, roots);
        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Unrestricted,
            "read-only roots alone must not arm process confinement"
        );
    }

    #[test]
    fn policy_for_code_with_process_config_applies_worktree_confinement() {
        // Real process-sandbox config (presets/read_roots/write_roots) is the
        // only opt-in signal for Worktree confinement. When present, any
        // read_only_roots the embedder also configured still ride along via
        // `apply_sandbox_config`.
        let mut sandbox =
            AcpSandboxConfig::with_process(harn_vm::orchestration::ProcessSandboxPolicy {
                presets: Some(vec![
                    harn_vm::orchestration::ProcessSandboxPreset::DeveloperToolchains,
                ]),
                read_roots: Vec::new(),
                write_roots: Vec::new(),
                ..Default::default()
            });
        sandbox.read_only_roots = vec!["/work/project".to_string()];
        assert!(sandbox.is_configured());
        let policy = policy_for_mode("code", &sandbox)
            .expect("process-configured code mode must install a confinement policy");
        // Worktree-level OS confinement is engaged...
        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Worktree
        );
        // ...the embedder's read-only roots are still carried through...
        assert_eq!(policy.read_only_roots, vec!["/work/project".to_string()]);
        // ...and ActAuto approval semantics are preserved (no approval gate ->
        // the current maximum side-effect ceiling, no recursion clamp).
        assert_eq!(policy.side_effect_level.as_deref(), Some("desktop_control"));
        assert_eq!(policy.recursion_limit, None);
    }

    #[test]
    fn policy_for_code_with_loopback_only_applies_worktree_confinement() {
        let sandbox =
            AcpSandboxConfig::with_process(harn_vm::orchestration::ProcessSandboxPolicy {
                allow_tcp_loopback: true,
                ..Default::default()
            });

        assert!(sandbox.is_configured());
        assert!(sandbox.has_process_confinement());
        let policy = policy_for_mode("code", &sandbox)
            .expect("loopback capability must install the process sandbox policy");
        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Worktree
        );
        assert!(policy.process_sandbox.allow_tcp_loopback);
    }

    #[test]
    fn policy_for_code_with_process_config_applies_confinement() {
        let process = harn_vm::orchestration::ProcessSandboxPolicy {
            presets: Some(vec![
                harn_vm::orchestration::ProcessSandboxPreset::DeveloperToolchains,
            ]),
            read_roots: vec!["/opt/sdk".to_string()],
            write_roots: Vec::new(),
            ..Default::default()
        };
        let sandbox = AcpSandboxConfig::with_process(process);
        assert!(sandbox.is_configured());
        let policy = policy_for_mode("code", &sandbox)
            .expect("process-config code mode must install a confinement policy");
        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Worktree
        );
        assert_eq!(
            policy.process_sandbox.read_roots,
            vec!["/opt/sdk".to_string()]
        );
        assert_eq!(policy.side_effect_level.as_deref(), Some("desktop_control"));
    }

    #[test]
    fn policy_for_architect_clamps_to_read_only() {
        let policy = policy_for_mode("architect", &AcpSandboxConfig::default())
            .expect("architect has policy");
        assert_eq!(policy.side_effect_level.as_deref(), Some("read_only"));
    }

    #[test]
    fn policy_for_ask_clamps_to_read_only() {
        let policy = policy_for_mode("ask", &AcpSandboxConfig::default()).expect("ask has policy");
        assert_eq!(policy.side_effect_level.as_deref(), Some("read_only"));
    }

    #[test]
    fn policy_for_shadow_blocks_side_effects() {
        let policy =
            policy_for_mode("shadow", &AcpSandboxConfig::default()).expect("shadow has policy");
        assert_eq!(policy.side_effect_level.as_deref(), Some("read_only"));
        assert_eq!(policy.recursion_limit, Some(0));
    }

    #[test]
    fn policy_for_unknown_mode_is_none() {
        assert!(policy_for_mode("not-a-real-mode", &AcpSandboxConfig::default()).is_none());
    }

    #[test]
    fn embedder_read_only_roots_union_into_per_turn_policy() {
        let roots = vec![
            "/opt/burin/pipelines".to_string(),
            "/opt/burin/pipelines/partials".to_string(),
        ];
        let sandbox = AcpSandboxConfig::with_read_only_roots(roots.clone());
        let policy = policy_for_mode("architect", &sandbox).expect("architect has policy");
        // Embedder roots survive the per-turn push as read-only entries...
        assert_eq!(policy.read_only_roots, roots);
        // ...without widening the writable workspace or relaxing the side
        // effect ceiling (reads only).
        assert!(policy.workspace_roots.is_empty());
        assert_eq!(policy.side_effect_level.as_deref(), Some("read_only"));
    }

    #[test]
    fn embedder_read_only_roots_dedupe_on_union() {
        let roots = vec![
            "/opt/burin/pipelines".to_string(),
            "/opt/burin/pipelines".to_string(),
        ];
        let sandbox = AcpSandboxConfig::with_read_only_roots(roots);
        let policy = policy_for_mode("ask", &sandbox).expect("ask has policy");
        assert_eq!(
            policy.read_only_roots,
            vec!["/opt/burin/pipelines".to_string()]
        );
    }

    #[test]
    fn embedder_process_sandbox_config_unions_into_per_turn_policy() {
        let process = harn_vm::orchestration::ProcessSandboxPolicy {
            presets: Some(vec![
                harn_vm::orchestration::ProcessSandboxPreset::SystemRuntime,
            ]),
            read_roots: vec!["/opt/vendor-sdk".to_string()],
            write_roots: vec!["/opt/vendor-cache".to_string()],
            ..Default::default()
        };
        let sandbox = AcpSandboxConfig::with_process(process);
        let policy = policy_for_mode("architect", &sandbox).expect("architect has policy");

        assert_eq!(
            policy.process_sandbox.presets,
            Some(vec![
                harn_vm::orchestration::ProcessSandboxPreset::SystemRuntime
            ])
        );
        assert_eq!(
            policy.process_sandbox.read_roots,
            vec!["/opt/vendor-sdk".to_string()]
        );
        assert_eq!(
            policy.process_sandbox.write_roots,
            vec!["/opt/vendor-cache".to_string()]
        );
        assert!(policy.read_only_roots.is_empty());
    }

    #[test]
    fn code_mode_honors_embedder_read_only_roots_when_process_sandbox_is_configured() {
        // A process-sandbox-configured embedder gets Worktree confinement
        // with its declared read-only roots still applied, even in
        // full-access ACP code mode. `read_only_roots` alone (no process
        // config) is covered by the read-only-roots-only regression above.
        let mut sandbox =
            AcpSandboxConfig::with_process(harn_vm::orchestration::ProcessSandboxPolicy {
                presets: Some(vec![
                    harn_vm::orchestration::ProcessSandboxPreset::DeveloperToolchains,
                ]),
                read_roots: Vec::new(),
                write_roots: Vec::new(),
                ..Default::default()
            });
        sandbox.read_only_roots = vec!["/opt/burin/pipelines".to_string()];
        let policy = policy_for_mode("code", &sandbox).expect("configured code mode has policy");
        assert_eq!(
            policy.read_only_roots,
            vec!["/opt/burin/pipelines".to_string()]
        );
        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Worktree
        );
    }

    #[test]
    fn default_embedder_run_policy_keeps_system_runtime_preset() {
        use harn_vm::orchestration::{
            CapabilityPolicy, ProcessSandboxPolicy, ProcessSandboxPreset,
        };
        // Regression for the 2026-07-18 Burin dogfood repro: the default
        // embedder config (bundled pipelines + dependency roots as read-only,
        // process read roots, and NO `presets` — i.e. no ~/.burin/sandbox.json)
        // must NOT narrow the process-sandbox presets. The full run policy — the
        // ModePolicyScope policy intersected with the agent-loop's tools-only
        // policy — must still carry SystemRuntime so child spawns can read
        // `/opt/homebrew` (Homebrew-installed toolchain roots such as GOROOT).
        let mut sandbox =
            AcpSandboxConfig::with_read_only_roots(vec!["/opt/burin/pipelines".to_string()]);
        sandbox.process = ProcessSandboxPolicy {
            presets: None,
            read_roots: vec!["/dep/sdk".to_string()],
            write_roots: Vec::new(),
            ..Default::default()
        };
        let outer = policy_for_mode("code", &sandbox).expect("configured code mode has policy");
        let requested = CapabilityPolicy {
            tools: vec!["look".to_string(), "run".to_string(), "edit".to_string()],
            ..CapabilityPolicy::default()
        };
        let effective = outer.intersect(&requested).expect("intersect ok");
        assert!(
            effective
                .process_sandbox
                .effective_presets()
                .contains(&ProcessSandboxPreset::SystemRuntime),
            "default embedder run policy must keep SystemRuntime (grants /opt/homebrew): {:?}",
            effective.process_sandbox.effective_presets()
        );
    }

    #[test]
    fn is_known_rejects_unknown_mode() {
        assert!(is_known("ask"));
        assert!(!is_known(""));
        assert!(!is_known("plan"));
    }

    #[test]
    fn no_config_code_mode_installs_no_ssrf_guard() {
        // The default (no-config) path must not change egress behavior at all:
        // the SSRF private-address guard is NOT installed. Assert ownership
        // directly so a legitimate ambient HARN_EGRESS_* policy cannot change
        // this unit test's premise.
        let scope = ModePolicyScope::new("code", &AcpSandboxConfig::default());
        assert!(
            !scope.require_ssrf_guard,
            "no-config code mode must not install an SSRF guard scope"
        );
    }

    #[test]
    fn read_only_roots_code_mode_installs_policy_without_ssrf_guard() {
        let sandbox =
            AcpSandboxConfig::with_read_only_roots(vec!["/opt/shared/prompts".to_string()]);
        let scope = ModePolicyScope::new("code", &sandbox);
        assert!(
            scope.policy.is_some(),
            "read-only roots must install a turn policy"
        );
        assert!(
            !scope.require_ssrf_guard,
            "read-only roots must not change network behavior"
        );
        let effective = scope.policy.expect("turn policy must be present");
        assert_eq!(
            effective.read_only_roots,
            vec!["/opt/shared/prompts".to_string()]
        );
        assert_eq!(
            effective.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Unrestricted
        );
    }

    #[test]
    fn configured_code_mode_installs_ssrf_guard() {
        // A process-sandbox-configured embedder gets the SSRF private-address
        // backstop for the turn: block_private becomes active. Public hosts
        // stay reachable (the guard only blocks
        // private/loopback/link-local/metadata addresses). `read_only_roots`
        // alone (Burin's ambient bundled-pipeline roots) must NOT arm this.
        // Harn VM owns the scope's effective-policy and drop semantics; this
        // adapter test proves that configured ACP mode retains such a scope.
        // Inspecting effective settings here would inherit the parent process's
        // documented HARN_EGRESS_* overrides and make the test non-hermetic.
        let sandbox =
            AcpSandboxConfig::with_process(harn_vm::orchestration::ProcessSandboxPolicy {
                presets: Some(vec![
                    harn_vm::orchestration::ProcessSandboxPreset::DeveloperToolchains,
                ]),
                read_roots: Vec::new(),
                write_roots: Vec::new(),
                ..Default::default()
            });
        let scope = ModePolicyScope::new("code", &sandbox);
        assert!(
            scope.require_ssrf_guard,
            "configured code mode must retain an SSRF guard scope"
        );
    }

    /// Two prompts in flight on one adapter must each descend under their OWN
    /// mode policy.
    ///
    /// The ACP adapter runs every session on one current-thread `LocalSet`, so
    /// two turns interleave at their `.await` points. A raw thread-local
    /// push/pop guard held across those awaits is a SHARED stack: the second
    /// turn's push lands on top of the first's, the first turn resumes reading
    /// the second's policy, and the drops then pop each other's entries.
    ///
    /// The arms assert the carrier that actually governs each turn's
    /// `agent_loop` descent — the value a child process is checked against —
    /// not the profile the embedder requested:
    ///
    /// 1. liveness: each turn descends under a real carrier, never `None`.
    ///    Without this arm, an adapter that installed nothing at all would
    ///    satisfy arm 3 by accident.
    /// 2. the defect: the `unrestricted` turn still descends `Unrestricted`
    ///    after the confined turn has interleaved.
    /// 3. the control: the confined turn descends `Worktree`, so arm 2 is not
    ///    passing because confinement stopped working in both directions.
    ///
    /// Falsifier: restore the thread-local `ModePolicyGuard` (push on enter,
    /// pop on drop, held across the awaits in `prompt.rs`). Arm 2 fails with
    /// the confined turn's profile, and the residue assertion fails too.
    #[tokio::test(flavor = "current_thread")]
    async fn concurrent_turns_each_descend_under_their_own_mode_policy() {
        use harn_vm::orchestration::{
            clear_execution_policy_stacks, current_execution_policy, enter_nested_execution_policy,
            NestedExecutionKind, SandboxProfile,
        };

        fn requesting(profile: SandboxProfile) -> AcpSandboxConfig {
            AcpSandboxConfig {
                requested_profile: Some(profile),
                ..AcpSandboxConfig::default()
            }
        }

        /// What the turn's `agent_loop` descent would hand a child process.
        fn descended_profile(label: &str) -> Option<SandboxProfile> {
            let guard =
                enter_nested_execution_policy(None, NestedExecutionKind::AgentLoop, label).ok()?;
            let profile = current_execution_policy().map(|policy| policy.sandbox_profile);
            drop(guard);
            profile
        }

        clear_execution_policy_stacks();
        let unrestricted = ModePolicyScope::new("code", &requesting(SandboxProfile::Unrestricted));
        let confined = ModePolicyScope::new("code", &requesting(SandboxProfile::Worktree));

        // The interleave is fixed, not raced: `join!` polls the two futures in
        // order on one thread, and the extra `yield_now` in each body places
        // the confined turn's entry between the unrestricted turn's entry and
        // its own read.
        let unrestricted_turn = unrestricted.run(async {
            tokio::task::yield_now().await;
            descended_profile("unrestricted-turn")
        });
        let confined_turn = confined.run(async {
            tokio::task::yield_now().await;
            tokio::task::yield_now().await;
            descended_profile("confined-turn")
        });
        let (unrestricted_descent, confined_descent) =
            tokio::join!(unrestricted_turn, confined_turn);

        assert!(
            unrestricted_descent.is_some() && confined_descent.is_some(),
            "arm 1 (liveness): each served turn must descend under a real carrier, or the \
             remaining arms are satisfied by an adapter that installs nothing"
        );
        assert_eq!(
            unrestricted_descent,
            Some(SandboxProfile::Unrestricted),
            "arm 2 (the defect): the embedder asked for `unrestricted`, so this turn's agent \
             loop must still descend unrestricted after a concurrent turn interleaved"
        );
        assert_eq!(
            confined_descent,
            Some(SandboxProfile::Worktree),
            "arm 3 (the control): the concurrent turn must keep its own confinement, so arm 2 \
             cannot be passing because the two policies simply swapped"
        );
        assert!(
            current_execution_policy().is_none(),
            "neither turn's policy may outlive its own prompt scope"
        );
        clear_execution_policy_stacks();
    }

    /// Two prompts in flight must also keep their own resource ceilings.
    ///
    /// Same cause and same seam as the policy arms above: the prompt body
    /// installs the turn's caps and holds them across the awaited execution, so
    /// on an unscoped span they live on the polling thread and the other turn
    /// reads and restores them. This arm covers the `code` mode with no
    /// embedder sandbox config, which installs no capability policy at all and
    /// was therefore the one span still running unscoped.
    ///
    /// The cap is read back through `mcp_calls_spent`, which answers `None`
    /// when no budget is installed and `Some` once one is. Charging a call
    /// against it first is what makes the read non-null: a probe that could
    /// only ever report `None` would pass with no budget installed anywhere.
    ///
    /// Falsifier: drop the `None` arm's scope back to a bare `inner.await`.
    /// The first turn then reads the second turn's budget.
    #[tokio::test(flavor = "current_thread")]
    async fn concurrent_turns_each_keep_their_own_resource_ceiling() {
        use harn_vm::orchestration::clear_execution_policy_stacks;

        /// `code` with no sandbox config: the mode that installs no policy.
        fn unconfigured() -> AcpSandboxConfig {
            AcpSandboxConfig::default()
        }

        clear_execution_policy_stacks();
        assert!(
            policy_for_mode("code", &unconfigured()).is_none(),
            "this arm must exercise the span that installs no capability policy"
        );

        async fn turn(scope: &ModePolicyScope, cap: u64, extra_yields: usize) -> Option<u64> {
            scope
                .run(async move {
                    let _budget = harn_vm::install_mcp_call_budget(cap);
                    harn_vm::charge_mcp_call().expect("first charge is under every cap here");
                    for _ in 0..=extra_yields {
                        tokio::task::yield_now().await;
                    }
                    // Charge again and report the total this turn has spent.
                    // Its own budget was charged once, so a turn that reads its
                    // own ceiling sees 2.
                    harn_vm::charge_mcp_call().ok();
                    harn_vm::mcp_calls_spent()
                })
                .await
        }

        let first = ModePolicyScope::new("code", &unconfigured());
        let second = ModePolicyScope::new("code", &unconfigured());
        // The same fixed interleave as the policy arms: `join!` polls in order,
        // and the yield counts place the second turn's install between the
        // first turn's install and its own read.
        let (first_spent, second_spent) = tokio::join!(turn(&first, 8, 0), turn(&second, 8, 1));

        assert_eq!(
            first_spent,
            Some(2),
            "the first turn must charge its OWN budget on both calls; reading anything else \
             means the second turn's ceiling replaced it while this one was suspended"
        );
        assert_eq!(
            second_spent,
            Some(2),
            "and the second turn must keep its own, so the pair cannot pass by simply swapping"
        );
        assert!(
            harn_vm::mcp_calls_spent().is_none(),
            "neither turn's ceiling may outlive its own prompt scope"
        );
        clear_execution_policy_stacks();
    }

    // ---- an embedder may DECLINE confinement, not only arm it --------------

    /// Inference can only ever arm confinement. Before `requested_profile`, an
    /// embedder that wanted a deliberately unconfined run had no way to say so:
    /// the request did not exist, so it could not be dropped loudly either. It
    /// simply got a confined policy and no error.
    #[test]
    fn an_explicit_unrestricted_request_overrides_the_confinement_inference() {
        let sandbox = AcpSandboxConfig {
            // Process config present, so the inference below WOULD select
            // Worktree. That is the point: the request has to beat it.
            process: harn_vm::orchestration::ProcessSandboxPolicy {
                presets: Some(vec![
                    harn_vm::orchestration::ProcessSandboxPreset::SystemRuntime,
                ]),
                ..Default::default()
            },
            requested_profile: Some(harn_vm::orchestration::SandboxProfile::Unrestricted),
            ..AcpSandboxConfig::default()
        };

        let policy = policy_for_mode("code", &sandbox).expect("policy");

        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Unrestricted,
            "an explicit request must beat the inference that would otherwise confine"
        );
    }

    /// Control: the same config WITHOUT the request still confines, so the test
    /// above is measuring the request and not a policy that was unconfined all
    /// along.
    #[test]
    fn the_same_config_without_a_request_still_confines() {
        let sandbox = AcpSandboxConfig {
            process: harn_vm::orchestration::ProcessSandboxPolicy {
                presets: Some(vec![
                    harn_vm::orchestration::ProcessSandboxPreset::SystemRuntime,
                ]),
                ..Default::default()
            },
            ..AcpSandboxConfig::default()
        };

        let policy = policy_for_mode("code", &sandbox).expect("policy");

        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Worktree,
            "without a request the historical inference must be unchanged"
        );
    }

    /// A request on its own is enough to produce a policy. Otherwise
    /// `is_configured()` would return false for a host whose ONLY instruction
    /// was the profile, `policy_for_mode` would return None, and the request
    /// would vanish into ambient policy.
    #[test]
    fn a_request_alone_is_enough_to_produce_a_policy() {
        let sandbox = AcpSandboxConfig {
            requested_profile: Some(harn_vm::orchestration::SandboxProfile::Unrestricted),
            ..AcpSandboxConfig::default()
        };
        assert!(sandbox.is_configured());
        let policy = policy_for_mode("code", &sandbox).expect("a request alone must configure");
        assert_eq!(
            policy.sandbox_profile,
            harn_vm::orchestration::SandboxProfile::Unrestricted
        );
    }
}