rto-spec 1.18.0

House-style ADR/blueprint parsing, intent interview, and drift checking for Roteiro
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
// roteiro:ignore-file — the scaffold templates here intentionally contain the
// generated document's `- [ ]` interview items and `_TODO_` placeholders; that
// vocabulary is product content, not debt in this generator.
//! The authoring pillar (`roteiro spec`, ADR-0004), Tier 0: deterministic,
//! **graph-grounded** context assembly — no model, no network.
//!
//! [`context`] answers "what does the graph already know about <topic>?" by
//! searching the store for related symbols and docs and gathering each symbol's
//! neighbourhood (its container, callers/callees, and the ADRs that govern it).
//! It is the grounding an author or agent starts from before writing an ADR or
//! blueprint, so generated intent references *real* nodes rather than
//! hallucinated ones.

use std::collections::BTreeSet;

use rto_graph::{NodeSummary, Store, StoreError, explain, search};

/// Versioned schema tag for authoring outputs, so agents can depend on the shape.
pub const SPEC_SCHEMA: &str = "roteiro.spec/v1";

/// A code symbol related to the topic, with the slice of its graph neighbourhood
/// that grounds authoring: what defines it, what it calls / is called by, and the
/// authored ADRs/sections that govern it.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct SymbolContext {
    /// The symbol node.
    pub node: NodeSummary,
    /// Key of the node that `contains`/`defines` it (its file or parent), if any.
    pub container: Option<String>,
    /// Keys this symbol `calls`.
    pub calls: Vec<String>,
    /// Keys that `call` this symbol.
    pub called_by: Vec<String>,
    /// Keys of ADR/section nodes with an `authored` edge to this symbol.
    pub authored_by: Vec<String>,
}

/// Graph-grounded context for a topic: the related symbols (with neighbourhood),
/// related docs/ADRs, and the set of ADRs that govern any matched symbol.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct SpecContext {
    /// Stable schema tag ([`SPEC_SCHEMA`]).
    pub schema: &'static str,
    /// The topic that was searched.
    pub topic: String,
    /// Matched code symbols with their neighbourhood, most relevant first.
    pub symbols: Vec<SymbolContext>,
    /// Matched docs (ADRs, sections, blueprints, lat/imported docs).
    pub docs: Vec<NodeSummary>,
    /// Keys of ADR-layer nodes governing the matched symbols or matched directly.
    pub related_adrs: Vec<String>,
}

/// Node kinds treated as code symbols for authoring context.
const SYMBOL_KINDS: &[&str] = &["fn", "struct", "enum", "trait", "module"];
/// Node kinds treated as authored/imported documentation.
const DOC_KINDS: &[&str] = &["adr", "adr_section", "blueprint", "doc", "lat_section"];

/// Assemble graph-grounded [`SpecContext`] for `topic`, keeping up to `limit`
/// symbols and up to `limit` docs (most relevant first).
///
/// # Errors
/// Returns [`StoreError`] on query failure.
pub fn context(store: &Store, topic: &str, limit: usize) -> Result<SpecContext, StoreError> {
    if limit == 0 {
        return Ok(SpecContext {
            schema: SPEC_SCHEMA,
            topic: topic.to_owned(),
            symbols: Vec::new(),
            docs: Vec::new(),
            related_adrs: Vec::new(),
        });
    }
    // Over-fetch candidates so we can keep the top `limit` of each category.
    let hits = search(store, topic, limit.saturating_mul(3).max(30))?;

    let mut symbols = Vec::new();
    let mut docs = Vec::new();
    let mut related_adrs: BTreeSet<String> = BTreeSet::new();

    for hit in hits {
        let kind = hit.node.kind.as_str();
        if SYMBOL_KINDS.contains(&kind) {
            if symbols.len() >= limit {
                continue;
            }
            let Some(ex) = explain(store, &hit.node.key)? else {
                continue;
            };
            let container = ex
                .incoming
                .iter()
                .find(|e| e.kind == "contains" || e.kind == "defines")
                .map(|e| e.node.clone());
            let calls = edges_of(&ex.outgoing, "calls");
            let called_by = edges_of(&ex.incoming, "calls");
            let authored_by: Vec<String> = ex
                .incoming
                .iter()
                .filter(|e| e.provenance == "authored")
                .map(|e| e.node.clone())
                .collect();
            related_adrs.extend(authored_by.iter().cloned());
            symbols.push(SymbolContext {
                node: hit.node,
                container,
                calls,
                called_by,
                authored_by,
            });
        } else if DOC_KINDS.contains(&kind) {
            if kind == "adr" || kind == "adr_section" {
                related_adrs.insert(hit.node.key.clone());
            }
            if docs.len() < limit {
                docs.push(hit.node);
            }
        }
    }

    Ok(SpecContext {
        schema: SPEC_SCHEMA,
        topic: topic.to_owned(),
        symbols,
        docs,
        related_adrs: related_adrs.into_iter().collect(),
    })
}

/// The other-end keys of `edges` whose kind is `kind`.
fn edges_of(edges: &[rto_graph::EdgeRef], kind: &str) -> Vec<String> {
    edges
        .iter()
        .filter(|e| e.kind == kind)
        .map(|e| e.node.clone())
        .collect()
}

/// Generate a **house-style ADR skeleton** for `topic`, grounded in `ctx`:
/// correct frontmatter (id `adr_id`, `Draft`), the house section headings with
/// placeholders, a clarify **interview checklist**, and a build-plan outline. The
/// `[[…]]` links it emits — affected symbols and related ADRs — are drawn from
/// the graph, so they resolve and the scaffold is `roteiro check`-clean by
/// construction. `date` is `YYYY-MM-DD` (the caller supplies today's date).
#[must_use]
pub fn scaffold_adr(
    topic: &str,
    title: Option<&str>,
    adr_id: &str,
    date: &str,
    ctx: &SpecContext,
) -> String {
    use std::fmt::Write as _;

    let title = title.unwrap_or(topic);
    let Grounded {
        symbol_links,
        adr_links,
        files,
    } = grounded(ctx);

    let mut out = String::new();
    let _ = write!(
        out,
        "---\n\
         Title: {title}\n\
         Space: ARCH\n\
         Parent: ADRs\n\n\
         # ADR-specific metadata (unknown keys are ignored; used for indexing/search)\n\
         type: adr\n\
         adr-id: \"{adr_id}\"\n\
         status: Draft                       # Draft | For Review | Accepted | Rejected | Superseded\n\
         architectural-significance: MEDIUM  # SOFT | LOW | MEDIUM | HIGH | VERY HIGH\n\
         domain: Developer Tooling\n\
         decision-makers: [\"The Roteiro Project Team\"]\n\
         superseded-by:\n\
         version: \"0.1\"\n\
         last-modified: {date}\n\
         confluence-url:\n\
         ---\n\n\
         # ADR-{adr_id}: {title}\n\n\
         | | |\n|---|---|\n\
         | **State** | Draft |\n\
         | **Architectural Significance** | MEDIUM |\n\
         | **Domain** | Developer Tooling |\n\
         | **Document version** | 0.1 |\n\n\
         ## Reference\n\n\
         _Scaffolded by `roteiro spec` and grounded in the graph — the links below\n\
         already resolve against real nodes; fill in the prose._\n\n"
    );

    if !adr_links.is_empty() {
        let _ = writeln!(out, "Related decisions: {}.\n", adr_links.join(", "));
    }
    if !symbol_links.is_empty() {
        let _ = writeln!(out, "Affected code: {}.\n", symbol_links.join(", "));
    }

    out.push_str(
        "## Summary\n\n\
         _TODO: the decision in a sentence or two._\n\n\
         ## Context\n\n\
         _TODO: the forces at play and why a decision is needed now._\n\n\
         ## Interview — clarify before writing\n\n\
         - [ ] What problem does this solve, and who has it?\n\
         - [ ] Which existing ADRs does this relate to or supersede? (see Reference)\n\
         - [ ] Are the affected symbols above the right scope — anything missing?\n\
         - [ ] What options were considered, and why this one?\n\
         - [ ] What are the consequences, costs, and risks?\n\n\
         ## Decision makers\n\n\
         - The Roteiro Project Team\n\n\
         ## Recommended option\n\n_TODO._\n\n\
         ## Options considered + consequences\n\n_TODO._\n\n\
         ## Consequences\n\n_TODO._\n\n\
         ## Build-plan outline (grounded)\n\n",
    );

    if files.is_empty() && adr_links.is_empty() {
        out.push_str("_No related graph facts found for this topic yet._\n\n");
    } else {
        for f in &files {
            let _ = writeln!(out, "- Touches `{f}`");
        }
        if !adr_links.is_empty() {
            let _ = writeln!(out, "- Reconcile with: {}", adr_links.join(", "));
        }
        out.push('\n');
    }

    let _ = write!(
        out,
        "## Document version history\n\n\
         | Version | Date | Notes |\n\
         |---------|------|-------|\n\
         | 0.1 | {date} | Draft scaffold generated by `roteiro spec scaffold`. |\n"
    );
    out
}

/// Generate a **house-style blueprint (technical implementation plan)** skeleton
/// for `topic`, grounded in `ctx`. Blueprints have no YAML frontmatter: an
/// `— Technical Implementation Plan` H1, a grounding intro citing related ADRs
/// and affected code, a `Status` blockquote, then numbered sections (scope →
/// crate placement → design → testing → phased build order → risks) plus a
/// clarify interview. Grounded `[[…]]` links resolve against real nodes.
#[must_use]
pub fn scaffold_blueprint(topic: &str, title: Option<&str>, ctx: &SpecContext) -> String {
    use std::fmt::Write as _;

    let title = title.unwrap_or(topic);
    let Grounded {
        symbol_links,
        adr_links,
        files,
    } = grounded(ctx);

    let mut out = String::new();
    let _ = write!(
        out,
        "# {title} — Technical Implementation Plan\n\n\
         _Scaffolded by `roteiro spec` and grounded in the graph — a build plan\n\
         for {topic}. The links below resolve against real nodes; fill in the\n\
         design._\n\n"
    );
    if !adr_links.is_empty() {
        let _ = writeln!(out, "Grounded in: {}.\n", adr_links.join(", "));
    }
    if !symbol_links.is_empty() {
        let _ = writeln!(out, "Touches: {}.\n", symbol_links.join(", "));
    }

    out.push_str("> **Status.** Design → build.\n\n---\n\n");
    out.push_str(
        "## 0. What this plan covers\n\n\
         _TODO: the operator-facing surface (CLI/API) and scope._\n\n\
         ## 1. Crate placement\n\n",
    );
    if files.is_empty() {
        out.push_str("_TODO: which crates/modules this touches._\n\n");
    } else {
        for f in &files {
            let _ = writeln!(out, "- `{f}`");
        }
        out.push('\n');
    }
    out.push_str(
        "## 2. Design\n\n_TODO: the load-bearing decisions and how the pieces fit._\n\n\
         ## 3. Interview — clarify before building\n\n\
         - [ ] What is the operator-facing surface (CLI/API)?\n\
         - [ ] Which crates/modules does this touch? (see Crate placement)\n\
         - [ ] Which ADRs/decisions does it realise? (see grounding)\n\
         - [ ] What are the phases / build order?\n\
         - [ ] What are the risks and the invariants it must always satisfy?\n\n\
         ## 4. Testing\n\n_TODO._\n\n\
         ## 5. Phased build order\n\n_TODO._\n\n\
         ## 6. Risks & invariants\n\n_TODO._\n",
    );
    out
}

/// The grounded `[[…]]` links and affected files for a scaffold, drawn from the
/// graph so they resolve.
struct Grounded {
    symbol_links: Vec<String>,
    adr_links: Vec<String>,
    files: Vec<String>,
}

/// Build the grounded links from `ctx`: affected symbols as `[[path#Symbol]]`,
/// related ADRs as `[[docs/adr/…md]]`, and the deduped affected file paths.
fn grounded(ctx: &SpecContext) -> Grounded {
    let symbol_links = ctx
        .symbols
        .iter()
        .filter_map(|s| symbol_link_target(&s.node.key))
        .map(|t| format!("[[{t}]]"))
        .collect();
    let adr_links = ctx
        .docs
        .iter()
        .filter(|d| d.kind == "adr")
        .filter_map(|d| d.path.clone())
        .map(|p| format!("[[{p}]]"))
        .collect();
    let mut files: Vec<String> = ctx
        .symbols
        .iter()
        .filter_map(|s| s.node.path.clone())
        .collect();
    files.sort();
    files.dedup();
    Grounded {
        symbol_links,
        adr_links,
        files,
    }
}

/// The `path#Symbol` wiki-link target reconstructed from a `sym:<lang>:<path>#…`
/// key (dropping the `sym:<lang>:` prefix), or `None` if not a symbol key.
fn symbol_link_target(key: &str) -> Option<&str> {
    key.strip_prefix("sym:")
        .and_then(|rest| rest.split_once(':'))
        .map(|(_lang, target)| target)
}

// --- Tier 1 drafting: turn a scaffold's `_TODO_` placeholders into grounded
// generation prompts, and splice the generated prose back in. Pure and
// model-agnostic — the caller runs the prompts through whatever generator
// (a local model, or an agent) and passes the prose back to [`apply_drafts`].

/// The placeholder sections of a scaffold a generator should fill: `(heading,
/// hint)` for each `_TODO…_` line, in document order. `hint` is the guidance
/// text after `_TODO:` (empty for a bare `_TODO._`).
#[must_use]
pub fn draft_targets(scaffold_md: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut heading = String::new();
    for line in scaffold_md.lines() {
        if let Some(h) = line.strip_prefix("## ") {
            h.trim().clone_into(&mut heading);
        } else if let Some(hint) = todo_hint(line) {
            out.push((heading.clone(), hint));
        }
    }
    out
}

/// The hint of a `_TODO: hint._` (or `_TODO._`) placeholder line, else `None`.
fn todo_hint(line: &str) -> Option<String> {
    let rest = line.trim().strip_prefix("_TODO")?.strip_suffix('_')?;
    // `rest` is now `.` (bare) or `: <hint>.`; drop the leading `:`/`.`/space
    // and the trailing `.`/space.
    Some(
        rest.trim_start_matches([':', '.', ' '])
            .trim_end_matches(['.', ' '])
            .to_owned(),
    )
}

/// Build a grounded generation prompt (a plain-text user message) for the
/// `heading` section of an artifact about `topic`, using `hint` as guidance and
/// `ctx` as the real symbols/ADRs the model may reference. The prompt constrains
/// the model to the grounded facts so drafts stay honest.
#[must_use]
pub fn draft_prompt(topic: &str, ctx: &SpecContext, heading: &str, hint: &str) -> String {
    use std::fmt::Write as _;

    let mut p = String::new();
    let _ = write!(
        p,
        "You are drafting the \"{heading}\" section of a house-style technical \
         document about \"{topic}\" for the Roteiro project (a provenance-tagged \
         codebase knowledge graph). "
    );
    if !hint.is_empty() {
        let _ = write!(p, "Focus: {hint}. ");
    }
    let symbols: Vec<&str> = ctx.symbols.iter().map(|s| s.node.name.as_str()).collect();
    if !symbols.is_empty() {
        let _ = write!(p, "Relevant code symbols: {}. ", symbols.join(", "));
    }
    if !ctx.related_adrs.is_empty() {
        let _ = write!(p, "Related decisions: {}. ", ctx.related_adrs.join(", "));
    }
    p.push_str(
        "Write 2–4 precise, technical sentences. Reference the real symbols above \
         where relevant; do not invent symbols, files, or facts. Output only the \
         prose, no heading.",
    );
    p
}

/// Splice generated prose back into a scaffold: each `_TODO…_` line under a
/// heading present in `drafts` (as `(heading, prose)`) is replaced by that prose.
/// Headings without a draft, and all other lines, are left unchanged.
#[must_use]
pub fn apply_drafts(scaffold_md: &str, drafts: &[(String, String)]) -> String {
    let by_heading: std::collections::BTreeMap<&str, &str> = drafts
        .iter()
        .map(|(h, prose)| (h.as_str(), prose.as_str()))
        .collect();
    let mut out = String::new();
    let mut heading = "";
    for line in scaffold_md.lines() {
        if let Some(h) = line.strip_prefix("## ") {
            heading = h.trim();
        } else if todo_hint(line).is_some()
            && let Some(prose) = by_heading.get(heading)
        {
            out.push_str(prose);
            out.push('\n');
            continue;
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{SPEC_SCHEMA, context};
    use rto_graph::{Edge, EdgeKind, FactSet, Node, NodeKind, Store};

    fn seeded() -> Store {
        let mut store = Store::open_in_memory().expect("store");
        let facts = FactSet::new()
            .with_node(Node::new("file:src/auth.rs", NodeKind::File, "auth.rs"))
            .with_node(Node {
                path: Some("src/auth.rs".to_owned()),
                ..Node::new(
                    "sym:rust:src/auth.rs#validate_token",
                    NodeKind::Fn,
                    "validate_token",
                )
            })
            .with_node(Node::new(
                "sym:rust:src/auth.rs#login",
                NodeKind::Fn,
                "login",
            ))
            .with_node(Node::new(
                "adr:0007",
                NodeKind::Adr,
                "Authentication design",
            ))
            // Structure + calls + an authored ADR link into validate_token.
            .with_edge(Edge::derived(
                "file:src/auth.rs",
                "sym:rust:src/auth.rs#validate_token",
                EdgeKind::Defines,
            ))
            .with_edge(Edge::derived(
                "sym:rust:src/auth.rs#login",
                "sym:rust:src/auth.rs#validate_token",
                EdgeKind::Calls,
            ))
            .with_edge(Edge::authored(
                "adr:0007",
                "sym:rust:src/auth.rs#validate_token",
                EdgeKind::References,
            ));
        store.apply_factset(&facts).expect("apply");
        store
    }

    #[test]
    fn context_grounds_a_symbol_in_its_neighbourhood() {
        let store = seeded();
        let ctx = context(&store, "validate_token", 10).expect("context");
        assert_eq!(ctx.schema, SPEC_SCHEMA);

        let sym = ctx
            .symbols
            .iter()
            .find(|s| s.node.key == "sym:rust:src/auth.rs#validate_token")
            .expect("the symbol");
        assert_eq!(sym.container.as_deref(), Some("file:src/auth.rs"));
        assert_eq!(sym.called_by, vec!["sym:rust:src/auth.rs#login"]);
        assert_eq!(sym.authored_by, vec!["adr:0007"]);
        // The governing ADR is surfaced as related.
        assert!(ctx.related_adrs.contains(&"adr:0007".to_owned()));
    }

    #[test]
    fn context_finds_related_docs_by_topic() {
        let store = seeded();
        // "authentication" matches the ADR's name.
        let ctx = context(&store, "authentication", 10).expect("context");
        assert!(
            ctx.docs.iter().any(|d| d.key == "adr:0007"),
            "the ADR should be a related doc: {:?}",
            ctx.docs
        );
        assert!(ctx.related_adrs.contains(&"adr:0007".to_owned()));
    }

    #[test]
    fn empty_topic_yields_empty_context() {
        let store = seeded();
        let ctx = context(&store, "   ", 10).expect("context");
        assert!(ctx.symbols.is_empty() && ctx.docs.is_empty());
    }

    #[test]
    fn scaffold_is_grounded_and_check_clean() {
        use super::scaffold_adr;
        let mut store = seeded();
        let ctx = context(&store, "validate_token", 10).expect("context");
        let md = scaffold_adr(
            "validate_token",
            Some("Token validation"),
            "0099",
            "2026-08-09",
            &ctx,
        );

        // House frontmatter + title with the given id.
        assert!(md.contains("adr-id: \"0099\""), "{md}");
        assert!(md.contains("# ADR-0099: Token validation"));
        // Grounded affected-code link and the interview checklist.
        assert!(
            md.contains("[[src/auth.rs#validate_token]]"),
            "grounded link: {md}"
        );
        assert!(md.contains("- [ ] What problem does this solve"));

        // It parses as a house ADR and its links resolve to a real node — so it
        // is `check`-clean by construction.
        let doc = crate::parse_adr("docs/adr/0099-token-validation.md", &md).expect("parse");
        assert!(
            doc.links
                .iter()
                .any(|l| l.target_key == "sym:rust:src/auth.rs#validate_token"),
            "the scaffold's link must resolve to the real symbol: {:?}",
            doc.links,
        );
        let report = crate::run(&mut store, std::slice::from_ref(&doc), &[], &[]).expect("check");
        assert_eq!(
            report.violations.len(),
            0,
            "scaffold must be check-clean: {:?}",
            report.violations
        );
    }

    #[test]
    fn scaffold_has_no_code_block_indentation() {
        use super::{scaffold_adr, scaffold_blueprint};
        let store = seeded();
        let ctx = context(&store, "validate_token", 10).expect("context");
        // The `\`-line-continuations in the templates strip source indentation, so
        // no line begins with whitespace; a 4-space indent would (wrongly) render
        // the frontmatter/headings as a CommonMark code block.
        let adr = scaffold_adr("validate_token", None, "0099", "2026-08-09", &ctx);
        let blueprint = scaffold_blueprint("validate_token", None, &ctx);
        for md in [&adr, &blueprint] {
            for (i, line) in md.lines().enumerate() {
                assert!(
                    !line.starts_with(' ') && !line.starts_with('\t'),
                    "line {} has leading whitespace: {line:?}",
                    i + 1
                );
            }
        }
    }

    #[test]
    fn draft_round_trip_fills_todo_sections() {
        use super::{apply_drafts, draft_prompt, draft_targets, scaffold_adr};
        let store = seeded();
        let ctx = context(&store, "validate_token", 10).expect("context");
        let scaffold = scaffold_adr("validate_token", None, "0099", "2026-08-09", &ctx);

        // Targets: every `## Heading` with a `_TODO…_` placeholder.
        let targets = draft_targets(&scaffold);
        assert!(targets.iter().any(|(h, _)| h == "Summary"));
        assert!(targets.iter().any(|(h, _)| h == "Context"));

        // A grounded prompt names the real symbol and forbids invention.
        let prompt = draft_prompt("validate_token", &ctx, "Summary", "the decision");
        assert!(prompt.contains("validate_token"), "{prompt}");
        assert!(prompt.contains("do not invent"));

        // A mock generator fills each target; apply_drafts splices the prose in
        // and the `_TODO_` placeholders for drafted sections are gone.
        let drafts: Vec<(String, String)> = targets
            .iter()
            .map(|(h, _)| (h.clone(), format!("Drafted prose for {h}.")))
            .collect();
        let filled = apply_drafts(&scaffold, &drafts);
        assert!(filled.contains("Drafted prose for Summary."));
        assert!(
            !filled.contains("_TODO: the decision"),
            "placeholder replaced: {filled}"
        );
        // Structure is preserved (headings still present).
        assert!(filled.contains("## Summary") && filled.contains("## Context"));
    }

    #[test]
    fn blueprint_is_grounded_and_house_style() {
        use super::scaffold_blueprint;
        let store = seeded();
        let ctx = context(&store, "validate_token", 10).expect("context");
        let md = scaffold_blueprint("validate_token", Some("Token flow"), &ctx);

        // House blueprint shape: no YAML frontmatter, the `— Technical
        // Implementation Plan` H1, a Status blockquote, numbered sections.
        assert!(
            md.starts_with("# Token flow — Technical Implementation Plan"),
            "{md}"
        );
        assert!(
            !md.contains("---\nTitle:"),
            "blueprints have no frontmatter"
        );
        assert!(md.contains("> **Status.** Design → build."));
        assert!(md.contains("## 1. Crate placement"));
        // Grounded: the affected code is linked and its file is listed.
        assert!(
            md.contains("[[src/auth.rs#validate_token]]"),
            "grounded link: {md}"
        );
        assert!(md.contains("`src/auth.rs`"), "affected file listed: {md}");
        assert!(md.contains("- [ ] What is the operator-facing surface"));
    }
}