Skip to main content

mnemo_engine/store/
findings.rs

1//! v0.18.0 (13a step 8b): review findings as records, `_mnemo.kind =
2//! "finding"`, a coordination kind (`docs/design/13a-coordination.md`,
3//! section 8, item 4). A Reviewer adds one under an id it gives
4//! (`RB-014.1`), the Planner triages it, and a Reviewer verifies it. The
5//! engine checks the transitions ([`FINDING_TRANSITIONS`]); who may make
6//! each one is the protocol's (AGENTS.md, tmux rule 9), as for tasks.
7//!
8//! Review round 1 (RB-014): a finding changes only by triage and
9//! verification. `update` and `delete` refuse its record, a wrong one is
10//! `rejected`, and an id is unique by its prefix and numbers. A `SECURITY`
11//! finding is written `private` until it's verified, so an older build's
12//! `export --git`, `list` and recall leave it out, and it's verified only
13//! against a release tag (`v1.2.3`): verified means shipped.
14
15use super::*;
16use crate::memory::{
17    finding_status, FINDING_BODY_MAX, FINDING_CATEGORIES, FINDING_PRIORITIES, FINDING_TITLE_MAX,
18    FINDING_TRANSITIONS, MNEMO_META_BATCH, MNEMO_META_CATEGORY, MNEMO_META_FINDING_ID,
19    MNEMO_META_KIND_FINDING, MNEMO_META_PRIORITY, MNEMO_META_TRIAGE, MNEMO_META_TRIAGED_BY,
20    MNEMO_META_VERIFIED_BY, MNEMO_META_VERIFIED_REF,
21};
22
23/// v0.18.0: a finding to add ([`Mnemo::finding_add`]).
24#[derive(Debug, Clone, Default, PartialEq, Eq)]
25#[non_exhaustive]
26pub struct FindingSpec {
27    /// Its id, `^[A-Z]+-[0-9]+\.[0-9]+$` (`RB-014.1`); unique.
28    pub id: String,
29    /// One of [`FINDING_CATEGORIES`].
30    pub category: String,
31    /// One of [`FINDING_PRIORITIES`].
32    pub priority: String,
33    /// One line, at most [`FINDING_TITLE_MAX`] bytes.
34    pub title: String,
35    /// At most [`FINDING_BODY_MAX`] bytes.
36    pub body: String,
37    /// What it points at: files and lines, commits, PRs.
38    pub refs: Vec<String>,
39}
40
41impl FindingSpec {
42    /// v0.19.0: a finding with its id, category, priority and title, and no
43    /// body or refs. The type is `#[non_exhaustive]`, so outside this crate
44    /// set the other fields after this (`spec.body = "…".into()`).
45    pub fn new(
46        id: impl Into<String>,
47        category: impl Into<String>,
48        priority: impl Into<String>,
49        title: impl Into<String>,
50    ) -> Self {
51        FindingSpec {
52            id: id.into(),
53            category: category.into(),
54            priority: priority.into(),
55            title: title.into(),
56            ..Default::default()
57        }
58    }
59}
60
61/// v0.18.0: one finding.
62#[derive(Debug, Clone, PartialEq)]
63#[non_exhaustive]
64pub struct Finding {
65    /// The record's id.
66    pub record_id: Ulid,
67    /// Its id (`RB-014.1`).
68    pub id: String,
69    /// Its batch, the id's prefix (`RB-014`).
70    pub batch: String,
71    /// Its category.
72    pub category: String,
73    /// Its priority.
74    pub priority: String,
75    /// One line.
76    pub title: String,
77    /// The body (may be empty).
78    pub body: String,
79    /// What it points at.
80    pub refs: Vec<String>,
81    /// Who added it (`_mnemo.author`).
82    pub author: Option<String>,
83    /// `open`, `accepted`, `deferred`, `rejected`, `needs-user` or
84    /// `verified`.
85    pub status: String,
86    /// The last triage's text.
87    pub triage: Option<String>,
88    /// Who triaged it last.
89    pub triaged_by: Option<String>,
90    /// What verified it.
91    pub verified_ref: Option<String>,
92    /// Who verified it.
93    pub verified_by: Option<String>,
94    /// When it was added, in unix seconds.
95    pub created_at: i64,
96    /// Its status changes, oldest first (`from`, `to`, `at`, `by`, and
97    /// `note` when there's one).
98    pub history: Vec<Value>,
99}
100
101impl Finding {
102    /// The finding a record holds, if it's one.
103    pub fn from_memory(m: &Memory) -> Option<Finding> {
104        if m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) != Some(MNEMO_META_KIND_FINDING)
105        {
106            return None;
107        }
108        let s = |k: &str| {
109            m.metadata
110                .get(k)
111                .and_then(Value::as_str)
112                .map(str::to_string)
113        };
114        let (title, body) = match m.content.split_once("\n\n") {
115            Some((a, b)) => (a.to_string(), b.to_string()),
116            None => (m.content.clone(), String::new()),
117        };
118        Some(Finding {
119            record_id: m.id,
120            id: s(MNEMO_META_FINDING_ID).unwrap_or_default(),
121            batch: s(MNEMO_META_BATCH).unwrap_or_default(),
122            category: s(MNEMO_META_CATEGORY).unwrap_or_default(),
123            priority: s(MNEMO_META_PRIORITY).unwrap_or_default(),
124            title,
125            body,
126            refs: m
127                .metadata
128                .get(crate::memory::MNEMO_META_REFS)
129                .and_then(Value::as_array)
130                .map(|a| {
131                    a.iter()
132                        .filter_map(|v| v.as_str().map(str::to_string))
133                        .collect()
134                })
135                .unwrap_or_default(),
136            author: s(crate::memory::MNEMO_META_AUTHOR),
137            status: s(MNEMO_META_STATUS).unwrap_or_default(),
138            triage: s(MNEMO_META_TRIAGE),
139            triaged_by: s(MNEMO_META_TRIAGED_BY),
140            verified_ref: s(MNEMO_META_VERIFIED_REF),
141            verified_by: s(MNEMO_META_VERIFIED_BY),
142            created_at: m.created_at,
143            history: m
144                .metadata
145                .get(MNEMO_META_STATUS_HISTORY)
146                .and_then(Value::as_array)
147                .cloned()
148                .unwrap_or_default(),
149        })
150    }
151
152    /// The order findings are listed in: by prefix, then batch and item
153    /// numbers (`RB-9.1` before `RB-10.1`).
154    pub fn sort_key(&self) -> (String, u64, u64) {
155        parse_id(&self.id).unwrap_or((self.id.clone(), 0, 0))
156    }
157}
158
159/// v0.18.0: which findings [`Mnemo::findings`] lists; each field left out
160/// matches every finding.
161#[derive(Debug, Clone, Default, PartialEq, Eq)]
162#[non_exhaustive]
163pub struct FindingFilter {
164    /// Its status.
165    pub status: Option<String>,
166    /// Its batch (`RB-014`).
167    pub batch: Option<String>,
168    /// Its category.
169    pub category: Option<String>,
170    /// Its priority.
171    pub priority: Option<String>,
172}
173
174/// `RB-014.1` as (`RB`, 14, 1); `None` when it isn't a finding's id.
175fn parse_id(id: &str) -> Option<(String, u64, u64)> {
176    let (prefix, rest) = id.split_once('-')?;
177    let (a, b) = rest.split_once('.')?;
178    let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
179    if prefix.is_empty()
180        || !prefix.bytes().all(|c| c.is_ascii_uppercase())
181        || !digits(a)
182        || !digits(b)
183    {
184        return None;
185    }
186    Some((prefix.to_string(), a.parse().ok()?, b.parse().ok()?))
187}
188
189/// v0.18.0: whether `id` is a finding's id: `^[A-Z]+-[0-9]+\.[0-9]+$`,
190/// at most 64 bytes.
191pub fn valid_finding_id(id: &str) -> bool {
192    id.len() <= 64 && parse_id(id).is_some()
193}
194
195/// The category whose findings stay `private` until they're verified.
196const SECURITY: &str = "SECURITY";
197
198/// Whether `r` is a release tag, `^v[0-9]+\.[0-9]+\.[0-9]+$`.
199fn is_release_tag(r: &str) -> bool {
200    let Some(rest) = r.strip_prefix('v') else {
201        return false;
202    };
203    let parts: Vec<&str> = rest.split('.').collect();
204    parts.len() == 3
205        && parts
206            .iter()
207            .all(|p| !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()))
208}
209
210/// Whether a record is a finding (for the writes that refuse one).
211pub(super) fn is_finding(m: &Memory) -> bool {
212    m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) == Some(MNEMO_META_KIND_FINDING)
213}
214
215/// What `update` and `delete` say when asked to change a finding.
216pub(super) fn finding_write_refused(what: &str) -> MnemoError {
217    MnemoError::Invalid(format!(
218        "a finding can't be {what}: it changes only by `finding triage` or `finding verify`; \
219         a wrong one is rejected, with why, which keeps its history"
220    ))
221}
222
223/// A finding's batch: its id without the item number (`RB-014`).
224fn batch_of(id: &str) -> String {
225    id.rsplit_once('.').map_or(id, |(b, _)| b).to_string()
226}
227
228impl Mnemo {
229    fn finding_records(&mut self, id: Option<&str>) -> Result<Vec<Memory>> {
230        self.coordination_records(MNEMO_META_KIND_FINDING, id)
231    }
232
233    fn finding_record(&mut self, id: &str) -> Result<Option<Memory>> {
234        Ok(self
235            .finding_records(Some(id))?
236            .into_iter()
237            .find(|m| Finding::from_memory(m).is_some_and(|f| f.id == id)))
238    }
239
240    /// v0.18.0: one finding by id. Reads only.
241    pub fn finding(&mut self, id: &str) -> Result<Option<Finding>> {
242        Ok(self
243            .finding_record(id)?
244            .as_ref()
245            .and_then(Finding::from_memory))
246    }
247
248    /// v0.18.0: the findings `filter` matches, ordered by id. Reads only.
249    pub fn findings(&mut self, filter: &FindingFilter) -> Result<Vec<Finding>> {
250        let eq = |want: &Option<String>, have: &str| want.as_deref().is_none_or(|w| w == have);
251        let mut v: Vec<Finding> = self
252            .finding_records(None)?
253            .iter()
254            .filter_map(Finding::from_memory)
255            .filter(|f| {
256                eq(&filter.status, &f.status)
257                    && eq(&filter.batch, &f.batch)
258                    && eq(&filter.category, &f.category)
259                    && eq(&filter.priority, &f.priority)
260            })
261            .collect();
262        v.sort_by_key(Finding::sort_key);
263        Ok(v)
264    }
265
266    /// v0.18.0: add a finding, `open`, by this handle's author, which it
267    /// needs. Its id must be free, by its prefix and numbers (`RB-0900.1`
268    /// is `RB-900.1`): a finding is changed only by triage and
269    /// verification. A `SECURITY` finding is written `private` until it's
270    /// verified.
271    pub fn finding_add(&mut self, spec: &FindingSpec) -> Result<Finding> {
272        if self.read_only {
273            return Err(MnemoError::ReadOnly);
274        }
275        if self.author.as_deref().is_none_or(|a| a.trim().is_empty()) {
276            return Err(MnemoError::Invalid(
277                "a finding needs its author: name the agent (MNEMO_AGENT, or --as on the CLI)"
278                    .into(),
279            ));
280        }
281        if !valid_finding_id(&spec.id) {
282            return Err(MnemoError::Invalid(format!(
283                "{:?} isn't a finding's id: capital letters, '-', a number, '.', a number \
284                 (RB-014.1)",
285                spec.id
286            )));
287        }
288        if !FINDING_CATEGORIES.contains(&spec.category.as_str()) {
289            return Err(MnemoError::Invalid(format!(
290                "{:?} isn't a category: {}",
291                spec.category,
292                FINDING_CATEGORIES.join(", ")
293            )));
294        }
295        if !FINDING_PRIORITIES.contains(&spec.priority.as_str()) {
296            return Err(MnemoError::Invalid(format!(
297                "{:?} isn't a priority: {}",
298                spec.priority,
299                FINDING_PRIORITIES.join(", ")
300            )));
301        }
302        let title = spec.title.trim();
303        if title.is_empty() || title.contains('\n') || title.len() > FINDING_TITLE_MAX {
304            return Err(MnemoError::Invalid(format!(
305                "a finding's title is one line, not empty, at most {FINDING_TITLE_MAX} bytes"
306            )));
307        }
308        if spec.body.len() > FINDING_BODY_MAX {
309            return Err(MnemoError::Invalid(format!(
310                "a finding's body is at most {FINDING_BODY_MAX} bytes"
311            )));
312        }
313        let want = parse_id(&spec.id);
314        if let Some(taken) = self
315            .finding_records(None)?
316            .iter()
317            .filter_map(Finding::from_memory)
318            .find(|f| f.id == spec.id || parse_id(&f.id) == want)
319        {
320            let same = if taken.id == spec.id {
321                String::new()
322            } else {
323                format!(" (as {})", taken.id)
324            };
325            return Err(MnemoError::Invalid(format!(
326                "{} is taken{same}; give the next free id",
327                spec.id
328            )));
329        }
330        let content = if spec.body.is_empty() {
331            title.to_string()
332        } else {
333            format!("{title}\n\n{}", spec.body)
334        };
335        let mut meta = Map::new();
336        meta.insert(MNEMO_META_FINDING_ID.into(), Value::String(spec.id.clone()));
337        meta.insert(MNEMO_META_BATCH.into(), Value::String(batch_of(&spec.id)));
338        meta.insert(
339            MNEMO_META_CATEGORY.into(),
340            Value::String(spec.category.clone()),
341        );
342        meta.insert(
343            MNEMO_META_PRIORITY.into(),
344            Value::String(spec.priority.clone()),
345        );
346        meta.insert(
347            MNEMO_META_STATUS.into(),
348            Value::String(finding_status::OPEN.into()),
349        );
350        meta.insert(
351            crate::memory::MNEMO_META_REFS.into(),
352            Value::Array(spec.refs.iter().map(|r| Value::String(r.clone())).collect()),
353        );
354        if spec.category == SECURITY {
355            meta.insert(
356                crate::memory::MNEMO_META_VISIBILITY.into(),
357                Value::String("private".into()),
358            );
359        }
360        let id =
361            self.put_coordination_with_id(Ulid::new(), MNEMO_META_KIND_FINDING, content, meta)?;
362        Ok(Finding::from_memory(&self.get(&id)?).expect("a finding"))
363    }
364
365    /// v0.18.0: triage a finding: to `accepted`, `deferred`, `rejected` or
366    /// `needs-user`, with `text` (why), as [`FINDING_TRANSITIONS`] allows.
367    /// The record changes in place, with a history entry.
368    pub fn finding_triage(&mut self, id: &str, to: &str, text: &str) -> Result<Finding> {
369        if to == finding_status::VERIFIED {
370            return Err(MnemoError::Invalid(
371                "a finding is verified with `verify`, and a ref".into(),
372            ));
373        }
374        let text = text.trim();
375        if text.is_empty() || text.len() > FINDING_BODY_MAX {
376            return Err(MnemoError::Invalid(format!(
377                "a triage needs its text (why), at most {FINDING_BODY_MAX} bytes"
378            )));
379        }
380        self.finding_move(id, to, text, |m, by| {
381            m.metadata
382                .insert(MNEMO_META_TRIAGE.into(), Value::String(text.to_string()));
383            m.metadata
384                .insert(MNEMO_META_TRIAGED_BY.into(), Value::String(by.to_string()));
385        })
386    }
387
388    /// v0.18.0: verify a finding against `verified_ref` (a commit, a tag,
389    /// a PR), from `accepted`, `deferred` or `needs-user`. A `SECURITY`
390    /// finding is verified only against a published release tag
391    /// (`v1.2.3`), and becomes `team` then.
392    pub fn finding_verify(&mut self, id: &str, verified_ref: &str) -> Result<Finding> {
393        let r = verified_ref.trim();
394        if r.is_empty() || r.contains('\n') || r.len() > FINDING_TITLE_MAX {
395            return Err(MnemoError::Invalid(format!(
396                "a verification needs its ref (a commit, a tag, a PR), one line, at most \
397                 {FINDING_TITLE_MAX} bytes"
398            )));
399        }
400        let security = self.finding(id)?.is_some_and(|f| f.category == SECURITY);
401        if security && !is_release_tag(r) {
402            return Err(MnemoError::Invalid(format!(
403                "a SECURITY finding is verified against a published release tag (v1.2.3), \
404                 not {r:?}"
405            )));
406        }
407        self.finding_move(id, finding_status::VERIFIED, r, |m, by| {
408            m.metadata
409                .insert(MNEMO_META_VERIFIED_REF.into(), Value::String(r.to_string()));
410            m.metadata
411                .insert(MNEMO_META_VERIFIED_BY.into(), Value::String(by.to_string()));
412            if security {
413                m.metadata.insert(
414                    crate::memory::MNEMO_META_VISIBILITY.into(),
415                    Value::String("team".into()),
416                );
417            }
418        })
419    }
420
421    /// Move a finding to `to`, as [`FINDING_TRANSITIONS`] allows, with
422    /// `set` filling in the fields that go with it.
423    fn finding_move(
424        &mut self,
425        id: &str,
426        to: &str,
427        note: &str,
428        set: impl FnOnce(&mut Memory, &str),
429    ) -> Result<Finding> {
430        if self.read_only {
431            return Err(MnemoError::ReadOnly);
432        }
433        let Some(mut m) = self.finding_record(id)? else {
434            return Err(MnemoError::Invalid(format!("no finding {id:?}")));
435        };
436        let f = Finding::from_memory(&m).expect("a finding");
437        if !FINDING_TRANSITIONS.contains(&(f.status.as_str(), to)) {
438            return Err(MnemoError::Invalid(format!(
439                "a finding can't go from {} to {to}",
440                f.status
441            )));
442        }
443        let by = self.author.clone().unwrap_or_else(|| "anonymous".into());
444        let now = self.coordination_now();
445        m.metadata
446            .insert(MNEMO_META_STATUS.into(), Value::String(to.to_string()));
447        set(&mut m, &by);
448        Self::task_history(&mut m, &f.status, to, &by, now, &[("note", note)]);
449        let rid = m.id;
450        self.put(m)?;
451        Ok(Finding::from_memory(&self.get(&rid)?).expect("a finding"))
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    #[test]
460    fn finding_ids() {
461        for ok in ["RB-014.1", "R-011.2", "REV-1.10", "A-0.0"] {
462            assert!(valid_finding_id(ok), "{ok}");
463        }
464        for bad in [
465            "",
466            "rb-014.1",
467            "RB014.1",
468            "RB-014",
469            "RB-014.",
470            "RB-.1",
471            "RB-01a.1",
472            "RB-014.1.2",
473            "R B-1.1",
474            "RB-1.1 ",
475            "-1.1",
476        ] {
477            assert!(!valid_finding_id(bad), "{bad}");
478        }
479        assert_eq!(batch_of("RB-014.12"), "RB-014");
480        assert!(parse_id("RB-9.1") < parse_id("RB-10.1"));
481        assert_eq!(parse_id("RB-0900.1"), parse_id("RB-900.1"));
482    }
483
484    #[test]
485    fn release_tags() {
486        for ok in ["v0.18.0", "v1.2.3", "v10.20.30"] {
487            assert!(is_release_tag(ok), "{ok}");
488        }
489        for bad in [
490            "",
491            "0.18.0",
492            "v0.18",
493            "v0.18.0-rc1",
494            "v0.18.0.1",
495            "abc1234",
496            "v.1.2",
497            "V1.2.3",
498            "v1..3",
499        ] {
500            assert!(!is_release_tag(bad), "{bad}");
501        }
502    }
503}