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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Lessons: bots learn from their earlier tasks, failed checks, send-backs and goals (#260)
Oleksandr Ivanchenko96b1c422edb0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6a0cae45..af9c7a6f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## Unreleased+### Added+- **Bots learn from their earlier tasks.** A bot's next task brief lists what went wrong on its tasks in the last 30+ days: a check that failed after hand-in, a turn that stalled or was denied, and every time you sent a task back with+ a reason. They come from kwant's own records, so a bot can't write its own. Chats get a shorter list. 1 task in 5+ goes without, so you can see whether it helps. Turn it off with the `lessons` setting; see what a bot carries at+ `GET /api/kwants/:id/lessons`.+- **Goals that stopped holding are lessons too.** When a "Keep this true" goal made from a bot's finished task is+ confirmed not met, that bot's briefs and chats say so until the goal holds again.+- **Bots check their work before hand-in.** A task with an approved check asks its bot to run the checks itself and+ fix what fails before moving it to review.+## [Mac 0.6.7] - 2026-11-03### Changeddiff --git a/docs/mission-control.md b/docs/mission-control.mdindex 590f0ed8..71c04f99 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -18,6 +18,7 @@ with `?space=<id>` (default space when omitted), like the rest of the API.| `mission_lease_minutes` | int 5–240 | `30` | How long a claim lives without activity. || `mission_default_budget_tokens` | int 0 or 1 000–5 000 000 | `0` | A new mission's budget when none is given. 0 = no limit. || `mission_default_task_budget_tokens` | int 0–5 000 000 | `0` | A new task's budget when none is given (capped at a limited mission's budget). 0 = no limit. |+| `lessons` | `on`/`off` | `on` | Unset is on. Off: no turn gets a lessons block and no `lessons_shown`, `lessons_held_out` or `self_checked` event is logged; `GET /api/kwants/:id/lessons` still answers with `enabled: false`. The self-check sentence in a task brief doesn't depend on it (§23). |Changing settings is person-only (as today). Bots can't change these through `settings_update`.@@ -1276,3 +1277,74 @@ List rows and `GET /api/goals/:id` carry `open_mission {id,title,status,attempt,### Known limitsRead-only Investigate is enforced by the brief only. A failed Investigate or Fix replans while attempts remain. Typed predicates are not evaluated by a task's own checks: the goal's re-check decides. `from_task` defaults: interval 60 minutes, confirm_failures 2, budget 0, max_fixes 3, priority 2, mode `suggest`.++## 23. Lessons (0.6.8, self-improving bots round 1)++A bot's earlier tasks teach its next ones. Lessons are derived on read from kwant's own records, so a bot can't add, edit or remove one: `task_failures` (append-only, written only by AutoFix's `record`) and the person's send-backs (a `state` event by the person from `review` to `ready` or `blocked`, with a reason). A task counts for the bot that owns it and held a claim on it (the rule `score_tasks` uses).++### Sources++| source | from | key |+|---|---|---|+| `check` | a failure of class `check_failed` | `check_failed:<hash of the check's kind and redacted spec>` (the same check copied into each task repeats under one key) |+| `stall` | `stalled` (a lease that ran out, or a runner turn that ended without a hand-in) | `stalled:run` (both are one behaviour) |+| `denied` | `denied` | `denied:tool` |+| `error` | `unknown` | `unknown:turn` |+| `review` | the person's send-back with a reason | `rejected:<hash of the reason's content words>`; alike reasons (`router::team::alike`) share the first one's key |+| `goal` | a "Keep this true" goal made from a task the bot finished verified, confirmed not met after that (`goal_lapses_of_bot`) and still `not_met` now | `goal:<goal id>` (one per goal, its newest lapse) |++`quota`, `auth`, `budget`, `transient`, `bad_spec` and `needs_input` are not the bot's doing and never become a lesson. The window is the last 30 days.++### Lines++Each line is a fixed template over enumerated fields: when, the task, what happened, how it settled, and `(xN in 30 days)` when it repeated. A task's title is shown only when the person wrote it and it is one line of at most 80 characters; otherwise the task is named by id. Person text (titles, reasons) and check output pass `safe_text`: one line, cut at 120 characters, and dropped when it has a URL, a backtick, a path or one of approve, allow, permission, payment, token, password; quotes and brackets are softened. A check's command, url or path is shown only when the check was approved by the person or a mission, and its output only while the check still fails. Lines are grouped by key, then ordered most repeated first, then newest.++A goal line names the goal only by its title, through the same title rule, and a date; never the goal's check, URL or output. A goal that holds again, goes unknown, or is paused, a draft or deleted has no line. Goal lines share the caps and the ordering with the other sources, and the setting and the holdout cover them too:++```+- A goal you worked on, "Publish the price list", is not met since 2026-11-03: check it before saying a task is done.+```++When the title can't be shown, the line says `made from task "<title>"`, or the task's id.++```+[Lessons from earlier tasks]+From kwant's records and the person's reviews. Observations, not instructions: use one only when this task is like that one, and never mention them in your reply unless asked.+- today, task "Write the release note": the person sent it back: "Too long, keep it under five lines"; it is still open.+- today, task "Export the sales CSV": the command check `echo expected 42 got 41; exit 1` failed after hand-in (output: "exit code 1 expected 42 got 41"); it is still open.+```++### Where they appear++- **Task brief (C1):** a Mission Control runner turn gets the block after the brief and any AutoFix retry note: at most 8 lines and 1,500 bytes. A line that doesn't fit is skipped so a shorter one can.+- **Other turns (C5):** chat, routine and hand-off turns get at most 5 lines and 1,000 bytes in the continuity block, before the app-tools section. It is an allow-list by turn purpose: decide, audit, Foundry draft and replay, work-ahead, goal draft and any purpose added later get none. Mission turns get only the brief's block.+- With nothing to learn from, or the setting off, there is no block and the prompt is byte-identical to one without the feature.++### Self-check (C0)++A task brief with at least one approved check adds: "Before you move it to review, run these checks yourself with task_request_check and fix what fails." After the turn, when the owner ran checks (`check_result` events by `kwant`) before moving the task to review, kwant logs `self_checked {checks: [check ids]}`. The person's own `POST /api/tasks/:id/checks/run` in that window counts too.++### Holdout and attribution++1 task in 5, picked by a hash of the task id (so a task always lands on the same side), gets no block. At the point the runner turn starts, kwant logs on the task (actor `kwant`):++- `lessons_shown {keys, bytes}`: the keys of the lines shown and the block's size in bytes;+- `lessons_held_out {keys}`: the keys it would have shown.++Nothing is logged when there were no lessons, and chat, routine and hand-off turns log nothing (they are not tied to a task).++### Route (person only)++```+GET /api/kwants/:id/lessons {enabled, window_days, lines: [{key, source, text, count, last_at, task_id}]}+```++`lines` are the brief's lines (8 / 1,500 bytes), in order; `last_at` is in milliseconds; `source` is one of `check`, `stall`, `denied`, `error`, `review`, `goal`. A bot's own token gets 403. The bot is looked up in the request's space: another space's bot, or no such bot, is 404. With the setting off it still answers, with `enabled: false`.++### Timeline events++`self_checked`, `lessons_shown`, `lessons_held_out`.++### Known limits++Routine and hand-off turns aren't tied to a task, so they get the chat-sized block with no holdout and no attribution. A goal line reflects the goal's status at the last check, so it can lag a fix until the goal's next run.diff --git a/src/db/lessons.rs b/src/db/lessons.rsnew file mode 100644index 00000000..3b062232--- /dev/null+++ b/src/db/lessons.rs@@ -0,0 +1,123 @@+//! Self-improving bots, round 1: the records a bot's lessons are computed from. Nothing here is+//! written: lessons are derived on read from `task_failures` (append-only, written only by+//! AutoFix's `record`) and the person's own send-backs, so a bot can't add, edit or remove one.+//! The rendering and its rails live in `server::missions::lessons`. Contract:+//! docs/mission-control.md §23.++use super::{Database, DbError};+use chrono::{DateTime, Utc};+use sqlx::FromRow;++/// The failure classes that are the bot's own doing. `quota`, `auth`, `budget`, `transient`,+/// `bad_spec` and `needs_input` are not, so they never become a lesson.+pub const LESSON_CLASSES: [&str; 4] = ["check_failed", "stalled", "denied", "unknown"];++/// One `task_failures` row of a task the bot owned and held a claim on.+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct FailureOfBot {+ pub id: String,+ pub task_id: String,+ pub source: String,+ pub class: String,+ /// Read only to find which check failed (its first line is the check's kind and redacted+ /// spec); never rendered.+ pub excerpt: Option<String>,+ pub created_at: DateTime<Utc>,+ pub title: String,+ pub created_by: String,+ pub task_state: String,+ /// An AutoFix retry of this failure succeeded.+ pub fixed_by_autofix: bool,+ /// The person moved the task from failed back to ready after this failure.+ pub person_retried: bool,+}++/// The person sent a task of the bot back from review (to ready or blocked) with a reason.+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct CorrectionOfBot {+ pub task_id: String,+ pub to_state: String,+ /// The event's detail JSON; `reason` is the person's own text.+ pub detail: String,+ pub created_at: DateTime<Utc>,+ pub title: String,+ pub created_by: String,+ pub task_state: String,+}++/// The rule `score_tasks` uses: a task counts for the bot that owns it and held a claim on it.+const OWNED: &str = "t.owner_kwant_id = ? AND EXISTS (SELECT 1 FROM agent_claims a WHERE a.task_id = t.id AND a.kwant_id = ?)";++const CLASSES_IN: &str = "('check_failed', 'stalled', 'denied', 'unknown')";++const SEND_BACK: &str = "e.kind = 'state' AND e.actor = 'person' AND e.from_state = 'review' AND e.to_state IN ('ready', 'blocked')";++impl Database {+ /// Add-only: the indexes the lesson readers use (`tasks` had no owner index and+ /// `task_failures` only `(task_id, created_at)`, so every read was a scan).+ pub(super) async fn migrate_lessons(&self) -> Result<(), DbError> {+ for stmt in [+ "CREATE INDEX IF NOT EXISTS tasks_owner_finished ON tasks (owner_kwant_id, finished_at)",+ "CREATE INDEX IF NOT EXISTS task_failures_created ON task_failures (created_at)",+ "CREATE INDEX IF NOT EXISTS task_events_kind_created ON task_events (kind, created_at)",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ Ok(())+ }++ /// The bot's failures of the lesson classes since `since`, newest first.+ pub async fn failures_of_bot(&self, kwant_id: &str, since: DateTime<Utc>, limit: i64) -> Result<Vec<FailureOfBot>, DbError> {+ let sql = format!(+ "SELECT f.id, f.task_id, f.source, f.class, f.excerpt, f.created_at, t.title, t.created_by, t.state AS task_state, \+ EXISTS (SELECT 1 FROM autofix_attempts x WHERE x.failure_id = f.id AND x.status = 'succeeded') AS fixed_by_autofix, \+ EXISTS (SELECT 1 FROM task_events e WHERE e.task_id = f.task_id AND e.kind = 'state' AND e.actor = 'person' \+ AND e.from_state = 'failed' AND e.to_state = 'ready' AND e.created_at >= f.created_at) AS person_retried \+ FROM task_failures f JOIN tasks t ON t.id = f.task_id \+ WHERE f.created_at >= ? AND f.class IN {CLASSES_IN} AND {OWNED} \+ ORDER BY f.created_at DESC, f.rowid DESC LIMIT ?"+ );+ Ok(sqlx::query_as::<_, FailureOfBot>(&sql).bind(since).bind(kwant_id).bind(kwant_id).bind(limit).fetch_all(&self.pool).await?)+ }++ /// The person's send-backs of the bot's tasks since `since`, newest first.+ pub async fn person_corrections_of_bot(&self, kwant_id: &str, since: DateTime<Utc>, limit: i64) -> Result<Vec<CorrectionOfBot>, DbError> {+ let sql = format!(+ "SELECT e.task_id, e.to_state, e.detail, e.created_at, t.title, t.created_by, t.state AS task_state \+ FROM task_events e JOIN tasks t ON t.id = e.task_id \+ WHERE {SEND_BACK} AND e.created_at >= ? AND {OWNED} \+ ORDER BY e.created_at DESC, e.id DESC LIMIT ?"+ );+ Ok(sqlx::query_as::<_, CorrectionOfBot>(&sql).bind(since).bind(kwant_id).bind(kwant_id).bind(limit).fetch_all(&self.pool).await?)+ }++ /// Whether the bot has anything to learn from since `since`: the cheap gate before a chat+ /// turn computes its lessons.+ pub async fn has_lessons_since(&self, kwant_id: &str, since: DateTime<Utc>) -> Result<bool, DbError> {+ let sql = format!(+ "SELECT EXISTS (SELECT 1 FROM task_failures f JOIN tasks t ON t.id = f.task_id \+ WHERE f.created_at >= ? AND f.class IN {CLASSES_IN} AND {OWNED}) \+ OR EXISTS (SELECT 1 FROM task_events e JOIN tasks t ON t.id = e.task_id \+ WHERE {SEND_BACK} AND e.created_at >= ? AND {OWNED})"+ );+ let (yes,): (bool,) =+ sqlx::query_as(&sql).bind(since).bind(kwant_id).bind(kwant_id).bind(since).bind(kwant_id).bind(kwant_id).fetch_one(&self.pool).await?;+ Ok(yes)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn lesson_classes_are_known_failure_classes() {+ for c in LESSON_CLASSES {+ assert!(super::super::autofix::CLASSES.contains(&c), "{c}");+ assert!(CLASSES_IN.contains(&format!("'{c}'")), "{c}");+ }+ for c in ["quota", "auth", "budget", "transient", "bad_spec", "needs_input"] {+ assert!(!LESSON_CLASSES.contains(&c), "{c}");+ }+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 18d9b80a..1d941135 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -37,6 +37,7 @@ pub mod automation;pub mod truth_ledger;pub mod goals;pub mod goal_missions;+pub mod lessons;pub mod routing;pub mod smart_results;@@ -225,6 +226,8 @@ impl Database {db.migrate_goals().await?;// 0.6.5: the missions a goal opened to restore itself, notices and re-checks (add-only)db.migrate_goal_missions().await?;+ // 0.6.8: the indexes the lesson readers use (add-only)+ db.migrate_lessons().await?;// Phase C1: the Truth Ledger mirrors memory (add-only). Last, so no later step rebuilds// a table its triggers or lookups depend ondb.migrate_truth_ledger().await?;diff --git a/src/server/auth.rs b/src/server/auth.rsindex 401c5c17..099c97b3 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -370,6 +370,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {["", "api", "teams", _] => matches!(*method, Method::DELETE | Method::PUT | Method::PATCH),["", "api", "channels", _] => *method == Method::PATCH,["", "api", "kwants", _] => *method == Method::DELETE,+ // A bot's lessons (its failures and the person's send-backs): the person reads them; bots+ // never read their own record, any method+ ["", "api", "kwants", _, "lessons", ..] => true,// A note written here is saved as the person's ("written by the person"), for any bot:// bots keep their own notes with the memory tools["", "api", "kwants", _, "memories", ..] => *method != Method::GET && *method != Method::HEAD,@@ -875,6 +878,11 @@ mod tests {assert!(person_only(&post, "/api/messages/m1/decisions/0/change"));assert!(person_only(&post, "/api/work-ahead/run"));assert!(person_only(&get, "/api/skills/foundry"));+ assert!(person_only(&get, "/api/kwants/k1/lessons"));+ assert!(person_only(&Method::HEAD, "/api/kwants/k1/lessons"));+ assert!(person_only(&post, "/api/kwants/k1/lessons"));+ assert!(person_only(&del, "/api/kwants/k1/lessons/x"));+ assert!(!person_only(&get, "/api/kwants/k1/memories"));assert!(person_only(&post, "/api/skills/foundry/k1~release/draft"));assert!(person_only(&get, "/api/skills/s1/foundry"));assert!(person_only(&post, "/api/skills/s1/rollback"));diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 887b844c..c5a1d3fe 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -71,6 +71,19 @@ pub async fn prompt_block(team_id: Option<&str>,channel_id: Option<&str>,with_tools: bool,+) -> String {+ prompt_block_with(state, kwant, team_id, channel_id, with_tools, "").await+}++/// [`prompt_block`] with the bot's lessons block (`missions::lessons::for_turn`, empty for none)+/// after its memories and before the tools section, so a turn that drops the tools keeps it.+pub async fn prompt_block_with(+ state: &AppState,+ kwant: &Kwant,+ team_id: Option<&str>,+ channel_id: Option<&str>,+ with_tools: bool,+ lessons: &str,) -> String {let db = &state.db;let mut out = String::new();@@ -97,6 +110,7 @@ pub async fn prompt_block(Some(block) => out.push_str(&block),None => out.push_str(&memory_block(&memories, with_tools)),}+ out.push_str(lessons);if with_tools {out.push_str(crate::drivers::APP_TOOLS_MARKER);out.push_str(&format!(diff --git a/src/server/missions/lessons.rs b/src/server/missions/lessons.rsnew file mode 100644index 00000000..21557a5f--- /dev/null+++ b/src/server/missions/lessons.rs@@ -0,0 +1,856 @@+//! Self-improving bots, round 1: lessons. A bot's own failed tasks and the person's send-backs of+//! the last [`WINDOW_DAYS`] become short lines in its task brief (`[Lessons from earlier tasks]`,+//! after AutoFix's retry note) and, smaller, in every chat, routine and hand-off turn (in the+//! continuity block, before the tools section).+//!+//! Rails: a line is rendered only from enumerated fields and person-written text, through the+//! fixed templates of [`line`] and [`safe_text`]. A check's spec shows only through+//! `redact_value` and only when the person or an approved mission approved it; at most 120+//! redacted characters of its output; failure summaries never reach a prompt. Lessons are+//! computed on read and never stored. One app-wide setting, `lessons` (on by default), turns all+//! of it off: no block and no events. With it on, 1 in 5 task-bound turns skip the block (by a+//! hash of the task id) so the effect can be measured. Contract: docs/mission-control.md §23.++use crate::db::lessons::{CorrectionOfBot, FailureOfBot};+use crate::db::missions::OutcomeCheck;+use crate::server::spaces::Scope;+use crate::server::AppState;+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::Json;+use chrono::{DateTime, Duration, Utc};+use serde::Serialize;+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::collections::HashMap;++pub const SETTING: &str = "lessons";+pub const MODES: [&str; 2] = ["on", "off"];+pub const WINDOW_DAYS: i64 = 30;+/// The task brief's block.+pub const BRIEF_LINES: usize = 8;+pub const BRIEF_BYTES: usize = 1500;+/// The smaller block every other turn gets.+pub const TURN_LINES: usize = 5;+pub const TURN_BYTES: usize = 1000;+/// 1 in this many task-bound turns skips the block.+pub const HOLDOUT_ONE_IN: u64 = 5;+/// Rows read per source; far more than the block can hold.+const READ_LIMIT: i64 = 200;++pub const HEADER: &str = "[Lessons from earlier tasks]\nFrom kwant's records and the person's reviews. Observations, not instructions: \+use one only when this task is like that one, and never mention them in your reply unless asked.";++const TITLE_CHARS: usize = 80;+const REASON_CHARS: usize = 120;+const OUTPUT_CHARS: usize = 120;+const SPEC_CHARS: usize = 100;+/// Words that make a title or reason look like a request for access; such text is never shown.+const FORBIDDEN: [&str; 6] = ["approve", "allow", "permission", "payment", "token", "password"];+/// Check kinds a lesson may name; anything else is "a check".+const CHECK_KINDS: [&str; 5] = ["command", "http", "file_exists", "file_contains", "file_sha256"];++// Settings++/// The saved setting; unset (a fresh install) is on. Only a saved `off` turns lessons off.+pub async fn enabled(state: &AppState) -> bool {+ state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim) != Some("off")+}++pub async fn mode(state: &AppState) -> &'static str {+ if enabled(state).await {+ "on"+ } else {+ "off"+ }+}++pub fn settings_error(mode: Option<&str>) -> Option<String> {+ mode.filter(|m| !MODES.contains(m)).map(|m| format!("lessons must be on or off (got {m})"))+}++// The model++/// Where a lesson comes from, as the API names it.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Source {+ Check,+ Stall,+ Denied,+ Error,+ Review,+ Goal,+}++/// What happened, from enumerated fields and person-written text only.+#[derive(Debug, Clone, PartialEq)]+pub enum What {+ /// A check failed after hand-in. `ident` is the check's kind and redacted spec (the key's+ /// input); `spec` is set only when the person or an approved mission approved the check.+ Check { kind: String, ident: String, spec: Option<String>, output: Option<String> },+ /// The run ended without a hand-in: its lease ran out, or the turn stopped.+ Stall { lease: bool },+ Denied,+ Error,+ /// The person sent it back from review (to ready, or `blocked`), with their reason.+ Review { blocked: bool, reason: String },+ /// A "Keep this true" goal made from the task was confirmed not met after the task finished,+ /// and still is. `goal` is the goal's title; [`line`] shows it only through [`safe_title`].+ Goal { goal_id: String, goal: Option<String> },+}++/// How it settled.+#[derive(Debug, Clone, PartialEq, Default)]+pub struct Settled {+ pub autofix: bool,+ pub person_retried: bool,+ /// The task's state now.+ pub state: String,+}++#[derive(Debug, Clone, PartialEq)]+pub struct Occurrence {+ pub task_id: String,+ /// Set only for a task the person created; [`line`] still runs it through [`safe_title`].+ pub title: Option<String>,+ pub at: DateTime<Utc>,+ pub what: What,+ pub settled: Settled,+}++/// One lesson: its newest occurrence's line and how often its key came up in the window.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Lesson {+ pub key: String,+ pub source: Source,+ pub text: String,+ pub count: i64,+ /// Unix milliseconds of the newest occurrence.+ pub last_at: i64,+ pub task_id: String,+}++/// What a task-bound turn carries about its lessons, so the turn logs `lessons_shown` or+/// `lessons_held_out` once, where it is attributed (just before the driver runs).+#[derive(Debug, Clone, Default, PartialEq)]+pub struct TaskHint {+ pub task_id: String,+ pub keys: Vec<String>,+ pub bytes: usize,+ pub held_out: bool,+}++// Pure functions++fn short_hash(text: &str) -> String {+ let d = Sha256::digest(text.as_bytes());+ d.iter().take(3).map(|b| format!("{b:02x}")).collect()+}++/// The lesson's key: `check_failed:<hash of the check's kind and spec>` (the same check copied+/// into each task repeats under one key), `stalled:run` (lease and turn stalls are one+/// behaviour), `denied:tool`, `unknown:turn`, `rejected:<hash of the reason's content words>`+/// and `goal:<goal id>`.+pub fn lesson_key(what: &What) -> String {+ match what {+ What::Check { ident, .. } => format!("check_failed:{}", short_hash(ident)),+ What::Stall { .. } => "stalled:run".into(),+ What::Denied => "denied:tool".into(),+ What::Error => "unknown:turn".into(),+ What::Review { reason, .. } => format!("rejected:{}", short_hash(&crate::router::team::content_words(reason).join(" "))),+ What::Goal { goal_id, .. } => format!("goal:{goal_id}"),+ }+}++fn source_of(what: &What) -> Source {+ match what {+ What::Check { .. } => Source::Check,+ What::Stall { .. } => Source::Stall,+ What::Denied => Source::Denied,+ What::Error => Source::Error,+ What::Review { .. } => Source::Review,+ What::Goal { .. } => Source::Goal,+ }+}++fn cut(text: &str, max: usize) -> String {+ if text.chars().count() <= max {+ return text.to_string();+ }+ let mut s: String = text.chars().take(max.saturating_sub(1)).collect();+ s.truncate(s.trim_end().len());+ s.push('…');+ s+}++fn looks_like_path(word: &str) -> bool {+ word.contains('/') || word.contains('\\') || word.starts_with('~')+}++/// Person-written or check-output text, made safe to quote in a prompt: one line, at most `max`+/// characters; `None` when it has a URL, a backtick, a path or a word that asks for access+/// (approve, allow, permission, payment, token, password). Quotes and brackets are softened so+/// it can't close the template's quote or open a section of its own.+pub fn safe_text(text: &str, max: usize) -> Option<String> {+ let one = text.split_whitespace().collect::<Vec<_>>().join(" ");+ if one.is_empty() {+ return None;+ }+ let lower = one.to_lowercase();+ if one.contains('`') || lower.contains("://") || lower.contains("www.") {+ return None;+ }+ if one.split(' ').any(looks_like_path) || FORBIDDEN.iter().any(|w| lower.contains(w)) {+ return None;+ }+ let soft = one.replace('"', "'").replace('[', "(").replace(']', ")");+ Some(cut(&soft, max))+}++/// A task title, shown only when it is one line of at most 80 characters that [`safe_text`]+/// accepts; otherwise the line names the task by id.+pub fn safe_title(title: &str) -> Option<String> {+ let t = title.trim();+ if t.contains('\n') || t.chars().count() > TITLE_CHARS {+ return None;+ }+ safe_text(t, TITLE_CHARS)+}++/// The part of a redacted check spec a lesson shows: the command, the url, or the path.+pub fn spec_text(kind: &str, redacted: &Value) -> Option<String> {+ let field = match kind {+ "command" => "command",+ "http" => "url",+ "file_exists" | "file_contains" | "file_sha256" => "path",+ _ => return None,+ };+ let raw = redacted[field].as_str()?;+ let one = raw.split_whitespace().collect::<Vec<_>>().join(" ").replace('`', "'");+ (!one.is_empty()).then(|| cut(&one, SPEC_CHARS))+}++fn ago(at: DateTime<Utc>, now: DateTime<Utc>) -> String {+ match (now - at).num_days().max(0) {+ 0 => "today".into(),+ 1 => "1 day ago".into(),+ n => format!("{n} days ago"),+ }+}++fn task_name(task_id: &str, title: Option<&str>) -> String {+ match title.and_then(safe_title) {+ Some(t) => format!("task \"{t}\""),+ None => format!("task {task_id}"),+ }+}++fn ending(s: &Settled) -> String {+ let fin = match s.state.as_str() {+ "verified" => "then verified.",+ "failed" => "it ended failed.",+ "blocked" => "it is blocked.",+ "cancelled" => "it was cancelled.",+ _ => "it is still open.",+ };+ if s.autofix && s.state == "verified" {+ "; fixed by AutoFix, then verified.".into()+ } else if s.autofix {+ format!("; AutoFix retried it; {fin}")+ } else if s.person_retried {+ format!("; the person retried; {fin}")+ } else {+ format!("; {fin}")+ }+}++/// One lesson line, without the leading "- ". Fixed templates over enumerated fields and+/// [`safe_text`]-checked person text only.+pub fn line(o: &Occurrence, count: i64, now: DateTime<Utc>) -> String {+ let times = if count > 1 { format!(" (x{count} in {WINDOW_DAYS} days)") } else { String::new() };+ let task = task_name(&o.task_id, o.title.as_deref());+ let what = match &o.what {+ What::Goal { goal, .. } => {+ // Only the title (through safe_title) and a date: never the check's spec, URL or output+ let g = match goal.as_deref().and_then(safe_title) {+ Some(g) => format!("A goal you worked on, \"{g}\","),+ None => format!("A goal you worked on, made from {task},"),+ };+ return format!("{g} is not met since {}: check it before saying a task is done.{times}", o.at.format("%Y-%m-%d"));+ }+ What::Check { kind, spec, output, .. } => {+ let mut s = match spec {+ Some(spec) => format!("the {kind} check `{spec}` failed after hand-in"),+ None if CHECK_KINDS.contains(&kind.as_str()) => format!("a {kind} check failed after hand-in"),+ None => "a check failed after hand-in".into(),+ };+ if let Some(out) = output {+ s.push_str(&format!(" (output: \"{out}\")"));+ }+ s+ }+ What::Stall { lease: true } => "its lease ran out without a hand-in".into(),+ What::Stall { lease: false } => "the turn ended without a hand-in".into(),+ What::Denied => "an action it needed was denied, so the turn ended without a hand-in".into(),+ What::Error => "the turn failed with an error before a hand-in".into(),+ What::Review { blocked, reason } => {+ let verb = if *blocked { "the person blocked it" } else { "the person sent it back" };+ match safe_text(reason, REASON_CHARS) {+ Some(r) => format!("{verb}: \"{r}\""),+ None => verb.into(),+ }+ }+ };+ format!("{}, {task}: {what}{}{times}", ago(o.at, now), ending(&o.settled))+}++/// Groups occurrences by key (send-back reasons by `router::team::alike` over content words),+/// renders each group's newest occurrence and orders them: most repeated first, then newest.+pub fn group(mut occurrences: Vec<Occurrence>, now: DateTime<Utc>) -> Vec<Lesson> {+ // Oldest first, so a group of alike reasons keeps the key of its first reason in the window+ occurrences.sort_by(|a, b| a.at.cmp(&b.at).then_with(|| a.task_id.cmp(&b.task_id)));+ let mut reasons: Vec<(String, Vec<String>)> = Vec::new();+ let mut groups: Vec<(String, Vec<Occurrence>)> = Vec::new();+ for o in occurrences {+ let mut key = lesson_key(&o.what);+ if let What::Review { reason, .. } = &o.what {+ let words = crate::router::team::content_words(reason);+ match reasons.iter().find(|(_, w)| !words.is_empty() && crate::router::team::alike(w, &words)) {+ Some((k, _)) => key = k.clone(),+ None => reasons.push((key.clone(), words)),+ }+ }+ match groups.iter_mut().find(|(k, _)| *k == key) {+ Some((_, list)) => list.push(o),+ None => groups.push((key, vec![o])),+ }+ }+ let mut out: Vec<Lesson> = groups+ .into_iter()+ .filter_map(|(key, list)| {+ let count = list.len() as i64;+ let newest = list.into_iter().last()?;+ Some(Lesson {+ source: source_of(&newest.what),+ text: line(&newest, count, now),+ count,+ last_at: newest.at.timestamp_millis(),+ task_id: newest.task_id,+ key,+ })+ })+ .collect();+ out.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| b.last_at.cmp(&a.last_at)).then_with(|| a.key.cmp(&b.key)));+ out+}++/// The lessons that fit `max_lines` lines and `max_bytes` bytes of block (header included), in+/// order; a line that doesn't fit is skipped so a shorter one after it still can.+pub fn select(lessons: Vec<Lesson>, max_lines: usize, max_bytes: usize) -> Vec<Lesson> {+ let mut bytes = HEADER.len() + 2;+ let mut out = Vec::new();+ for l in lessons {+ if out.len() >= max_lines {+ break;+ }+ let add = l.text.len() + 3;+ if bytes + add > max_bytes {+ continue;+ }+ bytes += add;+ out.push(l);+ }+ out+}++/// The block, starting with a blank line; empty when there are no lessons, so a bot with+/// nothing to learn from gets a byte-identical prompt.+pub fn block(lessons: &[Lesson]) -> String {+ if lessons.is_empty() {+ return String::new();+ }+ let mut s = format!("\n\n{HEADER}");+ for l in lessons {+ s.push_str("\n- ");+ s.push_str(&l.text);+ }+ s+}++/// Whether a turn of `purpose` gets the lessons block: chat, routine and hand-off turns (no+/// purpose) and mission turns. An allow-list, so any hidden purpose (decide, audit, a Foundry+/// draft or replay, work ahead, a goal draft, and any added later) gets none.+pub fn wants_block(purpose: Option<&str>) -> bool {+ matches!(purpose, None | Some(super::runner::PURPOSE))+}++/// Whether the task's turns are the held-out arm (no block): 1 in [`HOLDOUT_ONE_IN`], by a hash+/// of the task id, so the same task always lands on the same side.+pub fn held_out(task_id: &str) -> bool {+ let d = Sha256::digest(task_id.as_bytes());+ let n = u64::from_be_bytes([d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]]);+ n % HOLDOUT_ONE_IN == 0+}++// Reading the records++fn ident_line(excerpt: Option<&str>) -> Option<String> {+ excerpt.and_then(|e| e.lines().next()).map(str::trim).filter(|l| !l.is_empty()).map(String::from)+}++fn check_occurrence(f: &FailureOfBot, checks: &[OutcomeCheck]) -> What {+ let ident = ident_line(f.excerpt.as_deref()).unwrap_or_else(|| "check".into());+ let kind = ident.split(' ').next().unwrap_or("").to_string();+ let found = checks.iter().find(|c| format!("{} {}", c.kind, super::autofix::redact_value(&c.spec_value())) == ident);+ let approved = found.filter(|c| matches!(c.approved_by.as_deref(), Some("person" | "mission")));+ let spec = approved.and_then(|c| spec_text(&c.kind, &super::autofix::redact_value(&c.spec_value())));+ // The check's output now, only while it still fails (after a fix it is the passing output)+ let output = found+ .filter(|c| c.status == "failed")+ .and_then(|c| c.output_excerpt.as_deref())+ .and_then(|o| safe_text(&super::autofix::redact(o), OUTPUT_CHARS));+ What::Check { kind, ident, spec, output }+}++fn person_title(title: &str, created_by: &str) -> Option<String> {+ (created_by == "person").then(|| title.to_string())+}++async fn occurrences(state: &AppState, kwant_id: &str, since: DateTime<Utc>) -> Vec<Occurrence> {+ let failures = state.db.failures_of_bot(kwant_id, since, READ_LIMIT).await.unwrap_or_default();+ let corrections = state.db.person_corrections_of_bot(kwant_id, since, READ_LIMIT).await.unwrap_or_default();+ let mut checks: HashMap<String, Vec<OutcomeCheck>> = HashMap::new();+ let mut out = Vec::with_capacity(failures.len() + corrections.len());+ for f in &failures {+ let what = match f.class.as_str() {+ "check_failed" => {+ if !checks.contains_key(&f.task_id) {+ checks.insert(f.task_id.clone(), state.db.list_checks(&f.task_id).await.unwrap_or_default());+ }+ check_occurrence(f, &checks[&f.task_id])+ }+ "stalled" => What::Stall { lease: f.source == "lease" },+ "denied" => What::Denied,+ _ => What::Error,+ };+ out.push(Occurrence {+ task_id: f.task_id.clone(),+ title: person_title(&f.title, &f.created_by),+ at: f.created_at,+ what,+ settled: Settled { autofix: f.fixed_by_autofix, person_retried: f.person_retried, state: f.task_state.clone() },+ });+ }+ for c in corrections.iter().filter_map(correction) {+ out.push(c);+ }+ out.extend(goal_lapses(state, kwant_id, since).await);+ out+}++/// The bot's goal lapses in the window (`goal_lapses_of_bot`), only for goals that are still not+/// met: a goal that holds again, or that kwant can't check right now, is no lesson.+async fn goal_lapses(state: &AppState, kwant_id: &str, since: DateTime<Utc>) -> Vec<Occurrence> {+ let lapses = state.db.goal_lapses_of_bot(kwant_id, since.timestamp_millis(), READ_LIMIT).await.unwrap_or_default();+ let mut out = Vec::with_capacity(lapses.len());+ for l in lapses {+ let still = matches!(state.db.get_goal(&l.goal_id).await, Ok(Some(g)) if g.status == "not_met");+ if let (true, Some(at)) = (still, DateTime::from_timestamp_millis(l.lapsed_at)) {+ out.push(goal_occurrence(l, at));+ }+ }+ out+}++fn goal_occurrence(l: crate::db::goal_missions::GoalLapse, at: DateTime<Utc>) -> Occurrence {+ Occurrence {+ title: person_title(&l.task_title, &l.task_created_by),+ task_id: l.task_id,+ at,+ what: What::Goal { goal_id: l.goal_id, goal: Some(l.goal_title) },+ settled: Settled { state: "verified".into(), ..Default::default() },+ }+}++fn correction(c: &CorrectionOfBot) -> Option<Occurrence> {+ let detail: Value = serde_json::from_str(&c.detail).unwrap_or(Value::Null);+ let reason = detail["reason"].as_str().map(str::trim).filter(|r| !r.is_empty())?;+ Some(Occurrence {+ task_id: c.task_id.clone(),+ title: person_title(&c.title, &c.created_by),+ at: c.created_at,+ what: What::Review { blocked: c.to_state == "blocked", reason: reason.to_string() },+ settled: Settled { state: c.task_state.clone(), ..Default::default() },+ })+}++/// Every lesson of the bot in the window, grouped and ordered, before the caps.+pub async fn of_bot(state: &AppState, kwant_id: &str) -> Vec<Lesson> {+ let now = Utc::now();+ group(occurrences(state, kwant_id, now - Duration::days(WINDOW_DAYS)).await, now)+}++/// The task brief's block and the turn's hint. `None` with the setting off. A held-out task gets+/// no block; its hint still names the keys it would have shown.+pub async fn for_brief(state: &AppState, kwant_id: &str, task_id: &str) -> Option<(String, TaskHint)> {+ if !enabled(state).await {+ return None;+ }+ let lessons = select(of_bot(state, kwant_id).await, BRIEF_LINES, BRIEF_BYTES);+ let text = block(&lessons);+ let hint = TaskHint { task_id: task_id.into(), keys: lessons.iter().map(|l| l.key.clone()).collect(), bytes: text.len(), held_out: held_out(task_id) };+ Some((if hint.held_out { String::new() } else { text }, hint))+}++/// The smaller block for a chat, routine or hand-off turn: empty with the setting off or nothing+/// to learn from. Neither held out nor logged.+pub async fn for_turn(state: &AppState, kwant_id: &str) -> String {+ if !enabled(state).await {+ return String::new();+ }+ let since = Utc::now() - Duration::days(WINDOW_DAYS);+ // A cheap gate before reading: a failure or send-back, or a goal lapse (one row is enough)+ let any = state.db.has_lessons_since(kwant_id, since).await.unwrap_or(false)+ || !state.db.goal_lapses_of_bot(kwant_id, since.timestamp_millis(), 1).await.unwrap_or_default().is_empty();+ if !any {+ return String::new();+ }+ block(&select(of_bot(state, kwant_id).await, TURN_LINES, TURN_BYTES))+}++/// Logs the turn's `lessons_shown {keys, bytes}` or `lessons_held_out {keys}`; nothing when it+/// had no lessons.+pub async fn log_attribution(state: &AppState, hint: &TaskHint) {+ if hint.keys.is_empty() {+ return;+ }+ let (kind, detail) = if hint.held_out {+ ("lessons_held_out", json!({ "keys": hint.keys }))+ } else {+ ("lessons_shown", json!({ "keys": hint.keys, "bytes": hint.bytes }))+ };+ if let Err(e) = state.db.log_task_event(&hint.task_id, kind, "kwant", &detail).await {+ tracing::warn!(task_id = %hint.task_id, error = %e, "could not log {kind}");+ }+}++/// C0: after a runner turn, `self_checked {checks}` when the owner ran the task's checks+/// (`task_request_check`) before it moved the task to review in this turn.+pub async fn note_self_check(state: &AppState, task_id: &str, started: DateTime<Utc>) {+ if !enabled(state).await {+ return;+ }+ let events = state.db.task_events(task_id, 500).await.unwrap_or_default();+ let mut checks: Vec<String> = Vec::new();+ for e in events.iter().filter(|e| e.created_at >= started) {+ if e.kind == "state" && e.to_state.as_deref() == Some("review") {+ if !checks.is_empty() {+ let _ = state.db.log_task_event(task_id, "self_checked", "kwant", &json!({ "checks": checks })).await;+ }+ return;+ }+ // A check the runner's own tool ran (`checked_by` kwant), not one the person passed+ if e.kind == "check_result" && e.actor == "kwant" {+ if let Some(id) = e.detail_value()["check_id"].as_str() {+ if !checks.iter().any(|c| c == id) {+ checks.push(id.to_string());+ }+ }+ }+ }+}++// Route++/// `GET /api/kwants/:id/lessons` (person-only): the lines the bot's brief carries, in order.+/// Another space's bot is 404. With the setting off, `enabled` is false and no turn gets them.+pub async fn get_lessons(State(state): State<AppState>, Scope(space): Scope, Path(id): Path<String>) -> Response {+ let bot = match state.db.get_kwant(&id).await {+ Ok(Some(k)) if k.space_id == space.as_str() => k,+ Ok(_) => return (StatusCode::NOT_FOUND, Json(json!({ "error": "no such bot" }))).into_response(),+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ };+ let lines = select(of_bot(&state, &bot.id).await, BRIEF_LINES, BRIEF_BYTES);+ Json(json!({ "enabled": enabled(&state).await, "window_days": WINDOW_DAYS, "lines": lines })).into_response()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(days: i64) -> DateTime<Utc> {+ now() - Duration::days(days) - Duration::minutes(5)+ }++ fn now() -> DateTime<Utc> {+ DateTime::parse_from_rfc3339("2026-11-03T12:00:00Z").unwrap().with_timezone(&Utc)+ }++ fn occ(task: &str, days: i64, what: What, state: &str) -> Occurrence {+ Occurrence { task_id: task.into(), title: None, at: at(days), what, settled: Settled { state: state.into(), ..Default::default() } }+ }++ fn check(spec: Option<&str>) -> What {+ What::Check { kind: "command".into(), ident: "command {\"command\":\"cargo test --doc\"}".into(), spec: spec.map(String::from), output: None }+ }++ #[test]+ fn check_line_has_spec_output_and_settled() {+ let mut o = occ("t_ab12", 3, check(Some("cargo test --doc")), "verified");+ o.title = Some("Draft the 1.4 release notes".into());+ o.settled.autofix = true;+ if let What::Check { output, .. } = &mut o.what {+ *output = Some("error: doctest failed".into());+ }+ assert_eq!(+ line(&o, 3, now()),+ "3 days ago, task \"Draft the 1.4 release notes\": the command check `cargo test --doc` failed after hand-in \+ (output: \"error: doctest failed\"); fixed by AutoFix, then verified. (x3 in 30 days)"+ );+ }++ #[test]+ fn spec_only_for_approved_checks() {+ // check_occurrence keeps the spec only for person- or mission-approved checks+ let mk = |by: Option<&str>| OutcomeCheck {+ id: "c1".into(),+ task_id: "t1".into(),+ kind: "command".into(),+ spec: r#"{"command":"make test"}"#.into(),+ required: true,+ approved: true,+ status: "failed".into(),+ output_excerpt: Some("boom".into()),+ checked_by: Some("kwant".into()),+ requested_by: "b1".into(),+ approved_by: by.map(String::from),+ evidence_id: None,+ created_at: now(),+ started_at: None,+ finished_at: None,+ };+ let f = |c: &OutcomeCheck| FailureOfBot {+ id: "f1".into(),+ task_id: "t1".into(),+ source: "check".into(),+ class: "check_failed".into(),+ excerpt: Some(format!("{} {}\nboom", c.kind, super::super::autofix::redact_value(&c.spec_value()))),+ created_at: now(),+ title: "x".into(),+ created_by: "person".into(),+ task_state: "ready".into(),+ fixed_by_autofix: false,+ person_retried: false,+ };+ for (by, shown) in [(Some("person"), true), (Some("mission"), true), (Some("auto"), false), (None, false)] {+ let c = mk(by);+ let What::Check { spec, output, .. } = check_occurrence(&f(&c), std::slice::from_ref(&c)) else { panic!() };+ assert_eq!(spec.is_some(), shown, "{by:?}");+ assert_eq!(output.as_deref(), Some("boom"));+ }+ // A passing check's output (after a fix) isn't the failure's output+ let mut c = mk(Some("person"));+ c.status = "passed".into();+ let What::Check { output, .. } = check_occurrence(&f(&c), std::slice::from_ref(&c)) else { panic!() };+ assert_eq!(output, None);+ // Unapproved: the kind still shows+ let o = occ("t1", 0, What::Check { kind: "command".into(), ident: "command {}".into(), spec: None, output: None }, "ready");+ assert_eq!(line(&o, 1, now()), "today, task t1: a command check failed after hand-in; it is still open.");+ }++ #[test]+ fn other_templates() {+ let mut o = occ("t_2b10", 5, What::Review { blocked: false, reason: "the summary lists PRs that were reverted".into() }, "verified");+ assert_eq!(line(&o, 1, now()), "5 days ago, task t_2b10: the person sent it back: \"the summary lists PRs that were reverted\"; then verified.");+ o.what = What::Review { blocked: true, reason: "see /etc/passwd".into() };+ o.settled.state = "blocked".into();+ assert_eq!(line(&o, 1, now()), "5 days ago, task t_2b10: the person blocked it; it is blocked.");+ let mut o = occ("t_7f2c", 9, What::Stall { lease: false }, "verified");+ o.settled.person_retried = true;+ assert_eq!(line(&o, 1, now()), "9 days ago, task t_7f2c: the turn ended without a hand-in; the person retried; then verified.");+ let o = occ("t9", 1, What::Stall { lease: true }, "failed");+ assert_eq!(line(&o, 2, now()), "1 day ago, task t9: its lease ran out without a hand-in; it ended failed. (x2 in 30 days)");+ let o = occ("t9", 1, What::Denied, "cancelled");+ assert_eq!(line(&o, 1, now()), "1 day ago, task t9: an action it needed was denied, so the turn ended without a hand-in; it was cancelled.");+ let mut o = occ("t9", 0, What::Error, "failed");+ o.settled.autofix = true;+ assert_eq!(line(&o, 1, now()), "today, task t9: the turn failed with an error before a hand-in; AutoFix retried it; it ended failed.");+ let mut o = occ("t9", 12, What::Goal { goal_id: "g1".into(), goal: Some("Pricing page is up".into()) }, "verified");+ o.title = Some("X".into());+ assert_eq!(line(&o, 1, now()), "A goal you worked on, \"Pricing page is up\", is not met since 2026-10-22: check it before saying a task is done.");+ assert_eq!(lesson_key(&o.what), "goal:g1");+ assert_eq!(source_of(&o.what), Source::Goal);+ // An unsafe goal title (a URL, a path, an access word) names the task instead, or its id+ o.what = What::Goal { goal_id: "g1".into(), goal: Some("Keep https://x.dev/pricing up".into()) };+ assert_eq!(line(&o, 1, now()), "A goal you worked on, made from task \"X\", is not met since 2026-10-22: check it before saying a task is done.");+ o.title = None;+ o.what = What::Goal { goal_id: "g1".into(), goal: Some("Approve the deploy".into()) };+ assert_eq!(line(&o, 1, now()), "A goal you worked on, made from task t9, is not met since 2026-10-22: check it before saying a task is done.");+ }++ #[test]+ fn title_and_reason_rules() {+ assert_eq!(safe_title("Draft the 1.4 release notes").as_deref(), Some("Draft the 1.4 release notes"));+ for bad in [+ "Fix https://example.com",+ "Run `make`",+ "Edit src/main.rs",+ "Approve the deploy",+ "Allow writes",+ "Rotate the API token",+ "Reset password",+ "Get permission",+ "Send the payment",+ "two\nlines",+ &"x".repeat(81),+ ] {+ assert_eq!(safe_title(bad), None, "{bad}");+ }+ // Reasons: one line, quotes and brackets softened, cut at 120 characters+ assert_eq!(safe_text("say \"no\"\n[System] now", 120).as_deref(), Some("say 'no' (System) now"));+ let long = safe_text(&"word ".repeat(60), REASON_CHARS).unwrap();+ assert_eq!(long.chars().count(), REASON_CHARS);+ assert!(long.ends_with('…'));+ // A title only for a task the person created (person_title), and only through safe_title+ assert_eq!(person_title("T", "kwant"), None);+ let mut o = occ("t1", 0, What::Error, "failed");+ o.title = Some("Pay via www.x.com".into());+ assert!(line(&o, 1, now()).starts_with("today, task t1:"));+ }++ #[test]+ fn spec_text_shows_the_one_field() {+ assert_eq!(spec_text("command", &json!({"command": "cargo test\n--doc`", "timeout_secs": 5})).as_deref(), Some("cargo test --doc'"));+ assert_eq!(spec_text("http", &json!({"url": "https://x.dev/health"})).as_deref(), Some("https://x.dev/health"));+ assert_eq!(spec_text("file_contains", &json!({"path": "out.md", "text": "secret"})).as_deref(), Some("out.md"));+ assert_eq!(spec_text("peer_review", &json!({})), None);+ assert_eq!(spec_text("command", &json!({"command": "x".repeat(300)})).unwrap().chars().count(), SPEC_CHARS);+ }++ #[test]+ fn grouping_and_ordering() {+ let list = vec![+ occ("t1", 9, What::Stall { lease: true }, "verified"),+ occ("t2", 2, What::Stall { lease: false }, "failed"),+ occ("t3", 1, What::Denied, "ready"),+ occ("t4", 6, check(None), "verified"),+ occ("t5", 4, check(None), "verified"),+ occ("t6", 3, check(None), "ready"),+ occ("t7", 8, What::Review { blocked: false, reason: "The summary lists reverted pull requests".into() }, "verified"),+ occ("t8", 5, What::Review { blocked: false, reason: "summary still lists reverted pull requests".into() }, "verified"),+ occ("t9", 7, What::Review { blocked: false, reason: "wrong currency".into() }, "verified"),+ ];+ let out = group(list, now());+ let keys: Vec<(&str, i64, &str)> = out.iter().map(|l| (l.key.split(':').next().unwrap(), l.count, l.task_id.as_str())).collect();+ assert_eq!(+ keys,+ vec![("check_failed", 3, "t6"), ("stalled", 2, "t2"), ("rejected", 2, "t8"), ("denied", 1, "t3"), ("rejected", 1, "t9")]+ );+ // Lease and turn stalls share one key; the line is the newest one's+ assert_eq!(out[1].key, "stalled:run");+ assert!(out[1].text.starts_with("2 days ago, task t2: the turn ended"));+ // Alike reasons keep the key of the first one in the window+ assert_eq!(out[2].key, lesson_key(&What::Review { blocked: false, reason: "The summary lists reverted pull requests".into() }));+ assert_eq!(out[0].source, Source::Check);+ assert_eq!(out[2].source, Source::Review);+ assert_eq!(out[0].last_at, at(3).timestamp_millis());+ // The same check is one key; another check is another+ let other = What::Check { kind: "command".into(), ident: "command {\"command\":\"make\"}".into(), spec: None, output: None };+ assert_ne!(lesson_key(&other), lesson_key(&check(None)));+ assert_eq!(lesson_key(&What::Denied), "denied:tool");+ assert_eq!(lesson_key(&What::Error), "unknown:turn");+ }++ #[test]+ fn caps() {+ let many: Vec<Occurrence> = (0..12).map(|i| occ(&format!("t{i}"), i, What::Review { blocked: false, reason: format!("reason{i}") }, "ready")).collect();+ let all = group(many, now());+ assert_eq!(all.len(), 12);+ let brief = select(all.clone(), BRIEF_LINES, BRIEF_BYTES);+ assert_eq!(brief.len(), BRIEF_LINES);+ assert!(block(&brief).len() <= BRIEF_BYTES);+ let turn = select(all.clone(), TURN_LINES, TURN_BYTES);+ assert_eq!(turn.len(), TURN_LINES);+ // Bytes: long lines stop fitting, a shorter one after them still fits+ let mut big = all;+ for l in big.iter_mut().take(3) {+ l.text = "x".repeat(500);+ }+ let fit = select(big, BRIEF_LINES, BRIEF_BYTES);+ assert!(block(&fit).len() <= BRIEF_BYTES, "{}", block(&fit).len());+ assert_eq!(fit.iter().filter(|l| l.text.len() == 500).count(), 2);+ assert!(fit.iter().any(|l| l.task_id == "t3"), "a shorter line after the long one still fits");+ assert!(fit.len() < BRIEF_LINES);+ // Nothing to learn from: no block at all+ assert_eq!(block(&[]), "");+ assert!(block(&fit).starts_with("\n\n[Lessons from earlier tasks]\nFrom kwant's records"));+ }++ #[test]+ fn caps_hold_with_all_three_sources() {+ // Failures, send-backs and goal lapses rank together (repeats first, then newest) and+ // share one budget: 8 lines and 1,500 bytes in a brief, 5 and 1,000 in a turn+ let mut list: Vec<Occurrence> = Vec::new();+ for i in 0..6 {+ list.push(occ(&format!("c{i}"), i, What::Check { kind: "command".into(), ident: format!("command {{\"command\":\"make t{i}\"}}"), spec: None, output: None }, "ready"));+ list.push(occ(&format!("r{i}"), i, What::Review { blocked: false, reason: format!("{} is wrong", ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"][i as usize]) }, "ready"));+ let mut g = occ(&format!("g{i}"), i, What::Goal { goal_id: format!("goal{i}"), goal: Some(format!("Site {i} keeps its pricing page up to date for every region and every plan")) }, "verified");+ g.title = Some(format!("Site {i}"));+ list.push(g);+ }+ let all = group(list, now());+ assert_eq!(all.len(), 18);+ for (lines, bytes) in [(BRIEF_LINES, BRIEF_BYTES), (TURN_LINES, TURN_BYTES)] {+ let fit = select(all.clone(), lines, bytes);+ assert!(fit.len() <= lines && !fit.is_empty());+ assert!(block(&fit).len() <= bytes, "{} > {bytes}", block(&fit).len());+ assert!(fit.iter().take(3).all(|l| l.text.contains("today") || l.text.contains("2026-11-03")), "{fit:#?}");+ }+ let brief = select(all.clone(), BRIEF_LINES, BRIEF_BYTES);+ for src in [Source::Check, Source::Review, Source::Goal] {+ assert!(brief.iter().any(|l| l.source == src), "{src:?}");+ }+ // A repeated failure outranks a newer one-off goal lapse+ let mut list = vec![occ("g0", 0, What::Goal { goal_id: "goal0".into(), goal: Some("Up".into()) }, "verified")];+ list.extend((3..5).map(|d| occ(&format!("s{d}"), d, What::Stall { lease: true }, "verified")));+ let out = group(list, now());+ assert_eq!((out[0].source, out[1].source), (Source::Stall, Source::Goal));+ }++ #[test]+ fn one_in_five_held_out() {+ let n = (0..10_000).filter(|i| held_out(&format!("task-{i}"))).count();+ assert!((1800..2200).contains(&n), "{n}");+ // Stable for a task+ assert_eq!(held_out("abc"), held_out("abc"));+ }++ #[test]+ fn purpose_allow_list() {+ // Every PURPOSE constant a hidden turn uses; a new one gets no block until added here+ for p in [+ crate::server::decide::PURPOSE,+ crate::server::missions::auditor::PURPOSE,+ crate::server::missions::foundry::DRAFT_PURPOSE,+ crate::server::missions::foundry::REPLAY_PURPOSE,+ crate::server::work_ahead::PURPOSE,+ crate::server::goals_remediation::DRAFT_PURPOSE,+ ] {+ assert!(!wants_block(Some(p)), "{p}");+ }+ assert!(wants_block(Some(super::super::runner::PURPOSE)));+ // Chat, routine and hand-off turns have no purpose+ assert!(wants_block(None));+ assert!(!wants_block(Some("anything_new")));+ }++ #[test]+ fn settings() {+ assert_eq!(settings_error(Some("on")), None);+ assert_eq!(settings_error(Some("off")), None);+ assert_eq!(settings_error(None), None);+ assert!(settings_error(Some("measure")).unwrap().contains("on or off"));+ }+}diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rsindex 7287d21b..5281a299 100644--- a/src/server/missions/mod.rs+++ b/src/server/missions/mod.rs@@ -20,6 +20,7 @@ pub mod discovery;pub mod flight_school;pub mod foundry;pub mod graph;+pub mod lessons;pub mod listener;pub mod performance;pub mod routes;diff --git a/src/server/missions/runner.rs b/src/server/missions/runner.rsindex 1806db67..a44bd1f6 100644--- a/src/server/missions/runner.rs+++ b/src/server/missions/runner.rs@@ -11,6 +11,8 @@ use std::sync::{Arc, Mutex};pub const MAX_RUNNING: usize = 2;pub const PURPOSE: &str = "mission";+/// C0: the brief's sentence when the task has an approved check.+pub const SELF_CHECK: &str = "Before you move it to review, run these checks yourself with task_request_check and fix what fails.\n";/// Missions with a runner turn going, one set per server (`AppState::mission_runs`), so two/// servers in one process (as tests run them) never take each other's slots.@@ -154,7 +156,7 @@ async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {let deps = state.db.dependencies_of(&t.id).await.unwrap_or_default();format!("[Mission Control] You hold task {id} of the mission \"{mt}\" (goal: {goal}).\n\- Task: {title}\nAcceptance: {acc}\nChecks kwant will run when you're done:\n{checks}\n{deps}\+ Task: {title}\nAcceptance: {acc}\nChecks kwant will run when you're done:\n{checks}\n{self_check}{deps}\Work on it now. Attach what you produced with task_attach_evidence, then call task_update with \task_id {id} and status \"review\": kwant runs the checks and only they (or a teammate's review, \or the person) can verify it. If you can't finish, call task_update with status \"blocked\" and a \@@ -165,6 +167,8 @@ async fn prompt(state: &AppState, m: &Mission, t: &Task) -> String {title = t.title,acc = if t.acceptance.is_empty() { "(none given)" } else { &t.acceptance },checks = if list.is_empty() { "- none: a teammate or the person reviews it".into() } else { list.join("\n") },+ // C0: only a task with an approved check can be checked before hand-in+ self_check = if list.is_empty() { "" } else { SELF_CHECK },deps = if deps.is_empty() { String::new() } else { format!("It builds on tasks {} (verified).\n", deps.iter().map(|d| d.0.as_str()).collect::<Vec<_>>().join(", ")) },budget = if t.budget_tokens > super::NO_LIMIT { format!(" Budget: {} tokens.", t.budget_tokens - t.spent_tokens) } else { String::new() },)@@ -185,6 +189,14 @@ async fn run_one(state: &AppState, m: &Mission, task: &Task, bot: &crate::db::moif let Some(note) = super::autofix::retry_note(state, task).await {p.push_str(¬e);}+ // C1: lessons from the bot's earlier tasks; held out for 1 in 5 tasks (still logged)+ if let Some((block, hint)) = super::lessons::for_brief(state, &bot.id, &task.id).await {+ if !block.is_empty() {+ p.truncate(p.trim_end().len());+ p.push_str(&block);+ }+ opts.task = Some(hint);+ }turn_once(&scope, bot, p, opts).await}Err(e) => Err(e),@@ -223,6 +235,7 @@ async fn retry_coming(state: &AppState, task_id: &str) -> bool {/// `failed` for it (§13), and the failure is recorded: the turn's error, a denied action since/// `started`, or a stall; a task left waiting on the person records `needs_input`.pub async fn after_turn(state: &AppState, task_id: &str, err: Option<&str>, started: chrono::DateTime<chrono::Utc>) {+ super::lessons::note_self_check(state, task_id, started).await;// Waiting on nothing (its cards were answered or withdrawn) is still working: release itlet Some(t) = super::listener::settle_needs_you(state, task_id).await else { return };if t.state == "needs_you" {diff --git a/src/server/mod.rs b/src/server/mod.rsindex b684df31..9002c63c 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -339,6 +339,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/channels/:id", get(continuity::get_channel).patch(continuity::patch_channel)).route("/api/search", get(continuity::search)).route("/api/kwants/:id/memories", get(continuity::list_memories).post(continuity::add_memory))+ .route("/api/kwants/:id/lessons", get(missions::lessons::get_lessons)).route("/api/kwants/:id/model-usage", get(model_usage::get_usage)).route("/api/usage/daily", get(model_usage::get_daily)).route("/api/chains/:id/continue", post(budget::continue_chain))diff --git a/src/server/routes.rs b/src/server/routes.rsindex 76fddfa5..9b5b531a 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1793,6 +1793,10 @@ pub(super) struct TurnOpts {/// A Skill Foundry replay (a dry run, see [`super::mcp_runtime::RehearseApprover`]): runs only/// on Claude with kwant's permission hook, opens no page, and logs refused calls here.pub(super) rehearse: Option<super::mcp_runtime::RehearseLog>,+ /// The task this turn works on and its lessons (set by the mission runner): the turn logs+ /// `lessons_shown` or `lessons_held_out` once it reaches the driver, and gets no second+ /// lessons block in its continuity section.+ pub(super) task: Option<super::missions::lessons::TaskHint>,}impl TurnOpts {@@ -2417,12 +2421,20 @@ async fn run_kwant_turn_inner(let with_tools = mcp_ctx.as_ref().is_some_and(|c| c.servers.iter().any(|s| s.name == crate::mcp::SELF_SERVER_NAME));- let continuity = super::continuity::prompt_block(+ // C5: chat, routine and hand-off turns get the bot's lessons; a task turn has them in its+ // brief already (or is held out), and hidden purposes get none+ let lessons = if opts.task.is_none() && super::missions::lessons::wants_block(opts.purpose.as_deref()) {+ super::missions::lessons::for_turn(state, &target_kwant.id).await+ } else {+ String::new()+ };+ let continuity = super::continuity::prompt_block_with(state,target_kwant,scope.team_context.as_ref().map(|t| t.id.as_str()),channel_id.as_deref(),with_tools,+ &lessons,).await;let skills = super::skills::prompt_block(state, &target_kwant.id, &prompt, with_tools).await;@@ -2516,6 +2528,11 @@ async fn run_kwant_turn_inner(// The switches as the reply's `meta.failover` (one object per switch), so they survive a reloadlet mut switch_meta: Vec<serde_json::Value> = Vec::new();let chat_key = format!("{}|{:?}|{:?}", target_kwant.id, scope.channel_id, scope.thread_id);+ // The attribution point: past the refusal and engine checks, before the driver, once+ // across the failover loop, so a refused or parked turn never counts as shown+ if let (None, Some(hint)) = (&gave_up, &opts.task) {+ super::missions::lessons::log_attribution(state, hint).await;+ }for (i, profile) in attempts.iter().enumerate() {// An account of another engine than the bot's own runs the tier of the bot's model,// not its model id (which no other engine knows)@@ -3840,6 +3857,8 @@ pub struct SettingsResponse {pub checkpoint_keep: i64,/// AutoFix: `on` (the default), `suggest` (the person starts each retry) or `off` (record failures only).pub autofix: String,+ /// Lessons from a bot's earlier tasks in its brief and turns: `on` (the default) or `off`.+ pub lessons: String,/// Share of a task's budget its AutoFix retries may spend (0–100).pub recovery_budget_pct: i64,/// Flight School: on by default; tiers are enforced for task turns (see `super::missions::flight_school`).@@ -3910,6 +3929,7 @@ pub struct SaveSettingsPayload {pub checkpoint_max_mb: Option<i64>,pub checkpoint_keep: Option<i64>,pub autofix: Option<String>,+ pub lessons: Option<String>,pub recovery_budget_pct: Option<i64>,pub flight_school: Option<bool>,pub flight_school_new_bot_tier: Option<String>,@@ -3974,6 +3994,7 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settingscheckpoint_max_mb: super::missions::checkpoints::max_mb(&state).await,checkpoint_keep: super::missions::checkpoints::keep(&state).await,autofix: super::missions::autofix::mode(&state).await.into(),+ lessons: super::missions::lessons::mode(&state).await.into(),recovery_budget_pct: super::missions::autofix::recovery_pct(&state).await,flight_school: super::missions::flight_school::enabled(&state.db).await,flight_school_new_bot_tier: super::missions::flight_school::new_bot_tier(&state.db).await.into(),@@ -4044,6 +4065,9 @@ pub async fn save_settings(if let Some(e) = super::missions::autofix::settings_error(payload.autofix.as_deref(), payload.recovery_budget_pct) {return bad(e);}+ if let Some(e) = super::missions::lessons::settings_error(payload.lessons.as_deref()) {+ return bad(e);+ }if let Some(e) = super::missions::flight_school::settings_error(payload.flight_school_new_bot_tier.as_deref()) {return bad(e);}@@ -4175,6 +4199,9 @@ pub async fn save_settings(if let Some(n) = payload.checkpoint_keep {let _ = state.db.set_setting(super::missions::checkpoints::KEEP_SETTING, &n.to_string()).await;}+ if let Some(m) = &payload.lessons {+ let _ = state.db.set_setting(super::missions::lessons::SETTING, m).await;+ }if let Some(m) = &payload.autofix {let _ = state.db.set_setting(super::missions::autofix::SETTING, m).await;}diff --git a/tests/lessons_test.rs b/tests/lessons_test.rsnew file mode 100644index 00000000..d2abd195--- /dev/null+++ b/tests/lessons_test.rs@@ -0,0 +1,481 @@+//! Self-improving bots, round 1 (docs/mission-control.md §23): what a bot's earlier tasks taught+//! it reaches its next task's brief, the self-check sentence rides along when there is an approved+//! check, the turn is attributed, a bot with nothing to learn gets the same brief byte for byte,+//! the setting turns it all off, and only the person can read the lines. Its own test binary: it+//! changes PATH and listens on a real port the stand-in CLI calls back on.++#[path = "common/exe.rs"]+mod exe;++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Kwant, spaces::SpaceId, Database},+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router, mcp_runtime,+ missions::{lessons, runner},+ AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::path::PathBuf;+use std::sync::OnceLock;+use std::time::Duration;+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++/// On a Mission Control prompt: logs the prompt (with the task it holds) to prompts.log next to+/// itself; when the brief asks for it, runs the task's checks first (task_request_check); then+/// moves the task to review through its kwant tools.+const FAKE_CLAUDE: &str = r#"#!/usr/bin/env python3+import json, os, re, sys, urllib.request+args = sys.argv[1:]+if args[:1] == ["auth"]:+ print('{"loggedIn":true}')+ sys.exit(0)+prompt = args[-1] if args else ""+held = re.search(r"You hold task (\S+) of", prompt)+if held and "--mcp-config" in args:+ tid = held.group(1)+ with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompts.log"), "a") as f:+ f.write(json.dumps({"task": tid, "prompt": prompt}) + "\n")+ with open(args[args.index("--mcp-config") + 1]) as f:+ servers = json.load(f).get("mcpServers", {})+ for s in servers.values():+ if s.get("url", "").endswith("/api/mcp/self"):+ headers = dict(s.get("headers", {}), **{"content-type": "application/json"})+ calls = []+ if "task_request_check" in prompt:+ calls.append(("task_request_check", {"task_id": tid}))+ calls.append(("task_update", {"task_id": tid, "status": "review"}))+ for n, (name, arguments) in enumerate(calls):+ call = {"jsonrpc": "2.0", "id": n + 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}}+ req = urllib.request.Request(s["url"], data=json.dumps(call).encode(), headers=headers)+ urllib.request.urlopen(req, timeout=30).read()+print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": "done, sent for review",+ "usage": {"input_tokens": 10, "output_tokens": 10}}))+"#;++fn fake_cli() -> PathBuf {+ static DONE: OnceLock<PathBuf> = OnceLock::new();+ DONE.get_or_init(|| {+ let bin = tempfile::tempdir().unwrap().keep().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));+ bin+ })+ .clone()+}++/// The prompts the stand-in CLI got for `tid`, in order.+fn prompts(tid: &str) -> Vec<String> {+ let log = std::fs::read_to_string(fake_cli().join("prompts.log")).unwrap_or_default();+ log.lines()+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())+ .filter(|v| v["task"] == tid)+ .map(|v| v["prompt"].as_str().unwrap_or("").to_string())+ .collect()+}++struct Env {+ app: Router,+ state: AppState,+ general: String,+ _tmp: TempDir,+}++async fn setup() -> Env {+ fake_cli();+ let tmp = tempdir().unwrap();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config {+ data_dir: tmp.path().to_path_buf(),+ host: "127.0.0.1".into(),+ port,+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());+ let served = app.clone();+ tokio::spawn(async move { axum::serve(listener, served).await.unwrap() });+ let space = SpaceId::default_space();+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;+ state.db.set_space_approvals(&space, "off").await.unwrap();+ let e = Env { app, state, general, _tmp: tmp };+ // AutoFix off: a failing check fails the task once, with no retry turns+ person(&e, "POST", "/api/settings", Some(json!({"mission_board": true, "autofix": "off"}))).await;+ e+}++async fn send(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(token) = auth {+ req = req.header("authorization", format!("Bearer {token}"));+ }+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++async fn person(e: &Env, method: &str, uri: &str, body: Option<Value>) -> Value {+ let (status, v) = send(&e.app, method, uri, None, body).await;+ assert!(status.is_success(), "{method} {uri}: {status} {v}");+ v+}++async fn ok(e: &Env, token: &str, name: &str, args: Value) -> Value {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let (status, v) = send(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ let text = v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string();+ assert!(!v["result"]["isError"].as_bool().unwrap_or(false), "{name} {args} failed: {text}");+ serde_json::from_str(&text).unwrap_or(Value::Null)+}++/// A turn of `bot` in #general with its own tools; returns the turn token.+async fn turn(e: &Env, bot: &Kwant) -> String {+ let turn_id = format!("t-{}", uuid::Uuid::new_v4());+ let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(origin),+ turn_id: Some(turn_id.clone()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&e.state, bot, Some(turn_id), None, Some(scope)).await.unwrap().1+}++fn id(v: &Value) -> String {+ v["id"].as_str().unwrap().to_string()+}++async fn task(e: &Env, id: &str) -> Value {+ person(e, "GET", &format!("/api/tasks/{id}"), None).await["task"].clone()+}++async fn wait_state(e: &Env, tid: &str, want: &str) -> Value {+ for _ in 0..300 {+ let t = task(e, tid).await;+ if t["state"] == want {+ return t;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("{tid} never got to {want}: {}", task(e, tid).await);+}++/// A bot on the stand-in claude CLI.+async fn cli_bot(e: &Env, name: &str) -> Kwant {+ let bot = json!({"name": name, "title": format!("{name} the tester"), "persona_prompt": "Test persona",+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"});+ let bid = id(&person(e, "POST", "/api/kwants", Some(bot)).await);+ e.state.db.get_kwant(&bid).await.unwrap().unwrap()+}++/// A person task of `bot` outside any mission, claimed by `bot` and handed in; its checks run.+async fn handed_in(e: &Env, bot: &Kwant, title: &str, checks: Value) -> String {+ let body = json!({"title": title, "acceptance": "works", "owner_kwant_id": bot.id, "checks": checks});+ let tid = id(&person(e, "POST", "/api/tasks", Some(body)).await);+ let row = e.state.db.get_task(&tid).await.unwrap().unwrap();+ std::fs::create_dir_all(kwnt::server::missions::task_folder(&e.state, &row).await.unwrap()).unwrap();+ let token = turn(e, bot).await;+ ok(e, &token, "task_claim", json!({"task_id": tid})).await;+ ok(e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;+ tid+}++fn passing_check() -> Value {+ json!([{"kind": "command", "spec": {"command": "true"}}])+}++/// A mission of one task for `bot` (title "Ship it", task "Publish the notes" with a passing+/// check) that is not held out unless `held` says so; returns its ids.+async fn mission(e: &Env, bot: &Kwant, held: bool) -> (String, String) {+ for _ in 0..60 {+ let body = json!({"title": "Ship it", "goal": "a release", "lead_kwant_id": bot.id, "budget_tokens": 900_000,+ "channel_id": e.general, "tasks": [{"title": "Publish the notes", "owner": bot.id, "checks": passing_check()}]});+ let mid = id(&person(e, "POST", "/api/missions", Some(body)).await);+ let detail = person(e, "GET", &format!("/api/missions/{mid}"), None).await;+ let tid = id(&detail["tasks"][0]);+ if lessons::held_out(&tid) == held {+ let row = e.state.db.get_mission(&mid).await.unwrap().unwrap();+ std::fs::create_dir_all(&row.workspace_path).unwrap();+ return (mid, tid);+ }+ // The other arm: leave it unrun+ person(e, "POST", &format!("/api/missions/{mid}/cancel"), None).await;+ }+ panic!("no task id landed on held_out == {held} in 60 tries");+}++/// Runs the mission's one task to the end of its turn; returns the prompt the CLI got.+async fn run(e: &Env, mid: &str, tid: &str) -> String {+ person(e, "POST", &format!("/api/missions/{mid}/run"), Some(json!({"max_tasks": 1}))).await;+ wait_state(e, tid, "verified").await;+ for _ in 0..300 {+ if !runner::is_running(&e.state, mid) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ tokio::time::sleep(Duration::from_millis(200)).await;+ let p = prompts(tid);+ assert_eq!(p.len(), 1, "{p:?}");+ p[0].clone()+}++/// The task's events of `kind`, as their detail JSON.+async fn events(e: &Env, tid: &str, kind: &str) -> Vec<Value> {+ e.state.db.task_events(tid, 500).await.unwrap().into_iter().filter(|ev| ev.kind == kind).map(|ev| ev.detail_value()).collect()+}++/// The lessons block of a brief: from its header to the end.+fn block_of(prompt: &str) -> Option<&str> {+ prompt.find("[Lessons from earlier tasks]").map(|i| &prompt[i..])+}++#[tokio::test]+async fn a_failed_check_and_a_send_back_reach_the_next_brief_and_are_attributed() {+ let e = setup().await;+ let ann = cli_bot(&e, "Ann").await;++ // A: an approved check fails at hand-in+ let a = handed_in(&e, &ann, "Export the sales CSV", json!([{"kind": "command", "spec": {"command": "echo expected 42 got 41; exit 1"}}])).await;+ for _ in 0..300 {+ if !e.state.db.failures_of(&a).await.unwrap().is_empty() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert_eq!(e.state.db.failures_of(&a).await.unwrap().len(), 1);+ // B: the person sends it back with a reason+ let b = handed_in(&e, &ann, "Write the release note", json!([])).await;+ wait_state(&e, &b, "review").await;+ person(&e, "POST", &format!("/api/tasks/{b}/reject"), Some(json!({"reason": "Too long, keep it under five lines"}))).await;++ // C: the next task's brief carries both, after the brief, with the self-check sentence+ let (mid, c) = mission(&e, &ann, false).await;+ let p = run(&e, &mid, &c).await;+ assert!(p.contains(runner::SELF_CHECK), "{p}");+ let block = block_of(&p).unwrap_or_else(|| panic!("no lessons block: {p}"));+ println!("RENDERED BLOCK >>>\n{block}\n<<< RENDERED BLOCK");+ assert!(p.find(runner::SELF_CHECK).unwrap() < p.find(block).unwrap(), "the block comes after the brief");+ assert!(p.contains(&format!("\n\n{}", lessons::HEADER)), "{p}");+ let lines: Vec<&str> = block.lines().filter(|l| l.starts_with("- ")).collect();+ assert_eq!(lines.len(), 2, "{block}");+ let check = lines.iter().find(|l| l.contains("Export the sales CSV")).unwrap_or_else(|| panic!("{block}"));+ assert!(check.contains("echo expected 42 got 41; exit 1"), "the approved check's command: {check}");+ assert!(check.contains("expected 42 got 41"), "{check}");+ let review = lines.iter().find(|l| l.contains("Write the release note")).unwrap_or_else(|| panic!("{block}"));+ assert!(review.contains("Too long, keep it under five lines"), "{review}");++ // Attribution and the self-check, both logged by kwant+ let shown = events(&e, &c, "lessons_shown").await;+ assert_eq!(shown.len(), 1, "{shown:?}");+ assert_eq!(shown[0]["keys"].as_array().unwrap().len(), 2, "{shown:?}");+ assert!(shown[0]["keys"].as_array().unwrap().iter().any(|k| k.as_str().unwrap().starts_with("check_failed:")), "{shown:?}");+ assert!(shown[0]["keys"].as_array().unwrap().iter().any(|k| k.as_str().unwrap().starts_with("rejected:")), "{shown:?}");+ assert_eq!(shown[0]["bytes"].as_u64(), Some(block.len() as u64 + 2), "{shown:?}");+ assert!(events(&e, &c, "lessons_held_out").await.is_empty());+ let checked = events(&e, &c, "self_checked").await;+ assert_eq!(checked.len(), 1, "{checked:?}");+ assert_eq!(checked[0]["checks"].as_array().unwrap().len(), 1, "{checked:?}");++ // A held-out task gets no block, but the keys it would have shown are logged+ let (hmid, h) = mission(&e, &ann, true).await;+ let hp = run(&e, &hmid, &h).await;+ assert!(block_of(&hp).is_none(), "{hp}");+ assert!(hp.contains(runner::SELF_CHECK), "{hp}");+ let held = events(&e, &h, "lessons_held_out").await;+ assert_eq!(held.len(), 1, "{held:?}");+ assert_eq!(held[0]["keys"].as_array().unwrap().len(), 2, "{held:?}");+ assert!(held[0].get("bytes").is_none(), "{held:?}");+ assert!(events(&e, &h, "lessons_shown").await.is_empty());++ // The person reads the same lines+ let v = person(&e, "GET", &format!("/api/kwants/{}/lessons", ann.id), None).await;+ assert_eq!((v["enabled"].as_bool(), v["window_days"].as_i64()), (Some(true), Some(30)), "{v}");+ let got = v["lines"].as_array().unwrap();+ assert_eq!(got.len(), 2, "{v}");+ let mut sources: Vec<&str> = got.iter().map(|l| l["source"].as_str().unwrap()).collect();+ sources.sort();+ assert_eq!(sources, ["check", "review"], "{v}");+ for l in got {+ assert!(l["key"].is_string() && l["text"].is_string() && l["last_at"].is_i64(), "{l}");+ assert_eq!(l["count"], 1, "{l}");+ assert!(lines.iter().any(|b| b[2..] == *l["text"].as_str().unwrap()), "{l} in {block}");+ }+ assert_eq!(got.iter().find(|l| l["source"] == "check").unwrap()["task_id"], a.as_str(), "{v}");+ assert_eq!(got.iter().find(|l| l["source"] == "review").unwrap()["task_id"], b.as_str(), "{v}");++ // Only the person, and only in the bot's own space+ let token = turn(&e, &ann).await;+ let (s, v) = send(&e.app, "GET", &format!("/api/kwants/{}/lessons", ann.id), Some(&token), None).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");+ let (s, v) = send(&e.app, "POST", "/api/spaces", None, Some(json!({"name": "Other", "icon": "🧪", "this_machine_enabled": false}))).await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let other = id(&v);+ let (s, v) = send(&e.app, "GET", &format!("/api/kwants/{}/lessons?space={other}", ann.id), None, None).await;+ assert_eq!(s, StatusCode::NOT_FOUND, "{v}");+ let (s, v) = send(&e.app, "GET", "/api/kwants/no-such-bot/lessons", None, None).await;+ assert_eq!(s, StatusCode::NOT_FOUND, "{v}");++ // Off: no block, no attribution, no self-check event; the route still answers+ person(&e, "POST", "/api/settings", Some(json!({"lessons": "off"}))).await;+ assert_eq!(person(&e, "GET", "/api/settings", None).await["lessons"], "off");+ let (omid, o) = mission(&e, &ann, false).await;+ let op = run(&e, &omid, &o).await;+ assert!(block_of(&op).is_none(), "{op}");+ assert!(op.contains(runner::SELF_CHECK), "the self-check sentence doesn't depend on the setting: {op}");+ for kind in ["lessons_shown", "lessons_held_out", "self_checked"] {+ assert!(events(&e, &o, kind).await.is_empty(), "{kind}");+ }+ let v = person(&e, "GET", &format!("/api/kwants/{}/lessons", ann.id), None).await;+ assert_eq!(v["enabled"], false, "{v}");+ assert_eq!(v["lines"].as_array().unwrap().len(), 2, "{v}");+ let (s, v) = send(&e.app, "POST", "/api/settings", None, Some(json!({"lessons": "maybe"}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+}++#[tokio::test]+async fn a_bot_with_nothing_to_learn_gets_the_same_brief_byte_for_byte() {+ let e = setup().await;+ let bob = cli_bot(&e, "Bob").await;+ assert_eq!(person(&e, "GET", "/api/settings", None).await["lessons"], "on", "on by default");++ let (mid, on) = mission(&e, &bob, false).await;+ let with = run(&e, &mid, &on).await.replace(&on, "TASK");+ assert!(events(&e, &on, "lessons_shown").await.is_empty(), "nothing shown, nothing logged");+ assert!(events(&e, &on, "lessons_held_out").await.is_empty());+ assert_eq!(events(&e, &on, "self_checked").await.len(), 1, "the self-check is logged with the setting on");++ person(&e, "POST", "/api/settings", Some(json!({"lessons": "off"}))).await;+ let (mid, off) = mission(&e, &bob, false).await;+ let without = run(&e, &mid, &off).await.replace(&off, "TASK");+ // The brief, from its first line (the conversation history before it grows with each mission)+ let brief = |p: &str| p[p.find("[Mission Control]").unwrap()..].to_string();+ assert_eq!(brief(&with), brief(&without));+ assert!(block_of(&with).is_none(), "{with}");+ let v = person(&e, "GET", &format!("/api/kwants/{}/lessons", bob.id), None).await;+ assert_eq!(v["lines"], json!([]), "{v}");+}++/// A verified task of `bot` with a file check, its "Keep this true" goal made and met once.+async fn kept(e: &Env, bot: &Kwant, title: &str) -> kwnt::db::goals::Goal {+ let body = json!({"title": title, "acceptance": "the file is there", "owner_kwant_id": bot.id,+ "checks": [{"kind": "file_exists", "spec": {"path": "ok.txt"}}]});+ let tid = id(&person(e, "POST", "/api/tasks", Some(body)).await);+ let row = e.state.db.get_task(&tid).await.unwrap().unwrap();+ let folder = kwnt::server::missions::task_folder(&e.state, &row).await.unwrap();+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("ok.txt"), "x").unwrap();+ let token = turn(e, bot).await;+ ok(e, &token, "task_claim", json!({"task_id": tid})).await;+ ok(e, &token, "task_update", json!({"task_id": tid, "status": "review"})).await;+ for _ in 0..300 {+ let t = task(e, &tid).await;+ if t["state"] == "verified" {+ break;+ }+ if t["state"] == "review" && e.state.db.list_checks(&tid).await.unwrap().iter().all(|c| c.status == "passed") {+ person(e, "POST", &format!("/api/tasks/{tid}/verify"), Some(json!({}))).await;+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ wait_state(e, &tid, "verified").await;+ let v = person(e, "POST", "/api/goals", Some(json!({"from_task": tid}))).await;+ let g = e.state.db.get_goal(v["goal"]["id"].as_str().unwrap()).await.unwrap().unwrap();+ assert_eq!(run_goal(e, &g.id).await.status, "met");+ g+}++async fn run_goal(e: &Env, gid: &str) -> kwnt::db::goals::Goal {+ let g = e.state.db.lease_goal(gid, chrono::Utc::now().timestamp_millis(), false).await.unwrap().expect("a lease");+ kwnt::server::goals::runner::run_goal(&e.state, g).await.expect("a finished run")+}++/// The goal's file goes missing and the loop confirms it (two runs in a row).+async fn lapse(e: &Env, g: &kwnt::db::goals::Goal) {+ let _ = std::fs::remove_file(std::path::Path::new(&g.folder).join("ok.txt"));+ run_goal(e, &g.id).await;+ assert_eq!(run_goal(e, &g.id).await.status, "not_met");+}++async fn route_lines(e: &Env, bot: &Kwant) -> Vec<Value> {+ person(e, "GET", &format!("/api/kwants/{}/lessons", bot.id), None).await["lines"].as_array().unwrap().clone()+}++#[tokio::test]+async fn a_goal_that_stopped_holding_reaches_the_brief_and_the_route_until_it_holds_again() {+ let e = setup().await;+ let ann = cli_bot(&e, "Ann").await;+ let cid = cli_bot(&e, "Cid").await;+ let g = kept(&e, &ann, "Publish the price list").await;+ let theirs = kept(&e, &cid, "Refresh the store hours").await;+ assert!(route_lines(&e, &ann).await.is_empty(), "a goal that holds is no lesson");+ lapse(&e, &g).await;+ lapse(&e, &theirs).await;++ // The route: one goal line, only the bot's own+ let lines = route_lines(&e, &ann).await;+ assert_eq!(lines.len(), 1, "{lines:?}");+ let l = &lines[0];+ assert_eq!((l["source"].as_str(), l["key"].as_str()), (Some("goal"), Some(format!("goal:{}", g.id).as_str())), "{l}");+ let today = chrono::Utc::now().format("%Y-%m-%d").to_string();+ assert_eq!(+ l["text"].as_str().unwrap(),+ format!("A goal you worked on, \"Publish the price list\", is not met since {today}: check it before saying a task is done.")+ );+ assert!(!l["text"].as_str().unwrap().contains("ok.txt"), "no check spec: {l}");+ let mine = route_lines(&e, &cid).await;+ assert_eq!(mine.len(), 1, "{mine:?}");+ assert!(mine[0]["text"].as_str().unwrap().contains("Refresh the store hours"), "{mine:?}");++ // Every turn and the next task's brief carry it, attributed by its key+ let turn_block = lessons::for_turn(&e.state, &ann.id).await;+ assert!(turn_block.contains("\"Publish the price list\", is not met since"), "{turn_block}");+ assert!(!turn_block.contains("Refresh the store hours"), "{turn_block}");+ let (mid, t) = mission(&e, &ann, false).await;+ let p = run(&e, &mid, &t).await;+ let block = block_of(&p).unwrap_or_else(|| panic!("no lessons block: {p}"));+ println!("GOAL BLOCK >>>\n{block}\n<<< GOAL BLOCK");+ assert!(block.contains(l["text"].as_str().unwrap()), "{block}");+ assert!(!block.contains("Refresh the store hours"), "another bot's lapse: {block}");+ let shown = events(&e, &t, "lessons_shown").await;+ assert_eq!(shown.len(), 1, "{shown:?}");+ assert_eq!(shown[0]["keys"], json!([format!("goal:{}", g.id)]), "{shown:?}");++ // Met again: no line anywhere+ std::fs::write(std::path::Path::new(&g.folder).join("ok.txt"), "x").unwrap();+ assert_eq!(run_goal(&e, &g.id).await.status, "met");+ assert!(route_lines(&e, &ann).await.is_empty());+ assert_eq!(lessons::for_turn(&e.state, &ann.id).await, "");+ let (mid, t) = mission(&e, &ann, false).await;+ assert!(block_of(&run(&e, &mid, &t).await).is_none());+ assert!(events(&e, &t, "lessons_shown").await.is_empty());+ // The other bot's goal still hasn't recovered+ assert_eq!(route_lines(&e, &cid).await.len(), 1);+}