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.

Receipts export: GET /api/tasks/receipts.csv (#611)

Oleksandr Ivanchenko95f1ba24f78f
diff --git a/src/db/mod.rs b/src/db/mod.rs
index cefc3fb9..5b45df3b 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -59,6 +59,7 @@ pub mod telegram;
pub mod show_once;
pub mod isolated_folders;
pub mod tool_notes;
+pub mod receipts;
pub mod mission_watch;
pub mod verifier;
pub mod last_ran_on;
diff --git a/src/db/receipts.rs b/src/db/receipts.rs
new file mode 100644
index 00000000..58917f70
--- /dev/null
+++ b/src/db/receipts.rs
@@ -0,0 +1,147 @@
+//! Receipts export (roadmap Next 7): the read-only queries behind `GET /api/tasks/receipts.csv`.
+//! No table of its own: it reads `tasks`, `task_events`, `outcome_checks`, `evidence`, `kwants`
+//! and `missions`, a few queries per page of tasks (never one per task per column).
+
+use super::{Database, DbError};
+use crate::db::spaces::SpaceId;
+use chrono::{DateTime, Utc};
+use sqlx::FromRow;
+use std::collections::HashMap;
+
+/// How many task ids one `IN (…)` list carries.
+const PAGE: usize = 500;
+
+/// The task columns a receipt row needs.
+#[derive(Debug, Clone, FromRow)]
+pub struct ReceiptTask {
+ pub id: String,
+ pub title: String,
+ pub state: String,
+ pub mission_id: Option<String>,
+ pub owner_kwant_id: Option<String>,
+ pub source_kind: String,
+ pub created_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+ pub spent_tokens: i64,
+}
+
+/// One evidence row, without its excerpt.
+#[derive(Debug, Clone, FromRow)]
+pub struct ReceiptEvidence {
+ pub task_id: String,
+ pub label: String,
+ pub uri: Option<String>,
+ pub path: Option<String>,
+ pub sha256: Option<String>,
+}
+
+/// Everything about a page of tasks that isn't on the task row itself.
+#[derive(Debug, Default)]
+pub struct ReceiptParts {
+ /// The actor of each task's latest move to `verified` (`person`, `kwant` or a bot id).
+ pub verified_by: HashMap<String, String>,
+ /// Each task's checks as `(kind, status)`, oldest first.
+ pub checks: HashMap<String, Vec<(String, String)>>,
+ /// Each task's evidence, oldest first.
+ pub evidence: HashMap<String, Vec<ReceiptEvidence>>,
+ /// Bot display names, by id, for owners and verifiers.
+ pub bot_names: HashMap<String, String>,
+ /// Mission titles, by id.
+ pub mission_titles: HashMap<String, String>,
+}
+
+fn marks(n: usize) -> String {
+ vec!["?"; n].join(", ")
+}
+
+impl Database {
+ /// The space's tasks in `states` whose `finished_at` is in `[from, to)`, oldest first, at most
+ /// `limit` of them.
+ pub async fn receipt_tasks(
+ &self,
+ space: &SpaceId,
+ states: &[&str],
+ from: DateTime<Utc>,
+ to: DateTime<Utc>,
+ limit: i64,
+ ) -> Result<Vec<ReceiptTask>, DbError> {
+ if states.is_empty() {
+ return Ok(Vec::new());
+ }
+ let sql = format!(
+ "SELECT id, title, state, mission_id, owner_kwant_id, source_kind, created_at, finished_at, spent_tokens \
+ FROM tasks WHERE space_id = ? AND state IN ({}) AND finished_at IS NOT NULL AND finished_at >= ? AND finished_at < ? \
+ ORDER BY finished_at, rowid LIMIT ?",
+ marks(states.len())
+ );
+ let mut q = sqlx::query_as::<_, ReceiptTask>(&sql).bind(space.as_str());
+ for s in states {
+ q = q.bind(*s);
+ }
+ Ok(q.bind(from).bind(to).bind(limit).fetch_all(&self.pool).await?)
+ }
+
+ /// Who verified each task, its checks and evidence, and the names of the bots and missions
+ /// the rows mention: five queries per [`PAGE`] tasks.
+ pub async fn receipt_parts(&self, tasks: &[ReceiptTask]) -> Result<ReceiptParts, DbError> {
+ let mut out = ReceiptParts::default();
+ let mut bots: Vec<String> = Vec::new();
+ let mut missions: Vec<String> = Vec::new();
+ for page in tasks.chunks(PAGE) {
+ let ids: Vec<&str> = page.iter().map(|t| t.id.as_str()).collect();
+ let m = marks(ids.len());
+
+ let sql = format!("SELECT task_id, actor FROM task_events WHERE task_id IN ({m}) AND to_state = 'verified' ORDER BY id");
+ let mut q = sqlx::query_as::<_, (String, String)>(&sql);
+ for id in &ids {
+ q = q.bind(*id);
+ }
+ for (task, actor) in q.fetch_all(&self.pool).await? {
+ out.verified_by.insert(task, actor);
+ }
+
+ let sql = format!("SELECT task_id, kind, status FROM outcome_checks WHERE task_id IN ({m}) ORDER BY created_at, rowid");
+ let mut q = sqlx::query_as::<_, (String, String, String)>(&sql);
+ for id in &ids {
+ q = q.bind(*id);
+ }
+ for (task, kind, status) in q.fetch_all(&self.pool).await? {
+ out.checks.entry(task).or_default().push((kind, status));
+ }
+
+ let sql = format!("SELECT task_id, label, uri, path, sha256 FROM evidence WHERE task_id IN ({m}) ORDER BY captured_at, rowid");
+ let mut q = sqlx::query_as::<_, ReceiptEvidence>(&sql);
+ for id in &ids {
+ q = q.bind(*id);
+ }
+ for e in q.fetch_all(&self.pool).await? {
+ out.evidence.entry(e.task_id.clone()).or_default().push(e);
+ }
+
+ bots.extend(page.iter().filter_map(|t| t.owner_kwant_id.clone()));
+ missions.extend(page.iter().filter_map(|t| t.mission_id.clone()));
+ }
+ bots.extend(out.verified_by.values().filter(|a| !matches!(a.as_str(), "person" | "kwant")).cloned());
+ bots.sort();
+ bots.dedup();
+ missions.sort();
+ missions.dedup();
+ for page in bots.chunks(PAGE) {
+ let sql = format!("SELECT id, name FROM kwants WHERE id IN ({})", marks(page.len()));
+ let mut q = sqlx::query_as::<_, (String, String)>(&sql);
+ for id in page {
+ q = q.bind(id);
+ }
+ out.bot_names.extend(q.fetch_all(&self.pool).await?);
+ }
+ for page in missions.chunks(PAGE) {
+ let sql = format!("SELECT id, title FROM missions WHERE id IN ({})", marks(page.len()));
+ let mut q = sqlx::query_as::<_, (String, String)>(&sql);
+ for id in page {
+ q = q.bind(id);
+ }
+ out.mission_titles.extend(q.fetch_all(&self.pool).await?);
+ }
+ Ok(out)
+ }
+}
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index f95fb170..bda09058 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -22,6 +22,7 @@ pub mod flight_school;
pub mod foundry;
pub mod graph;
pub mod lessons;
+pub mod receipts;
pub mod listener;
pub mod performance;
pub mod routes;
diff --git a/src/server/missions/receipts.rs b/src/server/missions/receipts.rs
new file mode 100644
index 00000000..8480e5cb
--- /dev/null
+++ b/src/server/missions/receipts.rs
@@ -0,0 +1,299 @@
+//! `GET /api/tasks/receipts.csv` (roadmap Next 7): a space's closed tasks as one CSV an auditor
+//! can take away. One row per task: what it was, who verified it, how it was checked, the
+//! verifier's latest verdict, its evidence and the tokens it spent. Read-only, space-scoped and
+//! open like `GET /api/tasks`; no table of its own.
+
+use super::routes::{bad, internal};
+use crate::db::goals::CLOSED_TASK_STATES;
+use crate::db::receipts::{ReceiptEvidence, ReceiptParts, ReceiptTask};
+use crate::db::verifier::TaskVerdict;
+use crate::server::spaces::Scope;
+use crate::server::AppState;
+use axum::{
+ extract::{Query, State},
+ http::{header, HeaderValue},
+ response::{IntoResponse, Response},
+};
+use chrono::{DateTime, Duration, NaiveDate, SecondsFormat, Utc};
+use serde::Deserialize;
+use serde_json::Value;
+use std::collections::HashMap;
+
+/// At most this many rows; past it the response says `X-Kwant-Truncated: true`.
+pub const MAX_ROWS: usize = 10_000;
+/// The default window: tasks finished in the last 30 days (UTC), today included.
+pub const DEFAULT_DAYS: i64 = 30;
+/// How many tasks one verdict query covers.
+const PAGE: usize = 500;
+
+pub const HEADER: [&str; 17] = [
+ "task_id",
+ "title",
+ "state",
+ "mission",
+ "owner_bot",
+ "source",
+ "created_at",
+ "finished_at",
+ "verified_by",
+ "how_checked",
+ "checks_passed",
+ "checks_total",
+ "verdict",
+ "verdict_summary",
+ "couldnt_verify",
+ "evidence",
+ "tokens",
+];
+
+#[derive(Deserialize)]
+pub struct ReceiptQuery {
+ from: Option<String>,
+ to: Option<String>,
+ state: Option<String>,
+}
+
+/// One CSV cell (RFC 4180), with the formula guard: a cell that starts with `=`, `+`, `-`, `@`,
+/// a tab or a CR gets a leading `'`, so a spreadsheet shows it as text instead of running it
+/// (titles and labels come from bots and the web).
+pub fn cell(s: &str) -> String {
+ let s = if s.starts_with(['=', '+', '-', '@', '\t', '\r']) { format!("'{s}") } else { s.to_string() };
+ if s.contains([',', '"', '\r', '\n']) {
+ format!("\"{}\"", s.replace('"', "\"\""))
+ } else {
+ s
+ }
+}
+
+/// One CSV line, CRLF-terminated.
+pub fn line<S: AsRef<str>>(cells: &[S]) -> String {
+ let mut out = cells.iter().map(|c| cell(c.as_ref())).collect::<Vec<_>>().join(",");
+ out.push_str("\r\n");
+ out
+}
+
+fn iso(t: &DateTime<Utc>) -> String {
+ t.to_rfc3339_opts(SecondsFormat::Secs, true)
+}
+
+fn date(s: Option<&str>, name: &str) -> Result<Option<NaiveDate>, String> {
+ match s.map(str::trim).filter(|s| !s.is_empty()) {
+ None => Ok(None),
+ Some(s) => NaiveDate::parse_from_str(s, "%Y-%m-%d").map(Some).map_err(|_| format!("{name} must be a date like 2026-11-13")),
+ }
+}
+
+/// `(states, from, to)` from the query: `from` and `to` are whole UTC days, both included.
+type Window = (Vec<&'static str>, NaiveDate, NaiveDate);
+
+pub fn window(q: &ReceiptQuery, today: NaiveDate) -> Result<Window, String> {
+ let states: Vec<&'static str> = match q.state.as_deref().map(str::trim).filter(|s| !s.is_empty()).unwrap_or("closed") {
+ "closed" => CLOSED_TASK_STATES.to_vec(),
+ s => match CLOSED_TASK_STATES.iter().find(|c| **c == s) {
+ Some(c) => vec![*c],
+ None => return Err("unknown state: use verified, failed, cancelled or closed".into()),
+ },
+ };
+ let to = date(q.to.as_deref(), "to")?.unwrap_or(today);
+ let from = date(q.from.as_deref(), "from")?.unwrap_or(to - Duration::days(DEFAULT_DAYS));
+ if from > to {
+ return Err("from is after to".into());
+ }
+ Ok((states, from, to))
+}
+
+fn start_of(d: NaiveDate) -> DateTime<Utc> {
+ d.and_hms_opt(0, 0, 0).expect("midnight").and_utc()
+}
+
+/// Who verified it, in words: the person, kwant's own checks, or the bot's name.
+fn verifier_name(actor: &str, names: &HashMap<String, String>) -> String {
+ match actor {
+ "person" => "person".into(),
+ "kwant" => "kwant check".into(),
+ id => names.get(id).cloned().unwrap_or_else(|| id.to_string()),
+ }
+}
+
+fn couldnt_verify(v: &Value) -> String {
+ let items = v.as_array().map(Vec::as_slice).unwrap_or_default();
+ items
+ .iter()
+ .filter_map(|i| match i {
+ Value::String(s) => Some(s.clone()),
+ Value::Object(o) => {
+ let what = o.get("what").and_then(Value::as_str).unwrap_or("").trim();
+ let why = o.get("why").and_then(Value::as_str).unwrap_or("").trim();
+ match (what.is_empty(), why.is_empty()) {
+ (true, true) => None,
+ (false, true) => Some(what.to_string()),
+ (true, false) => Some(why.to_string()),
+ (false, false) => Some(format!("{what} ({why})")),
+ }
+ }
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("; ")
+}
+
+fn evidence(items: Option<&Vec<ReceiptEvidence>>) -> String {
+ items
+ .map(Vec::as_slice)
+ .unwrap_or_default()
+ .iter()
+ .map(|e| {
+ let at = e.uri.as_deref().or(e.path.as_deref()).map(str::trim).filter(|s| !s.is_empty());
+ let sha = e.sha256.as_deref().map(|s| s.chars().take(12).collect::<String>()).filter(|s| !s.is_empty());
+ let inner: Vec<String> = at.map(str::to_string).into_iter().chain(sha).collect();
+ if inner.is_empty() {
+ e.label.clone()
+ } else {
+ format!("{} ({})", e.label, inner.join(", "))
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" | ")
+}
+
+/// One receipt row, in [`HEADER`] order.
+pub fn row(t: &ReceiptTask, parts: &ReceiptParts, verdict: Option<&TaskVerdict>) -> Vec<String> {
+ let checks = parts.checks.get(&t.id).map(Vec::as_slice).unwrap_or_default();
+ let mut kinds: Vec<&str> = Vec::new();
+ for (kind, _) in checks {
+ if !kinds.contains(&kind.as_str()) {
+ kinds.push(kind);
+ }
+ }
+ let passed = checks.iter().filter(|(_, status)| status == "passed").count();
+ let verdict_text = verdict.map(|v| match &v.overturned_to {
+ Some(to) => format!("{} (overturned: {to})", v.verdict),
+ None => v.verdict.clone(),
+ });
+ vec![
+ t.id.clone(),
+ t.title.clone(),
+ t.state.clone(),
+ t.mission_id.as_ref().map(|m| parts.mission_titles.get(m).cloned().unwrap_or_default()).unwrap_or_default(),
+ t.owner_kwant_id.as_ref().map(|id| parts.bot_names.get(id).cloned().unwrap_or_else(|| id.clone())).unwrap_or_default(),
+ t.source_kind.clone(),
+ iso(&t.created_at),
+ t.finished_at.as_ref().map(iso).unwrap_or_default(),
+ parts.verified_by.get(&t.id).map(|a| verifier_name(a, &parts.bot_names)).unwrap_or_default(),
+ kinds.join("; "),
+ passed.to_string(),
+ checks.len().to_string(),
+ verdict_text.unwrap_or_default(),
+ verdict.map(|v| v.summary.clone()).unwrap_or_default(),
+ verdict.map(|v| couldnt_verify(&v.couldnt_verify)).unwrap_or_default(),
+ evidence(parts.evidence.get(&t.id)),
+ t.spent_tokens.to_string(),
+ ]
+}
+
+/// A space id as it may sit in a file name.
+fn file_part(s: &str) -> String {
+ s.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')).take(64).collect()
+}
+
+pub async fn receipts_csv(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ReceiptQuery>) -> Response {
+ let (states, from, to) = match window(&q, Utc::now().date_naive()) {
+ Ok(w) => w,
+ Err(msg) => return bad(msg),
+ };
+ let mut tasks = match state.db.receipt_tasks(&space, &states, start_of(from), start_of(to + Duration::days(1)), MAX_ROWS as i64 + 1).await {
+ Ok(t) => t,
+ Err(e) => return internal(e),
+ };
+ let truncated = tasks.len() > MAX_ROWS;
+ tasks.truncate(MAX_ROWS);
+ let parts = match state.db.receipt_parts(&tasks).await {
+ Ok(p) => p,
+ Err(e) => return internal(e),
+ };
+ let mut verdicts: HashMap<String, TaskVerdict> = HashMap::new();
+ for page in tasks.chunks(PAGE) {
+ let ids: Vec<String> = page.iter().map(|t| t.id.clone()).collect();
+ match state.db.latest_verdicts(&ids).await {
+ Ok(v) => verdicts.extend(v),
+ Err(e) => return internal(e),
+ }
+ }
+ let mut body = line(&HEADER);
+ for t in &tasks {
+ body.push_str(&line(&row(t, &parts, verdicts.get(&t.id))));
+ }
+ let name = format!("attachment; filename=\"kwant-receipts-{}-{}.csv\"", file_part(space.as_str()), to.format("%Y-%m-%d"));
+ let mut resp = body.into_response();
+ let h = resp.headers_mut();
+ h.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/csv; charset=utf-8"));
+ h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
+ if let Ok(v) = HeaderValue::from_str(&name) {
+ h.insert(header::CONTENT_DISPOSITION, v);
+ }
+ if truncated {
+ h.insert("x-kwant-truncated", HeaderValue::from_static("true"));
+ }
+ resp
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn q(from: Option<&str>, to: Option<&str>, state: Option<&str>) -> ReceiptQuery {
+ ReceiptQuery { from: from.map(Into::into), to: to.map(Into::into), state: state.map(Into::into) }
+ }
+
+ #[test]
+ fn cells_are_quoted_per_rfc_4180() {
+ assert_eq!(cell("plain"), "plain");
+ assert_eq!(cell(""), "");
+ assert_eq!(cell("a,b"), "\"a,b\"");
+ assert_eq!(cell("say \"hi\""), "\"say \"\"hi\"\"\"");
+ assert_eq!(cell("two\nlines"), "\"two\nlines\"");
+ assert_eq!(cell("cr\rhere"), "\"cr\rhere\"");
+ assert_eq!(line(&["a", "b,c", ""]), "a,\"b,c\",\r\n");
+ }
+
+ #[test]
+ fn formula_cells_get_a_leading_quote() {
+ assert_eq!(cell("=HYPERLINK(\"http://x\")"), "\"'=HYPERLINK(\"\"http://x\"\")\"");
+ assert_eq!(cell("=1+1"), "'=1+1");
+ assert_eq!(cell("+1"), "'+1");
+ assert_eq!(cell("-2"), "'-2");
+ assert_eq!(cell("@SUM(A1)"), "'@SUM(A1)");
+ assert_eq!(cell("\tx"), "'\tx");
+ assert_eq!(cell("\rx"), "\"'\rx\"");
+ // Only the first character counts
+ assert_eq!(cell("a=b"), "a=b");
+ assert_eq!(cell("2026-11-13T00:00:00Z"), "2026-11-13T00:00:00Z");
+ }
+
+ #[test]
+ fn the_window_defaults_to_30_days_of_closed_tasks() {
+ let today = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
+ let (states, from, to) = window(&q(None, None, None), today).unwrap();
+ assert_eq!(states, CLOSED_TASK_STATES.to_vec());
+ assert_eq!((from, to), (NaiveDate::from_ymd_opt(2026, 10, 14).unwrap(), today));
+ let (states, _, _) = window(&q(None, None, Some("failed")), today).unwrap();
+ assert_eq!(states, vec!["failed"]);
+ assert!(window(&q(None, None, Some("review")), today).unwrap_err().contains("unknown state"));
+ assert!(window(&q(Some("13/11/2026"), None, None), today).unwrap_err().contains("from must be a date"));
+ assert!(window(&q(None, Some("2026-13-01"), None), today).unwrap_err().contains("to must be a date"));
+ assert_eq!(window(&q(Some("2026-11-14"), Some("2026-11-13"), None), today).unwrap_err(), "from is after to");
+ }
+
+ #[test]
+ fn couldnt_verify_items_read_as_what_and_why() {
+ let v = serde_json::json!([{"what": "the login page", "why": "no browser"}, "a plain one", {"what": "", "why": ""}]);
+ assert_eq!(couldnt_verify(&v), "the login page (no browser); a plain one");
+ assert_eq!(couldnt_verify(&Value::Null), "");
+ }
+
+ #[test]
+ fn file_names_keep_only_safe_characters() {
+ assert_eq!(file_part("spc_default"), "spc_default");
+ assert_eq!(file_part("a\"b/../c\r\n"), "abc");
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 14e42cd1..88575305 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -536,6 +536,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/watch-checks/:id", get(missions::watch::get_check))
.route("/api/graph", get(missions::graph::loose_graph))
.route("/api/tasks", get(missions::routes::list_tasks).post(missions::routes::create_task))
+ .route("/api/tasks/receipts.csv", get(missions::receipts::receipts_csv))
.route("/api/tasks/:id", get(missions::routes::get_task).patch(missions::routes::patch_task))
.route("/api/tasks/:id/verify", post(missions::routes::verify_task))
.route("/api/tasks/:id/reject", post(missions::routes::reject_task))
diff --git a/tests/receipts_export_test.rs b/tests/receipts_export_test.rs
new file mode 100644
index 00000000..007cf636
--- /dev/null
+++ b/tests/receipts_export_test.rs
@@ -0,0 +1,394 @@
+//! `GET /api/tasks/receipts.csv` (roadmap Next 7): a space's closed tasks as one CSV. Covers
+//! escaping and the formula guard end to end, space isolation, the date and state filters, the
+//! 10,000-row cap, and a verified task's row (who verified it, the check kinds, the latest verdict).
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{HeaderMap, Request, StatusCode},
+ Router,
+};
+use chrono::{DateTime, NaiveDate, Utc};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{
+ missions::{NewCheck, NewEvidence, NewTask, TaskChange},
+ models::Kwant,
+ spaces::{NewSpace, SpaceId},
+ verifier::NewVerdict,
+ Database,
+ },
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::json;
+use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+struct Env {
+ app: Router,
+ state: AppState,
+ bot: Kwant,
+ raw: SqlitePool,
+ _tmp: TempDir,
+}
+
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ // A second connection, only to back-date finished_at and bulk-insert rows
+ let opts = SqliteConnectOptions::new().filename(tmp.path().join("kwnt.db")).busy_timeout(std::time::Duration::from_secs(10));
+ let raw = SqlitePoolOptions::new().max_connections(1).connect_with(opts).await.unwrap();
+ Env { app: create_router(state.clone()), state, bot, raw, _tmp: tmp }
+}
+
+struct Csv {
+ status: StatusCode,
+ headers: HeaderMap,
+ text: String,
+}
+
+impl Csv {
+ fn rows(&self) -> Vec<Vec<String>> {
+ parse(&self.text)
+ }
+ /// The data rows as maps by header name.
+ fn records(&self) -> Vec<std::collections::HashMap<String, String>> {
+ let rows = self.rows();
+ let head = rows[0].clone();
+ rows[1..].iter().map(|r| head.iter().cloned().zip(r.iter().cloned()).collect()).collect()
+ }
+ fn ids(&self) -> Vec<String> {
+ self.records().into_iter().map(|r| r["task_id"].clone()).collect()
+ }
+}
+
+async fn get(e: &Env, uri: &str) -> Csv {
+ let req = Request::builder().method("GET").uri(uri).body(Body::empty()).unwrap();
+ let resp = e.app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let headers = resp.headers().clone();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ Csv { status, headers, text: String::from_utf8(bytes.to_vec()).unwrap() }
+}
+
+/// An RFC 4180 reader, to read the export back the way a spreadsheet would.
+fn parse(s: &str) -> Vec<Vec<String>> {
+ let mut rows = Vec::new();
+ let mut row = Vec::new();
+ let mut cell = String::new();
+ let mut quoted = false;
+ let mut chars = s.chars().peekable();
+ while let Some(c) = chars.next() {
+ if quoted {
+ match c {
+ '"' if chars.peek() == Some(&'"') => {
+ chars.next();
+ cell.push('"');
+ }
+ '"' => quoted = false,
+ c => cell.push(c),
+ }
+ continue;
+ }
+ match c {
+ '"' => quoted = true,
+ ',' => row.push(std::mem::take(&mut cell)),
+ '\r' if chars.peek() == Some(&'\n') => {
+ chars.next();
+ row.push(std::mem::take(&mut cell));
+ rows.push(std::mem::take(&mut row));
+ }
+ c => cell.push(c),
+ }
+ }
+ assert!(cell.is_empty() && row.is_empty(), "the export ends with CRLF");
+ rows
+}
+
+fn at(day: &str) -> DateTime<Utc> {
+ NaiveDate::parse_from_str(day, "%Y-%m-%d").unwrap().and_hms_opt(12, 0, 0).unwrap().and_utc()
+}
+
+/// A task in `space` moved from backlog to `to`, finished at `finished`.
+async fn closed(e: &Env, space: &SpaceId, title: &str, to: &str, finished: DateTime<Utc>) -> String {
+ let t = e
+ .state
+ .db
+ .create_task(
+ space,
+ &NewTask {
+ title: title.into(),
+ state: "backlog".into(),
+ priority: 1,
+ owner_kwant_id: Some(e.bot.id.clone()),
+ max_attempts: 3,
+ source_kind: "person".into(),
+ created_by: "person".into(),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ if to == "verified" {
+ let c = e
+ .state
+ .db
+ .add_check(&NewCheck {
+ task_id: t.id.clone(),
+ kind: "person".into(),
+ spec: json!({"note": ""}),
+ required: true,
+ approved: true,
+ requested_by: "person".into(),
+ approved_by: Some("person".into()),
+ })
+ .await
+ .unwrap();
+ e.state.db.finish_check(&c.id, "passed", None, "person", None).await.unwrap();
+ }
+ let actor = if to == "failed" { "kwant" } else { "person" };
+ assert!(e.state.db.move_task(&t.id, "backlog", to, actor, &TaskChange::default()).await.unwrap());
+ finish_at(e, &t.id, finished).await;
+ t.id
+}
+
+async fn finish_at(e: &Env, id: &str, when: DateTime<Utc>) {
+ sqlx::query("UPDATE tasks SET finished_at = ? WHERE id = ?").bind(when).bind(id).execute(&e.raw).await.unwrap();
+}
+
+#[tokio::test]
+async fn a_verified_task_row_names_who_checked_it_how_and_the_latest_verdict() {
+ let e = setup().await;
+ let space = SpaceId::default_space();
+ let id = closed(&e, &space, "Publish the price list", "verified", Utc::now()).await;
+ // A kwant check before the person's Verify (both passed), and one that failed
+ for (kind, status) in [("command", "passed"), ("http", "failed")] {
+ let c = e
+ .state
+ .db
+ .add_check(&NewCheck {
+ task_id: id.clone(),
+ kind: kind.into(),
+ spec: json!({}),
+ required: false,
+ approved: true,
+ requested_by: e.bot.id.clone(),
+ approved_by: Some("person".into()),
+ })
+ .await
+ .unwrap();
+ e.state.db.finish_check(&c.id, status, None, "kwant", None).await.unwrap();
+ }
+ for (verdict, summary, couldnt) in [
+ ("fail", "old verdict", json!([])),
+ ("pass", "Prices match the sheet", json!([{"what": "the PDF export", "why": "no browser"}, "the email"])),
+ ] {
+ e.state
+ .db
+ .add_verdict(&NewVerdict {
+ task_id: id.clone(),
+ attempt: 1,
+ round: 1,
+ verdict: verdict.into(),
+ confidence: "medium".into(),
+ risk_tier: "low".into(),
+ couldnt_verify: couldnt,
+ difference: "none".into(),
+ next: "counted".into(),
+ summary: summary.into(),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ }
+ for (label, uri, path, sha) in [
+ ("=cmd|' /C calc'!A0", Some("https://example.com/prices"), None, Some("0123456789abcdef0123")),
+ ("notes, final", None, Some("out/notes.md"), None),
+ ("just a note", None, None, None),
+ ] {
+ e.state
+ .db
+ .add_evidence(&NewEvidence {
+ task_id: id.clone(),
+ kind: "note".into(),
+ label: label.into(),
+ uri: uri.map(Into::into),
+ path: path.map(Into::into),
+ sha256: sha.map(Into::into),
+ excerpt: Some("never exported".into()),
+ captured_by: e.bot.id.clone(),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ }
+
+ let csv = get(&e, "/api/tasks/receipts.csv").await;
+ assert_eq!(csv.status, StatusCode::OK, "{}", csv.text);
+ assert_eq!(csv.headers["content-type"], "text/csv; charset=utf-8");
+ let today = Utc::now().date_naive().format("%Y-%m-%d");
+ assert_eq!(csv.headers["content-disposition"], format!("attachment; filename=\"kwant-receipts-spc_default-{today}.csv\"").as_str());
+ assert!(csv.headers.get("x-kwant-truncated").is_none());
+ assert_eq!(
+ csv.rows()[0],
+ "task_id,title,state,mission,owner_bot,source,created_at,finished_at,verified_by,how_checked,checks_passed,checks_total,verdict,verdict_summary,couldnt_verify,evidence,tokens"
+ .split(',')
+ .collect::<Vec<_>>()
+ );
+ let r = &csv.records()[0];
+ assert_eq!(r["task_id"], id);
+ assert_eq!(r["state"], "verified");
+ assert_eq!(r["mission"], "");
+ assert_eq!(r["owner_bot"], e.bot.name);
+ assert_eq!(r["source"], "person");
+ assert_eq!(r["verified_by"], "person");
+ assert_eq!(r["how_checked"], "person; command; http");
+ assert_eq!((r["checks_passed"].as_str(), r["checks_total"].as_str()), ("2", "3"));
+ assert_eq!(r["verdict"], "pass");
+ assert_eq!(r["verdict_summary"], "Prices match the sheet");
+ assert_eq!(r["couldnt_verify"], "the PDF export (no browser); the email");
+ assert_eq!(
+ r["evidence"],
+ "'=cmd|' /C calc'!A0 (https://example.com/prices, 0123456789ab) | notes, final (out/notes.md) | just a note"
+ );
+ assert!(!csv.text.contains("never exported"), "no excerpts");
+ assert_eq!(r["tokens"], "0");
+ assert!(r["finished_at"].ends_with('Z') && r["created_at"].ends_with('Z'));
+}
+
+#[tokio::test]
+async fn titles_are_escaped_and_formulas_guarded() {
+ let e = setup().await;
+ let space = SpaceId::default_space();
+ let titles = ["Fix \"login\", then deploy", "two\nlines\r\nhere", "=HYPERLINK(\"http://evil\",\"x\")", "+1 call", "-5 items", "@SUM(A1)", "\tindented"];
+ for t in titles {
+ closed(&e, &space, t, "cancelled", Utc::now()).await;
+ }
+ let csv = get(&e, "/api/tasks/receipts.csv?state=cancelled").await;
+ assert_eq!(csv.status, StatusCode::OK, "{}", csv.text);
+ let got: Vec<String> = csv.records().into_iter().map(|r| r["title"].clone()).collect();
+ assert_eq!(
+ got,
+ vec![
+ "Fix \"login\", then deploy".to_string(),
+ "two\nlines\r\nhere".into(),
+ "'=HYPERLINK(\"http://evil\",\"x\")".into(),
+ "'+1 call".into(),
+ "'-5 items".into(),
+ "'@SUM(A1)".into(),
+ "'\tindented".into(),
+ ]
+ );
+ assert!(csv.text.contains("\"Fix \"\"login\"\", then deploy\""));
+ // Every record has all 17 cells: the newline title stayed in one cell
+ assert!(csv.rows().iter().all(|r| r.len() == 17));
+}
+
+#[tokio::test]
+async fn another_spaces_tasks_never_appear() {
+ let e = setup().await;
+ let home = SpaceId::default_space();
+ let other = e
+ .state
+ .db
+ .create_space(&NewSpace { name: "Clients".into(), icon: "C".into(), color: None, this_machine_enabled: false })
+ .await
+ .unwrap();
+ let other = SpaceId::new(other.id);
+ let mine = closed(&e, &home, "mine", "verified", Utc::now()).await;
+ let theirs = closed(&e, &other, "theirs", "verified", Utc::now()).await;
+
+ assert_eq!(get(&e, "/api/tasks/receipts.csv").await.ids(), vec![mine.clone()]);
+ assert_eq!(get(&e, "/api/tasks/receipts.csv?space=spc_default").await.ids(), vec![mine]);
+ let csv = get(&e, &format!("/api/tasks/receipts.csv?space={}", other.as_str())).await;
+ assert_eq!(csv.ids(), vec![theirs]);
+ assert!(csv.headers["content-disposition"].to_str().unwrap().contains(&format!("kwant-receipts-{}-", other.as_str())));
+ assert_eq!(get(&e, "/api/tasks/receipts.csv?space=spc_nope").await.status, StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn the_date_and_state_filters_pick_the_rows() {
+ let e = setup().await;
+ let s = SpaceId::default_space();
+ let early = closed(&e, &s, "early", "verified", at("2025-10-01")).await;
+ let mid_failed = closed(&e, &s, "mid failed", "failed", at("2025-10-15")).await;
+ let mid_cancelled = closed(&e, &s, "mid cancelled", "cancelled", at("2025-10-15")).await;
+ let late = closed(&e, &s, "late", "verified", at("2025-11-01")).await;
+ // Finished on the last second of `to` counts; midnight after it doesn't
+ let edge = closed(&e, &s, "edge", "verified", at("2025-10-31")).await;
+ finish_at(&e, &edge, "2025-10-31T23:59:59.999Z".parse().unwrap()).await;
+ let after = closed(&e, &s, "after", "verified", at("2025-11-01")).await;
+ finish_at(&e, &after, "2025-11-01T00:00:00Z".parse().unwrap()).await;
+ // Open tasks never appear
+ e.state
+ .db
+ .create_task(&s, &NewTask { title: "open".into(), state: "backlog".into(), priority: 1, max_attempts: 3, source_kind: "person".into(), created_by: "person".into(), ..Default::default() })
+ .await
+ .unwrap();
+
+ let all = get(&e, "/api/tasks/receipts.csv?from=2025-09-01&to=2025-12-01").await;
+ assert_eq!(all.ids(), vec![early.clone(), mid_failed.clone(), mid_cancelled.clone(), edge.clone(), after.clone(), late.clone()], "oldest first");
+ let closed_explicit = get(&e, "/api/tasks/receipts.csv?from=2025-09-01&to=2025-12-01&state=closed").await;
+ assert_eq!(closed_explicit.ids(), all.ids());
+
+ assert_eq!(get(&e, "/api/tasks/receipts.csv?from=2025-10-01&to=2025-10-31").await.ids(), vec![early.clone(), mid_failed.clone(), mid_cancelled.clone(), edge.clone()]);
+ assert_eq!(get(&e, "/api/tasks/receipts.csv?from=2025-10-02&to=2025-10-31&state=failed").await.ids(), vec![mid_failed]);
+ assert_eq!(get(&e, "/api/tasks/receipts.csv?from=2025-10-02&to=2025-10-31&state=cancelled").await.ids(), vec![mid_cancelled]);
+ assert_eq!(get(&e, "/api/tasks/receipts.csv?from=2025-09-01&to=2025-12-01&state=verified").await.ids(), vec![early, edge, after, late]);
+ // `to` alone: the 30 days before it
+ assert_eq!(get(&e, "/api/tasks/receipts.csv?to=2025-10-20").await.ids().len(), 3);
+ // The default window (last 30 days) holds none of these old tasks
+ let none = get(&e, "/api/tasks/receipts.csv").await;
+ assert_eq!(none.status, StatusCode::OK);
+ assert_eq!(none.rows().len(), 1, "header only");
+
+ for (q, says) in [
+ ("state=review", "unknown state"),
+ ("state=bogus", "unknown state"),
+ ("from=2026/10/01", "from must be a date"),
+ ("to=yesterday", "to must be a date"),
+ ("from=2025-11-02&to=2025-11-01", "from is after to"),
+ ] {
+ let r = get(&e, &format!("/api/tasks/receipts.csv?{q}")).await;
+ assert_eq!(r.status, StatusCode::BAD_REQUEST, "{q}");
+ assert!(r.text.contains(says), "{q}: {}", r.text);
+ }
+}
+
+#[tokio::test]
+async fn more_than_10000_rows_are_cut_and_say_so() {
+ let e = setup().await;
+ let when = at("2026-10-10");
+ sqlx::query(
+ "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 10001) \
+ INSERT INTO tasks (id, space_id, title, state, budget_tokens, source_kind, created_by, created_at, updated_at, finished_at) \
+ SELECT printf('bulk%05d', i), 'spc_default', 'bulk ' || i, 'cancelled', 0, 'person', 'person', ?, ?, ? FROM n",
+ )
+ .bind(when)
+ .bind(when)
+ .bind(when)
+ .execute(&e.raw)
+ .await
+ .unwrap();
+ let csv = get(&e, "/api/tasks/receipts.csv?from=2026-10-01&to=2026-10-31").await;
+ assert_eq!(csv.status, StatusCode::OK);
+ assert_eq!(csv.headers["x-kwant-truncated"], "true");
+ let ids = csv.ids();
+ assert_eq!(ids.len(), 10_000);
+ assert_eq!((ids[0].as_str(), ids[9_999].as_str()), ("bulk00001", "bulk10000"));
+
+ let fits = get(&e, "/api/tasks/receipts.csv?from=2026-10-01&to=2026-10-09").await;
+ assert!(fits.headers.get("x-kwant-truncated").is_none());
+}