doctrine 0.5.1

Project tooling CLI
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
// SPDX-License-Identifier: GPL-3.0-only
//! `doctrine rfc` — request-for-comment discussion artifacts, doctrine's
//! governance-neutral deliberation kind. A thin per-kind module over the shared
//! `governance` spine: this owns only the *RFC-specific* parts — the `GovKind`
//! descriptor, the clap status enum + known-set, the hide-set, and the
//! scaffold/render. All kind-agnostic CLI/status machinery lives in
//! `crate::governance`, parameterized by `RFC_KIND`.
//!
//! An RFC is a numeric directory under `.doctrine/rfc/` holding a sister
//! `rfc-NNN.toml` (structured, queried metadata) and a scaffolded `rfc-NNN.md`
//! prose body — the ADR shape exactly, riding `entity::Kind` over the
//! kind-blind engine. Unlike ADR, an RFC asserts NO governance position: it
//! is deliberation-only, structurally absent from governance surfaces.

use std::io::{self, Write};
use std::path::PathBuf;

use crate::entity::{Artifact, Fileset, Kind, ScaffoldCtx};
use crate::governance::{self, GovKind};
use crate::listing::{Format, ListArgs};
use crate::tomlfmt::toml_string;

/// Relative dir of the RFC tree inside the project root. Distinct top-level
/// tree — singular per design §3 (.doctrine/rfc).
const RFC_DIR: &str = ".doctrine/rfc";

/// The RFC governance descriptor the spine binds. `prefix` is the canonical-id
/// stem (`RFC-007`); `stem` is the file/JSON stem (`"rfc"`). `pub(crate)` so
/// `boot` etc. can access it.
pub(crate) const RFC_KIND: GovKind = GovKind {
    kind: Kind {
        dir: RFC_DIR,
        prefix: crate::kinds::RFC,
        scaffold: rfc_scaffold,
    },
    stem: "rfc",
    statuses: RFC_STATUSES,
    hidden: is_hidden,
};

/// The status transitions `rfc status` writes. A minimal, governance-neutral
/// machine (design §2): `open → resolved | withdrawn`. `open` is the scaffold
/// seed; `resolved` is outcome-blind ("concluded", not "concluded yes").
/// A flat enum — no per-state stamping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum RfcStatus {
    Open,
    Resolved,
    Withdrawn,
}

impl RfcStatus {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Resolved => "resolved",
            Self::Withdrawn => "withdrawn",
        }
    }
}

/// The RFC status known-set — the authority `governance::list_rows` checks
/// `--status` against. Mirrors `RfcStatus`'s variants, kept in lockstep by
/// `rfc_known_set_matches_variants` (a drift canary).
pub(crate) const RFC_STATUSES: &[&str] = &["open", "resolved", "withdrawn"];

/// The `rfc list` hide-set: `resolved` and `withdrawn` are terminal and drop
/// from the default list (live-set-by-default idiom, design §2 F4). The
/// override (`--all` or any explicit `--status`) reveals them — handled in
/// `listing::retain`, not here. Bound as `RFC_KIND.hidden`.
fn is_hidden(status: &str) -> bool {
    matches!(status, "resolved" | "withdrawn")
}

// ---------------------------------------------------------------------------
// Pure: render, scaffold (the RFC-specific templates — per-kind data)
// ---------------------------------------------------------------------------

/// Render `rfc-<id>.toml` from the embedded template by token substitution.
/// The `id/slug/title/status` keys round-trip into `meta::Meta` (VT-1).
fn render_rfc_toml(id: u32, slug: &str, title: &str, date: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/rfc.toml")?
        .replace("{{id}}", &id.to_string())
        .replace("{{slug}}", &toml_string(slug))
        .replace("{{title}}", &toml_string(title))
        .replace("{{date}}", date))
}

/// Render `rfc-<id>.md` from the embedded template: `{{ref}}` (the canonical
/// id, e.g. `RFC-007`) + `{{title}}`. No YAML frontmatter (D1) — metadata lives
/// in the sister toml, not the prose.
fn render_rfc_md(canonical_id: &str, title: &str) -> anyhow::Result<String> {
    Ok(crate::install::asset_text("templates/rfc.md")?
        .replace("{{ref}}", canonical_id)
        .replace("{{title}}", title))
}

/// The RFC fileset: sister TOML, prose body — no symlink (RFCs are simpler than
/// governance kinds; design §3 omits a slug symlink as unnecessary). Bound as
/// `RFC_KIND.kind.scaffold`.
fn rfc_scaffold(ctx: &ScaffoldCtx<'_>) -> anyhow::Result<Fileset> {
    let id = ctx.id;
    let name = format!("{id:03}");
    Ok(vec![
        Artifact::File {
            rel_path: PathBuf::from(format!("{name}/rfc-{name}.toml")),
            body: render_rfc_toml(id, ctx.slug, ctx.title, ctx.date)?,
        },
        Artifact::File {
            rel_path: PathBuf::from(format!("{name}/rfc-{name}.md")),
            body: render_rfc_md(ctx.canonical, ctx.title)?,
        },
    ])
}

// ---------------------------------------------------------------------------
// CLI entry points — thin forwarders binding RFC_KIND into the spine
// ---------------------------------------------------------------------------

/// `doctrine rfc new` → `governance::run_new(&RFC_KIND, …)`.
pub(crate) fn run_new(
    path: Option<PathBuf>,
    title: Option<String>,
    slug: Option<String>,
) -> anyhow::Result<()> {
    governance::run_new(&RFC_KIND, path, title, slug)
}

/// `doctrine rfc list` → `governance::run_list(&RFC_KIND, …)`.
pub(crate) fn run_list(path: Option<PathBuf>, args: ListArgs) -> anyhow::Result<()> {
    governance::run_list(&RFC_KIND, path, args)
}

/// `doctrine rfc show <RFC-NNN>` → `governance::run_show(&RFC_KIND, …)`.
pub(crate) fn run_show(
    path: Option<PathBuf>,
    reference: &str,
    format: Format,
) -> anyhow::Result<()> {
    governance::run_show(&RFC_KIND, path, reference, format)
}

/// `doctrine rfc status` — bind the concrete `RfcStatus` enum at the boundary,
/// delegate the edit-preserving transition to the spine, then print.
pub(crate) fn run_status(
    path: Option<PathBuf>,
    id: u32,
    status: RfcStatus,
    color: bool,
) -> anyhow::Result<()> {
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let gov_root = root.join(RFC_KIND.kind.dir);
    governance::set_status(
        &RFC_KIND,
        &gov_root,
        id,
        status.as_str(),
        &crate::clock::today(),
    )?;
    writeln!(
        io::stdout(),
        "RFC {id:03}: {}",
        crate::listing::status_colored(status.as_str(), color)
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests — the RFC-specific data (render, scaffold, known-set). The shared-spine
// behaviour tests (list/show/status/parse) live in `governance.rs`.
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::meta::Meta;
    use std::path::Path;

    // --- VT-1: render + round-trip ---

    #[test]
    fn render_rfc_toml_round_trips_to_metadata() {
        let body = render_rfc_toml(1, "use-rust", "Use Rust?", "2026-06-04").unwrap();
        let parsed: Meta = toml::from_str(&body).unwrap();
        assert_eq!(
            parsed,
            Meta {
                id: 1,
                slug: "use-rust".to_string(),
                title: "Use Rust?".to_string(),
                status: "open".to_string(),
            }
        );
        // VT-1: status seeds open, the date is injected, no token survives.
        assert!(body.contains("created = \"2026-06-04\""));
        assert!(!body.contains("{{"));
    }

    #[test]
    fn render_rfc_toml_escapes_hostile_title_and_slug() {
        let title = crate::tomlfmt::HOSTILE_TITLE;
        let slug = crate::tomlfmt::HOSTILE_SLUG;
        let body = render_rfc_toml(1, slug, title, "2026-06-04").unwrap();
        let parsed: Meta = toml::from_str(&body).unwrap();
        assert_eq!(parsed.slug, slug);
        assert_eq!(parsed.title, title);
    }

    #[test]
    fn render_rfc_md_substitutes_ref_and_title_without_frontmatter() {
        let body = render_rfc_md("RFC-001", "Use Rust?").unwrap();
        assert!(body.starts_with("# RFC-001: Use Rust?"));
        assert!(!body.contains("{{ref}}"));
        assert!(!body.contains("{{title}}"));
        assert!(!body.starts_with("---"));
        assert!(!body.contains("\n---\n"));
    }

    // --- VT-2: scaffold shape ---

    #[test]
    fn rfc_scaffold_lays_out_two_files() {
        let ctx = ScaffoldCtx {
            id: 1,
            canonical: "RFC-001",
            slug: "use-rust",
            title: "Use Rust?",
            date: "2026-06-04",
        };
        let fileset = rfc_scaffold(&ctx).unwrap();
        assert_eq!(fileset.len(), 2);
        assert!(matches!(&fileset[0],
            Artifact::File { rel_path, body }
            if rel_path == Path::new("001/rfc-001.toml") && body.contains("2026-06-04")));
        assert!(matches!(&fileset[1],
            Artifact::File { rel_path, body }
            if rel_path == Path::new("001/rfc-001.md") && body.contains("RFC-001: Use Rust?")));
    }

    /// Drift canary: the `RFC_STATUSES` known-set must stay in lockstep with the
    /// `RfcStatus` variants. Also proves EX-1: the defined known-status set is
    /// exactly {open, resolved, withdrawn} with NO "accepted".
    #[test]
    fn rfc_known_set_matches_variants() {
        let variants = [RfcStatus::Open, RfcStatus::Resolved, RfcStatus::Withdrawn];
        let from_variants: Vec<&str> = variants.iter().map(|v| v.as_str()).collect();
        assert_eq!(from_variants, RFC_STATUSES.to_vec());
        // EX-1: the set must NOT contain "accepted" — RFC is outcome-blind (design §2).
        assert!(!RFC_STATUSES.contains(&"accepted"));
    }

    // --- helpers -------------------------------------------------------------

    /// Write an RFC's authored toml directly at an explicit id (creating its dir).
    /// Bypasses the monotonic `Fresh` allocator so fixtures don't need a git
    /// trunk ref — the `adr_at` precedent. Only writes the fields `meta::read_meta`
    /// and `set_status` consume.
    fn rfc_at(root: &Path, id: u32, status: &str, slug: &str, title: &str) {
        let name = format!("{id:03}");
        let dir = root.join(RFC_DIR).join(&name);
        std::fs::create_dir_all(&dir).unwrap();
        let toml = format!(
            "schema = \"doctrine.rfc\"\nversion = 1\n\n\
             id = {id}\nslug = \"{slug}\"\ntitle = \"{title}\"\n\
             status = \"{status}\"\ncreated = \"2026-06-04\"\nupdated = \"2026-06-04\"\n"
        );
        std::fs::write(dir.join(format!("rfc-{name}.toml")), toml).unwrap();
    }

    /// The RFC tree root for a project root.
    fn rfc_root(root: &Path) -> PathBuf {
        root.join(RFC_DIR)
    }

    // --- VT-1 mint→show round-trip (integration) ---

    #[test]
    fn mint_show_round_trip_rfc_new_writes_both_tiers_rfc_show_renders_them() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // mint
        run_new(Some(root.to_path_buf()), Some("Use Rust?".into()), None).unwrap();
        let rfc_dir = root.join(".doctrine/rfc");
        assert!(rfc_dir.join("001/rfc-001.toml").is_file());
        assert!(rfc_dir.join("001/rfc-001.md").is_file());
        // show — prove the status-bearing path synthesises both tiers.
        // Default columns: id, status, title (no slug unless --columns …,slug).
        let out = governance::list_rows(&RFC_KIND, root, ListArgs::default()).unwrap();
        assert!(out.contains("RFC-001"));
        assert!(out.contains("open"));
        assert!(out.contains("Use Rust?"));
    }

    // --- VT-5: status field ---

    #[test]
    fn freshly_minted_rfc_reads_status_open_via_status_bearing_path() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        run_new(Some(root.to_path_buf()), Some("Use Rust?".into()), None).unwrap();
        // Read via the status-bearing path (meta::Meta parses the full authored
        // fields including status), NOT the status-less meta::read_id — VT-5.
        let rfc_root = root.join(RFC_KIND.kind.dir);
        let toml_path = rfc_root.join("001/rfc-001.toml");
        let text = std::fs::read_to_string(&toml_path).unwrap();
        let parsed: crate::meta::Meta = toml::from_str(&text).unwrap();
        assert_eq!(parsed.status, "open");
    }

    // --- PHASE-02 VT-1: status transitions ----------------------------------

    #[test]
    fn status_transition_open_to_resolved_persists() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        rfc_at(root, 1, "open", "think-rust", "Think Rust?");

        governance::set_status(
            &RFC_KIND,
            &rfc_root(root),
            1,
            RfcStatus::Resolved.as_str(),
            "2099-01-01",
        )
        .unwrap();

        let meta = crate::meta::read_meta(&rfc_root(root), "rfc", 1).unwrap();
        assert_eq!(meta.status, "resolved");
        // The file carries the stamp; `set_status` preserved the rest.
        let body = std::fs::read_to_string(rfc_root(root).join("001/rfc-001.toml")).unwrap();
        assert!(body.contains("updated = \"2099-01-01\""));
        assert!(body.contains("id = 1"));
        assert!(body.contains("slug = \"think-rust\""));
    }

    #[test]
    fn status_transition_open_to_withdrawn_persists() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        rfc_at(root, 3, "open", "too-early", "Too Early");

        governance::set_status(
            &RFC_KIND,
            &rfc_root(root),
            3,
            RfcStatus::Withdrawn.as_str(),
            "2099-01-01",
        )
        .unwrap();

        let meta = crate::meta::read_meta(&rfc_root(root), "rfc", 3).unwrap();
        assert_eq!(meta.status, "withdrawn");
    }

    #[test]
    fn status_transition_all_three_known_statuses_accepted_by_set_status() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // Prove each of the three known statuses is a legal transition target
        // (the set_status seam accepts every known value; the RFC has no FSM gate).
        for (id, target) in [
            (1, RfcStatus::Open.as_str()),
            (2, RfcStatus::Resolved.as_str()),
            (3, RfcStatus::Withdrawn.as_str()),
        ] {
            rfc_at(
                root,
                id,
                "open",
                &format!("slug-{id}"),
                &format!("Title {id}"),
            );
            governance::set_status(&RFC_KIND, &rfc_root(root), id, target, "2099-01-01").unwrap();
            let meta = crate::meta::read_meta(&rfc_root(root), "rfc", id).unwrap();
            assert_eq!(meta.status, target, "id {id}");
        }
    }

    #[test]
    fn status_transition_set_status_on_a_missing_rfc_errors() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        rfc_at(root, 1, "open", "exists", "Exists");
        let err = governance::set_status(
            &RFC_KIND,
            &rfc_root(root),
            9,
            RfcStatus::Resolved.as_str(),
            "2099-01-01",
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("not found"),
            "missing RFC is a hard error: {err}"
        );
    }

    // --- PHASE-02 VT-2: list visibility -------------------------------------

    #[test]
    fn rfc_list_default_hides_resolved_and_withdrawn() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        rfc_at(root, 1, "open", "alpha", "Alpha");
        rfc_at(root, 2, "resolved", "beta", "Beta");
        rfc_at(root, 3, "withdrawn", "gamma", "Gamma");

        // Default list: only open RFC-001 visible.
        let out = governance::list_rows(&RFC_KIND, root, ListArgs::default()).unwrap();
        assert!(out.contains("RFC-001"), "default shows open: {out}");
        assert!(!out.contains("RFC-002"), "default hides resolved: {out}");
        assert!(!out.contains("RFC-003"), "default hides withdrawn: {out}");
    }

    #[test]
    fn rfc_list_explicit_status_resolved_surfaces_it_and_filters_to_it() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        rfc_at(root, 1, "open", "alpha", "Alpha");
        rfc_at(root, 2, "resolved", "beta", "Beta");

        let out = governance::list_rows(
            &RFC_KIND,
            root,
            ListArgs {
                status: vec!["resolved".into()],
                ..ListArgs::default()
            },
        )
        .unwrap();
        assert!(out.contains("RFC-002"), "--status resolved surfaces: {out}");
        assert!(
            !out.contains("RFC-001"),
            "and filters to resolved only: {out}"
        );
    }

    #[test]
    fn rfc_list_all_reveals_every_status() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        rfc_at(root, 1, "open", "alpha", "Alpha");
        rfc_at(root, 2, "resolved", "beta", "Beta");
        rfc_at(root, 3, "withdrawn", "gamma", "Gamma");

        let out = governance::list_rows(
            &RFC_KIND,
            root,
            ListArgs {
                all: true,
                ..ListArgs::default()
            },
        )
        .unwrap();
        assert!(out.contains("RFC-001"), "--all reveals open: {out}");
        assert!(out.contains("RFC-002"), "--all reveals resolved: {out}");
        assert!(out.contains("RFC-003"), "--all reveals withdrawn: {out}");
    }

    // --- PHASE-02 VT-3: bogus --status errors -------------------------------

    #[test]
    fn rfc_list_rejects_an_unknown_status_with_a_clear_error() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        rfc_at(root, 1, "open", "alpha", "Alpha");

        let err = governance::list_rows(
            &RFC_KIND,
            root,
            ListArgs {
                status: vec!["bogus".into()],
                ..ListArgs::default()
            },
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("bogus"), "names the bad value: {err}");
        // The error must list the RFC known-status set, not a silent empty result.
        assert!(err.contains("open"), "lists the known set: {err}");
        assert!(
            err.contains("resolved"),
            "known set includes resolved: {err}"
        );
        assert!(
            err.contains("withdrawn"),
            "known set includes withdrawn: {err}"
        );
    }

    #[test]
    fn rfc_list_accepts_every_known_status_value() {
        let dir = tempfile::tempdir().unwrap();
        for s in RFC_STATUSES {
            assert!(
                governance::list_rows(
                    &RFC_KIND,
                    dir.path(),
                    ListArgs {
                        status: vec![(*s).to_string()],
                        ..ListArgs::default()
                    },
                )
                .is_ok(),
                "known status `{s}` accepted by --status"
            );
        }
    }
}