Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Smart Results v2: chart, metrics, facts, cards, findings, checklist/timeline, priority (A.4) (#232)

Oleksandr Ivanchenko77cd47bb4efc
diff --git a/docs/smart-results.md b/docs/smart-results.md
index 98437df4..5b29e818 100644
--- a/docs/smart-results.md
+++ b/docs/smart-results.md
@@ -1,7 +1,8 @@
# Smart Results (0.6.5)
A bot's final reply can carry one typed block, `results`, that the chat draws in place of a table
-or a list in the reply: a comparison card for a table, a checklist for numbered steps. The reply's
+or a list in the reply: a chart, a comparison, key numbers, findings, cards, steps (plain, checklist
+or timeline) or facts. The reply's
text is never changed. When there is no block, or the chat can't draw it, the reply shows its
markdown as it always has.
@@ -22,10 +23,16 @@ Code: `src/server/smart_results/` (contract types, selectors, checks) and
- **When it is worked out:** once, when the message is saved (`insert_message_on`), never while
the reply is streaming. The selectors are deterministic: no model calls and no network. A reply
longer than 128 KB stays text.
-- **How the block is chosen:** the candidates are offered in priority order, every comparison
- table first, then every steps list, each in the order it appears in the text. The first candidate
- whose type is in `ENABLED_TYPES` and that passes the checks is stored, and only that one: a
- message has at most one block.
+- **How the block is chosen:** each table gets at most one class (line chart, else bar chart unless
+ the prose names a pick, else metrics, else comparison) and each list at most one (metrics,
+ findings, cards, timeline, checklist, steps, facts). The candidates are then offered in the order
+ of `selector::PRIORITY`: chart > comparison > metrics > findings > cards > timeline > checklist >
+ steps > facts. A tie goes to the earliest in the text. The first candidate whose type is in
+ `ENABLED_TYPES` and that passes the checks is stored, and only that one: a message has at most
+ one block.
+- **The bot prompt line:** every turn's system prompt carries `smart_results::PROMPT_LINE` once
+ (in the cached tail, `drivers::TurnInput::system_prompt_parts`), asking for tables, numbered
+ steps and `**Label:** value` lines.
- **What it never costs:** the reply. If a selector panics, a block fails its checks, or the write
fails, kwant logs it and saves the message exactly as before.
- **Edits:** when a reply's text is replaced (`set_message_text`), its block is deleted, because the
@@ -54,7 +61,8 @@ Code: `src/server/smart_results/` (contract types, selectors, checks) and
```ts
type ResultSet = { version: 1, blocks: [Block] } // exactly one block when there is a row
-type Source = { kind: "markdown_table" | "markdown_list", index: number }
+type Source = { kind: "markdown_table" | "markdown_list" | "slot", index: number | null,
+ ordered: boolean | null } // lists: ordered or bullet; slot: no index
type Provenance = { kind: "reply_text" }
type Comparison = {
@@ -69,10 +77,12 @@ type Steps = {
}
```
-These are the v1 shapes. Plan v2 (§A.3) adds fields to them: `title`, column `role`, and the
-steps `variant`, `done`, `when` and `owner`. The client reads a missing field with its v1 meaning
-(`title` null, role `label` for the first column and `value` for the rest, variant `steps`).
-`smart-results-more` writes these fields.
+These are the v1 shapes. v2 (plan §A.3) adds fields to them: `title`, column `role`, and the
+steps `variant` (`steps`, `checklist`, `timeline`), `done`, `when` and `owner`. The client reads a
+missing field with its v1 meaning (`title` null, role `label` for the first column and `value` for
+the rest, variant `steps`). v2 also adds `chart`, `metrics`, `facts`, `cards` and `findings`; the
+Rust types in `src/server/smart_results/mod.rs` are the reference. Numbers (`values`, `value`) are
+parsed from the cell as written, never computed; a cell without one is `null`, never 0.
### Values are copied, never made up
@@ -101,6 +111,41 @@ steps `variant`, `done`, `when` and `owner`. The client reads a missing field wi
## Selectors
+Every selector abstains when in doubt.
+
+**Chart** (table, 1–4 series that share one unit, ≥ 80% of each series' cells numbers, the rest
+gap tokens such as `-` or `n/a`):
+- line: 4–60 rows and every first cell time-like (ISO date, `YYYY-MM`, month name, Q1–Q4,
+ Week N, Day N, a year 1900–2100);
+- bar: 5–20 rows, a text first column, 1–2 series, and no pick named in the prose; 2–4 rows stay
+ a comparison.
+- A series' unit is the affix its cells share, or for bare numbers the bracketed end of its
+ header (`Price (EUR)`, `Rating [1-5]`). Series whose units differ are never drawn on one Y
+ axis: the table is not a chart (SR-R-13). Units compare as written, so `€` and `EUR` differ.
+- Numbers are read with both `,` and `.` as the decimal mark; when the readings disagree for the
+ column (`1,299` alone), there is no chart.
+
+**Metrics:** 2–6 list items `**Label:** value` or `Label: value` whose value starts with a number
+(`$4.2M`, `12 ms`, `98%`, `3 of 5`), or a 2-column table of 2–6 rows with at least two different
+units (one shared unit is a comparison, or a bar chart from 5 rows). Not when the list is
+introduced as ingredients, a recipe, packing, a schedule or an agenda, nor for time or date labels.
+
+**Findings:** 2–30 items that each start with a severity token (`**High:**`, `[High]`, `High:`;
+Critical, Blocker, High, Major, Medium, Moderate, Low, Minor, Info, Nit, P0–P3), plus a second
+signal: a lead line or heading saying review, audit, findings, issues, bugs or risks, or a
+`path:line` in a code span. One item whose text starts with a number ("High: 18C") keeps the
+whole list text.
+
+**Cards:** 3–12 items starting with an `https` link or a `**Title**`, then " — ", " – " or " - "
+(or ": " after a link) and a description of at least 10 characters. Link text that looks like a
+different URL keeps the list text. `**Title:** text` reads as facts.
+
+**Steps:** a timeline when every item has a time-like or clock label (3–15 items); a checklist
+when every item is a task (3–20); otherwise the numbered-steps rule below. `owner` comes only from
+a literal "Owner: X" or "(owner: X)".
+
+**Facts:** 3–12 items `**Label:** value`, more than half of them not starting with a number.
+
**Comparison:**
- the table is a clean top-level GFM pipe table;
- it has 2–8 columns and 3–50 rows, every row with as many cells as the header;
@@ -121,12 +166,13 @@ steps `variant`, `done`, `when` and `owner`. The client reads a missing field wi
- **Tables:** every GFM table in document order, from 0. A table inside fenced or indented code,
or in raw HTML, is not a table and isn't counted.
-- **Lists:** every ordered list in pre-order, nested ones included, from 0; bullet lists aren't
- counted. An ordered task list counts as an ordered list, but it isn't offered as steps in this
- version.
+- **Lists:** two counters, each from 0: numbered lists and bullet lists (`ordered: false`), in
+ pre-order, nested ones included. A task list counts in its own kind. A change of marker (`-` to
+ `*`, `.` to `)`) starts a new list. `slot` blocks have no index and shift nothing.
- **Uncertainty:** the server reads markdown line by line. Some constructs could make its count
- differ from the chat's: a table or numbered list inside a quote or a bullet item, a list nested
- in a list, raw HTML, tabs, or a table run straight into a paragraph. From the first such
+ differ from the chat's: a table or list inside a quote or an item, a list nested in a list, raw
+ HTML, tabs, footnotes, a table run straight into a paragraph, or a leftover `[DECISIONS]` tag
+ (the whole reply). From the first such
construct on, kwant offers no block for that kind, and the reply stays text. Candidates before
that point are still offered.
@@ -136,8 +182,8 @@ The client checks every block again: the labels, the row and item counts, and th
## Adding a block type
1. Add a `Block` variant and its `kind()` arm (`mod.rs`).
-2. Add a selector to `candidates()`, in the priority order of plan §A.2.
+2. Add a selector to `candidates()` and the type to `PRIORITY` (plan §A.4).
3. Add its checks to `validate()`.
4. Add the type to `ENABLED_TYPES`.
-5. Add tests in `selector_tests.rs`. Each test must cover the cases where the selector abstains,
+5. Add tests in `block_tests.rs`. Each test must cover the cases where the selector abstains,
not only the ones where it fires.
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index b11b6472..56b45760 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -508,7 +508,10 @@ impl TurnInput {
head: base,
date,
team: team_block,
- tail: format!("{teammates_block}{sandbox_rules}"),
+ tail: format!(
+ "{teammates_block}\n\n[Results]\n{}{sandbox_rules}",
+ crate::server::smart_results::PROMPT_LINE
+ ),
}
}
}
@@ -870,6 +873,18 @@ pub(crate) mod tests {
}
}
+ /// Plan §A.4: one line asks for structure the Smart Results selectors can read, once per turn.
+ #[test]
+ fn every_turn_asks_for_structure_once() {
+ let line = crate::server::smart_results::PROMPT_LINE;
+ for access in [BrowserAccess::Tools, BrowserAccess::Shell, BrowserAccess::Unavailable] {
+ let prompt = input().format_system_prompt_with(access);
+ assert_eq!(prompt.matches(line).count(), 1, "{access:?}");
+ // In the part that stays the same between turns, so it doesn't break the cache
+ assert!(input().system_prompt_parts(access).tail.contains(line), "{access:?}");
+ }
+ }
+
/// Rigel's F1 probe: a teammate closes its own frame and opens a fake person frame after it.
#[test]
fn peer_message_cannot_break_out_of_its_frame() {
diff --git a/src/server/smart_results/block_tests.rs b/src/server/smart_results/block_tests.rs
new file mode 100644
index 00000000..fd06a86b
--- /dev/null
+++ b/src/server/smart_results/block_tests.rs
@@ -0,0 +1,373 @@
+//! One test group per v2 block type (plan §A.4) and the priority order, with Rigel's traps
+//! (qa/test-plan.md 5.4 and 5.14).
+use super::*;
+use crate::server::smart_results::{compute, validate, AxisKind, Block, ChartKind, Severity, Variant};
+
+fn first(text: &str) -> Option<Block> {
+ compute(text).map(|set| set.blocks.into_iter().next().expect("one block"))
+}
+
+fn kind(text: &str) -> Option<&'static str> {
+ first(text).map(|b| b.kind())
+}
+
+fn table(header: &str, rows: &[String]) -> String {
+ let n = header.matches('|').count() - 1;
+ format!("{header}\n|{}\n{}\n", "---|".repeat(n), rows.join("\n"))
+}
+
+fn rows(n: usize, f: impl Fn(usize) -> String) -> Vec<String> {
+ (0..n).map(f).collect()
+}
+
+const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+// --- chart: line
+
+#[test]
+fn a_time_series_of_four_rows_or_more_is_a_line_chart() {
+ let t = table("| Month | Visits |", &rows(4, |i| format!("| 2025-0{} | {} |", i + 1, 100 + i * 10)));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!((c.chart_kind, c.x.kind, c.series.len(), c.points.len()), (ChartKind::Line, AxisKind::Time, 1, 4));
+ assert_eq!((c.source.kind.as_str(), c.source.index), ("markdown_table", Some(0)));
+ assert_eq!((c.points[1].x.as_str(), c.points[1].cells[0].as_str(), c.points[1].values[0]), ("2025-02", "110", Some(110.0)));
+ assert!(c.summary.is_none());
+ // Four series is still a line; five isn't (never four of five silently)
+ let wide = |s: usize| {
+ let head = format!("| Month |{}", (0..s).map(|k| format!(" S{k} |")).collect::<String>());
+ table(&head, &rows(5, |i| format!("| {} 2025 |{}", MONTHS[i], (0..s).map(|k| format!(" {} |", i + k)).collect::<String>())))
+ };
+ let Some(Block::Chart(c)) = first(&wide(4)) else { panic!() };
+ assert_eq!(c.series.len(), 4);
+ assert_ne!(kind(&wide(5)), Some("chart"));
+}
+
+#[test]
+fn three_dated_rows_are_not_a_line() {
+ let t = table("| Quarter | Revenue |", &rows(3, |i| format!("| Q{} 2025 | {} |", i + 1, 10 + i)));
+ assert_ne!(kind(&t), Some("chart"));
+}
+
+#[test]
+fn gaps_are_null_never_zero_and_mixed_units_never_chart() {
+ let t = table("| Week | Sales |", &rows(5, |i| if i == 2 { "| Week 3 | n/a |".into() } else { format!("| Week {} | 4{i} |", i + 1) }));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.points[2].values, [None]);
+ let mixed = table("| Day | Price |", &rows(5, |i| format!("| Day {} | {} 1{i} |", i + 1, if i == 0 { "USD" } else { "EUR" })));
+ assert_ne!(kind(&mixed), Some("chart"));
+}
+
+#[test]
+fn series_in_different_units_never_share_one_axis() {
+ // SR-R-13: bare numbers whose headers name two units stay off one Y axis
+ let line = |h: &str| table(h, &rows(5, |i| format!("| {} 2025 | 1{i}0 | {}.{i} |", MONTHS[i], 3 + i % 2)));
+ assert_ne!(kind(&line("| Month | Price (EUR) | Rating (1-5) |")), Some("chart"));
+ assert_ne!(kind(&line("| Month | Price [EUR] | Rating |")), Some("chart"));
+ assert_ne!(kind(&line("| Month | Price (€) | Cost (EUR) |")), Some("chart"));
+ // A cell unit against a header unit that differs
+ let t = table("| Month | Price | Rating (1-5) |", &rows(5, |i| format!("| {} 2025 | €1{i} | 4.{i} |", MONTHS[i])));
+ assert_ne!(kind(&t), Some("chart"));
+ let bar = table("| Shop | Price (EUR) | Rating (1-5) |", &rows(5, |i| format!("| Shop{} | 1{i}0 | 4.{i} |", MONTHS[i])));
+ assert_ne!(kind(&bar), Some("chart"));
+ // One unit, named in the headers or the cells, still charts
+ for h in ["| Month | Revenue (EUR) | Cost (eur) |", "| Month | Signups | Paid |"] {
+ let Some(Block::Chart(c)) = first(&line(h)) else { panic!("{h}: {:?}", first(&line(h))) };
+ assert_eq!(c.series.len(), 2, "{h}");
+ }
+ let t = table("| Month | Revenue (€) | Cost |", &rows(5, |i| format!("| {} 2025 | 1{i}0 | €2{i} |", MONTHS[i])));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.series.len(), 2);
+}
+
+#[test]
+fn ambiguous_locale_numbers_abstain() {
+ // `1,299` alone is 1299 or 1.299: no chart, and never a misread scale
+ let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | 1,2{i}9 |", MONTHS[i])));
+ assert_ne!(kind(&t), Some("chart"));
+ // With `1,299.00` beside it the column has one reading
+ let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | 1,2{i}9.50 |", MONTHS[i])));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.points[0].values, [Some(1209.5)]);
+ let t = table("| Month | Cost |", &rows(5, |i| format!("| {} 2025 | 1.2{i}9,50 |", MONTHS[i])));
+ let Some(Block::Chart(c)) = first(&t) else { panic!("{:?}", first(&t)) };
+ assert_eq!(c.points[0].values, [Some(1209.5)]);
+}
+
+// --- chart: bar
+
+fn ranking(n: usize, cols: usize) -> String {
+ let head = format!("| Language |{}", (0..cols).map(|k| format!(" Score {k} |")).collect::<String>());
+ table(&head, &rows(n, |i| format!("| Lang{} |{}", (b'A' + i as u8) as char, (0..cols).map(|k| format!(" {} |", 90 - i - k)).collect::<String>())))
+}
+
+#[test]
+fn five_to_twenty_category_rows_are_a_bar_chart() {
+ for n in [5, 20] {
+ let Some(Block::Chart(c)) = first(&ranking(n, 1)) else { panic!("{n}: {:?}", first(&ranking(n, 1))) };
+ assert_eq!((c.chart_kind, c.x.kind, c.points.len()), (ChartKind::Bar, AxisKind::Category, n));
+ }
+ let Some(Block::Chart(c)) = first(&ranking(6, 2)) else { panic!() };
+ assert_eq!(c.series.len(), 2);
+}
+
+#[test]
+fn small_long_or_wide_rankings_are_comparisons() {
+ // Ada's A.4 decision: 2–4 rows stay a comparison (Rigel SR-T-06)
+ for n in [3, 4] {
+ assert_eq!(kind(&ranking(n, 1)), Some("comparison"), "{n} rows");
+ }
+ assert_ne!(kind(&ranking(21, 1)), Some("chart"));
+ assert_eq!(kind(&ranking(6, 3)), Some("comparison"));
+}
+
+#[test]
+fn a_named_pick_keeps_the_table_a_comparison_with_its_highlight() {
+ let text = format!("{}\nI'd go with LangB for this.\n", ranking(6, 1));
+ let Some(Block::Comparison(c)) = first(&text) else { panic!("{:?}", first(&text)) };
+ assert_eq!(c.highlight_row.as_deref(), Some("r1"));
+}
+
+// --- metrics
+
+#[test]
+fn bold_label_number_lines_are_metrics_with_value_text_verbatim() {
+ let text = "Key numbers:\n- **Revenue:** $4.2M, up from last year\n- **Latency:** 12 ms\n- **Uptime:** 98%\n- **Tests:** 3 of 5\n";
+ let Some(Block::Metrics(m)) = first(text) else { panic!("{:?}", first(text)) };
+ let got: Vec<_> = m.items.iter().map(|i| (i.label.as_str(), i.value_text.as_str(), i.value, i.unit.as_deref())).collect();
+ assert_eq!(got[0], ("Revenue", "$4.2M", 4.2, None));
+ assert_eq!(got[1], ("Latency", "12 ms", 12.0, Some("ms")));
+ assert_eq!(got[2], ("Uptime", "98%", 98.0, Some("%")));
+ assert_eq!(m.items[0].note.as_deref(), Some("up from last year"));
+ assert_eq!((m.source.kind.as_str(), m.source.index, m.source.ordered), ("markdown_list", Some(0), Some(false)));
+ // One item or seven: not metrics
+ assert_ne!(kind("- **Revenue:** $4.2M\n"), Some("metrics"));
+ let seven: String = (0..7).map(|i| format!("- **K{}:** {i}%\n", MONTHS[i])).collect();
+ assert_ne!(kind(&seven), Some("metrics"));
+}
+
+#[test]
+fn a_two_column_table_is_metrics_when_its_units_differ_and_a_bar_from_five_rows_when_they_dont() {
+ let mixed = table("| Metric | Value |", &["| Revenue | $4.2M |".into(), "| Latency | 12 ms |".into(), "| Uptime | 98% |".into()]);
+ assert_eq!(kind(&mixed), Some("metrics"));
+ let one_unit = |n: usize| table("| Team | Share |", &rows(n, |i| format!("| Team{} | {}% |", MONTHS[i], 10 + i)));
+ for n in [3, 4] {
+ assert_eq!(kind(&one_unit(n)), Some("comparison"), "{n} rows");
+ }
+ for n in [5, 6] {
+ let Some(Block::Chart(c)) = first(&one_unit(n)) else { panic!("{n}") };
+ assert_eq!(c.chart_kind, ChartKind::Bar);
+ }
+}
+
+#[test]
+fn recipes_packing_lists_and_schedules_are_not_metrics() {
+ for text in [
+ "Ingredients:\n- **Flour:** 2 cups\n- **Sugar:** 1 cup\n- **Eggs:** 3\n",
+ "What to pack:\n- **Socks:** 5 pairs\n- **Shirts:** 3\n",
+ "- **Mon:** 9 am\n- **Tue:** 10 am\n",
+ "- **Note:** 5 minutes of rest\n",
+ ] {
+ assert_ne!(kind(text), Some("metrics"), "{text}");
+ }
+}
+
+// --- the weather trap (Rigel SR-T-21)
+
+#[test]
+fn a_weather_reply_is_never_findings() {
+ for text in [
+ "- High: 18C\n- Low: 9C\n",
+ "High: 18C / Low: 9C\n",
+ "Forecast risks:\n- High: 18C\n- Low: 9C\n",
+ "Review:\n- Low prices: cheaper than last year\n- Major benefit: it is quiet\n",
+ "Issues:\n- High: 5 files fail to build\n- Low: one typo\n",
+ ] {
+ assert_ne!(kind(text), Some("findings"), "{text}");
+ }
+ // The bare high/low list reads as two key numbers, which is what it says
+ assert_eq!(kind("- High: 18C\n- Low: 9C\n"), Some("metrics"));
+ assert_eq!(kind("High: 18C / Low: 9C\n"), None);
+}
+
+// --- findings
+
+#[test]
+fn severity_lists_need_a_second_signal() {
+ let list = "- **High:** SQL built from user input in `src/db.rs:42`\n- **Low:** typo in the log message\n";
+ let Some(Block::Findings(f)) = first(list) else { panic!("{:?}", first(list)) };
+ assert_eq!((f.items[0].severity, f.items[0].severity_text.as_str()), (Severity::High, "High"));
+ assert_eq!(f.items[0].refs.len(), 1);
+ assert_eq!((f.items[0].refs[0].path.as_str(), f.items[0].refs[0].line), ("src/db.rs", Some(42)));
+ // Without the ref, only a review lead makes it findings
+ let bare = "- **High:** SQL built from user input\n- **Low:** typo in the log message\n";
+ assert_ne!(kind(bare), Some("findings"));
+ assert_eq!(kind(&format!("Code review findings:\n\n{bare}")), Some("findings"));
+ assert_eq!(kind(&format!("## Audit\n\n{bare}")), Some("findings"));
+ // A port or a URL isn't a ref
+ let port = "- **High:** the API listens on `localhost:8080`\n- **Low:** see `http://x:80`\n";
+ assert_ne!(kind(port), Some("findings"));
+}
+
+#[test]
+fn look_alike_severity_words_are_not_findings() {
+ for text in [
+ "Review:\n- High-quality build\n- Lowering the bar\n",
+ "Review:\n- P4: someday\n- P5: never\n",
+ "Review:\n- **High:** one thing\n",
+ ] {
+ assert_ne!(kind(text), Some("findings"), "{text}");
+ }
+}
+
+// --- cards
+
+#[test]
+fn https_links_with_descriptions_are_cards() {
+ let text = "Resources:\n- [Rust Book](https://doc.rust-lang.org/book/) — the official guide to the language\n- [Tokio](https://tokio.rs) — an async runtime for network services\n- [Serde](https://serde.rs) — serialization for Rust data structures\n";
+ let Some(Block::Cards(c)) = first(text) else { panic!("{:?}", first(text)) };
+ assert_eq!(c.items.len(), 3);
+ assert_eq!((c.items[1].title.as_str(), c.items[1].url.as_deref()), ("Tokio", Some("https://tokio.rs")));
+ for bad in ["http://tokio.rs", "javascript:alert(1)", "/docs", "mailto:[email protected]"] {
+ let t = text.replace("https://tokio.rs", bad);
+ assert_ne!(kind(&t), Some("cards"), "{bad}");
+ }
+ // Link text that looks like a URL elsewhere is a spoof
+ let spoof = text.replace("[Tokio](https://tokio.rs)", "[https://bank.com](https://evil.test)");
+ assert_ne!(kind(&spoof), Some("cards"));
+ // A description under 10 characters is too weak
+ assert_ne!(kind(&text.replace("an async runtime for network services", "a runtime")), Some("cards"));
+}
+
+#[test]
+fn bold_titles_with_a_dash_are_cards_and_with_a_colon_are_facts() {
+ let dash = "- **Alpha** — a description of fifteen characters\n- **Beta** — another long enough description\n- **Gamma** — and a third long description\n";
+ assert_eq!(kind(dash), Some("cards"));
+ let colon = dash.replace("** —", ":**");
+ assert_eq!(kind(&colon), Some("facts"));
+}
+
+// --- facts
+
+#[test]
+fn bold_label_lines_that_are_mostly_words_are_facts() {
+ let text = "Specs:\n- **Material:** aluminium\n- **Colour:** space grey\n- **Weight:** 1.2 kg\n- **Warranty:** two years\n";
+ let Some(Block::Facts(f)) = first(text) else { panic!("{:?}", first(text)) };
+ assert_eq!((f.items[2].label.as_str(), f.items[2].value.as_str()), ("Weight", "1.2 kg"));
+ // Two items, or half numeric: not facts
+ assert_ne!(kind("- **Material:** aluminium\n- **Colour:** grey\n"), Some("facts"));
+ let half = "- **A:** 1 kg\n- **B:** 2 kg\n- **C:** grey\n- **D:** blue\n";
+ assert_ne!(kind(half), Some("facts"));
+}
+
+// --- steps variants
+
+#[test]
+fn task_lists_are_checklists_with_the_reply_s_boxes() {
+ let text = "Launch:\n- [x] Write notes\n- [ ] Tag the release\n- [ ] Announce it (owner: Sam)\n";
+ let Some(Block::Steps(s)) = first(text) else { panic!("{:?}", first(text)) };
+ assert_eq!((s.variant, s.source.ordered), (Variant::Checklist, Some(false)));
+ assert_eq!(s.items.iter().map(|i| i.done).collect::<Vec<_>>(), [Some(true), Some(false), Some(false)]);
+ assert_eq!(s.items[2].owner.as_deref(), Some("Sam"));
+ // Two items, or plain items mixed in: markdown
+ assert_eq!(kind("- [x] a\n- [ ] b\n"), None);
+ assert_eq!(kind("- [x] a\n- b\n- [ ] c\n"), None);
+}
+
+#[test]
+fn owners_come_only_from_the_literal_forms() {
+ let owner = |tail: &str| {
+ let text = format!("Steps:\n1. Build it {tail}\n2. Test it\n3. Ship it\n");
+ match first(&text) {
+ Some(Block::Steps(s)) => s.items[0].owner.clone(),
+ other => panic!("{tail}: {other:?}"),
+ }
+ };
+ assert_eq!(owner("(owner: Sam)").as_deref(), Some("Sam"));
+ assert_eq!(owner("Owner: Sam").as_deref(), Some("Sam"));
+ for tail in ["owner - Sam", "assigned to Sam", "Sam will do it", "OWNER: Sam"] {
+ assert_eq!(owner(tail), None, "{tail}");
+ }
+}
+
+#[test]
+fn time_labelled_lists_are_timelines() {
+ let text = "Release plan:\n- 2025-01-05 — branch cut\n- Jan 12: beta\n- Q2: general availability\n";
+ let Some(Block::Steps(s)) = first(text) else { panic!("{:?}", first(text)) };
+ assert_eq!(s.variant, Variant::Timeline);
+ assert_eq!(s.items[1].when.as_deref(), Some("Jan 12"));
+ assert_eq!(s.items[1].text, "beta");
+ let day = "Agenda:\n- 9:00 – Intro\n- 10:30 – Demo\n- Mon: kickoff\n";
+ assert_eq!(first(day).map(|b| rank(&b)), Some((PRIORITY.iter().position(|t| *t == "steps").unwrap(), 0)));
+ // One label that isn't a time: not a timeline
+ assert_ne!(kind("- 9:00 – Intro\n- Note: bring a laptop\n- 11:00 – Lunch\n"), Some("steps"));
+}
+
+// --- priority: one block per reply
+
+#[test]
+fn one_block_per_reply_by_priority_whatever_the_order() {
+ let comparison = "| Plan | Price | Seats |\n|---|---|---|\n| Basic | EUR 12 | 1 |\n| Team | EUR 18 | 5 |\n| Business | EUR 26 | 20 |\n";
+ let checklist = "- [x] a task\n- [ ] b task\n- [ ] c task\n";
+ let metrics = "Key numbers:\n- **Revenue:** $4.2M\n- **Uptime:** 98%\n";
+ let parts = [checklist, metrics, comparison];
+ for order in [[0, 1, 2], [2, 1, 0], [1, 0, 2]] {
+ let text: String = order.iter().map(|&i| format!("{}\n", parts[i])).collect();
+ let set = compute(&text).expect("a block");
+ assert_eq!(set.blocks.len(), 1);
+ assert_eq!(set.blocks[0].kind(), "comparison", "{order:?}");
+ validate(&set, Some(&text)).expect("valid");
+ }
+ // Without the table, metrics beats the checklist
+ assert_eq!(kind(&format!("{checklist}\n{metrics}")), Some("metrics"));
+}
+
+#[test]
+fn a_tie_goes_to_the_earliest_and_later_blocks_keep_their_indexes() {
+ let a = "Steps:\n1. One\n2. Two\n3. Three\n";
+ let b = "Steps:\n1. Uno\n2. Dos\n3. Tres\n";
+ let Some(Block::Steps(s)) = first(&format!("{a}\n{b}")) else { panic!() };
+ assert_eq!((s.items[0].text.as_str(), s.source.index), ("One", Some(0)));
+ let all = candidates(&format!("{a}\n{b}"));
+ assert_eq!(all[1].source().index, Some(1));
+}
+
+#[test]
+fn ordered_and_unordered_lists_keep_separate_counters() {
+ let text = "Notes:\n- a\n- b\n\nSteps:\n1. One\n2. Two\n3. Three\n\nLaunch:\n- [ ] x task\n- [ ] y task\n- [ ] z task\n";
+ let all = candidates(text);
+ let got: Vec<_> = all.iter().map(|b| (b.kind(), b.source().index, b.source().ordered)).collect();
+ assert!(got.contains(&("steps", Some(0), Some(true))), "{got:?}");
+ assert!(got.contains(&("steps", Some(1), Some(false))), "{got:?}");
+ // A marker change splits an unordered list
+ let text = "- a\n- b\n* [ ] x task\n* [ ] y task\n* [ ] z task\n";
+ let Some(Block::Steps(s)) = first(text) else { panic!("{:?}", first(text)) };
+ assert_eq!(s.source.index, Some(1));
+}
+
+#[test]
+fn every_new_type_passes_its_checks() {
+ for text in [
+ table("| Month | Visits |", &rows(6, |i| format!("| {} 2025 | {} |", MONTHS[i], 100 + i))),
+ ranking(7, 2),
+ "- **Revenue:** $4.2M\n- **Uptime:** 98%\n".to_string(),
+ "Specs:\n- **Material:** aluminium\n- **Colour:** grey\n- **Size:** large\n".to_string(),
+ "Bugs:\n- [High] crash on start\n- Low: typo\n".to_string(),
+ "- [Tokio](https://tokio.rs) — an async runtime\n- [Serde](https://serde.rs) — serialization crate\n- [Axum](https://docs.rs/axum) — a web framework\n".to_string(),
+ ] {
+ let set = compute(&text).unwrap_or_else(|| panic!("no block: {text}"));
+ validate(&set, Some(&text)).unwrap_or_else(|e| panic!("{e:?}: {text}"));
+ }
+}
+
+/// Ada's call (2026-11-02): a bare high/low weather list is two key-number tiles, never findings.
+/// Pinned so a later change can't quietly turn it into findings or drop a tile.
+#[test]
+fn a_bare_weather_list_is_two_metric_tiles() {
+ let text = "- High: 18C\n- Low: 9C\n";
+ let Some(Block::Metrics(m)) = first(text) else { panic!("{:?}", first(text)) };
+ let tiles: Vec<_> = m.items.iter().map(|i| (i.label.as_str(), i.value_text.as_str(), i.value, i.unit.as_deref())).collect();
+ assert_eq!(tiles, [("High", "18C", 18.0, Some("C")), ("Low", "9C", 9.0, Some("C"))]);
+ assert!(candidates(text).iter().all(|b| b.kind() != "findings"));
+ let set = compute(text).unwrap();
+ validate(&set, Some(text)).unwrap();
+}
diff --git a/src/server/smart_results/chart.rs b/src/server/smart_results/chart.rs
new file mode 100644
index 00000000..7a855962
--- /dev/null
+++ b/src/server/smart_results/chart.rs
@@ -0,0 +1,465 @@
+//! Tables of numbers: line and bar charts, metrics tables, and the number and time readings the
+//! list selectors share (plan §A.4).
+
+use std::collections::HashSet;
+
+use super::selector::{currency, is_number, number_parts, plain, Table};
+use super::validate::has_html;
+use super::{Axis, AxisKind, Chart, ChartKind, Metric, Metrics, Point, Provenance, Series, Source};
+
+/// A table with 4–60 rows whose first column is time-like in every row and whose other 1–4
+/// columns are numbers of one unit.
+pub(super) fn line(t: &Table) -> Option<Chart> {
+ if !(4..=60).contains(&t.rows.len()) || !t.rows.iter().all(|r| time_like(r[0])) {
+ return None;
+ }
+ chart(t, ChartKind::Line, 1..=4)
+}
+
+/// A table with 5–20 rows, a text first column and 1–2 other columns of numbers of one unit. The
+/// caller turns it into a comparison instead when the reply names a pick.
+pub(super) fn bar(t: &Table) -> Option<Chart> {
+ if !(5..=20).contains(&t.rows.len()) {
+ return None;
+ }
+ if t.rows.iter().all(|r| time_like(r[0])) || t.rows.iter().any(|r| number_parts(r[0]).is_some()) {
+ return None;
+ }
+ chart(t, ChartKind::Bar, 1..=2)
+}
+
+fn chart(t: &Table, kind: ChartKind, series: std::ops::RangeInclusive<usize>) -> Option<Chart> {
+ let cols = t.header.len();
+ if !series.contains(&(cols - 1)) || !plain_cells(t) {
+ return None;
+ }
+ let mut columns = Vec::new();
+ for c in 1..cols {
+ columns.push(series_values(t.rows.iter().map(|r| r[c]))?);
+ }
+ // One axis: every series in the same unit, from its cells or else its header (SR-R-13)
+ let units: Vec<_> = (1..cols).map(|c| column_unit(columns[c - 1].0, t.header[c])).collect();
+ if units.windows(2).any(|w| w[0] != w[1]) {
+ return None;
+ }
+ let series = (1..cols)
+ .map(|c| Series { key: format!("s{}", c - 1), label: t.header[c].to_string(), unit: columns[c - 1].0.map(str::to_string) })
+ .collect();
+ let points = t
+ .rows
+ .iter()
+ .enumerate()
+ .map(|(i, r)| Point {
+ id: format!("p{i}"),
+ x: r[0].to_string(),
+ cells: r[1..].iter().map(|c| c.to_string()).collect(),
+ values: columns.iter().map(|(_, v)| v[i]).collect(),
+ })
+ .collect();
+ let axis = match kind {
+ ChartKind::Line => AxisKind::Time,
+ ChartKind::Bar => AxisKind::Category,
+ };
+ Some(Chart {
+ id: "b0".into(),
+ title: None,
+ source: Source::table(t.index),
+ chart_kind: kind,
+ x: Axis { label: t.header[0].to_string(), kind: axis },
+ series,
+ points,
+ summary: None,
+ provenance: Provenance::reply_text(),
+ })
+}
+
+/// The unit a column's numbers are in: the affix its cells share (`$`, `%`, `ms`), or for bare
+/// numbers the bracketed end of its header (`Price (EUR)`, `Rating [1-5]`). Compared as written,
+/// so `€` and `EUR` count as two units and the chart abstains.
+fn column_unit(affix: Option<&str>, header: &str) -> Option<String> {
+ if let Some(a) = affix {
+ return Some(a.trim().to_lowercase());
+ }
+ let h = header.trim().trim_matches(['*', '_', '`']).trim();
+ let (open, close) = match h.chars().last()? {
+ ')' => ('(', ')'),
+ ']' => ('[', ']'),
+ _ => return None,
+ };
+ let inner = h[..h.len() - close.len_utf8()].rsplit_once(open)?.1.trim();
+ (!inner.is_empty()).then(|| inner.to_lowercase())
+}
+
+/// Labels and cells a chart can show as they are: none empty in the header, none over 200
+/// characters, no HTML, no repeated label.
+fn plain_cells(t: &Table) -> bool {
+ if t.header.iter().any(|h| h.is_empty()) {
+ return false;
+ }
+ if t.header.iter().chain(t.rows.iter().flatten()).any(|c| c.chars().count() > 200 || has_html(c)) {
+ return false;
+ }
+ let mut seen = HashSet::new();
+ t.rows.iter().all(|r| {
+ let key = plain(r[0]).trim().to_lowercase();
+ !key.is_empty() && seen.insert(key)
+ })
+}
+
+/// Cells that hold no number: a gap in a chart, never a zero.
+fn gap(cell: &str) -> bool {
+ let c = cell.trim().trim_matches(['*', '_']).trim();
+ matches!(c.to_lowercase().as_str(), "" | "-" | "–" | "—" | "n/a" | "na" | "?" | "tbd")
+}
+
+/// A chart series: at least 80% of the cells are numbers with one affix (the unit), and the rest
+/// are gaps. `None` for anything else, a second unit or a number whose locale is unsure.
+fn series_values<'a>(cells: impl Iterator<Item = &'a str>) -> Option<(Option<&'a str>, Vec<Option<f64>>)> {
+ let mut unit: Option<Option<&str>> = None;
+ let mut numbers = Vec::new();
+ let mut slots = Vec::new();
+ for cell in cells {
+ if gap(cell) {
+ slots.push(None);
+ continue;
+ }
+ let (affix, number) = number_parts(cell)?;
+ match unit {
+ None => unit = Some(affix),
+ Some(u) if u != affix => return None,
+ Some(_) => {}
+ }
+ slots.push(Some(numbers.len()));
+ numbers.push(number);
+ }
+ if numbers.len() * 5 < slots.len() * 4 {
+ return None;
+ }
+ let values = column_values(&numbers)?;
+ Some((unit.flatten(), slots.into_iter().map(|s| s.map(|k| values[k])).collect()))
+}
+
+/// The numbers of one column as values, read with one locale for the whole column (`1,299.00`
+/// says `,` groups and `.` is the decimal point). `None` when the two readings both fit and
+/// disagree (`1,299` alone: 1299 or 1.299).
+pub(super) fn column_values(numbers: &[&str]) -> Option<Vec<f64>> {
+ let dot: Option<Vec<f64>> = numbers.iter().map(|n| reading(n, ',', '.')).collect();
+ let comma: Option<Vec<f64>> = numbers.iter().map(|n| reading(n, '.', ',')).collect();
+ match (dot, comma) {
+ (Some(d), Some(c)) => (d == c).then_some(d),
+ (Some(d), None) => Some(d),
+ (None, Some(c)) => Some(c),
+ (None, None) => None,
+ }
+}
+
+/// `n` as a number when `group` separates thousands and `decimal` marks the fraction.
+fn reading(n: &str, group: char, decimal: char) -> Option<f64> {
+ let (negative, n) = match n.strip_prefix(['-', '−']) {
+ Some(rest) => (true, rest),
+ None => (false, n.strip_prefix('+').unwrap_or(n)),
+ };
+ let (int, frac) = match n.split_once(decimal) {
+ Some((int, frac)) => (int, Some(frac)),
+ None => (n, None),
+ };
+ let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
+ if frac.is_some_and(|f| !digits(f)) {
+ return None;
+ }
+ let int_digits: String = if int.contains(group) {
+ let mut parts = int.split(group);
+ let first = parts.next()?;
+ if !(1..=3).contains(&first.len()) || !digits(first) {
+ return None;
+ }
+ let mut out = first.to_string();
+ for p in parts {
+ if p.len() != 3 || !digits(p) {
+ return None;
+ }
+ out.push_str(p);
+ }
+ out
+ } else if digits(int) {
+ int.to_string()
+ } else {
+ return None;
+ };
+ let text = match frac {
+ Some(f) => format!("{int_digits}.{f}"),
+ None => int_digits,
+ };
+ let v: f64 = text.parse().ok()?;
+ v.is_finite().then_some(if negative { -v } else { v })
+}
+
+/// A 2-column table of 2–6 rows whose second column is numbers in more than one unit. (With one
+/// shared unit it is a bar chart from 5 rows, and a comparison below that.)
+pub(super) fn metrics_table(t: &Table) -> Option<Metrics> {
+ if t.header.len() != 2 || !(2..=6).contains(&t.rows.len()) || !plain_cells(t) {
+ return None;
+ }
+ let mut items = Vec::new();
+ let mut units = HashSet::new();
+ for (i, r) in t.rows.iter().enumerate() {
+ if when_like(r[0]) || !r[0].chars().any(char::is_alphabetic) {
+ return None;
+ }
+ let v = metric_value(r[1])?;
+ units.insert(v.affixes);
+ items.push(Metric {
+ id: format!("m{i}"),
+ label: r[0].to_string(),
+ value_text: v.text.to_string(),
+ value: v.value,
+ unit: v.unit.map(str::to_string),
+ note: v.note.map(str::to_string),
+ });
+ }
+ if units.len() < 2 {
+ return None;
+ }
+ Some(Metrics { id: "b0".into(), title: None, source: Source::table(t.index), items, provenance: Provenance::reply_text() })
+}
+
+pub(super) struct MetricValue<'a> {
+ /// The value as written, affixes included (`$4.2M`).
+ pub text: &'a str,
+ pub value: f64,
+ /// The one affix when there is exactly one.
+ pub unit: Option<&'a str>,
+ /// Prefix and suffix as written, to tell units apart.
+ pub affixes: (Option<&'a str>, Option<&'a str>),
+ /// The rest of the text after the value, verbatim.
+ pub note: Option<&'a str>,
+}
+
+/// A value that starts `s`: an optional currency prefix (`$`, `EUR `), a number, an optional unit
+/// suffix (`%`, ` ms`, `M`), then the rest as the note. `None` when `s` doesn't start with one, or
+/// the number is a time, a range, a date or unsure in locale.
+pub(super) fn metric_value(s: &str) -> Option<MetricValue<'_>> {
+ let s = s.trim();
+ // A value in bold or code: `**$4.2M** up 8%`
+ for wrap in ["**", "__", "`"] {
+ if let Some(inner) = s.strip_prefix(wrap) {
+ let close = inner.find(wrap)?;
+ let v = metric_value(&inner[..close])?;
+ if v.note.is_some() {
+ return None;
+ }
+ let rest = inner[close + wrap.len()..].trim();
+ return Some(MetricValue { note: note(rest), ..v });
+ }
+ }
+ let b = s.as_bytes();
+ let mut i = 0;
+ let mut negative = take_sign(s, &mut i);
+ // Prefix: currency signs or capital letters (`$`, `US$`, `EUR `), at most 4
+ let p0 = i;
+ while let Some(c) = s[i..].chars().next() {
+ if currency(c) || c.is_ascii_uppercase() {
+ i += c.len_utf8();
+ } else {
+ break;
+ }
+ }
+ let prefix = (i > p0).then(|| &s[p0..i]);
+ if let Some(p) = prefix {
+ if p.chars().count() > 4 || !(p.chars().any(currency) || s[i..].starts_with(' ')) {
+ return None;
+ }
+ if s[i..].starts_with(' ') {
+ i += 1;
+ }
+ negative |= take_sign(s, &mut i);
+ }
+ let n0 = i;
+ while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || b[i] == b',') {
+ i += 1;
+ }
+ let number = s[n0..i].trim_end_matches(['.', ',']);
+ if !number.starts_with(|c: char| c.is_ascii_digit()) || !is_number(number) {
+ return None;
+ }
+ let mut end = n0 + number.len();
+ // A time, a range or a date is not a value
+ let after = &s[end..];
+ let digit_after = |a: &str| a.chars().nth(1).is_some_and(|c| c.is_ascii_digit());
+ if (after.starts_with(':') && digit_after(after))
+ || (after.starts_with(['-', '–', '/']) && digit_after(after) && !out_of(after))
+ {
+ return None;
+ }
+ let value = column_values(&[number])?[0];
+ let value = if negative { -value } else { value };
+ // Suffix: `%`, `/5`, or letters (at most 8), attached or after one space
+ let s1 = end;
+ let rest = &s[end..];
+ let take = if let Some(r) = rest.strip_prefix(['%', '‰']) {
+ rest.len() - r.len()
+ } else if out_of(rest) {
+ 1 + rest[1..].bytes().take_while(u8::is_ascii_digit).count()
+ } else {
+ let lead = usize::from(rest.starts_with(' '));
+ let word: usize = rest[lead..].chars().take_while(|c| c.is_alphabetic() || *c == '°').map(char::len_utf8).sum();
+ let unit = &rest[lead..lead + word];
+ let ends = rest[lead + word..].chars().next().is_none_or(|c| !c.is_alphanumeric());
+ let time = ["am", "pm", "a.m", "p.m"].contains(&unit.to_lowercase().as_str());
+ if time {
+ return None;
+ }
+ if word > 0 && unit.chars().count() <= 8 && ends && (lead == 0 || word <= 8) {
+ lead + word
+ } else {
+ 0
+ }
+ };
+ end += take;
+ let suffix = (end > s1).then(|| s[s1..end].trim_start());
+ let unit = match (prefix, suffix) {
+ (Some(p), None) => Some(p),
+ (None, Some(x)) => Some(x),
+ _ => None,
+ };
+ Some(MetricValue { text: &s[..end], value, unit, affixes: (prefix, suffix), note: note(&s[end..]) })
+}
+
+/// Steps past a leading `+`, `-` or `−`; true for a minus.
+fn take_sign(s: &str, i: &mut usize) -> bool {
+ let rest = &s[*i..];
+ if !rest.chars().nth(1).is_some_and(|c| c.is_ascii_digit() || currency(c) || c.is_ascii_uppercase()) {
+ return false;
+ }
+ match rest.chars().next() {
+ Some('+') => {
+ *i += 1;
+ false
+ }
+ Some('-') => {
+ *i += 1;
+ true
+ }
+ Some('−') => {
+ *i += '−'.len_utf8();
+ true
+ }
+ _ => false,
+ }
+}
+
+/// `/5` after a rating.
+fn out_of(s: &str) -> bool {
+ s.strip_prefix('/').is_some_and(|d| {
+ let n = d.bytes().take_while(u8::is_ascii_digit).count();
+ (1..=3).contains(&n) && !d[n..].starts_with(|c: char| c.is_alphanumeric() || c == '/')
+ })
+}
+
+/// The rest of an item after its value, without a leading separator; `None` when nothing is left.
+fn note(rest: &str) -> Option<&str> {
+ let r = rest.trim_start_matches([',', ';', ' ', '—', '–']).trim_start_matches("- ").trim();
+ (!r.is_empty()).then_some(r)
+}
+
+const MONTHS: [&str; 12] =
+ ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
+const DAYS: [&str; 7] = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
+
+/// Time-like for a chart axis (plan §A.4): an ISO date, YYYY-MM, a month name or abbreviation
+/// with an optional year, Q1–Q4 with an optional year, Week N, Day N, or a year 1900–2100.
+pub(super) fn time_like(cell: &str) -> bool {
+ let s = cell.trim().trim_matches(['*', '_']).trim();
+ let words: Vec<&str> = s.split_whitespace().collect();
+ match words.as_slice() {
+ [w] => year(w) || iso(w) || month(w) || quarter(w),
+ [a, b] => {
+ (month(a) && year(b))
+ || (quarter(a) && year(b))
+ || (year(a) && quarter(b))
+ || ((a.eq_ignore_ascii_case("week") || a.eq_ignore_ascii_case("day")) && small(b))
+ }
+ _ => false,
+ }
+}
+
+/// Time-like for a timeline label: [`time_like`], or a clock time (`9:00`, `9:30 am`, `14:00`), a
+/// span of two (`9:00–10:00`), a weekday (`Mon`, `Friday`) or a month and day (`Jan 5`).
+pub(super) fn when_like(label: &str) -> bool {
+ let s = label.trim().trim_matches(['*', '_']).trim();
+ if time_like(s) {
+ return true;
+ }
+ if let Some((a, b)) = s.split_once(['–', '—', '-']) {
+ if clock(a.trim()) && clock(b.trim()) {
+ return true;
+ }
+ }
+ if clock(s) {
+ return true;
+ }
+ let words: Vec<&str> = s.split_whitespace().collect();
+ match words.as_slice() {
+ [w] => weekday(w),
+ [m, d] => month(m) && small(d.trim_end_matches(',')) && d.trim_end_matches(',').parse::<u32>().is_ok_and(|n| (1..=31).contains(&n)),
+ [m, d, y] => month(m) && d.trim_end_matches(',').parse::<u32>().is_ok_and(|n| (1..=31).contains(&n)) && year(y),
+ _ => false,
+ }
+}
+
+fn year(w: &str) -> bool {
+ w.len() == 4 && w.parse::<u32>().is_ok_and(|y| (1900..=2100).contains(&y))
+}
+
+fn small(w: &str) -> bool {
+ (1..=3).contains(&w.len()) && w.bytes().all(|b| b.is_ascii_digit())
+}
+
+fn iso(w: &str) -> bool {
+ let parts: Vec<&str> = w.split('-').collect();
+ let num = |p: &str, len: usize| p.len() == len && p.bytes().all(|b| b.is_ascii_digit());
+ match parts.as_slice() {
+ [y, m] => year(y) && num(m, 2) && (1..=12).contains(&m.parse::<u32>().unwrap_or(0)),
+ [y, m, d] => {
+ year(y)
+ && num(m, 2)
+ && num(d, 2)
+ && (1..=12).contains(&m.parse::<u32>().unwrap_or(0))
+ && (1..=31).contains(&d.parse::<u32>().unwrap_or(0))
+ }
+ _ => false,
+ }
+}
+
+fn month(w: &str) -> bool {
+ let w = w.trim_end_matches('.').to_lowercase();
+ w.len() >= 3 && MONTHS.iter().any(|m| *m == w || (m.starts_with(&w) && (w.len() == 3 || w == "sept")))
+}
+
+fn weekday(w: &str) -> bool {
+ let w = w.trim_end_matches('.').to_lowercase();
+ w.len() >= 3 && DAYS.iter().any(|d| *d == w || (d.starts_with(&w) && w.len() <= 4))
+}
+
+fn quarter(w: &str) -> bool {
+ let w = w.to_ascii_uppercase();
+ matches!(w.as_str(), "Q1" | "Q2" | "Q3" | "Q4")
+}
+
+/// `9:00`, `14:30`, `9:00 am`, `9am`, `9 pm`.
+fn clock(s: &str) -> bool {
+ let lower = s.to_lowercase();
+ let (time, meridiem) = match lower.strip_suffix("am").or_else(|| lower.strip_suffix("pm")) {
+ Some(t) => (t.trim_end().to_string(), true),
+ None => (lower.clone(), false),
+ };
+ match time.split_once(':') {
+ Some((h, m)) => {
+ h.len() <= 2
+ && m.len() == 2
+ && h.parse::<u32>().is_ok_and(|h| h <= if meridiem { 12 } else { 23 })
+ && m.parse::<u32>().is_ok_and(|m| m <= 59)
+ }
+ None => meridiem && time.len() <= 2 && time.parse::<u32>().is_ok_and(|h| (1..=12).contains(&h)),
+ }
+}
diff --git a/src/server/smart_results/items.rs b/src/server/smart_results/items.rs
new file mode 100644
index 00000000..e0440a80
--- /dev/null
+++ b/src/server/smart_results/items.rs
@@ -0,0 +1,419 @@
+//! Top-level lists: metrics, findings, cards, timeline, checklist and facts, and the steps block
+//! every steps variant shares (plan §A.4). Every value is a slice of the item as written.
+
+use super::chart::{metric_value, when_like};
+use super::selector::{is_task, words, List};
+use super::validate::has_html;
+use super::{
+ Card, Cards, Fact, Facts, Finding, Findings, Metric, Metrics, Provenance, Ref, Severity, Source, Step, Steps,
+ Variant,
+};
+
+fn source(l: &List) -> Source {
+ Source::list(l.index, l.ordered)
+}
+
+/// Items no selector reads: empty, over 300 characters or with HTML in them.
+fn plain_items(l: &List) -> bool {
+ l.items.iter().all(|t| !t.is_empty() && t.chars().count() <= 300 && !has_html(t))
+}
+
+/// A label and the text after it.
+struct Labeled<'a> {
+ label: &'a str,
+ rest: &'a str,
+ bold: bool,
+ /// `:`, or `–` / `—` for a dash.
+ sep: char,
+}
+
+/// `**Label:** rest`, `**Label**: rest`, `**Label** – rest`, `Label: rest`, `Label – rest`.
+fn labeled(item: &str) -> Option<Labeled<'_>> {
+ let (label, rest, bold, sep) = if let Some(inner) = item.strip_prefix("**") {
+ let close = inner.find("**")?;
+ let (label, after) = (&inner[..close], &inner[close + 2..]);
+ if let Some(l) = label.strip_suffix(':') {
+ (l, after.strip_prefix(' ')?, true, ':')
+ } else if let Some(r) = after.strip_prefix(':') {
+ (label, r.strip_prefix(' ')?, true, ':')
+ } else if let Some(r) = after.strip_prefix(" – ").or_else(|| after.strip_prefix(" - ")) {
+ (label, r, true, '–')
+ } else {
+ (label, after.strip_prefix(" — ")?, true, '—')
+ }
+ } else {
+ let at = [": ", " – ", " — "].iter().filter_map(|sep| item.find(sep).map(|i| (i, *sep))).min()?;
+ let (i, sep) = at;
+ let label = &item[..i];
+ if label.contains(['*', '[', ']', '`', '_']) || label.split_whitespace().count() > 5 {
+ return None;
+ }
+ (label, &item[i + sep.len()..], false, sep.trim().chars().next().unwrap_or(':'))
+ };
+ let label = label.trim();
+ let rest = rest.trim();
+ if label.is_empty() || rest.is_empty() || label.chars().count() > 60 || !label.chars().any(char::is_alphanumeric) {
+ return None;
+ }
+ Some(Labeled { label, rest, bold, sep })
+}
+
+/// Intro or heading words that make "**Label:** number" lines a list of things to get, not key
+/// numbers.
+const NOT_METRICS: [&str; 12] =
+ ["ingredients", "ingredient", "recipe", "shopping", "groceries", "packing", "pack", "bring", "need", "serves", "schedule", "agenda"];
+
+fn lead_words(l: &List) -> Vec<String> {
+ let mut w = l.intro.map(words).unwrap_or_default();
+ w.extend(l.heading.map(words).unwrap_or_default());
+ w
+}
+
+/// 2–6 items, each "**Label:** value" or "Label: value" whose value starts with a number or a
+/// currency; the rest of the item is the note.
+pub(super) fn metrics(l: &List) -> Option<Metrics> {
+ if !(2..=6).contains(&l.items.len()) || !plain_items(l) || l.items.iter().any(|t| is_task(t)) {
+ return None;
+ }
+ if lead_words(l).iter().any(|w| NOT_METRICS.contains(&w.as_str())) {
+ return None;
+ }
+ let mut items = Vec::new();
+ for (i, t) in l.items.iter().enumerate() {
+ let x = labeled(t).filter(|x| x.sep == ':')?;
+ if when_like(x.label) || x.label.starts_with(|c: char| c.is_ascii_digit()) {
+ return None;
+ }
+ let v = metric_value(x.rest)?;
+ items.push(Metric {
+ id: format!("m{i}"),
+ label: x.label.to_string(),
+ value_text: v.text.to_string(),
+ value: v.value,
+ unit: v.unit.map(str::to_string),
+ note: v.note.map(str::to_string),
+ });
+ }
+ Some(Metrics { id: "b0".into(), title: None, source: source(l), items, provenance: Provenance::reply_text() })
+}
+
+/// 3–12 items, each "**Label:** value", more than half of them not starting with a number.
+pub(super) fn facts(l: &List) -> Option<Facts> {
+ if !(3..=12).contains(&l.items.len()) || !plain_items(l) || l.items.iter().any(|t| is_task(t)) {
+ return None;
+ }
+ let mut items = Vec::new();
+ let mut numeric = 0;
+ for (i, t) in l.items.iter().enumerate() {
+ let x = labeled(t).filter(|x| x.bold && x.sep == ':')?;
+ if metric_value(x.rest).is_some() {
+ numeric += 1;
+ }
+ items.push(Fact { id: format!("f{i}"), label: x.label.to_string(), value: x.rest.to_string() });
+ }
+ if numeric * 2 >= items.len() {
+ return None;
+ }
+ Some(Facts { id: "b0".into(), title: None, source: source(l), items, provenance: Provenance::reply_text() })
+}
+
+/// 3–12 items, each `[Title](https://…)` or `**Title**`, then " — ", " – " or " - " (or ": "
+/// after a link), then a description of at least 10 characters. `**Title:** text` reads as facts.
+pub(super) fn cards(l: &List) -> Option<Cards> {
+ if !(3..=12).contains(&l.items.len()) || !plain_items(l) || l.items.iter().any(|t| is_task(t)) {
+ return None;
+ }
+ let mut items = Vec::new();
+ for (i, t) in l.items.iter().enumerate() {
+ let (title, url, rest) = card_head(t)?;
+ let mut description = None;
+ for sep in [" — ", " – ", " - "] {
+ if let Some(d) = rest.strip_prefix(sep) {
+ description = Some(d);
+ }
+ }
+ if url.is_some() {
+ if let Some(d) = rest.strip_prefix(": ") {
+ description = Some(d);
+ }
+ }
+ let description = description?.trim();
+ if description.chars().count() < 10 || title.trim().is_empty() || title.chars().count() > 200 {
+ return None;
+ }
+ items.push(Card {
+ id: format!("k{i}"),
+ title: title.to_string(),
+ url: url.map(str::to_string),
+ description: description.to_string(),
+ meta: Vec::new(),
+ });
+ }
+ Some(Cards { id: "b0".into(), title: None, source: source(l), items, provenance: Provenance::reply_text() })
+}
+
+/// The item's title, its link (https only) and the text after them.
+fn card_head(t: &str) -> Option<(&str, Option<&str>, &str)> {
+ // `**[Title](url)**` reads like `[Title](url)`
+ let (inner, wrapped) = match t.strip_prefix("**").filter(|r| r.starts_with('[')) {
+ Some(r) => (r, true),
+ None => (t, false),
+ };
+ if let Some(r) = inner.strip_prefix('[') {
+ let close = r.find("](")?;
+ let title = &r[..close];
+ let after = &r[close + 2..];
+ let end = after.find(')')?;
+ let url = &after[..end];
+ let mut rest = &after[end + 1..];
+ if wrapped {
+ rest = rest.strip_prefix("**")?;
+ }
+ if title.contains(['[', ']']) || !url.starts_with("https://") || url.len() <= 8 {
+ return None;
+ }
+ if url.contains(|c: char| c.is_whitespace() || matches!(c, '(' | '<' | '>' | '"' | '\'' | '`')) {
+ return None;
+ }
+ // Link text that looks like another address would hide where the link goes
+ let looks_like_url = title.contains("://") || title.trim_start().to_lowercase().starts_with("www.");
+ if looks_like_url && title.trim() != url {
+ return None;
+ }
+ return Some((title, Some(url), rest));
+ }
+ let r = t.strip_prefix("**")?;
+ let close = r.find("**")?;
+ let title = &r[..close];
+ if title.ends_with(':') || title.contains('[') {
+ return None;
+ }
+ Some((title, None, &r[close + 2..]))
+}
+
+/// Words in the line before a list, or the heading above it, that say it is a review.
+const REVIEW_WORDS: [&str; 15] = [
+ "review", "reviewed", "audit", "audited", "finding", "findings", "issue", "issues", "bug", "bugs", "risk", "risks",
+ "vulnerability", "vulnerabilities", "problems",
+];
+
+/// 2–30 items that each start with a severity token (bold, bracketed or followed by ":"), when
+/// the list is introduced as a review or at least one item names a `path:line` in code. An item
+/// whose text after the token starts with a number ("High: 18C") keeps the whole list text.
+pub(super) fn findings(l: &List) -> Option<Findings> {
+ if !(2..=30).contains(&l.items.len()) || !plain_items(l) || l.items.iter().any(|t| is_task(t)) {
+ return None;
+ }
+ let mut items = Vec::new();
+ for (i, t) in l.items.iter().enumerate() {
+ let (severity, token, text) = severity_lead(t)?;
+ let first = text.trim_start_matches(['*', '_', '`']);
+ let mut chars = first.chars();
+ let c0 = chars.next()?;
+ let numbered = c0.is_ascii_digit()
+ || (matches!(c0, '+' | '-' | '−' | '~' | '$' | '€' | '£') && chars.next().is_some_and(|c| c.is_ascii_digit()));
+ if numbered {
+ return None;
+ }
+ let (title, detail) = title_detail(text);
+ if title.is_empty() {
+ return None;
+ }
+ items.push(Finding {
+ id: format!("x{i}"),
+ severity,
+ severity_text: token.to_string(),
+ title: title.to_string(),
+ detail: detail.to_string(),
+ refs: refs(t),
+ });
+ }
+ let signal = lead_words(l).iter().any(|w| REVIEW_WORDS.contains(&w.as_str())) || items.iter().any(|f| !f.refs.is_empty());
+ if !signal {
+ return None;
+ }
+ Some(Findings { id: "b0".into(), title: None, source: source(l), items, provenance: Provenance::reply_text() })
+}
+
+/// The severity a reply's own token stands for; `None` for any other word.
+pub(super) fn severity_of(token: &str) -> Option<Severity> {
+ Some(match token.to_ascii_lowercase().as_str() {
+ "critical" | "blocker" | "p0" => Severity::Critical,
+ "high" | "major" | "p1" => Severity::High,
+ "medium" | "moderate" | "p2" => Severity::Medium,
+ "low" | "minor" | "p3" => Severity::Low,
+ "info" | "nit" => Severity::Info,
+ _ => return None,
+ })
+}
+
+/// `**High**`, `**High:**`, `**High**:`, `[High]`, `**[High]**` or `High:` at the start of `t`:
+/// the severity, the token as written and the text after it.
+fn severity_lead(t: &str) -> Option<(Severity, &str, &str)> {
+ let (s, bold) = match t.strip_prefix("**") {
+ Some(r) => (r, true),
+ None => (t, false),
+ };
+ let (s, bracket) = match s.strip_prefix('[') {
+ Some(r) => (r, true),
+ None => (s, false),
+ };
+ let len = s.bytes().take_while(u8::is_ascii_alphanumeric).count();
+ let token = &s[..len];
+ let severity = severity_of(token)?;
+ let mut rest = &s[len..];
+ let mut marked = false;
+ if bracket {
+ rest = rest.strip_prefix(']')?;
+ marked = true;
+ }
+ if bold {
+ let colon = rest.strip_prefix(':');
+ rest = colon.unwrap_or(rest).strip_prefix("**")?;
+ marked = true;
+ }
+ if let Some(r) = rest.strip_prefix(':') {
+ rest = r;
+ marked = true;
+ }
+ if !marked || !rest.starts_with([' ', '\u{a0}']) && !rest.is_empty() {
+ return None;
+ }
+ let text = rest.trim_start_matches([' ', '-', '–', '—', ':']).trim();
+ (!text.is_empty()).then_some((severity, token, text))
+}
+
+/// A finding's title and detail: the bold lead, or the text before the first " — ", " – ",
+/// " - ", ": " or ". "; the whole text when there is none.
+fn title_detail(text: &str) -> (&str, &str) {
+ if let Some(r) = text.strip_prefix("**") {
+ if let Some(close) = r.find("**") {
+ let detail = r[close + 2..].trim_start_matches([' ', '-', '–', '—', ':', '.']).trim();
+ return (r[..close].trim(), detail);
+ }
+ }
+ let at = [" — ", " – ", " - ", ": ", ". "].iter().filter_map(|sep| text.find(sep).map(|i| (i, sep.len()))).min();
+ match at {
+ Some((i, n)) if !text[i + n..].trim().is_empty() => (text[..i].trim(), text[i + n..].trim()),
+ _ => (text, ""),
+ }
+}
+
+/// `path/to/file.ext:123` in code spans: a path with a file extension, never a URL, a port or a
+/// Windows path.
+fn refs(t: &str) -> Vec<Ref> {
+ let mut out = Vec::new();
+ for (k, span) in t.split('`').enumerate() {
+ if k % 2 == 0 || span.contains(char::is_whitespace) || span.contains("://") || span.contains('\\') {
+ continue;
+ }
+ let Some((path, line)) = span.rsplit_once(':') else { continue };
+ let digits = line.bytes().take_while(u8::is_ascii_digit).count();
+ if digits == 0 || !(line[digits..].is_empty() || line[digits..].starts_with('-')) {
+ continue;
+ }
+ let name = path.rsplit('/').next().unwrap_or(path);
+ let ext = name.rsplit_once('.');
+ let good_ext = ext.is_some_and(|(stem, ext)| {
+ !stem.is_empty() && (1..=8).contains(&ext.len()) && ext.bytes().all(|b| b.is_ascii_alphanumeric()) && ext.bytes().any(|b| b.is_ascii_alphabetic())
+ });
+ let path_chars = path.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'/' | b'-'));
+ if !good_ext || !path_chars || path.to_ascii_lowercase().starts_with("localhost") {
+ continue;
+ }
+ if out.len() < 10 {
+ out.push(Ref { path: path.to_string(), line: line[..digits].parse().ok() });
+ }
+ }
+ out
+}
+
+/// 3–15 items that each start with a time-like label and ":", "–" or "—"; the label is `when`.
+/// A task box in front of every item is left out of the text.
+pub(super) fn timeline(l: &List) -> Option<Steps> {
+ if !(3..=15).contains(&l.items.len()) || !plain_items(l) {
+ return None;
+ }
+ let all_tasks = l.items.iter().all(|t| task(t).is_some());
+ let mut items = Vec::new();
+ for t in &l.items {
+ let body = if all_tasks { task(t)?.1 } else { t };
+ let x = labeled(body)?;
+ if !when_like(x.label) {
+ return None;
+ }
+ items.push((x.rest.to_string(), None, Some(x.label.to_string())));
+ }
+ Some(steps_block(l, Variant::Timeline, items))
+}
+
+/// A task list of 3–20 items (`- [ ]` / `- [x]`, numbered or not); `done` comes from the box.
+pub(super) fn checklist(l: &List) -> Option<Steps> {
+ if !(3..=20).contains(&l.items.len()) || !plain_items(l) {
+ return None;
+ }
+ let items = l
+ .items
+ .iter()
+ .map(|t| task(t).map(|(done, text)| (text.to_string(), Some(done), None)))
+ .collect::<Option<Vec<_>>>()?;
+ Some(steps_block(l, Variant::Checklist, items))
+}
+
+/// A task item: whether it is checked, and its text. A box with no text after it is a plain item.
+fn task(t: &str) -> Option<(bool, &str)> {
+ let done = match t.get(..3)? {
+ "[ ]" => false,
+ "[x]" | "[X]" => true,
+ _ => return None,
+ };
+ let text = t[3..].strip_prefix(' ')?.trim();
+ (!text.is_empty()).then_some((done, text))
+}
+
+/// A steps block of any variant from `(text, done, when)` per item; `owner` only from a literal
+/// "Owner: X" or "(owner: X)" in the text.
+pub(super) fn steps_block(l: &List, variant: Variant, items: Vec<(String, Option<bool>, Option<String>)>) -> Steps {
+ let items = items
+ .into_iter()
+ .enumerate()
+ .map(|(i, (text, done, when))| {
+ let owner = owner_of(&text).map(str::to_string);
+ Step { id: format!("s{i}"), text, done, when, owner }
+ })
+ .collect();
+ Steps { id: "b0".into(), title: None, source: source(l), variant, items, provenance: Provenance::reply_text() }
+}
+
+/// The name in "(owner: X)", "(Owner: X)", or "Owner: X" / "owner: X" running to the end of the
+/// item; at most 40 characters and 4 words.
+pub(super) fn owner_of(text: &str) -> Option<&str> {
+ for open in ["(owner: ", "(Owner: "] {
+ if let Some(i) = text.find(open) {
+ let r = &text[i + open.len()..];
+ let end = r.find(')')?;
+ return name(&r[..end]);
+ }
+ }
+ for open in ["Owner: ", "owner: "] {
+ if let Some(i) = text.find(open) {
+ let before = text[..i].chars().next_back();
+ if before.is_some_and(|c| c.is_alphanumeric()) {
+ continue;
+ }
+ let r = text[i + open.len()..].trim_end().trim_end_matches('.');
+ return name(r);
+ }
+ }
+ None
+}
+
+fn name(s: &str) -> Option<&str> {
+ let s = s.trim();
+ let ok = !s.is_empty()
+ && s.chars().count() <= 40
+ && s.split_whitespace().count() <= 4
+ && !has_html(s)
+ && !s.contains(['*', '[', ']', '`', ':', '(', ')']);
+ ok.then_some(s)
+}
diff --git a/src/server/smart_results/mod.rs b/src/server/smart_results/mod.rs
index c9804d98..57d615a0 100644
--- a/src/server/smart_results/mod.rs
+++ b/src/server/smart_results/mod.rs
@@ -1,5 +1,6 @@
-//! Smart Results (0.6.5): a table or a numbered list in a bot's final reply, kept as a typed
-//! block the chat can draw as a comparison card or a checklist. Contract: docs/smart-results.md.
+//! Smart Results (0.6.5): a table or a list in a bot's final reply, kept as one typed block the
+//! chat can draw as a chart, a comparison, metric tiles, findings, cards, a checklist, a timeline,
+//! steps or facts. Contract: docs/smart-results.md.
//!
//! - The reply's text is never changed. The block set lives beside it in `message_results`,
//! written when the reply is saved ([`crate::db::Database::insert_message_with`]), and every
@@ -7,13 +8,17 @@
//! - It always runs; there is no setting. The release fallback is [`ENABLED_TYPES`].
//! - The selectors are deterministic (no model calls) and conservative: when one isn't sure the
//! chat would render the same table or list, it abstains and the reply stays markdown.
+//! - Every value is copied from the reply. The only numbers a block adds are the cells' own
+//! values, parsed (`chart` points, `metrics` items); nothing is summed, averaged or rounded.
//! - Nothing here may cost the reply: a panic, an invalid block or a failed write is logged and
//! the message is saved as it always was.
+mod chart;
+mod items;
mod selector;
mod validate;
-pub use selector::candidates;
+pub use selector::{candidates, rank, PRIORITY};
pub use validate::validate;
use serde::{Deserialize, Serialize};
@@ -21,7 +26,7 @@ use serde::{Deserialize, Serialize};
/// The block types this build stores and serves. Taking a type out (a one-line release fallback)
/// stops new blocks of it and hides stored ones (`results: null`); the chat then shows the
/// reply's markdown.
-pub const ENABLED_TYPES: &[&str] = &["comparison", "steps"];
+pub const ENABLED_TYPES: &[&str] = &["chart", "comparison", "metrics", "findings", "cards", "steps", "facts"];
/// The payload version this build writes and reads.
pub const VERSION: u32 = 1;
/// Largest stored payload, in bytes of JSON.
@@ -30,9 +35,13 @@ pub const MAX_PAYLOAD: usize = 64 * 1024;
pub const MAX_REPLY: usize = 128 * 1024;
/// Why a row is highlighted; the only reason v1 gives.
pub const PICK_REASON: &str = "named as the pick in this reply";
+/// The one line of the bot system prompt that asks for structure the selectors can read (plan
+/// §A.4). It is in every bot's system prompt once (`drivers::TurnInput::system_prompt_parts`).
+pub const PROMPT_LINE: &str = "When you compare 3 or more options use a table, for steps use a numbered list, and for key \
+ numbers use '**Label:** value' lines; kwant shows them as cards and charts.";
-/// The checked block set for a reply: the first candidate, in priority order, whose type is
-/// enabled and that passes [`validate`]; `None` when there isn't one. A selector bug must never
+/// The checked block set for a reply: the first candidate, in priority order ([`rank`]), whose
+/// type is enabled and that passes [`validate`]; `None` when there isn't one. A selector bug must never
/// cost the reply, so a panic is caught and logged.
pub fn compute(text: &str) -> Option<ResultSet> {
let run = std::panic::catch_unwind(|| {
@@ -61,35 +70,120 @@ pub struct ResultSet {
pub blocks: Vec<Block>,
}
+/// One block; every type has `id`, `title`, `source` and `provenance` (plan §A.3).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Block {
+ Chart(Chart),
Comparison(Comparison),
+ Metrics(Metrics),
+ Findings(Findings),
+ Cards(Cards),
Steps(Steps),
+ Facts(Facts),
}
impl Block {
/// The block's `type`.
pub fn kind(&self) -> &'static str {
match self {
+ Block::Chart(_) => "chart",
Block::Comparison(_) => "comparison",
+ Block::Metrics(_) => "metrics",
+ Block::Findings(_) => "findings",
+ Block::Cards(_) => "cards",
Block::Steps(_) => "steps",
+ Block::Facts(_) => "facts",
}
}
+
+ pub fn id(&self) -> &str {
+ common!(self, b => &b.id)
+ }
+
+ pub fn title(&self) -> Option<&str> {
+ common!(self, b => b.title.as_deref())
+ }
+
+ pub fn source(&self) -> &Source {
+ common!(self, b => &b.source)
+ }
+
+ pub fn provenance(&self) -> &Provenance {
+ common!(self, b => &b.provenance)
+ }
+}
+
+/// `$e` for whichever block type `$block` is, bound as `$b`: the fields every type has.
+macro_rules! common {
+ ($block:expr, $b:ident => $e:expr) => {
+ match $block {
+ Block::Chart($b) => $e,
+ Block::Comparison($b) => $e,
+ Block::Metrics($b) => $e,
+ Block::Findings($b) => $e,
+ Block::Cards($b) => $e,
+ Block::Steps($b) => $e,
+ Block::Facts($b) => $e,
+ }
+ };
}
+use common;
-/// Which table (`markdown_table`) or ordered list (`markdown_list`) of the reply a block stands
-/// for: `index` counts them in the order the chat renders them, from 0.
+/// Which table or list of the reply a block stands for, or `slot` (no source in the text: the
+/// chat draws it after the reply). `index` counts in the order the chat renders them, from 0:
+/// tables in one count, numbered lists in another, bullet lists (`ordered: false`) in a third.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Source {
+ /// `markdown_table`, `markdown_list` or `slot`.
pub kind: String,
- pub index: usize,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub index: Option<usize>,
+ /// Lists only; absent means `true` (v1).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ordered: Option<bool>,
+}
+
+impl Source {
+ pub fn table(index: usize) -> Self {
+ Source { kind: "markdown_table".into(), index: Some(index), ordered: None }
+ }
+ pub fn list(index: usize, ordered: bool) -> Self {
+ Source { kind: "markdown_list".into(), index: Some(index), ordered: Some(ordered) }
+ }
+ pub fn slot() -> Self {
+ Source { kind: "slot".into(), index: None, ordered: None }
+ }
}
-/// Where the values came from; v1 only copies them from the reply (`reply_text`).
+/// Where the values came from: copied from the reply (`reply_text`), declared by the bot with
+/// `present_result` and grounded against the reply (`bot_declared`, with `tool_call_id`), or typed
+/// kwant data (`kwant_data`, with `ref` "task:<id>" or "attachment:<id>").
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Provenance {
pub kind: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub tool_call_id: Option<String>,
+ #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")]
+ pub reference: Option<String>,
+}
+
+impl Provenance {
+ pub fn reply_text() -> Self {
+ Provenance { kind: "reply_text".into(), tool_call_id: None, reference: None }
+ }
+}
+
+/// What a comparison column holds; absent (v1) means `label` for the first column and `value`
+/// for the rest.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Role {
+ Label,
+ Value,
+ Pros,
+ Cons,
+ Note,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -98,6 +192,8 @@ pub struct Column {
pub label: String,
pub numeric: bool,
pub unit: Option<String>,
+ #[serde(default)]
+ pub role: Option<Role>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -106,9 +202,12 @@ pub struct Row {
pub cells: Vec<String>,
}
+/// A table: 2–8 columns, 3–50 rows.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Comparison {
pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
pub source: Source,
pub columns: Vec<Column>,
pub rows: Vec<Row>,
@@ -117,16 +216,192 @@ pub struct Comparison {
pub provenance: Provenance,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ChartKind {
+ Line,
+ Bar,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum AxisKind {
+ Time,
+ Category,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Axis {
+ pub label: String,
+ pub kind: AxisKind,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Series {
+ pub key: String,
+ pub label: String,
+ pub unit: Option<String>,
+}
+
+/// One table row: `x` is its first cell, `cells` the others (one per series), verbatim, and
+/// `values` the same cells as numbers (`null` where a cell has none: a gap, never a zero).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Point {
+ pub id: String,
+ pub x: String,
+ pub cells: Vec<String>,
+ pub values: Vec<Option<f64>>,
+}
+
+/// A table of numbers: 1–4 series, 3–60 points.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Chart {
+ pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
+ pub source: Source,
+ pub chart_kind: ChartKind,
+ pub x: Axis,
+ pub series: Vec<Series>,
+ pub points: Vec<Point>,
+ /// Quotes cells only, never a computed number; the selectors leave it `null`.
+ pub summary: Option<String>,
+ pub provenance: Provenance,
+}
+
+/// `value_text` is what the reply says ("$4.2M") and what the chat shows; `value` is its number as
+/// written (4.2), `unit` its one affix when it has exactly one, `note` the rest of the item.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Metric {
+ pub id: String,
+ pub label: String,
+ pub value_text: String,
+ pub value: f64,
+ pub unit: Option<String>,
+ pub note: Option<String>,
+}
+
+/// Key numbers: 2–6 items.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Metrics {
+ pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
+ pub source: Source,
+ pub items: Vec<Metric>,
+ pub provenance: Provenance,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Fact {
+ pub id: String,
+ pub label: String,
+ pub value: String,
+}
+
+/// Labelled values: 3–12 items.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Facts {
+ pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
+ pub source: Source,
+ pub items: Vec<Fact>,
+ pub provenance: Provenance,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Variant {
+ #[default]
+ Steps,
+ Checklist,
+ Timeline,
+}
+
+/// `done` is set for a checklist only, `when` for a timeline (every item), `owner` only from a
+/// literal "Owner: X" or "(owner: X)". `text` is the item as written, after any `[ ]` box or time
+/// label.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Step {
pub id: String,
pub text: String,
+ #[serde(default)]
+ pub done: Option<bool>,
+ #[serde(default)]
+ pub when: Option<String>,
+ #[serde(default)]
+ pub owner: Option<String>,
}
+/// A list to follow: 3–20 items.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Steps {
pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
pub source: Source,
+ #[serde(default)]
+ pub variant: Variant,
pub items: Vec<Step>,
pub provenance: Provenance,
}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Card {
+ pub id: String,
+ pub title: String,
+ /// An http(s) link of the reply, or `null`.
+ pub url: Option<String>,
+ pub description: String,
+ pub meta: Vec<String>,
+}
+
+/// Links or named options with a description: 3–12 items.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Cards {
+ pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
+ pub source: Source,
+ pub items: Vec<Card>,
+ pub provenance: Provenance,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Severity {
+ Critical,
+ High,
+ Medium,
+ Low,
+ Info,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Ref {
+ pub path: String,
+ pub line: Option<u32>,
+}
+
+/// `severity_text` is the reply's own token ("Blocker", "P1", "Nit"); `detail` may be empty.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Finding {
+ pub id: String,
+ pub severity: Severity,
+ pub severity_text: String,
+ pub title: String,
+ pub detail: String,
+ pub refs: Vec<Ref>,
+}
+
+/// Review or audit results: 2–30 items, in the reply's order.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Findings {
+ pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
+ pub source: Source,
+ pub items: Vec<Finding>,
+ pub provenance: Provenance,
+}
diff --git a/src/server/smart_results/selector.rs b/src/server/smart_results/selector.rs
index 08057b95..7140df86 100644
--- a/src/server/smart_results/selector.rs
+++ b/src/server/smart_results/selector.rs
@@ -1,61 +1,125 @@
-//! The selector: the first comparison table, else the first steps list, of a reply.
+//! The reader and the selectors: every table and top-level list of a reply that could be shown as
+//! a block, in priority order.
//!
//! A line-by-line reading of CommonMark + GFM that is exact for the shapes bots write (top-level
-//! pipe tables and numbered lists, fenced code) and abstains on the rest. `index` must name the
-//! same table or list the chat's remark-gfm renders, so anything that could make the count
-//! uncertain (a table or numbered list inside a quote or a bullet item, a list nested in a list,
-//! raw HTML, tabs, a table run straight into a paragraph or another block) marks the reply
-//! uncertain from that line on, and no block is offered at or after it.
+//! pipe tables, numbered and bullet lists, fenced code) and abstains on the rest. `index` must name
+//! the same table or list the chat's remark-gfm renders (smart-results-goals/index-rule.md), so
+//! anything that could make a count uncertain (a table or list inside a quote or an item, raw
+//! HTML, tabs, a table run straight into a paragraph or another block, footnotes) marks that count
+//! uncertain from that line on, and no block of that kind is offered at or after it.
use std::cell::OnceCell;
use std::collections::HashSet;
use super::validate::has_html;
-use super::{Block, Column, Comparison, Provenance, Row, Source, Step, Steps, MAX_REPLY, PICK_REASON};
+use super::{chart, items};
+use super::{Block, Column, Comparison, Provenance, Role, Row, Source, Steps, Variant, MAX_REPLY, PICK_REASON};
-/// Every block `text` could show, in priority order and unchecked (see [`super::compute`]): each
-/// qualifying table as a comparison, then each qualifying numbered list as steps, earliest first.
+/// The order types win in when a reply has more than one candidate (plan §A.2), best first.
+/// `present_result`, `verification` and `files` come from typed sources, not from these selectors.
+pub const PRIORITY: &[&str] =
+ &["present_result", "verification", "chart", "comparison", "metrics", "findings", "cards", "steps", "facts", "files"];
+
+/// Where `block` stands in [`PRIORITY`] (lower wins); steps rank timeline, then checklist, then
+/// plain steps.
+pub fn rank(block: &Block) -> (usize, u8) {
+ let at = PRIORITY.iter().position(|t| *t == block.kind()).unwrap_or(PRIORITY.len());
+ let sub = match block {
+ Block::Steps(s) => match s.variant {
+ Variant::Timeline => 0,
+ Variant::Checklist => 1,
+ Variant::Steps => 2,
+ },
+ _ => 0,
+ };
+ (at, sub)
+}
+
+/// Every block `text` could show, unchecked (see [`super::compute`]): each qualifying table and
+/// top-level list as the one type it reads as, sorted by [`rank`], earliest in the text on a tie.
pub fn candidates(text: &str) -> Vec<Block> {
if text.len() > MAX_REPLY {
return Vec::new();
}
let doc = parse(text);
- // Read the prose for a pick once, and only when there is a table
+ // Read the prose for a pick once, and only when a table needs it
let said = OnceCell::new();
- let tables = doc
- .tables
- .iter()
- .filter(|t| t.start < doc.tables_unsure_at)
- .filter_map(|t| comparison(t, said.get_or_init(|| recommending(&doc.prose)).as_deref()))
- .take(MAX_TRIES);
- let lists = doc.lists.iter().filter(|l| l.start < doc.lists_unsure_at).filter_map(steps).take(MAX_TRIES);
- tables.map(Block::Comparison).chain(lists.map(Block::Steps)).collect()
+ let said = || said.get_or_init(|| recommending(&doc.prose)).as_deref();
+ let mut found: Vec<(usize, Block)> = Vec::new();
+ let tables = doc.tables.iter().filter(|t| t.clean && t.start < doc.tables_unsure_at).take(MAX_TRIES);
+ for t in tables {
+ if let Some(b) = table_block(t, &said) {
+ found.push((t.start, b));
+ }
+ }
+ let lists = doc.lists.iter().filter(|l| l.clean && l.start < doc.list_unsure_at(l.ordered)).take(MAX_TRIES);
+ for l in lists {
+ if let Some(b) = list_block(l) {
+ found.push((l.start, b));
+ }
+ }
+ found.sort_by_key(|(start, b)| (rank(b), *start));
+ found.into_iter().map(|(_, b)| b).collect()
+}
+
+/// A table as the one type it reads as: a line chart, a bar chart, metrics, else a comparison.
+fn table_block<'s>(t: &Table, said: &impl Fn() -> Option<&'s [String]>) -> Option<Block> {
+ if let Some(c) = chart::line(t) {
+ return Some(Block::Chart(c));
+ }
+ if let Some(c) = chart::bar(t) {
+ // A named pick makes it a comparison
+ let labels: Vec<&str> = t.rows.iter().map(|r| r[0]).collect();
+ if said().and_then(|said| pick(&labels, said)).is_none() {
+ return Some(Block::Chart(c));
+ }
+ }
+ if let Some(m) = chart::metrics_table(t) {
+ return Some(Block::Metrics(m));
+ }
+ comparison(t, said()).map(Block::Comparison)
}
-/// Candidates offered per type: the first that passes its checks is used, and a reply with more
-/// tables or lists than this doesn't cost more.
-const MAX_TRIES: usize = 4;
+/// A top-level list as the one type it reads as, in priority order.
+fn list_block(l: &List) -> Option<Block> {
+ items::metrics(l)
+ .map(Block::Metrics)
+ .or_else(|| items::findings(l).map(Block::Findings))
+ .or_else(|| items::cards(l).map(Block::Cards))
+ .or_else(|| items::timeline(l).map(Block::Steps))
+ .or_else(|| items::checklist(l).map(Block::Steps))
+ .or_else(|| steps(l).map(Block::Steps))
+ .or_else(|| items::facts(l).map(Block::Facts))
+}
+
+/// Tables (lists) looked at per reply: a reply with more doesn't cost more.
+const MAX_TRIES: usize = 8;
// Reading the markdown
-struct Table<'a> {
- index: usize,
- start: usize,
- clean: bool,
- header: Vec<&'a str>,
- rows: Vec<Vec<&'a str>>,
+pub(super) struct Table<'a> {
+ pub index: usize,
+ pub start: usize,
+ pub clean: bool,
+ pub header: Vec<&'a str>,
+ pub rows: Vec<Vec<&'a str>>,
}
-struct List<'a> {
- index: usize,
- start: usize,
- clean: bool,
- delim: u8,
- number: u64,
- items: Vec<&'a str>,
+pub(super) struct List<'a> {
+ /// Counted among lists of its own kind (numbered or bullet).
+ pub index: usize,
+ pub ordered: bool,
+ pub start: usize,
+ /// One line per item, no item empty, nothing nested.
+ pub clean: bool,
+ /// `.` or `)` for a numbered list, `-`, `*` or `+` for a bullet list.
+ pub delim: u8,
+ /// The first item's number; 0 for a bullet list.
+ pub number: u64,
+ pub items: Vec<&'a str>,
/// The non-blank line just before the list, and the latest heading above it.
- intro: Option<&'a str>,
- heading: Option<&'a str>,
+ pub intro: Option<&'a str>,
+ pub heading: Option<&'a str>,
}
#[derive(Default)]
@@ -64,21 +128,51 @@ struct Doc<'a> {
lists: Vec<List<'a>>,
/// Lines outside code, HTML and tables, where a pick can be named.
prose: Vec<&'a str>,
- /// The first line from which table (list) counts may differ from the chat's.
+ /// The first line from which table (numbered list, bullet list) counts may differ from the
+ /// chat's.
tables_unsure_at: usize,
- lists_unsure_at: usize,
+ ol_unsure_at: usize,
+ ul_unsure_at: usize,
+ ol_count: usize,
+ ul_count: usize,
}
impl Doc<'_> {
fn unsure_tables(&mut self, line: usize) {
self.tables_unsure_at = self.tables_unsure_at.min(line);
}
- fn unsure_lists(&mut self, line: usize) {
- self.lists_unsure_at = self.lists_unsure_at.min(line);
+ fn unsure_ol(&mut self, line: usize) {
+ self.ol_unsure_at = self.ol_unsure_at.min(line);
+ }
+ fn unsure_ul(&mut self, line: usize) {
+ self.ul_unsure_at = self.ul_unsure_at.min(line);
}
fn unsure(&mut self, line: usize) {
self.unsure_tables(line);
- self.unsure_lists(line);
+ self.unsure_ol(line);
+ self.unsure_ul(line);
+ }
+ /// Nested lists of either kind start in `s` (after quote and list markers).
+ fn unsure_nested(&mut self, line: usize, s: &str) {
+ if has_ordered_marker(s) {
+ self.unsure_ol(line);
+ }
+ if has_bullet_marker(s) {
+ self.unsure_ul(line);
+ }
+ }
+ fn list_unsure_at(&self, ordered: bool) -> usize {
+ if ordered {
+ self.ol_unsure_at
+ } else {
+ self.ul_unsure_at
+ }
+ }
+ fn new_list<'a>(&mut self, line: usize, ordered: bool, delim: u8, number: u64, first: &'a str) -> List<'a> {
+ let count = if ordered { &mut self.ol_count } else { &mut self.ul_count };
+ let index = *count;
+ *count += 1;
+ List { index, ordered, start: line, clean: !first.is_empty(), delim, number, items: vec![first], intro: None, heading: None }
}
}
@@ -89,8 +183,8 @@ enum State {
Table(usize),
/// A top-level ordered list; `offset` is the current item's content column.
List { list: usize, offset: usize, blank: bool },
- /// A bullet list, read only as far as it can hide tables and numbered lists.
- Bullet { offset: usize, blank: bool },
+ /// A top-level bullet list.
+ Bullet { list: usize, offset: usize, blank: bool },
Quote,
Html,
Code,
@@ -105,7 +199,13 @@ struct Fence {
fn parse(text: &str) -> Doc<'_> {
let lines: Vec<&str> = text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)).collect();
- let mut doc = Doc { tables_unsure_at: usize::MAX, lists_unsure_at: usize::MAX, ..Doc::default() };
+ let mut doc = Doc { tables_unsure_at: usize::MAX, ol_unsure_at: usize::MAX, ul_unsure_at: usize::MAX, ..Doc::default() };
+ // The chat takes the last `[DECISIONS]` block still in a reply out of it, code or not, and
+ // trims and rejoins the rest (frontend/src/decideFirst.ts takeDecisionsBlock): no line of it
+ // is sure to read the same there
+ if lines.iter().any(|l| l.to_ascii_lowercase().contains("[decisions]")) {
+ doc.unsure(0);
+ }
let mut state = State::None;
let mut fence: Option<Fence> = None;
let mut heading: Option<&str> = None;
@@ -175,44 +275,74 @@ fn parse(text: &str) -> Doc<'_> {
in_table = true;
}
}
- State::List { list, offset, blank: after_blank } => {
+ State::List { list, offset, blank: after_blank } | State::Bullet { list, offset, blank: after_blank } => {
+ let ordered = matches!(state, State::List { .. });
+ let at = |list, offset, blank| {
+ if ordered {
+ State::List { list, offset, blank }
+ } else {
+ State::Bullet { list, offset, blank }
+ }
+ };
if blank {
- state = State::List { list, offset, blank: true };
+ state = at(list, offset, true);
break;
}
if indent >= offset {
// More of the current item: a second paragraph, nested blocks or code
doc.lists[list].clean = false;
let inner = after_cols(line, offset);
- if has_ordered_marker(inner) {
- doc.unsure_lists(i);
- }
+ doc.unsure_nested(i, inner);
if let Some((ch, len)) = fence_open(inner.trim_start()) {
fence = Some(Fence { ch, len, inside: Some(offset) });
}
- state = State::List { list, offset, blank: false };
+ state = at(list, offset, false);
break;
}
if indent <= 3 {
- if let Some(m) = ordered_marker(rest, indent) {
- if m.delim == doc.lists[list].delim {
+ if thematic_break(rest) {
+ state = State::None;
+ continue;
+ }
+ let item = if ordered {
+ ordered_marker(rest, indent).map(|m| (m.delim, m.content, m.offset))
+ } else {
+ bullet_marker(rest, indent).map(|b| (rest.as_bytes()[0], b.content, b.offset))
+ };
+ if let Some((delim, content, item_offset)) = item {
+ if delim == doc.lists[list].delim {
let l = &mut doc.lists[list];
- l.items.push(m.content);
- if m.content.is_empty() {
+ l.items.push(content);
+ if content.is_empty() {
l.clean = false;
}
- if has_ordered_marker(m.content) {
- doc.unsure_lists(i);
+ doc.unsure_nested(i, content);
+ fence = item_fence(content, item_offset);
+ if fence.is_some() {
+ doc.lists[list].clean = false;
}
- state = State::List { list, offset: m.offset, blank: false };
+ state = at(list, item_offset, false);
break;
}
- // `1.` then `1)`: a new list
+ // `1.` then `1)`, or `-` then `*`: a new list
state = State::None;
continue;
}
- if thematic_break(rest)
- || bullet_marker(rest, indent).is_some()
+ if !ordered {
+ if let Some(m) = ordered_marker(rest, indent) {
+ if after_blank || (m.number == 1 && !m.content.is_empty()) {
+ state = State::None;
+ continue;
+ }
+ // Lazy text, or a new list that ends this one: CommonMark readers differ
+ doc.unsure_ol(i);
+ doc.unsure_ul(i);
+ doc.lists[list].clean = false;
+ state = at(list, offset, false);
+ break;
+ }
+ }
+ if (ordered && bullet_marker(rest, indent).is_some())
|| atx_heading(rest).is_some()
|| fence_open(rest).is_some()
|| rest.starts_with('>')
@@ -228,74 +358,25 @@ fn parse(text: &str) -> Doc<'_> {
}
// A lazy continuation line of the item's paragraph
doc.lists[list].clean = false;
- if has_ordered_marker(rest) {
- doc.unsure_lists(i);
- }
- state = State::List { list, offset, blank: false };
- }
- State::Bullet { offset, blank: after_blank } => {
- if blank {
- state = State::Bullet { offset, blank: true };
- break;
- }
- if indent >= offset {
- let inner = after_cols(line, offset);
- if has_ordered_marker(inner) {
- doc.unsure_lists(i);
- }
- if let Some((ch, len)) = fence_open(inner.trim_start()) {
- fence = Some(Fence { ch, len, inside: Some(offset) });
- }
- state = State::Bullet { offset, blank: false };
- break;
- }
- if indent <= 3 {
- if thematic_break(rest) {
- state = State::None;
- continue;
- }
- if let Some(b) = bullet_marker(rest, indent) {
- if has_ordered_marker(b.content) {
- doc.unsure_lists(i);
- }
- state = State::Bullet { offset: b.offset, blank: false };
- break;
- }
- if let Some(m) = ordered_marker(rest, indent) {
- if after_blank || (m.number == 1 && !m.content.is_empty()) {
- state = State::None;
- continue;
- }
- // Lazy text, or a new list: CommonMark readers differ
- doc.unsure_lists(i);
- state = State::Bullet { offset, blank: false };
- break;
- }
- if atx_heading(rest).is_some() || fence_open(rest).is_some() || rest.starts_with('>') || html_start(rest) {
- state = State::None;
- continue;
- }
- }
- if after_blank {
- state = State::None;
- continue;
- }
- state = State::Bullet { offset, blank: false };
+ doc.unsure_nested(i, rest);
+ state = at(list, offset, false);
}
State::Quote => {
if blank {
state = State::None;
} else if indent <= 3 && rest.starts_with('>') {
- if has_ordered_marker(rest) {
- doc.unsure_lists(i);
- }
+ doc.unsure_nested(i, rest);
} else if indent <= 3 && block_start(rest) {
if let Some(m) = ordered_marker(rest, indent) {
if m.number != 1 || m.content.is_empty() {
- doc.unsure_lists(i);
+ doc.unsure_ol(i);
break;
}
}
+ if bullet_marker(rest, indent).is_some_and(|b| b.content.is_empty()) {
+ doc.unsure_ul(i);
+ break;
+ }
state = State::None;
continue;
}
@@ -316,9 +397,7 @@ fn parse(text: &str) -> Doc<'_> {
}
prose = false;
code = true;
- if has_ordered_marker(rest) {
- doc.unsure_lists(i);
- }
+ doc.unsure_nested(i, rest);
}
State::Para => {
if blank {
@@ -372,8 +451,10 @@ fn parse(text: &str) -> Doc<'_> {
state = State::Code;
prose = false;
code = true;
- if has_ordered_marker(rest) || fence_open(rest).is_some() {
- doc.unsure_lists(i);
+ doc.unsure_nested(i, rest);
+ if fence_open(rest).is_some() {
+ doc.unsure_ol(i);
+ doc.unsure_ul(i);
}
break;
}
@@ -390,9 +471,7 @@ fn parse(text: &str) -> Doc<'_> {
break;
}
if rest.starts_with('>') {
- if has_ordered_marker(rest) {
- doc.unsure_lists(i);
- }
+ doc.unsure_nested(i, rest);
state = State::Quote;
break;
}
@@ -403,28 +482,27 @@ fn parse(text: &str) -> Doc<'_> {
break;
}
if let Some(m) = ordered_marker(rest, indent) {
- let index = doc.lists.len();
- if has_ordered_marker(m.content) {
- doc.unsure_lists(i);
+ doc.unsure_nested(i, m.content);
+ let mut l = doc.new_list(i, true, m.delim, m.number, m.content);
+ (l.intro, l.heading) = (prev, heading);
+ if fence_open(m.content).is_some() {
+ l.clean = false;
}
- doc.lists.push(List {
- index,
- start: i,
- clean: !m.content.is_empty(),
- delim: m.delim,
- number: m.number,
- items: vec![m.content],
- intro: prev,
- heading,
- });
- state = State::List { list: index, offset: m.offset, blank: false };
+ doc.lists.push(l);
+ fence = item_fence(m.content, m.offset);
+ state = State::List { list: doc.lists.len() - 1, offset: m.offset, blank: false };
break;
}
if let Some(b) = bullet_marker(rest, indent) {
- if has_ordered_marker(b.content) {
- doc.unsure_lists(i);
+ doc.unsure_nested(i, b.content);
+ let mut l = doc.new_list(i, false, rest.as_bytes()[0], 0, b.content);
+ (l.intro, l.heading) = (prev, heading);
+ if fence_open(b.content).is_some() {
+ l.clean = false;
}
- state = State::Bullet { offset: b.offset, blank: false };
+ doc.lists.push(l);
+ fence = item_fence(b.content, b.offset);
+ state = State::Bullet { list: doc.lists.len() - 1, offset: b.offset, blank: false };
break;
}
if let Some(header) = table_start(&lines, i) {
@@ -445,6 +523,9 @@ fn parse(text: &str) -> Doc<'_> {
// A table this reader didn't take as top-level (in a quote or an item, or orphaned)
doc.unsure_tables(i);
}
+ if !code && footnote_like(line) {
+ doc.unsure(i);
+ }
if prose && !has_pipe(line) {
doc.prose.push(line);
}
@@ -455,6 +536,11 @@ fn parse(text: &str) -> Doc<'_> {
doc
}
+/// A code fence opened on a list item's marker line, closed by the item's end or its own fence.
+fn item_fence(content: &str, offset: usize) -> Option<Fence> {
+ fence_open(content).map(|(ch, len)| Fence { ch, len, inside: Some(offset) })
+}
+
/// The indentation in columns (a tab counts to the next multiple of 4) and the rest of the line.
fn lead(line: &str) -> (usize, &str) {
let mut cols = 0;
@@ -619,6 +705,21 @@ fn has_ordered_marker(s: &str) -> bool {
true
}
+/// Whether a bullet list starts in `s`, after any quote and numbered-list markers.
+fn has_bullet_marker(s: &str) -> bool {
+ let mut s = s.trim_start();
+ for _ in 0..32 {
+ if let Some(r) = s.strip_prefix('>') {
+ s = r.trim_start();
+ } else if let Some(m) = ordered_marker(s, 0).filter(|m| !m.content.is_empty()) {
+ s = m.content;
+ } else {
+ return !thematic_break(s) && bullet_marker(s, 0).is_some();
+ }
+ }
+ true
+}
+
fn has_pipe(line: &str) -> bool {
let bytes = line.as_bytes();
let mut i = 0;
@@ -687,7 +788,33 @@ fn delimiter_like(line: &str) -> bool {
break;
}
}
- s.contains('|') && s.contains('-') && s.chars().all(|c| matches!(c, '|' | '-' | ':' | ' ' | '\t'))
+ if !s.contains('|') {
+ // A one-column table needs no pipe when its delimiter has a colon (`Pro` over `--:`);
+ // `---` under a line is a heading
+ let cell = s.trim();
+ let dashes = cell.strip_prefix(':').unwrap_or(cell);
+ let dashes = dashes.strip_suffix(':').unwrap_or(dashes);
+ return cell.contains(':') && !dashes.is_empty() && dashes.bytes().all(|b| b == b'-');
+ }
+ s.contains('-') && s.chars().all(|c| matches!(c, '|' | '-' | ':' | ' ' | '\t'))
+}
+
+/// A footnote definition (`[^1]: ...`) once indentation and quote or list markers are gone. The
+/// client numbers what is inside it where it stands, but renders it at the end of the reply.
+fn footnote_like(line: &str) -> bool {
+ let mut s = line.trim_start();
+ for _ in 0..32 {
+ if let Some(r) = s.strip_prefix('>') {
+ s = r.trim_start();
+ } else if let Some(r) = s.strip_prefix("- ").or_else(|| s.strip_prefix("* ")).or_else(|| s.strip_prefix("+ ")) {
+ s = r.trim_start();
+ } else if let Some(m) = ordered_marker(s, 0).filter(|m| !m.content.is_empty()) {
+ s = m.content;
+ } else {
+ break;
+ }
+ }
+ s.strip_prefix("[^").is_some_and(|r| r.contains("]:"))
}
/// The header cells when lines `i` and `i + 1` open a GFM table.
@@ -695,10 +822,14 @@ fn table_start<'a>(lines: &[&'a str], i: usize) -> Option<Vec<&'a str>> {
let header = lines[i];
let delimiter = *lines.get(i + 1)?;
let (h_indent, h_rest) = lead(header);
- let (d_indent, _) = lead(delimiter);
+ let (d_indent, d_rest) = lead(delimiter);
if h_indent > 3 || d_indent > 3 || !has_pipe(h_rest) {
return None;
}
+ // `- | -` is a bullet item to the client, not a delimiter row
+ if d_rest.starts_with("- ") || d_rest.starts_with("-\t") {
+ return None;
+ }
let cells = split_cells(h_rest);
(delimiter_cells(delimiter)? == cells.len()).then_some(cells)
}
@@ -732,7 +863,8 @@ fn comparison(t: &Table, said: Option<&[String]>) -> Option<Comparison> {
let columns = (0..cols)
.map(|c| {
let (numeric, unit) = numeric_column(t.rows.iter().map(|r| r[c]));
- Column { key: format!("c{c}"), label: t.header[c].to_string(), numeric, unit }
+ let role = if c == 0 { Role::Label } else { header_role(t.header[c]) };
+ Column { key: format!("c{c}"), label: t.header[c].to_string(), numeric, unit, role: Some(role) }
})
.collect();
let rows = t
@@ -745,18 +877,29 @@ fn comparison(t: &Table, said: Option<&[String]>) -> Option<Comparison> {
let pick = said.and_then(|said| pick(&labels, said));
Some(Comparison {
id: "b0".into(),
- source: Source { kind: "markdown_table".into(), index: t.index },
+ title: None,
+ source: Source::table(t.index),
columns,
rows,
highlight_row: pick.map(|r| format!("r{r}")),
highlight_reason: pick.map(|_| PICK_REASON.to_string()),
- provenance: Provenance { kind: "reply_text".into() },
+ provenance: Provenance::reply_text(),
})
}
+/// Pros / Cons / Advantages / Drawbacks / Notes headers name what a column holds.
+fn header_role(header: &str) -> Role {
+ match plain(header).trim().to_lowercase().as_str() {
+ "pros" | "advantages" => Role::Pros,
+ "cons" | "drawbacks" | "disadvantages" => Role::Cons,
+ "notes" | "note" => Role::Note,
+ _ => Role::Value,
+ }
+}
+
/// Numeric when at least 80% of the cells are a number with the same prefix or suffix (that
/// affix is the unit; none counts as an affix too).
-fn numeric_column<'a>(cells: impl Iterator<Item = &'a str>) -> (bool, Option<String>) {
+pub(super) fn numeric_column<'a>(cells: impl Iterator<Item = &'a str>) -> (bool, Option<String>) {
let mut counts: Vec<(Option<&str>, usize)> = Vec::new();
let mut total = 0;
for cell in cells {
@@ -781,7 +924,12 @@ fn numeric_column<'a>(cells: impl Iterator<Item = &'a str>) -> (bool, Option<Str
/// `Some(affix)` when `cell` is a number with at most one affix: a prefix of up to 4 letters or
/// currency signs (`EUR 12`, `$12`) or a suffix of up to 10 (`12 EUR`, `-4%`, `4.5/5`).
-fn number_affix(cell: &str) -> Option<Option<&str>> {
+pub(super) fn number_affix(cell: &str) -> Option<Option<&str>> {
+ number_parts(cell).map(|(affix, _)| affix)
+}
+
+/// [`number_affix`], and the number as written (`1,299.00`, `-4`).
+pub(super) fn number_parts(cell: &str) -> Option<(Option<&str>, &str)> {
let mut s = cell.trim();
loop {
let before = s;
@@ -812,29 +960,29 @@ fn number_affix(cell: &str) -> Option<Option<&str>> {
return None;
}
match (prefix.is_empty(), suffix.is_empty()) {
- (true, true) => Some(None),
+ (true, true) => Some((None, number)),
(false, true) => {
let ok = prefix.chars().count() <= 4
&& prefix.chars().all(|c| c.is_alphabetic() || currency(c) || c == '.')
&& prefix.chars().any(|c| c != '.');
- ok.then_some(Some(prefix))
+ ok.then_some((Some(prefix), number))
}
(true, false) => {
let out_of = suffix.strip_prefix('/').is_some_and(|d| (1..=3).contains(&d.len()) && d.bytes().all(|b| b.is_ascii_digit()));
let unit = suffix.chars().all(|c| c.is_alphabetic() || currency(c) || "%‰°/²³µ'\".".contains(c))
&& suffix.chars().any(|c| c != '.');
- (suffix.chars().count() <= 10 && (out_of || unit)).then_some(Some(suffix))
+ (suffix.chars().count() <= 10 && (out_of || unit)).then_some((Some(suffix), number))
}
(false, false) => None,
}
}
-fn currency(c: char) -> bool {
+pub(super) fn currency(c: char) -> bool {
matches!(c, '$' | '¢' | '£' | '¤' | '¥' | '֏' | '؋' | '৳' | '฿' | '៛' | '﷼') || ('\u{20A0}'..='\u{20CF}').contains(&c)
}
/// `1299`, `12.5`, `12,5`, `1,299.00` or `1.299,00`, with an optional sign; at most 15 digits.
-fn is_number(n: &str) -> bool {
+pub(super) fn is_number(n: &str) -> bool {
let n = n.strip_prefix(['+', '-', '−']).unwrap_or(n);
let digits = n.bytes().filter(u8::is_ascii_digit).count();
if digits == 0 || digits > 15 {
@@ -1018,7 +1166,7 @@ fn occurrences(h: &str, label: &str, exact: bool, hits: &mut usize) -> Option<Ve
}
/// Text without emphasis or code marks, links reduced to their text: for matching only.
-fn plain(s: &str) -> String {
+pub(super) fn plain(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
let mut out = String::with_capacity(s.len());
let mut i = 0;
@@ -1059,7 +1207,7 @@ const NOT_STEPS: [&str; 24] = [
];
fn steps(l: &List) -> Option<Steps> {
- if !l.clean || l.number != 1 || !(3..=15).contains(&l.items.len()) {
+ if !l.clean || !l.ordered || l.number != 1 || !(3..=15).contains(&l.items.len()) {
return None;
}
if l.items.iter().any(|t| t.is_empty() || t.chars().count() > 300 || is_task(t) || has_html(t)) {
@@ -1077,20 +1225,16 @@ fn steps(l: &List) -> Option<Steps> {
if !(numbered || introduced) {
return None;
}
- Some(Steps {
- id: "b0".into(),
- source: Source { kind: "markdown_list".into(), index: l.index },
- items: l.items.iter().enumerate().map(|(i, t)| Step { id: format!("s{i}"), text: t.to_string() }).collect(),
- provenance: Provenance { kind: "reply_text".into() },
- })
+ let items = l.items.iter().map(|t| (t.to_string(), None, None)).collect();
+ Some(items::steps_block(l, Variant::Steps, items))
}
-fn words(s: &str) -> Vec<String> {
+pub(super) fn words(s: &str) -> Vec<String> {
let lower: String = s.chars().map(fold).collect();
lower.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).map(str::to_string).collect()
}
-fn is_task(item: &str) -> bool {
+pub(super) fn is_task(item: &str) -> bool {
["[ ]", "[x]", "[X]"].iter().any(|t| item.strip_prefix(t).is_some_and(|r| r.is_empty() || r.starts_with(' ')))
}
@@ -1108,3 +1252,7 @@ fn starts_step_n(item: &str) -> bool {
#[cfg(test)]
#[path = "selector_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "block_tests.rs"]
+mod block_tests;
diff --git a/src/server/smart_results/selector_tests.rs b/src/server/smart_results/selector_tests.rs
index 44c36700..2625673a 100644
--- a/src/server/smart_results/selector_tests.rs
+++ b/src/server/smart_results/selector_tests.rs
@@ -33,7 +33,7 @@ fn highlight(prose: &str) -> Option<String> {
fn a_pipe_table_is_a_comparison_with_cells_copied_verbatim() {
let c = comparison_of(PLANS);
assert_eq!(c.id, "b0");
- assert_eq!((c.source.kind.as_str(), c.source.index), ("markdown_table", 0));
+ assert_eq!((c.source.kind.as_str(), c.source.index), ("markdown_table", Some(0)));
assert_eq!(c.provenance.kind, "reply_text");
let cols: Vec<(&str, &str, bool, Option<&str>)> =
c.columns.iter().map(|k| (k.key.as_str(), k.label.as_str(), k.numeric, k.unit.as_deref())).collect();
@@ -89,11 +89,11 @@ fn tables_in_code_are_neither_offered_nor_counted() {
for fence in ["```", "~~~", "````"] {
let text = format!("{fence}\n| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n| 5 | 6 |\n{fence}\n\n{PLANS}");
let c = comparison_of(&text);
- assert_eq!(c.source.index, 0, "{fence}");
+ assert_eq!(c.source.index, Some(0), "{fence}");
assert_eq!(c.rows[0].cells[0], "Basic");
}
let indented = format!("Code:\n\n | a | b |\n |---|---|\n | 1 | 2 |\n\n{PLANS}");
- assert_eq!(comparison_of(&indented).source.index, 0);
+ assert_eq!(comparison_of(&indented).source.index, Some(0));
// An unclosed fence hides the rest of the reply
assert_eq!(first(&format!("```\n{PLANS}")), None);
}
@@ -102,10 +102,10 @@ fn tables_in_code_are_neither_offered_nor_counted() {
fn the_first_qualifying_table_wins_and_keeps_its_index() {
let small = "| a | b |\n|---|---|\n| 1 | 2 |\n\n";
let c = comparison_of(&format!("{small}{PLANS}"));
- assert_eq!(c.source.index, 1);
+ assert_eq!(c.source.index, Some(1));
// A table beats a list, wherever the list is
let text = format!("Steps:\n1. One\n2. Two\n3. Three\n\n{PLANS}");
- assert_eq!(comparison_of(&text).source.index, 0);
+ assert_eq!(comparison_of(&text).source.index, Some(0));
}
#[test]
@@ -130,7 +130,24 @@ fn uncertain_structure_before_a_candidate_abstains() {
assert_eq!(first(&format!("a\tb\n\n{PLANS}")), None);
// What comes after the uncertain part is out; what comes before is still offered
let before = format!("{PLANS}\n> | a | b |\n> |---|---|\n> | 1 | 2 |\n");
- assert_eq!(comparison_of(&before).source.index, 0);
+ assert_eq!(comparison_of(&before).source.index, Some(0));
+}
+
+#[test]
+fn text_the_chat_reads_differently_abstains() {
+ // `- | -` under a pipe line is a bullet item to the chat, not a delimiter row
+ assert_eq!(first(&format!("a | b\n- | -\n1 | 2\n\n{PLANS}")), None);
+ // A one-column table needs no pipe when its delimiter has a colon
+ assert_eq!(first(&format!("Pro\n--:\nrow\n\n{PLANS}")), None);
+ // ... but `---` under a line is a heading, and the table after it is still table 0
+ assert_eq!(comparison_of(&format!("Pro\n---\n\n{PLANS}")).source.index, Some(0));
+ // A footnote definition is rendered at the end, with any table in it
+ let note = format!("Text[^1]\n\n[^1]: Note\n\n | k | v |\n |---|---|\n | a | 1 |\n\n{PLANS}");
+ assert_eq!(first(&note), None);
+ // A [DECISIONS] tag left in the text: the chat hides it and what follows, and trims the rest
+ assert_eq!(first(&format!("Intro [DECISIONS]\n\n{PLANS}")), None);
+ let trimmed = " 1. a\n 2. b\n\nSteps:\n1. One\n2. Two\n3. Three\n\n[DECISIONS] none\n";
+ assert_eq!(first(trimmed), None);
}
#[test]
@@ -218,7 +235,7 @@ fn numeric_columns_and_units() {
#[test]
fn a_numbered_list_introduced_as_steps_is_steps() {
let s = steps_of("Steps:\n1. Open settings\n2. Pick a bot\n3. Save\n");
- assert_eq!((s.source.kind.as_str(), s.source.index), ("markdown_list", 0));
+ assert_eq!((s.source.kind.as_str(), s.source.index), ("markdown_list", Some(0)));
let items: Vec<(&str, &str)> = s.items.iter().map(|i| (i.id.as_str(), i.text.as_str())).collect();
assert_eq!(items, [("s0", "Open settings"), ("s1", "Pick a bot"), ("s2", "Save")]);
assert!(first("Here's how to set it up:\n1. One\n2. Two\n3. Three\n").is_some());
@@ -247,19 +264,27 @@ fn other_numbered_lists_stay_text() {
}
#[test]
-fn a_task_list_is_counted_but_not_offered() {
+fn a_task_list_is_a_checklist_and_counts_among_numbered_lists() {
let text = "Plan:\n1. [ ] a\n2. [x] b\n3. [ ] c\n\nSteps:\n1. One\n2. Two\n3. Three\n";
- assert_eq!(steps_of(text).source.index, 1);
+ let c = steps_of(text);
+ assert_eq!((c.variant, c.source.index, c.source.ordered), (Variant::Checklist, Some(0), Some(true)));
+ let done: Vec<_> = c.items.iter().map(|i| (i.text.as_str(), i.done)).collect();
+ assert_eq!(done, [("a", Some(false)), ("b", Some(true)), ("c", Some(false))]);
+ let all = candidates(text);
+ match &all[1] {
+ Block::Steps(s) => assert_eq!((s.variant, s.source.index), (Variant::Steps, Some(1))),
+ other => panic!("{other:?}"),
+ }
}
#[test]
fn lists_are_counted_in_order_and_by_delimiter() {
// `1.` then `1)` is two lists
let text = "Steps:\n1. a\n2. b\n1) c\n2) d\n3) e\n\nSteps:\n1. One\n2. Two\n3. Three\n";
- assert_eq!(steps_of(text).source.index, 2);
+ assert_eq!(steps_of(text).source.index, Some(2));
// A list in a fence isn't counted
let text = "```\n1. a\n2. b\n3. c\n```\n\nSteps:\n1. One\n2. Two\n3. Three\n";
- assert_eq!(steps_of(text).source.index, 0);
+ assert_eq!(steps_of(text).source.index, Some(0));
}
#[test]
@@ -372,3 +397,17 @@ fn a_long_run_of_recommending_prose_names_no_pick() {
let too_much = format!("I recommend Team. {}", "We recommend reading the docs. ".repeat(300));
assert_eq!(highlight(&too_much), None);
}
+
+/// Found by the bullet-list cross-check (index-check, Z129 and K20).
+#[test]
+fn bullet_lists_end_where_the_chat_ends_them() {
+ // `3.` after a bullet item: lazy text or a new numbered list; either way no later bullet
+ // list is sure of its number
+ let text = "- a\n- b\n3. c\n4. d\n\n- [ ] x task\n- [ ] y task\n- [ ] z task\n";
+ assert!(candidates(text).iter().all(|b| b.source().ordered != Some(false)), "{:?}", candidates(text));
+ // A fence opened on the marker line belongs to the item, and the list isn't offered
+ let text = "- ```\n [ ] a\n ```\n\nLaunch:\n\n- [ ] x task\n- [ ] y task\n- [ ] z task\n";
+ let Some(Block::Steps(s)) = first(text) else { panic!("{:?}", first(text)) };
+ assert_eq!((s.variant, s.source.index), (Variant::Checklist, Some(1)));
+ assert_eq!(first("Steps:\n1. ```\n2. b\n3. c\n"), None);
+}
diff --git a/src/server/smart_results/validate.rs b/src/server/smart_results/validate.rs
index c3676233..fb932de2 100644
--- a/src/server/smart_results/validate.rs
+++ b/src/server/smart_results/validate.rs
@@ -2,7 +2,8 @@
use std::collections::HashSet;
-use super::{Block, ResultSet, ENABLED_TYPES, MAX_PAYLOAD, PICK_REASON, VERSION};
+use super::items::severity_of;
+use super::{AxisKind, Block, ChartKind, ResultSet, Role, Variant, ENABLED_TYPES, MAX_PAYLOAD, PICK_REASON, VERSION};
/// `Ok` when `set` is a block set this build may store and serve. With `reply`, every label, unit,
/// cell and item must also be text of that reply (values are copied, never made up).
@@ -18,18 +19,19 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
}
let mut texts: Vec<&str> = Vec::new();
for (i, block) in set.blocks.iter().enumerate() {
- let want = format!("b{i}");
+ if block.id() != format!("b{i}") {
+ return Err(format!("block id {:?}", block.id()));
+ }
+ if let Some(title) = block.title() {
+ check_text(title, 300, "title")?;
+ texts.push(title);
+ }
+ check_source(block)?;
+ if block.provenance().kind != "reply_text" {
+ return Err(format!("{} provenance", block.kind()));
+ }
match block {
Block::Comparison(c) => {
- if c.id != want {
- return Err(format!("block id {:?}", c.id));
- }
- if c.source.kind != "markdown_table" || c.source.index > 10_000 {
- return Err("comparison source".into());
- }
- if c.provenance.kind != "reply_text" {
- return Err("comparison provenance".into());
- }
if !(2..=8).contains(&c.columns.len()) {
return Err(format!("{} columns", c.columns.len()));
}
@@ -47,6 +49,9 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
}
None => {}
}
+ if k == 0 && col.role.is_some_and(|r| r != Role::Label) || k > 0 && col.role == Some(Role::Label) {
+ return Err(format!("column {k} role"));
+ }
}
if !(3..=50).contains(&c.rows.len()) {
return Err(format!("{} rows", c.rows.len()));
@@ -64,12 +69,7 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
return Err(format!("row label {:?} repeats", row.cells[0]));
}
for cell in &row.cells {
- if cell.chars().count() > 200 {
- return Err("a cell over 200 characters".into());
- }
- if has_html(cell) {
- return Err("HTML in a cell".into());
- }
+ check_cell(cell)?;
texts.push(cell);
}
}
@@ -86,17 +86,102 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
_ => return Err("highlight_row and highlight_reason come together".into()),
}
}
- Block::Steps(s) => {
- if s.id != want {
- return Err(format!("block id {:?}", s.id));
+ Block::Chart(c) => {
+ check_text(&c.x.label, 200, "axis label")?;
+ texts.push(&c.x.label);
+ let axis_ok = matches!((c.chart_kind, c.x.kind), (ChartKind::Line, AxisKind::Time) | (ChartKind::Bar, AxisKind::Category));
+ if !axis_ok {
+ return Err("chart axis".into());
+ }
+ if !(1..=4).contains(&c.series.len()) {
+ return Err(format!("{} series", c.series.len()));
+ }
+ for (k, s) in c.series.iter().enumerate() {
+ if s.key != format!("s{k}") {
+ return Err(format!("series key {:?}", s.key));
+ }
+ check_text(&s.label, 200, "series label")?;
+ texts.push(&s.label);
+ if let Some(unit) = &s.unit {
+ check_text(unit, 10, "unit")?;
+ texts.push(unit);
+ }
+ }
+ if !(3..=60).contains(&c.points.len()) {
+ return Err(format!("{} points", c.points.len()));
+ }
+ let mut xs = HashSet::new();
+ for (k, p) in c.points.iter().enumerate() {
+ if p.id != format!("p{k}") {
+ return Err(format!("point id {:?}", p.id));
+ }
+ check_text(&p.x, 200, "point label")?;
+ if !xs.insert(p.x.as_str()) {
+ return Err(format!("point {:?} repeats", p.x));
+ }
+ texts.push(&p.x);
+ if p.cells.len() != c.series.len() || p.values.len() != c.series.len() {
+ return Err(format!("point {k} has {} cells, {} values", p.cells.len(), p.values.len()));
+ }
+ if p.values.iter().flatten().any(|v| !v.is_finite()) {
+ return Err("a value that isn't a number".into());
+ }
+ for cell in &p.cells {
+ check_cell(cell)?;
+ if !cell.trim().is_empty() {
+ texts.push(cell);
+ }
+ }
+ }
+ if c.points.iter().all(|p| p.values.iter().all(Option::is_none)) {
+ return Err("a chart with no values".into());
+ }
+ if let Some(summary) = &c.summary {
+ check_text(summary, 300, "summary")?;
+ texts.push(summary);
}
- if s.source.kind != "markdown_list" || s.source.index > 10_000 {
- return Err("steps source".into());
+ }
+ Block::Metrics(m) => {
+ if !(2..=6).contains(&m.items.len()) {
+ return Err(format!("{} metrics", m.items.len()));
+ }
+ for (k, x) in m.items.iter().enumerate() {
+ if x.id != format!("m{k}") {
+ return Err(format!("metric id {:?}", x.id));
+ }
+ check_text(&x.label, 200, "metric label")?;
+ check_text(&x.value_text, 100, "metric value")?;
+ if !x.value.is_finite() {
+ return Err("a value that isn't a number".into());
+ }
+ texts.extend([x.label.as_str(), x.value_text.as_str()]);
+ if let Some(unit) = &x.unit {
+ check_text(unit, 10, "unit")?;
+ if !x.value_text.contains(unit.as_str()) {
+ return Err(format!("unit {unit:?} is not in its value"));
+ }
+ }
+ if let Some(note) = &x.note {
+ check_text(note, 300, "note")?;
+ texts.push(note);
+ }
}
- if s.provenance.kind != "reply_text" {
- return Err("steps provenance".into());
+ }
+ Block::Facts(f) => {
+ if !(3..=12).contains(&f.items.len()) {
+ return Err(format!("{} facts", f.items.len()));
}
- if !(3..=15).contains(&s.items.len()) {
+ for (k, x) in f.items.iter().enumerate() {
+ if x.id != format!("f{k}") {
+ return Err(format!("fact id {:?}", x.id));
+ }
+ check_text(&x.label, 200, "fact label")?;
+ check_text(&x.value, 300, "fact value")?;
+ texts.extend([x.label.as_str(), x.value.as_str()]);
+ }
+ }
+ Block::Steps(s) => {
+ if !(3..=20).contains(&s.items.len()) {
return Err(format!("{} steps", s.items.len()));
}
for (k, item) in s.items.iter().enumerate() {
@@ -105,6 +190,76 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
}
check_text(&item.text, 300, "step")?;
texts.push(&item.text);
+ let shape = match s.variant {
+ Variant::Steps => item.done.is_none() && item.when.is_none(),
+ Variant::Checklist => item.done.is_some() && item.when.is_none(),
+ Variant::Timeline => item.done.is_none() && item.when.is_some(),
+ };
+ if !shape {
+ return Err(format!("step {k} doesn't fit its variant"));
+ }
+ for extra in [&item.when, &item.owner].into_iter().flatten() {
+ check_text(extra, 60, "step label")?;
+ texts.push(extra);
+ }
+ }
+ }
+ Block::Cards(c) => {
+ if !(3..=12).contains(&c.items.len()) {
+ return Err(format!("{} cards", c.items.len()));
+ }
+ for (k, x) in c.items.iter().enumerate() {
+ if x.id != format!("k{k}") {
+ return Err(format!("card id {:?}", x.id));
+ }
+ check_text(&x.title, 200, "card title")?;
+ check_text(&x.description, 300, "card description")?;
+ texts.extend([x.title.as_str(), x.description.as_str()]);
+ if let Some(url) = &x.url {
+ let safe = url.starts_with("https://")
+ && url.len() <= 2048
+ && !url.contains(|c: char| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>' | '"' | '\'' | '`'));
+ if !safe {
+ return Err("a card link that isn't a plain https link".into());
+ }
+ texts.push(url);
+ }
+ if x.meta.len() > 4 {
+ return Err("card meta".into());
+ }
+ for m in &x.meta {
+ check_text(m, 100, "card meta")?;
+ texts.push(m);
+ }
+ }
+ }
+ Block::Findings(f) => {
+ if !(2..=30).contains(&f.items.len()) {
+ return Err(format!("{} findings", f.items.len()));
+ }
+ for (k, x) in f.items.iter().enumerate() {
+ if x.id != format!("x{k}") {
+ return Err(format!("finding id {:?}", x.id));
+ }
+ if severity_of(&x.severity_text) != Some(x.severity) {
+ return Err(format!("severity {:?} for {:?}", x.severity, x.severity_text));
+ }
+ check_text(&x.title, 300, "finding title")?;
+ texts.extend([x.severity_text.as_str(), x.title.as_str()]);
+ if !x.detail.is_empty() {
+ check_text(&x.detail, 300, "finding detail")?;
+ texts.push(&x.detail);
+ }
+ if x.refs.len() > 10 {
+ return Err("too many refs".into());
+ }
+ for r in &x.refs {
+ check_text(&r.path, 300, "ref")?;
+ if r.path.contains("://") || r.path.contains(char::is_whitespace) {
+ return Err("a ref that isn't a path".into());
+ }
+ texts.push(&r.path);
+ }
}
}
}
@@ -121,6 +276,36 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
Ok(())
}
+/// Tables (lists) are indexed in their own count; `slot` has no index. A list's `ordered` absent
+/// means numbered (v1).
+fn check_source(block: &Block) -> Result<(), String> {
+ let s = block.source();
+ let kind = block.kind();
+ let table_ok = matches!(kind, "comparison" | "chart" | "metrics");
+ let list_ok = matches!(kind, "steps" | "metrics" | "facts" | "cards" | "findings");
+ let ok = match s.kind.as_str() {
+ "markdown_table" => table_ok && s.ordered.is_none() && s.index.is_some_and(|i| i <= 10_000),
+ "markdown_list" => list_ok && s.index.is_some_and(|i| i <= 10_000),
+ _ => false,
+ };
+ if ok {
+ Ok(())
+ } else {
+ Err(format!("{kind} source"))
+ }
+}
+
+/// A shown cell: at most 200 characters, no HTML; it may be empty (a gap).
+fn check_cell(cell: &str) -> Result<(), String> {
+ if cell.chars().count() > 200 {
+ return Err("a cell over 200 characters".into());
+ }
+ if has_html(cell) {
+ return Err("HTML in a cell".into());
+ }
+ Ok(())
+}
+
fn check_text(s: &str, max: usize, what: &str) -> Result<(), String> {
if s.trim().is_empty() {
return Err(format!("an empty {what}"));