basemind 0.21.1

Full AI context layer over MCP — tree-sitter code-map, document RAG (PDF/Office/HTML/email + OCR + reranker), shared agent memory, on-demand web crawl, git history + blame + per-symbol diff. 300+ languages, 10+ coding-agent harnesses, content-addressed Fjall + LanceDB.
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
//! `basemind init` — the re-runnable onboarding flow.
//!
//! Three side effects, each idempotent and safe to re-run:
//! 1. Write the commented `basemind.toml` scaffold at the repo root (kept, never clobbered, when
//!    one already exists).
//! 2. Ensure `.basemind/` is gitignored.
//! 3. Inject a "prefer basemind over grep / read / git" rules block into the host repo's
//!    agent-instructions file — an idempotent delimited block in CLAUDE.md / AGENTS.md, or an
//!    ai-rulez rule file when `.ai-rulez/config.toml` owns governance.
//!
//! Capability selection (interactive in a TTY, flag-driven otherwise) narrows which routing rows
//! the rules block advertises. `main.rs` is a thin dispatcher into [`run`]; the block content
//! lives in [`super::init_rules`].

use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use clap::{Args, ValueEnum};

use super::init_rules::{self, BlockSections, Capability};
use crate::config;

/// BEGIN delimiter of the managed rules block. Load-bearing: the splice matches this verbatim.
pub(crate) const BEGIN_MARKER: &str = "<!-- BEGIN basemind (managed by `basemind init`) -->";
/// END delimiter of the managed rules block.
pub(crate) const END_MARKER: &str = "<!-- END basemind -->";

/// Fully-commented `basemind.toml` scaffold. Doubles as living documentation: every value shown is
/// the built-in default, so an unedited file is a no-op. Written to the repo ROOT (committed);
/// the `.basemind/` cache it drives is gitignored.
pub(crate) const INIT_SCAFFOLD_TOML: &str = r##"# basemind configuration — https://github.com/Goldziher/basemind
# Lives at the repo root and is meant to be committed. The `.basemind/` cache (index + blobs) is
# derived state, gitignored, and wiped on schema bumps — never put durable config there.
# Every value below is the built-in default; uncomment and edit only what you want to change.
"$schema" = "v1"

[scan]
# Files to index. Default is "everything"; the tree-sitter language registry + a binary/size check
# filter the long tail. Narrow it if you only care about specific languages.
# include = ["**/*"]
# Extra exclude globs, ADDED ON TOP of the always-on floor (node_modules, target, dist, .venv,
# __pycache__, .git, .basemind, bazel-*, .idea, .DS_Store, …). You cannot remove a floor entry.
# exclude = []
# Honor .gitignore / .git/info/exclude while walking. Leave on unless you deliberately want
# ignored files indexed.
# respect_gitignore = true
# Follow symlinks during the walk. Off by default — symlinks often escape the repo (e.g. Bazel's
# bazel-* convenience symlinks). Turn on for repos that symlink real source into place.
# follow_symlinks = false
# Skip files larger than this many bytes (prevents minified-bundle stalls).
# max_file_bytes = 2097152
# Skip paths under any submodule root listed in .gitmodules.
# skip_submodules = true
# Run L2 extraction (calls + docs) inline with L1. Powers find_references / find_callers. Turning
# off roughly halves scan time on large repos but leaves reference search empty until an L2 pass.
# eager_l2 = true
# Absolute paths OUTSIDE the repo to also index (e.g. a Bazel external cache). Symlinks are always
# followed for these regardless of scan.follow_symlinks.
# extra_roots = []

[watch]
# Coalesce filesystem events within this window (milliseconds).
# debounce_ms = 250
# Run L2 extraction on live watch edits (extra CPU per edit).
# live_l2 = false

[cache]
# Max extracted file-maps kept hot in memory.
# file_map_lru = 256

[mcp]
# MCP transport. Only "stdio" is supported today.
# transport = "stdio"

[documents]
# Document RAG tier (PDF / Office / HTML / email / images). Requires a `documents` build.
# enabled = true
# Embed documents for semantic search. ON by default — embeddings pay off on real prose / OCR.
# embed = true
# Embedding model preset. Changing it forces a FULL RE-EMBED of the corpus (time + CPU): every
# document is re-encoded at the new model's dimension.
#   fast        — smallest / fastest, lowest quality
#   balanced    — default; 768-dim, good quality/cost tradeoff
#   quality     — larger model, best English quality, slower
#   multilingual— multilingual model for non-English corpora
# embedding_preset = "balanced"
# Globs for documents that are still extracted + indexed but NOT embedded (keyword-only).
# embed_exclude = []
# Route archives (.zip/.tar/.jar/…) into the recursive archive extractor. Off by default so one
# archive can't explode into thousands of embeds. True binaries are always skipped.
# extract_archives = false

[code_search]
# Semantic code-search tier. Requires a `code-search` build.
# enabled = true
# Embed source code for VECTOR search. OFF by default — local embeddings on code aren't worth the
# cost (code is embedded with a general English model, and NL→symbol is already served by the BM25
# keyword lane over the same text). Chunking + BM25 keyword search work regardless. Turn on only if
# you specifically want vector search over code (downloads an ONNX model, re-embeds on preset change).
# embed = false
# Globs for source files that are still chunked + BM25-indexed but NOT embedded (only used when
# embed = true).
# embed_exclude = []
"##;

/// Where to inject the usage rules. `Auto` follows detection priority
/// (ai-rulez → CLAUDE.md → AGENTS.md → create CLAUDE.md).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub enum RulesTarget {
    /// Detect the source of truth automatically (default).
    #[default]
    Auto,
    /// Force the CLAUDE.md delimited block.
    Claude,
    /// Force the AGENTS.md delimited block.
    Agents,
    /// Force an ai-rulez rule file (`.ai-rulez/rules/basemind-usage.md`).
    AiRulez,
    /// Write no rules at all (same as `--no-rules`).
    None,
}

/// Flags for `basemind init`. Flattened into the `Cmd::Init` clap variant in `main.rs`.
#[derive(Args, Debug, Default)]
pub struct InitArgs {
    /// Accept defaults non-interactively: enable every capability unless narrowed by
    /// `--with` / `--without`. Implied automatically when stdin is not a TTY.
    #[arg(long)]
    pub yes: bool,

    /// Enable only these capabilities (repeatable). Slugs: code-search-navigation,
    /// code-mapping-architecture, git-history, agent-comms, documents-rag, semantic-search.
    #[arg(long = "with", value_name = "CAPABILITY")]
    pub with: Vec<String>,

    /// Disable these capabilities (repeatable). Same slugs as `--with`.
    #[arg(long = "without", value_name = "CAPABILITY")]
    pub without: Vec<String>,

    /// Where to inject usage rules. `auto` (default) detects the source of truth.
    #[arg(long, value_enum, default_value_t = RulesTarget::Auto)]
    pub rules_target: RulesTarget,

    /// Skip rules injection entirely (config + gitignore only).
    #[arg(long)]
    pub no_rules: bool,

    /// Omit the usage-priority / routing-table section from the block.
    #[arg(long)]
    pub no_usage_rules: bool,

    /// Omit the setup & maintenance section from the block.
    #[arg(long)]
    pub no_setup_notes: bool,

    /// Dry run: print what WOULD change and write nothing.
    #[arg(long)]
    pub print: bool,
}

/// One planned filesystem effect, collected before anything is written so `--print` can report a
/// faithful dry-run and the real run reports the same set.
enum Change {
    /// A file will be created or its content changed. `note` is the human summary.
    Write {
        path: PathBuf,
        note: &'static str,
        contents: String,
    },
    /// Nothing to do for this target (already converged / opted out).
    NoOp { note: String },
}

/// Entry point. `root` is already resolved by `main`.
pub fn run(root: &Path, args: &InitArgs) -> Result<()> {
    let caps = select_capabilities(args)?;
    let sections = BlockSections {
        usage_rules: !args.no_usage_rules,
        setup_notes: !args.no_setup_notes,
    };

    let mut changes = Vec::new();
    changes.push(plan_config(root)?);
    changes.push(plan_gitignore(root)?);
    if let Some(rule_change) = plan_rules(root, args, &caps, sections)? {
        changes.push(rule_change);
    }

    if args.print {
        report_dry_run(&changes);
        return Ok(());
    }

    let mut any_write = false;
    for change in &changes {
        match change {
            Change::Write { path, note, contents } => {
                if let Some(parent) = path.parent() {
                    std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
                }
                std::fs::write(path, contents).with_context(|| format!("write {}", path.display()))?;
                println!("{note}: {}", path.display());
                any_write = true;
            }
            Change::NoOp { note } => println!("{note}"),
        }
    }
    if any_write {
        println!("basemind init: done.");
    } else {
        println!("basemind init: nothing to do — already up to date.");
    }
    Ok(())
}

/// Resolve the selected capability set from flags + interactivity.
fn select_capabilities(args: &InitArgs) -> Result<Vec<Capability>> {
    let with = parse_capabilities(&args.with)?;
    let without = parse_capabilities(&args.without)?;

    // ~keep Explicit `--with` is an allow-list; otherwise start from "all on".
    let base: Vec<Capability> = if with.is_empty() {
        Capability::ALL.to_vec()
    } else {
        with.clone()
    };

    let interactive = !args.yes && with.is_empty() && without.is_empty() && std::io::stdin().is_terminal();
    let selected: Vec<Capability> = if interactive {
        prompt_capabilities()?
    } else {
        base.into_iter().filter(|c| !without.contains(c)).collect()
    };
    Ok(selected)
}

/// Parse a list of capability slugs into [`Capability`], erroring on an unknown slug.
fn parse_capabilities(slugs: &[String]) -> Result<Vec<Capability>> {
    slugs
        .iter()
        .map(|s| {
            Capability::from_slug(s).ok_or_else(|| {
                anyhow::anyhow!(
                    "unknown capability {s:?}; expected one of: {}",
                    Capability::ALL.map(|c| c.slug()).join(", ")
                )
            })
        })
        .collect()
}

/// Interactive yes/no prompt per capability. Hand-rolled over stdin — no new crate dependency.
/// A blank answer accepts the default (yes).
fn prompt_capabilities() -> Result<Vec<Capability>> {
    let stdin = std::io::stdin();
    let mut stdout = std::io::stdout();
    println!("Select basemind capabilities to advertise (Y/n, blank = yes):");
    let mut selected = Vec::new();
    for cap in Capability::ALL {
        write!(stdout, "  {} [Y/n] ", cap.label()).context("write prompt")?;
        stdout.flush().context("flush prompt")?;
        let mut line = String::new();
        let read = stdin.read_line(&mut line).context("read stdin")?;
        // ~keep EOF mid-prompt: accept the default for this and every remaining capability.
        let answer = line.trim().to_ascii_lowercase();
        let yes = answer.is_empty() || answer == "y" || answer == "yes";
        if yes {
            selected.push(cap);
        }
        if read == 0 {
            break;
        }
    }
    Ok(selected)
}

/// Plan the `basemind.toml` write: scaffold when absent, keep when present.
fn plan_config(root: &Path) -> Result<Change> {
    let path = config::config_path(root);
    if path.exists() {
        return Ok(Change::NoOp {
            note: format!("basemind.toml: kept existing config at {}", path.display()),
        });
    }
    let legacy = config::legacy_config_path(root);
    if legacy.exists() {
        // ~keep A root scaffold would silently shadow the legacy config (root path wins in resolution), so
        // ~keep refuse rather than change the effective config behind the user's back. They migrate it,
        // ~keep then re-run init. Matches the pre-onboarding `cmd_init` contract (config_root_smoke).
        anyhow::bail!(
            "legacy config at {} is still read as a fallback; move it to {} to migrate — init will \
             not write a scaffold that shadows it",
            legacy.display(),
            path.display()
        );
    }
    Ok(Change::Write {
        path,
        note: "wrote basemind.toml scaffold",
        contents: INIT_SCAFFOLD_TOML.to_string(),
    })
}

/// Plan the `.gitignore` write: append `.basemind/` when the entry is missing.
fn plan_gitignore(root: &Path) -> Result<Change> {
    let path = root.join(".gitignore");
    let existing = match std::fs::read_to_string(&path) {
        Ok(contents) => Some(contents),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(anyhow::Error::new(e).context(format!("read {}", path.display()))),
    };
    let already = existing.as_deref().is_some_and(|contents| {
        contents.lines().any(|line| {
            let entry = line.trim().trim_start_matches('/').trim_end_matches('/');
            entry == ".basemind"
        })
    });
    if already {
        return Ok(Change::NoOp {
            note: format!(".gitignore: .basemind already ignored ({})", path.display()),
        });
    }
    let mut contents = existing.unwrap_or_default();
    if !contents.is_empty() && !contents.ends_with('\n') {
        contents.push('\n');
    }
    contents.push_str(".basemind/\n");
    Ok(Change::Write {
        path,
        note: "updated .gitignore (.basemind/)",
        contents,
    })
}

/// Which agent-instructions file owns the rules, after resolving `--rules-target`/`--no-rules`
/// against the detection priority.
enum RulesPlan {
    /// Skip rules entirely.
    Skip,
    /// Write an ai-rulez rule file at this path.
    AiRulez(PathBuf),
    /// Splice the delimited block into this markdown file (creating it if absent).
    Delimited(PathBuf),
}

/// Resolve where the rules go. Detection priority for `auto`:
/// `.ai-rulez/config.toml` → CLAUDE.md → AGENTS.md → create CLAUDE.md.
fn resolve_rules_plan(root: &Path, args: &InitArgs) -> RulesPlan {
    if args.no_rules || args.rules_target == RulesTarget::None {
        return RulesPlan::Skip;
    }
    let ai_rulez_rule = root.join(".ai-rulez").join("rules").join("basemind-usage.md");
    let claude = root.join("CLAUDE.md");
    let agents = root.join("AGENTS.md");
    match args.rules_target {
        RulesTarget::AiRulez => RulesPlan::AiRulez(ai_rulez_rule),
        RulesTarget::Claude => RulesPlan::Delimited(claude),
        RulesTarget::Agents => RulesPlan::Delimited(agents),
        RulesTarget::None => RulesPlan::Skip,
        RulesTarget::Auto => {
            if root.join(".ai-rulez").join("config.toml").exists() {
                RulesPlan::AiRulez(ai_rulez_rule)
            } else if claude.exists() {
                RulesPlan::Delimited(claude)
            } else if agents.exists() {
                RulesPlan::Delimited(agents)
            } else {
                RulesPlan::Delimited(claude)
            }
        }
    }
}

/// Plan the rules write. Returns `None` only when rules are skipped.
fn plan_rules(root: &Path, args: &InitArgs, caps: &[Capability], sections: BlockSections) -> Result<Option<Change>> {
    match resolve_rules_plan(root, args) {
        RulesPlan::Skip => Ok(Some(Change::NoOp {
            note: "rules: skipped (--no-rules / --rules-target none)".to_string(),
        })),
        RulesPlan::AiRulez(path) => {
            let contents = init_rules::render_ai_rulez_rule(caps, sections);
            let unchanged = std::fs::read_to_string(&path).is_ok_and(|prev| prev == contents);
            if unchanged {
                return Ok(Some(Change::NoOp {
                    note: format!("rules: ai-rulez rule already up to date ({})", path.display()),
                }));
            }
            Ok(Some(Change::Write {
                path,
                note: "wrote ai-rulez rule (run `ai-rulez generate` to render outputs)",
                contents,
            }))
        }
        RulesPlan::Delimited(path) => {
            let block = format!(
                "{BEGIN_MARKER}\n\n{}{END_MARKER}\n",
                init_rules::render_block_body(caps, sections)
            );
            let existing = match std::fs::read_to_string(&path) {
                Ok(c) => Some(c),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
                Err(e) => return Err(anyhow::Error::new(e).context(format!("read {}", path.display()))),
            };
            let next = splice_block(existing.as_deref(), &block)
                .with_context(|| format!("update basemind rules block in {}", path.display()))?;
            if existing.as_deref() == Some(next.as_str()) {
                return Ok(Some(Change::NoOp {
                    note: format!("rules: block already up to date ({})", path.display()),
                }));
            }
            Ok(Some(Change::Write {
                path,
                note: "injected basemind rules block",
                contents: next,
            }))
        }
    }
}

/// Splice the managed `block` into `existing` markdown idempotently: replace between the markers if
/// present, else append at EOF. Content outside the markers is preserved verbatim.
///
/// Bails (rather than guessing) when the markers are malformed — one marker present without its pair,
/// END before BEGIN, or a second BEGIN inside the block — because every such state makes the block
/// bounds ambiguous, and guessing risks silently deleting the user's own content between a stray
/// marker and the wrong pair. A hard stop asking the user to fix the markers is always safer.
fn splice_block(existing: Option<&str>, block: &str) -> Result<String> {
    let Some(existing) = existing else {
        return Ok(block.to_string());
    };
    match (existing.find(BEGIN_MARKER), existing.find(END_MARKER)) {
        (Some(begin), Some(end_start)) => {
            let begin_body = begin + BEGIN_MARKER.len();
            if end_start < begin_body {
                anyhow::bail!(
                    "malformed basemind block: END marker precedes BEGIN marker — resolve the markers manually then re-run"
                );
            }
            if existing[begin_body..end_start].contains(BEGIN_MARKER) {
                anyhow::bail!(
                    "malformed basemind block: a second BEGIN marker before the END marker — resolve the markers manually then re-run"
                );
            }
            let end = end_start + END_MARKER.len();
            // ~keep Absorb a single trailing newline (LF or CRLF) after the END marker so replacement is byte-stable.
            let after = &existing[end..];
            let tail_start = if after.starts_with("\r\n") {
                end + 2
            } else if after.starts_with('\n') {
                end + 1
            } else {
                end
            };
            let mut out = String::with_capacity(existing.len() + block.len());
            out.push_str(&existing[..begin]);
            out.push_str(block);
            out.push_str(&existing[tail_start..]);
            Ok(out)
        }
        (Some(_), None) | (None, Some(_)) => anyhow::bail!(
            "malformed basemind block: only one of the BEGIN/END markers is present — resolve the markers manually then re-run"
        ),
        (None, None) => {
            // ~keep No markers: append at EOF with a blank-line separator.
            let mut out = existing.to_string();
            if !out.is_empty() && !out.ends_with('\n') {
                out.push('\n');
            }
            if !out.is_empty() {
                out.push('\n');
            }
            out.push_str(block);
            Ok(out)
        }
    }
}

/// Print a faithful dry-run of the planned changes and note that nothing was written.
fn report_dry_run(changes: &[Change]) {
    let mut pending = 0;
    for change in changes {
        match change {
            Change::Write { path, note, .. } => {
                println!("would {note}: {}", path.display());
                pending += 1;
            }
            Change::NoOp { note } => println!("{note}"),
        }
    }
    if pending == 0 {
        println!("basemind init --print: no changes — already up to date.");
    } else {
        println!("basemind init --print: {pending} file(s) would change (nothing written).");
    }
}

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

    #[test]
    fn splice_appends_block_when_no_markers() {
        let out = splice_block(
            Some("# Title\n\nbody\n"),
            "<!-- BEGIN basemind (managed by `basemind init`) -->\nX\n<!-- END basemind -->\n",
        )
        .expect("well-formed input splices");
        assert!(out.starts_with("# Title\n\nbody\n"), "user content preserved");
        assert_eq!(out.matches(BEGIN_MARKER).count(), 1);
    }

    #[test]
    fn splice_replaces_in_place_and_is_idempotent() {
        let block = format!("{BEGIN_MARKER}\nv2\n{END_MARKER}\n");
        let before = format!("intro\n\n{BEGIN_MARKER}\nv1\n{END_MARKER}\n\noutro\n");
        let after = splice_block(Some(&before), &block).expect("well-formed input splices");
        assert_eq!(after.matches(BEGIN_MARKER).count(), 1, "no duplicate block");
        assert!(after.contains("v2") && !after.contains("v1"), "content replaced");
        assert!(
            after.contains("intro") && after.contains("outro"),
            "surrounding content kept"
        );
        // ~keep Re-splicing the same block is a fixpoint.
        assert_eq!(splice_block(Some(&after), &block).expect("fixpoint"), after);
    }

    #[test]
    fn splice_bails_on_orphaned_begin_marker() {
        // ~keep A lone BEGIN (END deleted by hand) must NOT append a second block — that would
        // ~keep leave a two-BEGIN/one-END state a later run could collapse, eating user content.
        let block = format!("{BEGIN_MARKER}\nv2\n{END_MARKER}\n");
        let orphaned = format!("intro\n{BEGIN_MARKER}\nv1\nno end here\noutro\n");
        assert!(
            splice_block(Some(&orphaned), &block).is_err(),
            "orphaned BEGIN must bail"
        );
    }

    #[test]
    fn splice_bails_on_reversed_and_doubled_markers() {
        let block = format!("{BEGIN_MARKER}\nv2\n{END_MARKER}\n");
        // ~keep END before BEGIN — bounds are inverted, refuse to guess.
        let reversed = format!("{END_MARKER}\nstray\n{BEGIN_MARKER}\n");
        assert!(
            splice_block(Some(&reversed), &block).is_err(),
            "reversed markers must bail"
        );
        // ~keep Two BEGINs before the END — ambiguous which block to replace.
        let doubled = format!("{BEGIN_MARKER}\na\n{BEGIN_MARKER}\nb\n{END_MARKER}\n");
        assert!(splice_block(Some(&doubled), &block).is_err(), "doubled BEGIN must bail");
    }

    #[test]
    fn splice_converges_to_fixpoint_on_crlf_file() {
        // ~keep A CRLF-authored rules file must reach a byte-stable fixpoint so `--print` stops
        // ~keep reporting a pending change and re-runs are no-ops (idempotency contract).
        let block = format!("{BEGIN_MARKER}\nv2\n{END_MARKER}\n");
        let crlf = format!("intro\r\n{BEGIN_MARKER}\r\nv1\r\n{END_MARKER}\r\noutro\r\n");
        let once = splice_block(Some(&crlf), &block).expect("first splice");
        let twice = splice_block(Some(&once), &block).expect("second splice");
        assert_eq!(once, twice, "CRLF file must converge to a fixpoint");
        assert_eq!(once.matches(BEGIN_MARKER).count(), 1, "single block");
        assert!(once.contains("outro"), "trailing user content kept");
    }

    #[test]
    fn none_target_skips_rules() {
        let args = InitArgs {
            rules_target: RulesTarget::None,
            ..Default::default()
        };
        assert!(matches!(
            resolve_rules_plan(Path::new("/nonexistent"), &args),
            RulesPlan::Skip
        ));
    }
}