coding-tools 0.2.0

Declarative, agent-friendly CLI tools behind one 'ct' command: search, view, verifiable edits, and framed command tests.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Jonathan Shook

//! `ct-rules` — say what the rules are.
//!
//! The specification and storage interface for the project's invariant
//! surface: `--init` scaffolds `.ct/rules.jsonc`, `--add` verifies a rule
//! and records it (or parks it `--pending`), `--promote` re-verifies and
//! enforces a pending rule, `--remove` deletes by id, `--def` manages the
//! store's named vocabulary, and `--hook cargo` wires `ct check` into
//! `cargo test`. All store mutations go through the suite's own
//! comment-preserving patch machinery. Reachable directly or as `ct rules`.
//! The canonical reference is `docs/explain/ct-rules.md`; the surface
//! specification is `docs/specs/rules.md`. `ct-rules` writes only the store
//! (and the hook shim) and is on no allow-gate.

use std::path::PathBuf;
use std::process::ExitCode;

use clap::Parser;
use coding_tools::explain::Format;
use coding_tools::patch::{Op, normalize_value, parse_path};
use coding_tools::pulse;
use coding_tools::rules::{self, Adapter, ProbeOutcome, Severity};
use serde_json::json;

/// Agent documentation, embedded from the canonical `docs/explain` payloads.
const EXPLAIN_MD: &str = include_str!("../../docs/explain/ct-rules.md");
const EXPLAIN_JSON: &str = include_str!("../../docs/explain/ct-rules.json");

/// The header comment every store carries at the top of the file. The store
/// is JSONC, so a leading line comment is first-class; any store write
/// re-establishes the header if it has gone missing.
const HEADER: &str = "\
// ct rule store — the project's recorded invariants (its \"living surface\").\n\
// Each rule is a read-only probe answering a question, with the why behind it.\n\
// Managed by `ct rules` (add/promote/remove/def); verified by `ct check`.\n\
// Docs: ct-rules --explain | ct-check --explain\n";

/// The scaffold written by `--init`.
const TEMPLATE: &str = "{\n  \"defs\": {\n  },\n  \"rules\": [\n  ]\n}\n";

/// First line of the generated cargo hook, used to recognise our own file.
const HOOK_MARKER: &str = "// Generated by `ct rules --hook cargo`.";

#[derive(Parser, Debug)]
#[command(
    name = "ct-rules",
    version,
    about = "Record, promote, remove, and list the project's invariant rules (.ct/rules.jsonc).",
    long_about = "ct-rules is the writing side of the invariant surface (also reachable as \
                  `ct rules`): --add verifies a probe and records it as a rule, --pending parks \
                  an aspiration, --promote enforces it once it holds, --def names shared \
                  vocabulary, --hook cargo wires `ct check` into `cargo test`. Verification of \
                  the store is ct-check's job. See `ct-rules --explain` for details."
)]
struct Cli {
    /// Rule store. Default: the nearest .ct/rules.jsonc walking upward (created by --init/--add when absent).
    #[arg(long)]
    file: Option<PathBuf>,

    /// Create .ct/rules.jsonc (commented scaffold) if it does not exist.
    #[arg(long)]
    init: bool,

    /// Record a rule with this id: the probe (after `--`) is gate-validated and RUN now; it must hold unless --pending.
    #[arg(long, value_name = "ID")]
    add: Option<String>,

    /// With --add: record an aspiration that does not yet hold; reported as PENDING, never enforced, until --promote.
    #[arg(long)]
    pending: bool,

    /// With --add: the question this rule answers (required).
    #[arg(long)]
    question: Option<String>,

    /// With --add: why this invariant exists; printed whenever it fails.
    #[arg(long)]
    why: Option<String>,

    /// With --add: the verbatim human request behind this rule, retained in the store so the intent can be revisited; strip all prompts later with --flatten.
    #[arg(long)]
    prompt: Option<String>,

    /// With --add: tags for selection (comma-separated).
    #[arg(long, value_delimiter = ',')]
    tag: Vec<String>,

    /// With --add: fail (default) or warn (violations report but never redden the exit).
    #[arg(long)]
    severity: Option<String>,

    /// With --add: outcome adapter for bridge probes: exit (default) or empty.
    #[arg(long, value_name = "exit|empty")]
    expect: Option<String>,

    /// With --add: matcher adapter — the rule holds when this pattern appears in the probe's output.
    #[arg(long, value_name = "PATTERN")]
    expect_ok: Option<String>,

    /// With --add: matcher adapter — a violation when this pattern appears in the probe's output.
    #[arg(long, value_name = "PATTERN")]
    expect_err: Option<String>,

    /// With --add: permit network access where the bridge entry deems it meaningful (cargo deny).
    #[arg(long)]
    network: bool,

    /// With --add: per-rule probe bound in seconds (fractional allowed).
    #[arg(long, value_name = "SECS")]
    timeout: Option<f64>,

    /// Re-run a pending rule's probe; if it now holds, clear the pending flag (enforce it).
    #[arg(long, value_name = "ID")]
    promote: Option<String>,

    /// Remove the rule with this exact id.
    #[arg(long, value_name = "ID")]
    remove: Option<String>,

    /// Set a def: NAME=VALUE. VALUE is parsed as JSON (e.g. ["A","B"]) or taken as a string.
    #[arg(long, value_name = "NAME=VALUE")]
    def: Option<String>,

    /// Print defs and rules without changing anything.
    #[arg(long)]
    list: bool,

    /// Strip the retained "prompt" prose from every rule, leaving only the mechanical definitions.
    #[arg(long)]
    flatten: bool,

    /// Write the build hook for an ecosystem (currently: cargo — a tests/ shim that runs `ct check`).
    #[arg(long, value_name = "ECOSYSTEM")]
    hook: Option<String>,

    /// Suppress informational output.
    #[arg(long)]
    quiet: bool,

    /// Print agent usage docs (md or json) and exit.
    #[arg(long, value_enum, num_args = 0..=1, default_missing_value = "md")]
    explain: Option<Format>,

    /// The probe for --add (after `--`): an argv run directly, never through a shell.
    #[arg(last = true, value_name = "PROBE...")]
    probe: Vec<String>,
}

/// Today as `YYYY-MM-DD` (UTC), via days-from-epoch civil conversion.
fn today_utc() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let days = (secs / 86_400) as i64;
    // Howard Hinnant's civil_from_days.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02}")
}

/// Resolve the store path; with `create`, fall back to `./.ct/rules.jsonc`
/// (creating the `.ct` directory and scaffold) when no `.ct` exists upward.
fn resolve_store(file: &Option<PathBuf>, create: bool, quiet: bool) -> Result<PathBuf, String> {
    if let Some(f) = file {
        return Ok(f.clone());
    }
    let cwd = std::env::current_dir().map_err(|e| format!("cwd: {e}"))?;
    if let Some(root) = rules::discover_root(&cwd) {
        let path = rules::store_path(&root);
        if path.is_file() || !create {
            return Ok(path);
        }
        scaffold(&path, quiet)?;
        return Ok(path);
    }
    if !create {
        return Err(format!(
            "no .ct directory found from {} upward; create the store with `ct rules --init`",
            cwd.display()
        ));
    }
    let path = cwd.join(".ct").join(rules::STORE_FILE);
    scaffold(&path, quiet)?;
    Ok(path)
}

/// Tidy the store text for humans: guarantee the explanatory header at the
/// top (a store whose first content is not a comment gets the standard one
/// prepended) and strip trailing whitespace from every line, so the blank
/// separators between rules stay genuinely blank.
fn tidy(text: &str) -> String {
    let body: String = text
        .lines()
        .map(|l| l.trim_end())
        .collect::<Vec<_>>()
        .join("\n");
    let body = format!("{}\n", body.trim_end_matches('\n'));
    if body.trim_start().starts_with("//") {
        body
    } else {
        format!("{HEADER}{body}")
    }
}

/// Write the commented scaffold (and the `.ct` directory) if absent.
fn scaffold(path: &PathBuf, quiet: bool) -> Result<bool, String> {
    if path.is_file() {
        return Ok(false);
    }
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
    }
    std::fs::write(path, tidy(TEMPLATE)).map_err(|e| format!("write {}: {e}", path.display()))?;
    if !quiet {
        println!("created {}", path.display());
    }
    Ok(true)
}

/// Apply patch ops to the store file, comment-preservingly, ensuring the
/// explanatory header survives (or is re-established) on every write.
fn patch_store(path: &PathBuf, ops: &[Op]) -> Result<(), String> {
    let text = std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?;
    let (patched, changes) =
        coding_tools::patch::apply_doc(&text, ops).map_err(|e| format!("{}: {e}", path.display()))?;
    if changes == 0 {
        return Err("store edit made no change".to_string());
    }
    std::fs::write(path, tidy(&patched)).map_err(|e| format!("write {}: {e}", path.display()))?;
    Ok(())
}

/// Render a rule as readable multi-line JSONC for the store: one field per
/// line in a stable, human-first order, the probe argv inline on one line.
/// Continuation lines carry the store's element indentation (4 spaces); the
/// patch splice supplies the first line's own indent.
fn format_rule_entry(fields: &[(&str, serde_json::Value)]) -> String {
    let mut out = String::from("{\n");
    for (i, (key, value)) in fields.iter().enumerate() {
        let comma = if i + 1 < fields.len() { "," } else { "" };
        out.push_str(&format!("      \"{key}\": {value}{comma}\n"));
    }
    out.push_str("    }");
    out
}

/// Run one rule's probe (def-expanded, gated) from the project root and
/// classify it.
fn verify(
    store: &std::path::Path,
    probe: &[String],
    defs: &std::collections::BTreeMap<String, rules::Def>,
    adapter: &Adapter,
    network: bool,
    timeout: Option<f64>,
) -> Result<(ProbeOutcome, String, String), String> {
    let expanded = rules::expand_defs(probe, defs)?;
    let gated = rules::gate_probe(&expanded)?;
    let timeout = timeout.map(|v| pulse::secs("--timeout", v)).transpose()?;
    let (outcome, reason, captured) = rules::run_probe(
        &expanded,
        &gated,
        &rules::probe_root(store),
        network,
        timeout,
        adapter,
    );
    let mut detail = captured.stdout.trim_end().to_string();
    if detail.lines().count() > 10 {
        let head: Vec<&str> = detail.lines().take(10).collect();
        detail = format!("{}\n(...)", head.join("\n"));
    }
    Ok((outcome, reason, detail))
}

fn cmd_add(cli: &Cli, id: &str) -> Result<ExitCode, String> {
    let question = cli
        .question
        .as_deref()
        .ok_or("--add requires --question (what does this rule answer?)")?;
    if cli.probe.is_empty() {
        return Err("--add requires a probe after `--`".to_string());
    }
    if id.is_empty() || id.contains(char::is_whitespace) {
        return Err(format!("invalid id '{id}'"));
    }
    let severity = match cli.severity.as_deref() {
        Some(s) => Severity::parse(s)?,
        None => Severity::Fail,
    };
    let adapter = match (&cli.expect, &cli.expect_ok, &cli.expect_err) {
        (Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
            return Err("--expect conflicts with --expect-ok/--expect-err".to_string());
        }
        (Some(s), None, None) => Adapter::from_value(&json!(s))?,
        (None, None, None) => Adapter::Exit,
        (None, ok, err) => Adapter::Match {
            ok: ok.clone(),
            err: err.clone(),
        },
    };

    let path = resolve_store(&cli.file, true, cli.quiet)?;
    let text = std::fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
    let store = rules::parse_store(&text).map_err(|e| format!("{}: {e}", path.display()))?;
    if store.rules.iter().any(|r| r.id == id) {
        return Err(format!("rule '{id}' already exists (use --remove first; ids are history)"));
    }

    // The probe runs NOW: an enforced rule records an established truth.
    let (outcome, reason, detail) =
        verify(&path, &cli.probe, &store.defs, &adapter, cli.network, cli.timeout)?;
    match (&outcome, cli.pending) {
        (ProbeOutcome::Broken, _) => {
            eprintln!("ct-rules: candidate probe is BROKEN ({reason}); not recorded");
            return Ok(ExitCode::from(2));
        }
        (ProbeOutcome::Violated, false) => {
            eprintln!("ct-rules: candidate rule FAILED ({reason}); not recorded");
            if !detail.is_empty() {
                eprintln!("{detail}");
            }
            eprintln!("ct-rules: fix the code first, or record it as an aspiration with --pending");
            return Ok(ExitCode::from(1));
        }
        _ => {}
    }

    // Human-first field order: identity and intent up top, the probe last.
    let mut fields: Vec<(&str, serde_json::Value)> =
        vec![("id", json!(id)), ("question", json!(question))];
    if let Some(w) = &cli.why {
        fields.push(("why", json!(w)));
    }
    if let Some(p) = &cli.prompt {
        fields.push(("prompt", json!(p)));
    }
    if !cli.tag.is_empty() {
        fields.push(("tags", json!(cli.tag)));
    }
    if severity == Severity::Warn {
        fields.push(("severity", json!("warn")));
    }
    match &adapter {
        Adapter::Exit => {}
        Adapter::Empty => fields.push(("expect", json!("empty"))),
        Adapter::Match { ok, err } => {
            let mut m = serde_json::Map::new();
            if let Some(p) = ok {
                m.insert("ok-match".into(), json!(p));
            }
            if let Some(p) = err {
                m.insert("err-match".into(), json!(p));
            }
            fields.push(("expect", serde_json::Value::Object(m)));
        }
    }
    if cli.network {
        fields.push(("network", json!(true)));
    }
    if let Some(t) = cli.timeout {
        fields.push(("timeout", json!(t)));
    }
    if cli.pending {
        fields.push(("pending", json!(true)));
    }
    fields.push(("added", json!(today_utc())));
    fields.push(("probe", json!(cli.probe)));

    // Multi-line entry, blank-line separated from its predecessor; the patch
    // splice supplies the comma and element indent for the non-empty case.
    let entry = format_rule_entry(&fields);
    let value = format!("\n    {entry}");
    patch_store(
        &path,
        &[Op::Add {
            path: parse_path(".rules")?,
            raw: ".rules".to_string(),
            value,
        }],
    )?;

    if !cli.quiet {
        if cli.pending {
            let state = match outcome {
                ProbeOutcome::Holds => "already holds — consider recording without --pending",
                _ => "not yet held",
            };
            println!("recorded '{id}' (pending; {state})");
        } else {
            println!("recorded '{id}' (verified: {reason})");
        }
        if cli.prompt.is_some() {
            println!(
                "note: the originating request is retained in the rule's \"prompt\" field; \
                 edit it in the store, or strip all prompts with `ct rules --flatten`"
            );
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_flatten(cli: &Cli) -> Result<ExitCode, String> {
    let path = resolve_store(&cli.file, false, cli.quiet)?;
    let text = std::fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
    let store = rules::parse_store(&text).map_err(|e| format!("{}: {e}", path.display()))?;
    let with_prompts: Vec<&str> = store
        .rules
        .iter()
        .filter(|r| r.prompt.is_some())
        .map(|r| r.id.as_str())
        .collect();
    if with_prompts.is_empty() {
        if !cli.quiet {
            println!("nothing to flatten: no rule retains a prompt");
        }
        return Ok(ExitCode::SUCCESS);
    }
    let ops: Vec<Op> = with_prompts
        .iter()
        .map(|id| {
            let spec = format!(".rules[id={id}].prompt");
            Ok(Op::Delete {
                path: parse_path(&spec)?,
                raw: spec,
            })
        })
        .collect::<Result<_, String>>()?;
    patch_store(&path, &ops)?;
    if !cli.quiet {
        println!(
            "flattened {} prompt(s) ({}); only the mechanical definitions remain",
            with_prompts.len(),
            with_prompts.join(", ")
        );
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_promote(cli: &Cli, id: &str) -> Result<ExitCode, String> {
    let path = resolve_store(&cli.file, false, cli.quiet)?;
    let text = std::fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
    let store = rules::parse_store(&text).map_err(|e| format!("{}: {e}", path.display()))?;
    let rule = store
        .rules
        .iter()
        .find(|r| r.id == id)
        .ok_or_else(|| format!("no rule '{id}' in {}", path.display()))?;
    if !rule.pending {
        return Err(format!("rule '{id}' is not pending"));
    }
    let (outcome, reason, detail) = verify(
        &path,
        &rule.probe,
        &store.defs,
        &rule.expect,
        rule.network,
        rule.timeout,
    )?;
    if outcome != ProbeOutcome::Holds {
        eprintln!("ct-rules: '{id}' does not hold yet ({reason}); not promoted");
        if !detail.is_empty() {
            eprintln!("{detail}");
        }
        return Ok(ExitCode::from(if outcome == ProbeOutcome::Broken { 2 } else { 1 }));
    }
    let spec = format!(".rules[id={id}].pending");
    patch_store(
        &path,
        &[Op::Delete {
            path: parse_path(&spec)?,
            raw: spec,
        }],
    )?;
    if !cli.quiet {
        println!("promoted '{id}' (verified: {reason}); now enforced");
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_remove(cli: &Cli, id: &str) -> Result<ExitCode, String> {
    let path = resolve_store(&cli.file, false, cli.quiet)?;
    let text = std::fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
    let store = rules::parse_store(&text).map_err(|e| format!("{}: {e}", path.display()))?;
    if !store.rules.iter().any(|r| r.id == id) {
        return Err(format!("no rule '{id}' in {}", path.display()));
    }
    let spec = format!(".rules[id={id}]");
    patch_store(
        &path,
        &[Op::Delete {
            path: parse_path(&spec)?,
            raw: spec,
        }],
    )?;
    if !cli.quiet {
        println!("removed '{id}'");
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_def(cli: &Cli, spec: &str) -> Result<ExitCode, String> {
    let (name, value) = coding_tools::patch::split_assign(spec)
        .ok_or_else(|| format!("--def needs NAME=VALUE, got '{spec}'"))?;
    if name.is_empty() || name.contains('.') || name.contains(char::is_whitespace) {
        return Err(format!("invalid def name '{name}'"));
    }
    let path = resolve_store(&cli.file, true, cli.quiet)?;
    let target = format!(".defs.{name}");
    patch_store(
        &path,
        &[Op::Set {
            path: parse_path(&target)?,
            raw: target.clone(),
            value: normalize_value(value),
        }],
    )?;
    if !cli.quiet {
        println!("def '{name}' set");
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_list(cli: &Cli) -> Result<ExitCode, String> {
    let path = resolve_store(&cli.file, false, cli.quiet)?;
    let text = std::fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
    let store = rules::parse_store(&text).map_err(|e| format!("{}: {e}", path.display()))?;
    if !store.defs.is_empty() {
        println!("defs:");
        for (name, def) in &store.defs {
            match def {
                rules::Def::One(s) => println!("  {name} = {s}"),
                rules::Def::Many(items) => println!("  {name} = [{}]", items.join(", ")),
            }
        }
    }
    println!("rules ({}):", store.rules.len());
    for r in &store.rules {
        let mut flags = Vec::new();
        if r.pending {
            flags.push("pending");
        }
        if r.severity == Severity::Warn {
            flags.push("warn");
        }
        let flags = if flags.is_empty() {
            String::new()
        } else {
            format!(" [{}]", flags.join(","))
        };
        let tags = if r.tags.is_empty() {
            String::new()
        } else {
            format!("  ({})", r.tags.join(","))
        };
        println!("  {}{flags}  {}{tags}", r.id, r.question);
    }
    Ok(ExitCode::SUCCESS)
}

fn cmd_hook(cli: &Cli, ecosystem: &str) -> Result<ExitCode, String> {
    if ecosystem != "cargo" {
        return Err(format!("unknown --hook ecosystem '{ecosystem}' (supported: cargo)"));
    }
    // The hook lives at the project root: where .ct is.
    let store = resolve_store(&cli.file, false, cli.quiet)?;
    let root = store
        .parent() // .ct
        .and_then(|p| p.parent())
        .ok_or("cannot determine project root from store path")?
        .to_path_buf();
    if !root.join("Cargo.toml").is_file() {
        return Err(format!(
            "no Cargo.toml at {} — the cargo hook belongs at a Rust project root",
            root.display()
        ));
    }
    let shim = root.join("tests").join("ct_invariants.rs");
    if shim.exists() {
        let existing = std::fs::read_to_string(&shim).unwrap_or_default();
        if !existing.starts_with(HOOK_MARKER) {
            return Err(format!(
                "{} exists and was not generated by ct-rules; not overwriting",
                shim.display()
            ));
        }
    }
    if let Some(dir) = shim.parent() {
        std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
    }
    let body = format!(
        "{HOOK_MARKER}\n\
         // Runs the project's recorded invariants (.ct/rules.jsonc) under `cargo test`.\n\
         // Degrades loudly: a missing ct binary fails the test with instructions.\n\
         \n\
         #[test]\n\
         fn ct_invariants_hold() {{\n    \
             let root = env!(\"CARGO_MANIFEST_DIR\");\n    \
             match std::process::Command::new(\"ct\")\n        \
                 .args([\"check\", \"--quiet\"])\n        \
                 .current_dir(root)\n        \
                 .status()\n    \
             {{\n        \
                 Ok(s) if s.success() => {{}}\n        \
                 Ok(s) => panic!(\n            \
                     \"ct check reported failures (exit {{:?}}); run `ct check` in {{root}} for details\",\n            \
                     s.code()\n        \
                 ),\n        \
                 Err(e) => panic!(\n            \
                     \"could not run `ct` (install coding-tools and put it on PATH): {{e}}\"\n        \
                 ),\n    \
             }}\n\
         }}\n"
    );
    std::fs::write(&shim, body).map_err(|e| format!("write {}: {e}", shim.display()))?;
    if !cli.quiet {
        println!("wrote {} — `cargo test` now enforces the rule store", shim.display());
    }
    Ok(ExitCode::SUCCESS)
}

fn run(cli: Cli) -> Result<ExitCode, String> {
    let verbs = [
        cli.init,
        cli.add.is_some(),
        cli.promote.is_some(),
        cli.remove.is_some(),
        cli.def.is_some(),
        cli.list,
        cli.flatten,
        cli.hook.is_some(),
    ];
    match verbs.iter().filter(|v| **v).count() {
        0 => return Err(
            "nothing to do: use --init, --add, --promote, --remove, --def, --list, --flatten, or --hook"
                .to_string(),
        ),
        1 => {}
        _ => return Err("choose exactly one of --init/--add/--promote/--remove/--def/--list/--flatten/--hook".to_string()),
    }

    if cli.init {
        let path = resolve_store(&cli.file, true, cli.quiet)?;
        if path.is_file() && !cli.quiet {
            println!("store present at {}", path.display());
        }
        return Ok(ExitCode::SUCCESS);
    }
    if let Some(id) = cli.add.clone() {
        return cmd_add(&cli, &id);
    }
    if let Some(id) = cli.promote.clone() {
        return cmd_promote(&cli, &id);
    }
    if let Some(id) = cli.remove.clone() {
        return cmd_remove(&cli, &id);
    }
    if let Some(spec) = cli.def.clone() {
        return cmd_def(&cli, &spec);
    }
    if cli.list {
        return cmd_list(&cli);
    }
    if cli.flatten {
        return cmd_flatten(&cli);
    }
    if let Some(eco) = cli.hook.clone() {
        return cmd_hook(&cli, &eco);
    }
    unreachable!("verb dispatch covered above")
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    if let Some(fmt) = cli.explain {
        let body = match fmt {
            Format::Md => EXPLAIN_MD,
            Format::Json => EXPLAIN_JSON,
        };
        print!("{body}");
        return ExitCode::SUCCESS;
    }

    match run(cli) {
        Ok(code) => code,
        Err(msg) => {
            eprintln!("ct-rules: {msg}");
            ExitCode::from(2)
        }
    }
}