nexo-core 0.2.1

Agent runtime: event bus, sessions, plugin trait, heartbeat, A2A delegation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
#![allow(clippy::all)] // scaffolding — re-enable once fully shipped

//! Plan-mode state, refusal, and tool classification.
//!
//! Plan mode is a per-goal toggle that puts the agent into a read-only
//! "exploration + design" phase. While active, every mutating tool call
//! is short-circuited at the dispatcher with a [`PlanModeRefusal`], and
//! the model is expected to call `ExitPlanMode { final_plan }` once it
//! has a coherent plan. Operator approval (delivered via the pairing
//! channel that owns the goal) unlocks plan mode and lets the model
//! resume mutating work.
//!
//! On entering plan mode the prior mode is saved so it can be
//! restored on exit, mirroring established plan-mode implementations.
//!
//! Centralised gate: every mutating tool MUST appear in
//! [`MUTATING_TOOLS`] and every read-only tool in [`READ_ONLY_TOOLS`].
//! [`assert_registry_classified`] is invoked at boot to refuse start-up
//! if a registered tool falls in neither bucket — ensures new tools are
//! never silently exempt from plan-mode gating.

use serde::{Deserialize, Serialize};

/// Restore target captured when plan mode is entered.
///
/// Mirrors the leak's `prePlanMode` field
/// (`permissionSetup.ts:1458-1489`). Today we only track the binary
/// "was-plan / was-not-plan" axis, but the field is a struct enum so
/// future modes (acceptEdits, bypassPermissions) can be added without
/// breaking existing serialised state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PriorMode {
    /// Default permission mode — reapply standard policy on exit.
    Default,
}

impl Default for PriorMode {
    fn default() -> Self {
        PriorMode::Default
    }
}

/// Why plan mode was entered. Surfaces in the
/// `[plan-mode] entered ... reason: <…>` notify line and inside
/// [`PlanModeRefusal::entered_reason`] so the model can react with the
/// right framing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PlanModeReason {
    /// Model called `EnterPlanMode { reason }` voluntarily.
    ModelRequested {
        /// Optional free-form reason from the model.
        reason: Option<String>,
    },
    /// Operator forced plan mode via channel command.
    OperatorRequested,
    /// Dispatcher pre-empted a destructive command and auto-entered
    /// plan mode. `tripped_check` carries the destructive-classifier
    /// verdict (e.g. `"rm -rf $HOME"`, `"sed -i without validated
    /// path"`).
    AutoDestructive {
        /// Destructive-classifier verdict that triggered the
        /// auto-enter.
        tripped_check: String,
    },
}

/// Plan-mode state machine kept on the goal's [`AgentContext`] and
/// mirrored in `agent_registry.goals.plan_mode`.
///
/// SQLite is canonical so daemon restart preserves the state via goal
/// reattach; the in-memory copy is a hot cache.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum PlanModeState {
    #[default]
    Off,
    On {
        /// Unix-seconds timestamp the state flipped to On.
        entered_at: i64,
        /// Why plan mode was entered.
        reason: PlanModeReason,
        /// Mode to restore on `ExitPlanMode` approval.
        prior_mode: PriorMode,
    },
}

impl PlanModeState {
    pub fn is_on(&self) -> bool {
        matches!(self, PlanModeState::On { .. })
    }

    pub fn is_off(&self) -> bool {
        matches!(self, PlanModeState::Off)
    }

    /// Convenience constructor for `On` states.
    pub fn on(entered_at: i64, reason: PlanModeReason) -> Self {
        PlanModeState::On {
            entered_at,
            reason,
            prior_mode: PriorMode::default(),
        }
    }
}

/// Coarse classification surfaced inside [`PlanModeRefusal`] so the
/// model can react with the right framing without parsing tool names.
///
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolKind {
    /// Bash / shell command. Mutating subset gated; read-only subset
    /// allowed (the destructive classifier provides the verdict at runtime).
    Bash,
    /// `FileWrite`, `FileEdit`, `NotebookEdit`.
    FileEdit,
    /// Plugin outbound — WhatsApp/Telegram/email send, browser
    /// click/type/navigate, etc.
    Outbound,
    /// `delegate_to`, `TeamCreate`.
    Delegate,
    /// `program_phase`, `dispatch_followup`.
    Dispatch,
    /// `ScheduleCron`, future schedulers.
    Schedule,
    /// `Config { op: apply }`.
    Config,
    /// `FileRead`, `Glob`, `Grep`, `WebSearch`, MCP read tools, plan
    /// mode tools themselves, `AskUserQuestion`, `Sleep`, etc.
    ReadOnly,
}

impl ToolKind {
    pub fn is_mutating(self) -> bool {
        !matches!(self, ToolKind::ReadOnly)
    }
}

/// Structured refusal returned when a mutating tool is invoked while
/// plan mode is on. The dispatcher serialises this as a
/// `tool_result { is_error: true }` so all four LLM provider clients
/// (Anthropic, MiniMax, OpenAI-compat, Gemini) classify it identically.
///
/// Diff vs leak: leak returns `{result: false, message: '…',
/// errorCode: 1}` from `validateInput` (`ExitPlanModeV2Tool.ts:213-218`)
/// — a string. We carry structured fields so the model can reason
/// without parsing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanModeRefusal {
    /// Tool name the model attempted (e.g. `"FileWrite"`).
    pub tool_name: String,
    /// Coarse classification.
    pub tool_kind: ToolKind,
    /// One-line directive for the model.
    pub hint: &'static str,
    /// Unix-seconds timestamp plan mode was entered. Lets the model
    /// see how long it has been planning.
    pub entered_at: i64,
    /// Why plan mode is currently active.
    pub entered_reason: PlanModeReason,
}

impl PlanModeRefusal {
    pub const HINT: &'static str = "Call ExitPlanMode { final_plan } when the plan is ready.";
}

/// Frozen system-prompt suffix injected on every turn while plan
/// mode is on. The string is intentionally `&'static` (no
/// timestamps, no per-goal substitutions) so the Anthropic prompt
/// cache stays warm across turns: sneaking variable text into
/// "stable" blocks would cause cache misses.
pub const PLAN_MODE_SYSTEM_HINT: &str = "[plan-mode] Active. Read-only exploration. Mutating tools refuse with PlanModeRefusal. Call ExitPlanMode { final_plan } when ready.";

/// Return the canonical plan-mode hint when plan mode is active,
/// `None` otherwise. Callers append this to the per-turn system
/// prompt block (e.g. `channel_meta` in
/// `crates/core/src/agent/prompt_assembly.rs`).
pub fn plan_mode_system_hint(state: &PlanModeState) -> Option<&'static str> {
    state.is_on().then_some(PLAN_MODE_SYSTEM_HINT)
}

/// Acceptance verdict surfaced via the `[plan-mode] acceptance: ...`
/// notify line. The variants match the two terminal states an
/// acceptance run can reach.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceptanceOutcome {
    Pass,
    Fail,
}

impl AcceptanceOutcome {
    fn as_str(self) -> &'static str {
        match self {
            AcceptanceOutcome::Pass => "pass",
            AcceptanceOutcome::Fail => "fail",
        }
    }
}

/// Format the canonical `[plan-mode] entered ...` notify line. Frozen
/// shape: any change here breaks operator-side parsers + dashboards.
pub fn format_notify_entered(entered_at: i64, reason: &PlanModeReason) -> String {
    let ts = chrono::DateTime::from_timestamp(entered_at, 0)
        .map(|d| d.to_rfc3339())
        .unwrap_or_else(|| entered_at.to_string());
    let reason_str = match reason {
        PlanModeReason::ModelRequested { reason: Some(r) } => format!("model: {r}"),
        PlanModeReason::ModelRequested { reason: None } => "model".to_string(),
        PlanModeReason::OperatorRequested => "operator".to_string(),
        PlanModeReason::AutoDestructive { tripped_check } => {
            format!("auto-destructive: {tripped_check}")
        }
    };
    format!("[plan-mode] entered at {ts} — reason: {reason_str}")
}

/// Format the canonical `[plan-mode] exited — plan: ...` notify
/// line. The plan body is truncated to 200 chars with an ellipsis;
/// the full body lives in the turn log (referenced by index).
pub fn format_notify_exited(plan: &str, turn_log_index: u64) -> String {
    let snippet: String = plan.chars().take(200).collect();
    let ellipsis = if plan.chars().count() > 200 {
        ""
    } else {
        ""
    };
    format!(
        "[plan-mode] exited — plan: {snippet}{ellipsis} (full plan in turn log #{turn_log_index})"
    )
}

/// Format the canonical `[plan-mode] acceptance: pass|fail (...)`
/// notify line. `summary` is rendered verbatim and SHOULD be one
/// short line — operators read this on the pairing channel.
pub fn format_notify_acceptance(outcome: AcceptanceOutcome, summary: &str) -> String {
    format!(
        "[plan-mode] acceptance: {} ({})",
        outcome.as_str(),
        summary.trim()
    )
}

/// Format the canonical `[plan-mode] refused tool=<name> kind=<kind>`
/// notify line — emitted when a mutating call short-circuits at the
/// dispatcher gate.
pub fn format_notify_refused(refusal: &PlanModeRefusal) -> String {
    let kind = match refusal.tool_kind {
        ToolKind::Bash => "bash",
        ToolKind::FileEdit => "file_edit",
        ToolKind::Outbound => "outbound",
        ToolKind::Delegate => "delegate",
        ToolKind::Dispatch => "dispatch",
        ToolKind::Schedule => "schedule",
        ToolKind::Config => "config",
        ToolKind::ReadOnly => "read_only",
    };
    format!(
        "[plan-mode] refused tool={tool} kind={kind}",
        tool = refusal.tool_name
    )
}

/// Canonical mutating-tool list. Adding a tool to the registry without
/// listing it here (or in [`READ_ONLY_TOOLS`]) makes
/// [`assert_registry_classified`] panic at boot.
///
/// Forward references (entries already valid even when not yet
/// registered — the gate just never fires for an unregistered
/// name): `ScheduleCron`, `RemoteTrigger`, `Config { op: apply }`,
/// `NotebookEdit`, `TeamCreate`.
pub const MUTATING_TOOLS: &[&str] = &[
    // Bash is special-cased — see `is_mutating_tool_call` below.
    "Bash",
    // File edits.
    "FileWrite",
    "FileEdit",
    "NotebookEdit",
    // Dispatch / programming.
    "program_phase",
    "delegate_to",
    "dispatch_followup",
    // Schedulers + remote.
    "ScheduleCron",
    "cron_create",
    "cron_delete",
    "cron_pause",
    "cron_resume",
    "start_followup",
    "cancel_followup",
    "RemoteTrigger",
    // REPL can exec arbitrary code (similar risk to Bash).
    "Repl",
    // Config self-edit — only `apply` op is mutating; the gate
    // resolves the op at call time. `Config` as a name is listed here
    // so an unclassified registration fails the boot assert.
    "Config",
    // Team-management tools. All three either spawn /
    // tear down N goals or deliver DMs that wake idle teammates.
    "TeamCreate",
    "TeamDelete",
    "TeamSendMessage",
    // Memory snapshot writes a full bundle to disk + a sibling
    // SHA-256 file. Restore is operator-only (CLI) and explicitly
    // not exposed as a tool.
    "memory_snapshot",
];

/// Canonical read-only tool list. Tools not in either bucket trigger a
/// boot panic. New plan-mode tools live here so they remain callable
/// while plan mode is on.
pub const READ_ONLY_TOOLS: &[&str] = &[
    "FileRead",
    "Glob",
    "Grep",
    "WebSearch",
    "WebFetch",
    "ListMcpResources",
    "ReadMcpResource",
    "list_mcp_resources",
    "read_mcp_resource",
    "ToolSearch",
    "AskUserQuestion",
    "Sleep",
    "EnterPlanMode",
    "ExitPlanMode",
    // Intra-turn scratch list. Mutates only the
    // per-goal todos cache; never touches the workspace, broker, or
    // external state.
    "TodoWrite",
    // Terminal output validator. Pure validate-and-echo;
    // never touches any external state.
    "SyntheticOutput",
    // Cron list reads the schedule store.
    "cron_list",
    "check_followup",
    // LSP tool. All ops (go_to_def, hover,
    // references, workspace_symbol, diagnostics) are pure
    // queries against the language server; classifying once at
    // tool name level is enough since the discriminator lives
    // INSIDE the args, not the tool name.
    "Lsp",
    // Read-only audit-log tool for ConfigTool
    // proposals. Always available (not gated by the Cargo
    // feature flag); reads only.
    "config_changes_tail",
    // Read-only team query tools.
    "TeamList",
    "TeamStatus",
    // Memory + observability tools that read but never write.
    "memory_search",
    "agent_query",
    "agent_turns_tail",
    "session_logs",
    "what_do_i_know",
    "who_am_i",
    "my_stats",
];

/// Decides whether `tool_name` is currently subject to plan-mode
/// gating. `Bash` returns `Some(ToolKind::Bash)` regardless — the
/// dispatcher pairs the verdict with the destructive classifier
/// to decide whether to actually refuse.
pub fn classify_tool(tool_name: &str) -> Option<ToolKind> {
    if MUTATING_TOOLS.contains(&tool_name) {
        return Some(match tool_name {
            "Bash" | "Repl" => ToolKind::Bash,
            "FileWrite" | "FileEdit" | "NotebookEdit" => ToolKind::FileEdit,
            "delegate_to" | "TeamCreate" | "TeamDelete" | "TeamSendMessage" => ToolKind::Delegate,
            "program_phase" | "dispatch_followup" => ToolKind::Dispatch,
            "ScheduleCron" | "start_followup" | "cancel_followup" => ToolKind::Schedule,
            "RemoteTrigger" => ToolKind::Outbound,
            "Config" => ToolKind::Config,
            _ => ToolKind::Outbound, // future plugin outbound names
        });
    }
    if READ_ONLY_TOOLS.contains(&tool_name) {
        return Some(ToolKind::ReadOnly);
    }
    // Plugin outbound names follow the `<channel>.<verb>` convention
    // (e.g. `whatsapp.send`, `browser.click`). Treat any name with a
    // dot as an outbound mutator so the boot assert does not need to
    // enumerate every plugin verb.
    if tool_name.contains('.') {
        return Some(ToolKind::Outbound);
    }
    None
}

/// Centralised gate consulted by `DispatchGate::check`. Returns
/// `Some(refusal)` when the call must be blocked, `None` to let it
/// through.
///
/// Bash short-circuit: callers pass `bash_is_mutating: Some(verdict)`
/// from the destructive classifier. When `None`, Bash is treated as
/// mutating in plan mode — fail-safe default to blocking when the
/// classifier returns Unknown.
pub fn gate_tool_call(
    state: &PlanModeState,
    tool_name: &str,
    bash_is_mutating: Option<bool>,
) -> Option<PlanModeRefusal> {
    gate_tool_call_with_args(state, tool_name, bash_is_mutating, &serde_json::Value::Null)
}

/// Args-aware gate. Same contract as [`gate_tool_call`] but
/// accepts the tool's call args so per-op discriminators can be
/// honoured. `Config { op: read }` is read-only and
/// should pass under plan-mode; `op: propose | apply` is mutating
/// and should refuse. Other tools fall through to the simple
/// classifier.
pub fn gate_tool_call_with_args(
    state: &PlanModeState,
    tool_name: &str,
    bash_is_mutating: Option<bool>,
    args: &serde_json::Value,
) -> Option<PlanModeRefusal> {
    let PlanModeState::On {
        entered_at,
        reason,
        prior_mode: _,
    } = state
    else {
        return None;
    };
    let kind = classify_tool(tool_name)?;
    // `Config { op: read }` is read-only despite
    // `Config` being in MUTATING_TOOLS. Fast path: when the tool is
    // `Config` and the op is `read`, bypass the gate entirely.
    if tool_name == "Config" {
        if let Some(op) = args.get("op").and_then(|v| v.as_str()) {
            if op == "read" {
                return None;
            }
        }
    }
    let blocked = match kind {
        ToolKind::Bash => bash_is_mutating.unwrap_or(true),
        ToolKind::ReadOnly => false,
        _ => true,
    };
    if !blocked {
        return None;
    }
    Some(PlanModeRefusal {
        tool_name: tool_name.to_string(),
        tool_kind: kind,
        hint: PlanModeRefusal::HINT,
        entered_at: *entered_at,
        entered_reason: reason.clone(),
    })
}

/// Boot-time guard: every name in `registered` must appear in
/// [`MUTATING_TOOLS`] or [`READ_ONLY_TOOLS`], OR follow the
/// `<channel>.<verb>` outbound convention. A tool that slips through
/// unclassified would silently bypass plan-mode gating, so we refuse
/// to start.
///
/// Returns the offending names instead of panicking so callers can
/// decide between hard-fail (production) and warn-only (dev fixtures).
pub fn unclassified_tools<I, S>(registered: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    registered
        .into_iter()
        .filter(|name| classify_tool(name.as_ref()).is_none())
        .map(|name| name.as_ref().to_string())
        .collect()
}

/// Hard-fail variant for production boot.
///
/// # Panics
/// If any registered tool is unclassified.
pub fn assert_registry_classified<I, S>(registered: I)
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let bad = unclassified_tools(registered);
    if !bad.is_empty() {
        panic!(
            "plan_mode: {} tool(s) registered without mutating/read-only \
             classification: {:?}. Add them to MUTATING_TOOLS or \
             READ_ONLY_TOOLS in crates/core/src/plan_mode.rs, or use the \
             `<channel>.<verb>` outbound convention.",
            bad.len(),
            bad
        );
    }
}

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

    #[test]
    fn state_default_off() {
        assert!(PlanModeState::default().is_off());
    }

    #[test]
    fn state_serde_roundtrip_on() {
        let state = PlanModeState::on(
            1_700_000_000,
            PlanModeReason::ModelRequested {
                reason: Some("explore auth flow".into()),
            },
        );
        let json = serde_json::to_string(&state).unwrap();
        let back: PlanModeState = serde_json::from_str(&json).unwrap();
        assert_eq!(state, back);
    }

    #[test]
    fn state_serde_roundtrip_auto_destructive() {
        let state = PlanModeState::on(
            1_700_000_000,
            PlanModeReason::AutoDestructive {
                tripped_check: "rm -rf $HOME".into(),
            },
        );
        let json = serde_json::to_string(&state).unwrap();
        let back: PlanModeState = serde_json::from_str(&json).unwrap();
        assert_eq!(state, back);
    }

    #[test]
    fn classify_known_mutators() {
        assert_eq!(classify_tool("Bash"), Some(ToolKind::Bash));
        assert_eq!(classify_tool("FileEdit"), Some(ToolKind::FileEdit));
        assert_eq!(classify_tool("delegate_to"), Some(ToolKind::Delegate));
        assert_eq!(classify_tool("ScheduleCron"), Some(ToolKind::Schedule));
        assert_eq!(classify_tool("Config"), Some(ToolKind::Config));
    }

    #[test]
    fn classify_known_read_only() {
        assert_eq!(classify_tool("FileRead"), Some(ToolKind::ReadOnly));
        assert_eq!(classify_tool("EnterPlanMode"), Some(ToolKind::ReadOnly));
        assert_eq!(classify_tool("ExitPlanMode"), Some(ToolKind::ReadOnly));
        assert_eq!(classify_tool("AskUserQuestion"), Some(ToolKind::ReadOnly));
    }

    #[test]
    fn classify_outbound_dotted_convention() {
        assert_eq!(classify_tool("whatsapp.send"), Some(ToolKind::Outbound));
        assert_eq!(classify_tool("browser.click"), Some(ToolKind::Outbound));
    }

    #[test]
    fn classify_unknown_returns_none() {
        assert_eq!(classify_tool("totally_unregistered_thing"), None);
    }

    #[test]
    fn lsp_is_classified_as_read_only() {
        // All 5 Lsp kinds are queries (no workspace mutation), so
        // the tool name `Lsp` is in READ_ONLY_TOOLS. Plan mode
        // never refuses an Lsp call.
        assert!(READ_ONLY_TOOLS.contains(&"Lsp"));
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        assert!(gate_tool_call(&state, "Lsp", None).is_none());
    }

    #[test]
    fn config_read_passes_plan_mode() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        let args = serde_json::json!({ "op": "read", "key": "model.model" });
        assert!(gate_tool_call_with_args(&state, "Config", None, &args).is_none());
    }

    #[test]
    fn config_propose_blocked_by_plan_mode() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        let args = serde_json::json!({ "op": "propose", "key": "model.model", "value": "claude-opus-4-7" });
        let refusal = gate_tool_call_with_args(&state, "Config", None, &args).unwrap();
        assert_eq!(refusal.tool_kind, ToolKind::Config);
    }

    #[test]
    fn config_apply_blocked_by_plan_mode() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        let args = serde_json::json!({ "op": "apply", "patch_id": "01J7" });
        let refusal = gate_tool_call_with_args(&state, "Config", None, &args).unwrap();
        assert_eq!(refusal.tool_kind, ToolKind::Config);
    }

    #[test]
    fn config_changes_tail_is_read_only() {
        assert!(READ_ONLY_TOOLS.contains(&"config_changes_tail"));
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        assert!(gate_tool_call(&state, "config_changes_tail", None).is_none());
    }

    // Team tool classification.

    #[test]
    fn team_create_classified_as_delegate() {
        assert_eq!(classify_tool("TeamCreate"), Some(ToolKind::Delegate));
    }

    #[test]
    fn team_delete_classified_as_delegate() {
        assert_eq!(classify_tool("TeamDelete"), Some(ToolKind::Delegate));
    }

    #[test]
    fn team_send_message_classified_as_delegate() {
        assert_eq!(classify_tool("TeamSendMessage"), Some(ToolKind::Delegate));
    }

    #[test]
    fn team_create_blocked_under_plan_mode() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        let refusal = gate_tool_call(&state, "TeamCreate", None).unwrap();
        assert_eq!(refusal.tool_kind, ToolKind::Delegate);
    }

    #[test]
    fn team_list_passes_plan_mode() {
        assert!(READ_ONLY_TOOLS.contains(&"TeamList"));
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        assert!(gate_tool_call(&state, "TeamList", None).is_none());
    }

    #[test]
    fn team_status_passes_plan_mode() {
        assert!(READ_ONLY_TOOLS.contains(&"TeamStatus"));
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        assert!(gate_tool_call(&state, "TeamStatus", None).is_none());
    }

    #[test]
    fn gate_off_lets_everything_through() {
        let state = PlanModeState::Off;
        assert!(gate_tool_call(&state, "FileEdit", None).is_none());
        assert!(gate_tool_call(&state, "Bash", Some(true)).is_none());
    }

    #[test]
    fn gate_on_blocks_mutators() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        let refusal = gate_tool_call(&state, "FileEdit", None).unwrap();
        assert_eq!(refusal.tool_kind, ToolKind::FileEdit);
        assert_eq!(refusal.entered_at, 123);
    }

    #[test]
    fn gate_on_allows_read_only() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        assert!(gate_tool_call(&state, "FileRead", None).is_none());
        assert!(gate_tool_call(&state, "ExitPlanMode", None).is_none());
    }

    #[test]
    fn gate_bash_with_classifier_unknown_blocks() {
        // Caller passes None → fail-safe block.
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        let refusal = gate_tool_call(&state, "Bash", None).unwrap();
        assert_eq!(refusal.tool_kind, ToolKind::Bash);
    }

    #[test]
    fn gate_bash_read_only_passes() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        assert!(gate_tool_call(&state, "Bash", Some(false)).is_none());
    }

    #[test]
    fn gate_bash_destructive_blocks() {
        let state = PlanModeState::on(123, PlanModeReason::ModelRequested { reason: None });
        let refusal = gate_tool_call(&state, "Bash", Some(true)).unwrap();
        assert_eq!(refusal.tool_kind, ToolKind::Bash);
    }

    #[test]
    fn unclassified_tools_reports_missing() {
        let names = ["FileEdit", "weird_new_tool", "Glob"];
        let bad = unclassified_tools(names);
        assert_eq!(bad, vec!["weird_new_tool".to_string()]);
    }

    #[test]
    fn assert_passes_for_known_registry() {
        // Smoke-test the canonical surface — every known name must
        // classify. Failures here would indicate a regression in the
        // const lists themselves.
        let names: Vec<&str> = MUTATING_TOOLS
            .iter()
            .chain(READ_ONLY_TOOLS.iter())
            .copied()
            .collect();
        assert_registry_classified(names);
    }

    #[test]
    #[should_panic(expected = "plan_mode:")]
    fn assert_panics_on_unclassified() {
        assert_registry_classified(["totally_unregistered_thing"]);
    }

    #[test]
    fn system_hint_returns_string_when_on() {
        let state = PlanModeState::on(1, PlanModeReason::ModelRequested { reason: None });
        assert_eq!(plan_mode_system_hint(&state), Some(PLAN_MODE_SYSTEM_HINT));
    }

    #[test]
    fn system_hint_returns_none_when_off() {
        assert_eq!(plan_mode_system_hint(&PlanModeState::Off), None);
    }

    #[test]
    fn system_hint_is_a_frozen_static() {
        // Sanity check: the constant body must contain the canonical
        // tokens so the model recognises it across providers and
        // the prompt cache treats it as stable.
        assert!(PLAN_MODE_SYSTEM_HINT.contains("[plan-mode]"));
        assert!(PLAN_MODE_SYSTEM_HINT.contains("ExitPlanMode"));
        assert!(PLAN_MODE_SYSTEM_HINT.contains("PlanModeRefusal"));
    }

    #[test]
    fn notify_entered_model_no_reason() {
        let s = format_notify_entered(
            1_700_000_000,
            &PlanModeReason::ModelRequested { reason: None },
        );
        assert!(s.starts_with("[plan-mode] entered at "));
        assert!(s.ends_with(" — reason: model"));
    }

    #[test]
    fn notify_entered_model_with_reason() {
        let s = format_notify_entered(
            1_700_000_000,
            &PlanModeReason::ModelRequested {
                reason: Some("auth flow".into()),
            },
        );
        assert!(s.contains("reason: model: auth flow"));
    }

    #[test]
    fn notify_entered_operator() {
        let s = format_notify_entered(1_700_000_000, &PlanModeReason::OperatorRequested);
        assert!(s.ends_with("reason: operator"));
    }

    #[test]
    fn notify_entered_auto_destructive_carries_check() {
        let s = format_notify_entered(
            1_700_000_000,
            &PlanModeReason::AutoDestructive {
                tripped_check: "rm -rf $HOME".into(),
            },
        );
        assert!(s.contains("auto-destructive: rm -rf $HOME"));
    }

    #[test]
    fn notify_exited_truncates_long_plan() {
        let plan = "x".repeat(300);
        let s = format_notify_exited(&plan, 7);
        // 200 x's + ellipsis + the suffix.
        assert!(s.contains("xxx"));
        assert!(s.contains(''));
        assert!(s.ends_with("(full plan in turn log #7)"));
    }

    #[test]
    fn notify_exited_short_plan_no_ellipsis() {
        let s = format_notify_exited("1. read auth\n2. patch", 42);
        assert!(!s.contains(''));
        assert!(s.ends_with("(full plan in turn log #42)"));
    }

    #[test]
    fn notify_acceptance_pass_and_fail() {
        let p = format_notify_acceptance(AcceptanceOutcome::Pass, "12 tests");
        assert_eq!(p, "[plan-mode] acceptance: pass (12 tests)");
        let f = format_notify_acceptance(AcceptanceOutcome::Fail, "build red");
        assert_eq!(f, "[plan-mode] acceptance: fail (build red)");
    }

    #[test]
    fn notify_refused_renders_tool_and_kind() {
        let refusal = PlanModeRefusal {
            tool_name: "FileEdit".into(),
            tool_kind: ToolKind::FileEdit,
            hint: PlanModeRefusal::HINT,
            entered_at: 1,
            entered_reason: PlanModeReason::ModelRequested { reason: None },
        };
        assert_eq!(
            format_notify_refused(&refusal),
            "[plan-mode] refused tool=FileEdit kind=file_edit"
        );
    }
}