car-server-core 0.52.1

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! Durable store + wire surface for the per-agent approval policy
//! ([`car_policy::AgentPermissionPolicy`]).
//!
//! The policy lives at `~/.car/agent-permissions.json` — one file, human-
//! readable — and is loaded on demand (config-frequency, not hot-path). Each
//! mutation is a daemon-serialized read-modify-write with a unique atomic
//! temp+rename, so concurrent host requests neither lose one another's changes
//! nor expose a torn file.
//!
//! Fail-safety notes (see the per-agent permissions review):
//! - A corrupt/unreadable policy file retains the last valid in-process
//!   snapshot. Before any valid snapshot exists it uses the Cautious posture,
//!   so corruption cannot silently widen authority.
//! - Enforcement classifies each tool call by risk tier (`classify_tool_call`).
//!   Under the **Trusting** preset (`sandbox_edit → always_allow`) a shell whose
//!   danger the keyword classifier misses (e.g. `cat /etc/shadow`) can run
//!   unprompted. Balanced keeps `sandbox_edit` gated, so this only bites when an
//!   operator has explicitly opted into Trusting.
//!
//! Wire methods (`agent_permissions.*`):
//! - `get` → the raw policy `{ default, agents, tool_overrides? }`.
//! - `set` `{ agent_id, tier?, mode }` → set one tier (or, with `tier` omitted,
//!   every tier) for an agent.
//! - `set_default` `{ preset }` or `{ tier, mode }` → move the fallback posture.
//! - `reset` `{ agent_id }` → drop an agent's override (revert to default).
//! - `evaluate` `{ agent_id, tier }` → the resolved `ApprovalMode` (the query
//!   the executor/HITL path consults before acting).
//! - `set_tool` / `reset_tool` configure one exact `(agent_id, tool)` pair.
//! - `evaluate_tool` reports that exact override when present, otherwise the
//!   existing tier posture. All three exact-tool methods are
//!   host-management-only at the dispatcher boundary.

use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Mutex as StdMutex, OnceLock};

use car_policy::agent_permissions::{ApprovalMode, ApprovalPreset};
use car_policy::permission::PermissionTier;
use car_policy::AgentPermissionPolicy;
use serde_json::{json, Value};

use crate::handler::JsonRpcMessage;

/// `agent-permissions.json` under the CAR state root — `CAR_HOME` when set,
/// otherwise `~/.car` (HOME, or USERPROFILE on Windows). Creates the root
/// best-effort; `None` when neither is resolvable.
fn policy_path() -> Option<PathBuf> {
    let dir = car_home::root()?;
    let _ = std::fs::create_dir_all(&dir);
    Some(dir.join("agent-permissions.json"))
}

#[derive(Default)]
struct PolicyStoreState {
    last_valid: HashMap<PathBuf, AgentPermissionPolicy>,
    next_temp: u64,
}

fn policy_store() -> &'static StdMutex<PolicyStoreState> {
    static STORE: OnceLock<StdMutex<PolicyStoreState>> = OnceLock::new();
    STORE.get_or_init(|| StdMutex::new(PolicyStoreState::default()))
}

fn cautious_policy() -> AgentPermissionPolicy {
    let mut policy = AgentPermissionPolicy::default();
    policy.set_default_preset(ApprovalPreset::Cautious);
    policy
}

fn load_policy_locked(path: &PathBuf, store: &mut PolicyStoreState) -> AgentPermissionPolicy {
    match std::fs::read_to_string(path) {
        Ok(contents) => match serde_json::from_str::<AgentPermissionPolicy>(&contents) {
            Ok(policy) => {
                store.last_valid.insert(path.clone(), policy.clone());
                policy
            }
            Err(error) => {
                tracing::error!(
                    "[agent_permissions] corrupt {path:?} ({error}); retaining the last valid policy or failing closed"
                );
                store
                    .last_valid
                    .get(path)
                    .cloned()
                    .unwrap_or_else(cautious_policy)
            }
        },
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            store.last_valid.get(path).cloned().unwrap_or_default()
        }
        Err(error) => {
            tracing::error!(
                "[agent_permissions] unreadable {path:?} ({error}); retaining the last valid policy or failing closed"
            );
            store
                .last_valid
                .get(path)
                .cloned()
                .unwrap_or_else(cautious_policy)
        }
    }
}

/// Load one coherent policy snapshot. Corruption never silently widens
/// authority: the daemon retains the last valid snapshot for this path, or
/// returns the cautious posture when no valid snapshot has ever been observed.
pub fn load_policy() -> AgentPermissionPolicy {
    let Some(path) = policy_path() else {
        return cautious_policy();
    };
    let mut store = policy_store()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    load_policy_locked(&path, &mut store)
}

fn save_policy_locked(
    path: &PathBuf,
    policy: &AgentPermissionPolicy,
    store: &mut PolicyStoreState,
) -> Result<(), String> {
    let json = serde_json::to_string_pretty(policy).map_err(|e| e.to_string())?;
    store.next_temp = store.next_temp.wrapping_add(1);
    let filename = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("agent-permissions.json");
    let tmp = path.with_file_name(format!(
        ".{filename}.{}.{}.tmp",
        std::process::id(),
        store.next_temp
    ));
    let write_result = (|| -> Result<(), String> {
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp)
            .map_err(|error| format!("create unique policy temp {tmp:?}: {error}"))?;
        file.write_all(json.as_bytes())
            .map_err(|error| format!("write policy temp {tmp:?}: {error}"))?;
        file.sync_all()
            .map_err(|error| format!("sync policy temp {tmp:?}: {error}"))?;
        std::fs::rename(&tmp, path).map_err(|error| format!("replace policy {path:?}: {error}"))?;
        Ok(())
    })();
    if write_result.is_err() {
        let _ = std::fs::remove_file(&tmp);
    }
    write_result?;
    store.last_valid.insert(path.clone(), policy.clone());
    Ok(())
}

fn update_policy<R>(
    mutation: impl FnOnce(&mut AgentPermissionPolicy) -> Result<R, String>,
) -> Result<(AgentPermissionPolicy, R), String> {
    let path = policy_path().ok_or("no home directory for agent-permissions.json")?;
    update_policy_at(path, mutation)
}

fn update_policy_at<R>(
    path: PathBuf,
    mutation: impl FnOnce(&mut AgentPermissionPolicy) -> Result<R, String>,
) -> Result<(AgentPermissionPolicy, R), String> {
    let mut store = policy_store()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let mut policy = load_policy_locked(&path, &mut store);
    let result = mutation(&mut policy)?;
    save_policy_locked(&path, &policy, &mut store)?;
    Ok((policy, result))
}

/// The resolved decision for `(agent_id, tier)`, consulted before an agent acts.
pub fn resolve(agent_id: &str, tier: PermissionTier) -> ApprovalMode {
    load_policy().resolve(agent_id, tier)
}

/// Fallback risk tier of one of the assistant's built-in tools. Supervised
/// `car do --serve` should prefer schema-declared `"tier"` metadata from the
/// actual advertised tool list; this map exists only for builtins whose defs do
/// not carry metadata and for non-assistant callers that lack a schema list.
pub fn assistant_tool_tier(tool: &str) -> PermissionTier {
    match tool {
        "write_file" | "edit_file" | "shell" | "generate_image" | "generate_speech" => {
            PermissionTier::SandboxEdit
        }
        "http_request"
        | "web_search"
        | "remember"
        | "generate_music"
        | "generate_jingle"
        | "generate_studio_image"
        | "generate_song"
        | "run_applescript"
        | "run_powershell" => PermissionTier::FullAccess,
        // read_file / list_dir / find_files / grep_files / calculate / unknown
        _ => PermissionTier::ReadOnly,
    }
}

fn declared_tool_tiers(tool_defs: &[Value]) -> HashMap<String, PermissionTier> {
    tool_defs
        .iter()
        .filter_map(|def| {
            let name = def.get("name").and_then(Value::as_str)?;
            let tier = def
                .get("tier")
                .and_then(Value::as_str)
                .and_then(PermissionTier::from_str_opt)?;
            Some((name.to_string(), tier))
        })
        .collect()
}

/// Payload params of the built-in file-write tools — the file body, which is
/// data, not an actionable command. Stripped before full-access keyword scanning
/// so an ordinary source edit isn't mis-escalated. `path` is intentionally NOT
/// here: a write targeting a sensitive path should still be able to escalate.
const WRITE_PAYLOAD_KEYS: &[&str] = &["new_text", "old_text", "content"];

/// Payload params of the built-in **read-only search** tools — the needle being
/// looked for, which is data, not an actionable command. A `grep_files` cannot
/// push, delete, or deploy anything no matter what it searches *for*.
///
/// Same reasoning as [`WRITE_PAYLOAD_KEYS`] (#595), and the same failure mode:
/// the keyword list contains ordinary domain vocabulary (`request`, `push`,
/// `token`, `secret`, `send`, `http`, `delete`, `format`), so searching a web
/// codebase escalates the *read* to full_access and HARD-BLOCKS a non-interactive
/// agent. Surfaced by the coder A/B on flask, whose domain vocabulary is almost
/// entirely on the list: `grep_files {"pattern":"preserv|context|push"}` — the
/// exactly-correct search for a "pass the context through" bug — was gated as
/// full_access, so the coder could not explore the repo at all and scored 0/16
/// while the external arm, which has its own sandbox, scored 75% on the same
/// backbone. `path` is intentionally NOT here: a search *targeting* a sensitive
/// path should still be able to escalate.
const SEARCH_NEEDLE_KEYS: &[&str] = &["pattern", "query"];

/// Return `params` with the non-actionable payload keys removed, so risk
/// classification scans only params that describe the call's *effect* (e.g.
/// `path`) rather than data the tool merely writes or looks for. Every other tool
/// passes through unchanged — `shell`'s `command` IS the action and stays
/// scanned. See the call site for why payloads must not be keyword-scanned.
fn strip_write_payload_for_scan(tool: &str, params: &Value) -> Value {
    let payload_keys: &[&str] = match tool {
        "edit_file" | "write_file" => WRITE_PAYLOAD_KEYS,
        "grep_files" | "search_files" => SEARCH_NEEDLE_KEYS,
        _ => return params.clone(),
    };
    match params {
        Value::Object(map) => Value::Object(
            map.iter()
                .filter(|(k, _)| !payload_keys.contains(&k.as_str()))
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
        ),
        other => other.clone(),
    }
}

/// Classify a tool call to a risk tier, **param-aware**: reuse car_policy's
/// `RiskClassifier` (which scans the tool name *and* string parameters for
/// full-access keywords, so a `shell` running `kubectl apply` or reading a secret
/// escalates to full_access), floored by the name-based mapping so a plain
/// `write_file` is still at least `sandbox_edit`. Falls back to the name map if
/// the call can't be shaped into an `Action`.
fn classify_tool_call(
    classifier: &car_policy::permission::RiskClassifier,
    declared_tiers: Option<&HashMap<String, PermissionTier>>,
    tool: &str,
    params: &Value,
) -> PermissionTier {
    // NOTE: this deserialize omits `id`, relying on `car_ir::Action.id` being
    // `#[serde(default = "short_id")]` (and `tool`/`parameters` defaulting too).
    // The no-downgrade guarantee — classify sees the SAME tool+params that
    // execute — rests on this deserialize succeeding for every well-formed call.
    // If `Action.id` ever becomes non-defaulting, this falls to the weaker
    // name-map tier while execution proceeds: a silent downgrade. Keep it
    // defaulted, or set an `id` here.
    let base = declared_tiers
        .and_then(|tiers| tiers.get(tool).copied())
        .unwrap_or_else(|| assistant_tool_tier(tool));
    // File-write tools carry the file BODY in a param (`new_text`/`old_text` for
    // edit_file, `content` for write_file). That body is DATA being written, not
    // a command, so it must not be keyword-scanned for full-access escalation:
    // otherwise editing any file whose text merely contains a common word like
    // "format", "apply", "request", "delete", or "token" wrongly escalates the
    // edit to full_access and — for a non-interactive agent like the coder —
    // HARD-BLOCKS it (surfaced by the coder A/B: an `edit_file` on `strutils.py`,
    // which contains "format", was gated as full_access with no approval
    // channel). The same holds for a read-only search: `grep_files`'s `pattern`
    // is the needle, not a command — grepping for "push" pushes nothing — and a
    // web codebase's vocabulary (request/push/token/secret/send/http) is almost
    // entirely on the keyword list, which blocked the coder's exploration
    // outright (0/16 on flask while the external arm scored 75% on the same
    // backbone). Scan only the actionable params (the `path` survives, so a write
    // or search targeting a sensitive path still escalates). Other tools pass
    // through unchanged — `shell`'s command param IS the action and stays scanned.
    let scan_params = strip_write_payload_for_scan(tool, params);
    let action_json = serde_json::json!({
        "type": "tool_call",
        "tool": tool,
        "parameters": scan_params,
    });
    match serde_json::from_value::<car_ir::Action>(action_json) {
        // Adopt the classifier's verdict ONLY when it escalates to full_access
        // (its param keyword scan — a `shell` running a deploy or reading a
        // secret). Its conservative sandbox_edit *baseline* for any tool call is
        // deliberately ignored: it would wrongly gate a plain `read_file` behind
        // approval under the Balanced default, defeating "auto-allow safe reads".
        Ok(action) if classifier.classify(&action) == PermissionTier::FullAccess => {
            PermissionTier::FullAccess
        }
        _ => base,
    }
}

/// Public param-aware tier classification for one tool call, for callers outside
/// the assistant loop (e.g. `WorktreeExecutor`). Builds a fresh classifier — fine
/// at tool-call cadence.
pub fn classify_tool_tier(tool: &str, params: &Value) -> PermissionTier {
    let classifier = car_policy::permission::RiskClassifier::new();
    classify_tool_call(&classifier, None, tool, params)
}

/// Public classifier variant for the flagship assistant, where the exact
/// advertised tool definitions are available. This is the path supervised
/// `car do --serve` uses so newly-added tools with `"tier"` metadata don't need
/// a second hand-maintained permission map.
pub fn classify_tool_tier_with_defs(
    tool: &str,
    params: &Value,
    tool_defs: &[Value],
) -> PermissionTier {
    let classifier = car_policy::permission::RiskClassifier::new();
    let declared_tiers = declared_tool_tiers(tool_defs);
    classify_tool_call(&classifier, Some(&declared_tiers), tool, params)
}

/// Build the live per-agent approval policy the assistant loop enforces: classify
/// each tool call, resolve the agent's posture from the (reloaded) store, and map
/// it to an allow / require-approval / deny decision. Reloading per call keeps
/// the decision live as the operator edits Agent Permissions — tool calls are
/// seconds apart, so the read cost is irrelevant.
pub fn build_approval_policy(
    agent_id: String,
    tool_defs: Vec<Value>,
) -> crate::assistant::agent_loop::ApprovalPolicyFn {
    use crate::assistant::agent_loop::ToolApprovalDecision;
    let classifier = car_policy::permission::RiskClassifier::new();
    let declared_tiers = declared_tool_tiers(&tool_defs);
    std::sync::Arc::new(move |tool: &str, params: &Value| {
        let tier = classify_tool_call(&classifier, Some(&declared_tiers), tool, params);
        match load_policy().resolve(&agent_id, tier) {
            ApprovalMode::AlwaysAllow => ToolApprovalDecision::Allow,
            ApprovalMode::RequireApproval => ToolApprovalDecision::RequireApproval,
            ApprovalMode::Deny => ToolApprovalDecision::Deny(format!(
                "'{tool}' is denied for this agent by your Agent Permissions settings"
            )),
        }
    })
}

/// Approval policy for governed production engineering. Full-access actions
/// can never inherit a standing auto-allow: each push, deployment, database or
/// production mutation must produce its own digest-bound approval event.
pub fn build_governed_approval_policy(
    agent_id: String,
    tool_defs: Vec<Value>,
) -> crate::assistant::agent_loop::ApprovalPolicyFn {
    use crate::assistant::agent_loop::ToolApprovalDecision;
    let classifier = car_policy::permission::RiskClassifier::new();
    let declared_tiers = declared_tool_tiers(&tool_defs);
    std::sync::Arc::new(move |tool: &str, params: &Value| {
        let policy = load_policy();
        // The generic shell schema has a SandboxEdit floor, but governed host
        // investigations need a narrow class of observational commands to be
        // genuinely read-only. Keep this allowlist fail-closed and still honor
        // an operator who explicitly denies the ReadOnly tier.
        if tool == "shell" && governed_read_only_shell(params) {
            return match policy.resolve(&agent_id, PermissionTier::ReadOnly) {
                ApprovalMode::AlwaysAllow => ToolApprovalDecision::Allow,
                ApprovalMode::RequireApproval => ToolApprovalDecision::RequireApproval,
                ApprovalMode::Deny => ToolApprovalDecision::Deny(
                    "read-only shell diagnostics are denied for this agent by your Agent Permissions settings".into(),
                ),
            };
        }
        let tier = classify_tool_call(&classifier, Some(&declared_tiers), tool, params);
        if tier == PermissionTier::FullAccess {
            return ToolApprovalDecision::RequireApproval;
        }
        match policy.resolve(&agent_id, tier) {
            ApprovalMode::AlwaysAllow => ToolApprovalDecision::Allow,
            ApprovalMode::RequireApproval => ToolApprovalDecision::RequireApproval,
            ApprovalMode::Deny => ToolApprovalDecision::Deny(format!(
                "'{tool}' is denied for this agent by your Agent Permissions settings"
            )),
        }
    })
}

/// Strict observational shell subset for governed engineering investigations.
/// Separators and redirects are parsed outside quotes so a quoted Kusto query
/// may contain `|`. Pipelines are allowed only when every stage independently
/// belongs to the observational allowlist; substitutions and writes fail closed.
fn governed_read_only_shell(params: &Value) -> bool {
    let Some(command) = params.get("command").and_then(Value::as_str) else {
        return false;
    };
    let Some(segments) = observational_segments(command) else {
        return false;
    };
    !segments.is_empty()
        && segments
            .iter()
            .all(|segment| observational_segment(segment))
}

fn observational_segments(command: &str) -> Option<Vec<String>> {
    if command.contains('`') || command.contains("$(") || command.contains(['\r', '\n']) {
        return None;
    }
    let mut segments = Vec::new();
    let mut current = String::new();
    let mut single = false;
    let mut double = false;
    let mut escaped = false;
    let chars: Vec<char> = command.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let ch = chars[i];
        if escaped {
            current.push(ch);
            escaped = false;
            i += 1;
            continue;
        }
        if ch == '\\' && !single {
            current.push(ch);
            escaped = true;
            i += 1;
            continue;
        }
        if ch == '\'' && !double {
            single = !single;
            current.push(ch);
            i += 1;
            continue;
        }
        if ch == '"' && !single {
            double = !double;
            current.push(ch);
            i += 1;
            continue;
        }
        if !single && !double {
            if matches!(ch, ';' | '>' | '<') {
                return None;
            }
            if ch == '|' {
                // `||` changes control flow and can hide a failing diagnostic;
                // a single pipe is safe only because every resulting stage is
                // subsequently checked against `observational_segment`.
                if chars.get(i + 1) == Some(&'|') {
                    return None;
                }
                let segment = current.trim();
                if segment.is_empty() {
                    return None;
                }
                segments.push(segment.to_string());
                current.clear();
                i += 1;
                continue;
            }
            if ch == '&' {
                if chars.get(i + 1) != Some(&'&') {
                    return None;
                }
                let segment = current.trim();
                if segment.is_empty() {
                    return None;
                }
                segments.push(segment.to_string());
                current.clear();
                i += 2;
                continue;
            }
        }
        current.push(ch);
        i += 1;
    }
    if single || double || escaped {
        return None;
    }
    let tail = current.trim();
    if tail.is_empty() {
        return None;
    }
    segments.push(tail.to_string());
    Some(segments)
}

fn observational_segment(segment: &str) -> bool {
    let tokens: Vec<&str> = segment
        .split_whitespace()
        .map(|token| token.trim_matches(['\'', '"']))
        .filter(|token| !token.is_empty())
        .collect();
    let Some(verb) = tokens.first().copied() else {
        return false;
    };
    if verb.contains('=') {
        return false;
    }
    match verb {
        "cd" => tokens.len() == 2,
        "pwd" => tokens.len() == 1,
        "ls" | "cat" | "head" | "tail" => true,
        "sed" => !tokens.iter().skip(1).any(|token| {
            *token == "-i" || token.starts_with("-i.") || token.starts_with("--in-place")
        }),
        "rg" => !tokens
            .iter()
            .skip(1)
            .any(|token| token.starts_with("--pre") || *token == "--files-with-matches"),
        "git" => {
            let Some(subcommand) = tokens.get(1).copied() else {
                return false;
            };
            matches!(
                subcommand,
                "status" | "log" | "show" | "diff" | "rev-parse" | "remote" | "branch"
            ) && !tokens.iter().skip(2).any(|token| {
                *token == "-o"
                    || token.starts_with("--output")
                    || *token == "--edit"
                    || *token == "-e"
                    || *token == "add"
                    || *token == "set-url"
                    || *token == "remove"
                    || *token == "rename"
            })
        }
        "az" => match (tokens.get(1).copied(), tokens.get(2).copied()) {
            (Some("account" | "resource" | "webapp"), Some("show" | "list")) => true,
            (Some("monitor"), Some("app-insights")) => tokens.get(3) == Some(&"query"),
            (Some("pipelines"), Some("show" | "list")) => true,
            (Some("pipelines"), Some("runs")) => tokens.get(3) == Some(&"show"),
            _ => false,
        },
        _ => false,
    }
}

fn policy_to_json(policy: &AgentPermissionPolicy) -> Value {
    serde_json::to_value(policy).unwrap_or_else(|_| json!({}))
}

fn tier_param(v: &Value) -> Option<PermissionTier> {
    v.get("tier")
        .and_then(|t| t.as_str())
        .and_then(PermissionTier::from_str_opt)
}

// MARK: - Handlers

pub fn handle_get(_req: &JsonRpcMessage) -> Result<Value, String> {
    Ok(policy_to_json(&load_policy()))
}

/// `{ agent_id, mode, tier? }` — set one tier (or all tiers if `tier` omitted)
/// for a specific agent.
pub fn handle_set(req: &JsonRpcMessage) -> Result<Value, String> {
    let p = &req.params;
    let agent_id = p
        .get("agent_id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .ok_or("missing or empty agent_id")?;
    let mode = p
        .get("mode")
        .and_then(|v| v.as_str())
        .and_then(ApprovalMode::from_str_opt)
        .ok_or("missing or invalid mode (always_allow|require_approval|deny)")?;

    let (policy, ()) = update_policy(|policy| {
        match tier_param(p) {
            Some(tier) => policy.set_agent(agent_id, tier, mode),
            None => policy.set_agent_uniform(agent_id, mode),
        }
        Ok(())
    })?;
    Ok(policy_to_json(&policy))
}

/// `{ preset }` (cautious|balanced|trusting) or `{ tier, mode }` — move the
/// default posture applied to agents without an override.
pub fn handle_set_default(req: &JsonRpcMessage) -> Result<Value, String> {
    let p = &req.params;
    let preset = p
        .get("preset")
        .and_then(|v| v.as_str())
        .and_then(ApprovalPreset::from_str_opt);
    let tier_mode = if preset.is_none() {
        let tier = tier_param(p).ok_or("missing preset, or tier+mode")?;
        let mode = p
            .get("mode")
            .and_then(|v| v.as_str())
            .and_then(ApprovalMode::from_str_opt)
            .ok_or("missing or invalid mode")?;
        Some((tier, mode))
    } else {
        None
    };
    let (policy, ()) = update_policy(|policy| {
        if let Some(preset) = preset {
            policy.set_default_preset(preset);
        } else if let Some((tier, mode)) = tier_mode {
            policy.set_default(tier, mode);
        }
        Ok(())
    })?;
    Ok(policy_to_json(&policy))
}

/// `{ agent_id }` — drop an agent's tier override so it reverts to the default.
pub fn handle_reset(req: &JsonRpcMessage) -> Result<Value, String> {
    let agent_id = req
        .params
        .get("agent_id")
        .and_then(|v| v.as_str())
        .ok_or("missing agent_id")?;
    let (policy, ()) = update_policy(|policy| {
        policy.reset_agent(agent_id);
        Ok(())
    })?;
    Ok(policy_to_json(&policy))
}

/// `{ agent_id, tier }` — the resolved mode the HITL/executor path consults.
pub fn handle_evaluate(req: &JsonRpcMessage) -> Result<Value, String> {
    let p = &req.params;
    let agent_id = p
        .get("agent_id")
        .and_then(|v| v.as_str())
        .ok_or("missing agent_id")?;
    let tier = tier_param(p).ok_or("missing or invalid tier")?;
    let policy = load_policy();
    let mode = policy.resolve(agent_id, tier);
    Ok(json!({
        "agent_id": agent_id,
        "tier": tier.as_str(),
        "mode": mode.as_str(),
        "has_override": policy.has_override(agent_id),
    }))
}

pub(crate) fn exact_tool_params(params: &Value) -> Result<(&str, &str), String> {
    let agent_id = params
        .get("agent_id")
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())
        .ok_or("missing or empty agent_id")?;
    let tool = params
        .get("tool")
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())
        .ok_or("missing or empty tool")?;
    Ok((agent_id, tool))
}

pub(crate) fn requested_tool_mode(params: &Value) -> Result<ApprovalMode, String> {
    params
        .get("mode")
        .and_then(Value::as_str)
        .and_then(ApprovalMode::from_str_opt)
        .ok_or_else(|| "missing or invalid mode (always_allow|require_approval|deny)".to_string())
}

/// `{ agent_id, tool, mode }` — set one literal tool override. For
/// `always_allow`, the dispatcher supplies the digest it observed from the
/// live authenticated reverse-callback registration; callers cannot assert
/// their own schema identity.
pub fn handle_set_tool(
    req: &JsonRpcMessage,
    observed_schema_digest: Option<String>,
) -> Result<Value, String> {
    let (agent_id, tool) = exact_tool_params(&req.params)?;
    let mode = requested_tool_mode(&req.params)?;
    if req.params.get("schema_digest").is_some() {
        return Err(
            "schema_digest is server-recorded and must not be supplied by the caller".into(),
        );
    }
    let stored_digest = (mode == ApprovalMode::AlwaysAllow)
        .then_some(observed_schema_digest)
        .flatten();
    if mode == ApprovalMode::AlwaysAllow
        && !stored_digest.as_deref().is_some_and(valid_schema_digest)
    {
        return Err(
            "always_allow requires a live authenticated exact callback registration".into(),
        );
    }
    let (_policy, ()) = update_policy(|policy| {
        policy.set_tool(agent_id, tool, mode, stored_digest.clone());
        Ok(())
    })?;
    Ok(json!({
        "agent_id": agent_id,
        "tool": tool,
        "mode": mode.as_str(),
        "schema_digest": stored_digest,
        "authorization_source": "agent_tool_override",
    }))
}

/// `{ agent_id, tool }` — remove one literal tool override.
pub fn handle_reset_tool(req: &JsonRpcMessage) -> Result<Value, String> {
    let (agent_id, tool) = exact_tool_params(&req.params)?;
    let (_policy, removed) = update_policy(|policy| Ok(policy.reset_tool(agent_id, tool)))?;
    Ok(json!({
        "agent_id": agent_id,
        "tool": tool,
        "removed": removed,
    }))
}

/// `{ agent_id, tool, tier }` — report the exact tool override when one exists,
/// otherwise the current tier posture. This query never performs pattern
/// matching on either identifier.
pub fn handle_evaluate_tool(req: &JsonRpcMessage) -> Result<Value, String> {
    let (agent_id, tool) = exact_tool_params(&req.params)?;
    let tier = tier_param(&req.params).ok_or("missing or invalid tier")?;
    let policy = load_policy();
    let tool_override = policy.resolve_tool(agent_id, tool);
    let mode = tool_override
        .map(|rule| rule.mode)
        .unwrap_or_else(|| policy.resolve(agent_id, tier));
    Ok(json!({
        "agent_id": agent_id,
        "tool": tool,
        "tier": tier.as_str(),
        "mode": mode.as_str(),
        "has_tool_override": tool_override.is_some(),
        "schema_digest": tool_override.and_then(|rule| rule.schema_digest.as_deref()),
        "authorization_source": tool_override.map(|_| "agent_tool_override").unwrap_or("tier_policy"),
    }))
}

fn valid_schema_digest(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

#[cfg(test)]
mod tests {

    /// A read-only search must not be escalated by what it searches FOR. The
    /// keyword list is ordinary web vocabulary (`push`, `request`, `token`,
    /// `secret`), so scanning the needle made `grep_files` full_access — which
    /// HARD-BLOCKS a non-interactive agent (no approval channel). Surfaced by the
    /// coder A/B on flask: `{"pattern":"preserv|context|push"}`, the correct
    /// search for a "pass the context through" bug, was denied, and the coder
    /// scored 0/16 unable to explore the repo. Same class as #595's file bodies.
    #[test]
    fn grep_pattern_is_a_needle_not_a_command_and_never_escalates() {
        let blocked = serde_json::json!({"path": ".", "pattern": "preserv|context|push"});
        assert_eq!(
            classify_tool_tier("grep_files", &blocked),
            PermissionTier::ReadOnly,
            "searching for 'push' must not become a full-access action"
        );
        for needle in ["delete", "secret", "token", "http", "request", "rm "] {
            let p = serde_json::json!({"path": "src", "pattern": needle});
            assert_ne!(
                classify_tool_tier("grep_files", &p),
                PermissionTier::FullAccess,
                "grep for {needle:?} must not escalate"
            );
        }
        // But a search TARGETING a sensitive path still escalates: `path` is
        // actionable and stays scanned.
        let sensitive = serde_json::json!({"path": "~/.ssh/id_rsa", "pattern": "x"});
        assert_eq!(
            classify_tool_tier("grep_files", &sensitive),
            PermissionTier::FullAccess
        );
        // And `shell`'s command IS the action — still scanned.
        let sh = serde_json::json!({"command": "git push origin main"});
        assert_eq!(classify_tool_tier("shell", &sh), PermissionTier::FullAccess);
    }
    use super::*;

    #[test]
    fn name_map_floors_are_correct() {
        assert_eq!(assistant_tool_tier("read_file"), PermissionTier::ReadOnly);
        assert_eq!(
            assistant_tool_tier("write_file"),
            PermissionTier::SandboxEdit
        );
        assert_eq!(assistant_tool_tier("shell"), PermissionTier::SandboxEdit);
        assert_eq!(
            assistant_tool_tier("generate_image"),
            PermissionTier::SandboxEdit
        );
        assert_eq!(
            assistant_tool_tier("generate_speech"),
            PermissionTier::SandboxEdit
        );
        assert_eq!(
            assistant_tool_tier("http_request"),
            PermissionTier::FullAccess
        );
        assert_eq!(
            assistant_tool_tier("web_search"),
            PermissionTier::FullAccess
        );
        assert_eq!(assistant_tool_tier("remember"), PermissionTier::FullAccess);
        assert_eq!(
            assistant_tool_tier("generate_music"),
            PermissionTier::FullAccess
        );
        assert_eq!(
            assistant_tool_tier("generate_jingle"),
            PermissionTier::FullAccess
        );
        assert_eq!(
            assistant_tool_tier("generate_studio_image"),
            PermissionTier::FullAccess
        );
        assert_eq!(
            assistant_tool_tier("generate_song"),
            PermissionTier::FullAccess
        );
        assert_eq!(
            assistant_tool_tier("run_applescript"),
            PermissionTier::FullAccess
        );
    }

    #[test]
    fn shell_running_a_deploy_escalates_to_full_access() {
        // The security-relevant case: a shell command isn't just "edit" when it
        // deploys or touches secrets — the param-aware classifier must escalate,
        // so an operator who allows sandbox_edit still gets asked for a deploy.
        let classifier = car_policy::permission::RiskClassifier::new();
        let params = json!({ "command": "kubectl apply -f prod.yaml" });
        let tier = classify_tool_call(&classifier, None, "shell", &params);
        assert_eq!(tier, PermissionTier::FullAccess);

        // A benign shell stays at the sandbox_edit floor.
        let benign = json!({ "command": "ls -la" });
        assert_eq!(
            classify_tool_call(&classifier, None, "shell", &benign),
            PermissionTier::SandboxEdit
        );
    }

    #[test]
    fn governed_read_only_shell_accepts_diagnostics_and_quoted_kusto() {
        for command in [
            "git status",
            "cd /repo && git status && git rev-parse HEAD && git diff --stat",
            "rg -n Veryon api/FMS.Api",
            "sed -n '150,220p' api/FMS.Api/Services/VeryonClient.cs",
            "az account show --output json",
            "az resource list --resource-type microsoft.insights/components --output json",
            "az pipelines runs show --id 23708 --output json",
            "az monitor app-insights query --analytics-query \"exceptions | where timestamp > ago(1d) | summarize count()\"",
            "git log --oneline --all | head -20",
            "rg -n Veryon api/FMS.Api | head -50",
        ] {
            assert!(
                governed_read_only_shell(&json!({"command": command})),
                "expected observational command: {command}"
            );
        }
    }

    #[test]
    fn governed_read_only_shell_rejects_mutation_and_shell_composition() {
        for command in [
            "git push origin main",
            "git remote set-url origin https://example.invalid/repo",
            "git diff --output=leak.patch",
            "sed -i '' s/a/b/ file",
            "rg x --pre 'sh -c evil'",
            "az webapp restart --name fms",
            "git status > status.txt",
            "git status | tee status.txt",
            "git status || touch changed",
            "git status; touch changed",
            "git status && $(touch changed)",
            "FOO=1 git status",
        ] {
            assert!(
                !governed_read_only_shell(&json!({"command": command})),
                "expected gated command: {command}"
            );
        }
    }

    #[test]
    fn public_classifier_escalates_and_floors() {
        // The helper WorktreeExecutor uses: param-aware escalation + name floor.
        assert_eq!(
            classify_tool_tier("shell", &json!({ "command": "terraform apply" })),
            PermissionTier::FullAccess
        );
        assert_eq!(
            classify_tool_tier("write_file", &json!({ "path": "a.txt", "content": "hi" })),
            PermissionTier::SandboxEdit
        );
        assert_eq!(
            classify_tool_tier("remember", &json!({ "subject": "token", "body": "secret" })),
            PermissionTier::FullAccess
        );
        assert_eq!(
            classify_tool_tier(
                "run_applescript",
                &json!({ "script": "display dialog \"hi\"" })
            ),
            PermissionTier::FullAccess
        );
        assert_eq!(
            classify_tool_tier("read_file", &json!({ "path": "a.txt" })),
            PermissionTier::ReadOnly
        );
    }

    #[test]
    fn file_write_body_is_not_keyword_scanned() {
        // The coder-A/B regression: an edit whose BODY contains an ordinary word
        // that happens to be a full-access keyword ("format", "delete", "apply",
        // "token", "push") must stay sandbox_edit, not escalate to full_access
        // and hard-block the edit. Only actionable params (path) are scanned.
        assert_eq!(
            classify_tool_tier(
                "edit_file",
                &json!({
                    "path": "boltons/strutils.py",
                    "old_text": "def split_punct_ws(text):",
                    "new_text": "def split(text, sep=None, maxsplit=-1):\n    \"\"\"Split text; a callable form is handy when you need to format or delete tokens.\"\"\"\n    return text.split(sep, maxsplit)\n\n\ndef split_punct_ws(text):",
                })
            ),
            PermissionTier::SandboxEdit,
            "an edit whose body mentions format/delete/token must not escalate"
        );
        assert_eq!(
            classify_tool_tier(
                "write_file",
                &json!({ "path": "src/net.rs", "content": "// http request push delete secret token" })
            ),
            PermissionTier::SandboxEdit,
            "write_file body keywords must not escalate"
        );
        // But a full-access keyword in the PATH still escalates — the actionable
        // param is not stripped.
        assert_eq!(
            classify_tool_tier(
                "write_file",
                &json!({ "path": "/home/u/.ssh/id_rsa", "content": "ok" })
            ),
            PermissionTier::FullAccess,
            "a sensitive target PATH must still escalate"
        );
        // And `shell` — whose param IS the command — is unaffected: still scanned.
        assert_eq!(
            classify_tool_tier("shell", &json!({ "command": "git push --force" })),
            PermissionTier::FullAccess,
            "shell command scanning must be unchanged"
        );
    }

    #[test]
    fn schema_declared_tier_is_the_supervised_policy_floor() {
        let defs = vec![
            json!({"name": "new_external_sink", "tier": "full_access"}),
            json!({"name": "new_writer", "tier": "sandbox_edit"}),
            json!({"name": "plain_reader"}),
        ];

        assert_eq!(
            classify_tool_tier_with_defs("new_external_sink", &json!({}), &defs),
            PermissionTier::FullAccess
        );
        assert_eq!(
            classify_tool_tier_with_defs("new_writer", &json!({}), &defs),
            PermissionTier::SandboxEdit
        );
        assert_eq!(
            classify_tool_tier_with_defs("plain_reader", &json!({}), &defs),
            PermissionTier::ReadOnly
        );
    }

    #[test]
    fn deny_posture_blocks_via_resolved_policy() {
        // A fully-denied agent resolves to Deny at every tier (independent of the
        // on-disk store, which the CI environment may not have).
        let mut policy = car_policy::AgentPermissionPolicy::default();
        policy.set_agent_uniform("blocked", ApprovalMode::Deny);
        assert_eq!(
            policy.resolve("blocked", PermissionTier::ReadOnly),
            ApprovalMode::Deny
        );
    }

    #[test]
    fn concurrent_policy_mutations_are_serialized_without_lost_updates() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("agent-permissions.json");
        let mut workers = Vec::new();
        for index in 0..16 {
            let path = path.clone();
            workers.push(std::thread::spawn(move || {
                update_policy_at(path, |policy| {
                    policy.set_agent_uniform(&format!("agent-{index}"), ApprovalMode::Deny);
                    Ok(())
                })
                .unwrap();
            }));
        }
        for worker in workers {
            worker.join().unwrap();
        }

        let persisted: AgentPermissionPolicy =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        for index in 0..16 {
            assert_eq!(
                persisted.resolve(&format!("agent-{index}"), PermissionTier::FullAccess),
                ApprovalMode::Deny
            );
        }
        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
            .unwrap()
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
            .collect();
        assert!(
            leftovers.is_empty(),
            "temporary files leaked: {leftovers:?}"
        );
    }

    #[test]
    fn corrupt_policy_retains_last_valid_or_uses_cautious_floor() {
        let dir = tempfile::tempdir().unwrap();
        let remembered = dir.path().join("remembered.json");
        update_policy_at(remembered.clone(), |policy| {
            policy.set_agent_uniform("blocked", ApprovalMode::Deny);
            Ok(())
        })
        .unwrap();
        std::fs::write(&remembered, "{broken").unwrap();
        let mut store = policy_store()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let retained = load_policy_locked(&remembered, &mut store);
        assert_eq!(
            retained.resolve("blocked", PermissionTier::FullAccess),
            ApprovalMode::Deny
        );

        let never_valid = dir.path().join("never-valid.json");
        std::fs::write(&never_valid, "{also-broken").unwrap();
        let cautious = load_policy_locked(&never_valid, &mut store);
        assert_eq!(
            cautious.resolve("unknown", PermissionTier::ReadOnly),
            ApprovalMode::RequireApproval
        );
    }
}