magi-code 0.77.1

Repository-aware CLI coding agent for terminal work
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
use serde_json::Value;

use crate::config::{
    CliConfigOverrides, EffectiveConfig, McPaths,
    settings_storage::{
        ensure_settings_schema_files as ensure_settings_schema_files_storage,
        insert_default_schema_ref_if_absent, merge_local_settings_json,
        merge_local_settings_values, read_merged_settings_json, read_settings_json_or_empty,
        settings_path_for_scope, update_settings_json,
    },
};

use super::{
    core::{AppearanceSettings, SessionSettings, Settings, SettingsListKind, SettingsScope},
    json::{remove_path, set_path, value_at_path, value_at_path_mut_or_create},
    validation::validate_settings,
    wire::{
        SettingsDocument, canonical_settings_value, migrate_settings_value,
        session_settings_from_normalized_value,
    },
};

#[cfg(test)]
pub(crate) fn ensure_settings_schema_files(paths: &McPaths) -> anyhow::Result<()> {
    ensure_settings_schema_files_and_load(paths).map(|_| ())
}

fn ensure_settings_schema_files_and_load(
    paths: &McPaths,
) -> anyhow::Result<Option<(serde_json::Value, SettingsDocument, SessionSettings)>> {
    let schema = serde_json::to_string_pretty(&schemars::schema_for!(Settings))?;
    ensure_settings_schema_files_storage(paths, schema.as_bytes(), |raw| {
        parse_settings_document_with_session_settings(raw.clone())
    })
    .map(|loaded| {
        loaded.map(|(raw, (document, session_settings))| (raw, document, session_settings))
    })
}

#[cfg(test)]
pub(crate) fn load_config_with_settings(
    paths: McPaths,
    cli: CliConfigOverrides,
) -> anyhow::Result<(
    EffectiveConfig,
    Settings,
    AppearanceSettings,
    SessionSettings,
)> {
    let (document, session_settings) = read_settings_document_with_session_settings(&paths)?;
    let config = EffectiveConfig::from_loaded_settings(paths, cli, document.settings.clone())?;
    Ok((
        config,
        document.settings,
        document.appearance,
        session_settings,
    ))
}

pub(crate) fn load_startup_config_with_settings(
    paths: McPaths,
    cli: CliConfigOverrides,
) -> anyhow::Result<(
    EffectiveConfig,
    Settings,
    AppearanceSettings,
    SessionSettings,
)> {
    let prepared = ensure_settings_schema_files_and_load(&paths)?;
    let local_path = paths
        .local_settings_file
        .as_ref()
        .filter(|path| path.exists())
        .unwrap_or(&paths.project_settings_file);
    let (document, session_settings) = match prepared {
        Some((_global_raw, document, session_settings)) if !local_path.exists() => {
            (document, session_settings)
        }
        Some((global_raw, _, _)) => {
            let raw = merge_local_settings_json(&paths, global_raw)?;
            let (document, session_settings) = parse_settings_document_with_session_settings(raw)?;
            (document, session_settings)
        }
        None => {
            // Do not let a local override repair or hide an invalid global file.
            let global_raw = read_settings_json_or_empty(&paths.settings_file)?;
            let (document, session_settings) =
                parse_settings_document_with_session_settings(global_raw.clone())?;
            if local_path.exists() {
                let raw = merge_local_settings_json(&paths, global_raw)?;
                parse_settings_document_with_session_settings(raw)?
            } else {
                (document, session_settings)
            }
        }
    };
    let config = EffectiveConfig::from_loaded_settings(paths, cli, document.settings.clone())?;
    Ok((
        config,
        document.settings,
        document.appearance,
        session_settings,
    ))
}

pub(crate) fn read_settings(paths: &McPaths) -> anyhow::Result<Settings> {
    read_settings_document(paths).map(|document| document.settings)
}

/// Capture settings relative to cooperating writes, with the same global/project lock order.
pub(crate) fn read_settings_locked(paths: &McPaths) -> anyhow::Result<Settings> {
    use crate::config::settings_storage::with_settings_file_lock;
    let deadline = std::time::Instant::now() + crate::persistence::LOCK_WAIT_TIMEOUT;
    with_settings_file_lock(&paths.settings_file, deadline, || {
        if paths.settings_file == paths.project_settings_file {
            read_settings(paths)
        } else {
            with_settings_file_lock(&paths.project_settings_file, deadline, || {
                read_settings(paths)
            })
        }
    })
}

#[cfg(test)]
pub(super) fn read_settings_with_session_settings(
    paths: &McPaths,
) -> anyhow::Result<(Settings, SessionSettings)> {
    read_settings_document_with_session_settings(paths)
        .map(|(document, session_settings)| (document.settings, session_settings))
}

pub(crate) fn read_settings_document(paths: &McPaths) -> anyhow::Result<SettingsDocument> {
    read_settings_document_with_session_settings(paths).map(|(document, _)| document)
}

pub(super) fn read_settings_document_with_session_settings(
    paths: &McPaths,
) -> anyhow::Result<(SettingsDocument, SessionSettings)> {
    let raw = read_merged_settings_json(paths)?;
    let (document, session_settings) = parse_settings_document_with_session_settings(raw)?;
    Ok((document, session_settings))
}

fn parse_settings_document_with_session_settings(
    raw: serde_json::Value,
) -> anyhow::Result<(SettingsDocument, SessionSettings)> {
    let normalized = migrate_settings_value(raw)?;
    let session_settings = session_settings_from_normalized_value(&normalized)?;
    let document = SettingsDocument::from_normalized_value(&normalized)?;
    validate_settings(&document.settings)?;
    Ok((document, session_settings))
}

#[cfg(test)]
pub(crate) fn write_settings(paths: &McPaths, settings: &Settings) -> anyhow::Result<()> {
    validate_settings(settings)?;
    update_settings_json(paths, SettingsScope::Global, |raw| {
        let before: Settings = serde_json::from_value(raw.clone())?;
        update_raw_from_settings(raw, &before, settings, SettingsScope::Global)
    })?;
    Ok(())
}

pub(crate) fn update_settings_preserving_unknown_top_level_fields(
    paths: &McPaths,
    mutate: impl FnOnce(&mut Settings),
) -> anyhow::Result<()> {
    update_settings_for_scope_preserving_unknown_top_level_fields(
        paths,
        SettingsScope::Global,
        mutate,
    )
}

pub(crate) fn read_settings_for_scope(
    paths: &McPaths,
    scope: SettingsScope,
) -> anyhow::Result<Settings> {
    let raw = read_settings_json_or_empty(&settings_path_for_scope(paths, scope))?;
    let settings: Settings = serde_json::from_value(raw)?;
    validate_settings(&settings)?;
    Ok(settings)
}

pub(crate) fn update_settings_for_scope_preserving_unknown_top_level_fields(
    paths: &McPaths,
    scope: SettingsScope,
    mutate: impl FnOnce(&mut Settings),
) -> anyhow::Result<()> {
    update_settings_for_scope_with_disabled_list(paths, scope, None, mutate)
}

pub(super) fn update_settings_for_scope_with_disabled_list(
    paths: &McPaths,
    scope: SettingsScope,
    explicit_disabled_list: Option<SettingsListKind>,
    mutate: impl FnOnce(&mut Settings),
) -> anyhow::Result<()> {
    update_settings_json(paths, scope, |raw| {
        let before: Settings = if scope == SettingsScope::Project {
            let global_raw = read_settings_json_or_empty(&paths.settings_file)?;
            let global_settings: Settings = serde_json::from_value(global_raw.clone())?;
            validate_settings(&global_settings)?;
            let effective_raw = merge_local_settings_values(global_raw, raw.clone())?;
            serde_json::from_value(effective_raw)?
        } else {
            serde_json::from_value(raw.clone())?
        };
        if explicit_disabled_list.is_some() {
            validate_settings(&before)?;
        }
        let mut after = before.clone();
        mutate(&mut after);
        validate_settings(&after)?;
        update_raw_from_settings(raw, &before, &after, scope)?;
        if scope == SettingsScope::Project
            && let Some(kind) = explicit_disabled_list
        {
            preserve_explicit_disabled_list(raw, &after, kind)?;
        }
        Ok(())
    })?;
    Ok(())
}

/// Validate a scoped change and its resulting effective state before the atomic write.
/// The returned projection is computed under the settings lock and released only on success.
pub(crate) fn update_settings_checked<T>(
    paths: &McPaths,
    scope: SettingsScope,
    explicit_paths: &[&[&str]],
    mutate: impl FnOnce(&mut Settings, &Settings) -> anyhow::Result<()>,
    project: impl FnOnce(&Settings) -> anyhow::Result<T>,
) -> anyhow::Result<T> {
    let mut result = None;
    update_settings_json(paths, scope, |raw| {
        let effective_raw = match scope {
            SettingsScope::Global => merge_local_settings_json(paths, raw.clone())?,
            SettingsScope::Project => merge_local_settings_values(
                read_settings_json_or_empty(&paths.settings_file)?,
                raw.clone(),
            )?,
        };
        let (effective, _) = parse_settings_document_with_session_settings(effective_raw)?;
        let before = if scope == SettingsScope::Global {
            serde_json::from_value(raw.clone())?
        } else {
            effective.settings.clone()
        };
        let mut after = before.clone();
        mutate(&mut after, &effective.settings)?;
        validate_settings(&after)?;
        update_raw_from_settings(raw, &before, &after, scope)?;
        // Explicit setters must pin their requested fields even when the project currently
        // inherits the same value. Otherwise a later global write would undo the selection.
        let canonical = canonical_settings_value(&after)?;
        for path in explicit_paths {
            if scope == SettingsScope::Project
                && (path.starts_with(&["agent", "fast"])
                    || path.starts_with(&["interface", "appearance"]))
            {
                anyhow::bail!("explicit setting requires global scope");
            }
            let value = value_at_path(&canonical, path)
                .ok_or_else(|| anyhow::anyhow!("explicit settings field has no value"))?;
            set_path(raw, path, value.clone())?;
        }
        let updated = match scope {
            SettingsScope::Global => merge_local_settings_json(paths, raw.clone())?,
            SettingsScope::Project => merge_local_settings_values(
                read_settings_json_or_empty(&paths.settings_file)?,
                raw.clone(),
            )?,
        };
        let (document, _) = parse_settings_document_with_session_settings(updated)?;
        result = Some(project(&document.settings)?);
        Ok(())
    })?;
    result.ok_or_else(|| anyhow::anyhow!("settings update produced no result"))
}

pub(super) fn update_raw_from_settings(
    raw: &mut serde_json::Value,
    before: &Settings,
    after: &Settings,
    scope: SettingsScope,
) -> anyhow::Result<()> {
    let normalized = migrate_settings_value(std::mem::take(raw))?;
    let before_value = canonical_settings_value(before)?;
    let after_value = canonical_settings_value(after)?;
    let context_was_cleared = before.context.is_some() && after.context.is_none();
    let primary_agent_was_cleared =
        before.selected_primary_agent.is_some() && after.selected_primary_agent.is_none();

    let mut updated = normalized;
    apply_canonical_changes(&mut updated, &before_value, &after_value, &[])?;
    if before.summarizer.auto_start != after.summarizer.auto_start {
        // Pin false too, including when disabling returns the whole group to defaults.
        set_path(
            &mut updated,
            &["agent", "summarizer", "auto_start"],
            Value::Bool(after.summarizer.auto_start),
        )?;
    }
    if scope == SettingsScope::Project {
        for (field, cleared) in [
            (
                "provider",
                before.summarizer.provider.is_some() && after.summarizer.provider.is_none(),
            ),
            (
                "model",
                before.summarizer.model.is_some() && after.summarizer.model.is_none(),
            ),
            (
                "reasoning",
                before.summarizer.reasoning.is_some() && after.summarizer.reasoning.is_none(),
            ),
            (
                "prompt",
                before.summarizer.prompt.is_some() && after.summarizer.prompt.is_none(),
            ),
        ] {
            if cleared {
                // Null clears a global override; omission would inherit it again.
                set_path(&mut updated, &["agent", "summarizer", field], Value::Null)?;
            }
        }
    }
    if context_was_cleared {
        // Keep an explicit null when a configured context is cleared. This is
        // distinct from an omitted context and preserves the existing wire
        // contract for settings mutations.
        set_path(&mut updated, &["agent", "context"], Value::Null)?;
    }
    if primary_agent_was_cleared {
        // Keep an explicit null when a configured primary agent is cleared.
        // This distinguishes clearing it from leaving it unset.
        set_path(&mut updated, &["agent", "primary_agent"], Value::Null)?;
    }
    if scope == SettingsScope::Project {
        remove_path(&mut updated, &["agent", "fast"]);
        remove_path(&mut updated, &["interface", "appearance"]);
    } else {
        insert_default_schema_ref_if_absent(&mut updated);
    }
    *raw = updated;
    Ok(())
}

fn apply_canonical_changes(
    raw: &mut Value,
    before: &Value,
    after: &Value,
    path: &[&str],
) -> anyhow::Result<()> {
    if before == after {
        return Ok(());
    }

    match (before, after) {
        (Value::Object(before), Value::Object(after)) => {
            for (key, before_value) in before {
                let child_path = append_path(path, key);
                match after.get(key) {
                    Some(after_value) => {
                        apply_canonical_changes(raw, before_value, after_value, &child_path)?;
                    }
                    None if is_dynamic_map(path) || is_dynamic_map(&child_path) => {
                        remove_path(raw, &child_path)
                    }
                    None => remove_canonical_value(raw, before_value, &child_path),
                }
            }
            for (key, after_value) in after {
                if before.contains_key(key) {
                    continue;
                }
                let child_path = append_path(path, key);
                add_canonical_value(raw, after_value, &child_path)?;
            }
            Ok(())
        }
        (_, after) => set_path(raw, path, after.clone()),
    }
}

fn add_canonical_value(raw: &mut Value, value: &Value, path: &[&str]) -> anyhow::Result<()> {
    match value {
        Value::Object(object) => {
            for (key, value) in object {
                let child_path = append_path(path, key);
                add_canonical_value(raw, value, &child_path)?;
            }
            Ok(())
        }
        value => set_path(raw, path, value.clone()),
    }
}

fn remove_canonical_value(raw: &mut Value, value: &Value, path: &[&str]) {
    if is_dynamic_map(path) {
        remove_path(raw, path);
        return;
    }
    match value {
        Value::Object(object) => {
            for (key, value) in object {
                let child_path = append_path(path, key);
                remove_canonical_value(raw, value, &child_path);
            }
            let is_empty = value_at_path(raw, path)
                .and_then(Value::as_object)
                .is_some_and(|object| object.is_empty());
            if is_empty {
                remove_path(raw, path);
            }
        }
        _ => remove_path(raw, path),
    }
}

fn append_path<'a>(path: &[&'a str], key: &'a str) -> Vec<&'a str> {
    let mut child_path = Vec::with_capacity(path.len() + 1);
    child_path.extend_from_slice(path);
    child_path.push(key);
    child_path
}

fn is_dynamic_map(path: &[&str]) -> bool {
    matches!(
        path,
        ["providers", "custom"]
            | ["capabilities", "mcp"]
            | ["capabilities", "lsp", "servers"]
            | ["agent", "context", "model_overrides"]
    )
}

#[cfg(test)]
pub(super) const KNOWN_SUBAGENTS_KEYS: &[&str] =
    &["disabled", "schema_validation_max_retries", "execution"];

fn preserve_explicit_disabled_list(
    raw: &mut Value,
    settings: &Settings,
    kind: SettingsListKind,
) -> anyhow::Result<()> {
    let (group, list): (&[&str], &[String]) = match kind {
        SettingsListKind::Skills => (&["knowledge", "skills"], &settings.skills.disabled),
        SettingsListKind::Tools => (&["capabilities", "tools"], &settings.tools.disabled),
        SettingsListKind::Subagents => (&["agent", "subagents"], &settings.subagents.disabled),
        SettingsListKind::Models => (&["providers", "catalog"], &settings.models.disabled),
    };
    if list.is_empty() {
        let group_value = value_at_path_mut_or_create(raw, group)?;
        group_value.insert("disabled".to_string(), Value::Array(Vec::new()));
    }
    Ok(())
}