Skip to main content

mur_common/config/
ops.rs

1use super::*;
2
3/// Pre-dispatch triage settings (`triage:` in `~/.mur/config.yaml`).
4///
5/// Both knobs default to the passive posture, and `enforce` in particular is
6/// off for a reason that is not caution: `triage_calibration` cannot score a
7/// decision that prevented a run. Enforcing from the start produces only
8/// unfalsifiable `held_back` records, so there would never be evidence that
9/// enforcing was correct. Shadow mode records the same predictions AND lets
10/// the run happen, which is what makes `Calibration::shadow_precision`
11/// computable — turn `enforce` on once that number says triage is right often
12/// enough to be worth the refusals.
13#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
14pub struct TriageConfig {
15    /// Run triage before dispatch at all. Off = not even the free prefilter
16    /// runs, and no verdicts are recorded.
17    #[serde(default)]
18    pub enabled: bool,
19    /// Let a triage decision actually stop a dispatch. Requires `enabled`.
20    /// See the type docs before turning this on.
21    #[serde(default)]
22    pub enforce: bool,
23}
24
25impl TriageConfig {
26    /// Does triage actually bind here? `enforce` alone is inert — with
27    /// `enabled: false` nothing runs to enforce — so the two are resolved in
28    /// one place rather than at each call site, where the pair would
29    /// eventually be got wrong in one of them.
30    pub fn enforces(&self) -> bool {
31        self.enabled && self.enforce
32    }
33}
34
35/// Rotation for `~/.mur/queue/events.jsonl`, in the shape FreeBSD's
36/// `newsyslog(8)` uses: rotate past a size, keep a bounded number of
37/// generations, compress all but the newest, drop the oldest.
38///
39/// The point of generations is that nobody has to decide to delete anything.
40/// A 934 MB queue becomes `.0`, then `.1.gz`, and ages out on a policy the
41/// user set rather than on a judgement call someone makes once.
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
43pub struct CaptureConfig {
44    /// Rotate once the live file passes this. 64 MB keeps `mur hook stats`
45    /// responsive — parsing is O(file), and 934 MB took minutes.
46    #[serde(default = "default_rotate_at_mb")]
47    pub rotate_at_mb: u64,
48    /// How many rotated generations to keep. `.0` stays uncompressed like
49    /// newsyslog's, the rest are gzipped.
50    #[serde(default = "default_keep_generations")]
51    pub keep_generations: u32,
52}
53
54pub(super) fn default_rotate_at_mb() -> u64 {
55    64
56}
57
58fn default_keep_generations() -> u32 {
59    5
60}
61
62impl Default for CaptureConfig {
63    fn default() -> Self {
64        Self {
65            rotate_at_mb: default_rotate_at_mb(),
66            keep_generations: default_keep_generations(),
67        }
68    }
69}
70
71/// Post-upgrade settings for `mur update`. Stored under `update:` in
72/// `~/.mur/config.yaml`.
73#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
74pub struct UpdateConfig {
75    /// macOS code-signing identity used to re-sign installed binaries after an
76    /// upgrade. Keychain grants bind to the signing identity; fresh installs
77    /// are ad-hoc (new CDHash per build), so without a stable identity every
78    /// upgrade kills the grants and service-launched agents fail silently
79    /// (#849/#866). Fallback: the `MUR_CODESIGN_IDENTITY` env var.
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub codesign_identity: Option<String>,
82    /// Agent names `mur update --restart-agents` must never touch.
83    #[serde(default, skip_serializing_if = "Vec::is_empty")]
84    pub restart_exclude: Vec<String>,
85}
86
87/// Which notification channels the durable monitor may use. `log` is not
88/// listed: it is always on and cannot be disabled, because a notable event
89/// must leave a trace somewhere even when a user has turned everything off.
90#[derive(Debug, Clone, Default, Serialize, Deserialize)]
91pub struct NotificationsConfig {
92    /// OS desktop notification. Opt-in: a background daemon that starts
93    /// popping banners on upgrade is a hostile default.
94    #[serde(default)]
95    pub desktop: bool,
96}
97
98/// Whether the durable monitor may ask a model what to do about a terminal
99/// failure the structured rules did not settle.
100///
101/// Off by default, and not merely as a courtesy: enabling it lets a
102/// background daemon send monitor context to a model on its own schedule,
103/// with no one watching. Nobody watching is not permission, so this is a
104/// decision a user makes once, explicitly, rather than something an upgrade
105/// makes for them.
106///
107/// The bound on how often it may ask is NOT here: one proposal per
108/// observation cycle is an invariant of the design, not a knob (see
109/// `mur_core::monitor::resolver`). A tunable would let a user turn a bounded
110/// feature into an unbounded one.
111#[derive(Debug, Clone, Default, Serialize, Deserialize)]
112pub struct MonitorResolverConfig {
113    /// Opt-in. While false, nothing in the resolver path runs and no request
114    /// leaves the machine.
115    #[serde(default)]
116    pub enabled: bool,
117
118    /// Which model to ask. `None` uses the same backend `mur chat` resolves,
119    /// so a user who has already configured one does not configure it twice.
120    #[serde(default)]
121    pub model: Option<String>,
122}
123
124/// Run-status heartbeat tuning. Both values are config, never literals at a
125/// call site: the right interval depends on how long the machine's steps take.
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct RunsConfig {
128    /// How often `execute_dag` stamps `last_heartbeat_at`.
129    #[serde(default = "default_heartbeat_interval_secs")]
130    pub heartbeat_interval_secs: u64,
131    /// How many missed intervals before a live process counts as `stalled`.
132    /// Three tolerates one lost tick plus scheduling jitter without calling a
133    /// healthy run dead.
134    #[serde(default = "default_heartbeat_stale_after_intervals")]
135    pub heartbeat_stale_after_intervals: u32,
136}
137
138pub(super) fn default_heartbeat_interval_secs() -> u64 {
139    10
140}
141
142pub(super) fn default_heartbeat_stale_after_intervals() -> u32 {
143    3
144}
145
146impl Default for RunsConfig {
147    fn default() -> Self {
148        Self {
149            heartbeat_interval_secs: default_heartbeat_interval_secs(),
150            heartbeat_stale_after_intervals: default_heartbeat_stale_after_intervals(),
151        }
152    }
153}
154
155/// Authorization gate for the `parallel_jobs` MCP tool. Stored under `parallel_jobs:`
156/// in `~/.mur/config.yaml`. Deny-by-default: an empty `targets` list means the
157/// tool cannot delegate to ANY agent (inert until the user opts specific
158/// agents in). This is a deterministic, out-of-model gate that a
159/// prompt-injected concierge cannot widen (OWASP Agentic ASI02/03/04).
160#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
161pub struct ParallelJobsConfig {
162    /// Canonical agent names the `parallel_jobs` tool is allowed to delegate to.
163    /// Empty = deny all.
164    #[serde(default)]
165    pub targets: Vec<String>,
166    /// Agents allowed to REQUEST a run through the daemon (#2379). Empty =
167    /// any agent that has the tool, which is how it worked before the daemon
168    /// launched runs on an agent's behalf. Re-checked by the daemon and by
169    /// its child; an agent cannot widen it.
170    #[serde(default, skip_serializing_if = "Vec::is_empty")]
171    pub requesters: Vec<String>,
172}
173
174// --- memory-federation snapshot (spec 2026-08-04-unified-memory-federation) ---
175
176/// Daemon-side settings for the signed snapshot pull. Stored under
177/// `federation_snapshot:` in `~/.mur/config.yaml`; every field has a default
178/// so an absent block means "defaults", never "off".
179#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
180#[serde(default)]
181pub struct SnapshotConfig {
182    /// How often the daemon sweeps `inbox/snapshot-requests/`, in seconds.
183    pub poll_secs: u64,
184    /// Reject requests older than this (replay blunting), in seconds.
185    pub request_max_age_secs: u64,
186    /// Minimum lifecycle state a global skill needs to enter a snapshot.
187    pub min_lifecycle: crate::skill::stats::LifecycleState,
188}
189
190impl Default for SnapshotConfig {
191    fn default() -> Self {
192        Self {
193            poll_secs: 30,
194            request_max_age_secs: 600,
195            min_lifecycle: crate::skill::stats::LifecycleState::Stable,
196        }
197    }
198}
199
200/// Proactive memory capture (memory federation P2): gates the runtime's
201/// built-in `remember` tool and its system-prompt directive. Stored under
202/// `memory:` in `~/.mur/config.yaml`.
203#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
204#[serde(default)]
205pub struct MemoryConfig {
206    pub capture: CaptureMode,
207    /// How many memories may enter the system prompt per turn. Deliberately
208    /// NOT `skills.max_skills_in_prompt`: sharing that budget means saving a
209    /// memory silently evicts a skill, and five is a plausible number of
210    /// standing preferences for one user to have.
211    #[serde(default = "default_memory_in_prompt")]
212    pub max_in_prompt: usize,
213    /// Character ceiling for the whole memory block, spent before skills.
214    #[serde(default = "default_memory_chars")]
215    pub max_chars: usize,
216}
217
218fn default_memory_in_prompt() -> usize {
219    20
220}
221
222fn default_memory_chars() -> usize {
223    1500
224}
225
226impl Default for MemoryConfig {
227    fn default() -> Self {
228        Self {
229            capture: CaptureMode::AutoAnnounce,
230            max_in_prompt: default_memory_in_prompt(),
231            max_chars: default_memory_chars(),
232        }
233    }
234}
235
236/// How agents capture memories mid-conversation.
237#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
238#[serde(rename_all = "snake_case")]
239pub enum CaptureMode {
240    /// Agent asks for a one-line confirmation before saving.
241    Ask,
242    /// Agent saves immediately and announces in the same reply (default).
243    AutoAnnounce,
244    /// The `remember` tool is not registered at all.
245    Off,
246}
247
248/// Authorization gate for the runtime's built-in `fleet_run` tool. Stored under
249/// `fleet_run:` in `~/.mur/config.yaml`. Deny-by-default on BOTH axes: an agent
250/// not named in `agents` never even sees the tool, and a fleet not named in
251/// `fleets` cannot be run. Lives in the global config (not the agent profile)
252/// because the profile is writable by the concierge itself — this gate must be
253/// out of reach of a prompt-injected agent (same rationale as
254/// [`ParallelJobsConfig`]).
255#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
256pub struct FleetRunConfig {
257    /// Canonical agent names allowed to call `fleet_run`. Empty = deny all.
258    #[serde(default)]
259    pub agents: Vec<String>,
260    /// Fleet names those agents may run. Empty = deny all.
261    #[serde(default)]
262    pub fleets: Vec<String>,
263}
264
265/// Daemon-side settings for cross-router fleet dispatch (#2116). Stored under
266/// `fleet_dispatch:` in `~/.mur/config.yaml`; an absent block means defaults.
267/// WHO may dispatch WHAT is still [`FleetRunConfig`] — this only tunes timing.
268#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
269#[serde(default)]
270pub struct FleetDispatchConfig {
271    /// How often the daemon sweeps `inbox/fleet-dispatch-requests/`, in seconds.
272    /// Short by default: an agent is waiting on the run it just dispatched.
273    pub poll_secs: u64,
274    /// Reject requests older than this (replay blunting), in seconds.
275    pub request_max_age_secs: u64,
276    /// A daemon heartbeat older than this is treated as "daemon down" by the
277    /// requesting agent, which then refuses instead of queueing into nothing.
278    pub heartbeat_stale_secs: u64,
279}
280
281impl Default for FleetDispatchConfig {
282    fn default() -> Self {
283        Self {
284            poll_secs: 3,
285            request_max_age_secs: 300,
286            heartbeat_stale_secs: 60,
287        }
288    }
289}
290
291/// Gate for the git push broker (`git_push:` in `~/.mur/config.yaml`).
292/// Deny-by-default on BOTH axes, like [`FleetRunConfig`]: `enabled` is the
293/// broker-wide switch (off: the daemon sweeper does not run and no agent gets
294/// anything), and `agents` names the only agents that see `git_push_request` /
295/// `git_push_status` / `git_push_cancel` and get the Landlock read grant on the
296/// registry. An agent not named here — a deep-research worker, say — never sees
297/// the tools, so it neither learns the registry exists nor adds requests to the
298/// human approval queue. Global config, not the agent profile, for the same
299/// reason as [`FleetRunConfig`]: a prompt-injected agent must not widen it.
300#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
301pub struct GitPushConfig {
302    #[serde(default)]
303    pub enabled: bool,
304    /// Canonical agent names allowed the push tools. Empty = deny all.
305    #[serde(default)]
306    pub agents: Vec<String>,
307}
308
309/// Display policy for `mur open`.
310///
311/// Lives in `config.yaml` rather than in `open-items.jsonl` because that log
312/// is append-only and agent-writable via the `open_item` tool. A user's
313/// decision to stop looking at a source must not be overturnable by an agent
314/// appending a record. Same reasoning as `fleet_run.agents`.
315#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
316pub struct OpenItemsConfig {
317    /// Exact `origin` strings to collapse out of `mur open`. Exact match
318    /// only — `fleet` never matches `fleet:acme`.
319    #[serde(default)]
320    pub muted: Vec<String>,
321}
322
323/// Daemon-wide gate for unattended fleet auto-run (`mur-daemon`'s `fleet_tick`).
324/// Stored under `fleet:` in `~/.mur/config.yaml`. Either this flag OR the
325/// `MUR_FLEET_AUTORUN` env var satisfies the gate — both are equally explicit,
326/// off-by-default opt-ins; the env var remains for ops/CI use, this flag is
327/// what the Hub's Settings toggle controls. Per-fleet `budget_usd > 0` and the
328/// `.stopped` kill-switch are unaffected — see `mur-daemon/src/fleet_tick.rs`.
329#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
330pub struct FleetConfig {
331    /// Allow fleets with a trigger + budget configured to auto-run unattended.
332    #[serde(default)]
333    pub autorun: bool,
334}
335
336/// Routing for Anthropic subscription-OAuth (`sk-ant-oat*`) tokens through a
337/// local bridge — cc-proxy — that swaps `x-api-key` for the Bearer +
338/// claude-code betas disguise the upstream requires.
339///
340/// The Hub injects `ANTHROPIC_BASE_URL` pointing at [`url`](Self::url) when it
341/// spawns an agent runtime, but only when [`enabled`](Self::enabled) is set and
342/// the bridge is actually listening; otherwise it leaves the runtime on the
343/// direct `api.anthropic.com` path (where an oat token would 401). A runtime
344/// launched with `ANTHROPIC_BASE_URL` already in its environment is never
345/// overridden.
346#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct CcProxyConfig {
348    /// Bridge base URL. Defaults to cc-proxy's default bind.
349    #[serde(default = "default_cc_proxy_url")]
350    pub url: String,
351
352    /// Master switch. When false the Hub never routes runtimes through the
353    /// bridge, regardless of reachability.
354    #[serde(default = "default_true")]
355    pub enabled: bool,
356}
357
358fn default_cc_proxy_url() -> String {
359    "http://127.0.0.1:8088".to_string()
360}
361
362fn default_true() -> bool {
363    true
364}
365
366impl Default for CcProxyConfig {
367    fn default() -> Self {
368        Self {
369            url: default_cc_proxy_url(),
370            enabled: true,
371        }
372    }
373}
374
375/// Configuration for the agent CLI TUI.
376/// Stored in ~/.mur/config.yaml under the `cli:` key.
377#[derive(Debug, Clone, Serialize, Deserialize, Default)]
378pub struct CliConfig {
379    /// Default visual skin for `mur agent cli`. Overridable with --skin.
380    /// Valid values: "ansi" (default; "dark" is an alias), "light", "mur",
381    /// "clay", or the stem of a user skin file `<mur home>/skins/<name>.yaml`.
382    pub skin: Option<String>,
383
384    /// True once the one-time "permanent instructions" notice has been shown
385    /// (memories P1 §10).
386    ///
387    /// The notice is informational and must appear at most once — repeating a
388    /// feature announcement every session reads as a warning about something
389    /// wrong. Absent (false) in existing configs, which is correct: a user who
390    /// has never seen it should.
391    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
392    pub seen_permanent_instructions_notice: bool,
393}
394
395/// Configuration for the mobile relay (P4).
396/// Stored in ~/.mur/config.yaml under the `mobile_relay:` key.
397#[derive(Debug, Clone, Serialize, Deserialize, Default)]
398pub struct MobileRelayConfig {
399    /// Base URL of the mur-server relay, e.g. "wss://relay.mur.run".
400    /// Leave blank to disable relay forwarding on the Mac daemon side.
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub relay_url: Option<String>,
403
404    /// API key or JWT used by the Mac daemon to authenticate with the relay.
405    /// The value is typically a `mur_...` API key from app.mur.run.
406    #[serde(default, skip_serializing_if = "Option::is_none")]
407    pub api_key: Option<String>,
408}
409
410#[cfg(test)]
411mod fleet_config_tests {
412    use super::*;
413
414    #[test]
415    fn fleet_config_defaults_off_and_roundtrips() {
416        assert!(!FleetConfig::default().autorun);
417
418        let cfg: Config = serde_yaml_ng::from_str("fleet:\n  autorun: true\n").unwrap();
419        assert!(cfg.fleet.autorun);
420
421        // `fleet:` key entirely absent → defaults to off
422        let cfg2: Config = serde_yaml_ng::from_str("{}").unwrap();
423        assert!(!cfg2.fleet.autorun);
424    }
425
426    #[test]
427    fn fleet_run_config_defaults_deny_all_and_roundtrips() {
428        // Absent section → both allowlists empty → deny all.
429        let cfg: Config = serde_yaml_ng::from_str("{}").unwrap();
430        assert!(cfg.fleet_run.agents.is_empty());
431        assert!(cfg.fleet_run.fleets.is_empty());
432
433        let cfg2: Config =
434            serde_yaml_ng::from_str("fleet_run:\n  agents: [mur]\n  fleets: [deep-research]\n")
435                .unwrap();
436        assert_eq!(cfg2.fleet_run.agents, vec!["mur"]);
437        assert_eq!(cfg2.fleet_run.fleets, vec!["deep-research"]);
438    }
439
440    #[test]
441    fn git_push_config_defaults_off_and_roundtrips() {
442        let cfg: Config = serde_yaml_ng::from_str("{}").unwrap();
443        assert!(!cfg.git_push.enabled);
444        assert!(cfg.git_push.agents.is_empty());
445        let cfg2: Config =
446            serde_yaml_ng::from_str("git_push:\n  enabled: true\n  agents: [mur]\n").unwrap();
447        assert!(cfg2.git_push.enabled);
448        assert_eq!(cfg2.git_push.agents, vec!["mur"]);
449    }
450}
451
452#[cfg(test)]
453mod runs_config_tests {
454    use super::*;
455
456    /// A zero `heartbeat_interval_secs` is legal YAML but illegal at runtime:
457    /// it zeroes the stale threshold (every live run instantly reads STALLED)
458    /// and `tokio::time::interval(Duration::ZERO)` panics in the executor's
459    /// ticker. The loader must clamp zeroes to the defaults so one
460    /// user-edited line can neither lie nor crash.
461    #[test]
462    fn zero_heartbeat_values_clamp_to_defaults_at_load() {
463        let tmp = tempfile::tempdir().unwrap();
464        let path = tmp.path().join("config.yaml");
465        std::fs::write(
466            &path,
467            "runs:\n  heartbeat_interval_secs: 0\n  heartbeat_stale_after_intervals: 0\n",
468        )
469        .unwrap();
470
471        let cfg = Config::load_or_default(&path);
472        assert_eq!(
473            cfg.runs.heartbeat_interval_secs, 10,
474            "a zero interval must load as the default, not 0"
475        );
476        assert_eq!(
477            cfg.runs.heartbeat_stale_after_intervals, 3,
478            "a zero interval count must load as the default, not 0"
479        );
480    }
481
482    /// The clamp must not rewrite legitimate tuning: positive values survive.
483    #[test]
484    fn positive_heartbeat_values_survive_the_load() {
485        let tmp = tempfile::tempdir().unwrap();
486        let path = tmp.path().join("config.yaml");
487        std::fs::write(
488            &path,
489            "runs:\n  heartbeat_interval_secs: 60\n  heartbeat_stale_after_intervals: 2\n",
490        )
491        .unwrap();
492
493        let cfg = Config::load_or_default(&path);
494        assert_eq!(cfg.runs.heartbeat_interval_secs, 60);
495        assert_eq!(cfg.runs.heartbeat_stale_after_intervals, 2);
496    }
497}
498
499#[cfg(test)]
500mod ambient_capture_cfg_tests {
501    use super::*;
502
503    #[test]
504    fn session_and_harvest_defaults() {
505        let cfg: Config = serde_yaml::from_str("{}").unwrap();
506        assert_eq!(cfg.session.capture, "ambient");
507        assert_eq!(cfg.session.retention_days, 14);
508        assert!(cfg.harvest.auto_gate);
509        assert_eq!(cfg.harvest.llm, "local-first");
510        assert_eq!(cfg.harvest.min_events, 5);
511        assert_eq!(cfg.harvest.min_user_turns, 2);
512        assert_eq!(cfg.harvest.min_duration_secs, 120);
513        assert_eq!(cfg.harvest.idle_minutes, 30);
514        assert_eq!(cfg.harvest.max_llm_calls_per_day, 10);
515        assert_eq!(cfg.harvest.max_extract_input_tokens, 12000);
516        assert!(cfg.harvest.session_start_hint);
517        assert!((cfg.harvest.similarity_merge_threshold - 0.6).abs() < f32::EPSILON);
518    }
519
520    #[test]
521    fn session_capture_override_parses() {
522        let cfg: Config =
523            serde_yaml::from_str("session:\n  capture: off\n  retention_days: 3\n").unwrap();
524        assert_eq!(cfg.session.capture, "off");
525        assert_eq!(cfg.session.retention_days, 3);
526    }
527}
528
529#[cfg(test)]
530mod cc_proxy_cfg_tests {
531    use super::*;
532
533    #[test]
534    fn defaults_to_local_cc_proxy_enabled() {
535        let cfg: Config = serde_yaml_ng::from_str("{}").unwrap();
536        assert_eq!(cfg.cc_proxy.url, "http://127.0.0.1:8088");
537        assert!(cfg.cc_proxy.enabled);
538    }
539
540    #[test]
541    fn url_and_enabled_override_parse() {
542        let cfg: Config =
543            serde_yaml_ng::from_str("cc_proxy:\n  url: http://127.0.0.1:9999\n  enabled: false\n")
544                .unwrap();
545        assert_eq!(cfg.cc_proxy.url, "http://127.0.0.1:9999");
546        assert!(!cfg.cc_proxy.enabled);
547    }
548
549    #[test]
550    fn partial_section_keeps_other_default() {
551        // Only `enabled` given → url stays at the default.
552        let cfg: Config = serde_yaml_ng::from_str("cc_proxy:\n  enabled: false\n").unwrap();
553        assert_eq!(cfg.cc_proxy.url, "http://127.0.0.1:8088");
554        assert!(!cfg.cc_proxy.enabled);
555    }
556}
557
558#[cfg(test)]
559mod notifications_config_tests {
560    use super::*;
561
562    #[test]
563    fn notifications_default_to_log_only() {
564        let c: Config = serde_yaml::from_str("{}").unwrap();
565        assert!(!c.notifications.desktop, "desktop must be opt-in");
566    }
567
568    #[test]
569    fn an_existing_config_without_the_block_still_parses() {
570        // Every user upgrading has a config.yaml with no `notifications:` key.
571        let c: Config = serde_yaml::from_str("retrieval:\n  min_score: 0.42\n").unwrap();
572        assert!(!c.notifications.desktop);
573    }
574
575    /// The whole safety argument for the resolver rests on this one bit: an
576    /// upgrade must never start letting the daemon talk to a model. Asserted
577    /// from both an empty config and a realistic existing one, because the
578    /// failure that matters is an upgrade, not a fresh install.
579    #[test]
580    fn the_monitor_resolver_is_off_until_a_user_turns_it_on() {
581        let empty: Config = serde_yaml::from_str("{}").unwrap();
582        assert!(
583            !empty.monitor_resolver.enabled,
584            "asking a model must be opt-in"
585        );
586        assert!(empty.monitor_resolver.model.is_none());
587
588        let upgraded: Config = serde_yaml::from_str(
589            "retrieval:\n  min_score: 0.42\nnotifications:\n  desktop: true\n",
590        )
591        .unwrap();
592        assert!(
593            !upgraded.monitor_resolver.enabled,
594            "a config written before this feature existed must not enable it"
595        );
596    }
597
598    #[test]
599    fn the_monitor_resolver_reads_back_what_a_user_wrote() {
600        let c: Config =
601            serde_yaml::from_str("monitor_resolver:\n  enabled: true\n  model: claude_haiku\n")
602                .unwrap();
603        assert!(c.monitor_resolver.enabled);
604        assert_eq!(c.monitor_resolver.model.as_deref(), Some("claude_haiku"));
605    }
606
607    /// Triage must be inert for everyone who never asked for it — including
608    /// every config file written before it existed.
609    #[test]
610    fn triage_is_off_and_non_binding_by_default() {
611        let c: Config = serde_yaml::from_str("retrieval:\n  min_score: 0.42\n").unwrap();
612        assert!(!c.triage.enabled, "triage must not run unasked");
613        assert!(!c.triage.enforce);
614        assert!(!c.triage.enforces());
615    }
616
617    /// The trap this guards: `enforce: true` alone looks like it turned
618    /// something on, but there is nothing running to enforce.
619    #[test]
620    fn enforce_without_enabled_binds_nothing() {
621        let c: Config = serde_yaml::from_str("triage:\n  enforce: true\n").unwrap();
622        assert!(c.triage.enforce, "the user's word is kept verbatim");
623        assert!(
624            !c.triage.enforces(),
625            "but it binds nothing while triage does not run"
626        );
627    }
628
629    #[test]
630    fn triage_binds_only_when_both_knobs_are_set() {
631        let c: Config =
632            serde_yaml::from_str("triage:\n  enabled: true\n  enforce: true\n").unwrap();
633        assert!(c.triage.enforces());
634    }
635
636    /// Enabled without enforce is shadow mode: it runs, it records, it never
637    /// stops anything.
638    #[test]
639    fn enabled_alone_is_shadow_mode() {
640        let c: Config = serde_yaml::from_str("triage:\n  enabled: true\n").unwrap();
641        assert!(c.triage.enabled);
642        assert!(!c.triage.enforces());
643    }
644}