Skip to main content

mira/
rca.rs

1//! The incident write-up, as a tool.
2//!
3//! `render_rca` is the ninth MCP tool and the only one that takes more than it
4//! gives back: structured fields in, one markdown document out. It is here
5//! because the last mile of an incident is not a query. It is the write-up, and
6//! an agent left to format that itself produces a different document every
7//! time, with the evidence inlined as prose that nobody can re-run.
8//!
9//! # Two things make this more than a template
10//!
11//! Every evidence item carries a citation — a trace id or a query document —
12//! and [`Rca::render`] cannot be called until every one of them has been re-run
13//! against the store. A citation that returns nothing is an error naming it,
14//! not a footnote: an RCA whose evidence has aged out of retention reads
15//! exactly like one whose evidence was invented, and telling those apart is
16//! most of what the document is worth.
17//!
18//! The other is `prevention`. The alerting rule the write-up proposes is parsed
19//! by the same [`crate::alert::rule`] that loads `alerts.kyaml`, so what comes
20//! back in the fence is a rule that will load rather than one that looks like
21//! it would. That is the fourth reading of principle 2 — self-tuning — reduced
22//! to the only mechanism that is honest about it: the incident emits the rule
23//! that would have caught it.
24//!
25//! # It still does not act
26//!
27//! Nothing in this file changes anything outside Mira, and there is no
28//! counterpart to it that does. The remediation section is text for whoever is
29//! on call, and [`Rca::render`] says so in the document's own body. Mira
30//! supplies evidence; the fixing is done elsewhere, with tools that were built
31//! for it (architecture section 14).
32
33use yaml_rust2::Yaml;
34
35use mira_core::json::Json;
36use mira_core::query::{Op, Search, Signal, Target, Term, Value};
37
38use crate::api;
39
40/// The citation could not be checked at all, as opposed to checked and empty.
41/// Rendered the same way in the error, because both mean "do not publish this".
42const UNREADABLE: usize = usize::MAX;
43
44/// A parsed, not-yet-verified write-up.
45///
46/// Nothing here is rendered until [`verified`](Rca::verified) is true, which is
47/// the type-level half of the promise the module header makes.
48#[derive(Debug)]
49pub(crate) struct Rca {
50    title: String,
51    from: i64,
52    to: i64,
53    summary: String,
54    impact: Vec<String>,
55    /// Sorted by time at parse, because a timeline given out of order is the
56    /// one defect in this document that a reader will believe rather than
57    /// notice.
58    timeline: Vec<(i64, String)>,
59    root_cause: String,
60    pub(crate) evidence: Vec<Fact>,
61    ruled_out: Vec<String>,
62    contributing: Vec<String>,
63    remediation: Vec<String>,
64    verification: Vec<String>,
65    /// An `alerts.kyaml` fragment, already through the rule parser.
66    prevention: Option<String>,
67    pub(crate) emit: bool,
68}
69
70/// One cited claim.
71#[derive(Debug)]
72pub(crate) struct Fact {
73    claim: String,
74    /// What to re-run. Never absent: an assertion Mira cannot check belongs in
75    /// `summary` or `root_cause`, which is where the document puts the parts
76    /// that are judgement.
77    pub(crate) cite: Search,
78    /// How the citation reads in the rendered document.
79    shown: String,
80    /// What re-running it found. `None` until the verification pass has been
81    /// through.
82    pub(crate) found: Option<usize>,
83}
84
85impl Fact {
86    pub(crate) fn seen(&mut self, rows: Option<usize>) {
87        self.found = Some(rows.unwrap_or(UNREADABLE));
88    }
89}
90
91/// `{"trace_id": ...}` as a query.
92///
93/// Shared with `mcp::trace_search` so that the id a write-up cites and
94/// the id `get_trace` accepts cannot drift into two different notions of
95/// well-formed. The window is all of retention for the same reason it is there:
96/// you look a trace up because you do not know when it happened.
97pub(crate) fn trace_query(id: &str, limit: usize) -> Result<Search, String> {
98    let id = id.trim();
99    if mira_core::query::unhex(id).is_none_or(|b| b.len() != 16) {
100        return Err(format!("{id:?} is not a 16-byte hex trace id"));
101    }
102    Ok(Search {
103        signal: Signal::Traces,
104        from: 0,
105        to: i64::MAX,
106        terms: vec![Term {
107            target: Target::Field("trace_id".into()),
108            op: Op::Eq,
109            value: Value::Str(id.to_owned()),
110        }],
111        limit,
112        after: None,
113        cursors: false,
114    })
115}
116
117/// Parse a `render_rca` argument document.
118pub(crate) fn doc(args: &Yaml, now: i64) -> Result<Rca, String> {
119    api::known(
120        args,
121        &[
122            "title",
123            "from",
124            "to",
125            "summary",
126            "impact",
127            "timeline",
128            "root_cause",
129            "evidence",
130            "ruled_out",
131            "contributing",
132            "remediation",
133            "verification",
134            "prevention",
135            "emit",
136        ],
137    )?;
138    let (from, to) = api::bounds(args, now)?;
139    let mut timeline = Vec::new();
140    for e in list(args, "timeline")? {
141        api::known(e, &["at", "what"])?;
142        let at = api::time_field(&e["at"], now, i64::MIN)?;
143        if at == i64::MIN {
144            return Err("each timeline entry needs `at`, as '-15m' or nanoseconds".into());
145        }
146        timeline.push((at, text(e, "what", "a timeline entry")?));
147    }
148    timeline.sort_by_key(|(at, _)| *at);
149
150    let mut evidence = Vec::new();
151    for e in list(args, "evidence")? {
152        evidence.push(fact(e, now, from, to)?);
153    }
154
155    // Parsed through the loader rather than pattern-matched, so the fence in
156    // the document is a rule the operator can paste into `alerts.kyaml` and
157    // restart on. `&[]` is the target list: a rendered rule may not name a
158    // webhook, because the webhooks are in the operator's file and this process
159    // has no idea what they are called.
160    let prevention = match &args["prevention"] {
161        Yaml::BadValue | Yaml::Null => None,
162        y => {
163            crate::alert::rule(y, &[]).map_err(|e| format!("prevention: {e}"))?;
164            Some(kyaml(y))
165        }
166    };
167
168    Ok(Rca {
169        title: text(args, "title", "an RCA")?,
170        from,
171        to,
172        summary: text(args, "summary", "an RCA")?,
173        impact: strings(args, "impact")?,
174        timeline,
175        root_cause: text(args, "root_cause", "an RCA")?,
176        evidence,
177        ruled_out: strings(args, "ruled_out")?,
178        contributing: strings(args, "contributing")?,
179        remediation: strings(args, "remediation")?,
180        verification: strings(args, "verification")?,
181        prevention,
182        emit: flag(args, "emit")?,
183    })
184}
185
186fn fact(y: &Yaml, now: i64, from: i64, to: i64) -> Result<Fact, String> {
187    api::known(y, &["claim", "trace_id", "query"])?;
188    let claim = text(y, "claim", "an evidence item")?;
189    let empty = |v: &Yaml| matches!(v, Yaml::BadValue | Yaml::Null);
190    let (mut cite, shown) = match (&y["trace_id"], &y["query"]) {
191        (t, q) if empty(t) && empty(q) => {
192            return Err(format!(
193                "evidence {claim:?} cites nothing: give it `trace_id` or `query`. \
194                 A claim Mira cannot re-run is not evidence — put it in `root_cause` \
195                 or `contributing` instead."
196            ));
197        }
198        (t, q) if !empty(t) && !empty(q) => {
199            return Err(format!(
200                "evidence {claim:?} cites both `trace_id` and `query`; pick one"
201            ));
202        }
203        (t, _) if !empty(t) => {
204            let id = t.as_str().ok_or("`trace_id` must be a quoted string")?;
205            (trace_query(id, 0)?, format!("trace `{}`", id.trim()))
206        }
207        (_, q) => {
208            let mut s = api::search_doc(q, now)?;
209            // A citation with no window of its own is a citation about the
210            // incident, not about the last hour. Without this, a write-up of
211            // something that happened this morning verifies against a window
212            // that does not contain it and every query citation comes back
213            // dead — which reads as "the agent made it up".
214            if empty(&q["from"]) && empty(&q["to"]) {
215                (s.from, s.to) = (from, to);
216            }
217            let shown = match filter(&s.terms) {
218                f if f.is_empty() => format!("all {}", s.signal.dir()),
219                f => format!("{} where `{f}`", s.signal.dir()),
220            };
221            (s, shown)
222        }
223    };
224    // Counting is free and reading is not: this pass asks whether the evidence
225    // is still there, not what it says. Same trick `alert::Engine` uses.
226    cite.limit = 0;
227    Ok(Fact {
228        claim,
229        cite,
230        shown,
231        found: None,
232    })
233}
234
235impl Rca {
236    /// True once every citation has been re-run.
237    pub(crate) fn verified(&self) -> bool {
238        self.evidence.iter().all(|f| f.found.is_some())
239    }
240
241    /// The citations that came back empty or unreadable, as one message.
242    ///
243    /// Returned instead of the document rather than alongside it. A markdown
244    /// RCA is a thing people paste into a ticket, and handing one back with a
245    /// warning above it is handing back a document that will be pasted without
246    /// the warning.
247    pub(crate) fn dead(&self) -> Option<String> {
248        let dead: Vec<&Fact> = self
249            .evidence
250            .iter()
251            .filter(|f| matches!(f.found, Some(0) | Some(UNREADABLE) | None))
252            .collect();
253        if dead.is_empty() {
254            return None;
255        }
256        let mut out = format!(
257            "nothing was rendered and nothing was stored: {} of {} citations do not \
258             hold against this store.\n",
259            dead.len(),
260            self.evidence.len()
261        );
262        for f in dead {
263            let why = match f.found {
264                Some(UNREADABLE) | None => "could not be read",
265                _ => "matches no records",
266            };
267            out.push_str(&format!("  - {} ({}) {why}\n", f.claim, f.shown));
268        }
269        out.push_str(
270            "Widen the window, fix the filter, or drop the claim — but do not publish \
271             a write-up citing evidence this node cannot produce.",
272        );
273        Some(out)
274    }
275
276    /// The document.
277    ///
278    /// # Panics
279    ///
280    /// If a citation has not been re-run. Callers go through
281    /// [`dead`](Rca::dead) first, which is only meaningful after the same pass.
282    pub(crate) fn render(&self) -> String {
283        assert!(self.verified(), "render before the citations were checked");
284        let mut m = String::new();
285        m.push_str(&format!("# {}\n\n", self.title));
286        m.push_str(&format!(
287            "*{} → {} ({}). Written by an agent against Mira; every citation below was \
288             re-run at render time and returned the record count beside it.*\n\n",
289            utc(self.from),
290            utc(self.to),
291            span(self.to - self.from)
292        ));
293
294        m.push_str("## Summary\n\n");
295        m.push_str(&self.summary);
296        m.push_str("\n\n");
297        bullets(&mut m, "Impact", &self.impact);
298
299        if !self.timeline.is_empty() {
300            m.push_str("## Timeline\n\n| When (UTC) | What |\n| --- | --- |\n");
301            for (at, what) in &self.timeline {
302                m.push_str(&format!("| {} | {} |\n", utc(*at), cell(what)));
303            }
304            m.push('\n');
305        }
306
307        m.push_str("## Root cause\n\n");
308        m.push_str(&self.root_cause);
309        m.push_str("\n\n");
310
311        if !self.evidence.is_empty() {
312            m.push_str("## Evidence\n\n");
313            for f in &self.evidence {
314                // One line per claim, no nesting and no raw HTML. An RCA gets
315                // pasted into whatever the team uses, and a two-line bullet is
316                // the first thing a renderer that is not GitHub gets wrong.
317                m.push_str(&format!(
318                    "- {} — {}, {} records\n",
319                    f.claim,
320                    f.shown,
321                    f.found.unwrap_or_default()
322                ));
323            }
324            m.push('\n');
325        }
326
327        bullets(&mut m, "Ruled out", &self.ruled_out);
328        bullets(&mut m, "Contributing factors", &self.contributing);
329        if !self.remediation.is_empty() {
330            bullets(&mut m, "Remediation", &self.remediation);
331            // In the document, not only in this repository's docs. Whoever
332            // reads the RCA is the one who needs to know that none of the above
333            // has happened yet.
334            m.push_str(
335                "> Mira did not apply any of this and cannot: it has no verb that \
336                 changes a cluster.\n\n",
337            );
338        }
339        bullets(&mut m, "Verification", &self.verification);
340
341        if let Some(rule) = &self.prevention {
342            m.push_str(
343                "## Prevention\n\nThe rule that would have caught this, ready for \
344                 `alerts.kyaml` — add your own `notify` targets:\n\n```yaml\nrules:\n  - ",
345            );
346            // The fragment is rendered at zero indent; inside the list it needs
347            // four spaces on every line but the first, which the `- ` above
348            // already carries.
349            m.push_str(&rule.replace('\n', "\n    "));
350            m.push_str("\n```\n\n");
351        }
352        m
353    }
354
355    /// The write-up as an OTLP log export, for `emit`.
356    ///
357    /// A log record and not a new kind of object, which is the whole reason
358    /// this is affordable: an RCA is then searchable by `query_records`, framed
359    /// by `correlate`, and expired by the same retention as the telemetry it
360    /// describes. There is no incident store, no index to maintain and no
361    /// second thing to back up (principle 4).
362    pub(crate) fn export(
363        &self,
364        md: &str,
365        now: i64,
366    ) -> mira_proto::collector::logs::v1::ExportLogsServiceRequest {
367        use mira_proto::collector::logs::v1::ExportLogsServiceRequest;
368        use mira_proto::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value};
369        use mira_proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
370        use mira_proto::resource::v1::Resource;
371
372        let kv = |k: &str, v: String| KeyValue {
373            key: k.into(),
374            value: Some(AnyValue {
375                value: Some(any_value::Value::StringValue(v)),
376            }),
377        };
378        ExportLogsServiceRequest {
379            resource_logs: vec![ResourceLogs {
380                resource: Some(Resource {
381                    // `service.name` is this node, because this node is what
382                    // produced the record. Naming the *subject* service here
383                    // would file the write-up under that service's entity key
384                    // and put a document in the middle of its logs — see the
385                    // identity ladder in `mira_core::identity`.
386                    attributes: vec![kv("service.name", "mira".into())],
387                    ..Default::default()
388                }),
389                scope_logs: vec![ScopeLogs {
390                    scope: Some(InstrumentationScope {
391                        name: "mira.rca".into(),
392                        ..Default::default()
393                    }),
394                    log_records: vec![LogRecord {
395                        time_unix_nano: now.max(0) as u64,
396                        // INFO. An RCA is a document about an incident, not an
397                        // incident: filed at ERROR it would show up in every
398                        // "show me the errors" query for the rest of retention.
399                        severity_number: 9,
400                        severity_text: "INFO".into(),
401                        event_name: "rca".into(),
402                        body: Some(AnyValue {
403                            value: Some(any_value::Value::StringValue(md.to_owned())),
404                        }),
405                        attributes: vec![
406                            kv("rca.title", self.title.clone()),
407                            kv("rca.window.from", utc(self.from)),
408                            kv("rca.window.to", utc(self.to)),
409                        ],
410                        ..Default::default()
411                    }],
412                    ..Default::default()
413                }],
414                ..Default::default()
415            }],
416        }
417    }
418}
419
420fn bullets(m: &mut String, heading: &str, items: &[String]) {
421    if items.is_empty() {
422        return;
423    }
424    m.push_str(&format!("## {heading}\n\n"));
425    for i in items {
426        m.push_str(&format!("- {i}\n"));
427    }
428    m.push('\n');
429}
430
431/// A pipe inside a table cell ends the cell. Nothing else in GitHub-flavoured
432/// markdown can break a row, and a newline cannot arrive here — KYAML scalars
433/// keep theirs, so they are turned into spaces rather than escaped.
434fn cell(s: &str) -> String {
435    s.replace('|', "\\|").replace('\n', " ")
436}
437
438/// A required, quoted scalar.
439fn text(doc: &Yaml, key: &str, what: &str) -> Result<String, String> {
440    doc[key]
441        .as_str()
442        .map(str::to_owned)
443        .ok_or(format!("{what} needs a quoted `{key}`"))
444}
445
446/// An optional list of quoted scalars. Absent is empty; a bare string is not a
447/// list of one, because a model that wrote one bullet meant to write a list.
448fn strings(doc: &Yaml, key: &str) -> Result<Vec<String>, String> {
449    list(doc, key)?
450        .iter()
451        .map(|y| {
452            y.as_str()
453                .map(str::to_owned)
454                .ok_or(format!("every entry of `{key}` must be a quoted string"))
455        })
456        .collect()
457}
458
459fn list<'a>(doc: &'a Yaml, key: &str) -> Result<&'a [Yaml], String> {
460    match &doc[key] {
461        Yaml::BadValue | Yaml::Null => Ok(&[]),
462        Yaml::Array(a) => Ok(a),
463        _ => Err(format!("`{key}` must be a list")),
464    }
465}
466
467fn flag(doc: &Yaml, key: &str) -> Result<bool, String> {
468    match &doc[key] {
469        Yaml::BadValue | Yaml::Null => Ok(false),
470        Yaml::Boolean(b) => Ok(*b),
471        y => y
472            .as_str()
473            .and_then(|s| s.parse().ok())
474            .ok_or(format!("{key}: expected \"true\" or \"false\"")),
475    }
476}
477
478/// Terms in the filter-bar grammar, so a reader can paste the citation into
479/// Mira's UI. The same spelling `alert::filter_of` puts in a page.
480fn filter(terms: &[Term]) -> String {
481    crate::alert::filter_of(terms)
482}
483
484/// UTC, RFC 3339, to the second.
485///
486/// `tui::stamp` is local time, which is right on a terminal someone is sitting
487/// at and wrong in a document that gets pasted into a ticket and read from
488/// another timezone — where an unqualified `09:41` is a bug report about the
489/// wrong hour. `gmtime_r` for the same reason `tui` uses `localtime_r`: libc is
490/// already here and the calendar is the part a hand-rolled version gets wrong.
491fn utc(ns: i64) -> String {
492    let secs = ns.div_euclid(1_000_000_000) as libc::time_t;
493    // SAFETY: identical to `tui::civil` — `tm` is integers plus a `tm_zone`
494    // pointer, for which all-zero is valid, and `gmtime_r` writes only into the
495    // local it is handed. A `time_t` it cannot represent leaves the zeroes,
496    // which render as 1900-01-01: a wrong date, not uninitialised memory.
497    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
498    // SAFETY: both arguments are live, correctly typed locals, and the `_r`
499    // form writes only into `tm`.
500    unsafe { libc::gmtime_r(&secs, &mut tm) };
501    format!(
502        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
503        tm.tm_year + 1900,
504        tm.tm_mon + 1,
505        tm.tm_mday,
506        tm.tm_hour,
507        tm.tm_min,
508        tm.tm_sec
509    )
510}
511
512/// A window length, for the line under the title.
513fn span(ns: i64) -> String {
514    match ns.max(0) / 1_000_000_000 {
515        s if s >= 86_400 => format!("{}d{}h", s / 86_400, s % 86_400 / 3_600),
516        s if s >= 3_600 => format!("{}h{:02}m", s / 3_600, s % 3_600 / 60),
517        s if s >= 60 => format!("{}m{:02}s", s / 60, s % 60),
518        s => format!("{s}s"),
519    }
520}
521
522/// A `Yaml` node back out as KYAML.
523///
524/// yaml-rust2 ships an emitter and it is the wrong one: it writes plain
525/// scalars, and this text goes into an `alerts.kyaml`. JSON is the quoted
526/// subset of KYAML (principle 5), so writing JSON is writing KYAML — and it is
527/// the spelling that keeps `{"gt": 500000000}` a number, which quoting every
528/// scalar alike would not.
529fn kyaml(y: &Yaml) -> String {
530    match y.as_hash() {
531        // One top-level key per line, values compact. All-compact is valid and
532        // unreadable — this is the one fragment in the document somebody edits
533        // by hand — and pretty-printing the nested `where` would be a YAML
534        // emitter, which is the thing this function exists to not be.
535        Some(h) => h
536            .iter()
537            .map(|(k, v)| format!("{}: {}", one(k), one(v)))
538            .collect::<Vec<_>>()
539            .join("\n"),
540        None => one(y),
541    }
542}
543
544fn one(y: &Yaml) -> String {
545    let mut j = Json::new();
546    write(y, &mut j);
547    j.into_string()
548}
549
550fn write(y: &Yaml, j: &mut Json) {
551    match y {
552        Yaml::Hash(h) => j.obj(|j| {
553            for (k, v) in h {
554                j.key(k.as_str().unwrap_or_default());
555                write(v, j);
556            }
557        }),
558        Yaml::Array(a) => j.arr(|j| {
559            for v in a {
560                write(v, j);
561            }
562        }),
563        Yaml::String(s) => j.str(s),
564        Yaml::Integer(n) => j.i64(*n),
565        Yaml::Boolean(b) => j.bool(*b),
566        Yaml::Real(r) => j.f64(r.parse().unwrap_or_default()),
567        _ => j.null(),
568    }
569}
570
571#[cfg(test)]
572mod tests {
573    use super::*;
574
575    fn parse(s: &str) -> Yaml {
576        api::parse(s).unwrap()
577    }
578
579    /// 2026-09-19T10:00:00Z.
580    const T: i64 = 1_789_812_000_000_000_000;
581
582    /// The one guarantee that separates this from a prompt asking for markdown:
583    /// a claim with nowhere to check it is refused at parse, and a claim whose
584    /// citation came back empty is refused at render. Both have to be errors the
585    /// model can act on, so both name the claim.
586    #[test]
587    fn a_claim_mira_cannot_re_run_is_not_evidence() {
588        let base = r#"{"title":"t","summary":"s","root_cause":"r","#;
589        let uncited = doc(
590            &parse(&format!(
591                r#"{base}"evidence":[{{"claim":"the pods were fine"}}]}}"#
592            )),
593            T,
594        )
595        .unwrap_err();
596        assert!(uncited.contains("cites nothing"), "{uncited}");
597        assert!(uncited.contains("the pods were fine"), "{uncited}");
598        assert!(uncited.contains("root_cause"), "{uncited}");
599
600        let both = doc(
601            &parse(&format!(
602                r#"{base}"evidence":[{{"claim":"c","query":{{}},
603                   "trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}}]}}"#
604            )),
605            T,
606        )
607        .unwrap_err();
608        assert!(both.contains("pick one"), "{both}");
609
610        // Checked and empty, and never checked at all, are both "do not
611        // publish" — a citation the store could not read is not a citation that
612        // held.
613        let mut r = doc(
614            &parse(&format!(
615                r#"{base}"evidence":[
616                   {{"claim":"checkout 5xx","query":{{"where":[{{"attr":"service.name","eq":"checkout"}}]}}}},
617                   {{"claim":"one bad trace","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}}]}}"#
618            )),
619            T,
620        )
621        .unwrap();
622        assert!(!r.verified());
623        r.evidence[0].seen(Some(0));
624        r.evidence[1].seen(None);
625        assert!(r.verified());
626        let dead = r.dead().unwrap();
627        assert!(dead.contains("2 of 2"), "{dead}");
628        assert!(dead.contains("matches no records"), "{dead}");
629        assert!(dead.contains("could not be read"), "{dead}");
630        // The citation is echoed in the grammar the UI's filter bar takes, so
631        // the reader can check it by hand.
632        assert!(dead.contains("attr:service.name=checkout"), "{dead}");
633        assert!(dead.contains("nothing was stored"), "{dead}");
634
635        r.evidence[0].seen(Some(12));
636        r.evidence[1].seen(Some(1));
637        assert!(r.dead().is_none());
638    }
639
640    /// A citation with no window of its own is about the incident, not about
641    /// the last hour — otherwise every write-up of something that happened this
642    /// morning fails its own verification. A citation that *does* name a window
643    /// keeps it.
644    #[test]
645    fn a_citation_inherits_the_incidents_window_unless_it_names_one() {
646        let r = doc(
647            &parse(
648                r#"{"title":"t","summary":"s","root_cause":"r",
649                    "from":"-6h","to":"-5h","evidence":[
650                      {"claim":"a","query":{}},
651                      {"claim":"b","query":{"from":"-30m"}}]}"#,
652            ),
653            T,
654        )
655        .unwrap();
656        assert_eq!(
657            (r.evidence[0].cite.from, r.evidence[0].cite.to),
658            (r.from, r.to)
659        );
660        assert_eq!(r.from, T - 6 * 3_600_000_000_000);
661        assert_eq!(r.evidence[1].cite.from, T - 30 * 60_000_000_000);
662        // Counting is free, reading is not: verification never materialises a
663        // row, whichever form the citation took.
664        assert!(r.evidence.iter().all(|f| f.cite.limit == 0));
665        // A trace citation is the whole of retention, because you look a trace
666        // up when you do not know when it happened.
667        let t = doc(
668            &parse(
669                r#"{"title":"t","summary":"s","root_cause":"r","evidence":[
670                    {"claim":"a","trace_id":" 4BF92F3577B34DA6A3CE929D0E0E4736 "}]}"#,
671            ),
672            T,
673        )
674        .unwrap();
675        assert_eq!(
676            (t.evidence[0].cite.from, t.evidence[0].cite.to),
677            (0, i64::MAX)
678        );
679        assert_eq!(t.evidence[0].cite.signal, Signal::Traces);
680
681        let bad = doc(
682            &parse(
683                r#"{"title":"t","summary":"s","root_cause":"r","evidence":[
684                    {"claim":"a","trace_id":"0102030405060708"}]}"#,
685            ),
686            T,
687        )
688        .unwrap_err();
689        assert!(bad.contains("16-byte"), "{bad}");
690    }
691
692    /// The prevention rule goes through the loader, so what the document
693    /// promises is a rule that will start — not one that looks like it would.
694    /// And it comes back as KYAML, because that is the file it is destined for.
695    #[test]
696    fn a_proposed_rule_is_one_the_alert_loader_accepts() {
697        let with = |rule: &str| {
698            doc(
699                &parse(&format!(
700                    r#"{{"title":"t","summary":"s","root_cause":"r","prevention":{rule}}}"#
701                )),
702                T,
703            )
704        };
705        let good = with(
706            r#"{"name":"checkout-5xx","over":"5m","for":"2m","when":"count > 20",
707                "query":{"signal":"logs","where":[{"attr":"service.name","eq":"checkout"},
708                                                  {"field":"severity_number","gte":17}]}}"#,
709        )
710        .unwrap();
711        let md = {
712            let mut g = good;
713            g.evidence.clear();
714            g.render()
715        };
716        assert!(md.contains("```yaml\nrules:\n  - \"name\""), "{md}");
717        // Quoted keys and quoted strings, and 17 still a number: quoting every
718        // scalar alike would turn the severity comparison into a string
719        // comparison.
720        assert!(md.contains(r#""name": "checkout-5xx""#), "{md}");
721        assert!(md.contains(r#""gte":17"#), "{md}");
722
723        // A window in the rule's query is the loader's error, not this file's,
724        // and it arrives at render time rather than at 3am.
725        let windowed =
726            with(r#"{"name":"r","when":"count > 1","query":{"signal":"logs","from":"-1h"}}"#)
727                .unwrap_err();
728        assert!(windowed.contains("prevention:"), "{windowed}");
729        assert!(windowed.contains("over"), "{windowed}");
730
731        let typo =
732            with(r#"{"name":"r","when":"count > 1","query":{},"notify":["oncall"]}"#).unwrap_err();
733        assert!(typo.contains("prevention:"), "{typo}");
734    }
735
736    /// The document itself: UTC because it leaves this machine, the timeline
737    /// sorted because a reader believes the order, and the remediation section
738    /// carrying the sentence that says none of it has happened.
739    #[test]
740    fn the_rendered_document_is_timezone_free_ordered_and_honest_about_what_it_did() {
741        let mut r = doc(
742            &parse(
743                r#"{"title":"Checkout 5xx","summary":"Checkout returned 502 for 31 minutes.",
744                    "from":1789812000000000000,"to":1789813860000000000,
745                    "impact":["4,102 requests failed"],
746                    "timeline":[{"at":1789813800000000000,"what":"rollback | complete"},
747                                {"at":1789812060000000000,"what":"first 502"}],
748                    "root_cause":"The 1.4.0 image raised the pool ceiling.",
749                    "evidence":[{"claim":"the pool was exhausted",
750                                 "query":{"where":[{"attr":"service.name","eq":"checkout"}]}}],
751                    "ruled_out":["Not the database: no slow queries."],
752                    "contributing":["No alert on pool saturation."],
753                    "remediation":["Roll back to 1.3.9."],
754                    "verification":["502 rate back to zero."]}"#,
755            ),
756            T,
757        )
758        .unwrap();
759        r.evidence[0].seen(Some(4_102));
760        let md = r.render();
761
762        assert!(md.starts_with("# Checkout 5xx\n"), "{md}");
763        assert!(
764            md.contains("2026-09-19T10:00:00Z → 2026-09-19T10:31:00Z (31m00s)"),
765            "{md}"
766        );
767        // Sorted, and the pipe inside a cell escaped rather than ending it.
768        let first = md.find("first 502").unwrap();
769        let second = md.find("rollback").unwrap();
770        assert!(first < second, "timeline out of order:\n{md}");
771        assert!(md.contains(r"rollback \| complete"), "{md}");
772        // Every citation carries what it found, which is the difference between
773        // a write-up and a template.
774        assert!(md.contains(", 4102 records"), "{md}");
775        assert!(
776            md.contains("> Mira did not apply any of this and cannot"),
777            "{md}"
778        );
779        // Sections with nothing in them are absent rather than empty: an RCA
780        // with a bare "## Prevention" invites the reader to assume there was
781        // none to propose.
782        assert!(!md.contains("## Prevention"), "{md}");
783
784        // The same document as an OTLP export: one log record, INFO, filed
785        // under this node rather than under the service it is about.
786        let req = r.export(&md, T);
787        let rl = &req.resource_logs[0];
788        let rec = &rl.scope_logs[0].log_records[0];
789        assert_eq!(rec.severity_number, 9);
790        assert_eq!(rec.event_name, "rca");
791        assert_eq!(rec.time_unix_nano, T as u64);
792        assert_eq!(
793            rl.resource.as_ref().unwrap().attributes[0].key,
794            "service.name"
795        );
796        assert!(rec.attributes.iter().any(|a| a.key == "rca.title"));
797    }
798
799    /// Everything a model can get wrong in the argument document, refused with
800    /// the key named. A dropped section is worse here than in a query: nobody
801    /// re-reads an RCA to check that the timeline they wrote is in it.
802    #[test]
803    fn a_misspelled_section_is_refused_rather_than_dropped() {
804        let bad = [
805            (r#"{"summary":"s","root_cause":"r"}"#, "`title`"),
806            (r#"{"title":"t","root_cause":"r"}"#, "`summary`"),
807            (r#"{"title":"t","summary":"s"}"#, "`root_cause`"),
808            (
809                r#"{"title":"t","summary":"s","root_cause":"r","timelines":[]}"#,
810                "unknown query key",
811            ),
812            (
813                r#"{"title":"t","summary":"s","root_cause":"r","impact":"one thing"}"#,
814                "`impact` must be a list",
815            ),
816            (
817                r#"{"title":"t","summary":"s","root_cause":"r","impact":[7]}"#,
818                "quoted string",
819            ),
820            (
821                r#"{"title":"t","summary":"s","root_cause":"r","timeline":[{"what":"x"}]}"#,
822                "needs `at`",
823            ),
824            (
825                r#"{"title":"t","summary":"s","root_cause":"r","timeline":[{"at":"-5m"}]}"#,
826                "`what`",
827            ),
828            (
829                r#"{"title":"t","summary":"s","root_cause":"r","emit":"yes"}"#,
830                "emit",
831            ),
832            (
833                r#"{"title":"t","summary":"s","root_cause":"r","from":"-1h","to":"-2h"}"#,
834                "is after",
835            ),
836        ];
837        for (args, want) in bad {
838            let e = doc(&parse(args), T).unwrap_err();
839            assert!(e.contains(want), "{args}\n  wanted {want:?}, got {e:?}");
840        }
841
842        // And the minimum that is accepted: three sentences and no citations.
843        // An RCA with nothing to cite is a short RCA, not an error.
844        let r = doc(&parse(r#"{"title":"t","summary":"s","root_cause":"r"}"#), T).unwrap();
845        assert!(r.verified());
846        assert!(r.dead().is_none());
847        assert!(!r.emit);
848        assert!(r.render().contains("## Root cause"));
849    }
850
851    /// The rule fence is written by hand, so the writer gets its own test: it
852    /// is the one place a value's *type* survives into the document, and
853    /// `{"gte": 17}` quoted like a string is a severity comparison that no
854    /// longer compares severities.
855    #[test]
856    fn the_rule_fence_keeps_a_number_a_number_and_one_key_per_line() {
857        let y = parse(
858            r#"{"name":"x","when":"count >= 1","query":{"where":[{"gte":17},{"on":true},
859               {"ratio":0.5},{"nil":null}]}}"#,
860        );
861        let out = kyaml(&y);
862        let lines: Vec<_> = out.lines().collect();
863        assert_eq!(lines[0], r#""name": "x""#, "{out}");
864        assert_eq!(lines.len(), 3, "one top-level key per line:\n{out}");
865        // Nested values stay compact, and every scalar keeps its own type.
866        assert!(out.contains(r#"{"gte":17}"#), "{out}");
867        assert!(out.contains(r#"{"on":true}"#), "{out}");
868        assert!(out.contains(r#"{"ratio":0.5}"#), "{out}");
869        assert!(out.contains(r#"{"nil":null}"#), "{out}");
870        // A fragment that is not a mapping is written as the one value it is,
871        // rather than losing itself in a key-per-line loop that has no keys.
872        assert_eq!(kyaml(&parse("[1, 2]")), "[1,2]");
873    }
874}