zeph-config 0.22.0

Pure-data configuration types for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Feature-specific (compaction, autodream, goals, orchestration persistence) config migration steps.
//!
//! Extracted from the former `migrate/mod.rs` monolith (#4874). Shared TOML helpers,
//! the [`Migration`](super::Migration) trait, and the [`MIGRATIONS`](super::MIGRATIONS)
//! registry remain in the parent module.

use regex::Regex;

use super::{MigrateError, MigrationResult};

/// Regex matching the `[tui]` section header line (used by step 67).
static TUI_HEADER_RE: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
    Regex::new(r"(?m)^[ \t]*\[tui\][ \t]*(?:#[^\r\n]*)?\r?\n").expect("static pattern")
});

/// Inject a commented-out `[tui.delights]` advisory block when absent (#5104).
///
/// No-op when `[tui]` is absent (config doesn't use TUI at all) or when
/// `[tui.delights]` already exists (active or commented) — idempotent.
///
/// # Errors
///
/// Returns `MigrateError::TomlParse` if the input is not valid TOML; infallible otherwise.
pub fn migrate_tui_delights(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    // No [tui] section → no-op.
    if !toml_src.contains("[tui]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    // Idempotency: scan for [tui.delights] already present (active or commented-out).
    let already_present = toml_src.lines().any(|l| {
        let t = l.trim().trim_start_matches('#').trim();
        t == "[tui.delights]" || t.starts_with("[tui.delights]")
    });
    if already_present {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    // Normalise trailing newline so the regex always matches.
    let owned;
    let src = if toml_src.ends_with('\n') {
        toml_src
    } else {
        owned = format!("{toml_src}\n");
        &owned
    };

    if !TUI_HEADER_RE.is_match(src) {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let advisory = "\n# [tui.delights] — micro-delight toggles (all default true, #5104).\n\
         # motion = off acts as a master kill-switch regardless of individual settings.\n\
         # [tui.delights]\n\
         # stream_metrics   = true  # tok/s during streaming + TTFT after turn in status bar\n\
         # toasts           = true  # ephemeral overlay notifications (theme switch, copy, etc.)\n\
         # completion_flash = true  # accent tint on a finished tool group for ~400 ms\n\
         # smooth_scroll    = true  # eased multi-frame interpolation on page-up / page-down\n\
         # splash_shimmer   = true  # one-shot gradient sweep across the wordmark at startup\n";

    let output = TUI_HEADER_RE
        .replacen(src, 1, |caps: &regex::Captures| {
            format!("{}{advisory}", &caps[0])
        })
        .into_owned();

    let changed = output != toml_src;
    let changed_count = usize::from(changed);
    Ok(MigrationResult {
        output,
        changed_count,
        sections_changed: if changed {
            vec!["tui.delights".to_owned()]
        } else {
            Vec::new()
        },
    })
}

/// Inject `mouse = false` under `[tui]` when absent (#5103).
///
/// No-op when `[tui]` is absent, or when `mouse` is already present (active or
/// commented-out) — idempotent.
///
/// # Errors
///
/// Returns `MigrateError::TomlParse` if the input is not valid TOML; infallible otherwise.
pub fn migrate_tui_mouse(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    if !toml_src.contains("[tui]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let already_present = toml_src.lines().any(|l| {
        let t = l.trim().trim_start_matches('#').trim();
        t.starts_with("mouse")
    });
    if already_present {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let owned;
    let src = if toml_src.ends_with('\n') {
        toml_src
    } else {
        owned = format!("{toml_src}\n");
        &owned
    };

    if !TUI_HEADER_RE.is_match(src) {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let insert =
        "# mouse = false  # opt-in mouse capture: wheel scrolls, clicks focus panels (#5103)\n";
    let output = TUI_HEADER_RE
        .replacen(src, 1, |caps: &regex::Captures| {
            format!("{}{insert}", &caps[0])
        })
        .into_owned();

    let changed = output != toml_src;
    let changed_count = usize::from(changed);
    Ok(MigrationResult {
        output,
        changed_count,
        sections_changed: if changed {
            vec!["tui".to_owned()]
        } else {
            Vec::new()
        },
    })
}

/// Strip any existing `[memory.compression.predictor]` section from the config (#3251).
///
/// The compression predictor feature was removed. This migration cleans up both active
/// and commented-out sections that previous `--migrate-config` runs may have injected.
/// # Errors
///
/// This function is a pure string operation and always returns `Ok`. The `Result`
/// return type is kept for API consistency with other migration functions.
pub fn migrate_compression_predictor_config(
    toml_src: &str,
) -> Result<MigrationResult, MigrateError> {
    // Strip any [memory.compression.predictor] section (active or commented-out) that
    // prior migrate-config runs may have injected. The feature is removed (#3251).
    let has_active = toml_src.contains("[memory.compression.predictor]");
    let has_commented = toml_src.contains("# [memory.compression.predictor]");
    if !has_active && !has_commented {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    // Remove lines that belong to the section header variants and their key lines.
    // A line belongs to the section when the section header has been seen and the
    // line is not a new `[section]` header (excluding the predictor header itself).
    let mut output_lines: Vec<&str> = Vec::new();
    let mut in_predictor = false;
    for line in toml_src.lines() {
        let trimmed = line.trim();
        // Detect active or commented-out section header.
        if trimmed == "[memory.compression.predictor]"
            || trimmed == "# [memory.compression.predictor]"
        {
            in_predictor = true;
            continue;
        }
        // Any new `[section]` header (not commented-out) ends the predictor block.
        if in_predictor && trimmed.starts_with('[') && !trimmed.starts_with("# [") {
            in_predictor = false;
        }
        if !in_predictor {
            output_lines.push(line);
        }
    }
    // Preserve trailing newline if original had one.
    let mut output = output_lines.join("\n");
    if toml_src.ends_with('\n') {
        output.push('\n');
    }

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["memory.compression.predictor".to_owned()],
    })
}

/// Add a commented-out `[memory.microcompact]` block if absent (#2699).
///
/// # Errors
///
/// Returns `MigrateError::Parse` if the TOML cannot be parsed.
pub fn migrate_microcompact_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    // Idempotency: comments are invisible to toml_edit, so check the raw source.
    if toml_src.contains("[memory.microcompact]") || toml_src.contains("# [memory.microcompact]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let doc = toml_src.parse::<toml_edit::DocumentMut>()?;
    if !doc.contains_key("memory") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "\n# Time-based microcompact (#2699). Strips stale low-value tool outputs after idle.\n\
         # [memory.microcompact]\n\
         # enabled = false\n\
         # gap_threshold_minutes = 60   # idle gap before clearing stale outputs\n\
         # keep_recent = 3              # always keep this many recent outputs intact\n";
    let raw = doc.to_string();
    let output = format!("{raw}{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["memory.microcompact".to_owned()],
    })
}

/// Add a commented-out `[memory.autodream]` block if absent (#2697).
///
/// # Errors
///
/// Returns `MigrateError::Parse` if the TOML cannot be parsed.
pub fn migrate_autodream_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    // Idempotency: comments are invisible to toml_edit, so check the raw source.
    if toml_src.contains("[memory.autodream]") || toml_src.contains("# [memory.autodream]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let doc = toml_src.parse::<toml_edit::DocumentMut>()?;
    if !doc.contains_key("memory") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "\n# autoDream background memory consolidation (#2697). Disabled by default.\n\
         # [memory.autodream]\n\
         # enabled = false\n\
         # min_sessions = 5             # sessions since last consolidation\n\
         # min_hours = 8                # hours since last consolidation\n\
         # consolidation_provider = \"\" # provider name from [[llm.providers]]; empty = primary\n\
         # max_iterations = 5\n";
    let raw = doc.to_string();
    let output = format!("{raw}{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["memory.autodream".to_owned()],
    })
}

/// Add a commented-out `[magic_docs]` block if absent (#2702).
///
/// # Errors
///
/// Returns `MigrateError::Parse` if the TOML cannot be parsed.
pub fn migrate_magic_docs_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    use toml_edit::{Item, Table};

    let mut doc = toml_src.parse::<toml_edit::DocumentMut>()?;

    if doc.contains_key("magic_docs") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    doc.insert("magic_docs", Item::Table(Table::new()));
    let comment = "# MagicDocs auto-maintained markdown (#2702). Disabled by default.\n\
         # [magic_docs]\n\
         # enabled = false\n\
         # min_turns_between_updates = 10\n\
         # update_provider = \"\"         # provider name from [[llm.providers]]; empty = primary\n\
         # max_iterations = 3\n";
    // Remove the just-inserted empty table and replace with a comment.
    doc.remove("magic_docs");
    // Append as a trailing comment on the document root.
    let raw = doc.to_string();
    let output = format!("{raw}\n{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["magic_docs".to_owned()],
    })
}

/// Add a commented-out `persistence_enabled` key under `[orchestration]` when absent (#3107).
///
/// Existing configs that omit this key pick up `true` via `#[serde(default)]`, so this
/// migration is informational — it surfaces the new option without changing behaviour.
///
/// # Errors
///
/// Returns [`MigrateError`] if the TOML document cannot be parsed.
pub fn migrate_orchestration_persistence(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    // Skip if the key is already present (active or commented).
    if toml_src.contains("persistence_enabled") || toml_src.contains("# persistence_enabled") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    // Only inject under an existing [orchestration] section.
    if !toml_src.contains("[orchestration]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    // Insert the commented key right after the `[orchestration]` header line.
    let comment = "# persistence_enabled = true  \
        # persist task graphs to SQLite after each tick; enables `/plan resume <id>` (#3107)\n";
    let output = toml_src.replacen(
        "[orchestration]\n",
        &format!("[orchestration]\n{comment}"),
        1,
    );
    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["orchestration.persistence_enabled".to_owned()],
    })
}

/// Add the `[goals]` section as commented-out defaults when it is absent.
///
/// # Errors
///
/// Returns [`MigrateError::Parse`] when `toml_src` is not valid TOML.
pub fn migrate_goals_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    if toml_src.contains("[goals]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "\n# Long-horizon goal lifecycle tracking (#3567).\n\
         # [goals]\n\
         # enabled = false\n\
         # inject_into_system_prompt = true\n\
         # max_text_chars = 2000\n\
         # max_history = 50\n";

    Ok(MigrationResult {
        output: format!("{toml_src}{comment}"),
        changed_count: 1,
        sections_changed: vec!["goals".to_owned()],
    })
}

/// Add a commented-out `[caveman]` block if absent (#4985).
///
/// All `CavemanConfig` fields have `#[serde(default)]` so existing configs parse without changes;
/// this migration only surfaces the section so users can discover and enable it.
///
/// # Errors
///
/// This function is infallible in practice; the `Result` return type matches the
/// migration function convention for use in chained pipelines.
pub fn migrate_caveman_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    if toml_src.contains("[caveman]") || toml_src.contains("# [caveman]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "\n# [caveman] — ultra-compressed telegraphic output mode (#4985).\n\
         # Toggle at runtime with /caveman [on|off] or via the bundled caveman skill.\n\
         # [caveman]\n\
         # default_on = false\n";
    let output = format!("{toml_src}{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["caveman".to_owned()],
    })
}

/// Add a commented-out `[deep_link]` section if absent (spec-066, #5011).
///
/// All `DeepLinkConfig` fields have `#[serde(default)]` so existing configs parse without
/// changes; this migration only surfaces the section so users can discover and configure it.
///
/// # Errors
///
/// This function is infallible in practice; the `Result` return type matches the migration
/// function convention.
pub fn migrate_deep_link_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    if toml_src.contains("[deep_link]") || toml_src.contains("# [deep_link]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "\n# [deep_link] — zeph:// URI scheme configuration (spec-066, #5011).\n\
         # Requires the `deep-link` Cargo feature to be active.\n\
         # [deep_link]\n\
         # confirm_before_prompt = true   # require y/N before injecting prompt (secure default)\n\
         # allowed_cwd_roots = []          # restrict cwd to these prefixes; empty = any non-denylisted path\n\
         # prefer_acp = \"never\"           # v1 only: \"never\"; \"auto\"/\"always\" reserved for v2\n";
    let output = format!("{toml_src}{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["deep_link".to_owned()],
    })
}

/// Add a commented-out `[memory.five_signal]` section if absent (#4374).
///
/// All five-signal fields have `#[serde(default)]` so existing configs parse without changes.
/// This step surfaces the new section for users upgrading from older configs.
///
/// # Errors
///
/// Returns `MigrateError::Parse` if the TOML cannot be parsed.
pub fn migrate_five_signal_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    if toml_src.contains("[memory.five_signal]") || toml_src.contains("# [memory.five_signal]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let doc = toml_src.parse::<toml_edit::DocumentMut>()?;
    if !doc.contains_key("memory") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "\n# Five-signal SYNAPSE retrieval (#4374). Disabled by default.\n\
         # [memory.five_signal]\n\
         # enabled = false\n\
         # w_recency = 0.35\n\
         # w_relevance = 0.35\n\
         # w_frequency = 0.15\n\
         # w_causal = 0.10\n\
         # w_novelty = 0.05\n\
         # causal_bfs_max_depth = 10\n\
         # neutral_causal_distance = 5\n\
         # novelty_decay_rate = 0.1\n\
         #\n\
         # [memory.five_signal.consolidation_daemon]\n\
         # enabled = false\n\
         # interval_seconds = 7200\n\
         # batch_size = 500\n\
         # promotion_score_threshold = 0.70\n\
         # demotion_score_threshold = 0.20\n\
         # top_k_per_run = 500\n";
    let raw = doc.to_string();
    let output = format!("{raw}{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["memory.five_signal".to_owned()],
    })
}

/// Add a commented-out `[knowledge]` block if absent (spec-067, #5017).
///
/// Idempotent: no-ops when `[knowledge]` is already present in any form.
///
/// # Errors
///
/// Returns `MigrateError::Parse` if the TOML cannot be parsed.
pub fn migrate_knowledge_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    if toml_src.contains("[knowledge]") || toml_src.contains("# [knowledge]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "\n# Knowledge-ingest subsystem (spec-067, #5017). All defaults shown.\n\
         # [knowledge]\n\
         # ingest_provider = \"\"          # provider from [[llm.providers]]; empty = primary (Phase 2 graph)\n\
         # concurrency = 3              # max parallel extract tasks (Phase 2)\n\
         # max_documents = 0            # 0 = unlimited; CLI --max-documents overrides\n\
         # recall_include_imported = true  # include imported rows in semantic recall\n\
         # transcript_scope = \"current-project\"  # INV-6: only current-project supported in Phase 1\n";
    let doc = toml_src.parse::<toml_edit::DocumentMut>()?;
    let raw = doc.to_string();
    let output = format!("{raw}{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["knowledge".to_owned()],
    })
}

static TUI_THEME_HEADER_RE: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
    Regex::new(r"(?m)^[ \t]*\[tui\.theme\][ \t]*(?:#[^\r\n]*)?\r?\n").expect("static pattern")
});

/// Insert active `name` and `color_mode` defaults into `[tui.theme]` when the section
/// exists but those keys are absent (#5091).
///
/// Step 65 added a commented-out advisory block so users could discover the new section.
/// This step upgrades configs that already have an active `[tui.theme]` section (either
/// hand-edited or promoted from the advisory block) by injecting the two mandatory keys
/// with their safe defaults so that the runtime never falls back to compiled-in values
/// silently.
///
/// The step is idempotent: if either key is already present the function is a no-op.
/// If the `[tui.theme]` section is absent entirely the step is also a no-op (step 65
/// handles that case).
///
/// # Errors
///
/// Returns `MigrateError::TomlParse` if the input is not valid TOML.
pub fn migrate_tui_theme_defaults(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    // Check whether a key with the exact name exists inside [tui.theme].
    // Uses exact-key matching: trim the line, strip a leading `#` for commented keys,
    // split on `=`, and compare the key token — prevents prefix false-positives
    // (e.g. `name_hint` must NOT satisfy `has_name`).
    let key_in_tui_theme = |key: &str| {
        let mut in_tui_theme = false;
        toml_src.lines().any(|l| {
            let t = l.trim();
            // Section header line — update scope flag and keep scanning.
            if !t.starts_with('#') && t.starts_with('[') {
                in_tui_theme = t == "[tui.theme]";
                return false;
            }
            if !in_tui_theme {
                return false;
            }
            // Strip optional leading `#` for commented-out keys.
            let body = t.trim_start_matches('#').trim();
            // Extract the key token (everything before `=`), trim whitespace.
            let lhs = body.split('=').next().unwrap_or("").trim();
            lhs == key
        })
    };

    let has_name = key_in_tui_theme("name");
    let has_color_mode = key_in_tui_theme("color_mode");

    // If [tui.theme] is absent, step 65 handles it — this step is a no-op.
    let has_section = toml_src.contains("[tui.theme]");
    if !has_section || (has_name && has_color_mode) {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    // Normalise: ensure the source ends with a newline so the regex can always
    // match the header line (hand-edited files may omit the trailing newline).
    let owned;
    let src = if toml_src.ends_with('\n') {
        toml_src
    } else {
        owned = format!("{toml_src}\n");
        &owned
    };

    if !TUI_THEME_HEADER_RE.is_match(src) {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let mut insert = String::new();
    if !has_name {
        insert
            .push_str("name       = \"zephyr\"  # built-in preset; see /theme for alternatives\n");
    }
    if !has_color_mode {
        insert.push_str("color_mode = \"auto\"    # auto | truecolor | ansi256 | ansi16 | never\n");
    }

    let output = TUI_THEME_HEADER_RE
        .replacen(src, 1, |caps: &regex::Captures| {
            format!("{}{insert}", &caps[0])
        })
        .into_owned();

    let changed = output != toml_src;
    let changed_count = usize::from(changed);
    Ok(MigrationResult {
        output,
        changed_count,
        sections_changed: if changed {
            vec!["tui.theme".to_owned()]
        } else {
            Vec::new()
        },
    })
}

/// Inject a commented-out `[tui.theme]` advisory block when absent (#5087).
///
/// The `[tui.theme]` section was added in the TUI Theme System 2.0. Existing configs parse
/// fine without it (all fields have defaults), but surfacing the new keys lets users discover
/// and customise them.
///
/// No-op when `[tui.theme]` is already present (active or commented-out), determined by a
/// section-scoped scan that only looks inside the `[tui]` body — identical to the idempotency
/// strategy used in step 63.
///
/// # Errors
///
/// Returns `MigrateError::TomlParse` if the input is not valid TOML; infallible otherwise.
pub fn migrate_tui_theme_config(toml_src: &str) -> Result<MigrationResult, MigrateError> {
    // Section-scoped idempotency: check only inside [tui] for [tui.theme].
    // A raw `toml_src.contains("[tui.theme]")` would also match `# [tui.theme]` advisory
    // blocks appended by earlier runs, but we restrict to the live [tui] body.
    let in_tui_section = {
        let mut in_section = false;
        toml_src.lines().any(|l| {
            let t = l.trim();
            if !t.starts_with('#') && t.starts_with('[') && !t.starts_with("[[") {
                in_section = t == "[tui]";
                return false;
            }
            if t.starts_with('#') {
                let inner = t.trim_start_matches('#').trim();
                if inner.starts_with('[') {
                    in_section = false;
                    return false;
                }
                return in_section && (inner == "[tui.theme]" || inner.starts_with("tui.theme"));
            }
            in_section && (t == "[tui.theme]" || t.starts_with("tui.theme"))
        })
    };

    if in_tui_section || toml_src.contains("[tui.theme]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let doc = toml_src.parse::<toml_edit::DocumentMut>()?;
    let raw = doc.to_string();
    let comment = "\n# [tui.theme] — TUI visual theme (Theme System 2.0, #5087).\n\
         # name sets the colour palette. Built-in presets: classic, zephyr, zephyr-light,\n\
         # high-contrast, catppuccin-mocha, gruvbox-dark, solarized-dark.\n\
         # Custom palettes: drop a TOML file in ~/.config/zeph/themes/<name>.toml.\n\
         # [tui.theme]\n\
         # name         = \"zephyr\"    # default: zephyr (new default since 2.0; use \"classic\" for legacy look)\n\
         # color_mode   = \"auto\"      # auto | truecolor | ansi256 | ansi16 | never\n";
    let output = format!("{raw}{comment}");

    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["tui.theme".to_owned()],
    })
}

/// Step 69 — add `default_asset_sensitivity` advisory comment to `[orchestration]` (spec-068, #3934).
///
/// Advisory only: the migration is informational — it surfaces the new option without
/// changing behaviour. Skipped when the key is already present or `[orchestration]` is absent.
///
/// # Errors
///
/// Returns [`MigrateError`] if the TOML document cannot be parsed.
pub fn migrate_orchestration_asset_sensitivity(
    toml_src: &str,
) -> Result<MigrationResult, MigrateError> {
    if toml_src.contains("default_asset_sensitivity")
        || toml_src.contains("# default_asset_sensitivity")
    {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    if !toml_src.contains("[orchestration]") {
        return Ok(MigrationResult {
            output: toml_src.to_owned(),
            changed_count: 0,
            sections_changed: Vec::new(),
        });
    }

    let comment = "# default_asset_sensitivity = \"public\"  \
        # advisory asset sensitivity: public | internal | confidential (spec-068, #3934)\n";
    let output = toml_src.replacen(
        "[orchestration]\n",
        &format!("[orchestration]\n{comment}"),
        1,
    );
    Ok(MigrationResult {
        output,
        changed_count: 1,
        sections_changed: vec!["orchestration.default_asset_sensitivity".to_owned()],
    })
}